Commit 83f71736 authored by 赵啸非's avatar 赵啸非

初始化提交

parent a112181a
...@@ -91,6 +91,17 @@ ...@@ -91,6 +91,17 @@
<artifactId>spring-boot-starter-thymeleaf</artifactId> <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency> </dependency>
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.3</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.9</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
......
package com.mortals.xhx.common.code;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* 产品资源部署
*
* @author: zxfei
* @date: 2024/9/14 14:21
*/
public enum ProductDisEnum {
基础服务("base-platform", "基础服务"),
门户服务("portal-platform", "门户服务");
private String value;
private String desc;
ProductDisEnum(String value, String desc) {
this.value = value;
this.desc = desc;
}
public String getValue() {
return this.value;
}
public String getDesc() {
return this.desc;
}
public static ProductDisEnum getByValue(String value) {
for (ProductDisEnum productDisEnum : ProductDisEnum.values()) {
if (productDisEnum.getValue() == value) {
return productDisEnum;
}
}
return null;
}
/**
* 获取Map集合
*
* @param eItem 不包含项
* @return
*/
public static Map<String, String> getEnumMap(String... eItem) {
Map<String, String> resultMap = new LinkedHashMap<>();
for (ProductDisEnum item : ProductDisEnum.values()) {
try {
boolean hasE = false;
for (String e : eItem) {
if (item.getValue() == e) {
hasE = true;
break;
}
}
if (!hasE) {
resultMap.put(item.getValue() + "", item.getDesc());
}
} catch (Exception ex) {
}
}
return resultMap;
}
}
\ No newline at end of file
package com.mortals.xhx.common.utils;
import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Set;
@Slf4j
public class ZipUtils {
public static Set<String> localFiles = null;
/**
* 解压tar.gz压缩包
*
* @param fileName
* @param unZipPath
* @return
*/
public static Set<String> unGzip(String fileName, String unZipPath) {
Set<String> set = new HashSet<>();
try {
InputStream inputStream = FileUtil.getInputStream(fileName);
TarArchiveInputStream fin = new TarArchiveInputStream(new GzipCompressorInputStream(inputStream));
log.info("********开始执行gzip");
TarArchiveEntry entry;
// 将 tar 文件解压到 extractPath 目录下
while ((entry = fin.getNextTarEntry()) != null) {
if (entry.isDirectory()) {
continue;
}
//目标文件位置
File curfile = new File(unZipPath + entry.getName());
File parent = curfile.getParentFile();
log.info("***文件保存的路径" + curfile.getAbsolutePath());
if (!parent.exists()) {
parent.mkdirs();
}
// 将文件写出到解压的目录
IOUtils.copy(fin, new FileOutputStream(curfile));
set.add(curfile.getAbsolutePath());
}
} catch (IOException e) {
e.printStackTrace();
}
if (localFiles == null) {
localFiles = set;
} else {
localFiles.addAll(set);
}
return set;
}
// 解压tar包
public Set<String> unTar(String fileName, String unZipPath) {
Set<String> set = new HashSet<>();
try {
InputStream inputStream = FileUtil.getInputStream(fileName);
TarArchiveInputStream fin = new TarArchiveInputStream(inputStream);
log.info("********开始执行tar");
// File extraceFolder = new File(unZipPath);
TarArchiveEntry entry;
// 将 tar 文件解压到 extractPath 目录下
while ((entry = fin.getNextTarEntry()) != null) {
if (entry.isDirectory()) {
continue;
}
log.info("*********创建目录开始" + unZipPath);
boolean flag = FileUtil.exist(unZipPath);
log.info("***********解压目录创建结束" + flag);
log.info("***文件名称" + entry.getName());
File curfile = new File(unZipPath + entry.getName());
File parent = curfile.getParentFile();
log.info("***文件保存的路径" + curfile.getAbsolutePath());
if (!parent.exists()) {
parent.mkdirs();
}
set.add(curfile.getAbsolutePath());
// 将文件写出到解压的目录
IOUtils.copy(fin, new FileOutputStream(curfile));
}
//fin.close();
} catch (IOException e) {
e.printStackTrace();
}
if (localFiles == null) {
localFiles = set;
} else {
localFiles.addAll(set);
}
return set;
}
public static void main(String[] args) {
String fileName = "E:\\pic\\zip\\base-manager.tar.gz";
String unZipPath = "E:\\pic\\zip\\";
ZipUtils.unGzip(fileName, unZipPath);
}
}
package com.mortals.xhx.module.setup.mode;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
@Data
public abstract class BaseReq implements Serializable {
/**
* 当前页
*/
private Integer page;
/**
* 每页条数
*/
private Integer size;
/**
* 工号
*/
private String workNum;
/**
* 标题
*/
private String title;
/**
* 扣分时间
*/
private Date happenTime;
/**
* 规则编码
*/
private String ruleCode;
private Long ruleId;
private String phone;
/**
* 类型
*/
private String performType;
private Long staffId;
}
...@@ -3,8 +3,7 @@ package com.mortals.xhx.module.setup.mode; ...@@ -3,8 +3,7 @@ package com.mortals.xhx.module.setup.mode;
import lombok.Data; import lombok.Data;
@Data @Data
public class DbSetupEntity { public class DbSetupEntity extends BaseReq {
private static final long serialVersionUID = 1L;
/** /**
* db数据库文件 * db数据库文件
......
package com.mortals.xhx.module.setup.mode;
import lombok.Data;
@Data
public class ProjectSetupEntity extends BaseReq {
/**
* 资源文件地址
*/
private String resourceFilePath;
}
\ No newline at end of file
...@@ -3,8 +3,7 @@ package com.mortals.xhx.module.setup.mode; ...@@ -3,8 +3,7 @@ package com.mortals.xhx.module.setup.mode;
import lombok.Data; import lombok.Data;
@Data @Data
public class ResourceSetupEntity { public class ResourceSetupEntity extends BaseReq {
private static final long serialVersionUID = 1L;
/** /**
* 资源文件地址 * 资源文件地址
......
package com.mortals.xhx.module.setup.web;
import com.mortals.framework.model.PageInfo;
import com.mortals.framework.web.BaseJsonBodyController;
import com.mortals.xhx.module.setup.mode.BaseReq;
import org.springframework.util.ObjectUtils;
import java.util.Map;
import static com.mortals.framework.ap.SysConstains.*;
public abstract class AbstractBaseController<T extends BaseReq> extends BaseJsonBodyController {
protected PageInfo buildPageInfo(T query) {
PageInfo pageInfo = new PageInfo();
if (!ObjectUtils.isEmpty(query) && !ObjectUtils.isEmpty(query.getPage())) {
pageInfo.setCurrPage(query.getPage());
}
if (!ObjectUtils.isEmpty(query) && !ObjectUtils.isEmpty(query.getSize())) {
pageInfo.setPrePageResult(query.getSize());
}
return pageInfo;
}
protected void parsePageInfo(Map<String, Object> model, PageInfo pageInfo) {
model.put(TOTAL, pageInfo.getTotalResult());
model.put(PER_PAGE, pageInfo.getPrePageResult());
model.put(CURRENT_PAGE, pageInfo.getCurrPage());
model.put(LAST_PAGE, pageInfo.getTotalPage());
model.put(PAGEINFO_KEY, pageInfo);
}
}
package com.mortals.xhx.module.setup.web; package com.mortals.xhx.module.setup.web;
import cn.hutool.db.ds.simple.SimpleDataSource;
import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection; import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.druid.proxy.jdbc.ConnectionProxy;
import com.alibaba.druid.util.JdbcUtils;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.annotation.UnAuth; import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.exception.AppException; import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.xhx.base.system.upload.service.UploadService; import com.mortals.xhx.base.system.upload.service.UploadService;
import com.mortals.xhx.module.setup.mode.DbSetupEntity; import com.mortals.xhx.module.setup.mode.DbSetupEntity;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
...@@ -20,6 +24,7 @@ import java.sql.Connection; ...@@ -20,6 +24,7 @@ import java.sql.Connection;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import java.util.Map;
import static com.mortals.framework.web.BaseController.*; import static com.mortals.framework.web.BaseController.*;
...@@ -32,9 +37,71 @@ public class SetupDbController { ...@@ -32,9 +37,71 @@ public class SetupDbController {
@Autowired @Autowired
private UploadService uploadService; private UploadService uploadService;
private int timeout = 1;
private String defaultValidateQuery = "SELECT 'x' FROM DUAL";
protected void init(Map<String, Object> model, Context context) {
// this.addDict(model, "product", ProductDisEnum.getEnumMap());
}
@PostMapping("/connect")
@UnAuth
public String connect(@RequestBody DbSetupEntity dbSetupEntity) {
JSONObject ret = new JSONObject();
int code = VALUE_RESULT_SUCCESS;
try {
if (ObjectUtils.isEmpty(dbSetupEntity.getDbName())) {
throw new AppException("请选择产品数据库名称");
}
SimpleDataSource simpleDataSource = new SimpleDataSource("jdbc:mysql://" + dbSetupEntity.getDbHost() + ":" + dbSetupEntity.getDbPort() + "?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Hongkong"
,dbSetupEntity.getUserName(),dbSetupEntity.getPassword(),"com.mysql.cj.jdbc.Driver");
// simpleDataSource.setUrl("jdbc:mysql://" + dbSetupEntity.getDbHost() + ":" + dbSetupEntity.getDbPort() + "?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Hongkong");
// simpleDataSource.setDriver("com.mysql.cj.jdbc.Driver");
// simpleDataSource.setUser(dbSetupEntity.getUserName());
// simpleDataSource.setPass(dbSetupEntity.getPassword());
//判断数据库是否已经存在 如果不存在 则链接默认库mysql 再初始化创建库
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setUrl("jdbc:mysql://" + dbSetupEntity.getDbHost() + ":" + dbSetupEntity.getDbPort() + "?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Hongkong");
druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
druidDataSource.setUsername(dbSetupEntity.getUserName());
druidDataSource.setPassword(dbSetupEntity.getPassword());
//druidDataSource.setConnectionErrorRetryAttempts(3); // 失败后重连的次数
druidDataSource.setBreakAfterAcquireFailure(true);
Connection connection = simpleDataSource.getConnection();
boolean valid = isValidConnection(connection, null, 0);
if (valid) {
ret.put(KEY_RESULT_MSG, "连接数据库成功!");
} else {
throw new AppException("连接数据库失败!");
}
boolean databaseExists = databaseExists(connection, dbSetupEntity.getDbName());
if (!databaseExists) {
throw new AppException("数据库不存在");
}
} catch (Exception e) {
code = VALUE_RESULT_FAILURE;
log.error("链接数据库异常", e);
ret.put(KEY_RESULT_MSG, e.getMessage());
}
ret.put(KEY_RESULT_CODE, code);
return ret.toJSONString();
}
@PostMapping("/init") @PostMapping("/init")
@UnAuth @UnAuth
public String initDb( DbSetupEntity dbSetupEntity) { public String initDb(@RequestBody DbSetupEntity dbSetupEntity) {
JSONObject ret = new JSONObject(); JSONObject ret = new JSONObject();
int code = VALUE_RESULT_SUCCESS; int code = VALUE_RESULT_SUCCESS;
try { try {
...@@ -137,4 +204,44 @@ public class SetupDbController { ...@@ -137,4 +204,44 @@ public class SetupDbController {
} }
//采用sql模式校验有效性
public boolean isValidConnection(Connection conn, String validateQuery, int validationQueryTimeout) throws Exception {
if (validateQuery == null || validateQuery.isEmpty()) {
validateQuery = this.defaultValidateQuery;
}
if (conn.isClosed()) {
return false;
}
if (conn instanceof DruidPooledConnection) {
conn = ((DruidPooledConnection) conn).getConnection();
}
if (conn instanceof ConnectionProxy) {
conn = ((ConnectionProxy) conn).getRawObject();
}
if (validateQuery == null || validateQuery.isEmpty()) {
return true;
}
int queryTimeout = validationQueryTimeout <= 0 ? timeout : validationQueryTimeout;
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
stmt.setQueryTimeout(queryTimeout);
rs = stmt.executeQuery(validateQuery);
return true;
} catch (Exception e) {
throw new AppException(e.getMessage());
} finally {
JdbcUtils.close(rs);
JdbcUtils.close(stmt);
}
}
} }
\ No newline at end of file
package com.mortals.xhx.module.setup.web;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ZipUtil;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.exception.AppException;
import com.mortals.xhx.base.system.upload.service.UploadService;
import com.mortals.xhx.common.utils.EncodeUtil;
import com.mortals.xhx.module.setup.mode.ResourceSetupEntity;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import static com.mortals.framework.web.BaseController.*;
/**
* 项目部署
* @author: zxfei
* @date: 2024/9/18 13:41
*/
@RestController
@RequestMapping("project")
@Slf4j
public class SetupProjectController {
@Value("${upload.path}")
@Getter
private String filePath;
@Autowired
private UploadService uploadService;
@PostMapping("/init")
@UnAuth
public String initDb(@RequestBody ResourceSetupEntity resourceSetupEntity) {
JSONObject ret = new JSONObject();
int code = VALUE_RESULT_SUCCESS;
try {
if (ObjectUtils.isEmpty(resourceSetupEntity.getResourceFilePath())) {
throw new AppException("请上传资源文件");
}
String targetFilePath = uploadService.getFilePath(resourceSetupEntity.getResourceFilePath());
if (FileUtil.isEmpty(new File(targetFilePath))) {
throw new AppException("部署文件不存在!");
}
if (!FileUtil.getSuffix(resourceSetupEntity.getResourceFilePath()).equals("zip")) {
throw new AppException("部署只支持zip文件!");
}
if(!FileUtil.isDirectory(filePath)){
//部署路径是否存在 如果不存在 创建目录,
FileUtil.mkdir(filePath);
}
String fileEncode = "UTF-8";
try {
fileEncode = EncodeUtil.getEncode(targetFilePath, true);
} catch (Exception e) {
log.error("异常", e);
}
ZipUtil.unzip(targetFilePath, filePath, Charset.forName(fileEncode));
ret.put(KEY_RESULT_MSG, "初始化资源文件成功!");
} catch (Exception e) {
code = VALUE_RESULT_FAILURE;
log.error("导入资源文件失败", e);
ret.put(KEY_RESULT_MSG, e.getMessage());
}
ret.put(KEY_RESULT_CODE, code);
return ret.toJSONString();
}
public static void main(String[] args) {
System.out.println(FileUtil.isDirectory("E://pic"));
}
}
\ No newline at end of file
...@@ -37,7 +37,7 @@ import static com.mortals.framework.web.BaseController.*; ...@@ -37,7 +37,7 @@ import static com.mortals.framework.web.BaseController.*;
@RestController @RestController
@RequestMapping("resource") @RequestMapping("resource")
@Slf4j @Slf4j
public class SetupResourceController { public class SetupResourceController {
@Value("${upload.path}") @Value("${upload.path}")
@Getter @Getter
...@@ -48,7 +48,7 @@ public class SetupResourceController { ...@@ -48,7 +48,7 @@ public class SetupResourceController {
@PostMapping("/init") @PostMapping("/init")
@UnAuth @UnAuth
public String initDb(ResourceSetupEntity resourceSetupEntity) { public String initDb(@RequestBody ResourceSetupEntity resourceSetupEntity) {
JSONObject ret = new JSONObject(); JSONObject ret = new JSONObject();
int code = VALUE_RESULT_SUCCESS; int code = VALUE_RESULT_SUCCESS;
try { try {
......
...@@ -3,10 +3,11 @@ ...@@ -3,10 +3,11 @@
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
</head> </head>
<iframe width=600 height=100 frameborder=0 id="myiframe" name="myiframe"></iframe>
<body> <body>
<h2>文件上传</h2> <h2>文件上传</h2>
<form action="/file/commonupload" method="POST" enctype ="multipart/form-data"> <form action="/file/commonupload" method="POST" enctype ="multipart/form-data" target="myiframe">
<label for="file">数据库文件路径</label><br> <label for="file">数据库文件路径</label><br>
<input type="file" id="file" name="file" value=""><br><br> <input type="file" id="file" name="file" value=""><br><br>
<input type="submit" value="Submit"> <input type="submit" value="Submit">
...@@ -14,20 +15,27 @@ ...@@ -14,20 +15,27 @@
<h2>数据库初始化</h2> <h2>数据库初始化</h2>
<form action="/db/initDb" method="POST"> <form action="/db/init" method="POST" target="myiframe">
<label for="dbFilePath">数据库文件路径</label><br> <label for="dbFilePath">数据库文件路径</label><br>
<input type="text" id="dbFilePath" name="dbFilePath" value="/file/fileupload/1724915454477.sql"><br> <input type="text" id="dbFilePath" name="dbFilePath" style="width: 300px;height: 25px;font-size: 16px" value="/file/fileupload/1724915454477.sql"><br>
<label for="dbHost">数据库host地址</label><br> <label for="dbHost">数据库host地址</label><br>
<input type="text" id="dbHost" name="dbHost" value="localhost"><br> <input type="text" id="dbHost" name="dbHost" style="width: 300px;height: 25px;font-size: 16px" value="localhost" width="100"><br>
<label for="dbName">数据库名称</label><br> <label for="dbName">数据库名称</label><br>
<input type="text" id="dbName" name="dbName" value="test2"><br> <input type="text" id="dbName" name="dbName" style="width: 300px;height: 25px;font-size: 16px" value="test2"><br>
<label for="dbPort">数据库端口</label><br> <label for="dbPort">数据库端口</label><br>
<input type="text" id="dbPort" name="dbPort" value="3306"><br> <input type="text" id="dbPort" name="dbPort" style="width: 300px;height: 25px;font-size: 16px" value="3306"><br>
<label for="userName">数据用户名</label><br> <label for="userName">数据用户名</label><br>
<input type="text" id="userName" name="userName" value="root"><br> <input type="text" id="userName" name="userName" style="width: 300px;height: 25px;font-size: 16px" value="root"><br>
<label for="password">数据密码</label><br> <label for="password">数据密码</label><br>
<input type="password" id="password" name="password" value="12345678"><br><br> <input type="password" id="password" name="password" style="width: 300px;height: 25px;font-size: 16px" value="12345678"><br><br>
<input type="submit" value="Submit">
</form>
<h2>资源文件</h2>
<form action="/resource/init" method="POST" target="myiframe">
<label for="resourceFilePath">资源文件路径</label><br>
<input type="text" id="resourceFilePath" name="resourceFilePath" style="width: 300px;height: 25px;font-size: 16px" value="/file/fileupload/1725938407302.zip"><br><br>
<input type="submit" value="Submit"> <input type="submit" value="Submit">
</form> </form>
......
...@@ -33,6 +33,20 @@ Content-Disposition: form-data; name="file"; filename="file.zip" ...@@ -33,6 +33,20 @@ Content-Disposition: form-data; name="file"; filename="file.zip"
< ./file.zip < ./file.zip
--WebAppBoundary-- --WebAppBoundary--
###测试链接数据库
POST http://localhost:8081/db/connect
Content-Type: application/json
{
"dbHost": "localhost",
"dbName": "test21",
"dbPort": "3306",
"userName": "root",
"password": "12345678"
}
###测试导入sql数据库文件 ###测试导入sql数据库文件
POST http://localhost:8081/db/init POST http://localhost:8081/db/init
Content-Type: application/json Content-Type: application/json
...@@ -45,6 +59,8 @@ Content-Type: application/json ...@@ -45,6 +59,8 @@ Content-Type: application/json
"userName": "root", "userName": "root",
"password": "12345678" "password": "12345678"
} }
###测试导入sql数据库文件 form ###测试导入sql数据库文件 form
POST http://localhost:8081/db/init POST http://localhost:8081/db/init
Content-Type: application/x-www-form-urlencoded Content-Type: application/x-www-form-urlencoded
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment