浏览代码

Merge branch 'master' of luofaqiang/esb into master

luofaqiang 8 年之前
父节点
当前提交
ea75b1530c
共有 31 个文件被更改,包括 905 次插入951 次删除
  1. 17 43
      hos-broker/src/main/java/com/yihu/hos/broker/services/camel/ESBCamelService.java
  2. 4 4
      hos-broker/src/main/resources/application.yml
  3. 5 0
      hos-core/pom.xml
  4. 59 43
      hos-core/src/main/java/com/yihu/hos/core/datatype/ClassFileUtil.java
  5. 25 0
      hos-core/src/main/java/com/yihu/hos/core/http/DefaultClientImpl.java
  6. 2 0
      hos-core/src/main/java/com/yihu/hos/core/http/HTTPClient.java
  7. 9 1
      hos-core/src/main/java/com/yihu/hos/core/http/HttpClientKit.java
  8. 16 0
      hos-core/src/test/java/com/yihu/hos/core/http/HttpClientKitTest.java
  9. 24 0
      hos-dfs/.gitignore
  10. 233 0
      hos-dfs/mvnw
  11. 145 0
      hos-dfs/mvnw.cmd
  12. 55 0
      hos-dfs/pom.xml
  13. 31 0
      hos-dfs/src/main/java/com/yihu/com/hos/HosDfsApplication.java
  14. 0 57
      hos-dfs/src/main/java/com/yihu/com/hos/configuration/MongoConfig.java
  15. 28 50
      hos-dfs/src/main/java/com/yihu/com/hos/controller/DFSController.java
  16. 91 31
      hos-dfs/src/main/java/com/yihu/com/hos/service/DFSService.java
  17. 0 385
      hos-dfs/src/main/java/com/yihu/com/hos/service/GridFSUtil.java
  18. 21 0
      hos-dfs/src/main/resources/application.yml
  19. 16 0
      hos-dfs/src/test/java/com/yihu/com/hos/HosFdsApplicationTests.java
  20. 5 0
      hos-parent/pom.xml
  21. 52 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/util/DFSUtil.java
  22. 1 26
      src/main/java/com/yihu/hos/ESBApplication.java
  23. 10 44
      src/main/java/com/yihu/hos/config/BeanConfig.java
  24. 2 2
      src/main/java/com/yihu/hos/remoteManage/controller/RemoteShellController.java
  25. 1 1
      src/main/java/com/yihu/hos/remoteManage/service/RemoteShellService.java
  26. 0 33
      src/main/java/com/yihu/hos/system/controller/AppController.java
  27. 0 43
      src/main/java/com/yihu/hos/system/controller/FlowController.java
  28. 0 27
      src/main/java/com/yihu/hos/system/service/AppManager.java
  29. 50 150
      src/main/java/com/yihu/hos/system/service/FlowManager.java
  30. 3 4
      src/main/resources/application.yml
  31. 0 7
      src/test/java/com/yihu/hos/HosAdminApplicationTests.java

+ 17 - 43
hos-broker/src/main/java/com/yihu/hos/broker/services/camel/ESBCamelService.java

