提交 c0260653 编写于 作者: tangyaolong's avatar tangyaolong

迁移lite代码

上级 f7a43359
package cn.ibizlab.core.extensions.service;
import cn.ibizlab.core.disk.domain.MetaDynamicModel;
import cn.ibizlab.core.disk.service.impl.MetaDynamicModelServiceImpl;
import cn.ibizlab.util.cache.listener.RedisPublisher;
import cn.ibizlab.util.client.IBZWFFeignClient;
import cn.ibizlab.util.dict.StaticDict;
import cn.ibizlab.util.domain.FileItem;
import cn.ibizlab.util.enums.RedisChannelTopic;
import cn.ibizlab.util.errors.BadRequestAlertException;
import cn.ibizlab.util.helper.FileHelper;
import cn.ibizlab.util.service.FileService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import cn.ibizlab.core.disk.domain.MetaDynamicModel;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Primary;
import java.util.*;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 实体[动态模型] 自定义服务对象
......@@ -21,25 +47,267 @@ public class MetaDynamicModelExService extends MetaDynamicModelServiceImpl {
return com.baomidou.mybatisplus.core.toolkit.ReflectionKit.getSuperClassGenericType(this.getClass().getSuperclass(), 1);
}
@Value("${ibiz.filePath:/app/file/}")
private String fileRoot;
@Autowired
private FileService fileService;
@Autowired
@Lazy
private IBZWFFeignClient wfClient;
@Value("${ibiz.dynamic.publishpath:/app/file/dynamicModel/publicpath}")
private String publishPath;
@Autowired
@Lazy
RedisTemplate<String, Object> redisOperations;
@Override
public boolean create(MetaDynamicModel et) {
unzip(et);
return super.create(et);
}
/**
* [Init:初始化副本实例] 行为扩展
* 将zip解压到file目录
*
* @param et
* @return
*/
@Override
@Transactional
public MetaDynamicModel init(MetaDynamicModel et) {
return super.init(et);
private void unzip(MetaDynamicModel et) {
try {
String strModelFile = et.getModelfile();
if (StringUtils.isEmpty(strModelFile)){
throw new BadRequestAlertException("模型文件为空", "MetaDynamicModel", "unzip");
}
List<FileItem> items = JSONArray.parseArray(strModelFile, FileItem.class);
if (!ObjectUtils.isEmpty(items) && items.size() > 1) {
throw new BadRequestAlertException("单次只允许上传一个模型文件", "MetaDynamicModel", "unzip");
}
File modelFile = fileService.getFile(items.get(0).getId());
JSONObject system = null;
String unzipPath = modelFile.getParent().replace("ibizutil", "dynamicmodel");
if(".gz".equals(modelFile.getName().substring(modelFile.getName().lastIndexOf(".")))){
FileHelper.unTarGz(modelFile, unzipPath, true);
system = getSystem(unzipPath);
}else if(".zip".equals(modelFile.getName().substring(modelFile.getName().lastIndexOf(".")))){
FileHelper.unzip(modelFile, unzipPath, true);
system = getSystem(unzipPath);
}
et.setDynainstid(system.getString("getPSDynaInstId"));
et.setSystemId(system.getString("name"));
} catch (IOException e) {
throw new BadRequestAlertException("解析动态模型文件失败," + e, "MetaDynamicModel", "unzip");
}
}
/**
* [Publish:发布模型] 行为扩展
* 发布动态模型
*
* @param et
* @return
*/
@SneakyThrows
@Override
@Transactional
public MetaDynamicModel publish(MetaDynamicModel et) {
return super.publish(et);
et = get(et.getConfigid());
String systemId = et.getSystemId();
String strModelFile = et.getModelfile();
if (StringUtils.isEmpty(strModelFile) && StringUtils.isEmpty(et.getSystemId())){
throw new BadRequestAlertException(String.format("信息不足,请检查[%s]模型数据是否存在系统标识及模型文件", et.getConfigid()), "MetaDynamicModel", "unzip");
}
List<FileItem> items = JSONArray.parseArray(strModelFile, FileItem.class);
if (!ObjectUtils.isEmpty(items) && items.size() > 1){
throw new BadRequestAlertException(String.format("模型解析失败,[%s]模型文件过多", et.getConfigid()), "MetaDynamicModel", "unzip");
}
File publishFile = new File(getPublishPath() + systemId + File.separator + et.getDynainstid());
//删除发布目录中的历史文件
if (publishFile.exists()) {
FileHelper.deleteDir(publishFile.getPath());
}
File modelFile = fileService.getFile(items.get(0).getId());
String unzipPath = modelFile.getParent().replace("ibizutil", "dynamicmodel");
File unzipFile = new File(unzipPath);
//拷贝文件到发布目录
FileHelper.copyFolder(unzipFile.getPath(), publishFile.getParent());
File dynamicFile = new File(publishFile.getParent() + File.separator + unzipFile.getName());
if (dynamicFile.exists()) {
dynamicFile.renameTo(publishFile);
}
List<Map<String, Object>> workflow = searchWorkFlow(publishFile.getPath());
//部署流程
if (workflow.size() > 0) {
wfClient.deployBpmnFile(workflow);
}
//发送redis广播
Map<String, Object> message = new HashMap<>();
message.put("cacheName", "dynamicModel");
message.put("dynamicModel", et.getConfigname());
RedisPublisher redisPublisher = new RedisPublisher(redisOperations, RedisChannelTopic.REDIS_CACHE_DYNAMICMODEL_TOPIC.getChannelTopic());
redisPublisher.publisher(message);
//激活当前et.
et.setStatus(StaticDict.DynamicModelStatus.ITEM_1.getValue());
update(Wrappers.<MetaDynamicModel>lambdaUpdate().set(MetaDynamicModel::getStatus, StaticDict.DynamicModelStatus.ITEM_0.getValue()).eq(MetaDynamicModel::getSystemId, systemId));
update(et);
return et;
}
/**
* 获取处理逻辑
*
* @param systemId
* @return
*/
@SneakyThrows
public List<Map<String, Object>> getDynamicModel(String systemId) {
String pubPath = getPublishPath() + systemId;
List<Map<String, Object>> delogics = searchLogic(pubPath);
if (ObjectUtils.isEmpty(delogics)) {
throw new BadRequestAlertException(String.format("在发布目录[%s]中没有找到系统[%s]动态模型文件", pubPath, systemId), "MetaDynamicModel", "getDynamicModel");
}
return delogics;
}
/**
* 从发布目录中查询 bpmn及drl
*
* @param path
* @return
*/
public List<Map<String, Object>> searchLogic(String path) {
List<Map<String, Object>> models = new ArrayList<>();
File publish = new File(path);
if (!publish.exists()) {
throw new BadRequestAlertException(String.format("发布目录[%s]不存在", publish.getPath()), "MetaDynamicModel", "search");
}
File[] subFiles = publish.listFiles();
if (null != subFiles) {
for (File subFile : subFiles) {
if (subFile.isDirectory()) {
List<Map<String, Object>> subModels = searchLogic(subFile.getAbsolutePath());
if (!ObjectUtils.isEmpty(subModels)) {
models.addAll(subModels);
}
} else if (subFile.isFile() && (!subFile.getName().equalsIgnoreCase("PSWFVERSION.json.bpmn")) && (subFile.getName().endsWith(".bpmn") || subFile.getName().endsWith(".drl"))) {
InputStream file = null;
try {
file = new FileInputStream(subFile);
Map fileMap = new HashMap();
fileMap.put("filename", subFile.getName().toLowerCase());
fileMap.put("filepath", subFile.getPath().replace(getPublishPath(), "").toLowerCase());
fileMap.put("filecontent", IOUtils.toString(file, "UTF-8"));
models.add(fileMap);
} catch (IOException e) {
} finally {
try {
if (file != null) {
file.close();
}
} catch (IOException e) {
}
}
}
}
}
return models;
}
/**
* 从查询工作流 bpmn
*
* @param pubPath
* @return
*/
public List<Map<String, Object>> searchWorkFlow(String pubPath) {
List<Map<String, Object>> models = new ArrayList<>();
File publish = new File(pubPath);
if (!publish.exists()) {
throw new BadRequestAlertException(String.format("发布目录[%s]不存在", publish.getPath()), "MetaDynamicModel", "search");
}
File[] subFiles = publish.listFiles();
if (null != subFiles) {
for (File subFile : subFiles) {
if (subFile.isDirectory()) {
List<Map<String, Object>> subModels = searchWorkFlow(subFile.getAbsolutePath());
if (!ObjectUtils.isEmpty(subModels)) {
models.addAll(subModels);
}
} else if (subFile.isFile() && (subFile.getName().equalsIgnoreCase("PSWFVERSION.json.bpmn"))) {
InputStream file = null;
try {
file = new FileInputStream(subFile);
Map fileMap = new HashMap();
fileMap.put(subFile.getName(), IOUtils.toString(file, "UTF-8"));
models.add(fileMap);
} catch (IOException e) {
} finally {
try {
if (file != null) {
file.close();
}
} catch (IOException e) {
}
}
}
}
}
return models;
}
/**
* 获取发布目录
*
* @return
*/
public String getPublishPath() {
if (!StringUtils.isEmpty(publishPath)) {
publishPath = publishPath.replace("\\\\", File.separator).replace("\\", File.separator).replace("/", File.separator);
if (!publishPath.endsWith(File.separator)) {
publishPath = publishPath + File.separator;
}
}
return publishPath;
}
/**
* 获取系统标识
*
* @param filePath
* @return
*/
private JSONObject getSystem(String filePath) {
JSONObject system = null;
InputStream in = null;
byte[] bytes = null;
try {
File file = new File(filePath + File.separator + "PSSYSTEM.json");
if (!file.exists()) {
throw new BadRequestAlertException(String.format("无法找到动态系统模型文件[%s]", file.getPath()), "MetaDynamicModel", "getSystemId");
}
in = new FileInputStream(file);
bytes = new byte[in.available()];
in.read(bytes);
} catch (Exception e) {
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
}
}
if (bytes != null) {
String strSystem = new String(bytes);
if (!StringUtils.isEmpty(strSystem)) {
system = JSONObject.parseObject(strSystem);
}
}
if (ObjectUtils.isEmpty(system)) {
throw new BadRequestAlertException("无法获取系统标识", "MetaDynamicModel", "getSystem");
}
return system;
}
}
package cn.ibizlab.util.helper;
import lombok.extern.slf4j.Slf4j;
import org.apache.tools.tar.TarEntry;
import org.apache.tools.tar.TarInputStream;
import org.springframework.util.StringUtils;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
@Slf4j
public class FileHelper {
/**
* zip解压
* @param zipFile zip文件路径
* @param descDir 解压目录
*/
public static boolean unzip(File zipFile, String descDir , boolean exp) throws IOException
{
try {
//解决zip文件中有中文目录或者中文文件
ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));
String root = zipFile.getName().replace(".zip","/");
for(Enumeration files = zip.entries(); files.hasMoreElements();)
{
ZipEntry file = (ZipEntry)files.nextElement();
String fileName = exp?file.getName().replace(root,""):file.getName();
InputStream in = zip.getInputStream(file);
if(StringUtils.isEmpty(fileName)){
continue;
}
String outPath = (descDir+File.separator+fileName).replaceAll("\\\\", "/");
//输出文件路径信息
log.debug(outPath);
//判断路径是否存在,不存在则创建文件路径
File folder = new File(outPath.substring(0, outPath.lastIndexOf('/')));
if(!folder.exists())
{
folder.mkdirs();
}
//判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
if(new File(outPath).isDirectory())
{
continue;
}
OutputStream out = new FileOutputStream(outPath);
byte[] buf1 = new byte[1024];
int len;
while((len=in.read(buf1))>0)
{
out.write(buf1,0,len);
}
in.close();
out.close();
}
log.debug("******************解压完毕********************");
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
/**
* tar.gz解压
* @param zipFile zip文件路径
* @param descDir 解压目录
*/
public static void unTarGz(File zipFile, String descDir,boolean exp) throws IOException{
TarInputStream tarIn = null;
try{
log.debug("***************************开始解压缩tar.gz格式文件***************************");
tarIn = new TarInputStream(new GZIPInputStream(
new BufferedInputStream(new FileInputStream(zipFile))),
1024 * 2);
//创建输出目录
String root = zipFile.getName().replace(".tar.gz","/");
createDirectory(descDir,null);
TarEntry entry = null;
String fileName = null;
while((entry = tarIn.getNextEntry()) != null ){
if(entry.isDirectory()){
continue;
}else{
if(!root.equals(entry.getName().split("/")[0]) && entry.getName().contains("/")){
fileName = exp ? entry.getName().replace(entry.getName().split("/")[0],"") : entry.getName();
}else {
fileName = exp ? entry.getName().replace(root,"") : entry.getName();
}
//是文件
File tmpFile = new File(descDir + "/" + fileName);
log.debug("正在输出文件:{}",tmpFile.getPath());
//创建输出目录
createDirectory(tmpFile.getParent() + "/",null);
OutputStream out = null;
try{
out = new FileOutputStream(tmpFile);
int length = 0;
byte[] b = new byte[2048];
while((length = tarIn.read(b)) != -1){
out.write(b, 0, length);
}
}catch(IOException ex){
throw ex;
}finally{
if(out!=null){
out.close();
}
}
}
}
}catch(IOException ex){
throw new IOException("解压归档文件出现异常",ex);
} finally{
try{
if(tarIn != null){
tarIn.close();
}
}catch(IOException ex){
throw new IOException("关闭tarFile出现异常",ex);
}
log.debug("***************************解压缩tar.gz格式文件结束***************************");
}
}
/**
* 获取相同路径下最新的文件
* @param files 传入文件组
* @return
*/
public static String getLatestFilePath(File[] files) {
if (files == null) {
return null;
}
BasicFileAttributes attr = null;
Map<Long,String> compareMap = new HashMap();
Long format = 0L;
try {
for (File file : files) {
Path path = file.toPath();
attr = Files.readAttributes(path, BasicFileAttributes.class);
Instant instant = attr.creationTime().toInstant();
Long compareDate = Long.parseLong(DateTimeFormatter.ofPattern("yyyyMMddHHmmss").withZone(ZoneId.systemDefault()).format(instant));
format = compareDate > format ? compareDate : format ;
compareMap.put(format,path.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
return compareMap.get(format);
}
/**
* 构建目录
* @param outputDir
* @param subDir
*/
public static void createDirectory(String outputDir,String subDir) {
File file = new File(outputDir);
//子目录不为空
if (!(subDir == null || subDir.trim().equals(""))) {
file = new File(outputDir + "/" + subDir);
}
if (!file.exists()) {
if (!file.getParentFile().exists())
file.getParentFile().mkdirs();
file.mkdirs();
}
}
/**
* 复制文件夹
*
* @param resource 源路径
* @param target 目标路径
*/
public static void copyFolder(String resource, String target) throws Exception {
File resourceFile = new File(resource);
if (!resourceFile.exists()) {
throw new Exception("源目标路径:[" + resource + "] 不存在...");
}
File targetFile = new File(target);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
// 获取源文件夹下的文件夹或文件
File[] resourceFiles = resourceFile.listFiles();
for (File file : resourceFiles) {
File file1 = new File(targetFile.getAbsolutePath() + File.separator + resourceFile.getName());
// 复制文件
if (file.isFile()) {
log.debug(file.getPath());
// 在 目标文件夹(B) 中 新建 源文件夹(A),然后将文件复制到 A 中
// 这样 在 B 中 就存在 A
if (!file1.exists()) {
file1.mkdirs();
}
File targetFile1 = new File(file1.getAbsolutePath() + File.separator + file.getName());
copyFile(file, targetFile1);
}
// 复制文件夹
if (file.isDirectory()) {// 复制源文件夹
String dir1 = file.getAbsolutePath();
// 目的文件夹
String dir2 = file1.getAbsolutePath();
copyFolder(dir1, dir2);
}
}
}
/**
* 复制文件
*
* @param resource
* @param target
*/
public static void copyFile(File resource, File target) throws Exception {
// 文件输入流并进行缓冲
FileInputStream inputStream = new FileInputStream(resource);
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
// 文件输出流并进行缓冲
FileOutputStream outputStream = new FileOutputStream(target);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
// 缓冲数组
// 大文件 可将 1024 * 2 改大一些,但是 并不是越大就越快
byte[] bytes = new byte[1024 * 2];
int len = 0;
while ((len = inputStream.read(bytes)) != -1) {
bufferedOutputStream.write(bytes, 0, len);
}
// 刷新输出缓冲流
bufferedOutputStream.flush();
//关闭流
bufferedInputStream.close();
bufferedOutputStream.close();
inputStream.close();
outputStream.close();
}
/**
* 删除文件
*
* @param dirPath
*/
public static void deleteDir(String dirPath) {
File file = new File(dirPath);
if (file.isFile()) {
file.delete();
} else {
File[] files = file.listFiles();
if (files == null) {
file.delete();
} else {
for (int i = 0; i < files.length; i++) {
deleteDir(files[i].getAbsolutePath());
}
file.delete();
}
}
}
}
Markdown 格式
0% or
您添加了 0 到此讨论。请谨慎行事。
先完成此消息的编辑!
想要评论请 注册