许鹏程
2023-06-13 c0b60dbd5791d499c037c2f7c8cdfc9760353bb3
套红文档,
已修改4个文件
2593 ■■■■ 文件已修改
src/main/java/com/product/file/controller/FileManagerController.java 1 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/product/file/service/FileManagerService.java 1392 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/product/file/service/OnlineDocumentEditService.java 517 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/product/file/util/AsposeUtil.java 683 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/product/file/controller/FileManagerController.java
@@ -33,6 +33,7 @@
    @Autowired
    public FileManagerService fileManagerService;
    /**
     * @param uuid
     * @param response
src/main/java/com/product/file/service/FileManagerService.java
@@ -45,749 +45,753 @@
@Service("fileManagerService")
public class FileManagerService extends AbstractBaseService {
    @Autowired
    public BaseDao baseDao;
    @Autowired
    FileUtils fileUtils;
    @Autowired
    public BaseDao baseDao;
    @Autowired
    FileUtils fileUtils;
    /**
     * 获取静态资源
     *
     * @param uuid
     * @param response
     * @throws IOException
     * @throws BaseException
     */
    public void getStaticFile(String uuid, HttpServletResponse response) throws IOException, BaseException {
        String systemConfig = Global.getSystemConfig("file.static", "");
        if (StringUtils.isEmpty(uuid) || StringUtils.isEmpty(systemConfig)) {
            throw new BaseException(FileCode.GET_FILE_FAIL);
        }
        FieldSetEntity fs = baseDao.getFieldSetEntity(CmnConst.PRODUCT_SYS_ATTACHMENTS, uuid, false);
        if (fs == null || StringUtils.isEmpty(fs.getString("attachment_data_table")) || StringUtils.isEmpty(fs.getString("attachment_data_field"))) {
            throw new BaseException(FileCode.GET_FILE_FAIL);
        }
        List<String> list = new ArrayList<>(Arrays.asList(systemConfig.split(",")));
        if (list != null && list.size() > 0) {
            if (list.contains((fs.getString("attachment_data_table") + "." + fs.getString("attachment_data_field")))) {
                // 允许的静态资源
                this.getFileContent(fs, response);
                return;
            }
        }
        throw new BaseException(FileCode.GET_FILE_FAIL);
    }
    /**
     * 获取静态资源
     *
     * @param uuid
     * @param response
     * @throws IOException
     * @throws BaseException
     */
    public void getStaticFile(String uuid, HttpServletResponse response) throws IOException, BaseException {
        String systemConfig = Global.getSystemConfig("file.static", "");
        if (StringUtils.isEmpty(uuid) || StringUtils.isEmpty(systemConfig)) {
            throw new BaseException(FileCode.GET_FILE_FAIL);
        }
        FieldSetEntity fs = baseDao.getFieldSetEntity(CmnConst.PRODUCT_SYS_ATTACHMENTS, uuid, false);
        if (fs == null || StringUtils.isEmpty(fs.getString("attachment_data_table")) || StringUtils.isEmpty(fs.getString("attachment_data_field"))) {
            throw new BaseException(FileCode.GET_FILE_FAIL);
        }
        List<String> list = new ArrayList<>(Arrays.asList(systemConfig.split(",")));
        if (list != null && list.size() > 0) {
            if (list.contains((fs.getString("attachment_data_table") + "." + fs.getString("attachment_data_field")))) {
                // 允许的静态资源
                this.getFileContent(fs, response);
                return;
            }
        }
        throw new BaseException(FileCode.GET_FILE_FAIL);
    }
    /**
     * 文件记录-文件新增结果回调:
     * result-1    服务器新增成功,修改状态
     * result-其他  服务器新增失败,删除准备新增的记录
     *
     * @param fse 参数对象
     * @return 结果
     * @throws BaseException 基本异常
     */
    public JSONObject addFileCallback(FieldSetEntity fse) throws BaseException {
        String result = fse.getString(CmnConst.RESULT);
        JSONObject returnResult = new JSONObject();
        if ("1".equals(result)) {
            returnResult.put(CmnConst.TYPE, "update");
            returnResult.put(CmnConst.RESULT, updateFileStatus(fse.getString("uuid"), 2) != null);
        } else {
            returnResult.put(CmnConst.TYPE, "del");
            returnResult.put(CmnConst.RESULT, baseDao.delete(CmnConst.PRODUCT_SYS_ATTACHMENTS, new String[]{fse.getString("uuid")}));
        }
        return returnResult;
    }
    /**
     * 文件记录-文件新增结果回调:
     * result-1    服务器新增成功,修改状态
     * result-其他  服务器新增失败,删除准备新增的记录
     *
     * @param fse 参数对象
     * @return 结果
     * @throws BaseException 基本异常
     */
    public JSONObject addFileCallback(FieldSetEntity fse) throws BaseException {
        String result = fse.getString(CmnConst.RESULT);
        JSONObject returnResult = new JSONObject();
        if ("1".equals(result)) {
            returnResult.put(CmnConst.TYPE, "update");
            returnResult.put(CmnConst.RESULT, updateFileStatus(fse.getString("uuid"), 2) != null);
        } else {
            returnResult.put(CmnConst.TYPE, "del");
            returnResult.put(CmnConst.RESULT, baseDao.delete(CmnConst.PRODUCT_SYS_ATTACHMENTS, new String[]{fse.getString("uuid")}));
        }
        return returnResult;
    }
    /**
     * 文件记录-删除准备(状态修改)
     *
     * @param fse 参数对象
     * @return 待删除的文件记录fse
     * @throws BaseException 基本异常
     */
    public FieldSetEntity delFileRecordPlan(FieldSetEntity fse) throws BaseException {
        return updateFileStatus(fse.getString("uuid"), 3);
    }
    /**
     * 文件记录-删除准备(状态修改)
     *
     * @param fse 参数对象
     * @return 待删除的文件记录fse
     * @throws BaseException 基本异常
     */
    public FieldSetEntity delFileRecordPlan(FieldSetEntity fse) throws BaseException {
        return updateFileStatus(fse.getString("uuid"), 3);
    }
    /**
     * 文件记录-文件删除回调:
     * result-1     服务器删除成功,删除本地记录
     * result-其他   服务器删除失败,还原本地记录
     *
     * @param fse 参数对象
     * @return 结果
     * @throws BaseException 基本异常
     */
    public JSONObject delFileCallback(FieldSetEntity fse) throws BaseException {
        String result = fse.getString(CmnConst.RESULT);
        JSONObject returnResult = new JSONObject();
        if ("1".equals(result)) {
            returnResult.put(CmnConst.TYPE, "del");
            returnResult.put(CmnConst.RESULT, baseDao.delete(CmnConst.PRODUCT_SYS_ATTACHMENTS, new String[]{fse.getString("uuid")}));
        } else {
            returnResult.put(CmnConst.TYPE, "update");
            returnResult.put(CmnConst.RESULT, updateFileStatus(fse.getString("uuid"), 2) != null);
        }
        return returnResult;
    }
    /**
     * 文件记录-文件删除回调:
     * result-1     服务器删除成功,删除本地记录
     * result-其他   服务器删除失败,还原本地记录
     *
     * @param fse 参数对象
     * @return 结果
     * @throws BaseException 基本异常
     */
    public JSONObject delFileCallback(FieldSetEntity fse) throws BaseException {
        String result = fse.getString(CmnConst.RESULT);
        JSONObject returnResult = new JSONObject();
        if ("1".equals(result)) {
            returnResult.put(CmnConst.TYPE, "del");
            returnResult.put(CmnConst.RESULT, baseDao.delete(CmnConst.PRODUCT_SYS_ATTACHMENTS, new String[]{fse.getString("uuid")}));
        } else {
            returnResult.put(CmnConst.TYPE, "update");
            returnResult.put(CmnConst.RESULT, updateFileStatus(fse.getString("uuid"), 2) != null);
        }
        return returnResult;
    }
    /**
     * 修改文件状态
     *
     * @param fileUUID 文件UUID
     * @param status   待修改的状态
     * @return 是否成功
     * @throws BaseException 基本异常
     */
    private FieldSetEntity updateFileStatus(String fileUUID, int status) throws BaseException {
        FieldSetEntity fse = baseDao.getFieldSetEntity(CmnConst.PRODUCT_SYS_ATTACHMENTS, fileUUID, false);
        fse.setValue("opt_flat", status);
        fse.setValue(CmnConst.UPDATED_BY, SpringMVCContextHolder.getCurrentUser().getUser_id());
        fse.setValue(CmnConst.UPDATED_UTC_DATETIME, new Date());
        baseDao.update(fse);
    /**
     * 修改文件状态
     *
     * @param fileUUID 文件UUID
     * @param status   待修改的状态
     * @return 是否成功
     * @throws BaseException 基本异常
     */
    private FieldSetEntity updateFileStatus(String fileUUID, int status) throws BaseException {
        FieldSetEntity fse = baseDao.getFieldSetEntity(CmnConst.PRODUCT_SYS_ATTACHMENTS, fileUUID, false);
        fse.setValue("opt_flat", status);
        fse.setValue(CmnConst.UPDATED_BY, SpringMVCContextHolder.getCurrentUser().getUser_id());
        fse.setValue(CmnConst.UPDATED_UTC_DATETIME, new Date());
        baseDao.update(fse);
        fse.setValue(CmnConst.SOURCE_DOMAIN, Global.getSystemConfig(CmnConst.SOURCE_DOMAIN, ""));
        return fse;
    }
        fse.setValue(CmnConst.SOURCE_DOMAIN, Global.getSystemConfig(CmnConst.SOURCE_DOMAIN, ""));
        return fse;
    }
    /**
     * 获取客户上传的文件总大小
     *
     * @param clientUUID 客户UUID
     * @return 已上传文件总大小
     * @throws BaseException 基本异常
     */
    public long findClientFileUsedCapacity(String clientUUID) throws BaseException {
        StringBuilder sql = new StringBuilder()
                .append("\nselect sum(attachment_size) usedCapacity from ").append(CmnConst.PRODUCT_SYS_ATTACHMENTS)
                .append("\nwhere client_uuid=?");
        DataTableEntity dt = baseDao.listTable(sql.toString(), new Object[]{clientUUID});
        FieldSetEntity fse;
        long usedCapacity = 0;
        if (dt.getRows() == 1) {
            fse = dt.getFieldSetEntity(0);
            usedCapacity = fse.getLong("usedCapacity") == null ? 0 : fse.getLong("usedCapacity");
        }
        return usedCapacity;
    }
    /**
     * 获取客户上传的文件总大小
     *
     * @param clientUUID 客户UUID
     * @return 已上传文件总大小
     * @throws BaseException 基本异常
     */
    public long findClientFileUsedCapacity(String clientUUID) throws BaseException {
        StringBuilder sql = new StringBuilder()
                .append("\nselect sum(attachment_size) usedCapacity from ").append(CmnConst.PRODUCT_SYS_ATTACHMENTS)
                .append("\nwhere client_uuid=?");
        DataTableEntity dt = baseDao.listTable(sql.toString(), new Object[]{clientUUID});
        FieldSetEntity fse;
        long usedCapacity = 0;
        if (dt.getRows() == 1) {
            fse = dt.getFieldSetEntity(0);
            usedCapacity = fse.getLong("usedCapacity") == null ? 0 : fse.getLong("usedCapacity");
        }
        return usedCapacity;
    }
    /**
     * 获取客户剩余的文件总大小
     *
     * @return 剩余空间大小
     */
    public long findClientFileResidueCapacity(String CLIENT_UUID) throws BaseException {
        FieldSetEntity clientFse = baseDao.getFieldSetEntityByFilter(CmnConst.PRODUCT_SYS_CLIENTS, "uuid=?", new String[]{CLIENT_UUID}, false);
        return findClientFileResidueCapacity(clientFse);
    }
    /**
     * 获取客户剩余的文件总大小
     *
     * @return 剩余空间大小
     */
    public long findClientFileResidueCapacity(String CLIENT_UUID) throws BaseException {
        FieldSetEntity clientFse = baseDao.getFieldSetEntityByFilter(CmnConst.PRODUCT_SYS_CLIENTS, "uuid=?", new String[]{CLIENT_UUID}, false);
        return findClientFileResidueCapacity(clientFse);
    }
    /**
     * 获取客户剩余的文件总大小
     *
     * @param fse 客户fse
     * @return 剩余空间大小
     */
    public long findClientFileResidueCapacity(FieldSetEntity fse) throws BaseException {
        long clientCapacity = fse.getLong(CmnConst.ATTACHMENT_CAPACITY) == null ? 0 : fse.getInteger(CmnConst.ATTACHMENT_CAPACITY);
        long usedCapacity = findClientFileUsedCapacity(fse.getString("uuid"));
        return clientCapacity - usedCapacity;
    }
    /**
     * 获取客户剩余的文件总大小
     *
     * @param fse 客户fse
     * @return 剩余空间大小
     */
    public long findClientFileResidueCapacity(FieldSetEntity fse) throws BaseException {
        long clientCapacity = fse.getLong(CmnConst.ATTACHMENT_CAPACITY) == null ? 0 : fse.getInteger(CmnConst.ATTACHMENT_CAPACITY);
        long usedCapacity = findClientFileUsedCapacity(fse.getString("uuid"));
        return clientCapacity - usedCapacity;
    }
    /**
     * 验证是否允许上传的文件类型
     *
     * @param attachmentTitle 文件名称
     * @return 是否
     */
    public boolean checkIsAllowedFileType(String attachmentTitle) {
        if (StringUtils.isEmpty(attachmentTitle) || attachmentTitle.lastIndexOf(".") < 0 || attachmentTitle.length() < 1) {
            return false;
        }
        String curFileTail = attachmentTitle.substring(attachmentTitle.lastIndexOf(".") + 1, attachmentTitle.length());
        String allowedFileTypes = Global.getSystemConfig("allowed_file_type", "").toLowerCase(Locale.ROOT);
        return allowedFileTypes != null && ("," + allowedFileTypes + ",").contains("," + curFileTail.toLowerCase() + ",");
    }
    /**
     * 验证是否允许上传的文件类型
     *
     * @param attachmentTitle 文件名称
     * @return 是否
     */
    public boolean checkIsAllowedFileType(String attachmentTitle) {
        if (StringUtils.isEmpty(attachmentTitle) || attachmentTitle.lastIndexOf(".") < 0 || attachmentTitle.length() < 1) {
            return false;
        }
        String curFileTail = attachmentTitle.substring(attachmentTitle.lastIndexOf(".") + 1, attachmentTitle.length());
        String allowedFileTypes = Global.getSystemConfig("allowed_file_type", "").toLowerCase(Locale.ROOT);
        return allowedFileTypes != null && ("," + allowedFileTypes + ",").contains("," + curFileTail.toLowerCase() + ",");
    }
    /**
     * 获取原始域名
     *
     * @return 原始域名
     */
    public String findSourceDomain() {
        return Global.getSystemConfig(CmnConst.SOURCE_DOMAIN, "");
    }
    /**
     * 获取原始域名
     *
     * @return 原始域名
     */
    public String findSourceDomain() {
        return Global.getSystemConfig(CmnConst.SOURCE_DOMAIN, "");
    }
    /**
     * 定时任务:自动清理无用数据
     */
    public boolean autoClearNoUsedData() throws BaseException {
        StringBuilder sql = new StringBuilder()
                .append("\ndelete from ").append(CmnConst.PRODUCT_SYS_ATTACHMENTS)
                .append("\nwhere opt_flat in (1,3)")
                .append("\nand ").append(CmnConst.CREATED_BY).append("<=date_format(adddate(now(),-1),'%Y-%m-%d')");
        return baseDao.executeUpdate(sql.toString());
    }
    /**
     * 定时任务:自动清理无用数据
     */
    public boolean autoClearNoUsedData() throws BaseException {
        StringBuilder sql = new StringBuilder()
                .append("\ndelete from ").append(CmnConst.PRODUCT_SYS_ATTACHMENTS)
                .append("\nwhere opt_flat in (1,3)")
                .append("\nand ").append(CmnConst.CREATED_BY).append("<=date_format(adddate(now(),-1),'%Y-%m-%d')");
        return baseDao.executeUpdate(sql.toString());
    }
    /**
     * 上传文件到本地服务器
     * 禁止修改任何逻辑!!!!!!
     *
     * @param rpe
     * @return
     */
    public FieldSetEntity uploadFile(RequestParameterEntity rpe) {
        FieldSetEntity fse = rpe.getFormData().clones();
    /**
     * 上传文件到本地服务器
     * 禁止修改任何逻辑!!!!!!
     *
     * @param rpe
     * @return
     */
    public FieldSetEntity uploadFile(RequestParameterEntity rpe) {
        FieldSetEntity fse = rpe.getFormData().clones();
        Map<String, File> fileMap = rpe.getFiles();
        Map<String, File> fileMap = rpe.getFiles();
        SystemUser user = SpringMVCContextHolder.getCurrentUser();
        String clientUuid = user == null ? fse.getString("client_uuid") : user.getClient_uuid();
        SystemUser user = SpringMVCContextHolder.getCurrentUser();
        String clientUuid = user == null ? fse.getString("client_uuid") : user.getClient_uuid();
//        long residueCapacity = findClientFileResidueCapacity(clientUuid);
//        long fileTotalSize = 0;
        for (Map.Entry<String, File> entry : fileMap.entrySet()) {
            // 格式验证
            if (!checkIsAllowedFileType(entry.getKey())) {
                throw new BaseException(FileCode.ADD_FILE_NOT_ALLOWED.getValue(), FileCode.ADD_FILE_NOT_ALLOWED.getText() + ":" + entry.getKey().substring(entry.getKey().indexOf(".") + 1));
            }
        for (Map.Entry<String, File> entry : fileMap.entrySet()) {
            // 格式验证
            if (!checkIsAllowedFileType(entry.getKey())) {
                throw new BaseException(FileCode.ADD_FILE_NOT_ALLOWED.getValue(), FileCode.ADD_FILE_NOT_ALLOWED.getText() + ":" + entry.getKey().substring(entry.getKey().indexOf(".") + 1));
            }
//            fileTotalSize += (int) entry.getValue().length();
        }
        // 剩余空间判定
        }
        // 剩余空间判定
//        if (residueCapacity < fileTotalSize) {
//            throw new BaseException(FileCode.ADD_FILE_NO_CAPACITY.getValue(), FileCode.ADD_FILE_NO_CAPACITY.getText());
//        }
        Map<Object, Object> map = new HashMap<>(fse.getValues());
        ConnectionManager.getConnection();
        FieldMetaEntity fieldMetaEntity = fse.getMeta();
        Object o;
        String fieldName = fse.getString("~field_name~");
        Object value;
        String fileNames;
        FieldSetEntity fieldFse;
        File tempFile;
        File localTempFile = null;
        long fileLength = 0;
        Map<Object, Object> map = new HashMap<>(fse.getValues());
        ConnectionManager.getConnection();
        FieldMetaEntity fieldMetaEntity = fse.getMeta();
        Object o;
        String fieldName = fse.getString("~field_name~");
        Object value;
        String fileNames;
        FieldSetEntity fieldFse;
        File tempFile;
        File localTempFile = null;
        long fileLength = 0;
        FTPService ftpService;
        boolean needUpload2FileServerFlag = FTPService.needUpload2FileServer();
        String templateType = fse.getString("template_type");
        String dir;
        if (StringUtils.isEmpty(templateType)) {
            String timeStr = new SimpleDateFormat("yyyyMMdd").format(new Date());
            dir = clientUuid + File.separator + timeStr;
        } else {
            dir = CmnConst.DIR_TEMPLATE + File.separator + ("1".equals(templateType) ? CmnConst.DIR_IMPORT : ("2".equals(templateType) ? CmnConst.DIR_PRINT : CmnConst.DIR_OTHER));
        }
        FTPService ftpService;
        boolean needUpload2FileServerFlag = FTPService.needUpload2FileServer();
        String templateType = fse.getString("template_type");
        String dir;
        if (StringUtils.isEmpty(templateType)) {
            String timeStr = new SimpleDateFormat("yyyyMMdd").format(new Date());
            dir = clientUuid + File.separator + timeStr;
        } else {
            dir = CmnConst.DIR_TEMPLATE + File.separator + ("1".equals(templateType) ? CmnConst.DIR_IMPORT : ("2".equals(templateType) ? CmnConst.DIR_PRINT : CmnConst.DIR_OTHER));
        }
        String uuids = "";
        for (Map.Entry<Object, Object> entry : map.entrySet()) {
            fieldFse = fieldMetaEntity.getFieldMeta(fieldName);
            if (fieldFse == null || !CmnConst.ATTACHMENT_TYPE.equals(fieldFse.getString(CmnConst.FIELD_TYPE))) {
                fse.setValue(entry.getKey().toString(), null);
                continue;
            }
            // 已经判定为附件,进行操作
            value = entry.getValue();
            if (value == null || StringUtils.isEmpty(fileNames = value.toString())) {
                fse.setValue(entry.getKey().toString(), null);
                continue;
            }
            for (String fileName : fileNames.split(",")) {
                if (StringUtils.isEmpty(fieldName)) {
                    fse.setValue(entry.getKey().toString(), null);
                    continue;
                }
        String uuids = "";
        for (Map.Entry<Object, Object> entry : map.entrySet()) {
            fieldFse = fieldMetaEntity.getFieldMeta(fieldName);
            if (fieldFse == null || !CmnConst.ATTACHMENT_TYPE.equals(fieldFse.getString(CmnConst.FIELD_TYPE))) {
                fse.setValue(entry.getKey().toString(), null);
                continue;
            }
            // 已经判定为附件,进行操作
            value = entry.getValue();
            if (value == null || StringUtils.isEmpty(fileNames = value.toString())) {
                fse.setValue(entry.getKey().toString(), null);
                continue;
            }
            for (String fileName : fileNames.split(",")) {
                if (StringUtils.isEmpty(fieldName)) {
                    fse.setValue(entry.getKey().toString(), null);
                    continue;
                }
                tempFile = fileMap.get(fileName);
                if (tempFile == null) {
                    //不是文件 跳过
                    continue;
                }
                fileLength = tempFile.length();
                String tail = fileName.substring(fileName.lastIndexOf(".") + 1);
                int viewOnlineSign = 0;
                if (("," + Global.getSystemConfig("can.direct.view.online.format", "") + ",").contains("," + tail + ",")) {
                    viewOnlineSign = 2;
                } else {
                    if (Global.getPropertyToBoolean("file.view.online", "true") && ("," + Global.getSystemConfig("can.transfer.format", "") + ",").contains("," + tail + ",") && StringUtils.isEmpty(templateType)) {
                        viewOnlineSign = 1;
                    }
                }
                tempFile = fileMap.get(fileName);
                if (tempFile == null) {
                    //不是文件 跳过
                    continue;
                }
                fileLength = tempFile.length();
                String tail = fileName.substring(fileName.lastIndexOf(".") + 1);
                int viewOnlineSign = 0;
                if (("," + Global.getSystemConfig("can.direct.view.online.format", "") + ",").contains("," + tail + ",")) {
                    viewOnlineSign = 2;
                } else {
                    if (Global.getPropertyToBoolean("file.view.online", "true") && ("," + Global.getSystemConfig("can.transfer.format", "") + ",").contains("," + tail + ",") && StringUtils.isEmpty(templateType)) {
                        viewOnlineSign = 1;
                    }
                }
                final String fileFinalName = FileUtils.uploadFile(tempFile, templateType, clientUuid);
                final String fileFinalName = FileUtils.uploadFile(tempFile, templateType, clientUuid);
                // 记录附件信息到数据库
                logger.info("正在记录附件信息到数据库...");
                FieldSetEntity dictFse = baseDao.getFieldSetEntityByFilter(CmnConst.PRODUCT_SYS_DICT,
                        new String[]{CmnConst.UUID, CmnConst.DICT_VALUE}, "lower( " + CmnConst.DICT_VALUE + ")=lower(?) and dict_name='upload_file_format' and is_used=1", new Object[]{tail}, false, "");
                FieldSetEntity attachmentFse = new FieldSetEntity();
                attachmentFse.setTableName(CmnConst.PRODUCT_SYS_ATTACHMENTS);
                String fileType;
                if (dictFse != null && !StringUtils.isEmpty(dictFse.getString(CmnConst.UUID))) {
                    attachmentFse.setValue(CmnConst.ATTACHMENT_TYPE_UUID, dictFse.getUUID());
                    fileType = dictFse.getString(CmnConst.DICT_VALUE);
                } else {
                    fileType = tail;
                    attachmentFse.setValue(CmnConst.ATTACHMENT_TYPE_UUID, tail);
                }
                //允许编辑
                int allowEdit = ("," + Global.getSystemConfig("can.web.online.edit", "doc,docx,xls,xlsx.ppt,pptx,wps,cvs,wps,wpt,et,eet") + ",").indexOf("," + fileType + ",") != -1 ? 1 : 0;
                attachmentFse.setValue(CmnConst.OPT_FLAT, 2);
                attachmentFse.setValue(CmnConst.FILE_NAME, fileName);
                attachmentFse.setValue(CmnConst.ATTACHMENT_TITLE, fileFinalName);
                attachmentFse.setValue(CmnConst.CLIENT_UUID, clientUuid);
                attachmentFse.setValue(CmnConst.VIEW_ONLINE_SIGN, viewOnlineSign);
                attachmentFse.setValue(CmnConst.ATTACHMENT_DATA_TABLE, fse.getTableName());
                attachmentFse.setValue(CmnConst.ATTACHMENT_DATA_FIELD, fieldName);
                attachmentFse.setValue(CmnConst.ATTACHMENT_URL, dir.replaceAll("\\\\", "/"));
                attachmentFse.setValue(CmnConst.ENCRPT_SIGN, Global.getPropertyToBoolean("file.encrypt", "true") ? 1 : 0);
                attachmentFse.setValue(CmnConst.ATTACHMENT_SIZE, fileLength);
                attachmentFse.setValue(CmnConst.UPLOAD_SIGN, needUpload2FileServerFlag ? 1 : 0);
                // 记录附件信息到数据库
                logger.info("正在记录附件信息到数据库...");
                FieldSetEntity dictFse = baseDao.getFieldSetEntityByFilter(CmnConst.PRODUCT_SYS_DICT,
                        new String[]{CmnConst.UUID, CmnConst.DICT_VALUE}, "lower( " + CmnConst.DICT_VALUE + ")=lower(?) and dict_name='upload_file_format' and is_used=1", new Object[]{tail}, false, "");
                FieldSetEntity attachmentFse = new FieldSetEntity();
                attachmentFse.setTableName(CmnConst.PRODUCT_SYS_ATTACHMENTS);
                String fileType;
                if (dictFse != null && !StringUtils.isEmpty(dictFse.getString(CmnConst.UUID))) {
                    attachmentFse.setValue(CmnConst.ATTACHMENT_TYPE_UUID, dictFse.getUUID());
                    fileType = dictFse.getString(CmnConst.DICT_VALUE);
                } else {
                    fileType = tail;
                    attachmentFse.setValue(CmnConst.ATTACHMENT_TYPE_UUID, tail);
                }
                //允许编辑
                int allowEdit = ("," + Global.getSystemConfig("can.web.online.edit", "doc,docx,xls,xlsx.ppt,pptx,wps,cvs,wps,wpt,et,eet") + ",").indexOf("," + fileType + ",") != -1 ? 1 : 0;
                attachmentFse.setValue(CmnConst.OPT_FLAT, 2);
                attachmentFse.setValue(CmnConst.FILE_NAME, fileName);
                attachmentFse.setValue(CmnConst.ATTACHMENT_TITLE, fileFinalName);
                attachmentFse.setValue(CmnConst.CLIENT_UUID, clientUuid);
                attachmentFse.setValue(CmnConst.VIEW_ONLINE_SIGN, viewOnlineSign);
                attachmentFse.setValue(CmnConst.ATTACHMENT_DATA_TABLE, fse.getTableName());
                attachmentFse.setValue(CmnConst.ATTACHMENT_DATA_FIELD, fieldName);
                attachmentFse.setValue(CmnConst.ATTACHMENT_URL, dir.replaceAll("\\\\", "/"));
                attachmentFse.setValue(CmnConst.ENCRPT_SIGN, Global.getPropertyToBoolean("file.encrypt", "true") ? 1 : 0);
                attachmentFse.setValue(CmnConst.ATTACHMENT_SIZE, fileLength);
                attachmentFse.setValue(CmnConst.UPLOAD_SIGN, needUpload2FileServerFlag ? 1 : 0);
                attachmentFse.setValue(CmnConst.ATTACHMENT_CONTAINER, fse.getString(CmnConst.ATTACHMENT_CONTAINER));
                attachmentFse.setValue(CmnConst.ATTACHMENT_DOMAIN, fse.getString(CmnConst.ATTACHMENT_DOMAIN));
                attachmentFse.setValue(CmnConst.MODULE_UUID, fse.getString(CmnConst.MODULE_UUID));
                //luoxin 未获取当前人id  就直接覆1
                try {
                    attachmentFse.setValue(CmnConst.CREATED_BY, SpringMVCContextHolder.getCurrentUser().getUser_id());
                } catch (Exception e) {
                    e.getStackTrace();
                    attachmentFse.setValue(CmnConst.CREATED_BY, 1);
                }
                attachmentFse.setValue(CmnConst.ATTACHMENT_CONTAINER, fse.getString(CmnConst.ATTACHMENT_CONTAINER));
                attachmentFse.setValue(CmnConst.ATTACHMENT_DOMAIN, fse.getString(CmnConst.ATTACHMENT_DOMAIN));
                attachmentFse.setValue(CmnConst.MODULE_UUID, fse.getString(CmnConst.MODULE_UUID));
                //luoxin 未获取当前人id  就直接覆1
                try {
                    attachmentFse.setValue(CmnConst.CREATED_BY, SpringMVCContextHolder.getCurrentUser().getUser_id());
                } catch (Exception e) {
                    e.getStackTrace();
                    attachmentFse.setValue(CmnConst.CREATED_BY, 1);
                }
                attachmentFse.setValue(CmnConst.CREATED_UTC_DATETIME, new Date());
                baseDao.saveFieldSetEntity(attachmentFse);
                logger.info("记录成功");
                String uuid = attachmentFse.getUUID();
                FieldSetEntity fseIndex = new FieldSetEntity();
                fseIndex.setTableName("fseIndex");
                fseIndex.setValue("function_uuid", fse.getString("function_uuid"));
                fseIndex.setValue("attachment_uuid", uuid);
                CreateDocumentIndexThread.getInstance().appendAttaInfo(fseIndex);
                fse.setValue(uuid, fileName);
                fse.setValue(entry.getKey().toString(), uuid);
                fse.setValue(entry.getKey().toString() + "_edit", allowEdit);
                fse.setValue(entry.getKey().toString() + "_type", fileType);
                if (!StringUtils.isEmpty(uuids)) {
                    uuids += ",";
                }
                uuids += uuid;
            }
            logger.info("正在回写uuid...");
            System.out.println(uuids);
            fse.setValue(fieldName, uuids);
        }
        return fse;
    }
                attachmentFse.setValue(CmnConst.CREATED_UTC_DATETIME, new Date());
                baseDao.saveFieldSetEntity(attachmentFse);
                logger.info("记录成功");
                String uuid = attachmentFse.getUUID();
                FieldSetEntity fseIndex = new FieldSetEntity();
                fseIndex.setTableName("fseIndex");
                fseIndex.setValue("function_uuid", fse.getString("function_uuid"));
                fseIndex.setValue("attachment_uuid", uuid);
                CreateDocumentIndexThread.getInstance().appendAttaInfo(fseIndex);
                fse.setValue(uuid, fileName);
                fse.setValue(entry.getKey().toString(), uuid);
                fse.setValue(entry.getKey().toString() + "_edit", allowEdit);
                fse.setValue(entry.getKey().toString() + "_type", fileType);
                if (!StringUtils.isEmpty(uuids)) {
                    uuids += ",";
                }
                uuids += uuid;
            }
            logger.info("正在回写uuid...");
            System.out.println(uuids);
            fse.setValue(fieldName, uuids);
        }
        return fse;
    }
    /**
     * 提取文件信息-下载文件或者在线预览文件
     *
     * @param fse
     * @param response
     */
    public void getFileContent(FieldSetEntity fse, HttpServletResponse response) throws IOException {
        logger.info("正在获取文件流...");
        String uuid = fse.getUUID();
        FieldSetEntity attachmentFse = baseDao.getFieldSetEntity(CmnConst.PRODUCT_SYS_ATTACHMENTS, uuid, false);
        if (attachmentFse == null) {
            return;
        }
        boolean needDownloadFromServerFlag = "1".equals(attachmentFse.getString(CmnConst.UPLOAD_SIGN));
        String dir = attachmentFse.getString(CmnConst.ATTACHMENT_URL);
        String fileName = attachmentFse.getString(CmnConst.ATTACHMENT_TITLE);
        String viewOnlineSign = attachmentFse.getString(CmnConst.VIEW_ONLINE_SIGN);
        boolean encrptSignFlag = "1".equals(attachmentFse.getString(CmnConst.ENCRPT_SIGN));
        boolean needOnlineViewFlag = "1".equals(fse.getString(CmnConst.NEED_ONLINE_VIEW)) && "1".equals(viewOnlineSign);
        if (needOnlineViewFlag) {
            // 需要在线预览且转换之后才能在线预览
            dir += File.separator + CmnConst.TRANSFER_DIR_NAME;
        }
    /**
     * 提取文件信息-下载文件或者在线预览文件
     *
     * @param fse
     * @param response
     */
    public void getFileContent(FieldSetEntity fse, HttpServletResponse response) throws IOException {
        logger.info("正在获取文件流...");
        String uuid = fse.getUUID();
        FieldSetEntity attachmentFse = baseDao.getFieldSetEntity(CmnConst.PRODUCT_SYS_ATTACHMENTS, uuid, false);
        if (attachmentFse == null) {
            return;
        }
        boolean needDownloadFromServerFlag = "1".equals(attachmentFse.getString(CmnConst.UPLOAD_SIGN));
        String dir = attachmentFse.getString(CmnConst.ATTACHMENT_URL);
        String fileName = attachmentFse.getString(CmnConst.ATTACHMENT_TITLE);
        String viewOnlineSign = attachmentFse.getString(CmnConst.VIEW_ONLINE_SIGN);
        boolean encrptSignFlag = "1".equals(attachmentFse.getString(CmnConst.ENCRPT_SIGN));
        boolean needOnlineViewFlag = "1".equals(fse.getString(CmnConst.NEED_ONLINE_VIEW)) && "1".equals(viewOnlineSign);
        if (needOnlineViewFlag) {
            // 需要在线预览且转换之后才能在线预览
            dir += File.separator + CmnConst.TRANSFER_DIR_NAME;
        }
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String userAgent = request.getHeader("User-Agent");
        String file_name = attachmentFse.getString("file_name");
        if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
            file_name = java.net.URLEncoder.encode(file_name, "UTF-8");
        } else {
            // 非IE浏览器的处理:
            file_name = new String(file_name.getBytes("UTF-8"), "ISO-8859-1");
        }
        String path = dir + File.separator + fileName;
        if (needDownloadFromServerFlag) {
            // 需要从附件服务器上取文件
            FTPService ftpService = new FTPService();
            logger.info("需要从附件服务器上取文件...");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-disposition",
                    String.format("attachment; filename=\"%s\"", file_name));
            if (!needOnlineViewFlag && !encrptSignFlag) {
                logger.info("不需要解密且获取原文件...");
                try (ServletOutputStream os = response.getOutputStream()) {
                    ftpService.downloadFile(path, os);
                }
            } else {
                logger.info("需要解密或者获取转换后的文件...");
                String localTempPath = Global.getSystemConfig("temp.dir", "") + File.separator + fileName;
                File localTempFile = new File(localTempPath);
                OutputStream tempOs = new FileOutputStream(localTempFile);
                ftpService.downloadFile(path, tempOs);
                tempOs.flush();
                tempOs.close();
                if (needOnlineViewFlag && localTempFile.length() == 0L) {
                    // 若是预览,但是转换后的文件不存在,那么重新执行转换操作
                    File sourceFile = fileUtils.getFile(true, attachmentFse.getString(CmnConst.ATTACHMENT_URL), fileName, encrptSignFlag);
                    File tempSourceFile = new File(sourceFile.getParentFile().getAbsolutePath() + File.separator + attachmentFse.getString(CmnConst.FILE_NAME));
                    sourceFile.renameTo(tempSourceFile);
                    FileUtils.convertPdf(false, true, encrptSignFlag, true, tempSourceFile, dir, fileName, attachmentFse.getString(CmnConst.FILE_NAME));
                    tempSourceFile.delete();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String userAgent = request.getHeader("User-Agent");
        String file_name = attachmentFse.getString("file_name");
        if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
            file_name = java.net.URLEncoder.encode(file_name, "UTF-8");
        } else {
            // 非IE浏览器的处理:
            file_name = new String(file_name.getBytes("UTF-8"), "ISO-8859-1");
        }
        String path = dir + File.separator + fileName;
        if (needDownloadFromServerFlag) {
            // 需要从附件服务器上取文件
            FTPService ftpService = new FTPService();
            logger.info("需要从附件服务器上取文件...");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-disposition",
                    String.format("attachment; filename=\"%s\"", file_name));
            if (!needOnlineViewFlag && !encrptSignFlag) {
                logger.info("不需要解密且获取原文件...");
                try (ServletOutputStream os = response.getOutputStream()) {
                    ftpService.downloadFile(path, os);
                }
            } else {
                logger.info("需要解密或者获取转换后的文件...");
                String localTempPath = Global.getSystemConfig("temp.dir", "") + File.separator + fileName;
                File localTempFile = new File(localTempPath);
                OutputStream tempOs = new FileOutputStream(localTempFile);
                ftpService.downloadFile(path, tempOs);
                tempOs.flush();
                tempOs.close();
                if (needOnlineViewFlag && localTempFile.length() == 0L) {
                    // 若是预览,但是转换后的文件不存在,那么重新执行转换操作
                    File sourceFile = fileUtils.getFile(true, attachmentFse.getString(CmnConst.ATTACHMENT_URL), fileName, encrptSignFlag);
                    File tempSourceFile = new File(sourceFile.getParentFile().getAbsolutePath() + File.separator + attachmentFse.getString(CmnConst.FILE_NAME));
                    sourceFile.renameTo(tempSourceFile);
                    FileUtils.convertPdf(false, true, encrptSignFlag, true, tempSourceFile, dir, fileName, attachmentFse.getString(CmnConst.FILE_NAME));
                    tempSourceFile.delete();
                    // 重新拉文件
                    tempOs = new FileOutputStream(localTempFile);
                    ftpService = new FTPService();
                    ftpService.downloadFile(path, tempOs);
                    tempOs.flush();
                    tempOs.close();
                }
                response.setContentLengthLong(localTempFile.length());
                InputStream is = new FileInputStream(localTempFile);
                int len;
                byte[] b = new byte[1024];
                try (ServletOutputStream os = response.getOutputStream()) {
                    while ((len = is.read(b)) > 0) {
                        os.write(encrptSignFlag ? FileUtil.decryption(b) : b, 0, len);
                    }
                    os.flush();
                    is.close();
                }
                // 删除临时文件
                localTempFile.delete();
            }
        } else {
            // 直接在本地的目录中找文件
            logger.info("直接在本地的目录中找文件...");
            String localBasePath = Global.getSystemConfig("local.dir", "");
            path = localBasePath + File.separator + path;
            File file = new File(path);
            if (needOnlineViewFlag && !file.exists()) {
                // 若是预览,但是转换后的文件不存在,那么重新执行转换操作
                File sourceFile = fileUtils.getFile(false, attachmentFse.getString(CmnConst.ATTACHMENT_URL), fileName, encrptSignFlag);
                File tempSourceFile = new File(sourceFile.getParentFile().getAbsolutePath() + File.separator + attachmentFse.getString(CmnConst.FILE_NAME));
                sourceFile.renameTo(tempSourceFile);
                FileUtils.convertPdf(false, false, encrptSignFlag, true, tempSourceFile, dir, fileName, attachmentFse.getString(CmnConst.FILE_NAME));
                tempSourceFile.delete();
            }
            int len;
            byte[] b = new byte[1024];
            response.setContentType("multipart/form-data");
            InputStream is = new FileInputStream(file);
            response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", file_name));
            response.setContentLengthLong(file.length());
            try (ServletOutputStream os = response.getOutputStream()) {
                while ((len = is.read(b)) > 0) {
                    if (encrptSignFlag) {
                        // 需要解密
                        logger.info("需要解密...");
                        os.write(FileUtil.decryption(b), 0, len);
                    } else {
                        // 无需解密
                        os.write(b, 0, len);
                    }
                }
                os.flush();
            }
                    // 重新拉文件
                    tempOs = new FileOutputStream(localTempFile);
                    ftpService = new FTPService();
                    ftpService.downloadFile(path, tempOs);
                    tempOs.flush();
                    tempOs.close();
                }
                response.setContentLengthLong(localTempFile.length());
                InputStream is = new FileInputStream(localTempFile);
                int len;
                byte[] b = new byte[1024];
                try (ServletOutputStream os = response.getOutputStream()) {
                    while ((len = is.read(b)) > 0) {
                        os.write(encrptSignFlag ? FileUtil.decryption(b) : b, 0, len);
                    }
                    os.flush();
                    is.close();
                }
                // 删除临时文件
                localTempFile.delete();
            }
        } else {
            // 直接在本地的目录中找文件
            logger.info("直接在本地的目录中找文件...");
            String localBasePath = Global.getSystemConfig("local.dir", "");
            path = localBasePath + File.separator + path;
            File file = new File(path);
            if (needOnlineViewFlag && !file.exists()) {
                // 若是预览,但是转换后的文件不存在,那么重新执行转换操作
                File sourceFile = fileUtils.getFile(false, attachmentFse.getString(CmnConst.ATTACHMENT_URL), fileName, encrptSignFlag);
                File tempSourceFile = new File(sourceFile.getParentFile().getAbsolutePath() + File.separator + attachmentFse.getString(CmnConst.FILE_NAME));
                sourceFile.renameTo(tempSourceFile);
                FileUtils.convertPdf(false, false, encrptSignFlag, true, tempSourceFile, dir, fileName, attachmentFse.getString(CmnConst.FILE_NAME));
                tempSourceFile.delete();
            }
            int len;
            byte[] b = new byte[1024];
            response.setContentType("multipart/form-data");
            InputStream is = new FileInputStream(file);
            response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", file_name));
            response.setContentLengthLong(file.length());
            try (ServletOutputStream os = response.getOutputStream()) {
                while ((len = is.read(b)) > 0) {
                    if (encrptSignFlag) {
                        // 需要解密
                        logger.info("需要解密...");
                        os.write(FileUtil.decryption(b), 0, len);
                    } else {
                        // 无需解密
                        os.write(b, 0, len);
                    }
                }
                os.flush();
            }
        }
        logger.info("文件流获取成功");
    }
        }
        logger.info("文件流获取成功");
    }
    /**
     * 获取文件字节 根据文件uuid
     */
    public byte[] getFileContent(String uuid) throws BaseException {
        FieldSetEntity attachmentFse = baseDao.getFieldSetEntity(CmnConst.PRODUCT_SYS_ATTACHMENTS, uuid, false);
        return this.getFileContent(attachmentFse);
    }
    /**
     * 获取文件字节 根据文件uuid
     */
    public byte[] getFileContent(String uuid) throws BaseException {
        FieldSetEntity attachmentFse = baseDao.getFieldSetEntity(CmnConst.PRODUCT_SYS_ATTACHMENTS, uuid, false);
        return this.getFileContent(attachmentFse);
    }
    /**
     * 根据附件uuid获取文件
     * 用完之后需要删除返回的 file (临时文件)
     *
     * @param uuid
     * @return
     * @throws BaseException
     */
    public File getFile(String uuid) throws BaseException {
        FieldSetEntity attachmentFse = baseDao.getFieldSetEntity(CmnConst.PRODUCT_SYS_ATTACHMENTS, uuid, false);
        byte[] fileContent = getFileContent(attachmentFse);
        if (fileContent != null && fileContent.length > 0) {
            String localTempPath = Global.getSystemConfig("temp.dir", "") + File.separator + new Date().getTime() + attachmentFse.getString(CmnConst.ATTACHMENT_TITLE) + attachmentFse.getString("file_name");
            File temp = new File(localTempPath);
            File td = new File(Global.getSystemConfig("temp.dir", ""));
            if (!td.exists()) td.mkdirs();
            try {
                temp.createNewFile();
            } catch (IOException e) {
                throw new BaseException(FileCode.GET_FILE_FAIL.getValue(), FileCode.GET_FILE_FAIL.getText() + (e.getMessage() != null ? e.getMessage() : ""));
            }
            try (FileOutputStream fos = new FileOutputStream(temp); BufferedOutputStream out = new BufferedOutputStream(fos)) {
    /**
     * 根据附件uuid获取文件
     * 用完之后需要删除返回的 file (临时文件)
     *
     * @param uuid
     * @return
     * @throws BaseException
     */
    public File getFile(String uuid) throws BaseException {
        FieldSetEntity attachmentFse = baseDao.getFieldSetEntity(CmnConst.PRODUCT_SYS_ATTACHMENTS, uuid, false);
        return getFile(attachmentFse);
    }
                out.write(fileContent);
                return temp;
            } catch (Exception e) {
                e.printStackTrace();
                throw new BaseException(FileCode.GET_FILE_FAIL.getValue(), FileCode.GET_FILE_FAIL.getText() + (e.getMessage() != null ? e.getMessage() : ""));
            }
        }
        throw new BaseException(FileCode.GET_FILE_FAIL.getValue(), FileCode.GET_FILE_FAIL.getText());
    }
    public File getFile(FieldSetEntity attachmentFse) throws BaseException {
        byte[] fileContent = getFileContent(attachmentFse);
        if (fileContent != null && fileContent.length > 0) {
            String localTempPath = Global.getSystemConfig("temp.dir", "") + File.separator + new Date().getTime() + attachmentFse.getString(CmnConst.ATTACHMENT_TITLE) + attachmentFse.getString("file_name");
            File temp = new File(localTempPath);
            File td = new File(Global.getSystemConfig("temp.dir", ""));
            if (!td.exists()) td.mkdirs();
            try {
                temp.createNewFile();
            } catch (IOException e) {
                throw new BaseException(FileCode.GET_FILE_FAIL.getValue(), FileCode.GET_FILE_FAIL.getText() + (e.getMessage() != null ? e.getMessage() : ""));
            }
            try (FileOutputStream fos = new FileOutputStream(temp); BufferedOutputStream out = new BufferedOutputStream(fos)) {
    /**
     * 获取文件字节 根据附件field
     */
    public byte[] getFileContent(FieldSetEntity attachmentFse) throws BaseException {
        if (attachmentFse == null || !CmnConst.PRODUCT_SYS_ATTACHMENTS.equals(attachmentFse.getTableName())) {
            return new byte[16];
        }
        try (ByteArrayOutputStream os = new ByteArrayOutputStream();) {
            FTPService ftpService = new FTPService();
            boolean needDownloadFromServerFlag = "1".equals(attachmentFse.getString(CmnConst.UPLOAD_SIGN));
            String dir = attachmentFse.getString(CmnConst.ATTACHMENT_URL);
            String fileName = attachmentFse.getString(CmnConst.ATTACHMENT_TITLE);
            boolean encrptSignFlag = "1".equals(attachmentFse.getString(CmnConst.ENCRPT_SIGN));
            String path = dir + File.separator + fileName;
            if (needDownloadFromServerFlag) {
                // 需要从附件服务器上取文件
                if (encrptSignFlag) {
                    // 需要解密
                    String localTempPath = Global.getSystemConfig("temp.dir", "") + File.separator + fileName;
                    File localTempFile = new File(localTempPath);
                    OutputStream tempOs = new FileOutputStream(localTempFile);
                    ftpService.downloadFile(path, tempOs);
                    tempOs.flush();
                    tempOs.close();
                    InputStream is = new FileInputStream(localTempFile);
                    int len;
                    byte[] b = new byte[1024];
                    while ((len = is.read(b)) > 0) {
                        os.write(FileUtil.decryption(b), 0, len);
                    }
                    os.flush();
                    is.close();
                    // 删除临时文件
                    localTempFile.delete();
                } else {
                    ftpService.downloadFile(path, os);
                }
            } else {
                // 直接在本地的目录中找文件
                String localBasePath = Global.getSystemConfig("local.dir", "");
                path = localBasePath + File.separator + path;
                File file = new File(path);
                int len;
                byte[] b = new byte[1024];
                try (InputStream is = new FileInputStream(file)) {
                    while ((len = is.read(b)) > 0) {
                        if (Global.getPropertyToBoolean("file.encrypt", "true")) {
                            // 需要解密
                            os.write(FileUtil.decryption(b), 0, len);
                        } else {
                            // 无需解密
                            os.write(b, 0, len);
                        }
                    }
                }
            }
                out.write(fileContent);
                return temp;
            } catch (Exception e) {
                e.printStackTrace();
                throw new BaseException(FileCode.GET_FILE_FAIL.getValue(), FileCode.GET_FILE_FAIL.getText() + (e.getMessage() != null ? e.getMessage() : ""));
            }
        }
        throw new BaseException(FileCode.GET_FILE_FAIL.getValue(), FileCode.GET_FILE_FAIL.getText());
    }
            return os.toByteArray();
        } catch (Exception e) {
            SpringMVCContextHolder.getSystemLogger().error(FileCode.GET_FILE_BYTES_FAIL.getValue(), FileCode.GET_FILE_BYTES_FAIL.getText() + "," + e.getMessage());
            throw new BaseException(FileCode.GET_FILE_BYTES_FAIL.getValue(), FileCode.GET_FILE_BYTES_FAIL.getText() + "," + e.getMessage());
        }
    }
    /**
     * 获取文件字节 根据附件field
     */
    public byte[] getFileContent(FieldSetEntity attachmentFse) throws BaseException {
        if (attachmentFse == null || !CmnConst.PRODUCT_SYS_ATTACHMENTS.equals(attachmentFse.getTableName())) {
            return new byte[16];
        }
        try (ByteArrayOutputStream os = new ByteArrayOutputStream();) {
            FTPService ftpService = new FTPService();
            boolean needDownloadFromServerFlag = "1".equals(attachmentFse.getString(CmnConst.UPLOAD_SIGN));
            String dir = attachmentFse.getString(CmnConst.ATTACHMENT_URL);
            String fileName = attachmentFse.getString(CmnConst.ATTACHMENT_TITLE);
            boolean encrptSignFlag = "1".equals(attachmentFse.getString(CmnConst.ENCRPT_SIGN));
            String path = dir + File.separator + fileName;
            if (needDownloadFromServerFlag) {
                // 需要从附件服务器上取文件
                if (encrptSignFlag) {
                    // 需要解密
                    String localTempPath = Global.getSystemConfig("temp.dir", "") + File.separator + fileName;
                    File localTempFile = new File(localTempPath);
                    OutputStream tempOs = new FileOutputStream(localTempFile);
                    ftpService.downloadFile(path, tempOs);
                    tempOs.flush();
                    tempOs.close();
                    InputStream is = new FileInputStream(localTempFile);
                    int len;
                    byte[] b = new byte[1024];
                    while ((len = is.read(b)) > 0) {
                        os.write(FileUtil.decryption(b), 0, len);
                    }
                    os.flush();
                    is.close();
                    // 删除临时文件
                    localTempFile.delete();
                } else {
                    ftpService.downloadFile(path, os);
                }
            } else {
                // 直接在本地的目录中找文件
                String localBasePath = Global.getSystemConfig("local.dir", "");
                path = localBasePath + File.separator + path;
                File file = new File(path);
                int len;
                byte[] b = new byte[1024];
                try (InputStream is = new FileInputStream(file)) {
                    while ((len = is.read(b)) > 0) {
                        if (Global.getPropertyToBoolean("file.encrypt", "true")) {
                            // 需要解密
                            os.write(FileUtil.decryption(b), 0, len);
                        } else {
                            // 无需解密
                            os.write(b, 0, len);
                        }
                    }
                }
            }
    /**
     * 获取文件字节,再转换成字符串 根据文件uuid
     */
    public String getFileContentString(String uuid) {
        byte[] b = getFileContent(uuid);
        if (b == null) {
            return null;
        }
        String str = new String(b);
        return str;
    }
            return os.toByteArray();
        } catch (Exception e) {
            SpringMVCContextHolder.getSystemLogger().error(FileCode.GET_FILE_BYTES_FAIL.getValue(), FileCode.GET_FILE_BYTES_FAIL.getText() + "," + e.getMessage());
            throw new BaseException(FileCode.GET_FILE_BYTES_FAIL.getValue(), FileCode.GET_FILE_BYTES_FAIL.getText() + "," + e.getMessage());
        }
    }
    /**
     * 提取文件信息-批量打包下载文件
     *
     * @param fse
     * @param
     */
    public void downLoadFileZip(FieldSetEntity fse, HttpServletResponse response) throws IOException, BaseException {
        logger.info("正在打包下载文件...");
        response.setContentType("multipart/form-data");
        try (ServletOutputStream os = response.getOutputStream()) {
            String uuids = fse.getString("uuids");
            if (StringUtils.isEmpty(uuids)) {
                throw new BaseException(FileCode.GET_DATA_FAIL.getValue(), FileCode.GET_DATA_FAIL.getText() + ":uuids");
            }
            DataTableEntity attachmentDte = baseDao.listTable(CmnConst.PRODUCT_SYS_ATTACHMENTS,
                    new Object[]{CmnConst.ATTACHMENT_URL, CmnConst.FILE_NAME, CmnConst.VIEW_ONLINE_SIGN, CmnConst.FILE_NAME, CmnConst.ENCRPT_SIGN, CmnConst.ATTACHMENT_TITLE, CmnConst.UPLOAD_SIGN},
                    uuids.split(","));
            FieldSetEntity attachmentFse;
            String fileName;
            String dir;
            String sourcePath;
            String localTempPath;
            FTPService ftpService;
            boolean needDownloadFromServerFlag;
            List<Map<String, String>> pathList = Lists.newArrayList();
            Map<String, String> pathMap;
            for (int i = 0; i < attachmentDte.getRows(); i++) {
                pathMap = Maps.newHashMap();
                attachmentFse = attachmentDte.getFieldSetEntity(i);
                needDownloadFromServerFlag = "1".equals(attachmentFse.getString(CmnConst.UPLOAD_SIGN));
                fileName = attachmentFse.getString(CmnConst.ATTACHMENT_TITLE);
                dir = attachmentFse.getString(CmnConst.ATTACHMENT_URL);
                sourcePath = dir + File.separator + fileName;
                localTempPath = Global.getSystemConfig("temp.dir", "") + File.separator + fileName;
                pathMap.put(CmnConst.REAL_FILE_NAME, attachmentFse.getString(CmnConst.FILE_NAME));
                pathMap.put(CmnConst.ENCRPT_SIGN, attachmentFse.getString(CmnConst.ENCRPT_SIGN));
                if (needDownloadFromServerFlag) {
                    ftpService = new FTPService();
                    ftpService.downloadFile(sourcePath, localTempPath);
                    pathMap.put(CmnConst.NEED_LOCAL_TEMP_FILE_SIGN, "1");
                    pathMap.put(CmnConst.SOURCE_PATH, localTempPath);
                } else {
                    pathMap.put(CmnConst.NEED_LOCAL_TEMP_FILE_SIGN, "0");
                    pathMap.put(CmnConst.SOURCE_PATH, Global.getSystemConfig("local.dir", "") + File.separator + sourcePath);
                }
                pathList.add(pathMap);
            }
    /**
     * 获取文件字节,再转换成字符串 根据文件uuid
     */
    public String getFileContentString(String uuid) {
        byte[] b = getFileContent(uuid);
        if (b == null) {
            return null;
        }
        String str = new String(b);
        return str;
    }
            long fileSize = FileUtil.createZip(pathList, os);
            response.setContentLengthLong(fileSize);
    /**
     * 提取文件信息-批量打包下载文件
     *
     * @param fse
     * @param
     */
    public void downLoadFileZip(FieldSetEntity fse, HttpServletResponse response) throws IOException, BaseException {
        logger.info("正在打包下载文件...");
        response.setContentType("multipart/form-data");
        try (ServletOutputStream os = response.getOutputStream()) {
            String uuids = fse.getString("uuids");
            if (StringUtils.isEmpty(uuids)) {
                throw new BaseException(FileCode.GET_DATA_FAIL.getValue(), FileCode.GET_DATA_FAIL.getText() + ":uuids");
            }
            DataTableEntity attachmentDte = baseDao.listTable(CmnConst.PRODUCT_SYS_ATTACHMENTS,
                    new Object[]{CmnConst.ATTACHMENT_URL, CmnConst.FILE_NAME, CmnConst.VIEW_ONLINE_SIGN, CmnConst.FILE_NAME, CmnConst.ENCRPT_SIGN, CmnConst.ATTACHMENT_TITLE, CmnConst.UPLOAD_SIGN},
                    uuids.split(","));
            FieldSetEntity attachmentFse;
            String fileName;
            String dir;
            String sourcePath;
            String localTempPath;
            FTPService ftpService;
            boolean needDownloadFromServerFlag;
            List<Map<String, String>> pathList = Lists.newArrayList();
            Map<String, String> pathMap;
            for (int i = 0; i < attachmentDte.getRows(); i++) {
                pathMap = Maps.newHashMap();
                attachmentFse = attachmentDte.getFieldSetEntity(i);
                needDownloadFromServerFlag = "1".equals(attachmentFse.getString(CmnConst.UPLOAD_SIGN));
                fileName = attachmentFse.getString(CmnConst.ATTACHMENT_TITLE);
                dir = attachmentFse.getString(CmnConst.ATTACHMENT_URL);
                sourcePath = dir + File.separator + fileName;
                localTempPath = Global.getSystemConfig("temp.dir", "") + File.separator + fileName;
                pathMap.put(CmnConst.REAL_FILE_NAME, attachmentFse.getString(CmnConst.FILE_NAME));
                pathMap.put(CmnConst.ENCRPT_SIGN, attachmentFse.getString(CmnConst.ENCRPT_SIGN));
                if (needDownloadFromServerFlag) {
                    ftpService = new FTPService();
                    ftpService.downloadFile(sourcePath, localTempPath);
                    pathMap.put(CmnConst.NEED_LOCAL_TEMP_FILE_SIGN, "1");
                    pathMap.put(CmnConst.SOURCE_PATH, localTempPath);
                } else {
                    pathMap.put(CmnConst.NEED_LOCAL_TEMP_FILE_SIGN, "0");
                    pathMap.put(CmnConst.SOURCE_PATH, Global.getSystemConfig("local.dir", "") + File.separator + sourcePath);
                }
                pathList.add(pathMap);
            }
            File file;
            for (Map<String, String> map : pathList) {
                for (String key : map.keySet()) {
                    if ("1".equals(map.get(CmnConst.NEED_LOCAL_TEMP_FILE_SIGN)) && !CmnConst.SOURCE_PATH.equals(key)) {
                        continue;
                    }
                    file = new File(key);
                    file.delete();
                }
            }
            logger.info("文件流获取成功");
        } catch (IOException e) {
            throw e;
        }
    }
            long fileSize = FileUtil.createZip(pathList, os);
            response.setContentLengthLong(fileSize);
    /**
     * 删除本地或线上服务器文件
     *
     * @param fse
     * @return
     */
    public boolean delFiles(FieldSetEntity fse) {
        FTPService ftpService = new FTPService();
        boolean needUpload2FileServerFlag = FTPService.needUpload2FileServer();
        String uuid = fse.getString(CmnConst.UUID);
        boolean needOnlineViewFlag = "1".equals(fse.getString(CmnConst.UPLOAD_SIGN));
        FieldSetEntity attachmentFse = baseDao.getFieldSetEntity(CmnConst.PRODUCT_SYS_ATTACHMENTS, uuid, false);
        String path = attachmentFse.getString(CmnConst.ATTACHMENT_URL);
        if (needUpload2FileServerFlag) {
            //删除线上服务器文件
            ftpService.deleteFile(path, attachmentFse.getString(CmnConst.FILE_NAME));
            //if(needOnlineViewFlag){//需要删除转换后的文件
            path += File.separator + CmnConst.TRANSFER_DIR_NAME;
            ftpService.deleteFile(path, attachmentFse.getString(CmnConst.FILE_NAME));
            //}
        } else {
            //删除本地服务器文件
            deleteFiles(Global.getSystemConfig("temp.dir", "") + "/" + attachmentFse.getString(CmnConst.FILE_NAME));// 路径及文件名(或文件夹)
            deleteFiles(Global.getSystemConfig("temp.dir", "") + "/" + CmnConst.TRANSFER_DIR_NAME + "/" + attachmentFse.getString(CmnConst.FILE_NAME));// 在线预览路径及文件名(或文件夹)
            deleteFiles(Global.getSystemConfig("local.dir", "") + "/" + attachmentFse.getString(CmnConst.FILE_NAME));// 路径及文件名(或文件夹)
            deleteFiles(Global.getSystemConfig("local.dir", "") + "/" + CmnConst.TRANSFER_DIR_NAME + "/" + attachmentFse.getString(CmnConst.FILE_NAME));// 在线预览路径及文件名(或文件夹)
        }
        //删除数据库记录
        return baseDao.delete(CmnConst.PRODUCT_SYS_ATTACHMENTS, new Object[]{uuid});
    }
            File file;
            for (Map<String, String> map : pathList) {
                for (String key : map.keySet()) {
                    if ("1".equals(map.get(CmnConst.NEED_LOCAL_TEMP_FILE_SIGN)) && !CmnConst.SOURCE_PATH.equals(key)) {
                        continue;
                    }
                    file = new File(key);
                    file.delete();
                }
            }
            logger.info("文件流获取成功");
        } catch (IOException e) {
            throw e;
        }
    }
    /**
     * 删除单个文件
     *
     * @param pathName 删除文件路径名
     * @return
     */
    public boolean deleteFiles(String pathName) {
        boolean flag = false;
        //根据路径创建文件对象
        File file = new File(pathName);
        //路径是个文件且不为空时删除文件
        if (file.isFile() && file.exists()) {
            flag = file.delete();
        }
        //删除失败时,返回false
        return flag;
    }
    /**
     * 删除本地或线上服务器文件
     *
     * @param fse
     * @return
     */
    public boolean delFiles(FieldSetEntity fse) {
        FTPService ftpService = new FTPService();
        boolean needUpload2FileServerFlag = FTPService.needUpload2FileServer();
        String uuid = fse.getString(CmnConst.UUID);
        boolean needOnlineViewFlag = "1".equals(fse.getString(CmnConst.UPLOAD_SIGN));
        FieldSetEntity attachmentFse = baseDao.getFieldSetEntity(CmnConst.PRODUCT_SYS_ATTACHMENTS, uuid, false);
        String path = attachmentFse.getString(CmnConst.ATTACHMENT_URL);
        if (needUpload2FileServerFlag) {
            //删除线上服务器文件
            ftpService.deleteFile(path, attachmentFse.getString(CmnConst.FILE_NAME));
            //if(needOnlineViewFlag){//需要删除转换后的文件
            path += File.separator + CmnConst.TRANSFER_DIR_NAME;
            ftpService.deleteFile(path, attachmentFse.getString(CmnConst.FILE_NAME));
            //}
        } else {
            //删除本地服务器文件
            deleteFiles(Global.getSystemConfig("temp.dir", "") + "/" + attachmentFse.getString(CmnConst.FILE_NAME));// 路径及文件名(或文件夹)
            deleteFiles(Global.getSystemConfig("temp.dir", "") + "/" + CmnConst.TRANSFER_DIR_NAME + "/" + attachmentFse.getString(CmnConst.FILE_NAME));// 在线预览路径及文件名(或文件夹)
            deleteFiles(Global.getSystemConfig("local.dir", "") + "/" + attachmentFse.getString(CmnConst.FILE_NAME));// 路径及文件名(或文件夹)
            deleteFiles(Global.getSystemConfig("local.dir", "") + "/" + CmnConst.TRANSFER_DIR_NAME + "/" + attachmentFse.getString(CmnConst.FILE_NAME));// 在线预览路径及文件名(或文件夹)
        }
        //删除数据库记录
        return baseDao.delete(CmnConst.PRODUCT_SYS_ATTACHMENTS, new Object[]{uuid});
    }
    /**
     * 删除目录本身以及目录下的所有文件及文件夹
     *
     * @param pathName 目录名
     * @return
     */
    public boolean deleteDiretory(String pathName) {
        boolean flag = false;
        //根据路径创建文件对象
        File directory = new File(pathName);
        //如果路径是一个目录且不为空时,删除目录
        if (directory.isDirectory() && directory.exists()) {
            //获取目录下的所有的目录和文件,放入数组files中
            File[] files = directory.listFiles();
            //遍历目录下的所有的文件和目录
            for (int i = 0; i < files.length; i++) {
                //如果目录下是文件时,调用deleteFiles()方法,删除单个文件
                if (files[i].isFile()) {
                    flag = deleteFiles(files[i].getAbsolutePath());
                }//如果目录下是目录时,调用自身deleteDirectory(),形成递归调用
                else {
                    flag = deleteDiretory(files[i].getAbsolutePath());
                }
            }
            //删除目录本身,如果想要保留目录只删除文件,此句可以不要
            flag = directory.delete();
        }
        //删除成功时返回true,失败时返回false
        return flag;
    }
    /**
     * 删除单个文件
     *
     * @param pathName 删除文件路径名
     * @return
     */
    public boolean deleteFiles(String pathName) {
        boolean flag = false;
        //根据路径创建文件对象
        File file = new File(pathName);
        //路径是个文件且不为空时删除文件
        if (file.isFile() && file.exists()) {
            flag = file.delete();
        }
        //删除失败时,返回false
        return flag;
    }
    /**
     * 删除文件或者目录
     *
     * @param pathName 路径名
     * @return
     */
    public boolean deleteDirectoryOrFile(String pathName) {
        boolean flag = false;
        File file = new File(pathName);
        //如果路径是一个文件则调用deleteFiles()
        if (file.isFile() && file.exists()) {
            flag = deleteFiles(pathName);
        }//如果路径是目录则调用deleteDirectory()
        else if (file.isDirectory() && file.exists()) {
            flag = deleteDiretory(pathName);
        }
    /**
     * 删除目录本身以及目录下的所有文件及文件夹
     *
     * @param pathName 目录名
     * @return
     */
    public boolean deleteDiretory(String pathName) {
        boolean flag = false;
        //根据路径创建文件对象
        File directory = new File(pathName);
        //如果路径是一个目录且不为空时,删除目录
        if (directory.isDirectory() && directory.exists()) {
            //获取目录下的所有的目录和文件,放入数组files中
            File[] files = directory.listFiles();
            //遍历目录下的所有的文件和目录
            for (int i = 0; i < files.length; i++) {
                //如果目录下是文件时,调用deleteFiles()方法,删除单个文件
                if (files[i].isFile()) {
                    flag = deleteFiles(files[i].getAbsolutePath());
                }//如果目录下是目录时,调用自身deleteDirectory(),形成递归调用
                else {
                    flag = deleteDiretory(files[i].getAbsolutePath());
                }
            }
            //删除目录本身,如果想要保留目录只删除文件,此句可以不要
            flag = directory.delete();
        }
        //删除成功时返回true,失败时返回false
        return flag;
    }
        return flag;
    }
    /**
     * 删除文件或者目录
     *
     * @param pathName 路径名
     * @return
     */
    public boolean deleteDirectoryOrFile(String pathName) {
        boolean flag = false;
        File file = new File(pathName);
        //如果路径是一个文件则调用deleteFiles()
        if (file.isFile() && file.exists()) {
            flag = deleteFiles(pathName);
        }//如果路径是目录则调用deleteDirectory()
        else if (file.isDirectory() && file.exists()) {
            flag = deleteDiretory(pathName);
        }
        return flag;
    }
}
src/main/java/com/product/file/service/OnlineDocumentEditService.java
@@ -38,284 +38,287 @@
@Service
@Primary
public class OnlineDocumentEditService extends AbstractBaseService implements IOnlineDocumentEditingService {
    /**
     * 文档编辑标识key
     */
    private final String DOCUMENT_EDIT_KEY = "document-edit:";
    /**
     * 文档编辑标识key
     */
    private final String DOCUMENT_EDIT_KEY = "document-edit:";
    @Autowired
    FileManagerService fileManagerService;
    @Autowired
    FileManagerService fileManagerService;
    @Autowired
    FileUtils fileUtils;
    @Autowired
    FileUtils fileUtils;
    /**
     * 文档套红
     *
     * @param ff
     * @param file
     */
    public void nestRedDocument(FieldSetEntity ff, File file) {
        try {
            String document_template = ff.getString("document_template");
            String document_template_tail = ff.getString("document_template_tail");
            List<File> fileList = new ArrayList<>(3);
            if (!StringUtils.isEmpty(document_template)) {
                fileList.add(fileManagerService.getFile(document_template));
                fileList.add(file);
            } else {
                fileList.add(file);
            }
            if (!StringUtils.isEmpty(document_template_tail)) {
                fileList.add(fileManagerService.getFile(document_template_tail));
            }
            File mergeFile = MergeDoc.mergeDoc(fileList, Global.getSystemConfig("upload.file.temp.path", "./attachment/temp") +
                    File.separator + "nest_red_document_" + IdUtil.randomUUID() + "_" + ff.getString("file_uuid"));
            if (mergeFile != null && mergeFile.isFile()) {
                HashMap<String, File> objectObjectHashMap = new HashMap<>();
                objectObjectHashMap.put("mergeFile", mergeFile);
                uploadFile(ff.getString("file_uuid"), objectObjectHashMap);
            } else {
                throw new BaseException(FileCode.NEST_RED_DOCUMENT_FAIL);
            }
        } catch (BaseException e) {
            throw e;
        } catch (Exception e) {
            throw new BaseException(FileCode.NEST_RED_DOCUMENT_FAIL);
        }
    }
    /**
     * 文档套红
     *
     * @param ff
     * @param file
     */
    public void nestRedDocument(FieldSetEntity ff, File file) {
        try {
            String document_template = ff.getString("document_template");
            String document_template_tail = ff.getString("document_template_tail");
            List<File> fileList = new ArrayList<>(3);
            if (!StringUtils.isEmpty(document_template)) {
                fileList.add(fileManagerService.getFile(document_template));
                fileList.add(file);
            } else {
                fileList.add(file);
            }
            if (!StringUtils.isEmpty(document_template_tail)) {
                fileList.add(fileManagerService.getFile(document_template_tail));
            }
            File mergeFile = MergeDoc.mergeDoc(fileList, Global.getSystemConfig("upload.file.temp.path", "./attachment/temp") +
                    File.separator + "nest_red_document_" + IdUtil.randomUUID() + "_" + ff.getString("file_uuid"));
            if (mergeFile != null && mergeFile.isFile()) {
                HashMap<String, File> objectObjectHashMap = new HashMap<>();
                objectObjectHashMap.put("mergeFile", mergeFile);
                uploadFile(ff.getString("file_uuid"), objectObjectHashMap);
            } else {
                throw new BaseException(FileCode.NEST_RED_DOCUMENT_FAIL);
            }
        } catch (BaseException e) {
            throw e;
        } catch (Exception e) {
            throw new BaseException(FileCode.NEST_RED_DOCUMENT_FAIL);
        }
    }
    /**
     * 在线预览或编辑获取文件
     *
     * @param response
     * @param uuid
     * @throws IOException
     */
    public void getFile(HttpServletResponse response, String uuid) throws IOException {
        String currentUserId = SpringMVCContextHolder.getCurrentUserId();
        if (StringUtils.isEmpty(currentUserId)) {
            return;
        }
        String redisKey = this.DOCUMENT_EDIT_KEY + uuid + "-" + currentUserId;
        //在redis中获取缓存 根据缓存是否存在判断该文件是否标识为正在编辑的状态
        Map<String, Object> map = (Map<String, Object>) RedisUtil.get(redisKey);  //查询文件记录
        FieldSetEntity fse = getBaseDao().getFieldSetEntity(CmnConst.PRODUCT_SYS_ATTACHMENTS, uuid, false);
        if (FieldSetEntity.isEmpty(fse)) {
            throw new BaseException(FileCode.GET_FILE_RECORD_FAIL);
        }
        if (map != null) {
            //正在编辑 准备输出已编辑过但未提交的文件
            String dir = fse.getString(CmnConst.ATTACHMENT_URL);
            String fileName = fse.getString(CmnConst.ATTACHMENT_TITLE);
            //已编辑未提交的文件路径
            try {
                File sourceFile = fileUtils.getFile(fse.getBoolean(CmnConst.UPLOAD_SIGN), dir, fileName + "_" + currentUserId + "_" + map.get("uniqueKey"), fse.getBoolean(CmnConst.ENCRPT_SIGN));
                if (sourceFile != null && sourceFile.isFile()) {
                    //输出
                    IoUtil.write(response.getOutputStream(), true, FileUtil.readBytes(sourceFile));
                    sourceFile.delete();
                    return;
                }
            } catch (BaseException e) {
                //捕获异常
            }
        }
        IoUtil.write(response.getOutputStream(), true, fileManagerService.getFileContent(fse));
    }
    /**
     * 在线预览或编辑获取文件
     *
     * @param response
     * @param uuid
     * @throws IOException
     */
    public void getFile(HttpServletResponse response, String uuid) throws IOException {
        String currentUserId = SpringMVCContextHolder.getCurrentUserId();
        if (StringUtils.isEmpty(currentUserId)) {
            return;
        }
        String redisKey = this.DOCUMENT_EDIT_KEY + uuid + "-" + currentUserId;
        //在redis中获取缓存 根据缓存是否存在判断该文件是否标识为正在编辑的状态
        Map<String, Object> map = (Map<String, Object>) RedisUtil.get(redisKey);  //查询文件记录
        FieldSetEntity fse = getBaseDao().getFieldSetEntity(CmnConst.PRODUCT_SYS_ATTACHMENTS, uuid, false);
        if (FieldSetEntity.isEmpty(fse)) {
            throw new BaseException(FileCode.GET_FILE_RECORD_FAIL);
        }
        if (map != null) {
            //正在编辑 准备输出已编辑过但未提交的文件
            String dir = fse.getString(CmnConst.ATTACHMENT_URL);
            String fileName = fse.getString(CmnConst.ATTACHMENT_TITLE);
            //已编辑未提交的文件路径
            try {
                File sourceFile = fileUtils.getFile(fse.getBoolean(CmnConst.UPLOAD_SIGN), dir, fileName + "_" + currentUserId + "_" + map.get("uniqueKey"), fse.getBoolean(CmnConst.ENCRPT_SIGN));
                if (sourceFile != null && sourceFile.isFile()) {
                    //输出
                    IoUtil.write(response.getOutputStream(), true, FileUtil.readBytes(sourceFile));
                    sourceFile.delete();
                    return;
                }
            } catch (BaseException e) {
                //捕获异常
            }
        }
        IoUtil.write(response.getOutputStream(), true, fileManagerService.getFileContent(fse));
    }
    /**
     * 清空正在编辑文档状态 根据用户
     *
     * @param userId 用户id
     */
    public void clearBeingEditDocumentStatus(String userId) {
        if (StringUtils.isEmpty(userId)) {
            return;
        }
        //正则匹配redis中的key
        try (Jedis jedis = RedisUtil.getJedis()) {
            Set<String> keys = jedis.keys(this.DOCUMENT_EDIT_KEY + "*-" + userId);
            if (keys != null && keys.size() > 0) {
                //清空redis
                RedisUtil.del(keys.toArray(new String[keys.size()]));
            }
        }
    }
    /**
     * 清空正在编辑文档状态 根据用户
     *
     * @param userId 用户id
     */
    public void clearBeingEditDocumentStatus(String userId) {
        if (StringUtils.isEmpty(userId)) {
            return;
        }
        //正则匹配redis中的key
        try (Jedis jedis = RedisUtil.getJedis()) {
            Set<String> keys = jedis.keys(this.DOCUMENT_EDIT_KEY + "*-" + userId);
            if (keys != null && keys.size() > 0) {
                //清空redis
                RedisUtil.del(keys.toArray(new String[keys.size()]));
            }
        }
    }
    /**
     * 业务数据保存时底层调用此方法
     * 调用此方法后将文件标记为已保存 清除正在编辑的状态标识
     *
     * @param fileUuid 文件uuid
     * @param userId   操作人id
     * @return
     */
    @Override
    public boolean saveDocNotice(String fileUuid, int userId) throws BaseException {
    /**
     * 业务数据保存时底层调用此方法
     * 调用此方法后将文件标记为已保存 清除正在编辑的状态标识
     *
     * @param fileUuid 文件uuid
     * @param userId   操作人id
     * @return
     */
    @Override
    public boolean saveDocNotice(String fileUuid, int userId) throws BaseException {
        if (StringUtils.isEmpty(fileUuid)) {
            return false;
        }
        String[] fileUuids = fileUuid.split(",");
        //查询文件记录
        DataTableEntity dt = getBaseDao().listTable(CmnConst.PRODUCT_SYS_ATTACHMENTS, BaseUtil.buildQuestionMarkFilter("uuid", fileUuids, true));
        if (!DataTableEntity.isEmpty(dt)) {
        if (StringUtils.isEmpty(fileUuid)) {
            return false;
        }
        String[] fileUuids = fileUuid.split(",");
        //查询文件记录
        DataTableEntity dt = getBaseDao().listTable(CmnConst.PRODUCT_SYS_ATTACHMENTS, BaseUtil.buildQuestionMarkFilter("uuid", fileUuids, true));
        if (!DataTableEntity.isEmpty(dt)) {
//                throw new BaseException(FileCode.GET_FILE_RECORD_FAIL);
            for (int i = 0; i < dt.getRows(); i++) {
                FieldSetEntity fse = dt.getFieldSetEntity(i);
                try {
                    String redisKey = this.DOCUMENT_EDIT_KEY + fse.getUUID() + "-" + userId;
                    Map<String, Object> map = (Map<String, Object>) RedisUtil.get(redisKey);
                    if (map != null) {
                        String dir = fse.getString(CmnConst.ATTACHMENT_URL);
                        String fileName = fse.getString(CmnConst.ATTACHMENT_TITLE);
                        if (!fileUtils.fileIsExist(fse.getBoolean(CmnConst.UPLOAD_SIGN), dir, fileName)) {
                            continue;
                        }
                        //系统附件存放的根路径
                        File sourceFile = fileUtils.getFile(fse.getBoolean(CmnConst.UPLOAD_SIGN), dir, fileName + "_" + userId + "_" + map.get("uniqueKey"), fse.getBoolean(CmnConst.ENCRPT_SIGN));
                        if (sourceFile != null && sourceFile.isFile()) {
                            File targetFile = fileUtils.getFile(fse.getBoolean(CmnConst.UPLOAD_SIGN), dir, fileName, false);
                            if (targetFile != null && targetFile.isFile()) {
                                //备份源文件
                                fileUtils.uploadOtherFile(fse.getBoolean(CmnConst.ENCRPT_SIGN), dir, targetFile, fileName + "_back_" + userId + "_" + map.get("uniqueKey"));
                                targetFile.delete();
                            }
            for (int i = 0; i < dt.getRows(); i++) {
                FieldSetEntity fse = dt.getFieldSetEntity(i);
                try {
                    String redisKey = this.DOCUMENT_EDIT_KEY + fse.getUUID() + "-" + userId;
                    if (!RedisUtil.exists(redisKey)) {
                        continue;
                    }
                    Map<String, Object> map = (Map<String, Object>) RedisUtil.get(redisKey);
                    if (map != null) {
                        String dir = fse.getString(CmnConst.ATTACHMENT_URL);
                        String fileName = fse.getString(CmnConst.ATTACHMENT_TITLE);
                        if (!fileUtils.fileIsExist(fse.getBoolean(CmnConst.UPLOAD_SIGN), dir, fileName)) {
                            continue;
                        }
                        //系统附件存放的根路径
                        File sourceFile = fileUtils.getFile(fse.getBoolean(CmnConst.UPLOAD_SIGN), dir, fileName + "_" + userId + "_" + map.get("uniqueKey"), fse.getBoolean(CmnConst.ENCRPT_SIGN));
                        if (sourceFile != null && sourceFile.isFile()) {
                            File targetFile = fileUtils.getFile(fse.getBoolean(CmnConst.UPLOAD_SIGN), dir, fileName, false);
                            if (targetFile != null && targetFile.isFile()) {
                                //备份源文件
                                fileUtils.uploadOtherFile(fse.getBoolean(CmnConst.ENCRPT_SIGN), dir, targetFile, fileName + "_back_" + userId + "_" + map.get("uniqueKey"));
                                targetFile.delete();
                            }
                            //将修改后的文件覆盖到源文件
                            fileUtils.replaceFile(dir, fileName, fse.getString(CmnConst.FILE_NAME), sourceFile, fse.getBoolean(CmnConst.ENCRPT_SIGN), fse.getBoolean(CmnConst.UPLOAD_SIGN), fse.getBoolean(CmnConst.VIEW_ONLINE_SIGN));
                            if (fse.getBoolean(CmnConst.ENCRPT_SIGN)) {
                                fileUtils.deleteFilesServerOnFile(dir, fileName + "_" + userId + "_" + map.get("uniqueKey"));
                            }
                            sourceFile.delete();
                        }
                    }
                    RedisUtil.del(redisKey);
                } catch (Exception e) {
                    e.printStackTrace();
                    SpringMVCContextHolder.getSystemLogger().error(e);
                            //将修改后的文件覆盖到源文件
                            fileUtils.replaceFile(dir, fileName, fse.getString(CmnConst.FILE_NAME), sourceFile, fse.getBoolean(CmnConst.ENCRPT_SIGN), fse.getBoolean(CmnConst.UPLOAD_SIGN), fse.getBoolean(CmnConst.VIEW_ONLINE_SIGN));
                            if (fse.getBoolean(CmnConst.ENCRPT_SIGN)) {
                                fileUtils.deleteFilesServerOnFile(dir, fileName + "_" + userId + "_" + map.get("uniqueKey"));
                            }
                            sourceFile.delete();
                        }
                    }
                    RedisUtil.del(redisKey);
                } catch (Exception e) {
                    e.printStackTrace();
                    SpringMVCContextHolder.getSystemLogger().error(e);
//                    return false;
                }
            }
        }
                }
            }
        }
        return true;
    }
        return true;
    }
    /**
     * weboffice 保存文件(手动、自动)
     *
     * @param uuid    文件的uuid
     * @param fileMap 新提交的文件
     * @throws BaseException
     */
    public void uploadFile(String uuid, Map<String, File> fileMap) throws BaseException {
        //查询文件记录
        FieldSetEntity fse = getBaseDao().getFieldSetEntity(CmnConst.PRODUCT_SYS_ATTACHMENTS, uuid, false);
        if (FieldSetEntity.isEmpty(fse)) {
            throw new BaseException(FileCode.GET_FILE_RECORD_FAIL);
        }
        String userId = SpringMVCContextHolder.getCurrentUserId();
        if (StringUtils.isEmpty(userId)) {
            return;
        }
        //获取源文件路径
        String dir = fse.getString(CmnConst.ATTACHMENT_URL);
        String fileName = fse.getString(CmnConst.ATTACHMENT_TITLE);
        if (!fileUtils.fileIsExist(fse.getBoolean(CmnConst.UPLOAD_SIGN), dir, fileName)) {
            throw new BaseException(FileCode.INVALID_FILE_PATH);
        }
        String redisKey = this.DOCUMENT_EDIT_KEY + uuid + "-" + userId;
        Map<String, Object> map = (Map<String, Object>) RedisUtil.get(redisKey);
    /**
     * weboffice 保存文件(手动、自动)
     *
     * @param uuid    文件的uuid
     * @param fileMap 新提交的文件
     * @throws BaseException
     */
    public void uploadFile(String uuid, Map<String, File> fileMap) throws BaseException {
        //查询文件记录
        FieldSetEntity fse = getBaseDao().getFieldSetEntity(CmnConst.PRODUCT_SYS_ATTACHMENTS, uuid, false);
        if (FieldSetEntity.isEmpty(fse)) {
            throw new BaseException(FileCode.GET_FILE_RECORD_FAIL);
        }
        String userId = SpringMVCContextHolder.getCurrentUserId();
        if (StringUtils.isEmpty(userId)) {
            return;
        }
        //获取源文件路径
        String dir = fse.getString(CmnConst.ATTACHMENT_URL);
        String fileName = fse.getString(CmnConst.ATTACHMENT_TITLE);
        if (!fileUtils.fileIsExist(fse.getBoolean(CmnConst.UPLOAD_SIGN), dir, fileName)) {
            throw new BaseException(FileCode.INVALID_FILE_PATH);
        }
        String redisKey = this.DOCUMENT_EDIT_KEY + uuid + "-" + userId;
        Map<String, Object> map = (Map<String, Object>) RedisUtil.get(redisKey);
        //系统附件存放的根路径
        File file = fileMap.values().toArray(new File[]{})[0];
        if (fse.getBoolean(CmnConst.ENCRPT_SIGN)) {
            String filePath = Global.getSystemConfig("temp.dir", "") + "/onlineEdit_" + redisKey;
            //加密文件
            com.product.file.util.FileUtil.copyFile(file, filePath, 1);
            file.delete();
            file = new File(filePath);
        }
        FileUtils.uploadOtherFile(fse.getBoolean(CmnConst.ENCRPT_SIGN), dir, file, fileName + "_" + userId + "_" + map.get("uniqueKey"));
        file.delete();
    }
        //系统附件存放的根路径
        File file = fileMap.values().toArray(new File[]{})[0];
        if (fse.getBoolean(CmnConst.ENCRPT_SIGN)) {
            String filePath = Global.getSystemConfig("temp.dir", "") + "/onlineEdit_" + redisKey;
            //加密文件
            com.product.file.util.FileUtil.copyFile(file, filePath, 1);
            file.delete();
            file = new File(filePath);
        }
        FileUtils.uploadOtherFile(fse.getBoolean(CmnConst.ENCRPT_SIGN), dir, file, fileName + "_" + userId + "_" + map.get("uniqueKey"));
        file.delete();
    }
    public void deleteFile(String dir, String fileName) {
        SystemUser currentUser = SpringMVCContextHolder.getCurrentUser();
        if (currentUser != null && !StringUtils.isEmpty(currentUser.getToken_info())) {
    public void deleteFile(String dir, String fileName) {
        SystemUser currentUser = SpringMVCContextHolder.getCurrentUser();
        if (currentUser != null && !StringUtils.isEmpty(currentUser.getToken_info())) {
//            TokenValidateInterceptor
        }
    }
        }
    }
    /**
     * 获取过期时间
     *
     * @return 过期时间 单位 秒
     */
    private int getExpirationTime() {
        int refreshTokenExpiration = Global.getPropertyToInteger("refresh.token.expiration", "8") * 60 * 60;
        int tokenExpiration = Global.getPropertyToInteger("token.expiration", (8 * 60) + "") * 60;
    /**
     * 获取过期时间
     *
     * @return 过期时间 单位 秒
     */
    private int getExpirationTime() {
        int refreshTokenExpiration = Global.getPropertyToInteger("refresh.token.expiration", "8") * 60 * 60;
        int tokenExpiration = Global.getPropertyToInteger("token.expiration", (8 * 60) + "") * 60;
        return refreshTokenExpiration > tokenExpiration ? refreshTokenExpiration : tokenExpiration;
    }
        return refreshTokenExpiration > tokenExpiration ? refreshTokenExpiration : tokenExpiration;
    }
    /**
     * 标识文档正在编辑
     *
     * @param fileUuid
     * @return
     */
    public void signDocumentEdit(String fileUuid) throws BaseException {
        String userId = SpringMVCContextHolder.getCurrentUserId();
        if (StringUtils.isEmpty(userId)) {
            throw new BaseException(FileCode.GET_FILE_RECORD_FAIL);
        }
        String key = this.DOCUMENT_EDIT_KEY + fileUuid + "-" + userId;
        try (Jedis jedis = RedisUtil.getJedis()) {
            //模糊匹配key
            Set<byte[]> keyBytes = jedis.keys((this.DOCUMENT_EDIT_KEY + fileUuid + "-*").getBytes(StandardCharsets.UTF_8));
            if (!CollectionUtil.isEmpty(keyBytes)) {
                Set<String> keys = keyBytes.stream().map(item -> new String(item, StandardCharsets.UTF_8)).collect(Collectors.toSet());
                boolean remove = keys.remove(this.DOCUMENT_EDIT_KEY + fileUuid + "-" + userId);
                if (keys != null && keys.size() > 0) {
                    //正在被编辑
                    String existsKey = keys.toArray(new String[]{})[0];
                    //这里会抛出正在编辑的异常
                    throwBeingEditDocument(existsKey.substring(existsKey.lastIndexOf("-")));
                } else if (remove) {
                    RedisUtil.setOutTime(key, getExpirationTime());
                    return;
                }
            }
    /**
     * 标识文档正在编辑
     *
     * @param fileUuid
     * @return
     */
    public void signDocumentEdit(String fileUuid) throws BaseException {
        String userId = SpringMVCContextHolder.getCurrentUserId();
        if (StringUtils.isEmpty(userId)) {
            throw new BaseException(FileCode.GET_FILE_RECORD_FAIL);
        }
        String key = this.DOCUMENT_EDIT_KEY + fileUuid + "-" + userId;
        try (Jedis jedis = RedisUtil.getJedis()) {
            //模糊匹配key
            Set<byte[]> keyBytes = jedis.keys((this.DOCUMENT_EDIT_KEY + fileUuid + "-*").getBytes(StandardCharsets.UTF_8));
            if (!CollectionUtil.isEmpty(keyBytes)) {
                Set<String> keys = keyBytes.stream().map(item -> new String(item, StandardCharsets.UTF_8)).collect(Collectors.toSet());
                boolean remove = keys.remove(this.DOCUMENT_EDIT_KEY + fileUuid + "-" + userId);
                if (keys != null && keys.size() > 0) {
                    //正在被编辑
                    String existsKey = keys.toArray(new String[]{})[0];
                    //这里会抛出正在编辑的异常
                    throwBeingEditDocument(existsKey.substring(existsKey.lastIndexOf("-")));
                } else if (remove) {
                    RedisUtil.setOutTime(key, getExpirationTime());
                    return;
                }
            }
            Map<String, Object> params = new HashMap<>();
            params.put("userId", userId);
            params.put("fileUuid", fileUuid);
            params.put("uniqueKey", IdUtil.randomUUID());
            RedisUtil.set(key, params);
            RedisUtil.setOutTime(key, getExpirationTime());
        }
    }
            Map<String, Object> params = new HashMap<>();
            params.put("userId", userId);
            params.put("fileUuid", fileUuid);
            params.put("uniqueKey", IdUtil.randomUUID());
            RedisUtil.set(key, params);
            RedisUtil.setOutTime(key, getExpirationTime());
        }
    }
    /**
     * 正在编辑文档错误抛出
     *
     * @param userId
     * @throws BaseException
     */
    private void throwBeingEditDocument(Object userId) throws BaseException {
        FieldSetEntity userInfo = BaseUtil.getSingleInfoByCache("用户缓存", new String[]{String.valueOf(userId)});
        String user_name;
        if (userInfo != null && !StringUtils.isEmpty(userInfo.getString("user_name"))) {
            user_name = userInfo.getString("user_name");
        } else {
            user_name = "未知用户";
        }
        throw new BaseException(FileCode.DOCUMENT_BEING_EDITED.getValue(), FileCode.DOCUMENT_BEING_EDITED.getText().replace("{{userName}}", user_name));
    }
    /**
     * 正在编辑文档错误抛出
     *
     * @param userId
     * @throws BaseException
     */
    private void throwBeingEditDocument(Object userId) throws BaseException {
        FieldSetEntity userInfo = BaseUtil.getSingleInfoByCache("用户缓存", new String[]{String.valueOf(userId)});
        String user_name;
        if (userInfo != null && !StringUtils.isEmpty(userInfo.getString("user_name"))) {
            user_name = userInfo.getString("user_name");
        } else {
            user_name = "未知用户";
        }
        throw new BaseException(FileCode.DOCUMENT_BEING_EDITED.getValue(), FileCode.DOCUMENT_BEING_EDITED.getText().replace("{{userName}}", user_name));
    }
}
src/main/java/com/product/file/util/AsposeUtil.java
@@ -23,362 +23,371 @@
public class AsposeUtil {
    //是否初始了license
    private static boolean isInitLicense=false;
    /**
     * 获取license
     * @return
     */
    public static boolean getLicense(int type)throws BaseException {
        //已经初始过,不再初始
        if(isInitLicense) {
            return true;
        }
        boolean result = true;
        InputStream is = null;
        try {
            is =  AsposeUtil.class.getClassLoader().getResourceAsStream("license.xml");
            com.aspose.cells.License excel = new com.aspose.cells.License();
            excel.setLicense(is);
            is =  AsposeUtil.class.getClassLoader().getResourceAsStream("license.xml");
            com.aspose.words.License word = new com.aspose.words.License();
            word.setLicense(is);
            is =  AsposeUtil.class.getClassLoader().getResourceAsStream("license.xml");
            com.aspose.slides.License ppt = new com.aspose.slides.License();
            ppt.setLicense(is);
    private static boolean isInitLicense = false;
            isInitLicense=true;
        } catch (Exception e) {
            result=false;
            throw new BaseException(FileCode.DOC_CONVERT_FALL,e);
        }finally{
            if(is!=null) {
    /**
     * 获取license
     *
     * @return
     */
    public static boolean getLicense(int type) throws BaseException {
        //已经初始过,不再初始
        if (isInitLicense) {
            return true;
        }
        boolean result = true;
        InputStream is = null;
        try {
            is = AsposeUtil.class.getClassLoader().getResourceAsStream("license.xml");
            com.aspose.cells.License excel = new com.aspose.cells.License();
            excel.setLicense(is);
            is = AsposeUtil.class.getClassLoader().getResourceAsStream("license.xml");
            com.aspose.words.License word = new com.aspose.words.License();
            word.setLicense(is);
            is = AsposeUtil.class.getClassLoader().getResourceAsStream("license.xml");
            com.aspose.slides.License ppt = new com.aspose.slides.License();
            ppt.setLicense(is);
            isInitLicense = true;
        } catch (Exception e) {
            result = false;
            throw new BaseException(FileCode.DOC_CONVERT_FALL, e);
        } finally {
            if (is != null) {
                try {
                    is.close();
                }catch(IOException e) {
                } catch (IOException e) {
                    throw new BaseException(e);
                }
            }
        }
        return result;
    }
    /**
     *
     * @param officePath
     * @param OutPutPath
     * @throws BaseException
     */
    public static void Excel2Pdf(String officePath,String OutPutPath)throws BaseException {
        // 验证License
        if (!getLicense(1)) {
            return;
        }
        FileOutputStream fileOS=null;
        try {
            File file = new File(OutPutPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            Workbook wb = new Workbook(officePath);// 原始excel路径
            fileOS = new FileOutputStream(OutPutPath);
            //wb.save(fileOS, com.aspose.cells.SaveFormat.PDF);
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            pdfSaveOptions.setAllColumnsInOnePagePerSheet(true);
            wb.save(fileOS, pdfSaveOptions);
        } catch (Exception e) {
            throw new BaseException(FileCode.DOC_CONVERT_FALL,e);
        }finally{
            if(fileOS!=null) {
                try {
                    fileOS.flush();
                    fileOS.close();
                }catch(IOException e) {
                    throw new BaseException(e);
                }
            }
        }
    }
    public static void Excel2Html(String officePath,String OutPutPath)throws BaseException {
        // 验证License
        if (!getLicense(1)) {
            return;
        }
        FileOutputStream fileOS=null;
        try {
            File file = new File(OutPutPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            Workbook wb = new Workbook(officePath);// 原始excel路径
            WorksheetCollection sheets=wb.getWorksheets();
            System.out.println("sheet个数:"+sheets.getCount());
            for(int i=0;i<sheets.getCount();i++) {
                setAutoWithHeight(sheets.get(i));
            }
            fileOS = new FileOutputStream(OutPutPath);
            wb.save(fileOS, SaveFormat.HTML);
        } catch (Exception e) {
            throw new BaseException(FileCode.DOC_CONVERT_FALL,e);
        }finally{
            if(fileOS!=null) {
                try {
                    fileOS.flush();
                    fileOS.close();
                }catch(IOException e) {
                    throw new BaseException(e);
                }
            }
        }
    }
    /**
     * 设置单元格的自动适宽、高
     * @param sheet
     * @throws Exception
     */
    public static void setAutoWithHeight(Worksheet sheet)throws Exception
    {
        Cells cells =sheet.getCells();
        int columnCount = cells.getMaxColumn();  //获取表页的最大列数
        int rowCount = cells.getMaxRow();        //获取表页的最大行数
        if(columnCount<0 ||rowCount<0 )return ;
        for (int col = 0; col < columnCount; col++)
        {
            sheet.autoFitColumn(col, 0, rowCount);
        }
        for (int row = 0; row < rowCount; row++)
        {
            sheet.autoFitRow(row, 0, columnCount);
        }
    }
    /**
     *
     * @param officePath
     * @param OutPutPath
     * @throws BaseException
     */
    public static void Word2Pdf(String officePath,String OutPutPath) throws BaseException {
        // 验证License
        if (!getLicense(2)) {
            return;
        }
        FileOutputStream fileOS=null;
        try {
            File file = new File(OutPutPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            Document doc = new Document(officePath);// 原始word路径
            fileOS = new FileOutputStream(OutPutPath);
            doc.save(fileOS, com.aspose.words.SaveFormat.PDF);
        } catch (Exception e) {
            throw new BaseException(FileCode.DOC_CONVERT_FALL,e);
        }finally{
            if(fileOS!=null) {
                try {
                    fileOS.flush();
                    fileOS.close();
                }catch(IOException e) {
                    throw new BaseException(e);
                }
            }
        }
    }
    /**
     *
     * @param officePath
     * @param OutPutPath
     * @throws BaseException
     */
    public static void PPT2Pdf(String officePath,String OutPutPath)throws BaseException {
        // 验证License
        if (!getLicense(3)) {
            return;
        }
        FileOutputStream fileOS=null;
        try {
            File PathFile = new File(OutPutPath);
            if (!PathFile.exists()) {
                PathFile.mkdirs();
            }
            InputStream slides = new FileInputStream(officePath);// 原始ppt路径
            Presentation pres = new Presentation(slides);
            fileOS = new FileOutputStream(OutPutPath);
            pres.save(fileOS, com.aspose.slides.SaveFormat.Pdf);
        } catch (Exception e) {
            throw new BaseException(FileCode.DOC_CONVERT_FALL,e);
        }finally{
            if(fileOS!=null) {
                try {
                    fileOS.flush();
                    fileOS.close();
                }catch(IOException e) {
                    throw new BaseException(e);
                }
            }
        }
    }
    /**
     * 文档转换
     * @param officePath
     * @param outFile
     * @return
     * @throws BaseException
     */
    public static String OfficeToPdf(String officePath,String outFile,String officeType )throws BaseException {
        return result;
    }
        SpringMVCContextHolder.getSystemLogger().info("The file of office type:"+officePath);
        if("pdf".equals(officeType)) {
            return outFile;
        }
        File file = new File(officePath);
        //判断当前office文件是否已经转为PDF,如果已转为PDF就不需要再次转换。
        if (file.exists()) {
            if(officeType.equals("doc")||officeType.equals("docx")){
                Word2Pdf(officePath,outFile);
            }else if(officeType.equals("xls")||officeType.equals("xlsx")){
    /**
     * @param officePath
     * @param OutPutPath
     * @throws BaseException
     */
    public static void Excel2Pdf(String officePath, String OutPutPath) throws BaseException {
        // 验证License
        if (!getLicense(1)) {
            return;
        }
        FileOutputStream fileOS = null;
        try {
            File file = new File(OutPutPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            Workbook wb = new Workbook(officePath);// 原始excel路径
            fileOS = new FileOutputStream(OutPutPath);
            //wb.save(fileOS, com.aspose.cells.SaveFormat.PDF);
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            pdfSaveOptions.setAllColumnsInOnePagePerSheet(true);
            wb.save(fileOS, pdfSaveOptions);
        } catch (Exception e) {
            throw new BaseException(FileCode.DOC_CONVERT_FALL, e);
        } finally {
            if (fileOS != null) {
                try {
                    fileOS.flush();
                    fileOS.close();
                } catch (IOException e) {
                    throw new BaseException(e);
                }
            }
        }
    }
    public static void Excel2Html(String officePath, String OutPutPath) throws BaseException {
        // 验证License
        if (!getLicense(1)) {
            return;
        }
        FileOutputStream fileOS = null;
        try {
            File file = new File(OutPutPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            Workbook wb = new Workbook(officePath);// 原始excel路径
            WorksheetCollection sheets = wb.getWorksheets();
            System.out.println("sheet个数:" + sheets.getCount());
            for (int i = 0; i < sheets.getCount(); i++) {
                setAutoWithHeight(sheets.get(i));
            }
            fileOS = new FileOutputStream(OutPutPath);
            wb.save(fileOS, SaveFormat.HTML);
        } catch (Exception e) {
            throw new BaseException(FileCode.DOC_CONVERT_FALL, e);
        } finally {
            if (fileOS != null) {
                try {
                    fileOS.flush();
                    fileOS.close();
                } catch (IOException e) {
                    throw new BaseException(e);
                }
            }
        }
    }
    /**
     * 设置单元格的自动适宽、高
     *
     * @param sheet
     * @throws Exception
     */
    public static void setAutoWithHeight(Worksheet sheet) throws Exception {
        Cells cells = sheet.getCells();
        int columnCount = cells.getMaxColumn();  //获取表页的最大列数
        int rowCount = cells.getMaxRow();        //获取表页的最大行数
        if (columnCount < 0 || rowCount < 0) return;
        for (int col = 0; col < columnCount; col++) {
            sheet.autoFitColumn(col, 0, rowCount);
        }
        for (int row = 0; row < rowCount; row++) {
            sheet.autoFitRow(row, 0, columnCount);
        }
    }
    /**
     * @param officePath
     * @param OutPutPath
     * @throws BaseException
     */
    public static void Word2Pdf(String officePath, String OutPutPath) throws BaseException {
        // 验证License
        if (!getLicense(2)) {
            return;
        }
        FileOutputStream fileOS = null;
        try {
            File file = new File(OutPutPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            Document doc = new Document(officePath);// 原始word路径
            fileOS = new FileOutputStream(OutPutPath);
            doc.save(fileOS, com.aspose.words.SaveFormat.PDF);
        } catch (Exception e) {
            throw new BaseException(FileCode.DOC_CONVERT_FALL, e);
        } finally {
            if (fileOS != null) {
                try {
                    fileOS.flush();
                    fileOS.close();
                } catch (IOException e) {
                    throw new BaseException(e);
                }
            }
        }
    }
    /**
     * @param officePath
     * @param OutPutPath
     * @throws BaseException
     */
    public static void PPT2Pdf(String officePath, String OutPutPath) throws BaseException {
        // 验证License
        if (!getLicense(3)) {
            return;
        }
        FileOutputStream fileOS = null;
        try {
            File PathFile = new File(OutPutPath);
            if (!PathFile.exists()) {
                PathFile.mkdirs();
            }
            InputStream slides = new FileInputStream(officePath);// 原始ppt路径
            Presentation pres = new Presentation(slides);
            fileOS = new FileOutputStream(OutPutPath);
            pres.save(fileOS, com.aspose.slides.SaveFormat.Pdf);
        } catch (Exception e) {
            throw new BaseException(FileCode.DOC_CONVERT_FALL, e);
        } finally {
            if (fileOS != null) {
                try {
                    fileOS.flush();
                    fileOS.close();
                } catch (IOException e) {
                    throw new BaseException(e);
                }
            }
        }
    }
    /**
     * 文档转换
     *
     * @param officePath
     * @param outFile
     * @return
     * @throws BaseException
     */
    public static String OfficeToPdf(String officePath, String outFile, String officeType) throws BaseException {
        SpringMVCContextHolder.getSystemLogger().info("The file of office type:" + officePath);
        if ("pdf".equals(officeType)) {
            return outFile;
        }
        File file = new File(officePath);
        //判断当前office文件是否已经转为PDF,如果已转为PDF就不需要再次转换。
        if (file.exists()) {
            if (officeType.equals("doc") || officeType.equals("docx")) {
                Word2Pdf(officePath, outFile);
            } else if (officeType.equals("xls") || officeType.equals("xlsx")) {
//                Excel2Pdf(officePath,outFile);
                Excel2Html(officePath,outFile);
            }else if(officeType.equals("ppt")||officeType.equals("pptx")){
                PPT2Pdf(officePath,outFile);
            }else{
                throw new BaseException(FileCode.DOC_CONVERT_NOT_SUPPORT_FILE_FALL);
            }
        } else {
            throw new BaseException(FileCode.DOC_CONVERT_FILE_NOT_EXIST_FALL);
        }
        return outFile;
    }
    /**
     * 文档转换
     * @param officePath
     * @return
     */
    public static String OfficeToPdf(String officePath) {
                Excel2Html(officePath, outFile);
            } else if (officeType.equals("ppt") || officeType.equals("pptx")) {
                PPT2Pdf(officePath, outFile);
            } else {
                throw new BaseException(FileCode.DOC_CONVERT_NOT_SUPPORT_FILE_FALL);
            }
        } else {
            throw new BaseException(FileCode.DOC_CONVERT_FILE_NOT_EXIST_FALL);
        }
        return outFile;
    }
        String[] split = officePath.split("⌒");
        int lastIndex = split[0].lastIndexOf(".");
        int lastNameIndex = split[0].lastIndexOf("/");
    /**
     * 文档转换
     *
     * @param officePath
     * @return
     */
    public static String OfficeToPdf(String officePath) {
        String officeType = split[0].substring(lastIndex+1);
        String officeName = split[0].substring(lastNameIndex+1,lastIndex)+".pdf";
        String OutPutPath = split[0].substring(0,lastNameIndex+1)+"office/";
        System.out.println("输出目录:"+OutPutPath);
        File file = new File(split[0]);
        File pdfFile = new File(OutPutPath+officeName);
        //判断当前office文件是否已经转为PDF,如果已转为PDF就不需要再次转换。
        if(pdfFile.exists()){
            return OutPutPath+officeName;
        }
        String[] split = officePath.split("⌒");
        int lastIndex = split[0].lastIndexOf(".");
        int lastNameIndex = split[0].lastIndexOf("/");
        if (file.exists()) {
        String officeType = split[0].substring(lastIndex + 1);
        String officeName = split[0].substring(lastNameIndex + 1, lastIndex) + ".pdf";
        String OutPutPath = split[0].substring(0, lastNameIndex + 1) + "office/";
        System.out.println("输出目录:" + OutPutPath);
        File file = new File(split[0]);
        File pdfFile = new File(OutPutPath + officeName);
        //判断当前office文件是否已经转为PDF,如果已转为PDF就不需要再次转换。
        if (pdfFile.exists()) {
            return OutPutPath + officeName;
        }
            double bytes = file.length();
            double kilobytes = (bytes / 1024);
            double megabytes = (kilobytes / 1024);
        if (file.exists()) {
            DecimalFormat df = new DecimalFormat("0.00");
            df.setRoundingMode(RoundingMode.HALF_UP);
            String MB = df.format(megabytes);
            Double Size = Double.parseDouble(MB);
            if(Size>10){
                return Size+"MB";
            }
            //"doc", "docx", "xls","xlsx", "ppt", "pptx"
            try {
                if(officeType.equals("doc")||officeType.equals("docx")){
                    Word2Pdf(split[0],OutPutPath+"/"+officeName);
                }else if(officeType.equals("xls")||officeType.equals("xlsx")){
                    Excel2Pdf(split[0],OutPutPath+"/"+officeName);
                }else if(officeType.equals("ppt")||officeType.equals("pptx")){
                    PPT2Pdf(split[0],OutPutPath+"/"+officeName);
                }else{
                    System.out.println("无法识别该文件!");
                    return "Error";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            return "NotExists";
        }
        return OutPutPath+officeName;
    }
    /**
     * word文档的合并
     * @param targetWordFile
     * @param sourceWordFile
     * @return
     * @throws Exception
     */
    public static File mergeWord(String targetWordFile,String sourceWordFile ) throws BaseException{
        File target=new File(targetWordFile);
        File source=new File(sourceWordFile);
        return mergeWord(target,source);
    }
    /**
     * word文档的合并
     * @param targetWordFile
     * @param sourceWordFile
     * @return
     * @throws Exception
     */
    public static File mergeWord(File target,File source ) throws BaseException{
        if(!target.exists() && !source.exists()) {
            return null;
        }else if(!source.exists() && target.exists()) {
            return target;
        }else if(source.exists() && !target.exists()) {
            return source;
        }
        // 验证License
        if (!getLicense(2)) {
            return null;
        }
        FileInputStream tin=null;
        FileInputStream sin=null;
        FileOutputStream out=null;
        String temp=target.getParent()+File.separator+"mergeTemp";
        File temp_target=new File(temp+File.separator+target.getName());
        try {
            tin=new FileInputStream(target);
            sin=new FileInputStream(source);
            Document targetDoc = new Document(tin);
            Document sourceDoc = new Document(sin);
            targetDoc.appendDocument(sourceDoc, ImportFormatMode.KEEP_SOURCE_FORMATTING);
            File dir=new File(temp);
            if(!dir.exists()) {
                if(dir.mkdirs()) {
                    if(temp_target.createNewFile()) {
                        out=new FileOutputStream(temp_target);
                        targetDoc.save(out, SaveFormat.DOCX);
                    }
                }
            }
        }catch(Exception e) {
            throw new BaseException(FileCode.DOC_MERGE_FALL,e);
        }
        finally{
            try {
                if(tin!=null) {
            double bytes = file.length();
            double kilobytes = (bytes / 1024);
            double megabytes = (kilobytes / 1024);
            DecimalFormat df = new DecimalFormat("0.00");
            df.setRoundingMode(RoundingMode.HALF_UP);
            String MB = df.format(megabytes);
            Double Size = Double.parseDouble(MB);
            if (Size > 10) {
                return Size + "MB";
            }
            //"doc", "docx", "xls","xlsx", "ppt", "pptx"
            try {
                if (officeType.equals("doc") || officeType.equals("docx")) {
                    Word2Pdf(split[0], OutPutPath + "/" + officeName);
                } else if (officeType.equals("xls") || officeType.equals("xlsx")) {
                    Excel2Pdf(split[0], OutPutPath + "/" + officeName);
                } else if (officeType.equals("ppt") || officeType.equals("pptx")) {
                    PPT2Pdf(split[0], OutPutPath + "/" + officeName);
                } else {
                    System.out.println("无法识别该文件!");
                    return "Error";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            return "NotExists";
        }
        return OutPutPath + officeName;
    }
    /**
     * word文档的合并
     *
     * @param targetWordFile
     * @param sourceWordFile
     * @return
     * @throws Exception
     */
    public static File mergeWord(String targetWordFile, String sourceWordFile) throws BaseException {
        File target = new File(targetWordFile);
        File source = new File(sourceWordFile);
        return mergeWord(target, source);
    }
    public static void main(String args[]) {
        String file = "E:/work/沄崃/FE6.6产品报价工具-新 - 副本.xlsx";
        AsposeUtil.OfficeToPdf(file);
    }
    /**
     * word文档的合并
     *
     * @param targetWordFile
     * @param sourceWordFile
     * @return
     * @throws Exception
     */
    public static File mergeWord(File target, File source) throws BaseException {
        if (!target.exists() && !source.exists()) {
            return null;
        } else if (!source.exists() && target.exists()) {
            return target;
        } else if (source.exists() && !target.exists()) {
            return source;
        }
        // 验证License
        if (!getLicense(2)) {
            return null;
        }
        FileInputStream tin = null;
        FileInputStream sin = null;
        FileOutputStream out = null;
        String temp = target.getParent() + File.separator + "mergeTemp";
        File temp_target = new File(temp + File.separator + target.getName());
        try {
            tin = new FileInputStream(target);
            sin = new FileInputStream(source);
            Document targetDoc = new Document(tin);
            Document sourceDoc = new Document(sin);
            targetDoc.appendDocument(sourceDoc, ImportFormatMode.KEEP_SOURCE_FORMATTING);
            File dir = new File(temp);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            if (temp_target.createNewFile()) {
                out = new FileOutputStream(temp_target);
                targetDoc.save(out, SaveFormat.DOCX);
            }
        } catch (Exception e) {
            throw new BaseException(FileCode.DOC_MERGE_FALL, e);
        } finally {
            try {
                if (tin != null) {
                    tin.close();
                }
                if(sin!=null) {
                    sin.close();
                if (sin != null) {
                    sin.close();
                }
                if(out!=null) {
                if (out != null) {
                    out.flush();
                    out.close();
                    out.close();
                }
            }catch(IOException e) {
                throw new BaseException(FileCode.DOC_MERGE_FALL,e);
            } catch (IOException e) {
                throw new BaseException(FileCode.DOC_MERGE_FALL, e);
            }
        }
        return temp_target;
    }
    public static void main(String args[]) {
        String file="E:/work/沄崃/FE6.6产品报价工具-新 - 副本.xlsx";
        AsposeUtil.OfficeToPdf(file);
    }
        return temp_target;
    }
}