@ -53,8 +53,8 @@ public class ESBCamelService {
    private String configuration = "runtime";
    @Autowired
    private ObjectMapper objectMapper;
    @Value("${hos.esb.rest-url}")
    private String centerUrl;
    @Value("${hos.filesystem.url}")
    private String fsUrl;
    @Value("${spring.data.mongodb.gridFsDatabase}")
    private String dbName;
@ -166,7 +166,7 @@ public class ESBCamelService {
                    String routeCode = serviceFlow.getRouteCode();
                    SystemCamelContext.getContext().stopRoute(routeCode);
                    SystemCamelContext.getContext().removeRoute(routeCode);
                    this.deleteClassFile(handleFile);  //清理文件?
                    this.deleteClassFile(handleFile);
                    this.deleteServiceFlow(handleFile.getRouteCode());//删除mongo中serviceFlow信息
                    //TODO 删除mongodb中文件
                }
@ -236,15 +236,13 @@ public class ESBCamelService {
        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);
//        MongoDatabase db = mongoConfig.mongoClient().getDatabase(dbName);
        String fileName = handleFile.getClassName() + ClassFileUtil.CLASS_FILE;
//        boolean read = GridFSUtil.readFile(db, outputStream, fileName);
        //从中心下载
        String downUrl = centerUrl + "/tenant/down/" + handleFile.getFilePath();
        String sourcePath =  ClassFileUtil.downFile(downUrl, resource, handleFile.getPackageName(), handleFile.getClassName(), ClassFileUtil.CLASS_FILE);
        String downUrl = fsUrl + "/" + handleFile.getFilePath();
        String sourcePath = ClassFileUtil.downFile(downUrl, resource, handleFile.getPackageName(), handleFile.getClassName(), ClassFileUtil.CLASS_FILE);
        if (sourcePath==null) {
        if (sourcePath == null) {
            logger.error("not mongo file, fileName:" + fileName);
            return false;
        }
@ -258,18 +256,10 @@ 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);
//        MongoDatabase db = mongoConfig.mongoClient().getDatabase(dbName);
//
//        boolean read = GridFSUtil.readFileContent(db, outputStream, fileName);
//        if (!read) {
//            logger.error("not mongo file, fileName:" + fileName);
//            return false;
//        }
        //从中心下载java文件
        String downUrl = centerUrl + "/tenant/down/" + handleFile.getFilePath();
        String sourcePath =  ClassFileUtil.downFile(downUrl, resource, handleFile.getPackageName(), handleFile.getClassName(), ClassFileUtil.JAVA_FILE);
        String downUrl = fsUrl + "/" + handleFile.getFilePath();
        String sourcePath = ClassFileUtil.downFile(downUrl, resource, handleFile.getPackageName(), handleFile.getClassName(), ClassFileUtil.JAVA_FILE);
        if (sourcePath == null) {
            return false;
@ -280,40 +270,24 @@ public class ESBCamelService {
        if (succ) {
            //编译成功后将class文件上传至mongodb;文件名为类名+ routeCode
            String packagePath = StringUtil.replaceStrAll(handleFile.getPackageName(), ".", "/");
            String classPath =  resource.getPath()+ packagePath + "/" + handleFile.getClassName() + ClassFileUtil.CLASS_FILE;
//            GridFSUtil.uploadFile(classPath, handleFile.getClassName() + handleFile.getRouteCode() + ClassFileUtil.CLASS_FILE, null);
//            TODO 上传到本地mongodb和中心mongodb
            String fileName = DES.decrypt(handleFile.getFilePath(), DES.COMMON_PASSWORD).replaceAll(ClassFileUtil.JAVA_FILE,ClassFileUtil.CLASS_FILE);
            String enFileName = DES.encrypt(fileName, DES.COMMON_PASSWORD);
            String uploadUrl = centerUrl + "/tenant/upload/" + enFileName;
            ClassFileUtil.uploadFile(uploadUrl,new File(classPath),fileName);
            String classPath = resource.getPath() + packagePath + "/" + handleFile.getClassName() + ClassFileUtil.CLASS_FILE;
            //上传文件
            String fileName = handleFile.getClassName() + ClassFileUtil.CLASS_FILE;
            String uploadUrl = fsUrl + "/" + handleFile.getFilePath();
            ClassFileUtil.uploadFile(uploadUrl, new File(classPath), fileName);
        }
        return succ;
    }
    private void deleteClassFile(ServiceFlow.HandleFile handleFile) throws Exception {
//        String className = SystemCamelContext.getClassMapping(handleFile.getRouteCode(), handleFile.getClassName(), handleFile.getUsage());
//        if (StringUtil.isEmpty(className)) {
//            return;
//        }
        String packagePath = StringUtil.replaceStrAll(handleFile.getPackageName(), ".", "/");
        String classPath = ClassLoader.getSystemResource("").getPath() + "/" + packagePath + "/" + handleFile.getClassName() + ".class";
        String javaPath = ClassLoader.getSystemResource("").getPath() + "/" + packagePath + "/" + handleFile.getClassName() + ".java";
        ClassFileUtil.deleteClassfile(classPath);
        ClassFileUtil.deleteClassfile(javaPath);
        //TODO 从中心删除
        //删除class文件
        String delJavaUrl = centerUrl + "/tenant/delFile/" + handleFile.getFilePath();
        String delJavaUrl = fsUrl + "/" + handleFile.getFilePath();
        ClassFileUtil.deleteFile(delJavaUrl);
        //删除java文件
        String classFilePath = DES.decrypt( handleFile.getFilePath(),DES.COMMON_PASSWORD);
        String javaFilePath = classFilePath.replace(ClassFileUtil.CLASS_FILE,ClassFileUtil.JAVA_FILE);
        String enJavaPath = DES.encrypt(javaFilePath,DES.COMMON_PASSWORD);
        String delClassUrl = centerUrl + "/tenant/delFile/" + enJavaPath;
         ClassFileUtil.deleteFile(delClassUrl);
        // 完成
        logger.info("===================" + handleFile.getPackageName() + CoreConstant.DOT + handleFile.getClassName() + ".class 删除过程结束");
    }

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

@ -34,8 +34,8 @@ spring:
    ip: localhost
    port: 8066
hos:
  esb:
    rest-url: http://localhost:8080/esb
  filesystem:
    url: 127.0.0.1:9010/dfs/file
  arbiter:
    enable: true
    url: http://localhost:10135
@ -74,8 +74,8 @@ spring:
    ip: localhost
    port: 8066
hos:
  esb:
    rest-url: http://172.19.103.67:8080/esb
  filesystem:
    url: 127.0.0.1:9010/dfs/file
  arbiter:
    enable: true
    url: http://172.19.103.67:10135

+ 5 - 0
hos-core/pom.xml

@ -107,6 +107,11 @@
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

+ 59 - 43
hos-core/src/main/java/com/yihu/hos/core/datatype/ClassFileUtil.java

@ -3,6 +3,8 @@ package com.yihu.hos.core.datatype;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.hos.core.file.FileUtil;
import com.yihu.hos.core.http.HTTPResponse;
import com.yihu.hos.core.http.HttpClientKit;
import com.yihu.hos.core.log.Logger;
import com.yihu.hos.core.log.LoggerFactory;
import org.apache.http.HttpEntity;
@ -182,14 +184,15 @@ public class ClassFileUtil {
    /**
     * 下载文件,返回下载后的文件地址
     * @param downUrl        http请求地址
     * @param url            本地保存根目录
     * @param packageName   包名
     * @param className     类名
     * @param 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) {
    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);
@ -202,10 +205,10 @@ public class ClassFileUtil {
            String classPath = packageFile.getPath() + "/" + className + fileType;
            byte[] bytes = down(downUrl);//文件内容
            boolean succ = FileUtil.writeFile(classPath,bytes,"UTF-8");//写入文件
            if (succ){
            boolean succ = FileUtil.writeFile(classPath, bytes, "UTF-8");//写入文件
            if (succ) {
                return classPath;
            }else {
            } else {
                return null;
            }
        } catch (Exception e) {
@ -214,12 +217,12 @@ public class ClassFileUtil {
    }
    public static String uploadFile(String uploadUrl, File file,String fileName) {
    public static String uploadFile(String uploadUrl, File file, String fileName) {
        try {
            boolean succ = upload(uploadUrl, file,fileName);//文件内容
            if (succ){
            boolean succ = upload(uploadUrl, file, fileName);//文件内容
            if (succ) {
                return fileName;
            }else {
            } else {
                return null;
            }
        } catch (Exception e) {
@ -228,22 +231,23 @@ public class ClassFileUtil {
    }
    /**
     *  http接口下载文件
     * @param url  请求地址
     * http接口下载文件
     *
     * @param url 请求地址
     * @return
     */
    public static byte[] down( String url) {
    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();//设置请求和传输超时时间
            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");
            response.setHeader("Content-Type", "application/octet-stream;charset=UTF-8");
            entity = response.getEntity();
            byte[] bytes= FileUtil.getBytesByStream(entity.getContent());
            byte[] bytes = FileUtil.getBytesByStream(entity.getContent());
            return bytes;
        } catch (IOException e) {
            e.printStackTrace();
@ -259,38 +263,48 @@ public class ClassFileUtil {
        return null;
    }
    public static String upload(String url, File file) {
        HTTPResponse response = HttpClientKit.postFile(url, "file", file.toString(), "text/plain");
        if (response.getStatusCode() != 200) {
            return null;
        }
        return response.getBody();
    }
    /**
     *  http 上传文件到中心请求
     * http 上传文件到中心请求
     *
     * @param url  请求地址
     * @param file  文件名
     * @param file 文件名
     * @return
     */
    public static boolean upload( String url,File file,String fileName) {
    public static boolean upload(String url, File file, String fileName) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        try {
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000*60*5).setConnectTimeout(1000*60*5).build();//设置请求和传输超时时间
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000 * 60 * 5).setConnectTimeout(1000 * 60 * 5).build();//设置请求和传输超时时间
            httpPost.setConfig(requestConfig);
            MultipartEntityBuilder reqEntity1 = MultipartEntityBuilder.create();
            reqEntity1.addBinaryBody("pack", file);
            reqEntity1.addTextBody("fileName",fileName, ContentType.create("text/plain", Charset.forName("UTF-8")));
            reqEntity1.addBinaryBody("file", file);
            reqEntity1.addTextBody("fileName", fileName, ContentType.create("text/plain", Charset.forName("UTF-8")));
            httpPost.setEntity(reqEntity1.build());
            response = httpClient.execute(httpPost);
            response.setHeader( "Content-Type", "application/json;charset=UTF-8");
            response.setHeader("Content-Type", "application/json;charset=UTF-8");
            entity = response.getEntity();
            int code = response.getStatusLine().getStatusCode();
            Map<String,Object> responMap = parseRespon(entity);
            if (code == 200){
            Map<String, Object> responMap = parseRespon(entity);
            if (code == 200) {
                boolean succ = (boolean) responMap.get("successFlg");
                if (!succ){
                    System.out.println("请求成功,上传失败!message:"+responMap.get("message").toString());;
                if (!succ) {
                    System.out.println("请求成功,上传失败!message:" + responMap.get("message").toString());
                    ;
                }
                return succ;
            }else {
                System.out.println("上传请求失败,status:"+code);
            } else {
                System.out.println("上传请求失败,status:" + code);
                return false;
            }
        } catch (IOException e) {
@ -309,30 +323,32 @@ public class ClassFileUtil {
    /**
     * http请求 从管理中心删除文件
     *
     * @param url
     * @return
     */
    public static boolean deleteFile( String url) {
    public static boolean deleteFile(String url) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        try {
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000*60*5).setConnectTimeout(1000*60*5).build();//设置请求和传输超时时间
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000 * 60 * 5).setConnectTimeout(1000 * 60 * 5).build();//设置请求和传输超时时间
            httpPost.setConfig(requestConfig);
            response = httpClient.execute(httpPost);
            response.setHeader( "Content-Type", "application/json;charset=UTF-8");
            response.setHeader("Content-Type", "application/json;charset=UTF-8");
            entity = response.getEntity();
            int code = response.getStatusLine().getStatusCode();
            Map<String,Object> responMap = parseRespon(entity);
            if (code == 200){
            Map<String, Object> responMap = parseRespon(entity);
            if (code == 200) {
                boolean succ = (boolean) responMap.get("successFlg");
                if (!succ){
                    System.out.println("请求成功,删除失败!message:"+responMap.get("message").toString());;
                if (!succ) {
                    System.out.println("请求成功,删除失败!message:" + responMap.get("message").toString());
                    ;
                }
                return succ;
            }else {
                System.out.println("删除请求失败,status:"+code);
            } else {
                System.out.println("删除请求失败,status:" + code);
                return false;
            }
        } catch (IOException e) {
@ -350,7 +366,7 @@ public class ClassFileUtil {
    }
    public static  Map<String,Object> parseRespon(HttpEntity entity ) throws IOException {
    public static Map<String, Object> parseRespon(HttpEntity entity) throws IOException {
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
        String line = null;
@ -359,7 +375,7 @@ public class ClassFileUtil {
        }
        String responseText = stringBuilder.toString();
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String,Object> map = objectMapper.readValue(responseText,Map.class);
        Map<String, Object> map = objectMapper.readValue(responseText, Map.class);
        return map;
    }

+ 25 - 0
hos-core/src/main/java/com/yihu/hos/core/http/DefaultClientImpl.java

@ -151,6 +151,31 @@ class DefaultClientImpl implements HTTPClient {
        return new HTTPResponse(417, "");
    }
    @Override
    public HTTPResponse postFile(String url, String key, String path, String contentType) {
        try {
            File file = new File(path);
            final MediaType type = MediaType.parse(contentType);
            Request.Builder requestBuilder = new Request.Builder();
            MultipartBody.Builder multipartBuilder = new MultipartBody.Builder();
            multipartBuilder.setType(MultipartBody.FORM)
                    .addFormDataPart(key, file.getName(), RequestBody.create(type, file));
            Request request = requestBuilder
                    .url(url)
                    .post(multipartBuilder.build())
                    .build();
            Response response = httpClient.newCall(request).execute();
            return new HTTPResponse(response.code(), response.body().string());
        } catch (IOException ex) {
            log.error(ex.getMessage());
        }
        return new HTTPResponse(417, "");
    }
    public HTTPResponse put(String url) {
        return put(url, (Map<String, String>) null);
    }

+ 2 - 0
hos-core/src/main/java/com/yihu/hos/core/http/HTTPClient.java

@ -32,6 +32,8 @@ public interface HTTPClient {
    HTTPResponse postFile(String url, String path, Map<String, String> params, Map<String, String> headers);
    HTTPResponse postFile(String url, String key, String path, String contentType);
    HTTPResponse put(String url);
    HTTPResponse put(String url, Map<String, String> params);

+ 9 - 1
hos-core/src/main/java/com/yihu/hos/core/http/HttpClientKit.java

@ -76,7 +76,7 @@ public class HttpClientKit {
        return use().post(url, json, null);
    }
    public static HTTPResponse post(String url, String json, Map<String, String> headers){
    public static HTTPResponse post(String url, String json, Map<String, String> headers) {
        return use().post(url, json, headers);
    }
@ -96,6 +96,14 @@ public class HttpClientKit {
        }
    }
    public static HTTPResponse postFile(String url, String key, String path, String contentType) {
        if (url.startsWith("https")) {
            return custom(url).postFile(url, key, path, contentType);
        } else {
            return use().postFile(url, key, path, contentType);
        }
    }
    public static HTTPResponse postFile(String url, String path, Map<String, String> params, Map<String, String> headers) {
        if (url.startsWith("https")) {
            return custom(url).postFile(url, path, params, headers);

+ 16 - 0
hos-core/src/test/java/com/yihu/hos/core/http/HttpClientKitTest.java

@ -0,0 +1,16 @@
package com.yihu.hos.core.http;
import org.junit.Test;
/**
 * Created by l4qiang on 2017-04-12.
 */
public class HttpClientKitTest {
    @Test
    public void postFile() throws Exception {
        HTTPResponse response = HttpClientKit.postFile("http://127.0.0.1:9010/dfs/file", "file", "e:/ss.jpg", "plain/text");
        System.out.println(response.getBody());
    }
}

+ 24 - 0
hos-dfs/.gitignore

@ -0,0 +1,24 @@
target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
nbproject/private/
build/
nbbuild/
dist/
nbdist/
.nb-gradle/

+ 233 - 0
hos-dfs/mvnw

@ -0,0 +1,233 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven2 Start Up Batch script
#
# Required ENV vars:
# ------------------
#   JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
#   M2_HOME - location of maven2's installed home dir
#   MAVEN_OPTS - parameters passed to the Java VM when running Maven
#     e.g. to debug Maven itself, use
#       set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
#   MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
  if [ -f /etc/mavenrc ] ; then
    . /etc/mavenrc
  fi
  if [ -f "$HOME/.mavenrc" ] ; then
    . "$HOME/.mavenrc"
  fi
fi
# OS specific support.  $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
  CYGWIN*) cygwin=true ;;
  MINGW*) mingw=true;;
  Darwin*) darwin=true
           #
           # Look for the Apple JDKs first to preserve the existing behaviour, and then look
           # for the new JDKs provided by Oracle.
           #
           if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then
             #
             # Apple JDKs
             #
             export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home
           fi
           if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then
             #
             # Apple JDKs
             #
             export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
           fi
           if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then
             #
             # Oracle JDKs
             #
             export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
           fi
           if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then
             #
             # Apple JDKs
             #
             export JAVA_HOME=`/usr/libexec/java_home`
           fi
           ;;
esac
if [ -z "$JAVA_HOME" ] ; then
  if [ -r /etc/gentoo-release ] ; then
    JAVA_HOME=`java-config --jre-home`
  fi
fi
if [ -z "$M2_HOME" ] ; then
  ## resolve links - $0 may be a link to maven's home
  PRG="$0"
  # need this for relative symlinks
  while [ -h "$PRG" ] ; do
    ls=`ls -ld "$PRG"`
    link=`expr "$ls" : '.*-> \(.*\)$'`
    if expr "$link" : '/.*' > /dev/null; then
      PRG="$link"
    else
      PRG="`dirname "$PRG"`/$link"
    fi
  done
  saveddir=`pwd`
  M2_HOME=`dirname "$PRG"`/..
  # make it fully qualified
  M2_HOME=`cd "$M2_HOME" && pwd`
  cd "$saveddir"
  # echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
  [ -n "$M2_HOME" ] &&
    M2_HOME=`cygpath --unix "$M2_HOME"`
  [ -n "$JAVA_HOME" ] &&
    JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
  [ -n "$CLASSPATH" ] &&
    CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Migwn, ensure paths are in UNIX format before anything is touched
if $mingw ; then
  [ -n "$M2_HOME" ] &&
    M2_HOME="`(cd "$M2_HOME"; pwd)`"
  [ -n "$JAVA_HOME" ] &&
    JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
  # TODO classpath?
fi
if [ -z "$JAVA_HOME" ]; then
  javaExecutable="`which javac`"
  if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
    # readlink(1) is not available as standard on Solaris 10.
    readLink=`which readlink`
    if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
      if $darwin ; then
        javaHome="`dirname \"$javaExecutable\"`"
        javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
      else
        javaExecutable="`readlink -f \"$javaExecutable\"`"
      fi
      javaHome="`dirname \"$javaExecutable\"`"
      javaHome=`expr "$javaHome" : '\(.*\)/bin'`
      JAVA_HOME="$javaHome"
      export JAVA_HOME
    fi
  fi
fi
if [ -z "$JAVACMD" ] ; then
  if [ -n "$JAVA_HOME"  ] ; then
    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
      # IBM's JDK on AIX uses strange locations for the executables
      JAVACMD="$JAVA_HOME/jre/sh/java"
    else
      JAVACMD="$JAVA_HOME/bin/java"
    fi
  else
    JAVACMD="`which java`"
  fi
fi
if [ ! -x "$JAVACMD" ] ; then
  echo "Error: JAVA_HOME is not defined correctly." >&2
  echo "  We cannot execute $JAVACMD" >&2
  exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
  echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
  [ -n "$M2_HOME" ] &&
    M2_HOME=`cygpath --path --windows "$M2_HOME"`
  [ -n "$JAVA_HOME" ] &&
    JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
  [ -n "$CLASSPATH" ] &&
    CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
fi
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
  local basedir=$(pwd)
  local wdir=$(pwd)
  while [ "$wdir" != '/' ] ; do
    if [ -d "$wdir"/.mvn ] ; then
      basedir=$wdir
      break
    fi
    wdir=$(cd "$wdir/.."; pwd)
  done
  echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
  if [ -f "$1" ]; then
    echo "$(tr -s '\n' ' ' < "$1")"
  fi
}
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)}
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
  $MAVEN_OPTS \
  -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
  "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
  ${WRAPPER_LAUNCHER} "$@"

+ 145 - 0
hos-dfs/mvnw.cmd

@ -0,0 +1,145 @@
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements.  See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership.  The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License.  You may obtain a copy of the License at
@REM
@REM    http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied.  See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven2 Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM     e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on"  echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
set MAVEN_CMD_LINE_ARGS=%*
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="".\.mvn\wrapper\maven-wrapper.jar""
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS%
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%

+ 55 - 0
hos-dfs/pom.xml

@ -0,0 +1,55 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.yihu.hos</groupId>
        <artifactId>hos-parent</artifactId>
        <version>1.3.0</version>
        <relativePath>../hos-parent</relativePath>
    </parent>
    <artifactId>hos-dfs</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>hos-dfs</name>
    <description>hos file and mq moddule</description>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
        </dependency>
        <dependency>
            <groupId>org.zbus</groupId>
            <artifactId>zbus</artifactId>
        </dependency>
    </dependencies>
</project>

+ 31 - 0
hos-dfs/src/main/java/com/yihu/com/hos/HosDfsApplication.java

@ -0,0 +1,31 @@
package com.yihu.com.hos;
import com.yihu.com.hos.configuration.ZbusConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.zbus.mq.server.MqServer;
import org.zbus.mq.server.MqServerConfig;
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class HosDfsApplication implements CommandLineRunner {
    @Autowired
    private ZbusConfiguration zbusConfiguration;
    public static void main(String[] args) {
        SpringApplication.run(HosDfsApplication.class, args);
    }
    @Override
    public void run(String... strings) throws Exception {
        MqServerConfig config = new MqServerConfig();
        config.serverPort = zbusConfiguration.getZbusPort();
        config.storePath = zbusConfiguration.getZbusStore();
        final MqServer server = new MqServer(config);
        server.start();
        System.out.println("zbus 启动成功!");
    }
}

+ 0 - 57
hos-dfs/src/main/java/com/yihu/com/hos/configuration/MongoConfig.java

@ -1,57 +0,0 @@
package com.yihu.com.hos.configuration;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import static java.util.Collections.singletonList;
/**
 * @created Airhead 2016/7/27.
 */
@Configuration
public class MongoConfig {
    @Value("${spring.data.mongodb.host}")
    private String host;
    @Value("${spring.data.mongodb.port}")
    private int port;
    @Value("${spring.data.mongodb.username}")
    private String username;
    @Value("${spring.data.mongodb.password}")
    private String password;
    @Value("${spring.data.mongodb.authenticationDatabase}")
    private String authenticationDatabase;
    @Bean
    public MongoClient mongoClient() throws Exception {
        return new MongoClient(singletonList(new ServerAddress(host, port)),
                singletonList(MongoCredential.createCredential(username, authenticationDatabase, password.toCharArray())));
    }
    @Bean
    public Mongo mongo() throws Exception {
        return new MongoClient(singletonList(new ServerAddress(host, port)),
                singletonList(MongoCredential.createCredential(username, authenticationDatabase, password.toCharArray())));
    }
    public String getHost() {
        return host;
    }
    public int getPort() {
        return port;
    }
    public String getUsername() {
        return username;
    }
    public String getPassword() {
        return password;
    }
}

+ 28 - 50
hos-dfs/src/main/java/com/yihu/com/hos/controller/DFSController.java

@ -1,73 +1,51 @@
package com.yihu.com.hos.controller;
import com.yihu.com.hos.service.DFSService;
import com.yihu.hos.web.framework.model.Result;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
/**
 * 基于Mongo的文件系统
 * <p>
 * Created by l4qiang on 2017-04-10.
 */
@RestController
@RequestMapping(value = "/dfs")
public class DFSController {
    @Autowired
    private DFSService dfsService;
    /**
     *  //TODO 后 独立到对应的rest接口中
     * 上传文件
     * @param response
     * @param fileName
     * @return
     */
    @RequestMapping(value = "/upload/{fileName}", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public Object upload(
            HttpServletResponse response, @PathVariable("fileName")  String fileName,
            @ApiParam(name = "pack", value = "文件", allowMultiple = true)
            @RequestPart() MultipartFile pack
    ) {
        try {
            return dfsService.uploadFile(pack.getInputStream(), fileName);
        } catch (Exception e) {
            return Result.error("上传文件出错!");
        }
    @RequestMapping(value = "file/{fileId}/info", method = RequestMethod.GET)
    public ResponseEntity info(@PathVariable("fileId") String fileId) {
        return dfsService.info(fileId);
    }
    @RequestMapping(value = "file/{fileId}", method = RequestMethod.GET)
    public ResponseEntity retrieve(@PathVariable("fileId") String fileId, HttpServletResponse httpServletResponse) {
        return dfsService.retrieve(fileId, httpServletResponse);
    }
    @RequestMapping(value = "file/{fileId}/download", method = RequestMethod.GET)
    public ResponseEntity download(@PathVariable("fileId") String fileId) {
        return dfsService.download(fileId);
    }
    /**
     *  //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 dfsService.dowFile(os, fileName);
        } catch (Exception e) {
            return Result.error("下载文件出错!");
        }
    @RequestMapping(value = "file", method = RequestMethod.POST)
    public ResponseEntity store(@RequestPart MultipartFile file) {
        return dfsService.store(file);
    }
    /**
     *  //TODO 后 独立到对应的rest接口中
     * 删除文件
     * @return
     */
    @RequestMapping(value = "/delFile/{fileName}", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public Object delFile(HttpServletResponse response, @PathVariable("fileName")  String fileName) {
        try {
            return dfsService.delFile(fileName);
        } catch (Exception e) {
            return Result.error("下载文件失败!");
        }
    @RequestMapping(value = "file/{fileId}", method = RequestMethod.POST)
    public ResponseEntity update(@PathVariable("fileId") String fileId, @RequestParam("file") MultipartFile file) {
        return dfsService.update(fileId, file);
    }
    @RequestMapping(value = "file/{fileId}", method = RequestMethod.DELETE)
    public ResponseEntity delete(@PathVariable("fileId") String fileId) {
        return dfsService.delete(fileId);
    }
}

+ 91 - 31
hos-dfs/src/main/java/com/yihu/com/hos/service/DFSService.java

@ -1,68 +1,128 @@
package com.yihu.com.hos.service;
import com.yihu.com.hos.configuration.MongoConfig;
import com.yihu.hos.core.encrypt.DES;
import com.yihu.hos.web.framework.model.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSFile;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsOperations;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Optional;
/**
 * Mongodb file system
 * Created by l4qiang on 2017-04-10.
 */
@Service
public class DFSService {
    @Autowired
    private GridFsOperations operations;
    private GridFsOperations gridFsOperations;
    @Autowired
    private MongoConfig mongoConfig;
    private ObjectMapper objectMapper;
    public Result dowFile(OutputStream os, String fileName) {
    public ResponseEntity info(String fileId) {
        try {
            fileName = DES.decrypt(fileName, DES.COMMON_PASSWORD);
            boolean succ = GridFSUtil.readFile(mongoConfig.mongoClient().getDatabase("dfs"), os, fileName);
            if (succ) {
                return Result.success("读取文件成功");
            } else {
                return Result.success("读取文件失败");
            Query query = Query.query(Criteria.where("_id").is(new ObjectId(fileId)));
            GridFSDBFile gridFSDBFile = gridFsOperations.findOne(query);
            if (gridFSDBFile == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body("file was not found");
            }
            ObjectNode objectNode = objectMapper.createObjectNode();
            objectNode.put("id", gridFSDBFile.getId().toString());
            objectNode.put("filename", gridFSDBFile.getFilename());
            objectNode.put("contentType", gridFSDBFile.getContentType());
            objectNode.put("length", gridFSDBFile.getLength());
            objectNode.put("uploadDate", gridFSDBFile.getUploadDate().toString());
//            objectNode.put("aliases", gridFSDBFile.getAliases().toString());
            objectNode.put("md5", gridFSDBFile.getMD5());
            String info = objectMapper.writeValueAsString(objectNode);
            return ResponseEntity.ok()
                    .body(info);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("读取文件异常");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
    }
    public Result uploadFile(InputStream inputStream, String fileName) {
    public ResponseEntity retrieve(String fileId, HttpServletResponse httpServletResponse) {
        try {
            fileName = DES.decrypt(fileName, DES.COMMON_PASSWORD);
            String saveFileName = GridFSUtil.uploadFile(inputStream, fileName, null);
            if (saveFileName != null) {
                return Result.success("上传文件成功");
            } else {
                return Result.error("上传文件失败");
            Query query = Query.query(Criteria.where("_id").is(new ObjectId(fileId)));
            GridFSDBFile gridFSDBFile = gridFsOperations.findOne(query);
            if (gridFSDBFile == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body("file was not found");
            }
            ServletOutputStream outputStream = httpServletResponse.getOutputStream();
            org.apache.commons.io.IOUtils.copy(gridFSDBFile.getInputStream(), outputStream);
            outputStream.close();
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("上传文件异常");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
    }
    public Result delFile(String fileName) {
    public ResponseEntity download(String fileId) {
        Query query = Query.query(Criteria.where("_id").is(new ObjectId(fileId)));
        GridFSDBFile gridFSDBFile = gridFsOperations.findOne(query);
        if (gridFSDBFile == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("file was not found");
        }
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; fileName=\"" + gridFSDBFile.getFilename() + "\"")
                .body(Optional.of(gridFSDBFile.getInputStream()));
    }
    public ResponseEntity store(MultipartFile file) {
        try {
            fileName = DES.decrypt(fileName, DES.COMMON_PASSWORD);
            boolean succ = GridFSUtil.deleteFile(fileName);
            if (succ) {
                return Result.success("删除文件成功");
            } else {
                return Result.success("删除文件失败");
            InputStream inputStream = file.getInputStream();
            String fileName = file.getOriginalFilename();
            GridFSFile gridFSFile = gridFsOperations.store(inputStream, fileName);
            if (gridFSFile != null) {
                return ResponseEntity.status(HttpStatus.OK).body(gridFSFile.getId().toString());
            }
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("file was fail to store");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
    }
    public ResponseEntity update(String fileId, MultipartFile file) {
        ResponseEntity delete = delete(fileId);
        if (delete.getStatusCode() != HttpStatus.OK) {
            return delete;
        }
        return store(file);
    }
    public ResponseEntity delete(String fileId) {
        try {
            Query query = Query.query(Criteria.where("_id").is(new ObjectId(fileId)));
            gridFsOperations.delete(query);
            return ResponseEntity.status(HttpStatus.OK).body("file was deleted");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除文件异常");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
    }
}

+ 0 - 385
hos-dfs/src/main/java/com/yihu/com/hos/service/GridFSUtil.java

@ -1,385 +0,0 @@
package com.yihu.com.hos.service;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import com.mongodb.client.gridfs.model.GridFSUploadOptions;
import com.mongodb.gridfs.GridFSDBFile;
import com.yihu.hos.core.file.FileUtil;
import eu.medsea.mimeutil.MimeUtil;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsCriteria;
import org.springframework.data.mongodb.gridfs.GridFsOperations;
import org.springframework.stereotype.Component;
import java.io.*;
import java.sql.Blob;
import java.util.*;
/**
 * MongoDB GridFS 操作类
 *
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/7/21.
 */
@Component
public class GridFSUtil {
    public static final int defaultChunkSize = 1024 * 1024 * 4;
    public static GridFsOperations gridFsOperations;
    public static ObjectId uploadFile( Blob blob, String fileType, Map<String, Object> params) {
//        String fileName = UUID.randomUUID().toString() + "." + fileType;
        //自定义字段
        Document metaDocument = new Document();
        if (params != null && params.size() > 0) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                String key = entry.getKey();
                metaDocument.append(key, entry.getValue());
            }
        }
        // Create some custom options
        GridFSUploadOptions gridFSUploadOptions = new GridFSUploadOptions()
                .chunkSizeBytes(defaultChunkSize).metadata(metaDocument);
        try {
            com.mongodb.gridfs.GridFSFile gridFSFile = gridFsOperations.store(blob.getBinaryStream(), gridFSUploadOptions);
            if (gridFSFile != null) {
                return (ObjectId) gridFSFile.getId();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 上传文件至Mongodb by GridFS
     *
     * @param filePath        上传的文件路径
     * @param saveFileName   保存到mongo的文件名
     * @param params          自定义保存字段
     */
    public static String uploadFile(String filePath,String saveFileName, Map<String, Object> params) {
        //自定义字段
        Document metaDocument = new Document();
        if (params != null && params.size() > 0) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                String key = entry.getKey();
                metaDocument.append(key, entry.getValue());
            }
        }
        // Create some custom options
        FileInputStream fileInputStream = null;
        try {
            File readFile = new File(filePath);
            fileInputStream = new FileInputStream(readFile);
            gridFsOperations.delete(Query.query(GridFsCriteria.where("filename").is(saveFileName)));//删除原来的文件,保证唯一
            com.mongodb.gridfs.GridFSFile gridFSFile = gridFsOperations.store(fileInputStream,saveFileName,"",metaDocument);
            if (gridFSFile != null) {
                return saveFileName;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
    /**
     * 从 mongodb GridFS 下载文件
     *
     * @param dbName   数据库名
     * @param savePath 文件保存路径
     * @param objectId GridFS文件保存ObjectId
     * @return
     */
    public static String downFile(String dbName, String savePath, ObjectId objectId) {
        FileOutputStream fileOutputStream = null;
        try {
            GridFSDBFile gridFSDBFile = gridFsOperations.findOne(Query.query(GridFsCriteria.where("_id").is(objectId)));
            fileOutputStream = new FileOutputStream(savePath);
            gridFSDBFile.writeTo(fileOutputStream);
            return savePath;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
    /**
     * 批量下载文件保存(根据 fs.files集合)
     *
     * @param dbName   数据库名
     * @param savePath 文件保存的路径
     * @param fsFiles  fs.files
     * @return 以“,”分割的文件名
     */
    public static Map<String, StringBuffer> downFileList(String dbName, String savePath, List<GridFSDBFile> fsFiles) {
        StringBuffer stringBuffer = new StringBuffer();
        Map<String, String> fileNames = new HashMap<>();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        if (fsFiles != null && fsFiles.size() > 0) {
            for (GridFSDBFile fsFile : fsFiles) {
                Object objectId = fsFile.getId();
                String fileType = fsFile.getFilename().substring(fsFile.getFilename().lastIndexOf("."));
                String newName = UUID.randomUUID().toString() + "." + fileType;
                GridFSDBFile gridFSDBFile = gridFsOperations.findOne(Query.query(GridFsCriteria.where("_id").is(objectId)));
                try {
                    gridFSDBFile.writeTo(out);
                    boolean success = FileUtil.writeFile(savePath + "/" + newName, out.toByteArray(), "utf-8");
                    if (!success) {
                        break;
                    }
                    String type = getMimeType(out.toByteArray());
                    fileNames.put(newName, type);
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                } finally {
                    if (out != null) {
                        try {
                            out.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            return groupDataMap(fileNames);
        } else {
            return null;
        }
    }
    /**
     * 删除 mongodb-GridFS文件
     *
     * @param dbName
     * @param objectId
     */
    public static void deleteFile(String dbName, ObjectId objectId) {
        gridFsOperations.delete(Query.query(GridFsCriteria.where("_id").is(objectId)));
    }
    /**
     * 查询fs.files 数据 in GridFS
     *
     * @param filters 查询条件
     * @return files集合
     */
    public static List<GridFSDBFile> findFiles( Map<String, Object> filters) {
        Query query = new Query();
        if (filters != null) {
            filters.forEach((key, value) -> query.addCriteria(GridFsCriteria.where(key).is(value)));
        }
        return gridFsOperations.find(query);
    }
    /**
     * 根据ObjectID集合查询GridFS 文件列表
     *
     * @param dbName 数据库名
     * @param ids    objectId集合
     * @return
     */
    public static List<GridFSDBFile> findFsFiles(String dbName, List<ObjectId> ids) {
        List<GridFSDBFile> list = new ArrayList<>();
        ids.forEach(objectId -> {
            GridFSDBFile gridFSDBFile = gridFsOperations.findOne(Query.query(GridFsCriteria.where("_id").is(objectId)));
            list.add(gridFSDBFile);
        });
        return list;
    }
    /*************************************** MineType 工具类 *********************************/
    /**
     * 获取文件Mine-Type
     *
     * @param file
     * @return
     */
    public static String getMimeType(File file) {
        MimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.MagicMimeMimeDetector");
        Collection<?> collection = MimeUtil.getMimeTypes(file);
        return collection.toString();
    }
    public static String getMimeType(byte[] bytes) {
        MimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.MagicMimeMimeDetector");
        Collection<?> collection = MimeUtil.getMimeTypes(bytes);
        return collection.toString();
    }
    /**
     * 非结构化档案--文件类型map生成
     *
     * @param map
     * @return
     */
    public static Map<String, StringBuffer> groupDataMap(Map<String, String> map) {
        Map<String, StringBuffer> result = new HashMap<String, StringBuffer>();
        Iterator<String> rs = map.keySet().iterator();
        while (rs.hasNext()) {
            String key = rs.next();
            String value = map.get(key);
            if (result.containsKey(value)) {
                result.get(value).append(",").append(key);
            } else {
                result.put(value, new StringBuffer(key));
            }
        }
        return result;
    }
    /**
     *  上传文件至Mongodb by GridFS
     * @param saveFileName  保存到mongo的文件名
     * @param inputStream   文件流
     * @param params         metaData数据
     * @return
     */
    public static String uploadFile( InputStream inputStream,String saveFileName,Map<String ,Object> params) {
        //metaData参数
        Document metaDocument = new Document();
        if (params != null && params.size() > 0) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                String key = entry.getKey();
                metaDocument.append(key, entry.getValue());
            }
        }
        try {
            gridFsOperations.delete(Query.query(GridFsCriteria.where("filename").is(saveFileName)));//删除原来的文件,保证唯一
            com.mongodb.gridfs.GridFSFile gridFSFile = gridFsOperations.store(inputStream, saveFileName, "", metaDocument);
            if (gridFSFile != null) {
                return saveFileName;
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
    /**
     * 据文件名返回文件,只返回第一个
     *
     * @param fileName
     * @return
     */
    public static boolean readFile(MongoDatabase db, OutputStream os, String fileName) {
        try {
            GridFSBucket gridFS = GridFSBuckets.create(db);
            gridFS.downloadToStreamByName(fileName, os);
            os.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 读取文件内容
     *
     * @param fileName 文件名
     * @return
     */
    public static String readFileContent( String fileName) {
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            GridFSDBFile gridFSDBFile = gridFsOperations.findOne(Query.query(GridFsCriteria.where("filename").is(fileName)));
            gridFSDBFile.writeTo(byteArrayOutputStream);
            return byteArrayOutputStream.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 从 mongodb GridFS 下载文件
     *
     * @param savePath 文件保存路径
     * @param fileName GridFS文件名
     * @return
     */
    public static String downFile( String savePath, String fileName) {
        FileOutputStream fileOutputStream = null;
        try {
            File file = new File(savePath);
            fileOutputStream = new FileOutputStream(file);
            List<GridFSDBFile> gridFSDBFiles = gridFsOperations.find(Query.query(GridFsCriteria.where("filename").is(fileName)));
            if (gridFSDBFiles==null || gridFSDBFiles.isEmpty()){
                return null;
            }else {
                GridFSDBFile gridFSDBFile = gridFSDBFiles.get(0);
                gridFSDBFile.writeTo(fileOutputStream);
                return savePath;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
    public static boolean deleteFile(String fileName){
        try {
            gridFsOperations.delete(Query.query(GridFsCriteria.where("filename").is(fileName)));//删除原来的文件,保证唯一
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }
}

+ 21 - 0
hos-dfs/src/main/resources/application.yml

@ -0,0 +1,21 @@
server:
  port: 9010
security:
  basic:
    enabled: false
---
spring:
  profiles: dev
  data:
    mongodb:
      host: 172.19.103.57
      port: 27017
      username: esb
      password: esb
      authenticationDatabase: admin
      gridFsDatabase: dfs
      database: runtime
hos:
  zbus:
    port: 9020
    store: ./store

+ 16 - 0
hos-dfs/src/test/java/com/yihu/com/hos/HosFdsApplicationTests.java

@ -0,0 +1,16 @@
package com.yihu.com.hos;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class HosFdsApplicationTests {
	@Test
	public void contextLoads() {
	}
}

+ 5 - 0
hos-parent/pom.xml

@ -325,6 +325,11 @@
                <artifactId>camel-restlet</artifactId>
                <version>${camel-version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.camel</groupId>
                <artifactId>camel-servlet</artifactId>
                <version>${camel-version}</version>
            </dependency>
            <!-- camel end -->
            <!-- ActiveMQ -->

+ 52 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/util/DFSUtil.java

@ -0,0 +1,52 @@
package com.yihu.hos.web.framework.util;
import com.yihu.hos.core.http.HTTPResponse;
import com.yihu.hos.core.http.HttpClientKit;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
 * MongoDB GridFS 操作类
 *
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/7/21.
 */
@Component
public class DFSUtil {
    @Value("")
    private String dfsUrl;
    /**
     * 读取文件内容
     *
     * @param fileName 文件名
     * @return
     */
    public String readFileContent(String fileName) {
        HTTPResponse httpResponse = HttpClientKit.get("dfsUrl/file" + fileName);
        if (httpResponse.getStatusCode() == 200) {
            return httpResponse.getBody();
        }
        return null;
    }
    /**
     * 上传文件至Mongodb by GridFS
     *
     * @param filePath     上传的文件路径
     * @param saveFileName 保存到mongo的文件名
     * @param params       自定义保存字段
     */
    public String uploadFile(String filePath, String saveFileName, Map<String, Object> params) {
//        HTTPResponse httpResponse = HttpClientKit.post("dfsUrl/file" + fileName);
//        if (httpResponse.getStatusCode() == 200) {
//            return httpResponse.getBody();
//        }
//
        return null;
    }
}

+ 1 - 26
src/main/java/com/yihu/hos/ESBApplication.java

@ -1,27 +1,13 @@
package com.yihu.hos;
import com.yihu.hos.config.BeanConfig;
import com.yihu.hos.interceptor.WebMvcInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.mongodb.gridfs.GridFsOperations;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@SpringBootApplication
public class ESBApplication extends WebMvcConfigurerAdapter  implements CommandLineRunner {
    private BeanConfig configuration;
    @Autowired
    private GridFsOperations operations;
    @Autowired
    public void setConfiguration(BeanConfig configuration) {
        this.configuration = configuration;
    }
public class ESBApplication extends WebMvcConfigurerAdapter {
    public static void main(String[] args) throws Exception {
        SpringApplication application = new SpringApplication(ESBApplication.class);
        application.run(args);
@ -30,17 +16,6 @@ public class ESBApplication extends WebMvcConfigurerAdapter  implements CommandL
    // 增加拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        GridFSUtil.gridFsOperations = operations;
        registry.addInterceptor(new WebMvcInterceptor());
    }
    @Override
    public void run(String... strings) throws Exception {
//        MqServerConfig config = new MqServerConfig();
//        config.serverPort = configuration.getZbusPort();
//        config.storePath = configuration.getZbusStore();
//        final MqServer server = new MqServer(config);
//        server.start();
//        System.out.println("zbus 启动成功!");
    }
}

+ 10 - 44
src/main/java/com/yihu/hos/config/BeanConfig.java

@ -19,11 +19,8 @@ import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.zbus.broker.ZbusBroker;
import org.zbus.mq.server.MqServer;
import org.zbus.mq.server.MqServerConfig;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Locale;
import java.util.Properties;
@ -42,24 +39,17 @@ public class BeanConfig {
    @Autowired
    private DataSource dataSource;
    @Value("${hos.zbus.port}")
    private Integer zbusPort;
    @Value("${hos.zbus.store}")
    private String zbusStore;
    @Value("${hos.zbus.url}")
    private String zbusUrl;
    private ZbusBroker zbusBroker;
    @Value("${hos.filesystem.url}")
    private String fsUrl;
    @Bean
    public ZbusBroker getZbusBroker() {
        try {
            MqServerConfig config = new MqServerConfig();
            config.serverPort = this.getZbusPort();
            config.storePath = this.getZbusStore();
            final MqServer server = new MqServer(config);
            server.start();
            System.out.println("zbus 启动成功!");
            zbusBroker = new ZbusBroker("127.0.0.1:" + zbusPort);
            zbusBroker = new ZbusBroker(zbusUrl);
            return zbusBroker;
        } catch (Exception e) {
            e.printStackTrace();
@ -67,12 +57,8 @@ public class BeanConfig {
        return null;
    }
    public Integer getZbusPort() {
        return zbusPort;
    }
    public String getZbusStore() {
        return zbusStore;
    public String getZbusUrl() {
        return zbusUrl;
    }
    @Bean
@ -102,29 +88,6 @@ public class BeanConfig {
        return hibernateTransactionManager;
    }
//    @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
    public CommonsMultipartResolver multipartResolver() {
@ -189,4 +152,7 @@ public class BeanConfig {
        super.finalize();
    }
    public String getFsUrl() {
        return fsUrl;
    }
}

+ 2 - 2
src/main/java/com/yihu/hos/remoteManage/controller/RemoteShellController.java

@ -1,8 +1,8 @@
package com.yihu.hos.remoteManage.controller;
package com.yihu.hos.remotemanage.controller;
import com.yihu.hos.common.constants.ContextAttributes;
import com.yihu.hos.interceptor.LocalContext;
import com.yihu.hos.remoteManage.service.RemoteShellService;
import com.yihu.hos.remotemanage.service.RemoteShellService;
import com.yihu.hos.web.framework.model.Result;
import com.yihu.hos.web.framework.util.controller.BaseController;
import io.swagger.annotations.ApiParam;

+ 1 - 1
src/main/java/com/yihu/hos/remoteManage/service/RemoteShellService.java

@ -1,4 +1,4 @@
package com.yihu.hos.remoteManage.service;
package com.yihu.hos.remotemanage.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.hos.common.constants.ContextAttributes;

+ 0 - 33
src/main/java/com/yihu/hos/system/controller/AppController.java

@ -316,37 +316,4 @@ public class AppController extends BaseController {
        }
    }
    /* ========================================== 上传相关(后面可抽出) ================================================= */
    /**
     * 文件上传
     * @param file
     * @return
     */
    @RequestMapping(value = "/upload", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public Object upload(@RequestParam MultipartFile file) {
        try {
            CommonsMultipartFile transferFile = (CommonsMultipartFile)file;
            return appManager.uploadFile(transferFile);
        } catch (Exception e) {
            return Result.error("上传失败!");
        }
    }
    /**
     * 图片查看
     * @return
     */
    @RequestMapping(value = "/read/{fileName}", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public Object read(HttpServletResponse response, @PathVariable("fileName")  String fileName) {
        // response.setContentType("image/*");
        try {
            OutputStream os = response.getOutputStream();
            return appManager.readFile(os, fileName);
        } catch (Exception e) {
            return Result.error("读取失败!");
        }
    }
}

+ 0 - 43
src/main/java/com/yihu/hos/system/controller/FlowController.java

@ -121,17 +121,6 @@ public class FlowController extends BaseController {
            ObjectMapper objectMapper = new ObjectMapper();
            SystemServiceFlow flow = objectMapper.readValue(flowClass,SystemServiceFlow.class);
//            SystemServiceFlow obj = new SystemServiceFlow();
//            BeanUtils.populate(obj, request.getParameterMap());
//
//            List<SystemServiceFlowClass> flowClass = new ArrayList<>();
//            BeanUtils.populate(flowClass, request.getParameterMap());
//            obj.setFlowClassArray(flowClass);
//
//            List<SystemServiceFlowTemp> flowTemps = new ArrayList<>();
//            BeanUtils.populate(flowTemps, request.getParameterMap());
//            obj.setFlowTempArray(flowTemps);
            return flowManage.addFlow(flow);
        } catch (Exception ex) {
            ex.printStackTrace();
@ -180,38 +169,6 @@ public class FlowController extends BaseController {
    }
    /**
     * 文件上传
     * @param file
     * @return
     */
    @RequestMapping(value = "/upload", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public Object upload(@RequestParam MultipartFile file) {
        //TODO 文件地址设置
        try {
            CommonsMultipartFile transferFile = (CommonsMultipartFile)file;
            return flowManage.uploadFile(transferFile);
        } catch (Exception e) {
            return Result.error("上传失败");
        }
    }
    /**
     * 图片查看
     * @return
     */
    @RequestMapping(value = "/read/{fileName}", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public Object read(HttpServletResponse response, @PathVariable("fileName")  String fileName) {
        try {
            OutputStream os = response.getOutputStream();
            return flowManage.readFile(os, fileName);
        } catch (Exception e) {
            return Result.error("读取失败!");
        }
    }
    @RequestMapping(value = "/flowTempList", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public Result flowTempList(String type) {

+ 0 - 27
src/main/java/com/yihu/hos/system/service/AppManager.java

@ -156,33 +156,6 @@ public class AppManager {
        return Result.success("删除成功");
    }
    public Result uploadFile(CommonsMultipartFile file) {
        String newFileName;
        try {
            String fileName = UUID.randomUUID() + file.getFileItem().getName();
            newFileName = GridFSUtil.uploadFile(file.getInputStream(), fileName, null);
            if (!StringUtil.isEmpty(newFileName)) {
                return Result.success(DES.encrypt(newFileName, DES.COMMON_PASSWORD));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("上传失败");
    }
    public Result readFile(OutputStream os, String fileName) {
        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("读取失败");
    }
    private void sendMsg(String event, SystemServiceEndpoint endpoint) {
        if (zbusBroker == null) {
            logger.error("zbusBroker is null.");

+ 50 - 150
src/main/java/com/yihu/hos/system/service/FlowManager.java

@ -1,8 +1,8 @@
package com.yihu.hos.system.service;
import com.yihu.hos.common.constants.ContextAttributes;
import com.yihu.hos.config.MongoConfig;
import com.yihu.hos.core.datatype.StringUtil;
import com.yihu.hos.config.BeanConfig;
import com.yihu.hos.core.datatype.ClassFileUtil;
import com.yihu.hos.core.encrypt.DES;
import com.yihu.hos.core.file.FileUtil;
import com.yihu.hos.interceptor.LocalContext;
@ -19,14 +19,16 @@ import com.yihu.hos.web.framework.model.DictItem;
import com.yihu.hos.web.framework.model.Result;
import com.yihu.hos.web.framework.model.bo.ServiceFlow;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.annotation.Resource;
import java.io.OutputStream;
import java.util.*;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
 * 系统流程管理业务类
@ -37,10 +39,11 @@ import java.util.*;
 */
@Service("flowManager")
public class FlowManager {
    public static final String BEAN_ID = "flowManager";
    @Autowired
    ServiceFlowEventService serviceFlowEventService;
    @Autowired
    private BeanConfig beanConfig;
    @Resource(name = "flowDao")
    private FlowDao flowDao;
@ -48,38 +51,6 @@ public class FlowManager {
    private FlowClassDao flowClassDao;
    @Resource(name = FlowTempDao.BEAN_ID)
    private FlowTempDao flowTempDao;
    @Value("${spring.data.mongodb.gridFsDatabase}")
    private String dbName;
    @Autowired
    private MongoConfig mongoConfig;
    /**
     * 生成processor的java文件
     *
     * @param routeId      流程Code
     * @param tempFilePath 模板文件名
     * @param className    模板类名
     * @return
     */
    public static String genProcessorJavaFile(String routeId, String tempFilePath, String className) {
        try {
            String newFileName = className + routeId + ".java";
            String newFilePath = "/temp/" + className;
            String text = GridFSUtil.readFileContent(tempFilePath);
            boolean succ = FileUtil.writeFile(newFilePath, text, "UTF-8");
            //TODO 上传到GridFS
            if (succ) {
                newFileName = GridFSUtil.uploadFile( newFilePath, newFileName,null);
                return newFileName;
            }
        } catch (Exception e) {
            System.out.println("生成processor的java文件操作出错");
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 生成Route流程的java文件
@ -90,11 +61,16 @@ public class FlowManager {
     * @param newCron      cron表达式
     * @return
     */
    public static String genRouteJavaFile(String routeId, String className, String tempFilePath, String newCron) {
    public String genRouteJavaFile(String routeId, String className, String tempFilePath, String newCron) {
        try {
            String newFileName = className + routeId + ".java";
            String newFilePath = "/temp/" + newFileName;
            String text = GridFSUtil.readFileContent( tempFilePath);
            byte[] content = ClassFileUtil.down(tempFilePath);
            if (content == null) {
                return null;
            }
            String text = new String(content, StandardCharsets.UTF_8);
            if (text.contains("?cron=")) {
                String oldStr = text.substring(text.indexOf("?cron=") + 6);
                String cron = oldStr.substring(0, oldStr.indexOf("\""));
@ -107,9 +83,8 @@ public class FlowManager {
            //修改routeId;模板规则 routeId("routeId")
            text = text.replace("routeId(\"routeId\")", "routeId(\"" + routeId + "\")");
            boolean succ = FileUtil.writeFile(newFilePath, text, "UTF-8");
            //TODO 上传到GridFS
            if (succ) {
                newFileName = GridFSUtil.uploadFile( newFilePath, newFileName,null);
                newFileName = ClassFileUtil.uploadFile(beanConfig.getFsUrl(), new File(newFilePath + newFileName), newFileName);
            } else {
                return null;
            }
@ -131,17 +106,22 @@ public class FlowManager {
     * @param className    模板类名
     * @return
     */
    public static String genProcessorJavaFile(String jobId, String routeId, String tempFilePath, String className) {
    public String genProcessorJavaFile(String jobId, String routeId, String tempFilePath, String className) {
        try {
            String newFileName = className + routeId + ".java";
            String newFilePath = "/temp/" + className;
            String text = GridFSUtil.readFileContent( tempFilePath);
            byte[] content = ClassFileUtil.down(tempFilePath);
            if (content == null) {
                return null;
            }
            String text = new String(content, StandardCharsets.UTF_8);
            text = text.replace("jobId=jobId", "jobId=" + jobId);
            boolean succ = FileUtil.writeFile(newFilePath, text, "UTF-8");
            //TODO 上传到GridFS
            if (succ) {
                newFileName = GridFSUtil.uploadFile( newFilePath, newFileName,null);
                newFileName = ClassFileUtil.uploadFile(beanConfig.getFsUrl(), new File(newFilePath + newFileName), newFileName);
                return newFileName;
            }
        } catch (Exception e) {
@ -226,27 +206,10 @@ public class FlowManager {
            serviceFlowEventService.serviceFlowAdded(serviceFlow);
        } else if (ServiceFlowConstant.JAVA.equals(obj.getFileType())) {
            List<SystemServiceFlowTemp> flowTempList = obj.getFlowTempArray();
//            ServiceFlow serviceFlow = new ServiceFlow();
//            serviceFlow.setRouteCode(obj.getCode());
//            serviceFlow.setFlowType(ServiceFlowConstant.JAVA);
            for (SystemServiceFlowTemp flowTemp : flowTempList) {
                flowTemp.setFlowId(obj.getId());
                flowDao.saveEntity(flowTemp);
//                ServiceFlow.HandleFile handleFile = new ServiceFlow.HandleFile();
//                handleFile.setRouteCode(obj.getCode());
//                handleFile.setFileType(ServiceFlowConstant.JAVA);
//                handleFile.setPackageName(flowTemp.getPackageName());
//                handleFile.setClassName(flowTemp.getClassName());
//                handleFile.setFilePath(flowTemp.getClassPath());
//                handleFile.setUsage(flowTemp.getType());
//                serviceFlow.addHandleFile(handleFile);
            }
//            serviceFlowEventService.serviceFlowAdded(serviceFlow);
        }
        return Result.success("保存成功");
@ -277,26 +240,15 @@ public class FlowManager {
            List<Integer> classIds = flowClassDao.getFlowClassIds(obj.getId());//原flowclass集合
            List<SystemServiceFlowClass> flowClassList = obj.getFlowClassArray();
            SystemServiceFlowClass flowClassRoute = null;
            String oper = "";
            serviceFlow.setRouteCode(obj.getCode());
            serviceFlow.setFlowType(ServiceFlowConstant.CLASS);
            for (SystemServiceFlowClass flowClass : flowClassList) {
                if (flowClass.getId() != null) {
                    classIds.remove(flowClass.getId());
                    flowClassDao.updateEntity(flowClass);
                    if (flowClass.getType().equals(ServiceFlowConstant.FLOW_TYPE_ROUTE)) {
//                        sendUpdateMessage(flow.getCode(), flowClass, ServiceFlowConstant.FLOW_OP_UPDATE);
//                    } else {
                        flowClassRoute = flowClass;
                        oper = ServiceFlowConstant.FLOW_OP_UPDATE;
                    }
                } else {
                    if (!flowClass.getType().equals(ServiceFlowConstant.FLOW_TYPE_ROUTE)) {
                        flowClassDao.saveEntity(flowClass);
//                        sendUpdateMessage(flow.getCode(), flowClass, ServiceFlowConstant.FLOW_OP_ADD);
                    } else {
                        flowClassRoute = flowClass;
                        oper = ServiceFlowConstant.FLOW_OP_ADD;
                    }
                }
@ -313,24 +265,17 @@ public class FlowManager {
            serviceFlowEventService.serviceFlowModifiedAdd(serviceFlow);
            //删除判断
            if (classIds != null && classIds.size() > 0) {
                for (Integer id : classIds) {
                    SystemServiceFlowClass flowClass = getFlowClassById(id);
                    flowClassDao.deleteEntity(flowClass);
                    if (flowClass.getType().equals(ServiceFlowConstant.FLOW_TYPE_ROUTE)) {
//                        sendUpdateMessage(flow.getCode(), flowClass, ServiceFlowConstant.FLOW_OP_DELETE);
//                    } else {
                        flowClassRoute = flowClass;
                        flowClassRoute.setIsUpdate("1");
                        oper = ServiceFlowConstant.FLOW_OP_DELETE;
                    }
                }
            }
//            if (flowClassRoute != null) {
//                sendUpdateMessage(flow.getCode(), flowClassRoute, oper);
//            }
        }
        flowDao.updateEntity(flow);
@ -422,32 +367,6 @@ public class FlowManager {
    }
    public Result uploadFile(CommonsMultipartFile file) {
        String newFileName;
        try {
            String fileName = UUID.randomUUID() + file.getFileItem().getName();
            newFileName = GridFSUtil.uploadFile(file.getInputStream(),fileName,null);
            if (!StringUtil.isEmpty(newFileName)) {
                return Result.success(DES.encrypt(newFileName, DES.COMMON_PASSWORD));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("上传失败");
    }
    public Result readFile(OutputStream os, String fileName) {
        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("读取失败");
    }
    /**
     * 发送MQ消息-更新路由
     *
@ -543,7 +462,7 @@ public class FlowManager {
     * @throws Exception
     */
    public Integer updateCamelFile(String jobId,Integer flowTempId, Integer flowId, String newCron) throws Exception {
    public Integer updateCamelFile(String jobId, Integer flowTempId, Integer flowId, String newCron) throws Exception {
         /* 修改route文件无需重新生成flowClass记录,文件名根据className+routeId 生成;*/
        List<SystemServiceFlowTemp> flowTempRouters = flowTempDao.getFlowTemps(flowTempId, ServiceFlowConstant.FLOW_TYPE_ROUTE);
        List<SystemServiceFlowTemp> flowTempProces = flowTempDao.getFlowTemps(flowTempId, ServiceFlowConstant.FLOW_TYPE_PROCESSOR);
@ -556,12 +475,8 @@ public class FlowManager {
            ServiceFlow serviceFlow = new ServiceFlow();
            //新增processor记录
            for (SystemServiceFlowTemp process : flowTempProces) {
                String deName = DES.decrypt(process.getClassPath(), DES.COMMON_PASSWORD);//吉阿米果的文件名
                String newFileName = genProcessorJavaFile(jobId, flow.getCode(), deName, process.getClassName());
                //生成新的java文件
                String enNewFileName = DES.encrypt(newFileName, DES.COMMON_PASSWORD);
                if (newFileName != null) {
                String newPath = genProcessorJavaFile(jobId, flow.getCode(), process.getClassPath(), process.getClassName());
                if (newPath != null) {
                    //发送消息
                    serviceFlow.setRouteCode(flow.getCode());
                    serviceFlow.setFlowType(ServiceFlowConstant.CLASS);
@ -570,7 +485,7 @@ public class FlowManager {
                    handleFile.setFileType(ServiceFlowConstant.JAVA);
                    handleFile.setPackageName(process.getPackageName());
                    handleFile.setClassName(process.getClassName());
                    handleFile.setFilePath(enNewFileName);
                    handleFile.setFilePath(newPath);
                    handleFile.setUsage(ServiceFlowConstant.FLOW_TYPE_PROCESSOR);
                    handleFiles.add(handleFile);
                    serviceFlow.setHandleFiles(handleFiles);
@ -580,14 +495,8 @@ public class FlowManager {
                }
            }
            String deName = DES.decrypt(flowTemp.getClassPath(), DES.COMMON_PASSWORD);//吉阿米果的文件名
            //生成新的route文件
            String newFileName = genRouteJavaFile(flow.getCode(), flowTemp.getClassName(), deName, newCron);
            String enNewFileName = DES.encrypt(newFileName, DES.COMMON_PASSWORD);
            String newPath = genRouteJavaFile(flow.getCode(), flowTemp.getClassName(), flowTemp.getClassPath(), newCron);
            serviceFlow.setRouteCode(flow.getCode());
            serviceFlow.setFlowType(ServiceFlowConstant.JAVA);
            ServiceFlow.HandleFile handleFile = new ServiceFlow.HandleFile();
@ -595,7 +504,7 @@ public class FlowManager {
            handleFile.setFileType(ServiceFlowConstant.JAVA);
            handleFile.setPackageName(flowTemp.getPackageName());
            handleFile.setClassName(flowTemp.getClassName() + flow.getCode());
            handleFile.setFilePath(enNewFileName);
            handleFile.setFilePath(newPath);
            handleFile.setUsage(ServiceFlowConstant.FLOW_TYPE_ROUTE);
            handleFiles.add(handleFile);
            serviceFlow.setHandleFiles(handleFiles);
@ -623,22 +532,18 @@ public class FlowManager {
            }
            //新增processor记录
            String deName = DES.decrypt(flowTemp.getClassPath(), DES.COMMON_PASSWORD);//吉阿米果的文件名
            String newFileName = genRouteJavaFile(newFlow.getCode(), flowTemp.getClassName(), deName, newCron);
            String enClassName = DES.encrypt(newFileName.replace(".java", ".class"), DES.COMMON_PASSWORD);//生成机密过的classPath
            String newPath = genRouteJavaFile(newFlow.getCode(), flowTemp.getClassName(), flowTemp.getClassPath(), newCron);
            SystemServiceFlowClass newFlowClass = new SystemServiceFlowClass();
            newFlowClass.setPackageName(flowTemp.getPackageName());
            newFlowClass.setClassName(flowTemp.getClassName() + newFlow.getCode());
            newFlowClass.setClassPath(enClassName);
            newFlowClass.setClassPath(flowTemp.getClassPath());
            newFlowClass.setFlowId(newFlow.getId());
            newFlowClass.setType(ServiceFlowConstant.FLOW_TYPE_ROUTE);
            flowClassDao.saveEntity(newFlowClass);
            newFlowClass.setIsUpdate("1");
            //生成新的route文件
            String enNewFileName = DES.encrypt(newFileName, DES.COMMON_PASSWORD);//加密文件名
            if (newFileName != null) {
            if (newPath != null) {
                ServiceFlow serviceFlow = new ServiceFlow();
                serviceFlow.setRouteCode(newFlow.getCode());
                serviceFlow.setFlowType(ServiceFlowConstant.CLASS);
@ -647,7 +552,7 @@ public class FlowManager {
                handleFile.setFileType(ServiceFlowConstant.JAVA);
                handleFile.setPackageName(flowTemp.getPackageName());
                handleFile.setClassName(flowTemp.getClassName() + newFlow.getCode());
                handleFile.setFilePath(enNewFileName);
                handleFile.setFilePath(newPath);
                handleFile.setUsage(ServiceFlowConstant.FLOW_TYPE_ROUTE);
                ArrayList<ServiceFlow.HandleFile> handleFiles = new ArrayList<>();
                handleFiles.add(handleFile);
@ -668,8 +573,9 @@ public class FlowManager {
        String fileName = javaName + ".java";
        String filePath = this.getClass().getProtectionDomain().getClassLoader().getResource("").getPath() + "temp/" + fileName;
        boolean succ = FileUtil.writeFile(filePath, fileInfo, "UTF-8");
        String path = "";
        if (succ) {
            fileName = GridFSUtil.uploadFile(filePath, fileName, null);
            path = ClassFileUtil.uploadFile(beanConfig.getFsUrl(), new File(filePath), fileName);
        } else {
            return null;
        }
@ -683,8 +589,6 @@ public class FlowManager {
            systemServiceFlow.setFileType(ServiceFlowConstant.JAVA);
            flowDao.saveEntity(systemServiceFlow);
            String enFileName = DES.encrypt(fileName, DES.COMMON_PASSWORD);//加密文件名
            ServiceFlow serviceFlow = new ServiceFlow();
            serviceFlow.setRouteCode(code);
            serviceFlow.setFlowType(ServiceFlowConstant.CLASS);
@ -693,18 +597,17 @@ public class FlowManager {
            handleFile.setFileType(ServiceFlowConstant.JAVA);
            handleFile.setPackageName(packageName);
            handleFile.setClassName(javaName);
            handleFile.setFilePath(enFileName);
            handleFile.setFilePath(path);
            handleFile.setUsage(ServiceFlowConstant.FLOW_TYPE_ROUTE);
            ArrayList<ServiceFlow.HandleFile> handleFiles = new ArrayList<>();
            handleFiles.add(handleFile);
            serviceFlow.setHandleFiles(handleFiles);
            serviceFlowEventService.serviceFlowAdded(serviceFlow);
            String enClassName = DES.encrypt(javaName + ".class", DES.COMMON_PASSWORD);//生成加密过的classPath
            SystemServiceFlowClass flowClass = new SystemServiceFlowClass();
            flowClass.setPackageName(packageName);
            flowClass.setClassName(javaName);
            flowClass.setClassPath(enClassName);
            flowClass.setClassPath(path);
            flowClass.setFlowId(systemServiceFlow.getId());
            flowClass.setType(ServiceFlowConstant.FLOW_TYPE_ROUTE);
            flowClass.setIsUpdate("1");
@ -748,21 +651,17 @@ public class FlowManager {
                    }
                }
                String deName = DES.decrypt(process.getClassPath(), DES.COMMON_PASSWORD);//吉阿米果的文件名
                String newFileName = genProcessorJavaFile(jobId, newFlow.getCode(), deName, process.getClassName());
                String newPath = genProcessorJavaFile(jobId, newFlow.getCode(), process.getClassPath(), process.getClassName());
                String enClassName = DES.encrypt(newFileName.replace(".java", ".class"), DES.COMMON_PASSWORD);//生成机密过的classPath
                SystemServiceFlowClass processClass = new SystemServiceFlowClass();
                processClass.setPackageName(process.getPackageName());
                processClass.setClassName(process.getClassName());
                processClass.setClassPath(enClassName);
                processClass.setClassPath(processClass.getClassPath());
                processClass.setFlowId(newFlow.getId());
                processClass.setType(ServiceFlowConstant.FLOW_TYPE_PROCESSOR);
                processClass.setIsUpdate("1");
                //生成新的java文件
                String enNewFileName = DES.encrypt(newFileName, DES.COMMON_PASSWORD);
                if (newFileName != null) {
                if (newPath != null) {
                    //发送消息
                    ServiceFlow serviceFlow = new ServiceFlow();
                    serviceFlow.setRouteCode(newFlow.getCode());
@ -772,7 +671,7 @@ public class FlowManager {
                    handleFile.setFileType(ServiceFlowConstant.JAVA);
                    handleFile.setPackageName(processClass.getPackageName());
                    handleFile.setClassName(processClass.getClassName());
                    handleFile.setFilePath(enNewFileName);
                    handleFile.setFilePath(newPath);
                    handleFile.setUsage(ServiceFlowConstant.FLOW_TYPE_PROCESSOR);
                    handleFiles.add(handleFile);
                    serviceFlow.setHandleFiles(handleFiles);
@ -790,7 +689,8 @@ public class FlowManager {
    }
    /**
     *  服务启动/暂停
     * 服务启动/暂停
     *
     * @param flowId 流程ID
     * @param oper   服务操作;1:启动;0:暂停
     * @return
@ -819,11 +719,11 @@ public class FlowManager {
                handleFiles.add(handleFile);
            }
            serviceFlow.setHandleFiles(handleFiles);
            if (1 == oper){
            if (1 == oper) {
                serviceFlowEventService.serviceFlowStarted(serviceFlow);
            }else if (0 == oper){
            } else if (0 == oper) {
                serviceFlowEventService.serviceFlowStopped(serviceFlow);
            }else {
            } else {
                return false;
            }
            return true;

+ 3 - 4
src/main/resources/application.yml

@ -55,8 +55,9 @@ spring:
    proxy-target-class: true
hos:
  zbus:
    port: 15555
    store: ./store
    url: 127.0.0.1:9020
  filesystem:
    url: 127.0.0.1:9010/dfs/file
  mysql:
    filePath: e://learn.sql   #租户基础表 sql文件位置
service-gateway:
@ -107,8 +108,6 @@ spring:
hos:
  zbus:
    url: 172.17.110.202:15555
    port: 15555
    store: ./store
  mysql:
    filePath: /usr/local/esb/esb.sql   #租户基础表 sql文件位置
service-gateway:

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

@ -15,13 +15,6 @@ import java.io.IOException;
public class HosAdminApplicationTests {
	@Test
	public void contextLoads() throws IOException {
		String newName = "text"+System.currentTimeMillis()+".java";
		String newFilePath = "/upload/"+newName;
		String  content = GridFSUtil.readFileContent( "955569af-43fb-422f-bded-d88f99cad1f9QuartzRoute.java");
		boolean succ = FileUtil.writeFile(newFilePath, content, "UTF-8");
		newName = GridFSUtil.uploadFile( newFilePath, newName,null);
		System.out.println(content);
	}
}