管道基础大数据平台系统开发-【后端】-Server
1
13693261870
2023-03-25 eba563608c2d059a8dbbc789dd2c567f2302c088
src/main/java/com/lf/server/service/all/UploadAttachService.java
@@ -1,18 +1,22 @@
package com.lf.server.service.all;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lf.server.controller.all.BaseController;
import com.lf.server.entity.all.HttpStatus;
import com.lf.server.entity.all.ResponseMsg;
import com.lf.server.entity.all.SettingData;
import com.lf.server.entity.all.StaticData;
import com.lf.server.entity.all.*;
import com.lf.server.entity.ctrl.KeyValueEntity;
import com.lf.server.entity.data.DownloadEntity;
import com.lf.server.entity.data.MetaEntity;
import com.lf.server.entity.data.MetaFileEntity;
import com.lf.server.entity.sys.AttachEntity;
import com.lf.server.entity.sys.UserEntity;
import com.lf.server.helper.FileHelper;
import com.lf.server.helper.PathHelper;
import com.lf.server.helper.StringHelper;
import com.lf.server.helper.WebHelper;
import com.lf.server.helper.*;
import com.lf.server.mapper.all.BasicMapper;
import com.lf.server.mapper.data.DownloadMapper;
import com.lf.server.service.sys.AttachService;
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.model.FileHeader;
import net.lingala.zip4j.model.ZipParameters;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
@@ -21,8 +25,8 @@
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.lang.reflect.Field;
import java.util.*;
/**
 * 上传附件服务类
@@ -36,11 +40,21 @@
    @Autowired
    AttachService attachService;
    private static Map<String, String> attachTabs = new HashMap<>();
    @Autowired
    DownloadMapper downloadMapper;
    private static String tabs = "''";
    public final static Map<String, String> ATTACH_TABS = new HashMap<>();
    private final static Log log = LogFactory.getLog(UploadAttachService.class);
    private static final String NO_FILE = JSON.toJSONString(new ResponseMsg<String>(HttpStatus.NOT_FOUND, "文件找不到"));
    /**
     * 获取表名
     */
    public static String getTabs() {
        return tabs;
    }
    /**
     * 初始化附件表
@@ -55,13 +69,16 @@
            return;
        }
        List<String> keys = new ArrayList<>();
        for (String str : strs) {
            if (attachTabs.containsKey(str)) {
            if (ATTACH_TABS.containsKey(str)) {
                continue;
            }
            attachTabs.put(str, str.contains("bd.") ? "materiname" : "photono");
            ATTACH_TABS.put(str, str.contains("bd.") ? "materiname" : "photono");
            keys.add("'" + str + "'");
        }
        tabs = StringHelper.join(keys, ",");
    }
    /**
@@ -111,7 +128,7 @@
        entity.setName(oldName);
        entity.setTab(tab);
        entity.setGuid(md5);
        String subPath = PathHelper.getUploadPath() + File.separator + md5;
        String subPath = PathHelper.getUploadPath() + File.separator + md5 + FileHelper.getExtension(oldName);
        entity.setPath(subPath);
        entity.setSizes(sizes);
        if (ue != null) {
@@ -125,28 +142,371 @@
     * 下载文件
     */
    public void download(String guid, HttpServletResponse res) {
        download(guid, false, res);
    }
    /**
     * 下载文件
     */
    public void download(String guid, boolean inline, HttpServletResponse res) {
        try {
            if (StringHelper.isEmpty(guid)) {
                WebHelper.write2Page(res, NO_FILE);
                WebHelper.writeStr2Page(res, StaticData.NO_FILE);
                return;
            }
            AttachEntity entity = attachService.selectByGuid(guid);
            if (entity == null) {
                WebHelper.write2Page(res, NO_FILE);
                WebHelper.writeStr2Page(res, StaticData.NO_FILE);
                return;
            }
            String file = pathHelper.getConfig().getUploadPath() + File.separator + entity.getPath();
            WebHelper.download(file, entity.getName(), res);
        } catch (Exception ex) {
            try {
                String msg = JSON.toJSONString(new ResponseMsg<String>(HttpStatus.ERROR, "文件下载出错"));
                WebHelper.write2Page(res, msg);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            String filePath = pathHelper.getConfig().getUploadPath() + File.separator + entity.getPath();
            File file = new File(filePath);
            if (!file.exists() || file.isDirectory()) {
                WebHelper.writeJson2Page(res, "文件不存在");
            }
            WebHelper.download(filePath, entity.getName(), inline, res);
        } catch (Exception ex) {
            WebHelper.writeJson2Page(res, "文件下载出错");
            log.error(ex.getMessage(), ex);
        }
    }
    /**
     * 上传Excel附件
     */
    public List<KeyValueEntity> uploadXlsAnnex(UserEntity ue, List<MetaEntity> ms, List<MetaFileEntity> list, String path) {
        List<String> files = getAttachFiles(list, path);
        if (files.size() == 0) {
            return null;
        }
        List<KeyValueEntity> rs = new ArrayList<>();
        for (MetaEntity meta : ms) {
            int rows = uploadXlsAnnex(ue, meta, files);
            rs.add(new KeyValueEntity(meta.getName(), String.valueOf(rows)));
        }
        return rs;
    }
    /**
     * 获取附件文件
     */
    private List<String> getAttachFiles(List<MetaFileEntity> list, String path) {
        List<String> files = new ArrayList<>();
        for (MetaFileEntity mf : list) {
            if (mf.getName().contains(StaticData.ZIP)) {
                List<String> subs = getZipFiles(mf, path);
                if (null != subs && subs.size() > 0) {
                    files.addAll(subs);
                }
                continue;
            }
            files.add(mf.getPath());
        }
        return files;
    }
    /**
     * 获取zip中的文件
     */
    private List<String> getZipFiles(MetaFileEntity mf, String path) {
        File file = new File(mf.getPath());
        if (!file.exists() || file.isDirectory()) {
            return null;
        }
        File zipFolder = new File(pathHelper.getConfig().getTempPath() + File.separator + path + "_zip");
        if (!zipFolder.exists() || !zipFolder.isDirectory()) {
            zipFolder.mkdirs();
        }
        String subPath = zipFolder + File.separator + mf.getName().toLowerCase().replace(".zip", "");
        ZipHelper.unzip(mf.getPath(), subPath);
        List<String> files = new ArrayList<>();
        getFilesByPath(files, subPath);
        return files;
    }
    /**
     * 根据路径获取文件
     */
    private void getFilesByPath(List<String> list, String path) {
        File file = new File(path);
        if (!file.isDirectory()) {
            list.add(file.getPath());
            return;
        }
        File[] files = file.listFiles();
        if (null == files) {
            return;
        }
        for (File f : files) {
            if (f.isDirectory()) {
                getFilesByPath(list, f.getPath());
            } else {
                list.add(f.getPath());
            }
        }
    }
    /**
     * 上传Excel附件
     */
    private int uploadXlsAnnex(UserEntity ue, MetaEntity meta, List<String> files) {
        List<?> list = queryXlsData(meta);
        if (null == list || list.size() == 0) {
            return 0;
        }
        Field field = getAnnexField(list.get(0), meta);
        String folder = meta.getName().split("\\.")[0].trim().toLowerCase() + File.separator;
        int rows = 0;
        for (Object obj : list) {
            String[] names = getNames(getAnnexName(obj, field));
            if (null == names || names.length == 0) {
                continue;
            }
            for (String name : names) {
                String file = findAnnexFile(name, folder, files);
                if (null == file) {
                    continue;
                }
                rows += insertXlsAnnex(ue, meta, (BaseEntity) obj, file);
            }
        }
        return rows;
    }
    /**
     * 获取名称
     */
    private String[] getNames(String str) {
        if (StringHelper.isEmpty(str)) {
            return null;
        }
        return str.replace(";", ",").replace(",", ",").split(",");
    }
    /**
     * 查询Excel数据
     */
    private List<?> queryXlsData(MetaEntity meta) {
        String entity = meta.getTab().substring(meta.getTab().indexOf(".") + 1).replace("_", "").toLowerCase();
        BasicMapper basicMapper = ClassHelper.getBasicMapper(entity);
        if (null == basicMapper) {
            return null;
        }
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("parentid", meta.getEventid());
        List<?> list = basicMapper.selectList(wrapper);
        if (null == list || list.size() == 0) {
            return null;
        }
        if (!(list.get(0) instanceof BaseEntity)) {
            return null;
        }
        return list;
    }
    /**
     * 获取附件字段
     */
    private Field getAnnexField(Object obj, MetaEntity meta) {
        try {
            String str = ATTACH_TABS.get(meta.getTab());
            Field field = obj.getClass().getDeclaredField(str);
            field.setAccessible(true);
            return field;
        } catch (Exception ex) {
            return null;
        }
    }
    /**
     * 获取附件名称
     */
    private String getAnnexName(Object obj, Field field) {
        try {
            Object val = field.get(obj);
            return null == val ? null : val.toString().trim();
        } catch (Exception ex) {
            return null;
        }
    }
    /**
     * 查找附件文件
     */
    private String findAnnexFile(String name, String folder, List<String> files) {
        name = File.separator + name.split("\\.")[0].trim().toLowerCase();
        for (String file : files) {
            if (file.toLowerCase().contains(folder) && file.toLowerCase().contains(name)) {
                return file;
            }
        }
        for (String file : files) {
            if (file.toLowerCase().contains(name)) {
                return file;
            }
        }
        return null;
    }
    /**
     * 插入Excel附件
     */
    private int insertXlsAnnex(UserEntity ue, MetaEntity meta, BaseEntity be, String file) {
        File f = new File(file);
        if (!f.exists() || f.isDirectory()) {
            return 0;
        }
        String md5 = FileHelper.getFileMd5(file);
        AttachEntity old = attachService.selectByTabAndGuid(meta.getTab(), be.getEventid(), md5);
        if (null != old) {
            return 0;
        }
        String fileName = FileHelper.getFileName(file);
        double sizes = FileHelper.sizeToMb(f.length());
        AttachEntity ae = getAttachEntity(ue, meta.getTab(), be.getEventid(), fileName, md5, sizes);
        String targetPath = pathHelper.getConfig().getUploadPath() + File.separator + ae.getPath();
        try {
            FileUtils.copyFile(f, new File(targetPath));
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
        return attachService.insert(ae);
    }
    /**
     * 获取附件实体类
     */
    protected AttachEntity getAttachEntity(UserEntity ue, String tabName, String eventid, String fileName, String md5, double sizes) {
        AttachEntity entity = new AttachEntity();
        entity.setTab(tabName);
        entity.setTabGuid(eventid);
        entity.setName(fileName);
        entity.setGuid(md5);
        String subPath = PathHelper.getUploadPath() + File.separator + md5 + FileHelper.getExtension(fileName);
        entity.setPath(subPath);
        entity.setSizes(sizes);
        if (ue != null) {
            entity.setCreateUser(ue.getId());
        }
        return entity;
    }
    /**
     * 请求下载
     */
    public String downloadReqForGuids(UserEntity ue, List<String> guids) {
        List<AttachEntity> list = attachService.selectByGuids(guids);
        return downloadReq(ue, list);
    }
    /**
     * 请求下载
     */
    public String downloadReqForTabGuids(UserEntity ue, String tab, List<String> guids) {
        List<AttachEntity> list = attachService.selectByTabGuids(tab, guids);
        return downloadReq(ue, list);
    }
    /**
     * 请求下载
     */
    protected String downloadReq(UserEntity ue, List<AttachEntity> list) {
        if (null == list || list.isEmpty()) {
            return null;
        }
        String zipName = StringHelper.YMDHMS2_FORMAT.format(new Date()) + ".zip";
        String zipFile = pathHelper.getDownloadFullPath() + File.separator + zipName;
        ZipFile zip = Zip4jHelper.createZipFile(zipFile, null);
        ZipParameters params = Zip4jHelper.getZipParams(false);
        addZipFiles(zip, params, list);
        DownloadEntity downloadEntity = getDownloadEntity(ue, zipFile, null);
        int rows = downloadMapper.insert(downloadEntity);
        return rows > 0 ? downloadEntity.getGuid() : null;
    }
    /**
     * 添加Zip文件
     */
    private void addZipFiles(ZipFile zip, ZipParameters params, List<AttachEntity> list) {
        int i = 1;
        String uploadPath = pathHelper.getConfig().getUploadPath();
        for (AttachEntity ae : list) {
            try {
                String filePath = uploadPath + File.separator + ae.getPath();
                File file = new File(filePath);
                if (!file.exists() || file.isDirectory()) {
                    continue;
                }
                zip.addFile(file, params);
                FileHeader header = zip.getFileHeader(file.getName());
                if (null != header) {
                    zip.renameFile(header, i + "_" + ae.getName());
                }
            } catch (Exception ex) {
                log.error(ex.getMessage(), ex);
            }
        }
    }
    /**
     * 获取下载实体类
     */
    private DownloadEntity getDownloadEntity(UserEntity ue, String file, String pwd) {
        DownloadEntity de = new DownloadEntity();
        de.setName(FileHelper.getFileName(file));
        // 1-Shp文件,2-专题图,3-元数据,4-业务数据,5-管道分析,6-统计报告,7-附件
        de.setType(7);
        de.setSizes(FileHelper.sizeToMb(new File(file).length()));
        de.setDepid(ue.getDepid());
        de.setDcount(0);
        de.setPwd(pwd);
        de.setUrl(FileHelper.getRelativePath(file));
        de.setDescr("附件文件");
        de.setGuid(FileHelper.getFileMd5(file));
        de.setCreateUser(ue.getId());
        // de.setGeom(null)
        return de;
    }
}