Commit 216bd5e4 authored by 赵啸非's avatar 赵啸非

初始化提交

parent fa1f6f17
package com.mortals.xhx.common.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.BitSet;
/**
* @author 自动识别文件编码格式
*/
public class EncodeUtil {
private static Logger logger = LoggerFactory.getLogger(EncodeUtil.class);
private static int BYTE_SIZE = 8;
public static String CODE_UTF8 = "UTF-8";
public static String CODE_UTF8_BOM = "UTF-8_BOM";
public static String CODE_GBK = "GBK";
/**
* 通过文件全名称获取编码集名称
*
* @param fullFileName
* @param ignoreBom
* @return
* @throws Exception
*/
public static String getEncode(String fullFileName, boolean ignoreBom) throws Exception {
logger.debug("fullFileName ; {}", fullFileName);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fullFileName));
return getEncode(bis, ignoreBom);
}
/**
* 通过文件缓存流获取编码集名称,文件流必须为未曾
*
* @param bis
* @param ignoreBom 是否忽略utf-8 bom
* @return
* @throws Exception
*/
public static String getEncode(BufferedInputStream bis, boolean ignoreBom) throws Exception {
bis.mark(0);
String encodeType = "未识别";
byte[] head = new byte[3];
bis.read(head);
if (head[0] == -1 && head[1] == -2) {
encodeType = "UTF-16";
} else if (head[0] == -2 && head[1] == -1) {
encodeType = "Unicode";
} else if (head[0] == -17 && head[1] == -69 && head[2] == -65) { //带BOM
if (ignoreBom) {
encodeType = CODE_UTF8;
} else {
encodeType = CODE_UTF8_BOM;
}
} else if ("Unicode".equals(encodeType)) {
encodeType = "UTF-16";
} else if (isUTF8(bis)) {
encodeType = CODE_UTF8;
} else {
encodeType = CODE_GBK;
}
logger.info("result encode type : " + encodeType);
return encodeType;
}
/**
* 是否是无BOM的UTF8格式,不判断常规场景,只区分无BOM UTF8和GBK
*
* @param bis
* @return
*/
private static boolean isUTF8(BufferedInputStream bis) throws Exception {
bis.reset();
//读取第一个字节
int code = bis.read();
do {
BitSet bitSet = convert2BitSet(code);
//判断是否为单字节
if (bitSet.get(0)) {//多字节时,再读取N个字节
if (!checkMultiByte(bis, bitSet)) {//未检测通过,直接返回
return false;
}
} else {
//单字节时什么都不用做,再次读取字节
}
code = bis.read();
} while (code != -1);
return true;
}
/**
* 检测多字节,判断是否为utf8,已经读取了一个字节
*
* @param bis
* @param bitSet
* @return
*/
private static boolean checkMultiByte(BufferedInputStream bis, BitSet bitSet) throws Exception {
int count = getCountOfSequential(bitSet);
byte[] bytes = new byte[count - 1];//已经读取了一个字节,不能再读取
bis.read(bytes);
for (byte b : bytes) {
if (!checkUtf8Byte(b)) {
return false;
}
}
return true;
}
/**
* 检测单字节,判断是否为utf8
*
* @param b
* @return
*/
private static boolean checkUtf8Byte(byte b) throws Exception {
BitSet bitSet = convert2BitSet(b);
return bitSet.get(0) && !bitSet.get(1);
}
/**
* 检测bitSet中从开始有多少个连续的1
*
* @param bitSet
* @return
*/
private static int getCountOfSequential(BitSet bitSet) {
int count = 0;
for (int i = 0; i < BYTE_SIZE; i++) {
if (bitSet.get(i)) {
count++;
} else {
break;
}
}
return count;
}
/**
* 将整形转为BitSet
*
* @param code
* @return
*/
private static BitSet convert2BitSet(int code) {
BitSet bitSet = new BitSet(BYTE_SIZE);
for (int i = 0; i < BYTE_SIZE; i++) {
int tmp3 = code >> (BYTE_SIZE - i - 1);
int tmp2 = 0x1 & tmp3;
if (tmp2 == 1) {
bitSet.set(i);
}
}
return bitSet;
}
/**
* 将一指定编码的文件转换为另一编码的文件
*
* @param oldFullFileName
* @param oldCharsetName
* @param newFullFileName
* @param newCharsetName
*/
public static void convert(String oldFullFileName, String oldCharsetName, String newFullFileName, String newCharsetName) throws Exception {
logger.info("the old file name is : {}, The oldCharsetName is : {}", oldFullFileName, oldCharsetName);
logger.info("the new file name is : {}, The newCharsetName is : {}", newFullFileName, newCharsetName);
StringBuffer content = new StringBuffer();
BufferedReader bin = new BufferedReader(new InputStreamReader(new FileInputStream(oldFullFileName), oldCharsetName));
String line;
while ((line = bin.readLine()) != null) {
content.append(line);
content.append(System.getProperty("line.separator"));
}
newFullFileName = newFullFileName.replace("\\", "/");
File dir = new File(newFullFileName.substring(0, newFullFileName.lastIndexOf("/")));
if (!dir.exists()) {
dir.mkdirs();
}
Writer out = new OutputStreamWriter(new FileOutputStream(newFullFileName), newCharsetName);
out.write(content.toString());
}
}
package com.mortals.xhx.module.setup.mode;
import lombok.Data;
@Data
public class ResourceSetupEntity {
private static final long serialVersionUID = 1L;
/**
* 资源文件地址
*/
private String resourceFilePath;
}
\ No newline at end of file
package com.mortals.xhx.module.setup.web;
import cn.hutool.core.io.FileUtil;
import cn.hutool.db.ds.simple.SimpleDataSource;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.web.BaseController;
import com.mortals.xhx.base.system.upload.service.UploadService;
import com.mortals.xhx.module.setup.mode.DbSetupEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.support.EncodedResource;
......@@ -20,8 +16,6 @@ import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.sql.DataSource;
import java.io.*;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
......@@ -33,17 +27,15 @@ import static com.mortals.framework.web.BaseController.*;
@RestController
@RequestMapping("db")
@Slf4j
public class SetupController {
public class SetupDbController {
@Autowired
private UploadService uploadService;
@PostMapping("/initDb")
@PostMapping("/init")
@UnAuth
public String initDb(@RequestBody DbSetupEntity dbSetupEntity) {
JSONObject ret = new JSONObject();
String busiDesc = "导入数据库";
int code = VALUE_RESULT_SUCCESS;
try {
if (ObjectUtils.isEmpty(dbSetupEntity.getDbFilePath())) {
......@@ -52,11 +44,9 @@ public class SetupController {
if (ObjectUtils.isEmpty(dbSetupEntity.getDbName())) {
throw new AppException("请输入数据库名称");
}
//判断数据库是否已经存在 如果不存在 则链接默认库mysql 再初始化创建库
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setUrl("jdbc:mysql://" + dbSetupEntity.getDbHost() + ":" + dbSetupEntity.getDbPort()+"?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Hongkong");
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());
......@@ -66,25 +56,16 @@ public class SetupController {
connection.setCatalog(dbSetupEntity.getDbName());
/* druidDataSource = new DruidDataSource();
druidDataSource.setUrl("jdbc:mysql://" + dbSetupEntity.getDbHost() + ":" + dbSetupEntity.getDbPort()
+ "/" + dbSetupEntity.getDbName() + "?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Hongkong");
druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
druidDataSource.setUsername(dbSetupEntity.getUserName());
druidDataSource.setPassword(dbSetupEntity.getPassword());
connection = druidDataSource.getConnection();*/
FileSystemResource rc = new FileSystemResource(uploadService.getFilePath(dbSetupEntity.getDbFilePath()));
EncodedResource er = new EncodedResource(rc, "UTF-8");
ScriptUtils.executeSqlScript(connection, er);
ret.put(KEY_RESULT_MSG, "初始化数据库成功!");
} catch (Exception e) {
code = VALUE_RESULT_FAILURE;
log.error("导入数据库失败", e);
ret.put(KEY_RESULT_MSG, e.getMessage());
//doException(request, busiDesc, model, e);
}
ret.put(KEY_RESULT_CODE, code);
return ret.toJSONString();
......@@ -107,8 +88,6 @@ public class SetupController {
//先链接已经存在的数据库
String filepath = uploadService.saveFileUpload(file, "/file/fileupload", null);
//CREATE DATABASE IF NOT EXISTS yourdbname DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
DruidDataSource druidDataSource = new DruidDataSource();
......@@ -119,16 +98,9 @@ public class SetupController {
druidDataSource.setPassword("12345678");
DruidPooledConnection connection = druidDataSource.getConnection();
boolean xhx = databaseExists(connection, "base-platform");
log.info("xhx数据库是否存在:{}", xhx);
/*
FileSystemResource rc = new FileSystemResource(uploadService.getFilePath(filepath));
EncodedResource er = new EncodedResource(rc, "UTF-8");
ScriptUtils.executeSqlScript(connection, er);
*/
} catch (Exception e) {
code = VALUE_RESULT_FAILURE;
log.error("导入数据库失败", e);
......@@ -139,7 +111,7 @@ public class SetupController {
}
//检查bank数据库是否存在
private static boolean databaseExists(Connection conn, String dbName) throws SQLException {
private boolean databaseExists(Connection conn, String dbName) throws SQLException {
ResultSet resultSet = conn.getMetaData().getCatalogs();
while (resultSet.next()) {
if (dbName.equals(resultSet.getString(1))) {
......@@ -150,7 +122,7 @@ public class SetupController {
}
//创建数据库
private void createDatabase(Connection conn, String dbName) throws SQLException {
private boolean createDatabase(Connection conn, String dbName) throws SQLException {
// 检查数据库是否已经存在
if (!databaseExists(conn, dbName)) {
Statement stmt = conn.createStatement();
......@@ -158,10 +130,11 @@ public class SetupController {
stmt.executeUpdate(sql);
log.info("成功创建数据库");
stmt.close();
} else {
log.info("数据库已经存在,无需创建");
return true;
}
}
log.info("数据库已经存在,无需创建与初始化");
return false;
}
}
\ 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.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.ap.GlobalSysInfo;
import com.mortals.framework.exception.AppException;
import com.mortals.xhx.base.system.upload.service.UploadService;
import com.mortals.xhx.common.key.Constant;
import com.mortals.xhx.common.utils.EncodeUtil;
import com.mortals.xhx.module.setup.mode.DbSetupEntity;
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.core.io.FileSystemResource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.jdbc.datasource.init.ScriptUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import static com.mortals.framework.web.BaseController.*;
@RestController
@RequestMapping("resource")
@Slf4j
public class SetupResourceController {
@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();
}
//检查bank数据库是否存在
private boolean databaseExists(Connection conn, String dbName) throws SQLException {
ResultSet resultSet = conn.getMetaData().getCatalogs();
while (resultSet.next()) {
if (dbName.equals(resultSet.getString(1))) {
return true;
}
}
return false;
}
public static void main(String[] args) {
System.out.println(FileUtil.isDirectory("E://pic"));
}
}
\ No newline at end of file
This diff is collapsed.
......@@ -7,15 +7,15 @@ Content-Disposition: form-data; name="file"; filename="file.sql"
< ./base.sql
--WebAppBoundary--
###上传数据库脚本文件
###上传资源文件
POST http://localhost:8081/setup/file/commonupload
Content-Type: multipart/form-data; boundary=WebAppBoundary
--WebAppBoundary
Content-Disposition: form-data; name="file"; filename="file.sql"
Content-Disposition: form-data; name="file"; filename="file.zip"
< ./base.sql
< ./file.zip
--WebAppBoundary--
###测试导入sql数据库文件
......@@ -30,3 +30,12 @@ Content-Type: application/json
"userName": "root",
"password": "12345678"
}
###测试导入资源文件
POST http://localhost:8081/setup/resource/init
Content-Type: application/json
{
"resourceFilePath": "/file/fileupload/1725938407302.zip"
}
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