package com.yihu.hos.broker.services.camel;

import com.yihu.hos.core.log.Logger;
import com.yihu.hos.core.log.LoggerFactory;

import javax.tools.*;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;

/**
 * java编译工具类
 *
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/11/17.
 */
public class CamelCompiler {
    private static final Logger logger = LoggerFactory.getLogger(CamelCompiler.class);

    public static boolean compile(String sourcePath, String targetPath) throws IOException {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        // 建立DiagnosticCollector对象
        DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, Charset.forName("UTF-8"));
        // 建立源文件对象，根据java模板文件生成要加载的java类
        Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(sourcePath);
        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();
        if (!success) {
            logger.error("compile source file failed.");
            //错误信息打印
            List diagnosticList = diagnostics.getDiagnostics();
            for (Object aDiagnosticList : diagnosticList) {
                System.out.println(aDiagnosticList.toString());
                logger.error(aDiagnosticList.toString());
            }
        }else {
            System.out.println("编译成功"+sourcePath);
        }

        return success;
    }


}
