规则的导入、导出、复制功能

导出功能

@Autowired
private AssetsMapper assetsMapper;
@Autowired
private AssetsVersionMapper assetsVersionMapper;
@Autowired
private ProjectMapper projectMapper;
@Autowired
private PermissionMapper permissionMapper;

@Value("${rules.export-dir}")
private String exportDir;

@Override
public void rulesExport(String uuid, HttpServletResponse response, HttpServletRequest request) {
    List<Assets> assetsList = new ArrayList<>();
    List<AssetsVersion> assetsVersionList = new ArrayList<>();
    Assets assets = assetsMapper.selectByUuid(uuid);
    facts(uuid, assetsList,assetsVersionList);
    exportRule(assets, assetsList, assetsVersionList, response, request);
}

/**
 * @Author: mahongfei
 * @description: 获取fact对象
 */
public void facts (String uuid, List<Assets> assetsList, List<AssetsVersion> assetsVersionList) {
    Assets assets = assetsMapper.selectByUuid(uuid);
    AssetsVersion assetsVersion = assetsVersionMapper.selectAssetsVersionByAssetUuid(uuid, assets.getNowVersion());
    assetsVersionList.add(assetsVersion);
    List<Assets> assetsList1 = new ArrayList<>();
    if (assets != null && assets.getType() != null) {
        Set<Fact> facts = new HashSet<>();
        Set<Fact> factSet = new HashSet<>();
        if (assets.getType().equals("scorecard")) {
            factSet = new ScorecardParser(assets.getContent()).getDrl().getImports();
            facts = new ScorecardParser(assets.getContent()).getDrl().getExportRules();
        } else if (assets.getType().equals("guidedrule")) {
            factSet = new GuidedRuleParser(assets.getContent()).getDrl().getImports();
            facts = new GuidedRuleParser(assets.getContent()).getDrl().getExportRules();
        } else if (assets.getType().equals("ruleflow")) {
            if (assets.getContent() == null) {
                return;
            }
            factSet = new FlowParser(assets.getContent()).parse().getImports();
            facts = new FlowParser(assets.getContent()).parse().getExportRules();
        } else if (assets.getType().equals("ruletable")) {
            factSet = new RuleTableParser(assets.getContent()).getDrl().getImports();
            facts = new RuleTableParser(assets.getContent()).getDrl().getExportRules();
        } else if (assets.getType().equals("ruletree")) {
            factSet = new RuleTreeParser(assets.getContent()).getDrl().getImports();
            facts = new RuleTreeParser(assets.getContent()).getDrl().getExportRules();
        }

        if (!factSet.isEmpty()) {
            for (Fact fact : factSet) {
                Assets assets1 = assetsMapper.selectByUuid(fact.getUuid());
                AssetsVersion assetsVersion1 = assetsVersionMapper.selectAssetsVersionByAssetUuid(fact.getUuid(), assets.getNowVersion());
                assetsList.add(assets1);
                assetsVersionList.add(assetsVersion1);
            }
        }

        if (!facts.isEmpty()) {
            for (Fact fact :  facts) {
                Assets assets1 = assetsMapper.selectByUuid(fact.getUuid());
                AssetsVersion assetsVersion1 = assetsVersionMapper.selectAssetsVersionByAssetUuid(assets1.getUuid(), assets.getNowVersion());
                assetsVersionList.add(assetsVersion1);
                if (!assets1.getType().equals("constant")) {
                    assetsList1.add(assets1);
                }
                if (!assetsList.contains(assets1)) {
                    assetsList.add(assets1);
                }
            }
        }

        if (!assetsList1.isEmpty()) {
            for (Assets assets1 : assetsList1) {
                facts(assets1.getUuid(), assetsList, assetsVersionList);
            }
        }
    } else {
        throw new IllegalArgumentException("该规则不存在");
    }
}

/**
 * @Author: mahongfei
 * @description: 规则导出
 */
