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 启动失败...");
        }

    }
}
