Commit cd7af517 by henry

删除多的包

1 parent 90cf2390
package org.arch.modules.base.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@ApiModel(description = "oss对象存储DTO")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class DelDTO {
/**
* 文件 ID
*/
@ApiModelProperty(value = "文件ID")
private Long fileId;
/**
* 地址
*/
@ApiModelProperty(value = "地址")
private String url;
}
package org.arch.modules.base.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* 字典 dto
*
* @author
* @date 2023/12/14
*/
@ApiModel(description = "字典 dto")
@Data
public class DictDTO {
/**
* 字典标识
*/
@ApiModelProperty(value = "字典标识", position = 1)
private String key;
}
package org.arch.modules.base.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* oss对象存储
*
* @author admin
* @date 2023/12/05
*/
@ApiModel(description = "oss对象存储DTO")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class DownloadObjectDTO {
/**
* 文件 ID
*/
@ApiModelProperty(value = "文件ID")
private Long fileId;
}
package org.arch.modules.base.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* oss对象存储
*
* @author admin
* @date 2023/12/05
*/
@ApiModel(description = "oss对象存储DTO")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UpLoadDTO {
/**
* 文件 ID
*/
@ApiModelProperty(value = "文件ID")
private Long fileId;
/**
* 地址
*/
@ApiModelProperty(value = "地址")
private String url;
}
package org.arch.modules.base.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* oss对象存储
*
* @author admin
* @date 2023/12/05
*/
@ApiModel(description = "oss对象存储")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UpLoadVO {
/**
* 预览地址
*/
@ApiModelProperty(value = "预览地址", position = 1)
private String viewUrl;
/**
* 下载地址
*/
@ApiModelProperty(value = "下载地址", position = 2)
private String downLoadUrl;
/**
* 文件 ID
*/
@ApiModelProperty(value = "文件 ID", position = 3)
private Long fileId;
}
package org.arch.utils;
public class Constant {
/**
* 创建资产根节点标识
*/
public static final String NO = "无";
/**
* redis过期时间,以秒为单位,一分钟
*/
public static final int EXRP_MINUTE = 60;
/**
* redis过期时间,以秒为单位,一小时
*/
public static final int EXRP_HOUR = 60 * 60;
/**
* redis过期时间,以秒为单位,一天
*/
public static final int EXRP_DAY = 60 * 60 * 24;
/**
* redis-key-前缀-shiro:cache:
*/
public static final String PREFIX_SHIRO_CACHE = "shiro:cache:";
/**
* 用户信息缓存
*/
public static final String USER_ACCOUNT = "user_account:";
/**
* redis-key-前缀-shiro:access_token:
*/
public static final String PREFIX_SHIRO_ACCESS_TOKEN = "shiro:access_token:";
/**
* redis-key-前缀-shiro:refresh_token:
*/
public static final String PREFIX_SHIRO_REFRESH_TOKEN = "shiro:refresh_token:";
/**
* redis-key-前缀-tkv:refresh_token:
*/
public static final String PREFIX_TKV_REFRESH_TOKEN = "tkv:refresh_token:";
/**
* JWT-account:
*/
public static final String ACCOUNT = "account";
/**
* JWT-currentTimeMillis:
*/
public static final String CURRENT_TIME_MILLIS = "currentTimeMillis";
/**
* PASSWORD_MAX_LEN
*/
public static final Integer PASSWORD_MAX_LEN = 8;
//token
public static final int RESCODE_REFTOKEN_MSG = 1006; //刷新TOKEN(有返回数据)
public static final int RESCODE_REFTOKEN = 1007; //刷新TOKEN
public static final int JWT_ERRCODE_NULL = 4000; //Token不存在
public static final int JWT_ERRCODE_EXPIRE = 4001; //Token过期
public static final int JWT_ERRCODE_FAIL = 4002; //验证不通过
//密匙
public static final String JWT_SECRET = "8677df7fc87d23u87k61c89s54312hpk";
public static final String TOKEN_ISSUER = "IT4IT";
//token失效的时间,单位:秒,默认设置3天
public static final Long ACCESS_TOKEN_EXPIRE = 7 * 24 * 60 * 60L;
//accessToken在header中的key
public static final String ACCESS_TOKEN_HEADER_KEY = "accessToken";
//用户sessionKey前缀
public static final String USER_SESSION_KEY = "User:Session:key:";
//用户令牌前缀
public static final String JWT_TOKEN_REDIS_KEY_PREFIX = "UserAuth:JWT:Key:";
//省市区redis key,缓存7天
public static final String AREA_REDIS_KEY = "areaKey";
public static final Long AREA_REDIS_EXPEPIRE = 7 * 24 * 60 * 60L;
//一次最多只能两个时段
public static final Integer EVERY_TIME_MAX_TWO_TIMES = 2;
//排队受理业务人均时长,单位:分钟
public static final Integer LINE_PER_TIMES = 3;
//订单到期规定的时间不能取消订单(分钟)
public static final Integer VALID_EXPIRE_TIME = 120;
//演示系统账户
public static String DEMO_ACCOUNT = "test";
//自动去除表前缀
public static String AUTO_REOMVE_PRE = "true";
//停止计划任务
public static String STATUS_RUNNING_STOP = "stop";
//开启计划任务
public static String STATUS_RUNNING_START = "start";
//通知公告阅读状态-未读
public static String OA_NOTIFY_READ_NO = "0";
//通知公告阅读状态-已读
public static int OA_NOTIFY_READ_YES = 1;
//部门根节点id
public static Long DEPT_ROOT_ID = 0l;
//缓存方式
public static String CACHE_TYPE_REDIS = "redis";
public static String LOG_ERROR = "error";
public static String HTTP = "http://";
/**
* 默认画布信息
*/
public static final String MX_MODEL_GRAPH =
"<mxGraphModel dx=\"908\" dy=\"473\" grid=\"1\" gridSize=\"10\" guides=\"1\" tooltips=\"1\" connect=\"1\" arrows=\"1\" fold=\"1\" page=\"1\" pageScale=\"1\" pageWidth=\"827\" pageHeight=\"1169\" math=\"0\" shadow=\"0\">\n" +
" <root>\n" +
" <mxCell id=\"0\" />\n" +
" <mxCell id=\"1\" parent=\"0\" />\n" +
" </root>\n" +
"</mxGraphModel>\n";
/**
* oss对象存储
*/
public static final String BUCKET_NAME = "com/eadc";
/**
* 解析结构类型 1:线状结构;2:包含结构
*/
public static final Integer STRUCTURE_TYPE_1 = 1;
/**
* 解析结构类型 1:线状结构;2:包含结构
*/
public static final Integer STRUCTURE_TYPE_2 = 2;
/**
* 元模型数据
*/
public static final String META_MODEL_DATA = "meta_model_data";
/**
* 架构视图数据
*/
public static final String ARCHI_VIEW_DATA = "archi_view_data";
/**
* MX模型缓存key
*/
public static final String MX_MODEL_KEY = "MX_MODEL_KEY";
/**
* 业务架构
*/
public static final String ARCHI_BUSINESS ="ARCHI_BUSINESS";
/**
* 业务架构
*/
public static final String ARCHI_APPLICATION ="ARCHI_APPLICATION";
/**
* 业务架构
*/
public static final String ARCHI_TECHNOLOGY ="ARCHI_TECHNOLOGY";
/**
* 业务架构
*/
public static final String ARCHI_SAFE ="ARCHI_SAFE";
/**
* 业务架构
*/
public static final String ARCHI_DATA ="ARCHI_DATA";
public static final String WORD_TYPE="application/vnd.openxmlformats-officedocument.wordprocessingml.document";
public static final String IMAGE_TYPE ="image/png";
}
package org.arch.utils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @ClassName FileUtils
* @Description //TODO
* @Date 2019/1/7 0007 11:19
* @Author Administrator
**/
public class FileUtils {
/**
* 根据文件路径获取文件
*
* @param filePath 文件路径
* @return 文件
*/
public static File getFileByPath(String filePath) {
return new File(filePath);
}
/**
* 转换fileItem
* @param file
* @return
*/
public static FileItem createFileItem(File file) {
FileItemFactory factory = new DiskFileItemFactory(16, null);
FileItem item = factory.createItem("textField",
Constant.WORD_TYPE,
true,
file.getName());
int bytesRead = 0;
byte[] buffer = new byte[8192];
try {
FileInputStream fis = new FileInputStream(file);
OutputStream os = item.getOutputStream();
while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
return item;
}
/**
* 判断文件是否存在,不存在则判断是否创建成功
*
* @param file 文件
* @return {@code true}: 存在或创建成功<br>{@code false}: 不存在或创建失败
*/
public static boolean createOrExistsFile(final File file) {
if (file == null) return false;
// 如果存在,是文件则返回true,是目录则返回false
if (file.exists()) return file.isFile();
if (!createOrExistsDir(file.getParentFile())) return false;
try {
return file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 判断目录是否存在,不存在则判断是否创建成功
*
* @param dirPath 目录路径
* @return {@code true}: 存在或创建成功<br>{@code false}: 不存在或创建失败
*/
public static boolean createOrExistsDir(final String dirPath) {
return createOrExistsDir(getFileByPath(dirPath));
}
/**
* 判断目录是否存在,不存在则判断是否创建成功
*
* @param file 文件
* @return {@code true}: 存在或创建成功<br>{@code false}: 不存在或创建失败
*/
public static boolean createOrExistsDir(final File file) {
// 如果存在,是目录则返回true,是文件则返回false,不存在则返回是否创建成功
return file != null && (file.exists() ? file.isDirectory() : file.mkdirs());
}
/**
* 判断包路径是否存在
*
* @param path 路径
*/
public static void pathExist(String path) {
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
}
/**
* 获得文件名称
*
* @param file
* @return
*/
public static String getFileName(File file) {
if (file == null) return null;
if (file.isDirectory()) return file.getName();
return getFileName(file.getName());
}
/**
* 文件路径
*
* @return {@link String }
*/
public static String filePath(){
return LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd/"));
}
/**
* 获得文件类型的字符串名称
*
* @param name
* @return
*/
public static String getFileName(String name) {
if (name.contains(".")) {
String[] split = name.split("\\.");
return split[0];
}
return name;
}
public static String getFileFullName(String name) {
if (!name.contains(File.separator)) return name;
return name.substring(name.lastIndexOf(File.separator) + 1, name.length());
}
public static String getPathnamePath(String pathname) {
if (!pathname.contains(File.separator)) return pathname;
return pathname.substring(0, pathname.lastIndexOf(File.separator));
}
/**
* 获得文件后缀
*
* @param file
* @return
*/
public static String getFileSuffix(File file) {
if (file == null) return null;
if (file.isDirectory()) new RuntimeException("此文件是目录。");
String name = file.getName();
if (name.contains(".")) return name.split(".")[1];
new RuntimeException("文件【" + name + "】此文件没有扩展名。");
return null;
}
public static String getClassPathFile(String path) {
String reg = "(classes/[\\s\\S]*)";
Pattern compile = Pattern.compile(reg);
Matcher matcher = compile.matcher(path);
if (matcher.find()) {
String group = matcher.group();
group = group.replaceAll("classes/|.class", "").replaceAll("/", ".");
return group;
}
return null;
}
public static Resource[] getResource(String locationPattern) {
Resource[] resources = new Resource[0];
try {
ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
resources = resourcePatternResolver.getResources(locationPattern);
} catch (IOException e) {
e.printStackTrace();
}
return resources;
}
public static Resource getResource(String locationPattern, String fileName) {
Resource[] resources = getResource(locationPattern);
if (resources == null || resources.length <= 0) return null;
for (Resource resource : resources) {
String filename = resource.getFilename();
if (fileName.equals(filename)) {
return resource;
}
}
return null;
}
public static String toString(InputStream inputStream) {
StringBuilder stringBuilder = new StringBuilder();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
boolean firstLine = true;
String line = null;
while (true) {
if (!((line = bufferedReader.readLine()) != null)) break;
if (!firstLine) {
stringBuilder.append(System.getProperty("line.separator"));
} else {
firstLine = false;
}
stringBuilder.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
/**
* 复制文件夹
*
* @param resource 源路径
* @param target 目标路径
*/
public static void copyFolder(File resource, File target) throws Exception {
if (!resource.exists()) {
throw new Exception("源目标路径:[" + resource + "] 不存在...");
}
if (!target.exists()) {
throw new Exception("存放的目标路径:[" + target + "] 不存在...");
}
File[] resourceFiles = resource.listFiles();
for (File file : resourceFiles) {
File file1 = new File(target.getAbsolutePath() + File.separator + resource.getName());
if (file.isFile()) {
System.out.println("文件" + file.getName());
if (!file1.exists()) {
file1.mkdirs();
}
File targetFile1 = new File(file1.getAbsolutePath() + File.separator + file.getName());
copyFile(file, targetFile1);
}
// 复制文件夹
if (file.isDirectory()) {// 复制源文件夹
String dir1 = file.getAbsolutePath();
// 目的文件夹
String dir2 = file1.getAbsolutePath();
copyFolder(dir1, dir2);
}
}
}
/**
* 复制文件夹
*
* @param resource 源路径
* @param target 目标路径
*/
public static void copyFolder(String resource, String target) throws Exception {
copyFolder(new File(resource), new File(target));
}
/**
* 复制文件
*
* @param resource
* @param target
*/
public static void copyFile(File resource, File target) throws Exception {
long start = System.currentTimeMillis();
FileInputStream inputStream = new FileInputStream(resource);
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
FileOutputStream outputStream = new FileOutputStream(target);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
byte[] bytes = new byte[1024 * 10];
int len = 0;
while ((len = inputStream.read(bytes)) != -1) {
bufferedOutputStream.write(bytes, 0, len);
}
bufferedOutputStream.flush();
bufferedInputStream.close();
bufferedOutputStream.close();
inputStream.close();
outputStream.close();
long end = System.currentTimeMillis();
System.out.println("耗时:" + (end - start) / 1000 + " s");
}
public static void copyFile(InputStream resource, String target) throws IOException {
File file = new File(target);
copyFile(resource, file);
}
/**
* @Description 复制文件
* @author Viven
*/
public static void copyFile(InputStream resource, File target) throws IOException {
BufferedInputStream bufferedInputStream = new BufferedInputStream(resource);
FileOutputStream outputStream = new FileOutputStream(target);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
byte[] bytes = new byte[1024 * 10];
int len = 0;
while ((len = bufferedInputStream.read(bytes)) != -1) {
bufferedOutputStream.write(bytes, 0, len);
}
bufferedOutputStream.flush();
bufferedInputStream.close();
bufferedOutputStream.close();
resource.close();
outputStream.close();
}
public static boolean renameFile(File sources, String name) {
if (sources.exists()) {
String absolutePath = sources.getAbsolutePath();
String newName = absolutePath.substring(0, absolutePath.lastIndexOf(File.separator)) + File.separator + name;
File newFile = new File(newName);
return sources.renameTo(newFile);
}
return false;
}
static String REG_IMAGE = ".*(.JPEG|.jpeg|.JPG|.jpg|.png|.PNG)$";
static String REG_GIF = ".*(.GIF|.gif)$";
public static boolean isImage(String path) {
return path.matches(REG_IMAGE);
}
public static boolean isGif(String path) {
return path.matches(REG_GIF);
}
public static void forceDownload(HttpServletResponse response, File file) {
try {
response.setContentType(new MimetypesFileTypeMap().getContentType(file.getName()));
response.setHeader("Content-Disposition", "attachment;fileName="
+ java.net.URLEncoder.encode(file.getName(), "UTF-8"));
response.setHeader("Access-Control-Expose-Headers", "File-Name"); //允许头部信息字段设置
response.addHeader("Access-Control-Allow-Headers", "File-Name"); //允许头部信息字段设置
response.setHeader("File-Name",
java.net.URLEncoder.encode(file.getName(), "UTF-8")); //设置头部额外信息
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "0");
response.setHeader("Last-Modified", new Date().toString());
response.setHeader("ETag", String.valueOf(System.currentTimeMillis()));
response.setHeader("Accept-Ranges", "bytes");
response.setContentLengthLong(file.length());
response.setHeader("Content-Range", "" + file.length());
byte[] buffer = new byte[10240];
FileInputStream fis = null; //文件输入流
OutputStream os = null; //输出流
try {
os = response.getOutputStream();
fis = new FileInputStream(file);
int readTmp = 0;
while ((readTmp = fis.read(buffer)) != -1) {
os.write(buffer, 0, readTmp);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
if (os != null) {
os.flush();
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
// 下载指定文件并返回给前端返回流文件
public static void downloadFile(String filePath, String fileName, HttpServletResponse response) throws IOException {
// 处理文件名称
// if(StringUtils.isNotEmpty(fileName)){
// String[] split = fileName.split("\\.");
// fileName = split[0];
// }
// 设置响应的Header参数
response.reset();
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
// 读取文件内容并将其转换为字节数组
FileInputStream fis = new FileInputStream(filePath);
BufferedInputStream bis = new BufferedInputStream(fis);
byte[] buffer = new byte[bis.available()];
bis.read(buffer);
// 设置文件的MIME类型
response.setContentType("application/octet-stream");
// 设置响应的Content-Disposition头部信息
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
// 将字节数组写入响应的输出流
OutputStream os = response.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(os);
bos.write(buffer);
bos.flush();
// 关闭输出流
bos.close();
bis.close();
}
/**
* 日志备份
*
* @param srcPath 源文件
* @param destDir 目标文件
* @param pdate 计划日期
* @param peirodname
*/
public static void copyLogFile(String srcPath, String destDir, String pdate, String peirodname) {
File file = new File(srcPath);
if (!file.exists()) {
System.out.println("源目录不存在!");
return;
}
if (file.isFile()) {
copyFile(srcPath, destDir);
} else if (file.isDirectory()) {
copyDirectory(srcPath, destDir, pdate, peirodname);
}
//备份之后,删除源文件
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f : files) {
f.delete();
}
file.delete();
}
}
/**
* 复制文件夹
*
* @param srcPath 源文件夹路径
* @param destDir 目标文件夹所在目录
*/
private static void copyDirectory(String srcPath, String destDir, String pdate, String peirodname) {
File srcFile = new File(srcPath);
// 获得待复制的文件夹的名字,比如待复制的文件夹为"D://dir"则获取的名字为"dir"
String dirName = getDirName(srcPath);
// 目标文件夹的完整路径 D://dir20190509_1019
String destPath = destDir + File.separator + dirName + "_" + pdate + "_" + peirodname.replace(":", "");
System.out.println("目标文件夹的完整路径为:" + destPath);
File destDirFile = new File(destPath);
if (!destDirFile.exists()) {
destDirFile.mkdirs();
}
File[] fileList = srcFile.listFiles();
if (fileList.length != 0) {
for (File temp : fileList) {
if (temp.isFile()) {
copyFile(temp.getAbsolutePath(), destPath);
} else if (temp.isDirectory()) {
copyDirectory(temp.getAbsolutePath(), destPath, pdate, peirodname);
}
}
}
}
/**
* 复制文件
*
* @param srcPath 源文件绝对路径
* @param destDir 目标文件所在目录
*/
private static void copyFile(String srcPath, String destDir) {
// 获取待复制文件的文件名
String fileName = srcPath
.substring(srcPath.lastIndexOf(File.separator));
String destPath = destDir + fileName;
File destFile = new File(destPath);
if (destFile.exists() && destFile.isFile()) { // 该路径下已经有一个同名文件
return;
}
File destFileDir = new File(destDir);
destFileDir.mkdirs();
try {
BufferedWriter bw = null;
BufferedReader br = null;
br = new BufferedReader(new FileReader(srcPath));
bw = new BufferedWriter(new FileWriter(destFile));
String dataline;
while ((dataline = br.readLine()) != null) {
bw.write(dataline);
bw.newLine();
bw.flush();
}
br.close();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 复制文件
*
* @param srcPath 源文件绝对路径
* @param destPath 目标文件绝对路径
*/
public static void copyFile2(String srcPath, String destPath) {
// 获取待复制文件的文件名
String fileName = srcPath
.substring(srcPath.lastIndexOf(File.separator));
// String destPath = destDir + fileName;
File destFile = new File(destPath);
// if (destFile.exists() && destFile.isFile()) { // 该路径下已经有一个同名文件
// return;
// }
// File destFileDir = new File(destDir);
// destFileDir.mkdirs();
try {
BufferedWriter bw = null;
BufferedReader br = null;
br = new BufferedReader(new FileReader(srcPath));
bw = new BufferedWriter(new FileWriter(destFile));
String dataline;
while ((dataline = br.readLine()) != null) {
bw.write(dataline);
bw.newLine();
bw.flush();
}
br.close();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取待复制文件夹的文件夹名
*
* @param dir
* @return String
*/
private static String getDirName(String dir) {
if (dir.endsWith(File.separator)) { // 如果文件夹路径以"//"结尾,则先去除末尾的"//"
dir = dir.substring(0, dir.lastIndexOf(File.separator));
}
return dir.substring(dir.lastIndexOf(File.separator) + 1);
}
public static void writeFile(InputStream inputStream, OutputStream outputStream) {
try {
byte[] bytes = new byte[1024];
int len;
while ((len = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close(inputStream);
close(outputStream);
}
}
public static void close(Closeable closeable) {
try {
if (closeable != null) {
closeable.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package org.arch.utils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.util.Base64;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
public class MD5Utils {
/**
* 获取md5字符串
*/
public static String encrypt(String dataStr) {
return encrypt(dataStr.getBytes(StandardCharsets.UTF_8));
}
public static String encrypt(byte[] bytes) {
try {
MessageDigest m = MessageDigest.getInstance("MD5");
m.update(bytes);
byte s[] = m.digest();
String result = "";
for (int i = 0; i < s.length; i++) {
result += Integer.toHexString((0x000000FF & s[i]) | 0xFFFFFF00).substring(6);
}
return result;
} catch (Exception e) {
e.printStackTrace();
}
return StringUtils.EMPTY;
}
public static String key(String u) {
Random random = new Random();
StringBuilder sbr = new StringBuilder();
for (int i = 0; i < 10; i++) {
sbr.append(u.charAt(random.nextInt(u.length())));
}
return sbr.toString();
}
//加盐加密的盐值
private static String saltValue = "jiamiDaSHAGua&521^%sB;f";
/**
* MD5加密,得到32位字符串
*
* @param strSrc
* @return
*/
public static String encryptStr(String strSrc) {
try {
char hexChars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'a', 'b', 'c', 'd', 'e', 'f'};
byte[] bytes = strSrc.getBytes();
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(bytes);
bytes = md.digest();
int j = bytes.length;
char[] chars = new char[j * 2];
int k = 0;
for (int i = 0; i < bytes.length; i++) {
byte b = bytes[i];
chars[k++] = hexChars[b >>> 4 & 0xf];
chars[k++] = hexChars[b & 0xf];
}
return new String(chars);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
throw new RuntimeException("MD5加密出错!!+" + e);
}
}
/**
* MD5加密,获得32位字符串(结果和上一个相同)
*
* @param password
* @return
*/
public static String getMD5(String password) {
try {
// 得到一个信息摘要器
MessageDigest digest = MessageDigest.getInstance("md5");
byte[] result = digest.digest(password.getBytes());
StringBuffer buffer = new StringBuffer();
// 把每一个byte 做一个与运算 0xff;
for (byte b : result) {
// 与运算
int number = b & 0xff;// 加盐
String str = Integer.toHexString(number);
if (str.length() == 1) {
buffer.append("0");
}
buffer.append(str);
}
// 标准的md5加密后的结果
return buffer.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return "";
}
}
/**
* 加盐加密
*
* @param strValue
* @return
* @throws Exception
*/
public static String getMD5Str(String strValue) throws Exception {
MessageDigest md5 = MessageDigest.getInstance("MD5");
String newstr = Base64.encodeBase64String(md5.digest((strValue + saltValue).getBytes()));
return newstr;
}
}
package org.arch;
public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
\ No newline at end of file
......@@ -14,7 +14,7 @@
<modules>
<module>log</module>
<module>office</module>
<module>attach</module>
<module>storage</module>
<module>mybatis</module>
<module>nacos</module>
</modules>
......
......@@ -10,7 +10,7 @@
</parent>
<version>1.0-SNAPSHOT</version>
<name>文件存储</name>
<artifactId>attach</artifactId>
<artifactId>storage</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
......@@ -33,6 +33,16 @@
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
</dependency>
<dependency>
<groupId>org.arch</groupId>
<artifactId>mybatis</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.arch</groupId>
<artifactId>arch-base</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package org.arch.storage.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Slf4j
@Configuration
@ComponentScan("org.arch.storage.config")
public class StoreConfiguration {
public StoreConfiguration(){
log.info("加载StoreConfiguration~~~");
}
}
package org.arch.storage.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.arch.common.entity.BaseEntity;
import java.io.Serializable;
/**
* <p>
* 附件表
* </p>
*
* @author audit
* @since 2020-09-12
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("sys_file")
@ApiModel(value = "File对象", description = "附件表")
public class File extends BaseEntity implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "唯一主键ID")
@TableId(value = "id", type = IdType.AUTO)
@JsonSerialize(using = ToStringSerializer.class)
private Long id;
@ApiModelProperty(value = "原文件名(含拓展名)")
private String fileName;
@ApiModelProperty(value = "文件类型")
private String fileType;
@ApiModelProperty(value = "来源ID(业务ID)")
private String srcId;
@ApiModelProperty(value = "附件功能分类")
private String typeCode;
@ApiModelProperty(value = "组织ID")
private Long orgId;
@ApiModelProperty(value = "服务器端存储文件名")
private String storeFileName;
@ApiModelProperty(value = "附件分类")
private Integer attribute1;
@ApiModelProperty(value = "附件大小(KB)")
private double attribute2;
@ApiModelProperty(value = "弹性扩展字段3")
private String attribute3;
@ApiModelProperty(value = "弹性扩展字段4")
private String attribute4;
@ApiModelProperty(value = "弹性扩展字段5")
private String attribute5;
@ApiModelProperty(value = "版本")
private Long versionId;
@ApiModelProperty(value = "是否储存在oss服务器上0否1是")
private String isOss;
@ApiModelProperty(value = "原ftp文件路径")
private String ftpStoreFileName;
@ApiModelProperty(value = "文件content-type")
private String contentType;
@ApiModelProperty(value = "文件真实地址")
private String url;
/**
* 标题
*/
private String title;
/**
* 名字
*/
private String name;
/**
* 后缀
*/
private String suffix;
/**
* 文件大小
*/
private Long length;
/**
* MD5
*/
private String md5;
/**
* 过期时间
*/
private Long expiry;
/**
* 文件唯一标识
*/
private String fileKey;
/**
* 状态
*/
private Integer status;
/**
* 平台
*/
private String platform;
/**
* 基本路径
*/
private String basePath;
}
package org.arch.storage.mapper;
import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import lombok.SneakyThrows;
import org.arch.storage.entity.File;
import org.arch.utils.MD5Utils;
import org.dromara.x.file.storage.core.FileInfo;
import org.springframework.web.multipart.MultipartFile;
/**
* <p>
* 附件表 Mapper 接口
* </p>
*
* @author audit
* @since 2020-09-12
*/
public interface FileMapper extends BaseMapper<File> {
@SneakyThrows
default File saveFile(FileInfo upload, MultipartFile file) {
File sysFile = new File();
String suffix = FileUtil.getSuffix(upload.getOriginalFilename());
String prefix = FileUtil.getPrefix(upload.getOriginalFilename());
sysFile.setFileName(upload.getOriginalFilename());
sysFile.setContentType(upload.getContentType());
sysFile.setUrl(upload.getUrl());
sysFile.setFileType(suffix);
sysFile.setSuffix(suffix);
String encrypt = MD5Utils.encrypt(file.getBytes());
sysFile.setMd5(encrypt);
sysFile.setFileKey(MD5Utils.key(encrypt));
sysFile.setLength(upload.getSize());
sysFile.setTitle(upload.getOriginalFilename());
sysFile.setName(prefix);
sysFile.setStoreFileName(upload.getFilename());
sysFile.setPlatform(upload.getPlatform());
sysFile.setBasePath(upload.getBasePath());
insert(sysFile);
return sysFile;
}
}
package org.arch.storage.service;
import org.arch.modules.base.dto.DelDTO;
import org.arch.modules.base.dto.DownloadObjectDTO;
import org.arch.modules.base.vo.UpLoadVO;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
/**
* oss对象存储管理
*
* @author makejava
* @since 2023-05-04 13:29:23
*/
public interface OssService {
/**
* oss对象存储上传
*
* @param file {@link MultipartFile}
* @return {@link UpLoadVO}
*/
UpLoadVO upload(MultipartFile file);
/**
* 下载对象
*/
void downloadObject(DownloadObjectDTO params, HttpServletResponse response);
/**
* oss对象存储删除
*
* @param dto 参数
* @return {@link UpLoadVO}
*/
Boolean delObject(DelDTO dto);
}
package org.arch.storage.service.impl;
import cn.hutool.core.io.file.FileNameUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.arch.storage.entity.File;
import org.arch.storage.mapper.FileMapper;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.recorder.FileRecorder;
import org.dromara.x.file.storage.core.upload.FilePartInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Component
public class FileRecorderImpl implements FileRecorder {
@Autowired
private FileMapper fileMapper;
@Override
public boolean save(FileInfo fileInfo) {
return true;
}
@Override
public void update(FileInfo fileInfo) {
}
@Override
public FileInfo getByUrl(String s) {
FileInfo fileInfo = new FileInfo();
File file = fileMapper.selectOne(Wrappers.lambdaQuery(File.class).eq(File::getUrl, s));
if (Objects.nonNull(file)) {
fileInfo.setPlatform(file.getPlatform());
fileInfo.setUrl(s);
fileInfo.setPath(extractDateFromUrl(s) + "/");
fileInfo.setBasePath(file.getBasePath());
fileInfo.setFilename(FileNameUtil.getName(s));
}
return fileInfo;
}
@Override
public boolean delete(String s) {
return true;
}
@Override
public void saveFilePart(FilePartInfo filePartInfo) {
}
@Override
public void deleteFilePartByUploadId(String s) {
}
public static String extractDateFromUrl(String url) {
// 使用正则表达式来匹配日期部分
String regex = "/(\\d{4}/\\d{2}/\\d{2})/";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(url);
if (matcher.find()) {
return matcher.group(1);
} else {
return "Date not found";
}
}
}
package org.arch.storage.service.impl;
import cn.hutool.core.lang.Assert;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.arch.storage.entity.File;
import org.arch.modules.base.dto.DelDTO;
import org.arch.modules.base.dto.DownloadObjectDTO;
import org.arch.modules.base.vo.UpLoadVO;
import org.arch.storage.mapper.FileMapper;
import org.arch.storage.service.OssService;
import org.arch.utils.FileUtils;
import org.dromara.x.file.storage.core.Downloader;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
/**
* oss对象存储管理
*
* @author makejava
* @since 2023-05-04 13:29:24
*/
@Service
@Slf4j
@RequiredArgsConstructor
public class OssServiceImpl implements OssService {
private final FileMapper sysFileMapper;
private final FileStorageService fileStorageService;
/**
* oss对象存储上传
*
* @param file {@link MultipartFile}
* @return {@link UpLoadVO}
*/
@SneakyThrows
@Override
@Transactional(rollbackFor = Exception.class)
public UpLoadVO upload(MultipartFile file) {
UpLoadVO uploadFileVO = new UpLoadVO();
Assert.notNull(file, "上传文件不能为空");
FileInfo upload = fileStorageService.of(file)
.setPath(FileUtils.filePath()).upload();
Assert.notNull(uploadFileVO, "上传失败");
File saveFile = sysFileMapper.saveFile(upload, file);
uploadFileVO.setFileId(saveFile.getId());
return uploadFileVO;
}
@SneakyThrows
@Override
public void downloadObject(DownloadObjectDTO params, HttpServletResponse response) {
File file = sysFileMapper.selectById(params.getFileId());
Assert.notNull(file, "文件不存在");
Downloader download = fileStorageService.download(file.getUrl());
response.setContentType(file.getFileType());
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getFileName(), StandardCharsets.UTF_8.name()));
response.getOutputStream().write(download.bytes());
}
@Override
@Transactional(rollbackFor = Exception.class)
public Boolean delObject(DelDTO dto) {
boolean flag = false;
Long fileId = dto.getFileId();
File file = sysFileMapper.selectById(fileId);
Assert.notNull(file, "文件不存在");
// 判断文件是否存在
FileInfo fileInfo = fileStorageService.getFileInfoByUrl(file.getUrl());
boolean exists = fileStorageService.exists(fileInfo);
Assert.isTrue(exists, "文件不存在");
boolean delete = fileStorageService.delete(fileInfo);
if (delete) {
// 删除文件数据表sys_file里的记录信息
int i = this.sysFileMapper.deleteById(file.getId());
if (i >= 0) {
flag = true;
}
}
return flag;
}
}
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.arch.storage.config.StoreConfiguration
......@@ -41,6 +41,11 @@
<artifactId>arch-base</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.arch</groupId>
<artifactId>storage</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!