public void exportRule(Assets assets,
                       List<Assets> assetsList,
                       List<AssetsVersion> assetsVersionList,
                       HttpServletResponse response,
                       HttpServletRequest request) {
    String[] dirs = new String[] {exportDir + "rules", exportDir + "facts", exportDir + "assetsversion"};
    for (int i = 0; i < dirs.length; i++) {
        if (dirs[i].contains("facts")) {
            for (Assets assets1 : assetsList) {
                String name = assets1.getName();
                FileWrite(dirs[i], assets1, name);
            }
        } else if (dirs[i].contains("assetsversion")) {
            for (AssetsVersion assetsVersion : assetsVersionList) {
                String name = assetsVersion.getAssetUuid();
                FileWrite(dirs[i], assetsVersion, name);
            }
        } else {
            String name = assets.getName();
            FileWrite(dirs[i], assets, name);
        }
    }

    response.reset();
    response.setCharacterEncoding("utf-8");
    response.setContentType("multipart/form-data");
    //设置压缩包的名字
    //解决不同浏览器压缩包名字含有中文时乱码的问题
    String downloadName = assets.getName() + ".zip";
    //返回客户端浏览器的版本号、类型
    String agent = request.getHeader("USER-AGENT");
    try {
        //针对IE或者以IE为内核的浏览器:
        if (agent.contains("MSIE")||agent.contains("Trident")) {
            downloadName = java.net.URLEncoder.encode(downloadName, "UTF-8");
        } else {
            //非IE浏览器的处理:
            downloadName = new String(downloadName.getBytes("UTF-8"),"ISO-8859-1");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    response.setHeader("Content-Disposition", "attachment;fileName=\"" + downloadName + "\"");
    //设置压缩流:直接写入response,实现边压缩边下载
    ZipOutputStream zipos = null;
    try {
        zipos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));

        zipos.setMethod(ZipOutputStream.DEFLATED); //设置压缩方法
    } catch (Exception e) {
        e.printStackTrace();
    }
    //循环将文件写入压缩流
    DataOutputStream os = null;
    for (int j = 0; j < dirs.length; j++) {
        String zipName = null;
        String dir = dirs[j];
        if (!dir.isEmpty()) {
            if (dirs[j].contains("rules")) {
             zipName = "rules/";
             os = FileZip(dir, zipos, os, zipName);
            } else if (dirs[j].contains("fact")) {
                zipName = "facts/";
                os = FileZip(dir, zipos, os, zipName);
            } else if (dirs[j].contains("assetsversion")) {
                zipName = "assetsversion/";
                os = FileZip(dir, zipos, os, zipName);
            }
        }
    }
    //关闭流
    try {
        os.close();
        zipos.close();
    } catch (IOException e) {
        throw new IllegalArgumentException("关闭流失败");
    }

    String newDir2;
    for (int a = 0 ; a<dirs.length; a++) {
        newDir2 = dirs[a];
        boolean success = deleteDir(new File(newDir2));
        if (success) {
            System.out.println("Successfully deleted populated directory: " + newDir2);
        } else {
            System.out.println("Failed to delete populated directory: " + newDir2);
        }
    }
    doDeleteEmptyDir(exportDir);
}
/**
 *@Author: mahongfei
 *@description: 将uuid查询到的内容写入文件中
 */
public void FileWrite(String dir,Object object, String name) {
    try {
        String as = JSON.toJSONString(object);
        File f = new File(dir, name +".txt");
        f.getParentFile().mkdirs();
        System.out.println(f);
        FileWriter fw = null;
        if(!f.exists()){
            f.createNewFile();
            fw = new FileWriter(f);
            BufferedWriter out = new BufferedWriter(fw);
            out.write(as);
            out.close();
        }
    } catch (Exception e) {
        throw new IllegalArgumentException("数据库内容写入文件失败");
    }
}

/**
 *@Author: mahongfei
 *@description: 将内容进行打包
 */
