Browse Source

任务配置-- 生成新的javacamel文件

demon 8 years ago
parent
commit
29fb351d3f

+ 34 - 1
hos-core/src/main/java/com/yihu/hos/core/file/FileUtil.java

@ -143,7 +143,10 @@ public class FileUtil {
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return output.toByteArray();
        byte[] bytes =output.toByteArray();
        input.close();
        output.close();
        return bytes;
    }
@ -314,5 +317,35 @@ public class FileUtil {
        return stringBuilder.toString();
    }
    /**
     * 读取文件内容
     * @param bytes
     * @return
     */
    public static String readFileText(byte[] bytes) {
        StringBuilder stringBuilder = new StringBuilder();
        InputStream in = null;
        BufferedReader br = null;
        try {
            in = new ByteArrayInputStream(bytes);
            br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            String line = null;
            while ((line = br.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                }
            }
        }
        return stringBuilder.toString();
    }
}

+ 24 - 2
hos-web-framework/src/main/java/com/yihu/hos/web/framework/util/GridFSUtil.java

@ -494,7 +494,6 @@ public class GridFSUtil {
        //获取mongodb连接
//        MongodbHelper mongoOrigin = new MongodbHelper(dbName);
        //创建一个容器
        File file = new File(filePath);
        MongoDatabase db = MongodbFactory.getDB(dbName);
        GridFSBucket gridFS = GridFSBuckets.create(db);
        //自定义字段
@ -516,6 +515,8 @@ public class GridFSUtil {
        finally {
            if (uploadStream != null) {
                uploadStream.close();
                File file = new File(filePath);
                file.deleteOnExit();
            }
        }
        return "";
@ -538,6 +539,27 @@ public class GridFSUtil {
        }
    }
    /**
     * 读取文件内容
     * @param dbName    数据库名
     * @param fileName  文件名
     * @return
     */
    public static String readFile(String dbName, String fileName){
        try {
            MongoDatabase db = MongodbFactory.getDB(dbName);
            GridFSBucket gridFS = GridFSBuckets.create(db);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            gridFS.downloadToStreamByName(fileName, out);
            String content = FileUtil.readFileText(out.toByteArray());
            out.close();
            return content;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 从 mongodb GridFS 下载文件
@ -555,7 +577,7 @@ public class GridFSUtil {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        gridFS.downloadToStreamByName(fileName, out);
        try {
            boolean succ = FileUtil.writeFile(savePath, out.toByteArray(), "utf-8");
            boolean succ = FileUtil.writeFile(savePath, out.toByteArray(), "UTF-8");
            if (succ) {
                return savePath;
            } else {

+ 1 - 1
src/main/java/com/yihu/hos/interceptor/AuditInterceptor.java

@ -30,7 +30,7 @@ public class AuditInterceptor extends EmptyInterceptor {
            String myCatAnnotation = "/*#mycat:schema=" + schemaName + "*/ ";
            completeSql = myCatAnnotation + sql;
        }
        logger.info("prepare " + completeSql);
//        logger.info("prepare " + completeSql);
        return super.onPrepareStatement(completeSql);
    }

+ 92 - 145
src/main/java/com/yihu/hos/system/service/FlowManager.java

@ -2,6 +2,8 @@ package com.yihu.hos.system.service;
import com.yihu.hos.common.constants.Constants;
import com.yihu.hos.config.MongoConfig;
import com.yihu.hos.core.datatype.StringUtil;
import com.yihu.hos.core.encrypt.DES;
import com.yihu.hos.core.file.FileUtil;
import com.yihu.hos.services.ServiceFlowEventService;
import com.yihu.hos.system.dao.FlowClassDao;
@ -10,18 +12,19 @@ import com.yihu.hos.system.dao.FlowTempDao;
import com.yihu.hos.system.model.SystemServiceFlow;
import com.yihu.hos.system.model.SystemServiceFlowClass;
import com.yihu.hos.system.model.SystemServiceFlowTemp;
import com.yihu.hos.system.model.bo.ServiceFlow;
import com.yihu.hos.system.service.intf.IFlowManage;
import com.yihu.hos.web.framework.model.ActionResult;
import com.yihu.hos.web.framework.model.DictItem;
import com.yihu.hos.web.framework.model.Result;
import com.yihu.hos.web.framework.util.GridFSUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.annotation.Resource;
import com.yihu.hos.config.MongoConfig;
import com.yihu.hos.core.datatype.StringUtil;
import com.yihu.hos.core.encrypt.DES;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@ -390,141 +393,6 @@ public class FlowManager implements IFlowManage {
        }
    }
    public Integer addRouteFile(Integer tempId,Integer flowId, String newCron ,Long timestamp) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        List<SystemServiceFlowTemp> flowTempRouters = flowTempDao.getFlowTemps(tempId, Constants.FLOW_TYPE_ROUTE);
        SystemServiceFlow newFlow = getFlowById(flowId);
        //route模板文件记录是否存在。不存在就返回。
        if (!flowTempRouters.isEmpty()){
            Map<String,String> params = null;
            SystemServiceFlowTemp flowTemp =flowTempRouters.get(0);
            StringBuilder basePath = new StringBuilder();;
            if (flowTemp.getPackageName()!=null){
                String packagePath[] = flowTemp.getPackageName().split("\\.");
                for (int i=0;i<packagePath.length;i++){
                    basePath.append(packagePath[i]).append("/");
                }
            }
            //新增processor记录
                String newClassName = flowTemp.getClassName()+timestamp;
                String newRoutePath =null;
                params = new HashMap<>();
                params.put("routeId", newFlow.getCode());
                params.put("type",Constants.FLOW_TYPE_ROUTE);
                params.put("filePath", flowTemp.getClassPath());
                params.put("packageName", basePath.toString());
                params.put("oldClassName", flowTemp.getClassName());
                params.put("newClassName",newClassName);//原文件名加当前时间戳
                params.put("newCron",newCron);
                HTTPResponse response  = HttpClientKit.post(genCamelUrl, params);
                if (response.getStatusCode()==200 ){
                    Map<String,Object> body = objectMapper.readValue(response.getBody(),Map.class);
                    boolean succ = (boolean) body.get("successFlg");
                    if (succ){
                        newRoutePath = body.get("message").toString();
                    }else {
                        return null;
                    }
                    System.out.println(response.getBody());
                    SystemServiceFlowClass newFlowClass = new SystemServiceFlowClass();
                    newFlowClass.setPackageName(flowTemp.getPackageName());
                    newFlowClass.setClassName(newClassName);
                    newFlowClass.setClassPath(newRoutePath);
                    newFlowClass.setFlowId(newFlow.getId());
                    newFlowClass.setType(Constants.FLOW_TYPE_ROUTE);
                    flowClassDao.saveEntity(newFlowClass);
                    newFlowClass.setIsUpdate("1");
                    sendUpdateMessage(newFlow.getCode(), newFlowClass, Constants.FLOW_OP_ADD);
                }else {
                    return null;
                }
            return newFlow.getId();
        }
        return null;
    }
    public Integer addProcessorFile(Integer flowId, String newCron,Long timestamp) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        List<SystemServiceFlowTemp> flowClassRouters = flowTempDao.getFlowTemps(flowId, Constants.FLOW_TYPE_ROUTE);
        List<SystemServiceFlowTemp> flowClassProces = flowTempDao.getFlowTemps(flowId, Constants.FLOW_TYPE_PROCESSOR);
        SystemServiceFlow oldFlow = getFlowById(flowId);
        //route模板文件记录是否存在。不存在就返回。
        if (!flowClassRouters.isEmpty()){
            Map<String,String> params = null;
            SystemServiceFlowTemp flowTemp =flowClassRouters.get(0);
            StringBuilder basePath = new StringBuilder();;
            if (flowTemp.getPackageName()!=null){
                String packagePath[] = flowTemp.getPackageName().split("\\.");
                for (int i=0;i<packagePath.length;i++){
                    basePath.append(packagePath[i]).append("/");
                }
            }
            //成功生成文件后,添加flow和flowclass记录
            //生成新流程
            SystemServiceFlow newFlow = new SystemServiceFlow();
            newFlow.setName(oldFlow.getName()+timestamp);
            newFlow.setCode(oldFlow.getCode()+timestamp);
            newFlow.setChart(oldFlow.getChart());
            newFlow.setValid(1);
            newFlow.setCreateDate(new Date());
            newFlow.setFileType(Constants.CLASS);
            flowDao.saveEntity(newFlow);
            //新增processor记录
            for (SystemServiceFlowTemp process:flowClassProces){
//                String newProcessName = process.getClassName()+timestamp;
                String newProcessPath = null;
                StringBuilder proPath =  new StringBuilder( );;
                if (process.getPackageName()!=null){
                    String packagePath[] = process.getPackageName().split("\\.");
                    for (int i=0;i<packagePath.length;i++){
                        proPath.append(packagePath[i]).append("/");
                    }
                }
                params = new HashMap<>();
                params.put("routeId", newFlow.getCode());
                params.put("type",Constants.FLOW_TYPE_PROCESSOR);
                params.put("filePath", process.getClassPath());
                params.put("packageName", proPath.toString());
                params.put("newClassName",process.getClassName());//原文件名加当前时间戳
                params.put("oldClassName", process.getClassName());
                params.put("newCron",newCron);
                HTTPResponse response = HttpClientKit.post(genCamelUrl, params);
                if (response.getStatusCode()==200 ){
                    Map<String,Object> body = objectMapper.readValue(response.getBody(),Map.class);
                    boolean succ = (boolean) body.get("successFlg");
                    if (succ){
                        newProcessPath = body.get("message").toString();
                        System.out.println(response.getBody());
                        SystemServiceFlowClass processClass = new SystemServiceFlowClass();
                        processClass.setPackageName(process.getPackageName());
                        processClass.setClassName(process.getClassName());
                        processClass.setClassPath(newProcessPath);
                        processClass.setFlowId(newFlow.getId());
                        processClass.setType(Constants.FLOW_TYPE_PROCESSOR);
                        flowClassDao.saveEntity(processClass);
                        processClass.setIsUpdate("1");
                        sendUpdateMessage(newFlow.getCode(), processClass, Constants.FLOW_OP_ADD);
                    }else {
                        return null;
                    }
                }else {
                    return null;
                }
            }
            return newFlow.getId();
        }
        return null;
    }
    /**
     * 修改任务,修改camel相关文件
     * @param flowId 流程ID
@ -584,9 +452,15 @@ public class FlowManager implements IFlowManage {
            newFlowClass.setType(Constants.FLOW_TYPE_ROUTE);
            flowClassDao.saveEntity(newFlowClass);
            newFlowClass.setIsUpdate("1");
            serviceFlowEventService.routeClassAdded(newFlow.getCode(), basePath.toString(),  flowTemp.getClassName(), deName,newCron);
            return newFlow.getId();
            //生成新的route文件
            String  newFileName = genRouteJavaFile(newFlow.getCode(),flowTemp.getClassName(),deName,newCron);
            if (newFileName!=null){
                serviceFlowEventService.routeClassAdded(newFlow.getCode(), basePath.toString(),  flowTemp.getClassName(), deName,newCron);
                return newFlow.getId();
            }else {
                System.out.println("生成route的java文件过程出错");
                return null;
            }
        }
        return null;
@ -632,15 +506,88 @@ public class FlowManager implements IFlowManage {
                processClass.setFlowId(newFlow.getId());
                processClass.setType(Constants.FLOW_TYPE_PROCESSOR);
                processClass.setIsUpdate("1");
                //发送消息
                serviceFlowEventService.processorClassAdded(newFlow.getCode(),proPath.toString(), processClass.getClassName(), deName);
                //生成新的java文件
                String newFileName = genProcessorJavaFile(newFlow.getCode(),deName,processClass.getClassName());
                if (newFileName!=null){
                    //发送消息
                    serviceFlowEventService.processorClassAdded(newFlow.getCode(),proPath.toString(), processClass.getClassName(), deName);
                    flowClassDao.saveEntity(processClass);
                }else {
                    System.out.println("生成processor的java文件过程出错");
                    return null;
                }
            }
            return newFlow.getId();
        }
                flowClassDao.saveEntity(processClass);
        return null;
    }
    /**
     * 生成Route流程的java文件
     * @param routeId       流程Id
     * @param className     模板类名
     * @param tempFilePath      模板文件路径
     * @param newCron       cron表达式
     * @return
     */
    public static String genRouteJavaFile(String routeId,String className,String tempFilePath,String newCron) {
        try {
            String newFileName = className+routeId+".java";
            String newFilePath = "/temp/"+newFileName;
            String text = GridFSUtil.readFile("upload",tempFilePath);
            if (text.contains("?cron=")) {
                String oldStr = text.substring(text.indexOf("?cron=") + 6);
                String cron = oldStr.substring(0, oldStr.indexOf("\""));
                text = text.replace(cron,newCron);
            }
            return newFlow.getId();
            //修改java类名
            if (text.contains(className)) {
                text = text.replace(className, className+routeId);//新类名规则=旧类名+routeId
            }
            //修改routeId;模板规则 routeId("routeId")
            text = text.replace("routeId(\"routeId\")", "routeId(\"" + routeId + "\")");
            boolean succ = FileUtil.writeFile(newFilePath,text,"UTF-8");
            //TODO 上传到GridFS
            if (succ){
                newFileName = GridFSUtil.uploadFile("upload", newFilePath, newFileName);
            }else {
                return null;
            }
            return newFileName;
        } catch (Exception e) {
            System.out.println("修改Route的java文件操作出错");
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 生成processor的java文件
     * @param routeId       流程Code
     * @param tempFilePath      模板文件名
     * @param className     模板类名
     * @return
     */
    public static String genProcessorJavaFile(String routeId ,String tempFilePath, String className) {
        try {
            String newFileName = className+routeId+".java";
            String newFilePath = "/temp/"+className;
            String text = GridFSUtil.readFile("upload",tempFilePath);
            boolean succ = FileUtil.writeFile(newFilePath,text,"UTF-8");
            //TODO 上传到GridFS
            if (succ){
                newFileName = GridFSUtil.uploadFile("upload", newFilePath, newFileName);
                return newFileName;
            }
        } catch (Exception e) {
            System.out.println("生成processor的java文件操作出错");
            e.printStackTrace();
        }
        return null;
    }

+ 12 - 1
src/test/java/com/yihu/hos/HosAdminApplicationTests.java

@ -1,17 +1,28 @@
package com.yihu.hos;
import com.yihu.hos.core.file.FileUtil;
import com.yihu.hos.web.framework.util.GridFSUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import java.io.IOException;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ESBApplication.class)
@WebAppConfiguration
public class HosAdminApplicationTests {
	@Test
	public void contextLoads() {
	public void contextLoads() throws IOException {
		String newName = "text"+System.currentTimeMillis()+".java";
		String newFilePath = "/upload/"+newName;
		String  content = GridFSUtil.readFile("upload", "955569af-43fb-422f-bded-d88f99cad1f9QuartzRoute.java");
		boolean succ = FileUtil.writeFile(newFilePath, content, "UTF-8");
		newName = GridFSUtil.uploadFile("upload", newFilePath, newName);
		System.out.println(content);
	}
}