Bladeren bron

新增租户自动化配置1:自动建库,建表,数据复制

demon 8 jaren geleden
bovenliggende
commit
5f84729bd4

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

@ -82,6 +82,7 @@ public class RemoteShellService {
        try {
            if (consumer != null) {
                //TODO  new后,原对象引用可能断开无法找到;使用静态锁map来保存
                consumer = new Consumer(zbusBroker, ServiceFlowConstant.SHELL_RESPONSE + "@" + attachment);
                String messageBodyString = consumer.queryMQ().getBodyString();
                Map<String,Object> message = objectMapper.readValue(messageBodyString,Map.class);

+ 198 - 0
src/main/java/com/yihu/hos/tenant/controller/DBInfoController.java

@ -0,0 +1,198 @@
package com.yihu.hos.tenant.controller;
import com.yihu.hos.tenant.model.DBInfoModel;
import com.yihu.hos.tenant.service.DBInfoService;
import com.yihu.hos.web.framework.model.DetailModelResult;
import com.yihu.hos.web.framework.model.Result;
import com.yihu.hos.web.framework.util.controller.BaseController;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
 *  数据库实例管理
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/12/16.
 */
@RequestMapping("/tenant/dataBase")
@Controller
public class DBInfoController extends BaseController{
    @Resource(name = DBInfoService.BEAN_ID)
    private DBInfoService dbInfoService;
    /**
     *   管理界面
     *
     * @param model
     * @return
     */
    @RequestMapping("/initial")
    public String dbInfoInitial(Model model) {
        model.addAttribute("contentPage", "tenant/dataBase/dbInfo");
        return "partView";
    }
    /**
     * 列表
     *
     * @param request
     * @return
     */
    @RequestMapping("/getDBList")
    @ResponseBody
    public Result getDBInfoList(HttpServletRequest request,String name,String valid) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("name", name);
            params.put("valid", valid);
            String page = StringUtils.isEmpty(request.getParameter("page")) ? "1" : request.getParameter("page");
            String rows = StringUtils.isEmpty(request.getParameter("rows")) ? "10" : request.getParameter("rows");
            params.put("page", page);
            params.put("rows", rows);
            Result result = dbInfoService.getDBInfoList(params);
            return result;
        } catch (Exception ex) {
            ex.printStackTrace();
            return Result.error(ex.getMessage());
        }
    }
    /**
     *  修改页面
     * @param model
     * @param id
     * @param categoryId
     * @return
     */
    @RequestMapping("/editorDbInfo")
    public String editorDBInfo(Model model, Long id, String flag, String categoryId) {
        try {
            DBInfoModel dbInfoModel = null;
            if (id != null) {
                dbInfoModel = dbInfoService.getDBInfoById(id);
            }  else {
                dbInfoModel = new DBInfoModel();
            }
            model.addAttribute("model", dbInfoModel);
            model.addAttribute("flag", flag);
            model.addAttribute("categoryId", categoryId);
            model.addAttribute("contentPage", "/tenant/dataBase/editorDbInfo");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "pageView";
    }
    /**
     * 详情页
     * @param model
     * @param id
     * @return
     */
    @RequestMapping("/dbDetail")
    public String dBInfoDetail(Model model, Long id) {
        try {
            DBInfoModel dbInfoModel = null;
            if (id != null ) {
                dbInfoModel = dbInfoService.getDBInfoById(id);
            }  else {
                dbInfoModel = new DBInfoModel();
            }
            model.addAttribute("model", dbInfoModel);
            model.addAttribute("contentPage", "/tenant/dataBase/dbDetail");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "pageView";
    }
    /**
     * 新增
     * @param request
     * @return
     */
    @RequestMapping("addDBInfo")
    @ResponseBody
    public Result addDBInfo(HttpServletRequest request) {
        try {
            DBInfoModel obj = new DBInfoModel();
            BeanUtils.populate(obj, request.getParameterMap());
            obj.setCreated(new Date());
            return dbInfoService.addDBInfo(obj);
        } catch (Exception ex) {
            ex.printStackTrace();
            return Result.error(ex.getMessage());
        }
    }
    /**
     * 删除
     * @param request
     * @return
     */
    @RequestMapping("/deleteDBInfo")
    @ResponseBody
    public Result deleteDBInfo(HttpServletRequest request) {
        try {
            String id = request.getParameter("id");
            dbInfoService.deleteDBInfo(Long.parseLong(id));
            return Result.success("删除成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除失败!");
        }
    }
    /**
     * 修改租户信息
     */
    @RequestMapping("updateDBInfo")
    @ResponseBody
    public Result updateDBInfo(HttpServletRequest request) {
        try {
            DBInfoModel obj = new DBInfoModel();
            BeanUtils.populate(obj, request.getParameterMap());
            return dbInfoService.updateDBInfo(obj);
        } catch (Exception ex) {
            ex.printStackTrace();
            return Result.error(ex.getMessage());
        }
    }
    @RequestMapping(value="/getDataBaseValues" , method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取数据库实例下拉框信息", response = DetailModelResult.class, produces = "application/json", notes = "获取数据库实例下拉框信息")
    public DetailModelResult getSelectList(
            @ApiParam(name = "q", value = "数据库名称或实例名", required = false)
            @RequestParam(value = "q", required = false) String q,
            @ApiParam(name = "initVal", value = "初始化数据库名称", required = false)
            @RequestParam(value = "initVal", required = false) String initVal) {
        return dbInfoService.getDataBaseSelectList(q);
    }
}

+ 67 - 0
src/main/java/com/yihu/hos/tenant/dao/DBInfoDao.java

@ -0,0 +1,67 @@
package com.yihu.hos.tenant.dao;
import com.yihu.hos.tenant.model.DBInfoModel;
import com.yihu.hos.web.framework.dao.SQLGeneralDAO;
import com.yihu.hos.web.framework.model.Result;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;
import java.util.List;
import java.util.Map;
/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/12/2.
 */
@Repository("dBInfoDao")
public class DBInfoDao extends SQLGeneralDAO {
    public static final String BEAN_ID = "dBInfoDao";
    public List<DBInfoModel> getDBInfoList(String name) throws Exception {
        List<DBInfoModel> list = (List<DBInfoModel>) super.hibernateTemplate.find("from DBInfoModel s where (s.name like ? or s.userName like ?) and s.valid = 1", name,name);
        return list;
    }
    public List<DBInfoModel> getAllList() throws Exception {
        List<DBInfoModel> list = (List<DBInfoModel>) super.hibernateTemplate.find("from DBInfoModel s where  s.valid = 1");
        return list;
    }
    /**\
     * 分页列表
     * @param params
     * @return
     * @throws Exception
     */
    public Result getDBInfoList(Map<String, Object> params) throws Exception {
        StringBuilder sb = new StringBuilder("from DBInfoModel t where 1=1 ");
        Object valid = params.get("valid");
        Object name = params.get("name");
        if (!StringUtils.isEmpty(valid)) //是否有效
        {
            sb.append(" and t.valid = :valid");
        }
        //用户名过滤
        if (!StringUtils.isEmpty(name)) {
            sb.append(" and (t.name like ? or t.userName like ?)");
        }
        sb.append(" order by t.created desc");
        Query query = super.hibernateTemplate.getSessionFactory().getCurrentSession().createQuery(sb.toString());
        if (!StringUtils.isEmpty(valid)) //是否有效
        {
            query.setInteger("valid",Integer.parseInt(valid.toString()));
        }
        if (!StringUtils.isEmpty(name)) {
            query.setString(0, "%" + name.toString() + "%");
            query.setString(1, "%" + name.toString() + "%");
        }
        return super.getDataGridResult(query, Integer.valueOf(params.get("page").toString()), Integer.valueOf(params.get("rows").toString()));
    }
}

+ 114 - 0
src/main/java/com/yihu/hos/tenant/model/DBInfoModel.java

@ -0,0 +1,114 @@
package com.yihu.hos.tenant.model;
import com.yihu.hos.web.framework.model.IdModel;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.Date;
/**
 *  系统真实数据库实例
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/12/2.
 */
@Entity
@Table(name = "system_datasource_info")
public class DBInfoModel extends IdModel {
    private String name;
    private String userName;
    private String password;
    private String host;
    private Integer port;
    private Date created;
    private Date updated;
    private Integer valid;
    // @Transient 不映射
    private String dbName;
    @Column(name="name")
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Column(name="user_name")
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    @Column(name="password")
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    @Column(name="host")
    public String getHost() {
        return host;
    }
    public void setHost(String host) {
        this.host = host;
    }
    @Column(name="port")
    public Integer getPort() {
        return port;
    }
    public void setPort(Integer port) {
        this.port = port;
    }
    @Column(name="created")
    public Date getCreated() {
        return created;
    }
    public void setCreated(Date created) {
        this.created = created;
    }
    @Column(name="updated")
    public Date getUpdated() {
        return updated;
    }
    public void setUpdated(Date updated) {
        this.updated = updated;
    }
    @Column(name="valid")
    public Integer getValid() {
        return valid;
    }
    public void setValid(Integer valid) {
        this.valid = valid;
    }
    public String getDbName() {
        return dbName;
    }
    public void setDbName(String dbName) {
        this.dbName = dbName;
    }
}

+ 10 - 0
src/main/java/com/yihu/hos/tenant/model/TenantModel.java

@ -28,6 +28,16 @@ public class TenantModel extends IdModel {
    private Integer updatedUnix;
    private Integer valid;
    private Long dataSourceId;
    @Column(name="datasource_id")
    public Long getDataSourceId() {
        return dataSourceId;
    }
    public void setDataSourceId(Long dataSourceId) {
        this.dataSourceId = dataSourceId;
    }
    @Column(name="code")
    public String getCode() {

+ 97 - 0
src/main/java/com/yihu/hos/tenant/service/DBInfoService.java

@ -0,0 +1,97 @@
package com.yihu.hos.tenant.service;
import com.yihu.hos.core.datatype.StringUtil;
import com.yihu.hos.tenant.dao.DBInfoDao;
import com.yihu.hos.tenant.model.DBInfoModel;
import com.yihu.hos.web.framework.model.DetailModelResult;
import com.yihu.hos.web.framework.model.Result;
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 java.util.*;
/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/12/2.
 */
@Service("dBInfoService")
public class DBInfoService {
    public static final String BEAN_ID = "dBInfoService";
    @Autowired
    private DBInfoDao dbInfoDao;
    
    @Value("${spring.data.mongodb.gridFsDatabase}")
    private String dbName;
    public List<DBInfoModel> findDBInfoByName(String name) throws Exception {
        if (name!=null && !StringUtil.isEmpty(name)){
            return dbInfoDao.getDBInfoList(name);
        }else {
            return dbInfoDao.getAllList();
        }
    }
    public Result getDBInfoList(Map<String, Object> params) throws Exception {
        return dbInfoDao.getDBInfoList(params);
    }
    public DBInfoModel getDBInfoById(Long id) throws Exception {
        return dbInfoDao.getEntity(DBInfoModel.class,id);
    }
    public Result addDBInfo(DBInfoModel obj) throws Exception {
        obj.setCreated(new Date());
        obj.setUpdated(new Date());
        dbInfoDao.saveEntity(obj);
        return Result.success("保存成功");
    }
    @Transactional
    public Result updateDBInfo(DBInfoModel obj) throws Exception {
        DBInfoModel DBInfo = dbInfoDao.getEntity(DBInfoModel.class, obj.getId());
        DBInfo.setName(obj.getName());
        DBInfo.setUserName(obj.getUserName());
        DBInfo.setPassword(obj.getPassword());
        DBInfo.setHost(obj.getHost());
        DBInfo.setPort(obj.getPort());
        DBInfo.setValid(obj.getValid());
        DBInfo.setUpdated(new Date());
        dbInfoDao.updateEntity(DBInfo);
        return Result.success("更新成功");
    }
    @Transactional
    public Result deleteDBInfo(Long id) throws Exception {
        DBInfoModel systemApp = dbInfoDao.getEntity(DBInfoModel.class, id);
        dbInfoDao.deleteEntity(systemApp);
        return Result.success("删除成功");
    }
    public DetailModelResult getDataBaseSelectList( String name) {
        try {
            List<DBInfoModel> dbList = findDBInfoByName(name);
            List<Map<String,Object>> detailModelList = new ArrayList<>();
            for (DBInfoModel dbInfoModel : dbList) {
                Map select2 = new HashMap<>();
                select2.put("code" ,dbInfoModel.getId().toString());
                select2.put("value",dbInfoModel.getName());
                detailModelList.add(select2);
            }
            DetailModelResult detailModelResult = DetailModelResult.success("获取数据库实例下拉列表成功");
            detailModelResult.setDetailModelList(detailModelList);
            detailModelResult.setTotalCount(detailModelList.size());
            return detailModelResult;
        } catch (Exception e) {
            return DetailModelResult.error("获取数据库实例下拉列表失败");
        }
    }
}

+ 186 - 0
src/main/java/com/yihu/hos/tenant/service/MySqlImportAndExport.java

@ -0,0 +1,186 @@
package com.yihu.hos.tenant.service;
import com.yihu.hos.tenant.model.DBInfoModel;
import org.springframework.stereotype.Component;
import java.io.*;
/**
 * MYSQL数据库导出/导入 (测试版)
 *
 * @author HZY
 * @vsrsion 1.0
 * Created at 2017/1/18.
 */
@Component
public class MySqlImportAndExport {
//    public static void main(String args[]) throws Exception {
//        DBInfoModel db = new DBInfoModel();
//        db.setUserName("root");
//        db.setPassword("xmjkzl");
//        db.setHost("172.19.103.57");
//        db.setPort(3306);
//        db.setDbName("ccc");
////
////        db.setUserName("root");
////        db.setPassword("123");
////        db.setHost("192.168.131.119");
////        db.setPort(3306);
////        db.setDbName("learn");
//        MySqlImportAndExport mySqlImportAndExport = new MySqlImportAndExport();
////      MySqlImportAndExport.export(db,"e://learn_copy.sql");//这里简单点异常我就直接往上抛
//        mySqlImportAndExport.importSql(db,"e://learn.sql");
//    }
    /**
     * 根据属性文件的配置导出指定位置的指定数据库到指定位置
     *
     * @param db         数据库信息
     * @param exportPath 导出的sql文件路径
     * @throws IOException
     */
    public void export(DBInfoModel db, String exportPath) throws Exception {
        Runtime runtime = Runtime.getRuntime();
//        String mysqlPath = getMysqlPath(db,runtime);
//        System.out.println("安装地址:"+mysqlPath);
        String command = getExportCommand(db, exportPath);
        System.out.println(command);
        runtime.exec(command);//这里简单一点异常我就直接往上抛
    }
    /**
     * 在命令窗口进行mysql的数据库导入一般分三步走:
     * 第一步是登到到mysql; mysql -uusername -ppassword -hhost -Pport -DdatabaseName;如果在登录的时候指定了数据库名则会
     * 直接转向该数据库,这样就可以跳过第二步,直接第三步;
     * 第二步是切换到导入的目标数据库;use 数据库名;
     * 第三步是开始从目标文件导入数据到目标数据库;source importPath;
     *
     * @param db         数据库信息
     * @param importPath 导入的sql文件路径
     * @throws IOException
     */
    public String importSql(DBInfoModel db, String importPath) {
        Runtime runtime = Runtime.getRuntime();
        //因为在命令窗口进行mysql数据库的导入一般分三步走,所以所执行的命令将以字符串数组的形式出现
        String cmdarray[] = getImportCommand(db, importPath);//根据属性文件的配置获取数据库导入所需的命令,组成一个数组
        try {
            //runtime.exec(cmdarray);//这里也是简单的直接抛出异常
            Process process = runtime.exec(cmdarray[0]);
            //执行了第一条命令以后已经登录到mysql了,所以之后就是利用mysql的命令窗口
            //进程执行后面的代码
            OutputStream os = process.getOutputStream();
            OutputStreamWriter writer = new OutputStreamWriter(os);
            //命令1和命令2要放在一起执行
            writer.write(cmdarray[1] + "\r\n" + cmdarray[2]);
            writer.flush();
            writer.close();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
            return e.getMessage();
        }
        return "";
    }
    /**
     * 生成导出sql命令
     * 在拼装命令语句的时候有一点是需要注意的:一般我们在命令窗口直接使用命令来
     * 进行导出的时候可以简单使用“>”来表示导出到什么地方,即mysqldump -uusername -ppassword databaseName > exportPath,
     * 但在Java中这样写是不行的,它需要你用-r明确的指出导出到什么地方,如:
     * mysqldump -uusername -ppassword databaseName -r exportPath。(经验证> 也是可以)
     *
     * @param exportPath 输出路径
     * @return
     */
    public String getExportCommand(DBInfoModel db, String exportPath) {
        StringBuffer command = new StringBuffer();
        //window需要进入mysql安装的bin目录
        if (System.getProperties().getProperty("os.name").contains("Windows")) {
            System.out.println("===========操作系统是:" + System.getProperties().getProperty("os.name"));
            //TODO 获取mysql的安装路径
            String mysqlPath = "C:\\Program Files\\MySQL\\MySQL Server 5.6\\bin ";
            String cmd = "cmd /c C: && cd " + mysqlPath + " && ";
            command.append(cmd);
        }
        command.append("mysqldump -u").append(db.getUserName()).append(" -p").append(db.getPassword())//密码是用的小p,而端口是用的大P。
                .append(" -h").append(db.getHost()).append(" -P").append(db.getPort()).append(" ").append(db.getDbName()).append(" > ").append(exportPath);
        return command.toString();
    }
    /**
     * 生成导入文件的命令行
     * 如果在登录的时候指定了数据库名则会
     * 直接转向该数据库,这样就可以跳过第二步,直接第三步;
     *
     * @param db         数据库信息
     * @param importPath 导入的sql文件路径
     * @return
     */
    public String[] getImportCommand(DBInfoModel db, String importPath) {
        //第一步,获取登录命令语句
        StringBuffer loginCommand = new StringBuffer();
        //window需要进入mysql安装的bin目录
        if (System.getProperties().getProperty("os.name").contains("Windows")) {
            System.out.println("===========操作系统是:" + System.getProperties().getProperty("os.name"));
            //TODO 获取mysql的安装路径
            String mysqlPath = "C:\\Program Files\\MySQL\\MySQL Server 5.6\\bin ";
            String cmd = "cmd /c C: && cd " + mysqlPath + " && ";
            loginCommand.append(cmd);
        }
        loginCommand.append("mysql --default-character-set=utf8 -u").append(db.getUserName()).append(" -p").append(db.getPassword()).append(" -h").append(db.getHost())
                .append(" -P").append(db.getPort());
        //第二步,创建数据库 获取切换数据库到目标数据库的命令语句
        String switchCommand = new StringBuffer("CREATE DATABASE " + db.getDbName() + "; use ").append(db.getDbName()).append(";").toString();
        //第三步,获取导入的命令语句
        String importCommand = new StringBuffer("source ").append(importPath).toString();
        //需要返回的命令语句数组
        String[] commands = new String[]{loginCommand.toString(), switchCommand, importCommand};
        return commands;
    }
    public String getMysqlPath(DBInfoModel db, Runtime runtime) throws Exception {
        //第一步,获取登录命令语句
        StringBuffer loginCommand = new StringBuffer();
        //window需要进入mysql安装的bin目录
        if (System.getProperties().getProperty("os.name").contains("Windows")) {
            System.out.println("===========操作系统是:" + System.getProperties().getProperty("os.name"));
            //TODO 获取mysql的安装路径
            String mysqlPath = "C:\\Program Files\\MySQL\\MySQL Server 5.6\\bin ";
            String cmd = "cmd /c C: && cd " + mysqlPath + " && ";
            loginCommand.append(cmd);
        }
        loginCommand.append("mysql -u").append(db.getUserName()).append(" -p").append(db.getPassword()).append(" -h").append(db.getHost())
                .append(" -P").append(db.getPort());
        Process process = runtime.exec(loginCommand.toString());
        //执行了第一条命令以后已经登录到mysql了,所以之后就是利用mysql的命令窗口
        //进程执行后面的代码
        OutputStream os = process.getOutputStream();
        OutputStreamWriter writer = new OutputStreamWriter(os);
        //命令1和命令2要放在一起执行
        writer.write("select @@basedir as basePath from dual" + "\r\n");
        writer.flush();
        writer.close();
        //需要返回的命令语句数组
        InputStream is = process.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        process.waitFor();
        is.close();
        reader.close();
        process.destroy();
        os.close();
        return "";
    }
}

+ 43 - 14
src/main/java/com/yihu/hos/tenant/service/TenantService.java

@ -3,6 +3,7 @@ package com.yihu.hos.tenant.service;
import com.yihu.hos.config.MongoConfig;
import com.yihu.hos.core.encrypt.DES;
import com.yihu.hos.tenant.dao.TenantDao;
import com.yihu.hos.tenant.model.DBInfoModel;
import com.yihu.hos.tenant.model.TenantModel;
import com.yihu.hos.web.framework.model.Result;
import com.yihu.hos.web.framework.util.GridFSUtil;
@ -11,6 +12,7 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
@ -37,10 +39,19 @@ public class TenantService {
    @Value("${spring.data.mongodb.gridFsDatabase}")
    private String dbName;
    @Value("${hos.mysql.filePath}")
    private String sqlFilePath;
    @Autowired
    private DBInfoService dbInfoService;
    @Autowired
    private MySqlImportAndExport mySqlImportAndExport;
    public TenantModel findTenantByName(String name) throws Exception {
        List<TenantModel> list = tenantDao.getTenantList(name);
        if (list!=null && !list.isEmpty()){
        if (list != null && !list.isEmpty()) {
            return list.get(0);
        }
        return null;
@ -51,18 +62,36 @@ public class TenantService {
    }
    public TenantModel getTenantById(Long id) throws Exception {
        return tenantDao.getEntity(TenantModel.class,id);
        return tenantDao.getEntity(TenantModel.class, id);
    }
    public Result addTenant(TenantModel obj) throws Exception {
    public Result addTenant(TenantModel obj) {
        String code = UUID.randomUUID().toString();
        obj.setCode(code);
        obj.setCreated(new Date());
        obj.setCreatedUnix(0);
        obj.setUpdated(new Date());
        obj.setUpdatedUnix(0);
        tenantDao.saveEntity(obj);
        return Result.success("保存成功");
        String message = "";
        try {
            //TODO 建库建表操作
            DBInfoModel dbInfo = dbInfoService.getDBInfoById(obj.getDataSourceId());
            DBInfoModel db = new DBInfoModel();
            db.setUserName(dbInfo.getUserName());
            db.setPassword(dbInfo.getPassword());
            db.setHost(dbInfo.getHost());
            db.setPort(dbInfo.getPort());
            db.setDbName(obj.getSchema());
            //建库,建表,数据复制操作
            message = mySqlImportAndExport.importSql(db, sqlFilePath);
            tenantDao.saveEntity(obj);
            return Result.success("保存成功");
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("保存租户信息失败:" + message);
    }
    @Transactional
@ -90,9 +119,9 @@ public class TenantService {
        try {
            fileName = DES.decrypt(fileName, DES.COMMON_PASSWORD);
            boolean succ = GridFSUtil.readFile(mongoConfig.mongoClient().getDatabase(dbName), os, fileName);
            if (succ){
            if (succ) {
                return Result.success("读取文件成功");
            }else {
            } else {
                return Result.success("读取文件失败");
            }
        } catch (Exception e) {
@ -104,10 +133,10 @@ public class TenantService {
    public Result uploadFile(InputStream inputStream, String fileName) {
        try {
            fileName = DES.decrypt(fileName, DES.COMMON_PASSWORD);
            String saveFileName = GridFSUtil.uploadFile(inputStream,fileName,null);
            if (saveFileName != null){
            String saveFileName = GridFSUtil.uploadFile(inputStream, fileName, null);
            if (saveFileName != null) {
                return Result.success("上传文件成功");
            }else {
            } else {
                return Result.error("上传文件失败");
            }
        } catch (Exception e) {
@ -116,13 +145,13 @@ public class TenantService {
        }
    }
    public Result delFile( String fileName) {
    public Result delFile(String fileName) {
        try {
            fileName = DES.decrypt(fileName, DES.COMMON_PASSWORD);
            boolean succ = GridFSUtil.deleteFile( fileName);
            if (succ){
            boolean succ = GridFSUtil.deleteFile(fileName);
            if (succ) {
                return Result.success("删除文件成功");
            }else {
            } else {
                return Result.success("删除文件失败");
            }
        } catch (Exception e) {

+ 2 - 0
src/main/resources/application.yml

@ -59,6 +59,8 @@ spring:
hos:
  zbus:
    url: 192.168.131.119:15555
  mysql:
    filePath: e://learn.sql   #sql文件位置
---
spring:

+ 16 - 11
src/main/webapp/WEB-INF/ehr/jsp/common/indexJs.jsp

@ -102,15 +102,6 @@
                {id: 37, pid: 3, text: '维度类别配置', url: '${contextRoot}/dimension/dimensioncatetory'},
                //用户安全中心
                {id: 7, text: '用户安全', icon: '${staticRoot}/images/index/menu5_icon.png'},
            ];
            if(userRole=="admin"){
                //是管理中心用户,则添加租户管理模块
//                menu = menu.concat(tenantManager);
                 menu.push({id: 70, pid: 7, text: '租户管理', url: '${contextRoot}/tenant/initial'});
            }
            var menu_1 = [
                {id: 71, pid: 7, text: '机构管理', url: '${contextRoot}/org/initial'},
                {id: 72, pid: 7, text: '用户管理', url: '${contextRoot}/user/initial'},
                {id: 73, pid: 7, text: '角色管理', url: '${contextRoot}/role/initial'},
@ -122,9 +113,23 @@
                {id: 93, pid: 9, text: '菜单配置', url: '${contextRoot}/menu/initial'},
                {id: 94, pid: 9, text: '菜单按钮配置', url: '${contextRoot}/menu/menuAction/initial'},
                {id: 95, pid: 9, text: '数据源配置', url: '${contextRoot}/datasource/configSources'},
            ]
            ];
            if(userRole=="admin"){
                //是管理中心用户,则添加租户管理模块
//                menu = menu.concat(tenantManager);
                var menu_1 = [
                    {id: 10, text: '租户管理', icon: '${staticRoot}/images/index/menu1_icon.png'},
                    {id: 101, pid: 10, text: '租户管理', url: '${contextRoot}/tenant/initial'},
                    {id: 102, pid: 10, text: '数据库实例管理', url: '${contextRoot}/tenant/dataBase/initial'}
                ];
                menu =  menu.concat(menu_1);
            }
            menu =  menu.concat(menu_1);
//            var menu_1 = [
//            ]
//            menu =  menu.concat(menu_1);
            me.menuTree = $('#ulTree').ligerTree({
                data: menu,

+ 32 - 0
src/main/webapp/WEB-INF/ehr/jsp/tenant/dataBase/dbInfo.jsp

@ -0,0 +1,32 @@
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="utf-8" %>
<%@include file="/WEB-INF/ehr/commons/jsp/commonInclude.jsp" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<!--######用户管理页面Title设置######-->
<!-- ####### 页面部分 ####### -->
<div class="m-content">
    <!-- ####### 查询条件部分 ####### -->
    <div class="m-form-inline">
        <div class="m-form-group">
            <div class="m-form-control">
                <input type="text" id="txtName" class="l-text-field" placeholder="请输入数据库实例名称"/>
            </div>
            <div class="m-form-control" >
                <label>状态:</label>
                <input type="text" id="valid" class="l-text-field" />
            </div>
            <div class="m-form-control right" >
                <div id="div_new_record" class="l-button">
                    <span><spring:message code="btn.create"/></span>
                </div>
            </div>
        </div>
    </div>
    <!--######菜单信息表######-->
    <div id="div_grid">
    </div>
</div>

+ 152 - 0
src/main/webapp/WEB-INF/ehr/jsp/tenant/dataBase/dbInfoJs.jsp

@ -0,0 +1,152 @@
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="utf-8" %>
<%@include file="/WEB-INF/ehr/commons/jsp/commonInclude.jsp" %>
<script>
    /* *************************** 模块初始化 ***************************** */
    var dbInfo = {
        grid: null,
        dialog: null,
        init: function () {
            this.bindEvents();
            this.initForm();
        },
        initForm: function () {
            var me = this;
            $('.m-retrieve-area').show();
            $("#txtName").ligerSearch({
                onClick:function(value){
                    me.reloadGrid();
            }});
            var dbInfoStatus = liger.get("valid").value;
            if(dbInfoStatus ==undefined || dbInfoStatus ==null || dbInfoStatus.length<=0){
                liger.get("valid").selectValue("");
            }
            me.grid = $("#div_grid").ligerGrid({
                url: '${contextRoot}/tenant/dataBase/getDBList',
                parms: {
                    name: $('#txtName').val(),
                    valid:dbInfoStatus
                },
                columns: [
                    {display: '实例名称', id: 'id', name: 'name', width: '20%'},
                    {display: '主机', name: 'host', width: '15%'},
                    {display: '端口', name: 'port', width: '10%'},
                    {display: '用户', name: 'usrName', width: '10%'},
                    {display: '状态', name: 'valid', width: '10%',align: 'center', render: function (rowdata, rowindex, value) {
                        if(rowdata.valid==1 ){
                            return ' <div style="vertical-align:middle;margin-top: 10px;"><span>有效  </span></div>';
                        }else if(rowdata.valid==0){
                            return ' <div style="vertical-align:middle;margin-top: 10px;"><span>无效 </span></div>';
                        }
                    }},
                    {
                        display: '操作', name: 'operator', width: '40%', render: function (row) {
                        var html = '<div class="m-inline-buttons" style="width:350px;">';
                        html += "<a class=\"m-btn\" style=\"padding-right:10px\" onclick=\"dbInfo.editorDialog('"+row.id+"','disabled')\">查看详情</a>";
                        html += "<a class=\"m-btn-edit\" onclick=\"dbInfo.editorDialog('"+row.id+"','')\"></a>";
                        html += "<a class=\"m-btn-delete\" onclick=\"dbInfo.delete('"+row.id+"')\"></a>";
                        html += '</div>';
                        return html;
                    }
                    }
                ],
                onDblClickRow: function (row) {
                    me.editorDialog(row.id);
                }
            });
        },
        bindEvents: function () {
            var me = this;
            var flag = false;
            $('#div_new_record').click(function () {
                me.editorDialog();
            });
            $("#valid").ligerComboBox({data : [{"value":"全部","code":""},{"value":"有效","code":"1"},{"value":"无效","code":"0"}],
                cancelable:false,
                initIsTriggerEvent: false,
                onSelected: function (value)
                {
                    if (flag) {
                        me.reloadGrid();
                    } else {
                        flag = true;
                    }
                },
                onSuccess:function(data){
                }});
            $(".l-text").css("display","inline-block");
            $(".l-text-wrapper").css("display","inline-block");
        },
        delete:function(id){
            var message = "确定要删除该应用信息吗?";
            jQuery.ligerDialog.confirm(message, function (confirm) {
                if (confirm)
                {
                    $.ajax({ //ajax处理
                        type: "POST",
                        url : "${contextRoot}/tenant/dataBase/deleteDBinfo",
                        dataType : "json",
                        data:{id:id},
                        cache:false,
                        success :function(data){
                            if(data.successFlg) {
                                $.ligerDialog.success(data.message);
                                dbInfo.grid.reload();
                            }
                            else{
                                $.ligerDialog.error(data.message);
                            }
                        },
                        error :function(data){
                            $.ligerDialog.error("Status:"+data.status +"(" +data.statusText+")");
                        }
                    });
                }
            });
        },
        //刷新列表数据
        reloadGrid: function () {
            this.grid.set({
                parms: {name: $('#txtName').val(),valid:$('#valid_val').val()}
            });
            this.grid.reload();
        },
        //编辑弹窗
        editorDialog: function (id, flag) {
            var me = this;
            var title = "新增数据库实例";
            var params = null;
            if (id != undefined && id != null) {
                title = "编辑数据库实例";
                params = {"id": id, "flag": flag};
            }
            me.dialog = $.ligerDialog.open({
                height: 600,
                width: 500,
                title: title,
                url: '${contextRoot}/tenant/dataBase/editorDbInfo',
                //load: true,
                urlParms: params
            });
        },
    anthorize: function (id) {
        },
        //弹窗返回
        dialogSuccess: function (message) {
            $.ligerDialog.success(message);
            dbInfo.reloadGrid();
            dbInfo.dialog.close();
        }
    };
    $(function () {
        dbInfo.init();
    });
</script>

+ 85 - 0
src/main/webapp/WEB-INF/ehr/jsp/tenant/dataBase/editorDbInfo.jsp

@ -0,0 +1,85 @@
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="utf-8" %>
<%@include file="/WEB-INF/ehr/commons/jsp/commonInclude.jsp" %>
<!--######应用管理页面 > 应用详情模板页######-->
<div id="div_info_form" class="m-form-inline" style="padding-top:10px;" data-role-form>
    <input id="flag" value="${flag}" style="display: none">
    <div class="m-form-group">
        <label><span class="red">*&nbsp;</span>实例名称:</label>
        <div class="m-form-control ">
            <div class="l-text">
                <input type="text" class="l-text-field required" placeholder="请输入数据库实例名称" name="name"/>
            </div>
        </div>
    </div>
    <div class="m-form-group">
        <label><span class="red">*&nbsp;</span>用户名:</label>
        <div class="m-form-control">
            <div class="l-text">
                <input type="text" class="l-text-field required" placeholder="请输入实例登录名" name="userName"/>
            </div>
        </div>
    </div>
    <div class="m-form-group">
        <label><span class="red">*&nbsp;</span>登录密码:</label>
        <div class="m-form-control">
            <div class="l-text">
                <input type="text" class="l-text-field required" placeholder="请输入实例登录密码" name="password"/>
            </div>
        </div>
    </div>
    <div class="m-form-group">
        <label><span class="red">*&nbsp;</span>主机名:</label>
        <div class="m-form-control">
            <div class="l-text">
                <input type="text" class="l-text-field required" placeholder="请输入实例主机名" name="host"/>
            </div>
        </div>
    </div>
    <div class="m-form-group">
        <label><span class="red">*&nbsp;</span>端口:</label>
        <div class="m-form-control">
            <div class="l-text">
                <input type="text" class="l-text-field required" placeholder="请输入实例端口号" name="port"/>
            </div>
        </div>
    </div>
    <div class="m-form-group">
        <label><span class="red">*&nbsp;</span>状态:</label>
        <div class="m-form-control ">
            <div class="l-text">
                <input type="text" id="valid"  class="l-text-field required" name="valid">
            </div>
        </div>
    </div>
    <!-- 隐藏字段 -->
    <div class="m-form-group" style="display: none;">
        <input name="id" hidden="hidden"/>
    </div>
    <div class="m-form-bottom">
        <div id="btnCancel" class="l-button l-button-no">
            <span>关闭</span>
        </div>
        <div id="btnEditor" class="l-button" style="display:none">
            <span>编辑</span>
        </div>
        <div id="btnSave" class="l-button">
            <span>保存</span>
        </div>
    </div>
</div>
<style>
    .m-form-group label{width: 135px;}
    .btnGrayUp.required{border: #FF7777 1px solid; float: left;}
</style>

+ 131 - 0
src/main/webapp/WEB-INF/ehr/jsp/tenant/dataBase/editorDbInfoJs.jsp

@ -0,0 +1,131 @@
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="utf-8" %>
<%@include file="/WEB-INF/ehr/commons/jsp/commonInclude.jsp" %>
<script type="text/javascript">
    /* *************************** 模块初始化 ***************************** */
    var editorParam = {
        //form
        actionUrl:"${contextRoot}/tenant/dataBase/addDBInfo",
        init: function () {
            this.toDisable();
            this.bindEvents();
            this.initForm();
        },
        toDisable: function () {
            if ($("#flag").val()=='disabled') {
                $("#btnEditor").show();
                $("#btnSave").hide();
                $("input[name='name']").attr("disabled", "disabled");
                $("input[name='userName']").attr("disabled", "disabled");
                $("input[name='passward']").attr("disabled", "disabled");
                $("input[name='host']").attr("disabled", "disabled");
                $("input[name='port']").attr("disabled", "disabled");
                $("input[name='valid']").attr("disabled", "disabled");
            }
        },
        initForm: function () {
            var me = this;
           var data;
            var modelString = "${model.id}";
            if(modelString!=undefined && modelString!=null && modelString.length>0)
            {
                var valid = "${model.valid}";
                liger.get("valid").selectValue(valid);
               data={
                    id: "${model.id}",
                    name: "${model.name}",
                   userName: "${model.userName}",
                   valid: valid,
                   password: "${model.password}",
                   host: "${model.host}",
                   port: "${model.port}",
                };
                me.actionUrl = "${contextRoot}/tenant/dataBase/updateDBInfo";
            }else{
                liger.get("valid").selectValue("1");//默认有效
            }
            $("#div_info_form").ligerAutoForm({
                data:data,
                validate:{
                    name:"required",
                    userName:"required",
                    password:"required",
                    host:"required",
                    port:"required",
                    valid: {
                        required:true
                    }
                },
            });
        },
        bindEvents: function () {
            var me = this;
            $(".m-form-bottom").on("click","#btnSave",function () {
                $("#btnSave").css("pointer-events","none");
                $("#name_icon").removeClass("required");
                if($("#name_icon").val()=="") {
                    $("#name_icon").addClass("required");
                    if(!$("#div_info_form").ligerAutoForm("validate")){
                        return;
                    }
                    return;
                }
                if(!$("#div_info_form").ligerAutoForm("validate")){
                    return;
                }
                var data = $("#div_info_form").ligerAutoForm("getData");
                $.ajax({ //ajax处理
                    type: "POST",
                    url : me.actionUrl,
                    dataType : "json",
                    data:data,
                    cache:false,
                    success :function(data){
                        if(data.successFlg) {
                            parent.dbInfo.dialogSuccess(data.message);
                        }
                        else{
                            $.ligerDialog.error(data.message);
                        }
                        $("#btnSave").css("pointer-events","");
                    },
                    error :function(data){
                        $.ligerDialog.error("Status:"+data.status +"(" +data.statusText+")");
                        $("#btnSave").css("pointer-events","");
                    }
                });
            });
            $(".m-form-bottom").on("click","#btnEditor",function () {
                        $("#btnEditor").hide();
                        $("#btnSave").show();
                        $("input[name='name']").removeAttr("disabled");
                        $("input[name='userName']").removeAttr("disabled");
                        $("input[name='password']").removeAttr("disabled");
                        $("input[name='host']").removeAttr("disabled");
                        $("input[name='port']").removeAttr("disabled");
                        $("input[name='valid']").removeAttr("disabled");
                        $("#flag").val("");
            });
            $(".m-form-bottom").on("click","#btnCancel",function () {
                parent.dbInfo.dialog.close();
            });
            $("#valid").ligerComboBox({data : [{"value":"有效","code":"1"},{"value":"无效","code":"0"}],
                cancelable:false,
                onSuccess:function(data){
                }});
        }
    };
    $(function () {
        editorParam.init();
    });
</script>
<script type="text/javascript" src="${staticRoot}/lib/jquery/jqueryform.js"></script>

+ 9 - 0
src/main/webapp/WEB-INF/ehr/jsp/tenant/editorTenant.jsp

@ -52,6 +52,15 @@
        </div>
    </div>
    <div class="m-form-group">
        <label><span class="red">*&nbsp;</span>数据库实例:</label>
        <div class="m-form-control ">
            <div class="l-text">
                <input type="text" id="dataSourceId" class="l-text-field required" name="dataSourceId">
            </div>
        </div>
    </div>
    <!-- 隐藏字段 -->
    <div class="m-form-group" style="display: none;">
        <input name="id" hidden="hidden"/>

+ 46 - 2
src/main/webapp/WEB-INF/ehr/jsp/tenant/editorTenantJs.jsp

@ -5,12 +5,16 @@
    /* *************************** 模块初始化 ***************************** */
    var editorParam = {
        //form
        dbListUrl:"${contextRoot}/tenant/dataBase/getDataBaseValues",
        actionUrl:"${contextRoot}/tenant/addTenant",
        init: function () {
            var me = this;
            this.selectDBs("");
            this.toDisable();
            this.bindEvents();
            this.initForm();
        },
        toDisable: function () {
            if ($("#flag").val()=='disabled') {
@ -21,6 +25,8 @@
                $("input[name='passward']").attr("disabled", "disabled");
                $("input[name='schema']").attr("disabled", "disabled");
                $("input[name='valid']").attr("disabled", "disabled");
                $("input[name='datasourceId']").attr("disabled", "disabled");
            }
        },
        initForm: function () {
@ -30,19 +36,25 @@
            if(modelString!=undefined && modelString!=null && modelString.length>0)
            {
                var valid = "${model.valid}";
                var dataSourceId = "${model.dataSourceId}";
                liger.get("valid").selectValue(valid);
               data={
                liger.get("dataSourceId").selectValue(dataSourceId);
                data={
                    id: "${model.id}",
                    name: "${model.name}",
                   loginName: "${model.loginName}",
                   valid: valid,
                   password: "${model.password}",
                   schema: "${model.schema}",
                   dataSourceId: dataSourceId,
                };
                me.actionUrl = "${contextRoot}/tenant/updateTenant";
            }else{
                liger.get("valid").selectValue("1");//默认有效
                liger.get("dataSourceId").selectValue("1");//默认有效
            }
            $("#div_info_form").ligerAutoForm({
                data:data,
@ -58,6 +70,33 @@
            });
        },
        selectDBs: function (q) {
            var me = this;
            $.ajax({ //ajax处理
                type: "GET",
                url : me.dbListUrl,
                dataType : "json",
                async: false,
                data:{"q":q},
                cache:false,
                success :function(data){
                    if(data.successFlg) {
                        debugger
                        $("#dataSourceId").ligerComboBox({data : data.detailModelList,
                            cancelable:false,
                            onSuccess:function(data){
                                alert(1111);
                            }});
                    }
                    else{
                        $.ligerDialog.error(data.message);
                    }
                },
                error :function(data){
                    $.ligerDialog.error("Status:"+data.status +"(" +data.statusText+")");
                }
            });
        },
        bindEvents: function () {
            var me = this;
            $(".m-form-bottom").on("click","#btnSave",function () {
@ -103,12 +142,17 @@
                        $("input[name='password']").removeAttr("disabled");
                        $("input[name='schema']").removeAttr("disabled");
                        $("input[name='valid']").removeAttr("disabled");
                        $("input[name='datasourceId']").removeAttr("disabled");
                        $("#flag").val("");
            });
            $(".m-form-bottom").on("click","#btnCancel",function () {
                parent.tenant.dialog.close();
            });
//            $(".l-text").on("click","#dataSourceId",function () {
//                var q = $(this).val();
//               me.selectDBs(q);
//            });
            $("#valid").ligerComboBox({data : [{"value":"有效","code":"1"},{"value":"无效","code":"0"}],
                cancelable:false,
                onSuccess:function(data){