Browse Source

测试完成camel动态加载class流程

Airhead 8 years ago
parent
commit
92ab2a40e4

+ 5 - 5
hos-arbiter/src/main/java/com/yihu/hos/arbiter/services/ServiceFlowService.java

@ -84,9 +84,9 @@ public class ServiceFlowService {
        flowController("post", "/esb/serviceFlow/start", msg);
    }
    public void serviceFlowStarted(String msg, BrokerServer brokerServer) {
        flowController("post", "/esb/serviceFlow/start", msg, brokerServer);
    }
//    public void serviceFlowStarted(String msg, BrokerServer brokerServer) {
//        flowController("post", "/esb/serviceFlow/start", msg, brokerServer);
//    }
    public void serviceFlowStopped(String msg) {
        flowController("post", "/esb/serviceFlow/stop", msg);
@ -114,7 +114,7 @@ public class ServiceFlowService {
            try {
                BrokerServer brokerServer = objectMapper.readValue(msg, BrokerServer.class);
                String serviceFlowMsg = objectMapper.writeValueAsString(serviceFlow);
                serviceFlowStarted(serviceFlowMsg, brokerServer);
                serviceFlowStarted(serviceFlowMsg);
            } catch (IOException e) {
                e.printStackTrace();
            }
@ -144,7 +144,7 @@ public class ServiceFlowService {
    private void flowController(String method, String path, String msg, BrokerServer brokerServer) {
        try {
            ServiceFlow serviceFlow = getServiceFlow(msg);
            this.save(serviceFlow); //需要改造??
//            this.save(serviceFlow); //需要改造??
            boolean one = ServiceFlowConstant.JAVA.equals(serviceFlow.getFlowType());   //有cron表达式,就是采集任务。
            if (one) {

+ 8 - 4
hos-broker/src/main/java/com/yihu/hos/broker/HosBrokerApplication.java

@ -1,6 +1,7 @@
package com.yihu.hos.broker;
import com.yihu.hos.broker.listeners.ApplicationStartListener;
import com.yihu.hos.broker.services.camel.CamelStartBoot;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration;
@ -11,18 +12,21 @@ import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
@EnableScheduling
public class HosBrokerApplication extends SpringBootServletInitializer {
public class HosBrokerApplication extends SpringBootServletInitializer implements CommandLineRunner {
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(HosBrokerApplication.class);
//        app.addListeners(new ApplicationStartListener());
        app.run(args);
    }
    @Override
    public void run(String... strings) throws Exception {
        new CamelStartBoot().start();
    }
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        builder.sources(this.getClass());
        builder.listeners(new ApplicationStartListener());
        return super.configure(builder);
    }
}

+ 0 - 46
hos-broker/src/main/java/com/yihu/hos/broker/listeners/ApplicationStartListener.java

@ -1,46 +0,0 @@
package com.yihu.hos.broker.listeners;
import com.yihu.hos.broker.models.SystemCamelContext;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
public class ApplicationStartListener implements ApplicationListener<ContextRefreshedEvent> {
    private static Logger logger = LogManager.getLogger(ApplicationStartListener.class);
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        try {
            camelRouteStart(contextRefreshedEvent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 这是一个固定的存储class文件的根路径
     * 正式系统中,这个值可来自于系统的配置文件
     */
    private void camelRouteStart(ContextRefreshedEvent contextRefreshedEvent) throws Exception {
        logger.info("Apache Camel Context 启动...");
        // 加载和设置ClassLoader
        List<URL> URLs = new ArrayList<>();
        ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
        ClassLoader camelESBClassLoader = new URLClassLoader(URLs.toArray(new URL[]{}), currentClassLoader);
        Thread.currentThread().setContextClassLoader(camelESBClassLoader);
        SystemCamelContext.getContext().setApplicationContextClassLoader(camelESBClassLoader);
        // 然后就可以进行RouteBuilder的加载
        SystemCamelContext.getContext().setTracing(true);
        SystemCamelContext.getContext().setUseMDCLogging(true);
        SystemCamelContext.getContext().start();
        logger.info("Apache Camel Context 启动完成...");
    }
}

+ 0 - 18
hos-broker/src/main/java/com/yihu/hos/broker/models/SystemCamelContext.java

@ -1,18 +0,0 @@
package com.yihu.hos.broker.models;
import org.apache.camel.CamelContext;
import org.apache.camel.impl.DefaultCamelContext;
/**
 * Created by lingfeng on 2016/8/9.
 */
public class SystemCamelContext {
    private static CamelContext context;
    public static CamelContext getContext() {
        if (context == null) {
            context = new DefaultCamelContext();
        }
        return context;
    }
}

+ 0 - 32
hos-broker/src/main/java/com/yihu/hos/broker/models/SystemClassMapping.java

@ -1,32 +0,0 @@
package com.yihu.hos.broker.models;
import com.yihu.hos.core.constants.CoreConstant;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
/**
 * 加载的类文件列表
 * <p>
 * Created by lingfeng on 2016/8/4.
 */
public class SystemClassMapping {
    private static Map<String, String> mapping = new HashMap<>();
    public static Map<String, String> getMapping() {
        return mapping;
    }
    public static void put(String routeCode, String packageName, String type, String className) {
        mapping.put(routeCode + "|" + type + "|" + className, packageName + CoreConstant.DOT + className);
    }
    public static String get(String routeCode, String className, String type) {
        return mapping.get(routeCode + "|" + type + "|" + className);
    }
    public static URL getResource(Object o) {
        return o.getClass().getProtectionDomain().getClassLoader().getResource("");
    }
}

+ 0 - 71
hos-broker/src/main/java/com/yihu/hos/broker/services/camel/CamelClassLoader.java

@ -1,71 +0,0 @@
package com.yihu.hos.broker.services.camel;
import com.yihu.hos.broker.common.constants.BrokerConstant;
import com.yihu.hos.core.constants.CoreConstant;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class CamelClassLoader extends ClassLoader {
    public CamelClassLoader(ClassLoader parent) {
        super(parent);
    }
    @SuppressWarnings("unchecked")
    public Class<?> loadClass(String classPath, String className)
            throws ClassNotFoundException {
        try {
            className = className + CoreConstant.DOT + BrokerConstant.CLASS;
            String url = classPathParser(classPath)
                    + classNameParser(className);
            URL myUrl = new URL(url);
            URLConnection connection = myUrl.openConnection();
            InputStream input = connection.getInputStream();
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            int data = input.read();
            while (data != -1) {
                buffer.write(data);
                data = input.read();
            }
            input.close();
            byte[] classData = buffer.toByteArray();
            return defineClass(noSuffix(className), classData, 0,
                    classData.length);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    private String pathParser(String path) {
        return path.replaceAll("\\\\", "/");
    }
    private String classPathParser(String path) {
        String classPath = pathParser(path);
        if (!classPath.startsWith("file:")) {
            classPath = "file:" + classPath;
        }
        if (!classPath.endsWith("/")) {
            classPath = classPath + "/";
        }
        return classPath;
    }
    private String classNameParser(String className) {
        return className.substring(0, className.lastIndexOf(".")).replaceAll(
                "\\.", "/")
                + className.substring(className.lastIndexOf("."));
    }
    private String noSuffix(String className) {
        return className.substring(0, className.lastIndexOf("."));
    }
}

+ 0 - 180
hos-broker/src/main/java/com/yihu/hos/broker/services/camel/CamelCompiler.java

@ -1,14 +1,9 @@
package com.yihu.hos.broker.services.camel;
import com.yihu.hos.broker.common.constants.BrokerConstant;
import com.yihu.hos.broker.models.SystemClassMapping;
import com.yihu.hos.core.file.FileUtil;
import com.yihu.hos.core.log.Logger;
import com.yihu.hos.core.log.LoggerFactory;
import com.yihu.hos.web.framework.util.GridFSUtil;
import javax.tools.*;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;
@ -23,181 +18,6 @@ import java.util.List;
 */
public class CamelCompiler {
    private static final Logger logger = LoggerFactory.getLogger(CamelCompiler.class);
    private static String packagePathTemplate = System.getProperty("user.dir")//获取到项目的根路径
            + "/hos-broker/src/main/java/";
    private static String classPathTemplate = System.getProperty("user.dir")//获取到项目的根路径
            + "/hos-broker/src/main/java/%s/%s.java";
    /**
     * 编译java模板文件,生成class
     *
     * @param params 参数对象
     * @throws IOException
     */
    public static String genRouteClass(ClassParams params) throws IOException {
        String targetPath = CamelCompiler.class.getProtectionDomain().getCodeSource().getLocation().getPath();//项目class根目录
        String copyClassPath = params.getFilePath().replace(".java", ".class");//数据库保存的class路径
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        // 建立DiagnosticCollector对象
        DiagnosticCollector diagnostics = new DiagnosticCollector();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, Charset.forName("UTF-8"));
        // 建立源文件对象,根据java模板文件生成要加载的java类
        File loadJavaFile = genRouteJavaFile(params);
        if (loadJavaFile != null) {
            Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(loadJavaFile.getAbsolutePath());
            // options命令行选项
            Iterable<String> options = Arrays.asList("-d", targetPath, "-sourcepath", targetPath);// 指定的路径一定要存在,javac不会自己创建文件夹
            JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null, compilationUnits);
            // 编译源程序
            boolean success = task.call();
            fileManager.close();
            System.out.println((success) ? "编译成功" : "编译失败");
            if (!success) {
                //错误信息打印
                List diagnostics1 = diagnostics.getDiagnostics();
                for (int i = 0; i < diagnostics1.size(); i++) {
                    System.out.println(diagnostics1.get(i).toString());
                }
                return null;
            } else {
                //添加加载类
                String dotPackageName = params.getPackageName().replace("/", "."); //将带“/"的包名转为”.";
                SystemClassMapping.getMapping().put(params.getRouteId() + BrokerConstant.ROUTE + params.getNewClassName(), dotPackageName + params.getNewClassName());
                String loadClassName = loadJavaFile.getName().replace(".java", ".class");
                targetPath = targetPath.substring(1);
                String loadClassPath = targetPath + params.getPackageName() + loadClassName;//加载的class路径
                copyClassPath = GridFSUtil.uploadFile("upload", loadClassPath, params.getFilePath().replace(".java", ".class"));
                return copyClassPath;
            }
        }
        return null;
    }
    /**
     * 根据java模板生成新的class文件
     *
     * @param routeId
     * @param filePath    java模板路径
     * @param packageName java模板包名
     * @param className   java模板类名
     * @return
     * @throws IOException
     */
    public static String genProcessClass(String routeId, String filePath, String packageName, String className) throws IOException {
        String targetPath = CamelCompiler.class.getProtectionDomain().getCodeSource().getLocation().getPath();//项目class根目录
        String copyClassPath = filePath.replace(".java", ".class");//管理端 数据库保存的class路径
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        // 建立DiagnosticCollector对象
        DiagnosticCollector diagnostics = new DiagnosticCollector();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, Charset.forName("UTF-8"));
        // 建立源文件对象,创建父文件夹
        File fPath = new File(packagePathTemplate + packageName);
        if (!fPath.exists()) fPath.mkdirs();
        File loadFIle = genProcessorJavaFile(routeId, filePath, packageName, className);
        if (loadFIle.exists()) {
            Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(loadFIle.getAbsolutePath());
            // options命令行选项
            Iterable<String> options = Arrays.asList("-d", targetPath, "-sourcepath", targetPath);// 指定的路径一定要存在,javac不会自己创建文件夹
            JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null, compilationUnits);
            // 编译源程序
            boolean success = task.call();
            System.out.println((success) ? className + "编译成功" : className + "编译失败");
            fileManager.close();
            if (!success) {
                //失败信息打印
                List diagnostics1 = diagnostics.getDiagnostics();
                for (int i = 0; i < diagnostics1.size(); i++) {
                    System.out.println(diagnostics1.get(i).toString());
                }
                return null;
            } else {
                String dotPackageName = packageName.replace("/", ".");//将带“/"的包名转为”.";
                SystemClassMapping.getMapping().put(routeId + BrokerConstant.PROCESSOR + className, dotPackageName + className);
                String loadPath = loadFIle.getName().replace(".java", ".class");
                targetPath = targetPath.substring(1);
                String loadClassPath = targetPath + packageName + loadPath;//要加载的class路径
//                FileUtils.copyFile(new File(loadClassPath), new File(copyClassPath));
                copyClassPath = GridFSUtil.uploadFile("upload", loadClassPath, filePath.replace(".java", ".class"));
                return copyClassPath;
            }
        }
        System.out.println("生成processor的java文件失败");
        return null;
    }
    /**
     * 修改cron表达式,生成新java文件
     *
     * @param params 生成camel的参数
     */
    public static File genRouteJavaFile(ClassParams params) {
        try {
//            String oldPath = String.format(classPathTemplate, packageName, oldClassName);
            String newPath = String.format(classPathTemplate, params.getPackageName(), params.getOldClassName() + params.getRouteId());
            newPath = GridFSUtil.downFile("upload", newPath, params.getFilePath());
            String text = FileUtil.readFileText(new File(newPath));
            if (text.contains("?cron=")) {
                String oldStr = text.substring(text.indexOf("?cron=") + 6);
                String cron = oldStr.substring(0, oldStr.indexOf("\""));
                text = text.replace(cron, params.getCron());
            }
            //修改java类名
            if (text.contains(params.getOldClassName())) {
                text = text.replace(params.getOldClassName(), params.getNewClassName());
            }
            //修改routeId;模板规则 routeId("routeId")
            text = text.replace("routeId(\"routeId\")", "routeId(\"" + params.getRouteId() + "\")");
            File fPath = new File(packagePathTemplate + params.getPackageName());
            if (!fPath.exists()) fPath.mkdirs();
            File f = new File(newPath);
            boolean b = FileUtil.writeFile(newPath, text, "UTF-8");
//            FileWriter fw = new FileWriter(f);
//            fw.write(text);
//            fw.flush();
//            fw.close();//这里只是产生一个JAVA文件,简单的IO操作
            return f;
        } catch (Exception e) {
            System.out.println("修改Route文件操作出错");
            e.printStackTrace();
        }
        return null;
    }
    public static File genProcessorJavaFile(String routId, String filePath, String packageName, String className) {
        try {
            String newPath = String.format(classPathTemplate, packageName, className);
            newPath = GridFSUtil.downFile("upload", newPath, filePath);
            String text = FileUtil.readFileText(new File(newPath));
            File fPath = new File(packagePathTemplate + packageName);
            if (!fPath.exists()) fPath.mkdirs();
            File f = new File(newPath);
            boolean b = FileUtil.writeFile(newPath, text, "UTF-8");
//            FileWriter fw = new FileWriter(f);
//            fw.write(text);
//            fw.flush();
//            fw.close();//这里只是产生一个JAVA文件,简单的IO操作
            return f;
        } catch (Exception e) {
            System.out.println("撑撑processor文件操作出错");
            e.printStackTrace();
        }
        return null;
    }
    public static boolean compile(String sourcePath, String targetPath) throws IOException {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

+ 51 - 0
hos-broker/src/main/java/com/yihu/hos/broker/services/camel/CamelStartBoot.java

@ -0,0 +1,51 @@
package com.yihu.hos.broker.services.camel;
import org.apache.camel.builder.RouteBuilder;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.SynchronousQueue;
/**
 * @author Airhead
 * @since 2016/12/9.
 */
public class CamelStartBoot {
    private static Logger logger = LogManager.getLogger(ESBCamelService.class);
    public void start() {
        logger.info("Apache Camel Context 启动...");
        try {
            SystemCamelContext.getContext().setTracing(true);
            SystemCamelContext.getContext().setUseMDCLogging(true);
            SystemCamelContext.getContext().start();
            List<URL> URLs = new ArrayList<>();
            ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
            ClassLoader camelClassLoader = new URLClassLoader(URLs.toArray(new URL[]{}), currentClassLoader);
            Thread.currentThread().setContextClassLoader(camelClassLoader);
            SystemCamelContext.getContext().setApplicationContextClassLoader(camelClassLoader);
            logger.info("Apache Camel Context 启动完成...");
            SynchronousQueue<String> camelContextOperateQueue = SystemCamelContext.getQueue();
            String className = null;
            // 如果没有收到其它线程的加载请求,主线程将停止在这里
            while ((className = camelContextOperateQueue.take()) != null) {
                Class<RouteBuilder> routeBuilderClass = (Class<RouteBuilder>) camelClassLoader.loadClass(className);
                if (routeBuilderClass != null) {
                    RouteBuilder routeBuilder = routeBuilderClass.newInstance();
                    SystemCamelContext.getContext().addRoutes(routeBuilder);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("Apache Camel Context 启动失败...");
        }
    }
}

+ 49 - 54
hos-broker/src/main/java/com/yihu/hos/broker/services/camel/ESBCamelService.java

@ -3,8 +3,6 @@ package com.yihu.hos.broker.services.camel;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.client.MongoDatabase;
import com.yihu.hos.broker.configurations.MongoConfiguration;
import com.yihu.hos.broker.models.SystemCamelContext;
import com.yihu.hos.broker.models.SystemClassMapping;
import com.yihu.hos.core.constants.CoreConstant;
import com.yihu.hos.core.datatype.ClassFileUtil;
import com.yihu.hos.core.datatype.StringUtil;
@ -13,7 +11,6 @@ import com.yihu.hos.web.framework.constant.ServiceFlowConstant;
import com.yihu.hos.web.framework.model.Result;
import com.yihu.hos.web.framework.model.bo.ServiceFlow;
import com.yihu.hos.web.framework.util.GridFSUtil;
import org.apache.camel.builder.RouteBuilder;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
@ -57,24 +54,34 @@ public class ESBCamelService {
            if (serviceFlowValid.is()) return Result.error("必要的入参数据不正确,请检查!");
            ServiceFlow serviceFlow = serviceFlowValid.getServiceFlow();
            ServiceFlow.HandleFile handleFile = serviceFlowValid.getHandleFile();
            boolean created;
            if ("java".equals(handleFile.getFileType())) {
                created = this.generateClassFile(handleFile);
            } else {
                created = this.createClassFile(handleFile);
            }
            if (!created) {
                return Result.error("服务流程变更增加失败!");
            ArrayList<ServiceFlow.HandleFile> handleFiles = serviceFlowValid.getHandleFiles();
            for (ServiceFlow.HandleFile handleFile : handleFiles) {
                boolean created;
                if ("java".equals(handleFile.getFileType())) {
                    logger.debug("generate class file...");
                    created = this.generateClassFile(handleFile);
                } else {
                    logger.debug("create class file");
                    created = this.createClassFile(handleFile);
                }
                if (!created) {
                    logger.debug("create class file failed");
                    return Result.error("服务流程增加失败!");
                }
            }
            this.addRouter(handleFile);
            this.startRouter(serviceFlow.getRouteCode());
            logger.debug("add camel router" + serviceFlow.getRouteCode());
            this.addRouter(serviceFlow.getHandleFiles());
            return Result.error("服务流程变更增加成功!");
            logger.debug("start camel router," + serviceFlow.getRouteCode());
            SystemCamelContext.startRouter(serviceFlow.getRouteCode());
            logger.debug("start camel router success," + serviceFlow.getRouteCode());
            return Result.error("服务流程增加成功!");
        } catch (Exception e) {
            logger.error(e);
            return Result.error("服务流程变更增加失败!");
            return Result.error("服务流程增加失败!");
        }
    }
@ -98,10 +105,10 @@ public class ESBCamelService {
                return Result.error("服务流程变更增加失败!");
            }
            this.stopRouter(serviceFlow.getRouteCode());
            this.removeRouter(serviceFlow.getRouteCode());
            this.addRouter(handleFile);
            this.startRouter(serviceFlow.getRouteCode());
            SystemCamelContext.stopRouter(serviceFlow.getRouteCode());
            SystemCamelContext.removeRouter(serviceFlow.getRouteCode());
            this.addRouter(serviceFlowValid.getHandleFiles());
            SystemCamelContext.startRouter(serviceFlow.getRouteCode());
            return Result.error("服务流程变更增加成功!");
        } catch (Exception e) {
@ -124,8 +131,8 @@ public class ESBCamelService {
            SystemCamelContext.getContext().stopRoute(routeCode);
            SystemCamelContext.getContext().removeRoute(routeCode);
            this.deleteClassFile(handleFile);
            this.addRouter(handleFile);
            this.startRouter(serviceFlow.getRouteCode());
            this.addRouter(serviceFlowValid.getHandleFiles());
            SystemCamelContext.startRouter(serviceFlow.getRouteCode());
            return Result.success("服务流程变更减少成功!");
        } catch (Exception e) {
@ -172,11 +179,11 @@ public class ESBCamelService {
                if (!created) {
                    return Result.error("服务流程启动失败!");
                }
                this.addRouter(handleFile);
            }
            this.startRouter(serviceFlow.getRouteCode());
            this.addRouter(handleFiles);
            SystemCamelContext.startRouter(serviceFlow.getRouteCode());
            return Result.success("服务流程启动成功!");
        } catch (Exception e) {
@ -206,8 +213,8 @@ public class ESBCamelService {
        if (handleFile == null) {
            return false;
        }
        SystemClassMapping.put(handleFile.getRouteCode(), handleFile.getPackageName(), handleFile.getUsage(), handleFile.getClassName());
        URL resource = SystemClassMapping.getResource(this);
        SystemCamelContext.putClassMapping(handleFile.getRouteCode(), handleFile.getPackageName(), handleFile.getUsage(), handleFile.getClassName());
        URL resource = SystemCamelContext.getResource(this);
        FileOutputStream outputStream = ClassFileUtil.createFile(resource, handleFile.getPackageName(), handleFile.getClassName(), ClassFileUtil.CLASS_FILE);
        String fileName = DES.decrypt(handleFile.getFilePath(), DES.COMMON_PASSWORD);
@ -225,8 +232,8 @@ public class ESBCamelService {
        if (handleFile == null) {
            return false;
        }
        SystemClassMapping.put(handleFile.getRouteCode(), handleFile.getPackageName(), handleFile.getUsage(), handleFile.getClassName());
        URL resource = SystemClassMapping.getResource(this);
        SystemCamelContext.putClassMapping(handleFile.getRouteCode(), handleFile.getPackageName(), handleFile.getUsage(), handleFile.getClassName());
        URL resource = SystemCamelContext.getResource(this);
        FileOutputStream outputStream = ClassFileUtil.createFile(resource, handleFile.getPackageName(), handleFile.getClassName(), ClassFileUtil.JAVA_FILE);
        String fileName = DES.decrypt(handleFile.getFilePath(), DES.COMMON_PASSWORD);
@ -244,7 +251,7 @@ public class ESBCamelService {
    }
    private void deleteClassFile(ServiceFlow.HandleFile handleFile) {
        String className = SystemClassMapping.get(handleFile.getRouteCode(), handleFile.getClassName(), handleFile.getUsage());
        String className = SystemCamelContext.getClassMapping(handleFile.getRouteCode(), handleFile.getClassName(), handleFile.getUsage());
        if (StringUtil.isEmpty(className)) {
            return;
        }
@ -261,41 +268,29 @@ public class ESBCamelService {
    }
    private void addRouter(ArrayList<ServiceFlow.HandleFile> handleFiles) throws Exception {
        ArrayList<ServiceFlow.HandleFile> routerFiles = new ArrayList<>();
        handleFiles.forEach(handleFile -> {
            try {
                addRouter(handleFile);
                if (handleFile.getUsage().equals(ServiceFlowConstant.FLOW_TYPE_ROUTE)) {
                    String className = SystemCamelContext.getClassMapping(handleFile.getRouteCode(), handleFile.getClassName(), handleFile.getUsage());
                    SystemCamelContext.getQueue().put(className);
                }
            } catch (Exception e) {
                logger.error(e.getMessage());
                e.printStackTrace();
            }
        });
    }
    private void addRouter(ServiceFlow.HandleFile handleFile) throws Exception {
        if (handleFile.getUsage().equals(ServiceFlowConstant.FLOW_TYPE_PROCESSOR)) {
            return;
        }
        CamelClassLoader classLoader = new CamelClassLoader(CamelClassLoader.class.getClassLoader());
        String path = ClassLoader.getSystemResource(CoreConstant.EMPTY).getPath();
        String className = SystemClassMapping.get(handleFile.getRouteCode(), handleFile.getClassName(), handleFile.getUsage());
        Class<RouteBuilder> routeBuilderClass = (Class<RouteBuilder>) classLoader.loadClass(path, className);
        if (routeBuilderClass != null) {
            RouteBuilder routeBuilder = routeBuilderClass.newInstance();
            SystemCamelContext.getContext().addRoutes(routeBuilder);
        }
    }
        routerFiles.forEach(handleFile -> {
            try {
    private void startRouter(String routeCode) throws Exception {
        SystemCamelContext.getContext().startRoute(routeCode);
    }
            } catch (Exception e) {
                logger.error(e.getMessage());
                e.printStackTrace();
            }
        });
    private void stopRouter(String routeCode) throws Exception {
        SystemCamelContext.getContext().stopRoute(routeCode);
    }
    private boolean removeRouter(String routeCode) throws Exception {
        return SystemCamelContext.getContext().removeRoute(routeCode);
    }
    private class ServiceFlowValid {

+ 59 - 0
hos-broker/src/main/java/com/yihu/hos/broker/services/camel/SystemCamelContext.java

@ -0,0 +1,59 @@
package com.yihu.hos.broker.services.camel;
import com.yihu.hos.core.constants.CoreConstant;
import org.apache.camel.CamelContext;
import org.apache.camel.impl.DefaultCamelContext;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.SynchronousQueue;
/**
 * Created by lingfeng on 2016/8/9.
 */
public class SystemCamelContext {
    private static CamelContext context;
    private static SynchronousQueue<String> queue = new SynchronousQueue<>();
    private static Map<String, String> mapping = new HashMap<>();
    public static Map<String, String> getMapping() {
        return mapping;
    }
    public static void putClassMapping(String routeCode, String packageName, String type, String className) {
        mapping.put(routeCode + "|" + type + "|" + className, packageName + CoreConstant.DOT + className);
    }
    public static String getClassMapping(String routeCode, String className, String type) {
        return mapping.get(routeCode + "|" + type + "|" + className);
    }
    public static URL getResource(Object o) {
        return o.getClass().getProtectionDomain().getClassLoader().getResource("");
    }
    public static CamelContext getContext() {
        if (context == null) {
            context = new DefaultCamelContext();
        }
        return context;
    }
    public static SynchronousQueue<String> getQueue() {
        return queue;
    }
    public static void startRouter(String routeCode) throws Exception {
        getContext().startRoute(routeCode);
    }
    public static void stopRouter(String routeCode) throws Exception {
        getContext().stopRoute(routeCode);
    }
    public static boolean removeRouter(String routeCode) throws Exception {
        return getContext().removeRoute(routeCode);
    }
}

+ 7 - 0
hos-broker/src/test/java/com/yihu/hos/HosBrokerApplicationTests.java

@ -1,7 +1,14 @@
package com.yihu.hos;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@WebAppConfiguration
public class HosBrokerApplicationTests {
    @Test

+ 70 - 0
hos-broker/src/test/java/com/yihu/hos/broker/services/camel/ESBCamelServiceTest.java

@ -1,14 +1,80 @@
package com.yihu.hos.broker.services.camel;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import java.io.File;
import java.net.URI;
/**
 * @author Airhead
 * @since 2016/12/6.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@WebAppConfiguration
public class ESBCamelServiceTest {
    @Autowired
    private ESBCamelService esbCamelService;
    @Test
    public void onServiceFlowAdd() throws Exception {
    String msg="{\n" +
            "    \"routeCode\" : \"invokeSync\",\n" +
            "    \"updated\" : null,\n" +
            "    \"flowType\" : \"class\",\n" +
            "    \"handleFiles\" : [ \n" +
            "        {\n" +
            "            \"usage\" : \"processor\",\n" +
            "            \"packageName\" : \"apisync.processor\",\n" +
            "            \"className\" : \"ApiProcessor\",\n" +
            "            \"filePath\" : \"22241906357fac850e39df5dd74e7ddc4f1c6808019c571a98e96ad7e01a635afe687822969a785b523d97cbc5d33904b5296227c61c08bb\",\n" +
            "            \"fileType\" : \"class\",\n" +
            "            \"routeCode\" : \"invokeSync\"\n" +
            "        }, \n" +
            "        {\n" +
            "            \"usage\" : \"route\",\n" +
            "            \"packageName\" : \"apisync.route\",\n" +
            "            \"className\" : \"ApiRouteBulider\",\n" +
            "            \"filePath\" : \"89108d6cbec5e48ae19806476e1e946fb10e5656424326c288c69dcfda6a3add873b0c64959cb310e96e4cd4f3c0d627f82f813633c2f8ebe73a3fa3a83feb15\",\n" +
            "            \"fileType\" : \"class\",\n" +
            "            \"routeCode\" : \"invokeSync\"\n" +
            "        }\n" +
            "    ]\n" +
            "}";
    esbCamelService.onServiceFlowAdd(msg);
    }
    @Test
    public void onServiceFlowModifyAdd() throws Exception {
    }
    @Test
    public void onServiceFlowModifyReduce() throws Exception {
    }
    @Test
    public void onServiceFlowDelete() throws Exception {
    }
    @Test
    public void onServiceFlowStart() throws Exception {
    }
    @Test
    public void onServiceFlowStop() throws Exception {
    }
    @Test
    public void onProcessorAdded() throws Exception {
        String url = this.getClass().getProtectionDomain().getClassLoader().getResource("").toString();
@ -18,6 +84,10 @@ public class ESBCamelServiceTest {
        String sysPath = systemClassFlowPath.toURI().toURL().toString();
        System.out.println(sysPath);
        URI uri = ESBCamelService.class.getResource("").toURI();
        File file  = new File("d:/usr");
        URI uri1 = file.toURI();
        uri1.toURL();
    }