Sfoglia il codice sorgente

新增数据还原

wangliang 2 anni fa
parent
commit
6e912563cb

+ 55 - 53
distributed-print-business/src/main/java/com/qmth/distributed/print/business/backup/MySQLDatabaseBackup.java

@@ -1,7 +1,5 @@
 package com.qmth.distributed.print.business.backup;
 
-import cn.hutool.core.date.DateUtil;
-import com.aventrix.jnanoid.jnanoid.NanoIdUtils;
 import com.qmth.teachcloud.common.config.DictionaryConfig;
 import com.qmth.teachcloud.common.contant.SystemConstant;
 import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
@@ -9,12 +7,12 @@ import org.apache.commons.io.FileUtils;
 import org.apache.commons.io.IOUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Component;
 
 import javax.annotation.Resource;
 import java.io.*;
 import java.nio.charset.StandardCharsets;
-import java.util.Date;
 import java.util.Objects;
 import java.util.Optional;
 
@@ -32,27 +30,33 @@ public class MySQLDatabaseBackup {
     @Resource
     DictionaryConfig dictionaryConfig;
 
+    @Value("${db.host}")
+    String host;
+
+    @Value("${db.port}")
+    String port;
+
+    @Value("${db.name}")
+    String databaseName;
+
+    @Value("${db.username}")
+    String username;
+
+    @Value("${db.password}")
+    String password;
+
     /**
      * Java代码实现MySQL数据库导出
      *
-     * @param hostIP
-     * @param userName
-     * @param password
      * @param fileName
-     * @param databaseName
      * @return
      * @throws Exception
      */
-    public boolean exportDatabaseTool(String hostIP, String userName, String password, String fileName, String databaseName) throws Exception {
-//        File saveFile = new File(savePath);
-//        if (!saveFile.exists()) {// 如果目录不存在
-//            saveFile.mkdirs();// 创建文件夹
-//        }
-//        if (!savePath.endsWith(File.separator)) {
-//            savePath = savePath + File.separator;
-//        }
-//        File file = new File(dictionaryConfig.fssLocalFileDomain().getConfig() + File.separator + fileName);
-        File file = new File("/Users/king/Downloads/file-temp/db/backup" + File.separator + fileName);
+    public boolean exportDatabaseTool(String fileName) throws Exception {
+        Optional.ofNullable(fileName).orElseThrow(() -> ExceptionResultEnum.ERROR.exception("文件名不能为空"));
+
+        File file = new File(dictionaryConfig.fssLocalFileDomain().getConfig() + File.separator + fileName);
+//        File file = new File("/Users/king/Downloads/file-temp/db/backup" + File.separator + fileName);
         if (!file.exists()) {
             file.getParentFile().mkdirs();
             file.createNewFile();
@@ -62,7 +66,7 @@ public class MySQLDatabaseBackup {
         BufferedReader bufferedReader = null;
         try {
             printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8));
-            String execSql = "mysqldump -h" + hostIP + " -u" + userName + " -p" + password + " --set-charset=" + StandardCharsets.UTF_8 + " " + databaseName;
+            String execSql = "mysqldump -h" + this.host + " -P" + this.port + " -u" + this.username + " -p" + this.password + " --set-charset=" + StandardCharsets.UTF_8 + " " + this.databaseName;
             Process process = Runtime.getRuntime().exec(execSql);
             InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8);
             bufferedReader = new BufferedReader(inputStreamReader);
@@ -86,31 +90,29 @@ public class MySQLDatabaseBackup {
     /**
      * 删除数据库数据
      *
-     * @param hostIP
-     * @param userName
-     * @param password
-     * @param databaseName
      * @param fileName
      * @param schoolId
      * @throws Exception
      */
-    public void deleteDbTool(String hostIP, String userName, String password, String databaseName, String fileName, Long schoolId) throws Exception {
-//        InputStream inputStream = MySQLDatabaseBackup.class.getClassLoader().getResourceAsStream(fileName);
-//        Optional.ofNullable(inputStream).orElseThrow(() -> ExceptionResultEnum.ERROR.exception(fileName + "未找到"));
-//        File file = new File(dictionaryConfig.fssLocalFileDomain().getConfig() + File.separator + fileName);
-//        if (!file.exists()) {
-//            file.getParentFile().mkdirs();
-//            file.createNewFile();
-//        }
-//        FileUtils.copyInputStreamToFile(inputStream, file);
-
+    public void deleteDbTool(String fileName, Long schoolId) throws Exception {
+        Optional.ofNullable(fileName).orElseThrow(() -> ExceptionResultEnum.ERROR.exception("文件名不能为空"));
         Optional.ofNullable(schoolId).orElseThrow(() -> ExceptionResultEnum.ERROR.exception("学校id不能为空"));
-        File file = new File("/Users/king/Downloads/file-temp/db/delete" + File.separator + DateUtil.format(new Date(), SystemConstant.BACK_UP_DATE_PATTERN) + "_" + NanoIdUtils.randomNanoId() + "_" + schoolId + "_delete.sql");
+
+        InputStream inputStream = MySQLDatabaseBackup.class.getClassLoader().getResourceAsStream(fileName);
+        Optional.ofNullable(inputStream).orElseThrow(() -> ExceptionResultEnum.ERROR.exception(fileName + "未找到"));
+        File file = new File(dictionaryConfig.fssLocalFileDomain().getConfig() + File.separator + fileName);
         if (!file.exists()) {
             file.getParentFile().mkdirs();
             file.createNewFile();
         }
-        FileUtils.copyInputStreamToFile(new FileInputStream(new File(fileName)), file);
+        FileUtils.copyInputStreamToFile(inputStream, file);
+
+//        File file = new File("/Users/king/Downloads/file-temp/db/delete" + File.separator + DateUtil.format(new Date(), SystemConstant.BACK_UP_DATE_PATTERN) + "_" + NanoIdUtils.randomNanoId() + "_" + schoolId + "_delete.sql");
+//        if (!file.exists()) {
+//            file.getParentFile().mkdirs();
+//            file.createNewFile();
+//        }
+//        FileUtils.copyInputStreamToFile(new FileInputStream(new File(fileName)), file);
 
         ByteArrayOutputStream ou = new ByteArrayOutputStream();
         IOUtils.copy(new FileInputStream(file), ou);
@@ -119,7 +121,7 @@ public class MySQLDatabaseBackup {
             string = string.replaceAll("\\#\\{schoolId\\}", String.valueOf(schoolId));
         }
         IOUtils.write(string.getBytes(StandardCharsets.UTF_8), new FileOutputStream(file));
-        String cmdarray[] = {"mysql -h" + hostIP + " -u" + userName + " -p" + password + " " + databaseName, "source " + file.getPath()};
+        String cmdarray[] = {"mysql -h" + this.host + " -P" + this.port + " -u" + this.username + " -p" + this.password + " " + this.databaseName, "source " + file.getPath()};
         Runtime runtime = Runtime.getRuntime();
         Process process = null;
         try {
@@ -150,27 +152,27 @@ public class MySQLDatabaseBackup {
             log.error(SystemConstant.LOG_ERROR, e);
         } finally {
             if (process.waitFor() == 0 && Objects.nonNull(file)) {
-                string = "用户" + "删除数据成功";
+                string = "删除数据成功";
                 IOUtils.write(string.getBytes(StandardCharsets.UTF_8), new FileOutputStream(file));
             }
         }
     }
 
-    public static void main(String[] args) {
-        MySQLDatabaseBackup mySQLDatabaseBackup = new MySQLDatabaseBackup();
-        try {
-            String host = "127.0.0.1", userName = "root", password = "123456789", databaseName = "distributed-v3.2.0";
-            Long schoolId = 290869043907264512L;
-            if (mySQLDatabaseBackup.exportDatabaseTool(host, userName, password, DateUtil.format(new Date(), SystemConstant.BACK_UP_DATE_PATTERN) + "_" + NanoIdUtils.randomNanoId() + "_backup.sql", databaseName)) {
-                System.out.println("数据库成功备份!!!");
-//                deleteDbTool(host, userName, password, databaseName, SystemConstant.PRINT_DELETE_DATA_FILE_NAME, schoolId);
-                mySQLDatabaseBackup.deleteDbTool(host, userName, password, databaseName, "/Users/king/git/distributed-print-service/distributed-print-business/src/main/resources/db/4、delete-data.sql", schoolId);
-                System.out.println("删除数据成功!!!");
-            } else {
-                System.out.println("数据库备份失败!!!");
-            }
-        } catch (Exception e) {
-            e.printStackTrace();
-        }
-    }
+//    public static void main(String[] args) {
+//        MySQLDatabaseBackup mySQLDatabaseBackup = new MySQLDatabaseBackup();
+//        try {
+//            String host = "127.0.0.1", userName = "root", password = "123456789", databaseName = "distributed-v3.2.0";
+//            Long schoolId = 290869043907264512L;
+//            if (mySQLDatabaseBackup.exportDatabaseTool(this.host, userName, password, DateUtil.format(new Date(), SystemConstant.BACK_UP_DATE_PATTERN) + "_" + NanoIdUtils.randomNanoId() + "_backup.sql", databaseName)) {
+//                System.out.println("数据库成功备份!!!");
+////                deleteDbTool(host, userName, password, databaseName, SystemConstant.PRINT_DELETE_DATA_FILE_NAME, schoolId);
+//                mySQLDatabaseBackup.deleteDbTool(host, userName, password, databaseName, "/Users/king/git/distributed-print-service/distributed-print-business/src/main/resources/db/4、delete-data.sql", schoolId);
+//                System.out.println("删除数据成功!!!");
+//            } else {
+//                System.out.println("数据库备份失败!!!");
+//            }
+//        } catch (Exception e) {
+//            e.printStackTrace();
+//        }
+//    }
 }

+ 11 - 0
distributed-print-business/src/main/java/com/qmth/distributed/print/business/bean/params/SysAdminSetParam.java

@@ -29,6 +29,9 @@ public class SysAdminSetParam extends TSchoolPrivilege {
     @ApiModelProperty(value = "第三方统一身份认证地址")
     String teachcloudExchangeSerivePath;
 
+    @ApiModelProperty(value = "同步配置地址")
+    String syncServicePath;
+
     public SysAdminSetParam() {
 
     }
@@ -46,6 +49,14 @@ public class SysAdminSetParam extends TSchoolPrivilege {
         this.teachcloudExchangeSerivePath = teachcloudExchangeSerivePath;
     }
 
+    public String getSyncServicePath() {
+        return syncServicePath;
+    }
+
+    public void setSyncServicePath(String syncServicePath) {
+        this.syncServicePath = syncServicePath;
+    }
+
     public Boolean getAccountSmsVerify() {
         return accountSmsVerify;
     }

+ 16 - 0
distributed-print-business/src/main/java/com/qmth/distributed/print/business/bean/result/SysAdminSetResult.java

@@ -34,6 +34,9 @@ public class SysAdminSetResult implements Serializable {
     @ApiModelProperty(value = "第三方统一身份认证地址")
     String teachcloudExchangeSerivePath;
 
+    @ApiModelProperty(value = "同步配置地址")
+    String syncServicePath;
+
     public SysAdminSetResult() {
 
     }
@@ -47,12 +50,25 @@ public class SysAdminSetResult implements Serializable {
         this.privilegeIdList = privilegeIdList;
     }
 
+    public SysAdminSetResult(Long schoolId, String syncServicePath) {
+        this.schoolId = schoolId;
+        this.syncServicePath = syncServicePath;
+    }
+
     public SysAdminSetResult(Long schoolId, Boolean accountSmsVerify, String teachcloudExchangeSerivePath) {
         this.schoolId = schoolId;
         this.accountSmsVerify = accountSmsVerify;
         this.teachcloudExchangeSerivePath = teachcloudExchangeSerivePath;
     }
 
+    public String getSyncServicePath() {
+        return syncServicePath;
+    }
+
+    public void setSyncServicePath(String syncServicePath) {
+        this.syncServicePath = syncServicePath;
+    }
+
     public String getTeachcloudExchangeSerivePath() {
         return teachcloudExchangeSerivePath;
     }

+ 50 - 3
distributed-print/src/main/java/com/qmth/distributed/print/api/SysAdminSetController.java

@@ -3,6 +3,7 @@ package com.qmth.distributed.print.api;
 
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.qmth.boot.api.constant.ApiConstant;
+import com.qmth.distributed.print.business.backup.MySQLDatabaseBackup;
 import com.qmth.distributed.print.business.bean.params.SysAdminSetParam;
 import com.qmth.distributed.print.business.bean.result.CustomPrivilegeResult;
 import com.qmth.distributed.print.business.bean.result.SysAdminSetResult;
@@ -11,6 +12,7 @@ import com.qmth.teachcloud.common.contant.SystemConstant;
 import com.qmth.teachcloud.common.entity.*;
 import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
 import com.qmth.teachcloud.common.service.*;
+import com.qmth.teachcloud.common.util.JacksonUtil;
 import com.qmth.teachcloud.common.util.Result;
 import com.qmth.teachcloud.common.util.ResultUtil;
 import io.swagger.annotations.*;
@@ -62,8 +64,54 @@ public class SysAdminSetController {
     @Resource
     SysConfigService sysConfigService;
 
-    @ApiOperation(value = "查询自定义菜单权限")
-    @ApiResponses({@ApiResponse(code = 200, message = "菜单权限信息", response = SysPrivilege.class)})
+    @Resource
+    MySQLDatabaseBackup mySQLDatabaseBackup;
+
+    @ApiOperation(value = "数据还原")
+    @ApiResponses({@ApiResponse(code = 200, message = "数据还原信息", response = ResultUtil.class)})
+    @RequestMapping(value = "/backup", method = RequestMethod.POST)
+    public Result sysadminBackup(@ApiParam(value = "学校id ", required = true) @RequestParam Long schoolId) throws Exception {
+        mySQLDatabaseBackup.exportDatabaseTool(SystemConstant.PRINT_DELETE_DATA_FILE_NAME);
+        mySQLDatabaseBackup.deleteDbTool(SystemConstant.PRINT_DELETE_DATA_FILE_NAME, schoolId);
+        return ResultUtil.ok(true);
+    }
+
+    @ApiOperation(value = "同步配置查询")
+    @ApiResponses({@ApiResponse(code = 200, message = "同步配置信息", response = SysAdminSetResult.class)})
+    @RequestMapping(value = "/sync/select", method = RequestMethod.POST)
+    public Result sysadminSyncSelect(@ApiParam(value = "学校id ", required = true) @RequestParam Long schoolId) {
+        SysConfig sysConfigSyncServicePath = commonCacheService.addSysConfigCache(schoolId, SystemConstant.SYNC_SERVICE_PATH);
+        String syncServicePath = null;
+        if (Objects.nonNull(sysConfigSyncServicePath)) {
+            syncServicePath = JacksonUtil.parseJson(sysConfigSyncServicePath.getConfigValue());
+        }
+        return ResultUtil.ok(new SysAdminSetResult(schoolId, syncServicePath));
+    }
+
+    @ApiOperation(value = "同步配置保存")
+    @ApiResponses({@ApiResponse(code = 200, message = "同步配置信息", response = ResultUtil.class)})
+    @RequestMapping(value = "/sync/save", method = RequestMethod.POST)
+    @Transactional
+    public Result sysadminSyncSave(@Valid @RequestBody SysAdminSetParam sysAdminSetParam, BindingResult bindingResult) {
+        if (bindingResult.hasErrors()) {
+            return ResultUtil.error(bindingResult.getAllErrors().get(0).getDefaultMessage());
+        }
+        Optional.ofNullable(sysAdminSetParam.getSyncServicePath()).orElseThrow(() -> ExceptionResultEnum.PARAMS_ERROR.exception("同步配置地址不能为空"));
+
+        SysConfig sysConfigSyncServicePath = commonCacheService.addSysConfigCache(sysAdminSetParam.getSchoolId(), SystemConstant.SYNC_SERVICE_PATH);
+        if (Objects.isNull(sysConfigSyncServicePath)) {
+            sysConfigSyncServicePath = new SysConfig(sysAdminSetParam.getSchoolId(), SystemConstant.SYNC_SERVICE_PATH, "同步配置地址", sysAdminSetParam.getSyncServicePath());
+        } else {
+            sysConfigSyncServicePath.setConfigValue(sysAdminSetParam.getSyncServicePath());
+        }
+        sysConfigService.saveOrUpdate(sysConfigSyncServicePath);
+
+        commonCacheService.removeSysConfigCache(sysAdminSetParam.getSchoolId(), SystemConstant.SYNC_SERVICE_PATH);
+        return ResultUtil.ok(true);
+    }
+
+    @ApiOperation(value = "系统试卷规格配置查询")
+    @ApiResponses({@ApiResponse(code = 200, message = "系统试卷规格配置信息", response = SysPrivilege.class)})
     @RequestMapping(value = "/paper/sys/select", method = RequestMethod.POST)
     public Result sysadminPaperSysSelect() {
         SysConfig sysConfig = commonCacheService.addSysConfigCache(SystemConstant.SYS_PDF_SIZE_LIST);
@@ -111,7 +159,6 @@ public class SysAdminSetController {
         return ResultUtil.ok(true);
     }
 
-
     @ApiOperation(value = "用户验证查询")
     @ApiResponses({@ApiResponse(code = 200, message = "用户验证信息", response = SysAdminSetResult.class)})
     @RequestMapping(value = "/user/select", method = RequestMethod.POST)

+ 1 - 0
teachcloud-common/src/main/java/com/qmth/teachcloud/common/contant/SystemConstant.java

@@ -41,6 +41,7 @@ public class SystemConstant {
     public static final String PDF_SIZE_LIST = "pdf.size.list";
     public static final String ACCOUNT_SMS_VERIFY = "account.sms.verify";
     public static final String TEACHCLOUD_EXCHANGE_SERVICE_PATH = "teachcloud.exchange.serive.path";
+    public static final String SYNC_SERVICE_PATH = "sync.service.path";
     public static final String CHARSET_NAME = "UTF-8";
     //    public static final String CHARSET_GB2312 = "gb2312";
     public static final String CHARSET_GBK = "gbk";

+ 2 - 0
teachcloud-report/src/main/resources/application-dev.properties

@@ -43,7 +43,9 @@ sys.config.adminLogoUrl=http://qmth-test.oss-cn-shenzhen.aliyuncs.com/frontend/w
 sys.config.threadPoolCoreSize=1
 sys.config.customThreadPoolCoreSize=true
 sys.config.sessionActive=2h
+#\u914D\u7F6E\u6559\u7814\u5206\u6790ip
 sys.config.reportUrl=http://localhost:9099/#/student-report/
+#\u914D\u7F6E\u6559\u7814\u5206\u6790ip
 sys.config.loginAuthenUrl=http://127.0.0.1:8057/#/login-authen/
 spring.resources.static-locations=file:${sys.config.serverUpload},classpath:/META-INF/resources/,classpath:/resources/