Browse Source

终端broker从中心下载流程文件

demon 8 years ago
parent
commit
83b27c826e

+ 4 - 4
hos-arbiter/src/main/resources/application.yml

@ -11,23 +11,23 @@ spring:
  profiles: dev
  data:
    mongodb:
      host: 172.19.103.86
      host: 172.19.103.57
      port: 27017
      username: esb
      password: esb
      authenticationDatabase: admin
      database: configuration
  activemq:
    broker-url: tcp://172.19.103.86:61616
    broker-url: tcp://172.19.103.57:61616
    user: admin
    password: admin
arbiter:
  timer:
      period: 10000
  central:
    url: http://127.0.0.1:10135
    url:
  terminal:
    url: http://127.0.0.1:10135
    url: http://172.19.103.57:10135
  tenant:
    name: jkzl
---

+ 16 - 7
hos-broker/src/main/java/com/yihu/hos/broker/services/camel/ESBCamelService.java

@ -18,6 +18,7 @@ import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.FileOutputStream;
@ -53,6 +54,8 @@ public class ESBCamelService {
    private String configuration = "configuration";
    @Autowired
    private ObjectMapper objectMapper;
    @Value("${hos.esb.rest-url}")
    private String centerUrl;
    public Result onServiceFlowAdd(String msg) {
        try {
@ -247,18 +250,24 @@ public class ESBCamelService {
        }
        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);
//        FileOutputStream outputStream = ClassFileUtil.createFile(resource, handleFile.getPackageName(), handleFile.getClassName(), ClassFileUtil.JAVA_FILE);
//        String fileName = DES.decrypt(handleFile.getFilePath(), DES.COMMON_PASSWORD);
//        MongoDatabase db = mongoConfig.mongoClient().getDatabase(dbName);
//
//        boolean read = GridFSUtil.readFile(db, outputStream, fileName);
//        if (!read) {
//            logger.error("not mongo file, fileName:" + fileName);
//            return false;
//        }
        String fileName = DES.decrypt(handleFile.getFilePath(), DES.COMMON_PASSWORD);
        MongoDatabase db = mongoConfig.mongoClient().getDatabase(dbName);
        //从中心下载java文件
        String downUrl = centerUrl+"/tenant/down/"+handleFile.getFilePath();
        String sourcePath = ClassFileUtil.downFile(downUrl, resource, handleFile.getPackageName(), handleFile.getClassName(), ClassFileUtil.JAVA_FILE);
        boolean read = GridFSUtil.readFile(db, outputStream, fileName);
        if (!read) {
            logger.error("not mongo file, fileName:" + fileName);
        if (sourcePath==null){
            return false;
        }
        String sourcePath = ClassFileUtil.getFilePath(resource, handleFile.getPackageName(), handleFile.getClassName(), ClassFileUtil.JAVA_FILE);
        logger.info(sourcePath);
        boolean succ = CamelCompiler.compile(sourcePath, resource.getPath());
        if (succ){

+ 12 - 8
hos-broker/src/main/resources/application.yml

@ -31,12 +31,12 @@ spring:
    min-idle: 10
    initial-size: 10
  activemq:
      broker-url: tcp://172.19.103.86:61616
      broker-url: tcp://172.19.103.57:61616
      user: admin
      password: admin
  data:
    mongodb:
      host: 172.19.103.86
      host: 172.19.103.57
      port: 27017
      username: esb
      password: esb
@ -46,6 +46,8 @@ spring:
    ip: localhost
    port: 8066
hos:
  esb:
    rest-url: http://192.168.131.119:8080/esb
  arbiter:
    enable: true
    url: http://localhost:10135
@ -59,9 +61,9 @@ spring:
  profiles: test
  datasource:
      driverClassName: com.mysql.jdbc.Driver
      url: jdbc:mysql://192.168.1.220:3306/esb?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true
      username: hos2
      password: hos2
      url: jdbc:mysql://192.168.1.220:8066/hos1?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true
      username: hos
      password: 123456
      test-on-borrow: true
      validation-query: SELECT 1
      test-while-idle: true
@ -71,12 +73,12 @@ spring:
      min-idle: 10
      initial-size: 10
  activemq:
      broker-url: tcp://172.19.103.86:61616
      broker-url: tcp://172.19.103.57:61616
      user: admin
      password: admin
  data:
    mongodb:
      host: 172.19.103.86
      host: 172.19.103.57
      port: 27017
      username: esb
      password: esb
@ -86,9 +88,11 @@ spring:
    ip: localhost
    port: 8066
hos:
  esb:
    rest-url: http://192.168.131.119:8080/esb
  arbiter:
    enable: false
    url: http://172.19.103.89:10135
    url: http://172.19.103.57:10135
  timer:
      period: 10000

+ 76 - 0
hos-core/src/main/java/com/yihu/hos/core/datatype/ClassFileUtil.java

@ -1,12 +1,21 @@
package com.yihu.hos.core.datatype;
import com.yihu.hos.core.file.FileUtil;
import com.yihu.hos.core.log.Logger;
import com.yihu.hos.core.log.LoggerFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
public class ClassFileUtil {
@ -165,4 +174,71 @@ public class ClassFileUtil {
        String packagePath = StringUtil.replaceStrAll(packageName, ".", "/");
        return url.getPath() + packagePath + "/" + className + fileType;
    }
    /**
     * 下载文件,返回下载后的文件地址
     * @param downUrl        http请求地址
     * @param url            本地保存根目录
     * @param packageName   包名
     * @param className     类名
     * @param fileType      文件类型
     * @return
     */
    public static String downFile(String downUrl,URL url, String packageName, String className, String fileType) {
        try {
            String packagePath = StringUtil.replaceStrAll(packageName, ".", "/");
            File packageFile = new File(url.getPath() + "/" + packagePath);
            if (!packageFile.exists()) {
                boolean mkdirs = packageFile.mkdirs();
                if (!mkdirs) {
                    return null;
                }
            }
            String classPath = packageFile.getPath() + "/" + className + fileType;
            byte[] bytes = down(downUrl);//文件内容
            boolean succ = FileUtil.writeFile(classPath,bytes,"UTF-8");//写入文件
            if (succ){
                return classPath;
            }else {
                return null;
            }
        } catch (Exception e) {
            return null;
        }
    }
    /**
     *  http接口下载文件
     * @param url  请求地址
     * @return
     */
    public static byte[] down( String url) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet(url);
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        try {
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000*60*5).setConnectTimeout(1000*60*5).build();//设置请求和传输超时时间
            httpget.setConfig(requestConfig);
            response = httpClient.execute(httpget);
            response.setHeader( "Content-Type", "application/octet-stream;charset=UTF-8");
            entity = response.getEntity();
            byte[] bytes= FileUtil.getBytesByStream(entity.getContent());
            return bytes;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                EntityUtils.consume(entity);
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

+ 36 - 39
src/main/java/com/yihu/hos/config/BeanConfig.java

@ -2,10 +2,8 @@ package com.yihu.hos.config;
import com.yihu.hos.interceptor.AuditInterceptor;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.ApplicationContextException;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
@ -25,7 +23,6 @@ import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
@ -41,15 +38,15 @@ import java.util.Properties;
//@ImportResource({"classpath:spring/applicationContext.xml"}) //applicationContext相关bean创建
public class BeanConfig  implements EnvironmentAware {
//    @Autowired
//    BasicDataSource dataSource;
    @Autowired
    BasicDataSource dataSource;
    @Value("${spring.jpa.hibernate.dialect}")
    private String dialect;
    @Value("${spring.jpa.format-sql}")
    private String formatSql;
    @Value("${spring.jpa.show-sql}")
    private String showSql;
//    @Value("${spring.jpa.hibernate.dialect}")
//    private String dialect;
//    @Value("${spring.jpa.format-sql}")
//    private String formatSql;
//    @Value("${spring.jpa.show-sql}")
//    private String showSql;
    private Environment environment;
    private Map<String , Object> hibernatePropertyResolver;
@ -85,11 +82,11 @@ public class BeanConfig  implements EnvironmentAware {
    @Bean
    public LocalSessionFactoryBean sessionFactory()   {
        LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
        localSessionFactoryBean.setDataSource(dataSource());
        localSessionFactoryBean.setDataSource(this.dataSource);
        Properties properties1 = new Properties();
        properties1.setProperty("hibernate.dialect",dialect);
        properties1.setProperty("hibernate.show_sql", showSql);
        properties1.setProperty("hibernate.format_sql",formatSql);
        properties1.setProperty("hibernate.dialect","org.hibernate.dialect.MySQL5Dialect");
        properties1.setProperty("hibernate.show_sql", "false");
        properties1.setProperty("hibernate.format_sql","true");
        localSessionFactoryBean.setHibernateProperties(properties1);
        localSessionFactoryBean.setPackagesToScan("com.yihu.hos.*.model");
        ResourceLoader resourceLoader = new DefaultResourceLoader();
@ -100,28 +97,28 @@ public class BeanConfig  implements EnvironmentAware {
        return localSessionFactoryBean;
    }
    @Bean( destroyMethod = "close")
    public BasicDataSource dataSource() {
        if (StringUtils.isEmpty(datasourcePropertyResolver.get("url").toString())) {
            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.get("url").toString());
        dataSource.setUsername(datasourcePropertyResolver.get("username").toString());
        dataSource.setPassword(datasourcePropertyResolver.get("password").toString());
        dataSource.setInitialSize((Integer)datasourcePropertyResolver.get("initial-size"));
        dataSource.setMaxTotal((Integer)datasourcePropertyResolver.get("max-total"));
        dataSource.setMinIdle((Integer)datasourcePropertyResolver.get("min-idle"));
        dataSource.setMaxIdle((Integer)datasourcePropertyResolver.get("max-idle"));
        dataSource.setValidationQuery(datasourcePropertyResolver.get("validation-query").toString());
        dataSource.setRemoveAbandonedTimeout(55);
        dataSource.setTestOnBorrow((boolean)datasourcePropertyResolver.get("test-on-borrow"));
        return dataSource;
    }
//    @Bean( destroyMethod = "close")
//    public BasicDataSource dataSource() {
//        if (StringUtils.isEmpty(datasourcePropertyResolver.get("url").toString())) {
//            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.get("url").toString());
//        dataSource.setUsername(datasourcePropertyResolver.get("username").toString());
//        dataSource.setPassword(datasourcePropertyResolver.get("password").toString());
//        dataSource.setInitialSize((Integer)datasourcePropertyResolver.get("initial-size"));
//        dataSource.setMaxTotal((Integer)datasourcePropertyResolver.get("max-total"));
//        dataSource.setMinIdle((Integer)datasourcePropertyResolver.get("min-idle"));
//        dataSource.setMaxIdle((Integer)datasourcePropertyResolver.get("max-idle"));
//        dataSource.setValidationQuery(datasourcePropertyResolver.get("validation-query").toString());
//        dataSource.setRemoveAbandonedTimeout(55);
//        dataSource.setTestOnBorrow((boolean)datasourcePropertyResolver.get("test-on-borrow"));
//        return dataSource;
//    }
    //txManager事务开启
    @Bean
@ -167,7 +164,7 @@ public class BeanConfig  implements EnvironmentAware {
    public JdbcTemplate jdbcTemplate(){
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        try {
            jdbcTemplate.setDataSource(this.dataSource());
            jdbcTemplate.setDataSource(this.dataSource);
            jdbcTemplate.setLazyInit(false);
        } catch (Exception e) {
            e.printStackTrace();

+ 1 - 0
src/main/java/com/yihu/hos/filter/SessionOutTimeFilter.java

@ -31,6 +31,7 @@ public class SessionOutTimeFilter extends OncePerRequestFilter {
                || path.indexOf(httpServletRequest.getContextPath() + "/rest") != -1
                || path.indexOf("swagger") != -1
                || path.indexOf(httpServletRequest.getContextPath() + "/v2/api-docs") != -1
                || path.indexOf("/tenant/down") != -1
                || path.indexOf(httpServletRequest.getContextPath() + "/mobile") != -1) {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;

+ 37 - 0
src/main/java/com/yihu/hos/tenant/controller/TenantController.java

@ -8,11 +8,15 @@ import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@ -177,4 +181,37 @@ public class TenantController extends BaseController{
        }
    }
    /**
     *  //TODO 后 独立到对应的rest接口中
     * 文件下载
     * @return
     */
    @RequestMapping(value = "/down/{fileName}", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public Object down(HttpServletResponse response, @PathVariable("fileName")  String fileName) {
        try {
            OutputStream os = response.getOutputStream();
            return tenantService.readFile(os, fileName);
        } catch (Exception e) {
            return Result.error("下载文件失败!");
        }
    }
    /**
     *  //TODO 后 独立到对应的rest接口中
     * 删除文件
     * @return
     */
    @RequestMapping(value = "/delFile/{fileName}", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public Object delFile(HttpServletResponse response, @PathVariable("fileName")  String fileName) {
        try {
            OutputStream os = response.getOutputStream();
            return tenantService.readFile(os, fileName);
        } catch (Exception e) {
            return Result.error("下载文件失败!");
        }
    }
}

+ 18 - 0
src/main/java/com/yihu/hos/tenant/service/TenantService.java

@ -1,12 +1,16 @@
package com.yihu.hos.tenant.service;
import com.yihu.hos.config.MongoConfig;
import com.yihu.hos.core.encrypt.DES;
import com.yihu.hos.tenant.dao.TenantDao;
import com.yihu.hos.tenant.model.TenantModel;
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 java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;
@ -25,6 +29,9 @@ public class TenantService {
    @Autowired
    private TenantDao tenantDao;
    @Autowired
    private MongoConfig mongoConfig;
    public TenantModel findTenantByName(String name) throws Exception {
        List<TenantModel> list = tenantDao.getTenantList(name);
@ -74,5 +81,16 @@ public class TenantService {
        return Result.success("删除成功");
    }
    public Result readFile(OutputStream os, String fileName) {
        String dbName = "upload";
        try {
            fileName = DES.decrypt(fileName, DES.COMMON_PASSWORD);
            GridFSUtil.readFile(mongoConfig.mongoClient().getDatabase(dbName), os, fileName);
            return Result.success("读取成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("读取失败");
    }
}