zhenglingfeng 8 anni fa
parent
commit
9a76de9c35

+ 83 - 74
hos-broker/src/main/java/com/yihu/hos/common/compiler/CamelCompiler.java

@ -16,7 +16,8 @@ import java.util.Arrays;
import java.util.List;
/**
 *  java编译工具类
 * java编译工具类
 *
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/11/17.
@ -29,90 +30,98 @@ public class CamelCompiler {
            + "/hos-broker/src/main/java/%s/%s.java";
    /**
     * 编译java文件
     * @param params     java包路径
     * 编译java模板文件,生成class
     *
     * @param params 参数对象
     * @throws IOException
     */
    public static String compiler(ClassParams params) throws IOException {
        String classPath = CamelCompiler.class.getProtectionDomain().getCodeSource().getLocation().getPath() ;
        String toClassPath = params.getFilePath().replace(".java",".class");
    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"));
        // 建立源文件对象,每个文件被保存在一个从JavaFileObject继承的类中
        File file = genNewJava(params);
        if (file!=null){
            Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(file.getAbsolutePath());
        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",classPath,"-sourcepath", classPath);// 指定的路径一定要存在,javac不会自己创建文件夹
            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){
            if (!success) {
                //错误信息打印
                List diagnostics1 = diagnostics.getDiagnostics();
                for (int i=0;i<diagnostics1.size();i++){
                for (int i = 0; i < diagnostics1.size(); i++) {
                    System.out.println(diagnostics1.get(i).toString());
                }
                return null;
            }else {
            } else {
                //添加加载类
                String dotPackageName = params.getPackageName().replace("/",".");
                SystemClassMapping.getSystemClassNameMapping().put(params.getRouteId() + BrokerConstant.ROUTE + params.getNewClassName(),dotPackageName  + params.getNewClassName());
                String className = file.getName().replace(".java", ".class");
                classPath = classPath.substring(1);
                String oldClassPath = classPath  + params.getPackageName()  + className;
                File oldClassFile = new File(oldClassPath);
                FileUtils.copyFile(oldClassFile,new File(toClassPath));
                return toClassPath;
                String dotPackageName = params.getPackageName().replace("/", "."); //将带“/"的包名转为”.";
                SystemClassMapping.getSystemClassNameMapping().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路径
                FileUtils.copyFile(new File(loadClassPath), new File(copyClassPath));
                return copyClassPath;
            }
        }
        return null;
    }
    public static String copyProcess (String routeId ,String filePath,String packageName,String oldClassName) throws IOException {
        String classPath = CamelCompiler.class.getProtectionDomain().getCodeSource().getLocation().getPath() ;
        String toClassPath = filePath.replace(".java",".class");
    /**
     * 根据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"));
        // 建立源文件对象,每个文件被保存在一个从JavaFileObject继承的类中
        File fPath = new File(packagePathTemplate+packageName);
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, Charset.forName("UTF-8"));
        // 建立源文件对象,创建父文件夹
        File fPath = new File(packagePathTemplate + packageName);
        if (!fPath.exists()) fPath.mkdirs();
        File toFIle = genProcessor(filePath,packageName,oldClassName);
        if (toFIle.exists()){
                Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(toFIle.getAbsolutePath());
                // options命令行选项
                Iterable<String> options = Arrays.asList("-d",classPath,"-sourcepath", classPath);// 指定的路径一定要存在,javac不会自己创建文件夹
                JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null, compilationUnits);
                // 编译源程序
                boolean success = task.call();
                System.out.println((success) ? oldClassName+"编译成功" : "编译失败");
        File loadFIle = genProcessorJavaFile(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.getSystemClassNameMapping().put(routeId+ BrokerConstant.PROCESSOR + oldClassName,dotPackageName  + oldClassName);
                    String resultPath = toFIle.getName().replace(".java", ".class");
                    classPath = classPath.substring(1);
                     String oldClassPath = classPath + packageName  + resultPath;
                File classFile = new File(oldClassPath);
                FileUtils.copyFile(classFile,new File(toClassPath));
                    return toClassPath;
            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.getSystemClassNameMapping().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));
                return copyClassPath;
            }
        }
        System.out.println("生成processor的java文件失败");
@ -121,28 +130,30 @@ public class CamelCompiler {
    }
    /**
     *  修改cron表达式,生成新java文件
     * @param params   生成camel的参数
     * 修改cron表达式,生成新java文件
     *
     * @param params 生成camel的参数
     */
    public static File genNewJava(ClassParams params) {
    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());
            String newPath = String.format(classPathTemplate, params.getPackageName(), params.getOldClassName() + params.getRouteId());
            String text = FileUtil.readFileText(new File(params.getFilePath()));
            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());
            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());
            }
            if (text.contains(params.getOldClassName())){
            //修改java类名
            if (text.contains(params.getOldClassName())) {
                text = text.replace(params.getOldClassName(), params.getNewClassName());
            }
            //修改routeId;模板规则 routeId("routeId")
            text = text.replace("routeId(\"routeId\")","routeId(\""+params.getRouteId() +"\")" );
            text = text.replace("routeId(\"routeId\")", "routeId(\"" + params.getRouteId() + "\")");
            File fPath = new File(packagePathTemplate+params.getPackageName());
            File fPath = new File(packagePathTemplate + params.getPackageName());
            if (!fPath.exists()) fPath.mkdirs();
            File f = new File(newPath);
@ -151,21 +162,20 @@ public class CamelCompiler {
            fw.flush();
            fw.close();//这里只是产生一个JAVA文件,简单的IO操作
            return f;
        }
        catch (Exception e) {
            System.out.println("修改操作出错");
        } catch (Exception e) {
            System.out.println("修改Route文件操作出错");
            e.printStackTrace();
        }
        return null;
    }
    public static File genProcessor(String filePath,String packageName,String newClassName) {
    public static File genProcessorJavaFile(String filePath, String packageName, String newClassName) {
        try {
            String newPath = String.format(classPathTemplate, packageName, newClassName);
            String text = FileUtil.readFileText(new File(filePath));
            File fPath = new File(packagePathTemplate+packageName);
            File fPath = new File(packagePathTemplate + packageName);
            if (!fPath.exists()) fPath.mkdirs();
            File f = new File(newPath);
@ -174,9 +184,8 @@ public class CamelCompiler {
            fw.flush();
            fw.close();//这里只是产生一个JAVA文件,简单的IO操作
            return f;
        }
        catch (Exception e) {
            System.out.println("复制文件操作出错");
        } catch (Exception e) {
            System.out.println("撑撑processor文件操作出错");
            e.printStackTrace();
        }
        return null;

+ 1 - 1
hos-broker/src/main/java/com/yihu/hos/common/compiler/ClassParams.java

@ -10,7 +10,7 @@ public class ClassParams {
    private String routeId;             //routeId
    private String filePath;            //原java文件路径
    private String filePath;            //原java模板文件路径
    private String packageName;        //包名
    private String oldClassName;      //旧java文件名
    private String newClassName;      //新java文件名

+ 8 - 0
src/main/java/com/yihu/hos/common/constants/ContextAttributes.java

@ -0,0 +1,8 @@
package com.yihu.hos.common.constants;
/**
 * @created Airhead 2016/11/14.
 */
public interface ContextAttributes {
    String SCHEMA = "schema";
}

+ 144 - 2
src/main/java/com/yihu/hos/config/BeanConfig.java

@ -9,7 +9,149 @@ import org.springframework.context.annotation.ImportResource;
 * Created at 2016/8/5.
 */
@Configuration
@ImportResource({"classpath:spring/applicationContext.xml"}) //����xml������
public class BeanConfig {
//@EnableTransactionManagement
//@ComponentScan("com.yihu.hos")
@ImportResource({"classpath:spring/applicationContext.xml"}) //applicationContext相关bean创建
public class BeanConfig{
//    private Environment environment;
//    private RelaxedPropertyResolver datasourcePropertyResolver;
//    private RelaxedPropertyResolver hibernatePropertyResolver;
//
//
//    //从application.yml中读取资源
//    @Override
//    public void setEnvironment(Environment environment) {
//        this.environment = environment;
//        this.datasourcePropertyResolver = new RelaxedPropertyResolver(environment, "spring.datasource.");
//        this.hibernatePropertyResolver = new RelaxedPropertyResolver(environment, "spring.jpa.");
//
//    }
//
//    //datasource 池方式
////    @Bean(initMethod = "init", destroyMethod = "close")
////    public DataSource dataSource() throws SQLException {
////        if (StringUtils.isEmpty(datasourcePropertyResolver.getProperty("url"))) {
////            System.out.println("Your database connection pool configuration is incorrect!" +
////                    " Please check your Spring profile, current profiles are:"+
////                    Arrays.toString(environment.getActiveProfiles()));
////            throw new ApplicationContextException(
////                    "Database connection pool is not configured correctly");
////        }
////        DruidDataSource druidDataSource = new DruidDataSource();
////        druidDataSource.setUrl(datasourcePropertyResolver.getProperty("url"));
////        druidDataSource.setUsername(datasourcePropertyResolver
////                .getProperty("username"));
////        druidDataSource.setPassword(datasourcePropertyResolver
////                .getProperty("password"));
////        druidDataSource.setInitialSize(1);
////        druidDataSource.setMinIdle(1);
////        druidDataSource.setMaxActive(20);
////        druidDataSource.setMaxWait(60000);
////        druidDataSource.setTimeBetweenEvictionRunsMillis(60000);
////        druidDataSource.setMinEvictableIdleTimeMillis(300000);
////        druidDataSource.setValidationQuery("SELECT 'x'");
////        druidDataSource.setTestWhileIdle(true);
////        druidDataSource.setTestOnBorrow(false);
////        druidDataSource.setTestOnReturn(false);
////        return druidDataSource;
////    }
//
//    @Bean( destroyMethod = "close")
//    public BasicDataSource dataSource() throws SQLException {
//        if (StringUtils.isEmpty(datasourcePropertyResolver.getProperty("url"))) {
//            System.out.println("Your database connection pool configuration is incorrect!" +
//                    " Please check your Spring profile, current profiles are:"+
//                    Arrays.toString(environment.getActiveProfiles()));
//            throw new ApplicationContextException(
//                    "Database connection pool is not configured correctly");
//        }
//        BasicDataSource dataSource = new BasicDataSource();
//        dataSource.setUrl(datasourcePropertyResolver.getProperty("url"));
//        dataSource.setUsername(datasourcePropertyResolver.getProperty("username"));
//        dataSource.setPassword(datasourcePropertyResolver.getProperty("password"));
//        dataSource.setInitialSize(datasourcePropertyResolver.getProperty("initial-size", Integer.class));
//        dataSource.setMaxTotal(datasourcePropertyResolver.getProperty("max-total", Integer.class));
//        dataSource.setMinIdle(datasourcePropertyResolver.getProperty("min-idle",Integer.class));
//        dataSource.setMaxIdle(datasourcePropertyResolver.getProperty("max-idle",Integer.class));
//        dataSource.setValidationQuery(datasourcePropertyResolver.getProperty("validation-query"));
//        dataSource.setRemoveAbandonedTimeout(55);
//        dataSource.setTestOnBorrow(datasourcePropertyResolver.getProperty("test-on-borrow",Boolean.class));
//        return dataSource;
//    }
//
//    //sessionFactory
//    @Bean
//    public LocalSessionFactoryBean sessionFactory() throws SQLException {
//        LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
//        localSessionFactoryBean.setDataSource(this.dataSource());
//        Properties properties1 = new Properties();
//        properties1.setProperty("hibernate.dialect",hibernatePropertyResolver.getProperty("hibernate.dialect"));
//        properties1.setProperty("hibernate.show_sql",hibernatePropertyResolver.getProperty("show-sql"));
//        properties1.setProperty("hibernate.format_sql",hibernatePropertyResolver.getProperty("format-sql"));
//        localSessionFactoryBean.setHibernateProperties(properties1);
//        localSessionFactoryBean.setPackagesToScan("com.yihu.hos.standard.model");
//        ResourceLoader resourceLoader = new DefaultResourceLoader();
//        Resource resource = resourceLoader.getResource("classpath:resource/");
//        localSessionFactoryBean.setMappingDirectoryLocations(resource);
////        localSessionFactoryBean.setPackagesToScan("*");
//        return localSessionFactoryBean;
//    }
//
//    //txManager事务开启
//    @Bean
//    public HibernateTransactionManager txManager() throws SQLException {
//        HibernateTransactionManager hibernateTransactionManager = new HibernateTransactionManager();
//        hibernateTransactionManager.setSessionFactory(sessionFactory().getObject());
//        return hibernateTransactionManager;
//    }
//
//    //文经上传
//    @Bean
//    public CommonsMultipartResolver multipartResolver(){
//        return new CommonsMultipartResolver();
//    }
//
//    //国际化配置
//    @Bean
//    public ResourceBundleMessageSource messageSource(){
//        ResourceBundleMessageSource messageSource =new ResourceBundleMessageSource();
//        messageSource.setBasenames("text/message");
//        messageSource.setDefaultEncoding("UTF-8");
//        return messageSource;
//    }
//
//    @Bean
//    public CookieLocaleResolver localeResolver(){
//        CookieLocaleResolver localeResolver = new CookieLocaleResolver();
//        localeResolver.setCookieName("Language");
//        localeResolver.setCookieMaxAge(604800);
//        localeResolver.setDefaultLocale(new Locale("zh_CN"));
//        return localeResolver;
//    }
//
//    @Bean
//    public LocaleChangeInterceptor localeChangeInterceptor(){
//        return new LocaleChangeInterceptor();
//    }
//
//    @Bean
//    public JdbcTemplate jdbcTemplate(){
//        JdbcTemplate jdbcTemplate = new JdbcTemplate();
//        try {
//            jdbcTemplate.setDataSource(this.dataSource());
//        } catch (SQLException e) {
//            e.printStackTrace();
//        }
//        return jdbcTemplate;
//    }
//
//    //Hibernate模版配置
//    @Bean
//    public HibernateTemplate hibernateTemplate() throws SQLException {
//        HibernateTemplate hibernateTemplate = new HibernateTemplate();
//        hibernateTemplate.setSessionFactory(this.sessionFactory().getObject());
//        return hibernateTemplate;
//    }
}

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

@ -0,0 +1,46 @@
package com.yihu.hos.interceptor;
import com.yihu.hos.common.constants.ContextAttributes;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.EmptyInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.Iterator;
/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/11/30.
 */
@Component
public class AuditInterceptor extends EmptyInterceptor {
    private static final long serialVersionUID = 1L;
    private static Logger logger = LoggerFactory.getLogger(AuditInterceptor.class);
    @Override
    public String onPrepareStatement(String sql) {
        String schemaName = getSchema();
        String completeSql = sql;
        if (StringUtils.isNotEmpty(schemaName)) {
            String myCatAnnotation = "/*#mycat:schema=" + schemaName + "*/ ";
            completeSql = myCatAnnotation + sql;
        }
        logger.info("prepare " + completeSql);
        return super.onPrepareStatement(completeSql);
    }
    @Override
    public void preFlush(Iterator entities) {
        System.out.println("preflush..............");
        super.preFlush(entities);
    }
    private String getSchema() {
        return LocalContext.getContext().getAttachment(ContextAttributes.SCHEMA);
    }
}

+ 60 - 0
src/main/java/com/yihu/hos/interceptor/LocalContext.java

@ -0,0 +1,60 @@
package com.yihu.hos.interceptor;
import java.util.HashMap;
import java.util.Map;
/**
 * @created Airhead 2016/11/14.
 */
public class LocalContext {
    private static final ThreadLocal<LocalContext> LOCAL = new ThreadLocal<LocalContext>() {
        protected LocalContext initialValue() {
            return new LocalContext();
        }
    };
    private final Map<String, String> attachments = new HashMap<>();
    public static LocalContext getContext() {
        return LOCAL.get();
    }
    public static void removeContext() {
        LOCAL.remove();
    }
    public String getAttachment(String key) {
        return (String) this.attachments.get(key);
    }
    public LocalContext setAttachment(String key, String value) {
        if (value == null) {
            this.attachments.remove(key);
        } else {
            this.attachments.put(key, value);
        }
        return this;
    }
    public LocalContext removeAttachment(String key) {
        this.attachments.remove(key);
        return this;
    }
    public Map<String, String> getAttachments() {
        return this.attachments;
    }
    public LocalContext setAttachments(Map<String, String> attachment) {
        this.attachments.clear();
        if (attachment != null && attachment.size() > 0) {
            this.attachments.putAll(attachment);
        }
        return this;
    }
    public void clearAttachments() {
        this.attachments.clear();
    }
}

+ 7 - 1
src/main/resources/spring/applicationContext.xml

@ -49,9 +49,15 @@
        <property name="removeAbandonedTimeout" value="55"/>
    </bean>
    <bean id="cacheIntercepter" class="com.yihu.hos.interceptor.AuditInterceptor" />
    <!--Hibernate 会话管理器配置-->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="entityInterceptor">
            <ref bean="cacheIntercepter"/>
        </property>
        <property name="packagesToScan">
            <list>
                <!-- 可以加多个包 -->
@ -61,7 +67,7 @@
        <property name="hibernateProperties">
            <value>
                hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
                hibernate.show_sql=false
                hibernate.show_sql=true
                hibernate.format_sql=true
            </value>
        </property>