public DataOutputStream FileZip(String dir, ZipOutputStream zipos, DataOutputStream os, String zipName) {
    FileInputStream fis = null;
    BufferedInputStream bis = null;
    String modipath = dir;
    File file = new File(modipath);
    if(file.exists()){
        try {
            File sourceFile = new File(dir);
            //添加ZipEntry,并ZipEntry中写入文件流
            //这里,加上i是防止要下载的文件有重名的导致下载失败
            File[] sourceFiles = sourceFile.listFiles();
            os = new DataOutputStream(zipos);
            byte[] bufs = new byte[1024*10];
            for(int i=0;i<sourceFiles.length;i++){
                zipos.putNextEntry(new ZipEntry(zipName + sourceFiles[i].getName()));
                InputStream is = new FileInputStream(sourceFiles[i]);
                fis = new FileInputStream(sourceFiles[i]);
                bis = new BufferedInputStream(fis, 1024*10);
                int read = 0;
                while((read = bis.read(bufs, 0, 1024*10)) != -1){
                    zipos.write(bufs,0,read);
                }
                is.close();
                fis.close();
                bis.close();
                zipos.closeEntry();
            }
             os.flush();
        } catch (IOException e) {
            throw new IllegalArgumentException("打包失败");
        }
    }
    return os;
}

/**
*@Author: mahongfei
*@description: 删除写入内容的源文件夹
*/
private static void doDeleteEmptyDir(String dir) {
boolean success = (new File(dir)).delete();
if (success) {
System.out.println("Successfully deleted empty directory: " + dir);
} else {
System.out.println("Failed to delete empty directory: " + dir);
}
}

/**
 *@Author: mahongfei
 *@description: 删除源文件下的目录及文件
 */
private static boolean deleteDir(File dir) {
    if (dir.isDirectory()) {
        String[] children = dir.list();
        //递归删除目录中的子目录下
        for (int i=0; i<children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
    }
    // 目录此时为空,可以删除
    return dir.delete();
}

导入功能

/**
* @Author: mahongfei
* @description: 规则导入
*/
@Override
public void rulesImport(MultipartFile zipPath, String projectUuid, Integer nowVersion, String dirParentId) {
if (zipPath == null) {
throw new IllegalArgumentException(“导入路径不能为空”);
}
if (StringUtil.isBlank(projectUuid) || nowVersion < 0) {
throw new IllegalArgumentException(“参数不能为空”);
}

     try {
         // 获取文件名
        String fileName = zipPath.getOriginalFilename();
        // 获取文件后缀
        String prefix=fileName.substring(fileName.lastIndexOf("."));
        // 用uuid作为文件名,防止生成的临时文件重复
        final File excelFile = File.createTempFile(IdUtil.UUID(), prefix);
        zipPath.transferTo(excelFile);
        // MultipartFile to File
        //程序结束时,删除临时文件
	    /*2.实例化ZpFile对象,这个对象主要有两个作用,一个是用来实例化压缩文件的输入流,
	    第二就是通过getInputStream()方法获得每个压缩实体的输入流.可以这样理解:首先
	    你要获得一个集装箱,然后再获得集装箱里面的每一个实体东西*/
        ZipFile zipFile = new ZipFile(excelFile);
        ZipInputStream zipInput = new ZipInputStream(new FileInputStream(excelFile));
        List<Assets> ruleAssetList = new ArrayList<>();
        List<Assets> factAssetsList = new ArrayList<>();
        List<Assets> ruleFacts = new ArrayList<>();
        List<AssetsVersion> assetsVersionList = new ArrayList<>();

        Account cont = new  Account();
        //cont.setUuid(SessionHolder.currentAccount().getUuid());
        cont.setUuid("20f3bc7fb3ad44eeb3cf948f238cb46b");

        /*3.声明一些要用到的对象引用*/
        ZipEntry entry = null;   //这个是压缩实体,就压缩文件中每一个压缩文件或压缩文件夹

        while((entry = zipInput.getNextEntry())!= null) {   //获取压缩文件夹中的每一个文件实体
            if (entry.getName().split("/")[0].equals("rules")) {
                BufferedReader br = new BufferedReader(new InputStreamReader(zipFile.getInputStream(entry)));
                String line;
                StringBuilder sb = new StringBuilder();
                while ((line = br.readLine()) != null) {
                    sb.append(line +"");
                }
                JSONObject json = JSONObject.parseObject(sb.toString());
                Assets assets = json .toJavaObject(Assets.class);
                ruleAssetList.add(assets);
                br.close();
            } else if (entry.getName().split("/")[0].equals("facts")) {
                BufferedReader br = new BufferedReader(new InputStreamReader(zipFile.getInputStream(entry)));
                String line;
                StringBuilder sb = new StringBuilder();
                while ((line = br.readLine()) != null) {
                    sb.append(line +"");
                }
                JSONObject json = JSONObject.parseObject(sb.toString());
                Assets assets = json .toJavaObject(Assets.class);
                factAssetsList.add(assets);
                br.close();
            } else if (entry.getName().split("/")[0].equals("assetsversion")) {
                BufferedReader br = new BufferedReader(new InputStreamReader(zipFile.getInputStream(entry)));
                String line;
                StringBuilder sb = new StringBuilder();
                while ((line = br.readLine()) != null) {
                    sb.append(line +"");
                }
                JSONObject json = JSONObject.parseObject(sb.toString());
                AssetsVersion assetsVersion = json .toJavaObject(AssetsVersion.class);
                assetsVersionList.add(assetsVersion);
                br.close();
            }
        }

        if (!factAssetsList.isEmpty()) {
            for (Assets assets : factAssetsList) {
                if (!assets.getType().equals("fact") && !assets.getType().equals("constant")) {
                    ruleFacts.add(assets);
                }
            }
        }

        if (!ruleFacts.isEmpty()) {
            for (Assets assets : ruleFacts) {
                factAssetsList.remove(assets);
            }
        }

        if (!factAssetsList .isEmpty()) {
            for (Assets a : factAssetsList) {
                String uuid = IdUtil.UUID();
                Assets as = new Assets();

            for (AssetsVersion assetsVersion : assetsVersionList) {
                if (a.getUuid().equals(assetsVersion.getAssetUuid())) {
                    if (!StringUtil.isBlank(assetsVersion.getContent())) {
                        for (Assets ruleAssets : ruleAssetList) {
                            for (AssetsVersion ruleAssetsVersion : assetsVersionList) {
                                if (ruleAssets.getUuid().equals(ruleAssetsVersion.getAssetUuid())) {
                                    if (ruleAssetsVersion.getContent() != null) {
                                        ruleAssetsVersion.setContent(ruleAssetsVersion.getContent().replace(a.getUuid(), uuid));
                                    }
                                }
                            }
                        }

                        if (!ruleFacts.isEmpty()) {
                            for (Assets ruleFact : ruleFacts) {
                                for (AssetsVersion ruleFactVersion : assetsVersionList) {
                                    if (ruleFact.getUuid().equals(ruleFactVersion.getAssetUuid())) {
                                        if (ruleFactVersion.getContent() != null) {
                                            ruleFactVersion.setContent(ruleFactVersion.getContent().replace(a.getUuid(), uuid));
                                            }
                                        }
                                    }
                            }
                        }
                    }

                    AssetsVersion assetsVersion1 = new AssetsVersion();
                    assetsVersion1.setProjectUuid(projectUuid);
                    assetsVersion1.setVersionNo(nowVersion);
                    assetsVersion1.setContent(assetsVersion.getContent());
                    assetsVersion1.setVersionDes(assetsVersion.getVersionDes());
                    assetsVersion1.setCreator(cont);
                    assetsVersion1.setAssetUuid(uuid);
                    assetsVersionMapper.insert(assetsVersion1);
                }
            }

            as.setUpdateTime(a.getUpdateTime());
            as.setName(copyName(a.getName(), projectUuid, nowVersion));
            as.setDescription(a.getDescription());
            as.setContent(a.getContent());
            as.setType(a.getType());
            as.setType(a.getType());
            as.setLocked(a.isLocked());
            as.setTag(a.getTag());
            as.setCreator(cont);
            as.setNowVersion(nowVersion);
            as.setUuid(uuid);
            as.setProjectUuid(projectUuid);
            as.getCreator();
            if (dirParentId == null) {
                as.setDirParentId("0");
            } else {
                as.setDirParentId(dirParentId);
            }
            assetsMapper.insert(as);
            projectMapper.updateFileNum(as.getProjectUuid(), 1);

            Permission p = new Permission();
            p.setUuid(IdUtil.UUID());
            p.setIdentifier(String.valueOf(as.getId()));
            p.setType(2);
            p.setAccountId(/*SessionHolder.currentAccount().getId()*/123);
            p.setPermission("a");
            permissionMapper.insert(p);
            }
        }

        if (!ruleFacts.isEmpty()) {
            for (Assets a : ruleFacts) {
                String uuid = IdUtil.UUID();
                Assets as = new Assets();

            for (AssetsVersion assetsVersion : assetsVersionList) {
                if (a.getUuid().equals(assetsVersion.getAssetUuid())) {
                    if (!StringUtil.isBlank(assetsVersion.getContent())) {
                        for (Assets ruleAssets : ruleAssetList) {
                            for (AssetsVersion ruleAssetsVersion : assetsVersionList) {
                                if (ruleAssets.getUuid().equals(ruleAssetsVersion.getAssetUuid())) {
                                    if (ruleAssetsVersion.getContent() != null) {
                                        ruleAssetsVersion.setContent(ruleAssetsVersion.getContent().replace(a.getUuid(), uuid));
                                        ruleAssetsVersion.setContent(ruleAssetsVersion.getContent().replace(a.getName(),
                                                copyName(a.getName(), projectUuid, nowVersion)));
                                    }
                                }
                            }
                        }
                    }

                    AssetsVersion assetsVersion1 = new AssetsVersion();
                    assetsVersion1.setProjectUuid(projectUuid);
                    assetsVersion1.setVersionNo(nowVersion);
                    assetsVersion1.setContent(assetsVersion.getContent());
                    assetsVersion1.setVersionDes(assetsVersion.getVersionDes());
                    assetsVersion1.setCreator(cont);
                    assetsVersion1.setAssetUuid(uuid);
                    assetsVersionMapper.insert(assetsVersion1);
                }
            }

            as.setUpdateTime(a.getUpdateTime());
            as.setName(copyName(a.getName(), projectUuid, nowVersion));
            as.setDescription(a.getDescription());
            as.setContent(a.getContent());
            as.setType(a.getType());
            as.setType(a.getType());
            as.setLocked(a.isLocked());
            as.setTag(a.getTag());
            as.setCreator(cont);
            as.setNowVersion(nowVersion);
            as.setUuid(uuid);
            as.setProjectUuid(projectUuid);
            as.getCreator();
            if (dirParentId == null) {
                as.setDirParentId("0");
            } else {
                as.setDirParentId(dirParentId);
            }
            assetsMapper.insert(as);
            projectMapper.updateFileNum(as.getProjectUuid(), 1);

            Permission p = new Permission();
            p.setUuid(IdUtil.UUID());
            p.setIdentifier(String.valueOf(as.getId()));
            p.setType(2);
            p.setAccountId(/*SessionHolder.currentAccount().getId()*/123);
            p.setPermission("a");
            permissionMapper.insert(p);
            }
        }

        if (!ruleAssetList.isEmpty()) {
            for (Assets a : ruleAssetList) {
                String uuid = IdUtil.UUID();
                Assets as = new Assets();

                for (AssetsVersion assetsVersion : assetsVersionList) {
                    if (a.getUuid().equals(assetsVersion.getAssetUuid())) {
                        AssetsVersion assetsVersion1 = new AssetsVersion();
                        assetsVersion1.setProjectUuid(projectUuid);
                        assetsVersion1.setVersionNo(nowVersion);
                        assetsVersion1.setContent(assetsVersion.getContent());
                        assetsVersion1.setVersionDes(assetsVersion.getVersionDes());
                        assetsVersion1.setCreator(cont);
                        assetsVersion1.setAssetUuid(uuid);
                        assetsVersionMapper.insert(assetsVersion1);
                }
            }
            as.setUpdateTime(a.getUpdateTime());
            as.setName(copyName(a.getName(), projectUuid, nowVersion));
            as.setDescription(a.getDescription());
            as.setContent(a.getContent());
            as.setType(a.getType());
            as.setType(a.getType());
            as.setLocked(a.isLocked());
            as.setTag(a.getTag());
            as.setCreator(cont);
            as.setNowVersion(nowVersion);
            as.setUuid(uuid);
            as.setProjectUuid(projectUuid);
            as.getCreator();
            if (dirParentId == null) {
                as.setDirParentId("0");
            } else {
                as.setDirParentId(dirParentId);
            }
            assetsMapper.insert(as);
            projectMapper.updateFileNum(as.getProjectUuid(), 1);

            Permission p = new Permission();
            p.setUuid(IdUtil.UUID());
            p.setIdentifier(String.valueOf(as.getId()));
            p.setType(2);
            p.setAccountId(/*SessionHolder.currentAccount().getId()*/123);
            p.setPermission("a");
            permissionMapper.insert(p);
            }
        }
        deleteFile(excelFile);
        zipFile.close();
        zipInput.close();
     } catch (Exception e) {
         throw new IllegalArgumentException("导入失败" + e.getLocalizedMessage());
     }
 }

/**
 * @Author: mahongfei
 * @description: 删除表文件
 */
private void deleteFile(File... files) {
    for (File file : files) {
        if (file.exists()) {
            file.delete();
        }
    }
}

/**
 * @Author: mahongfei
 * @description: 规则复制
 */
@Override
public void rulesCopy(Assets assets, String dirParentId) {
    if (assets == null || assets.getProjectUuid() == null || assets.getNowVersion() == null
            || assets.getName() == null || assets.getType() == null) {
        throw new IllegalArgumentException("需要复制的资源文件的projectUuid、name、nowVersion、type不能为空");
    }

    String newUuid = IdUtil.UUID();
    Account cont = new  Account();
    //cont.setUuid(SessionHolder.currentAccount().getUuid());
    cont.setUuid("20f3bc7fb3ad44eeb3cf948f238cb46b");
    Assets newAsset = new Assets();
    AssetsVersion assetsVersion = assetsVersionMapper.selectByAssetAndVersion(assets.getUuid(), assets.getNowVersion());
    AssetsVersion newAssetsVersion = new AssetsVersion();
    newAssetsVersion.setProjectUuid(assetsVersion.getProjectUuid());
    newAssetsVersion.setVersionNo(assetsVersion.getVersionNo());
    newAssetsVersion.setContent(assetsVersion.getContent());
    newAssetsVersion.setVersionDes(assetsVersion.getVersionDes());
    newAssetsVersion.setCreator(cont);
    newAssetsVersion.setAssetUuid(newUuid);
    assetsVersionMapper.insert(newAssetsVersion);

    newAsset.setUpdateTime(assets.getUpdateTime());
    newAsset.setName(copyName(assets.getName(), assets.getProjectUuid(), assets.getNowVersion()));
    newAsset.setDescription(assets.getDescription());
    newAsset.setContent(assets.getContent());
    newAsset.setType(assets.getType());
    newAsset.setType(assets.getType());
    newAsset.setLocked(assets.isLocked());
    newAsset.setTag(assets.getTag());
    newAsset.setCreator(cont);
    newAsset.setNowVersion(assets.getNowVersion());
    newAsset.setUuid(newUuid);
    newAsset.setProjectUuid(assets.getProjectUuid());
    newAsset.getCreator();
    if (dirParentId == null) {
        newAsset.setDirParentId("0");
    } else {
        newAsset.setDirParentId(dirParentId);
    }
    assetsMapper.insert(newAsset);
    projectMapper.updateFileNum(newAsset.getProjectUuid(), 1);

    Permission p = new Permission();
    p.setUuid(IdUtil.UUID());
    p.setIdentifier(String.valueOf(newAsset.getId()));
    p.setType(2);
    p.setAccountId(/*SessionHolder.currentAccount().getId()*/123);
    p.setPermission("a");
    permissionMapper.insert(p);
}

public String copyName(String name, String projectUuid, int nowVersion) {
    Assets assets = assetsMapper.selectAsset(name, projectUuid, nowVersion);
    if (assets != null) {
        return copyName(assets.getName() + "-副本", projectUuid, nowVersion);
    }
    return name;
}

猜你喜欢

转载自blog.csdn.net/weixin_43812065/article/details/89848512