Commit 015d4257 authored by kang.nie@inzymeits.com's avatar kang.nie@inzymeits.com
Browse files

初始化代码

parent bd38ff8b
Pipeline #3108 failed with stages
in 0 seconds
package com.cusc.nirvana.user.rnr.fp.common.handler;
import com.cusc.nirvana.common.result.Response;
import com.cusc.nirvana.user.exception.CuscUserException;
import com.cusc.nirvana.user.rnr.fp.common.ResponseCode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
* @author yubo
* @since 2022-04-21 20:06
*/
@ControllerAdvice
@Order(0)
public class RnrFpExceptionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(RnrFpExceptionHandler.class);
@ExceptionHandler(CuscUserException.class)
@ResponseBody
@ResponseStatus(HttpStatus.OK)
public Response<?> cuscUserHandler(CuscUserException e) {
LOGGER.warn("cuscRnrHandler Handler code: {}, msg: {}", e.getCode(), e.getMessage());
return Response.createError(e.getMessage(), StringUtils.isBlank(e.getCode()) ? ResponseCode.SYSTEM_ERROR.getCode() : Integer.parseInt(e.getCode()));
}
}
package com.cusc.nirvana.user.rnr.fp.common.po;
import com.baomidou.mybatisplus.annotation.FieldStrategy;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* 指令PO基类
*/
@Data
public class BaseInstructionPO implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 业务主键
*/
@TableField("uuid")
private String uuid;
/**
* 指令标识
*/
@TableField("request_id")
private String requestId;
/**
* 车联网卡ICCID
*/
@TableField("iccid")
private String iccid;
/**
* 创建时间
*/
@TableField(value = "create_time", insertStrategy = FieldStrategy.NEVER, updateStrategy = FieldStrategy.NEVER)
private Date createTime;
}
package com.cusc.nirvana.user.rnr.fp.common.util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class Base64ToMultipartFile implements MultipartFile {
private final byte[] fileContent;
private final String extension;
private final String contentType;
private final String fileName;
/**
* @param base64
* @param dataUri 格式类似于: data:image/png;base64
*/
public Base64ToMultipartFile(String base64, String dataUri, String fileName) {
this.fileContent = Base64.getDecoder().decode(base64.getBytes(StandardCharsets.UTF_8));
if (StringUtils.isNotBlank(dataUri)) {
this.extension = dataUri.split(";")[0].split("/")[1];
this.contentType = dataUri.split(";")[0].split(":")[1];
} else {
this.extension = "jpg";
this.contentType = "image";
}
this.fileName = fileName;
}
// public Base64ToMultipartFile(String base64, String extension, String contentType) {
// this.fileContent = Base64.getDecoder().decode(base64.getBytes(StandardCharsets.UTF_8));
// this.extension = extension;
// this.contentType = contentType;
// }
@Override
public String getName() {
if (StringUtils.isBlank(fileName)) {
return "param_" + System.currentTimeMillis();
} else {
return fileName.split(".")[0];
}
}
@Override
public String getOriginalFilename() {
if (StringUtils.isBlank(fileName)) {
return "file_" + System.currentTimeMillis() + "." + extension;
} else {
return fileName;
}
}
@Override
public String getContentType() {
return contentType;
}
@Override
public boolean isEmpty() {
return fileContent == null || fileContent.length == 0;
}
@Override
public long getSize() {
return fileContent.length;
}
@Override
public byte[] getBytes() throws IOException {
return fileContent;
}
@Override
public ByteArrayInputStream getInputStream() throws IOException {
return new ByteArrayInputStream(fileContent);
}
@Override
public void transferTo(File file) throws IOException, IllegalStateException {
try (FileOutputStream fos = new FileOutputStream(file)) {
fos.write(fileContent);
}
}
}
package com.cusc.nirvana.user.rnr.fp.common.util;
import com.cusc.nirvana.user.rnr.fp.dto.T1FileReqDTO;
import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
/**
* @description: sftp 工具类
*/
@Slf4j
public class CMCCSftpUtil {
//ip地址
private String host;
//端口号
private Integer port;
//路径
private String phoPath;
//用户名
private String username;
//密码
private String password;
//session链接超时时间
private Integer sessionConnectTimeout = 15000;
//channel链接超时时间
private Integer channelConnectedTimeout = 15000;
public CMCCSftpUtil(String host, Integer port, String phoPath, String username, String password, Integer sessionConnectTimeout, Integer channelConnectedTimeout) {
this.host = host;
this.port = port;
this.phoPath = phoPath;
this.username = username;
this.password = password;
this.sessionConnectTimeout = sessionConnectTimeout;
this.channelConnectedTimeout = sessionConnectTimeout;
}
/**
* 检查SFTP目录或文件是否存在
* @param remotePath
* @return
*/
public boolean checkFileExist(String remotePath) throws SftpException, JSchException {
ChannelSftp channelSftp = loginSftp();
try {
channelSftp.ls(remotePath);
return true;
} catch (SftpException e) {
throw e;
}
}
/**
* 文件上传
* @param file
* @return
*/
public String uploadFile(T1FileReqDTO file) throws SftpException, JSchException {
ChannelSftp channelSftp = loginSftp();
String remoteFilePath = "";
if (null == channelSftp) {
return remoteFilePath;
}
phoPath = "/realname/"+file.getPlatformID()+"/accountOpening/"+file.getRequestID();
try {
boolean dirs = createDirs(phoPath, channelSftp);
if (!dirs) {
log.error("Remote path error. path:{}", phoPath);
return null;
}
channelSftp.put(file.getEncryptFile().getPath(), phoPath);
remoteFilePath = phoPath + "/" + new File(file.getEncryptFile().getPath()).getName();
log.info("upload file:::{}", remoteFilePath);
return remoteFilePath;
} catch (SftpException ex) {
log.error("Error upload file", ex);
throw ex;
} finally {
logoutSftp(channelSftp);
}
}
/**
* 文件下载
* @param localDirPath
* @param remoteFilePath
* @return
*/
public String downloadFile(String localDirPath, String remoteFilePath) throws IOException, SftpException, JSchException {
ChannelSftp channelSftp = loginSftp();
OutputStream outputStream = null;
try {
String fileName = remoteFilePath.substring(remoteFilePath.lastIndexOf("/") + 1);
if(!new File(localDirPath).exists()){
new File(localDirPath).mkdirs();
}
String localFilePath = localDirPath+"/"+fileName;
File file = new File(localFilePath);
outputStream = new FileOutputStream(file);
channelSftp.get(remoteFilePath, outputStream);
file.createNewFile();
return localFilePath;
} catch(SftpException | IOException ex) {
ex.printStackTrace();
throw ex;
} finally {
logoutSftp(channelSftp);
if(outputStream!=null){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 登录SFTP
* @return
*/
private ChannelSftp loginSftp() throws JSchException {
JSch jsch = new JSch();
try {
Session sshSession = jsch.getSession(username, host, port);
sshSession.setPassword(password);
sshSession.setConfig("StrictHostKeyChecking", "no");
sshSession.connect(sessionConnectTimeout);
Channel channel = sshSession.openChannel("sftp");
channel.connect(channelConnectedTimeout);
ChannelSftp channelSftp = (ChannelSftp) channel;
return channelSftp;
} catch (JSchException e) {
log.warn("登录SFTP失败{}",e.getMessage());
ChannelSftp channelSftp = null;
return channelSftp;
}
}
/**
* 关闭SFTP
* @param channelSftp
*/
private void logoutSftp(ChannelSftp channelSftp) throws JSchException {
try {
if( channelSftp == null){
return;
}
if(channelSftp.isConnected()){
channelSftp.disconnect();
}
if(channelSftp.getSession() != null){
channelSftp.getSession().disconnect();
}
} catch(Exception ex) {
ex.printStackTrace();
throw ex;
}
}
/**
* 创建SFTP目录,如果目录不存在就创建
* 加锁,防止创建目录混乱
* @param dirPath
* @param sftp
* @return
*/
private synchronized boolean createDirs(String dirPath, ChannelSftp sftp) throws SftpException {
if (StringUtils.isNotBlank(dirPath)) {
String[] dirs = Arrays.stream(dirPath.split("/")).filter(StringUtils::isNotBlank).toArray(String[]::new);
//将当前位置定位到/,根目录
sftp.cd("/");
for (String dir : dirs) {
try {
sftp.cd(dir);
log.info("Change directory {}", dir);
} catch (Exception e) {
try {
sftp.mkdir(dir);
log.info("Create directory {}", dir);
} catch (SftpException e1) {
log.error("Create directory failure, directory:{}", dir, e1);
e1.printStackTrace();
return false;
}
try {
sftp.cd(dir);
log.info("Change directory {}", dir);
} catch (SftpException e1) {
log.error("Change directory failure, directory:{}", dir, e1);
e1.printStackTrace();
return false;
}
}
}
return true;
}
return false;
}
}
package com.cusc.nirvana.user.rnr.fp.common.util;
import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
/**
* @description: sftp 工具类
*/
@Slf4j
public class CTCCSftpUtil {
//ip地址
private String host;
//端口号
private Integer port;
//路径
private String phoPath;
//用户名
private String username;
//密码
private String password;
//session链接超时时间
private Integer sessionConnectTimeout = 15000;
//channel链接超时时间
private Integer channelConnectedTimeout = 15000;
public CTCCSftpUtil(String host, Integer port, String phoPath, String username, String password, Integer sessionConnectTimeout, Integer channelConnectedTimeout) {
this.host = host;
this.port = port;
this.phoPath = phoPath;
this.username = username;
this.password = password;
this.sessionConnectTimeout = sessionConnectTimeout;
this.channelConnectedTimeout = sessionConnectTimeout;
}
/**
* 检查SFTP目录或文件是否存在
* @param remotePath
* @return
*/
public boolean checkFileExist(String remotePath) throws SftpException, JSchException {
ChannelSftp channelSftp = loginSftp();
try {
channelSftp.ls(remotePath);
return true;
} catch (SftpException e) {
throw e;
}
}
/**
* 文件上传
* @param localFilePath
* @return
*/
public String uploadFile(String localFilePath) throws SftpException, JSchException {
ChannelSftp channelSftp = loginSftp();
String remoteFilePath ="";
if(null == channelSftp){
return remoteFilePath;
}
try {
boolean dirs = createDirs(phoPath, channelSftp);
if (!dirs) {
log.error("Remote path error. path:{}", phoPath);
return null;
}
channelSftp.put(localFilePath, phoPath);
remoteFilePath = phoPath+"/"+new File(localFilePath).getName();
log.info("upload file:::{}", remoteFilePath);
return remoteFilePath;
} catch(SftpException ex) {
log.error("Error upload file", ex);
throw ex;
} finally {
logoutSftp(channelSftp);
}
}
/**
* 文件下载
* @param localDirPath
* @param remoteFilePath
* @return
*/
public String downloadFile(String localDirPath, String remoteFilePath) throws IOException, SftpException, JSchException {
ChannelSftp channelSftp = loginSftp();
OutputStream outputStream = null;
try {
String fileName = remoteFilePath.substring(remoteFilePath.lastIndexOf("/") + 1);
if(!new File(localDirPath).exists()){
new File(localDirPath).mkdirs();
}
String localFilePath = localDirPath+"/"+fileName;
File file = new File(localFilePath);
outputStream = new FileOutputStream(file);
channelSftp.get(remoteFilePath, outputStream);
file.createNewFile();
return localFilePath;
} catch(SftpException | IOException ex) {
ex.printStackTrace();
throw ex;
} finally {
logoutSftp(channelSftp);
if(outputStream!=null){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 登录SFTP
* @return
*/
private ChannelSftp loginSftp() throws JSchException {
JSch jsch = new JSch();
try {
Session sshSession = jsch.getSession(username, host, port);
sshSession.setPassword(password);
sshSession.setConfig("StrictHostKeyChecking", "no");
sshSession.connect(sessionConnectTimeout);
Channel channel = sshSession.openChannel("sftp");
channel.connect(channelConnectedTimeout);
ChannelSftp channelSftp = (ChannelSftp) channel;
return channelSftp;
} catch (JSchException e) {
ChannelSftp channelSftp = null;
log.warn("电信登录SFTP失败{}",e.getMessage());
return channelSftp;
}
}
/**
* 关闭SFTP
* @param channelSftp
*/
private void logoutSftp(ChannelSftp channelSftp) throws JSchException {
try {
if( channelSftp == null){
return;
}
if(channelSftp.isConnected()){
channelSftp.disconnect();
}
if(channelSftp.getSession() != null){
channelSftp.getSession().disconnect();
}
} catch(Exception ex) {
ex.printStackTrace();
throw ex;
}
}
/**
* 创建SFTP目录,如果目录不存在就创建
* 加锁,防止创建目录混乱
* @param dirPath
* @param sftp
* @return
*/
private synchronized boolean createDirs(String dirPath, ChannelSftp sftp) throws SftpException {
if (StringUtils.isNotBlank(dirPath)) {
String[] dirs = Arrays.stream(dirPath.split("/")).filter(StringUtils::isNotBlank).toArray(String[]::new);
//将当前位置定位到/,根目录
sftp.cd("/");
for (String dir : dirs) {
try {
sftp.cd(dir);
log.info("Change directory {}", dir);
} catch (Exception e) {
try {
sftp.mkdir(dir);
log.info("Create directory {}", dir);
} catch (SftpException e1) {
log.error("Create directory failure, directory:{}", dir, e1);
e1.printStackTrace();
return false;
}
try {
sftp.cd(dir);
log.info("Change directory {}", dir);
} catch (SftpException e1) {
log.error("Change directory failure, directory:{}", dir, e1);
e1.printStackTrace();
return false;
}
}
}
return true;
}
return false;
}
}
package com.cusc.nirvana.user.rnr.fp.common.util;
import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
/**
* @description: sftp 工具类
*/
@Component
@Slf4j
public class ChinaMobileSftpUtil {
//ip地址
@Value("${t1.chinaMobile.sftp.client.host:}")
private String host;
//端口号
@Value("${t1.chinaMobile.sftp.client.port:}")
private Integer port;
//用户名
@Value("${t1.chinaMobile.sftp.client.username:}")
private String username;
//密码
@Value("${t1.chinaMobile.sftp.client.password:}")
private String password;
//session链接超时时间
@Value("${t1.chinaMobile.sftp.client.sessionConnectTimeout:15000}")
private Integer sessionConnectTimeout = 15000;
//channel链接超时时间
@Value("${t1.chinaMobile.sftp.client.channelConnectedTimeout:15000}")
private Integer channelConnectedTimeout = 15000;
/**
* 检查SFTP目录或文件是否存在
* @param remotePath
* @return
*/
public boolean checkFileExist(String remotePath) throws SftpException, JSchException {
ChannelSftp channelSftp = loginSftp();
try {
channelSftp.ls(remotePath);
return true;
} catch (SftpException e) {
throw e;
}
}
/**
* 文件上传
* @param localFilePath
* @param remoteDirPath
* @return
*/
public String uploadFile(String localFilePath, String remoteDirPath) throws SftpException, JSchException {
ChannelSftp channelSftp = loginSftp();
try {
boolean dirs = createDirs(remoteDirPath, channelSftp);
if (!dirs) {
log.error("Remote path error. path:{}", remoteDirPath);
return null;
}
channelSftp.put(localFilePath, remoteDirPath);
String remoteFilePath = remoteDirPath+"/"+new File(localFilePath).getName();
log.info("upload file:::{}", remoteFilePath);
return remoteFilePath;
} catch(SftpException ex) {
log.error("Error upload file", ex);
throw ex;
} finally {
logoutSftp(channelSftp);
}
}
/**
* 文件下载
* @param localDirPath
* @param remoteFilePath
* @return
*/
public String downloadFile(String localDirPath, String remoteFilePath) throws IOException, SftpException, JSchException {
ChannelSftp channelSftp = loginSftp();
OutputStream outputStream = null;
try {
String fileName = remoteFilePath.substring(remoteFilePath.lastIndexOf("/") + 1);
if(!new File(localDirPath).exists()){
new File(localDirPath).mkdirs();
}
String localFilePath = localDirPath+"/"+fileName;
File file = new File(localFilePath);
outputStream = new FileOutputStream(file);
channelSftp.get(remoteFilePath, outputStream);
file.createNewFile();
return localFilePath;
} catch(SftpException | IOException ex) {
ex.printStackTrace();
throw ex;
} finally {
logoutSftp(channelSftp);
if(outputStream!=null){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 登录SFTP
* @return
*/
private ChannelSftp loginSftp() throws JSchException {
JSch jsch = new JSch();
try {
Session sshSession = jsch.getSession(username, host, port);
sshSession.setPassword(password);
sshSession.setConfig("StrictHostKeyChecking", "no");
sshSession.connect(sessionConnectTimeout);
Channel channel = sshSession.openChannel("sftp");
channel.connect(channelConnectedTimeout);
ChannelSftp channelSftp = (ChannelSftp) channel;
return channelSftp;
} catch (JSchException e) {
e.printStackTrace();
throw e;
}
}
/**
* 关闭SFTP
* @param channelSftp
*/
private void logoutSftp(ChannelSftp channelSftp) throws JSchException {
try {
if( channelSftp == null){
return;
}
if(channelSftp.isConnected()){
channelSftp.disconnect();
}
if(channelSftp.getSession() != null){
channelSftp.getSession().disconnect();
}
} catch(Exception ex) {
ex.printStackTrace();
throw ex;
}
}
/**
* 创建SFTP目录,如果目录不存在就创建
* 加锁,防止创建目录混乱
* @param dirPath
* @param sftp
* @return
*/
private synchronized boolean createDirs(String dirPath, ChannelSftp sftp) throws SftpException {
if (StringUtils.isNotBlank(dirPath)) {
String[] dirs = Arrays.stream(dirPath.split("/")).filter(StringUtils::isNotBlank).toArray(String[]::new);
//将当前位置定位到/,根目录
sftp.cd("/");
for (String dir : dirs) {
try {
sftp.cd(dir);
log.info("Change directory {}", dir);
} catch (Exception e) {
try {
sftp.mkdir(dir);
log.info("Create directory {}", dir);
} catch (SftpException e1) {
log.error("Create directory failure, directory:{}", dir, e1);
e1.printStackTrace();
return false;
}
try {
sftp.cd(dir);
log.info("Change directory {}", dir);
} catch (SftpException e1) {
log.error("Change directory failure, directory:{}", dir, e1);
e1.printStackTrace();
return false;
}
}
}
return true;
}
return false;
}
}
package com.cusc.nirvana.user.rnr.fp.common.util;
import lombok.extern.slf4j.Slf4j;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author stayAnd
* @date 2022/4/18
*/
@Slf4j
public class DateUtil {
public static final String YYYYMMDDDOT = "yyyy.MM.dd";
public static final String YYMM_DD_MM = "yy-MM-dd";
public static final String FORMAT_YYYYMMDDHHMMSS = "yyyy-MM-dd HH:mm:ss";
public static Date parseDate(String validDateStr,String pattern) {
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
return simpleDateFormat.parse(validDateStr);
} catch (Exception e) {
log.error("parseDate has error",e);
}
return null;
}
public static String formate(Date time, String pattern) {
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
return simpleDateFormat.format(time);
} catch (Exception e) {
log.error("parseDate has error",e);
}
return null;
}
}
/*
package com.cusc.nirvana.user.rnr.fp.common.util;
import io.minio.*;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
*/
/**
* @Author: wangft
* @CreateTime: 2022/6/2 0002 15:09
* @Description: MinIO工具类
*//*
@Slf4j
public class MinIOUtils {
private static MinioClient minioClient;
private static String endpoint;
private static String bucketName;
private static String accessKey;
private static String secretKey;
private static Integer imgSize;
private static Integer fileSize;
private static final String SEPARATOR = "/";
public MinIOUtils() {
}
public MinIOUtils(String endpoint, String bucketName, String accessKey, String secretKey, Integer imgSize, Integer fileSize) {
MinIOUtils.endpoint = endpoint;
MinIOUtils.bucketName = bucketName;
MinIOUtils.accessKey = accessKey;
MinIOUtils.secretKey = secretKey;
MinIOUtils.imgSize = imgSize;
MinIOUtils.fileSize = fileSize;
createMinioClient();
}
*/
/**
* 创建基于Java端的MinioClient
*//*
public void createMinioClient() {
try {
if (null == minioClient) {
log.info("开始创建 MinioClient...");
minioClient = MinioClient
.builder()
.endpoint(endpoint)
.credentials(accessKey, secretKey)
.build();
createBucket(bucketName);
log.info("创建完毕 MinioClient...");
}
} catch (Exception e) {
log.error("MinIO服务器异常:{}", e);
}
}
*/
/**
* 获取上传文件前缀路径
*
* @return
*//*
public static String getBasisUrl() {
return endpoint + SEPARATOR + bucketName + SEPARATOR;
}
*/
/****************************** Operate Bucket Start ******************************//*
*/
/**
* 启动SpringBoot容器的时候初始化Bucket
* 如果没有Bucket则创建
*
* @throws Exception
*//*
private static void createBucket(String bucketName) throws Exception {
if (!bucketExists(bucketName)) {
minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
}
}
*/
/**
* 判断Bucket是否存在,true:存在,false:不存在
*
* @return
* @throws Exception
*//*
public static boolean bucketExists(String bucketName) throws Exception {
return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
}
*/
/**
* 获得Bucket的策略
*
* @param bucketName
* @return
* @throws Exception
*//*
public static String getBucketPolicy(String bucketName) throws Exception {
String bucketPolicy = minioClient
.getBucketPolicy(
GetBucketPolicyArgs
.builder()
.bucket(bucketName)
.build()
);
return bucketPolicy;
}
*/
/**
* 获得所有Bucket列表
*
* @return
* @throws Exception
*//*
public static List<Bucket> getAllBuckets() throws Exception {
return minioClient.listBuckets();
}
*/
/**
* 根据bucketName获取其相关信息
*
* @param bucketName
* @return
* @throws Exception
*//*
public static Optional<Bucket> getBucket(String bucketName) throws Exception {
return getAllBuckets().stream().filter(b -> b.name().equals(bucketName)).findFirst();
}
*/
/**
* 根据bucketName删除Bucket,true:删除成功; false:删除失败,文件或已不存在
*
* @param bucketName
* @throws Exception
*//*
public static void removeBucket(String bucketName) throws Exception {
minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
}
*/
/****************************** Operate Bucket End ******************************//*
*/
/****************************** Operate Files Start ******************************//*
*/
/**
* 判断文件是否存在
*
* @param bucketName 存储桶
* @param objectName 文件名
* @return
*//*
public static boolean isObjectExist(String bucketName, String objectName) {
boolean exist = true;
try {
minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
} catch (Exception e) {
exist = false;
}
return exist;
}
*/
/**
* 判断文件夹是否存在
*
* @param bucketName 存储桶
* @param objectName 文件夹名称
* @return
*//*
public static boolean isFolderExist(String bucketName, String objectName) {
boolean exist = false;
try {
Iterable<Result<Item>> results = minioClient.listObjects(
ListObjectsArgs.builder().bucket(bucketName).prefix(objectName).recursive(false).build());
for (Result<Item> result : results) {
Item item = result.get();
if (item.isDir() && objectName.equals(item.objectName())) {
exist = true;
}
}
} catch (Exception e) {
exist = false;
}
return exist;
}
*/
/**
* 根据文件前缀查询文件
*
* @param bucketName 存储桶
* @param prefix 前缀
* @param recursive 是否使用递归查询
* @return MinioItem 列表
* @throws Exception
*//*
public static List<Item> getAllObjectsByPrefix(String bucketName,
String prefix,
boolean recursive) throws Exception {
List<Item> list = new ArrayList<>();
Iterable<Result<Item>> objectsIterator = minioClient.listObjects(
ListObjectsArgs.builder().bucket(bucketName).prefix(prefix).recursive(recursive).build());
if (objectsIterator != null) {
for (Result<Item> o : objectsIterator) {
Item item = o.get();
list.add(item);
}
}
return list;
}
*/
/**
* 获取文件流
*
* @param bucketName 存储桶
* @param objectName 文件名
* @return 二进制流
*//*
public static InputStream getObject(String bucketName, String objectName) throws Exception {
return minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
}
*/
/**
* 断点下载
*
* @param bucketName 存储桶
* @param objectName 文件名称
* @param offset 起始字节的位置
* @param length 要读取的长度
* @return 二进制流
*//*
public InputStream getObject(String bucketName, String objectName, long offset, long length) throws Exception {
return minioClient.getObject(
GetObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.offset(offset)
.length(length)
.build());
}
*/
/**
* 获取路径下文件列表
*
* @param bucketName 存储桶
* @param prefix 文件名称
* @param recursive 是否递归查找,false:模拟文件夹结构查找
* @return 二进制流
*//*
public static Iterable<Result<Item>> listObjects(String bucketName, String prefix,
boolean recursive) {
return minioClient.listObjects(
ListObjectsArgs.builder()
.bucket(bucketName)
.prefix(prefix)
.recursive(recursive)
.build());
}
*/
/**
* 使用MultipartFile进行文件上传
*
* @param bucketName 存储桶
* @param file 文件名
* @param objectName 对象名
* @param contentType 类型
* @return
* @throws Exception
*//*
public static ObjectWriteResponse uploadFile(String bucketName, MultipartFile file,
String objectName, String contentType) throws Exception {
InputStream inputStream = file.getInputStream();
return minioClient.putObject(
PutObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.contentType(contentType)
.stream(inputStream, inputStream.available(), -1)
.build());
}
*/
/**
* 上传本地文件
*
* @param bucketName 存储桶
* @param objectName 对象名称
* @param fileName 本地文件路径
*//*
public static ObjectWriteResponse uploadFile(String bucketName, String objectName,
String fileName) throws Exception {
return minioClient.uploadObject(
UploadObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.filename(fileName)
.build());
}
*/
/**
* 通过流上传文件
*
* @param bucketName 存储桶
* @param objectName 文件对象
* @param inputStream 文件流
*//*
public static ObjectWriteResponse uploadFile(String bucketName, String objectName, InputStream inputStream) throws Exception {
return minioClient.putObject(
PutObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.stream(inputStream, inputStream.available(), -1)
.build());
}
*/
/**
* 创建文件夹或目录
*
* @param bucketName 存储桶
* @param objectName 目录路径
*//*
public static ObjectWriteResponse createDir(String bucketName, String objectName) throws Exception {
return minioClient.putObject(
PutObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.stream(new ByteArrayInputStream(new byte[]{}), 0, -1)
.build());
}
*/
/**
* 获取文件信息, 如果抛出异常则说明文件不存在
*
* @param bucketName 存储桶
* @param objectName 文件名称
*//*
public static String getFileStatusInfo(String bucketName, String objectName) throws Exception {
return minioClient.statObject(
StatObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.build()).toString();
}
*/
/**
* 拷贝文件
*
* @param bucketName 存储桶
* @param objectName 文件名
* @param srcBucketName 目标存储桶
* @param srcObjectName 目标文件名
*//*
public static ObjectWriteResponse copyFile(String bucketName, String objectName,
String srcBucketName, String srcObjectName) throws Exception {
return minioClient.copyObject(
CopyObjectArgs.builder()
.source(CopySource.builder().bucket(bucketName).object(objectName).build())
.bucket(srcBucketName)
.object(srcObjectName)
.build());
}
*/
/**
* 删除文件
*
* @param bucketName 存储桶
* @param objectName 文件名称
*//*
public static void removeFile(String bucketName, String objectName) throws Exception {
minioClient.removeObject(
RemoveObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.build());
}
*/
/**
* 批量删除文件
*
* @param bucketName 存储桶
* @param keys 需要删除的文件列表
* @return
*//*
public static void removeFiles(String bucketName, List<String> keys) {
List<DeleteObject> objects = new LinkedList<>();
keys.forEach(s -> {
objects.add(new DeleteObject(s));
try {
removeFile(bucketName, s);
} catch (Exception e) {
log.error("批量删除失败!error:{}", e);
}
});
}
*/
/**
* 获取文件外链
*
* @param bucketName 存储桶
* @param objectName 文件名
* @param expires 过期时间 <=7 秒 (外链有效时间(单位:秒))
* @return url
* @throws Exception
*//*
public static String getPresignedObjectUrl(String bucketName, String objectName, Integer expires) throws Exception {
GetPresignedObjectUrlArgs args = GetPresignedObjectUrlArgs.builder().expiry(expires).bucket(bucketName).object(objectName).build();
return minioClient.getPresignedObjectUrl(args);
}
*/
/**
* 获得文件外链
*
* @param bucketName
* @param objectName
* @return url
* @throws Exception
*//*
public static String getPresignedObjectUrl(String bucketName, String objectName) throws Exception {
GetPresignedObjectUrlArgs args = GetPresignedObjectUrlArgs.builder()
.bucket(bucketName)
.object(objectName)
.method(Method.GET).build();
return minioClient.getPresignedObjectUrl(args);
}
*/
/**
* 将URLDecoder编码转成UTF8
*
* @param str
* @return
* @throws UnsupportedEncodingException
*//*
public static String getUtf8ByURLDecoder(String str) throws UnsupportedEncodingException {
String url = str.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
return URLDecoder.decode(url, "UTF-8");
}
*/
/**
* 获取文件大小
* @param bucketName
* @param objectName
* @return
* @throws Exception
*//*
public static StatObjectResponse getObjectInfo(String bucketName, String objectName) throws Exception {
return minioClient.statObject(StatObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.build());
}
*/
/****************************** Operate Files End ******************************//*
}
*/
/*
package com.cusc.nirvana.user.rnr.fp.common.util;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import com.cusc.nirvana.user.exception.CuscUserException;
import com.cusc.nirvana.user.rnr.fp.dto.OssDownloadRs;
import lombok.Data;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.List;
@Data
public class OSSUtil {
private static String endpoint;
private static String accessKeyId;
private static String accessKeySecret;
private static String bucketName;
private static String prefix;
private static OSS ossClient;
public OSSUtil(String endpoint, String bucketName, String accessKey, String secretKey, String prefix) {
OSSUtil.endpoint = endpoint;
OSSUtil.bucketName = bucketName;
OSSUtil.accessKeyId = accessKey;
OSSUtil.accessKeySecret = secretKey;
OSSUtil.prefix = prefix;
getOSSClient();
}
*/
/**
* 获取oss客户端实例
* @return
*//*
public static OSS getOSSClient(){
// if(null == ossClient){
// // 创建OSSClient实例。
// ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// }
// return ossClient;
return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
}
*/
/**
* 本地文件上传
*
* @param sourceFilePathName 本地文件路径
* @param aimFilePathName 在阿里OSS中保存的可以包含路径的文件名
* @return 返回上传后文件的访问路径
* @throws FileNotFoundException
*//*
public static String upload(String bucketName, String sourceFilePathName, String aimFilePathName) throws FileNotFoundException {
FileInputStream is = new FileInputStream(sourceFilePathName);
if (aimFilePathName.startsWith("/")) {
aimFilePathName = aimFilePathName.substring(1);
}
// 如果需要上传时设置存储类型与访问权限,请参考以下示例代码。
// ObjectMetadata metadata = new ObjectMetadata();
// int indexOfLastDot = aimFilePathName.lastIndexOf(".");
// String suffix = aimFilePathName.substring(indexOfLastDot);
// metadata.setContentType(getContentType(suffix));
//避免文件覆盖
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, aimFilePathName, is);
//避免访问时将图片下载下来
//putObjectRequest.setMetadata(metadata);
OSS ossClient = getOSSClient();
ossClient.putObject(putObjectRequest);
// 设置URL过期时间为100年
Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 100);
URL url = ossClient.generatePresignedUrl(bucketName, aimFilePathName, expiration);
ossClient.shutdown();
return url.toString();
}
*/
/**
* 流上传文件
*
* @param is 文件流
* @param aimFilePathName 在阿里OSS中保存的可以包含路径的文件名
* @return 返回上传后文件的访问路径
* @throws FileNotFoundException
*//*
public static String upload(String bucketName, InputStream is, String aimFilePathName) throws FileNotFoundException {
if (aimFilePathName.startsWith("/")) {
aimFilePathName = aimFilePathName.substring(1);
}
//避免文件覆盖
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, aimFilePathName, is);
//避免访问时将图片下载下来
//putObjectRequest.setMetadata(metadata);
OSS ossClient = getOSSClient();
ossClient.putObject(putObjectRequest);
// 设置URL过期时间为100年
Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 100);
URL url = ossClient.generatePresignedUrl(bucketName, aimFilePathName, expiration);
ossClient.shutdown();
return url.toString();
}
*/
/**
* 获取文件大小
*
* @param aimFilePathName 在阿里OSS中保存的可以包含路径的文件名
* @return 返回上传后文件的访问路径
* @throws FileNotFoundException
*//*
public static Double getFileSize(String bucketName, String aimFilePathName) throws FileNotFoundException {
OSS ossClient = getOSSClient();
boolean existFlag = ossClient.doesObjectExist(bucketName, aimFilePathName);
if(!existFlag){
throw new CuscUserException("500","文件不存在");
}
Double fileSize = 0D;
ObjectMetadata objectMetadata = ossClient.getObjectMetadata(bucketName, aimFilePathName);
fileSize = Double.valueOf(objectMetadata.getContentLength());
ossClient.shutdown();
return fileSize;
}
*/
/**
* multipartFile实现上传
*
* @param multipartFile
* @return
*//*
public static String upload(String bucketName, MultipartFile multipartFile) throws IOException {
// 获取上传的文件的输入流
InputStream inputStream = multipartFile.getInputStream();
// 获取文件名称
String fileName = multipartFile.getOriginalFilename();
// 拼接fileName
fileName = prefix + fileName;
// 如果需要上传时设置存储类型与访问权限
//ObjectMetadata metadata = new ObjectMetadata();
//metadata.setContentType(getContentType(fileName.substring(fileName.lastIndexOf("."))));
// 上传文件到OSS时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg。
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, inputStream);
//putObjectRequest.setMetadata(metadata);
OSS ossClient = getOSSClient();
ossClient.putObject(putObjectRequest);
//文件访问路径
Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 100);
URL url = ossClient.generatePresignedUrl(bucketName, fileName, expiration);
// 关闭ossClient
ossClient.shutdown();
// 把上传到oss的路径返回
return url.toString();
}
*/
/**
* 判断文件是否存在,文件名需要完整路径,
* 如rnr_test/1.jpg
*
* @param objectName
* @return
*//*
public static boolean isFileExist(String bucketName, String objectName) {
OSS ossClient = getOSSClient();
boolean res = ossClient.doesObjectExist(bucketName, objectName);
return res;
}
*/
/**
* 根据文件名获取文件路径
*
* @param bucketName 要下载的文件名
* @param fileName 文件完整名称
* *//*
public static String getFileUrl(String bucketName, String fileName) {
OSS ossClient = getOSSClient();
//文件访问路径
Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 100);
URL url = ossClient.generatePresignedUrl(bucketName, fileName, expiration);
// 关闭ossClient
ossClient.shutdown();
return url.toString();
}
*/
/**
* 通过文件名下载文件到本地
*
* @param objectName 要下载的文件名
* @param localFileName 本地要创建的文件名
*//*
public static void downloadFile(String bucketName, String objectName, String localFileName) {
OSS ossClient = getOSSClient();
// 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖,不存在则新建。
ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(localFileName));
// 关闭OSSClient。
ossClient.shutdown();
}
*/
/**
* 通过文件名获取下载流
*
* @param objectName 要下载的文件名
*//*
public static OssDownloadRs downloadFile(String bucketName, String objectName) {
OSS ossClient = getOSSClient();
// 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖,不存在则新建。
OSSObject object = ossClient.getObject(new GetObjectRequest(bucketName, objectName));
InputStream inputStream = object.getObjectContent();
OssDownloadRs ossDownloadRs = new OssDownloadRs();
ossDownloadRs.setOss(ossClient);
ossDownloadRs.setInputStream(inputStream);
// 关闭OSSClient。
// ossClient.shutdown();
return ossDownloadRs;
}
*/
/**
* 删除文件
*
* @param objectName
*//*
public static void deleteFile(String bucketName, String objectName) {
OSS ossClient = getOSSClient();
ossClient.deleteObject(bucketName, objectName);
ossClient.shutdown();
}
*/
/**
* 批量删除文件或目录
*
* @param keys
*//*
public static void deleteFiles(String bucketName, List<String> keys) {
OSS ossClient = getOSSClient();
// 删除文件。
DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(keys));
java.util.List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
ossClient.shutdown();
}
*/
/**
* 创建文件夹
*
* @param folder
* @return
*//*
public static String createFolder(String bucketName, String folder) {
// 文件夹名
String fileName = folder;
OSS ossClient = getOSSClient();
// 判断文件夹是否存在,不存在则创建
if (!ossClient.doesObjectExist(bucketName, fileName)) {
// 创建文件夹
ossClient.putObject(bucketName, fileName, new ByteArrayInputStream(new byte[0]));
// 得到文件夹名
OSSObject object = ossClient.getObject(bucketName, fileName);
return object.getKey();
}
ossClient.shutdown();
return fileName;
}
*/
/**
* @return String
* @MethodName: contentType
* @Description: 获取文件类型
*//*
private static String contentType(String fileType) {
fileType = fileType.toLowerCase();
String contentType = "";
if (fileType.equals("bmp")) {
contentType = "image/bmp";
} else if (fileType.equals("gif")) {
contentType = "image/gif";
} else if (fileType.equals("png") || fileType.equals("jpeg") || fileType.equals("jpg")) {
contentType = "image/jpeg";
} else if (fileType.equals("html")) {
contentType = "text/html";
} else if (fileType.equals("txt")) {
contentType = "text/plain";
} else if (fileType.equals("vsd")) {
contentType = "application/vnd.visio";
} else if (fileType.equals("ppt") || fileType.equals("pptx")) {
contentType = "application/vnd.ms-powerpoint";
} else if (fileType.equals("doc") || fileType.equals("docx")) {
contentType = "application/msword";
} else if (fileType.equals("xml")) {
contentType = "text/xml";
} else if (fileType.equals("mp4")) {
contentType = "video/mp4";
} else {
contentType = "application/octet-stream";
}
return contentType;
}
}*/
package com.cusc.nirvana.user.rnr.fp.common.util;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
* Description SnowflakeUtil function
*
* @author zx
* @version 1.0
* @date 2022-06-15 10:42
*/
@Component
@Slf4j
public class SnowflakeUtil {
//为终端ID
private long workerId = 0;
//数据中心ID
private long datacenterId = 1;
private Snowflake snowflake = IdUtil.getSnowflake(workerId, datacenterId);
public synchronized long snowflakeId() {
return snowflake.nextId();
}
public synchronized String snowflakeIdStr() {
return snowflake.nextIdStr();
}
public synchronized long snowflakeId(long workerId, long datacenterId) {
Snowflake snowflake = IdUtil.getSnowflake(workerId, datacenterId);
return snowflake.nextId();
}
}
package com.cusc.nirvana.user.rnr.fp.common.util;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
/**
* @className: WatermarkUtil
* @description: 移动图片加水印
* @author: jk
* @date: 2022/8/9 16:02
* @version: 1.0
**/
public class WatermarkUtil {
/**
* 图片加水印
*
* @param src 源图片
* @param out 输出图片
* @param fontSize 字体大小,设置为 10
* @param alpha 透明度,设置为 60
* @param x 右下角,右边偏移量
* @param y 右下角,底部偏移量
* @param waterMarks 水印文字内容数组,每个 item 代表一行
* @throws IOException
*/
public static void waterPress(InputStream src, OutputStream out, int fontSize, float alpha, int x, int y, String[] waterMarks) throws IOException {
// 读取原图片信息
Image srcImg = ImageIO.read(src);
int srcImgWidth = srcImg.getWidth(null);
int srcImgHeight = srcImg.getHeight(null);
// 加水印
BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
// 得到画笔对象
Graphics2D g = bufImg.createGraphics();
// 设置起点
g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
Font font = new Font("宋体", Font.PLAIN, fontSize);
// 根据图片的背景设置水印颜色
g.setColor(Color.RED);
// 设置水印文字字体
g.setFont(font);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
// 获取水印文字中最长的
int maxLength = 0;
for (String waterMarkContent : waterMarks) {
int fontlen = getWatermarkLength(waterMarkContent, g);
if (maxLength < fontlen) {
maxLength = fontlen;
}
}
int length = waterMarks.length;
for (int j = 0; j < length; j++) {
String waterMark = waterMarks[j];
int tempX = 10;
int tempY = fontSize;
// 单字符长度
int tempCharLen = 0;
// 单行字符总长度临时计算
int tempLineLen = 0;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < waterMark.length(); i++) {
char tempChar = waterMark.charAt(i);
tempCharLen = getCharLen(tempChar, g);
tempLineLen += tempCharLen;
if (tempLineLen >= srcImgWidth) {
// 长度已经满一行,进行文字叠加
g.drawString(sb.toString(), tempX, tempY);
// 清空内容,重新追加
sb.delete(0, sb.length());
tempLineLen = 0;
}
// 追加字符
sb.append(tempChar);
}
// 通过设置后两个输入参数给水印定位
g.drawString(sb.toString(), srcImgWidth - maxLength - x, srcImgHeight - (length - j - 1) * tempY - y);
}
g.dispose();
// 输出图片
ImageIO.write(bufImg, "jpg", out);
out.flush();
out.close();
}
private static int getCharLen(char c, Graphics2D g) {
return g.getFontMetrics(g.getFont()).charWidth(c);
}
private static int getWatermarkLength(String waterMarkContent, Graphics2D g) {
return g.getFontMetrics(g.getFont()).charsWidth(
waterMarkContent.toCharArray(), 0, waterMarkContent.length());
}
public static void main(String[] args) throws IOException {
// 原图位置, 输出图片位置, 水印文字颜色, 水印文字
String font = " 中 国 移 动 车 联 卡 实 名 登 记,2020-05-27 17:00:00,abcefg123-1234567890123456";
WatermarkUtil.waterPress(new FileInputStream("C:\\Users\\PC\\Desktop\\文档\\演示数据\\魏身份证正面.jpg"),
new FileOutputStream("C:\\Users\\PC\\Desktop\\文档\\演示数据\\out.jpg"),
14, 0.9f, 30, 30, font.split(","));
}
}
package com.cusc.nirvana.user.rnr.fp.config;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
/**
* 生成默认的中文字体
*/
@Component
@Slf4j
public class ChineseFontComponent {
private static Map<String, Font> chineseFontMap;
/**
* 创建中文字体
*
* @param key 字体类型的key
* @param fontPath 字体路径
*/
private static void createChineseFont(String key, String fontPath) throws Exception {
log.info("初始化中文字体: {}, path: {}", key, fontPath);
InputStream fisInJar = new ClassPathResource(fontPath).getInputStream();
File file = File.createTempFile("Font-", ".ttf");
//将jar包里的字体文件复制到操作系统的目录里
OutputStream fosInOs = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int readLength = fisInJar.read(buffer);
while (readLength != -1) {
fosInOs.write(buffer, 0, readLength);
readLength = fisInJar.read(buffer);
}
IOUtils.closeQuietly(fosInOs);
IOUtils.closeQuietly(fisInJar);
Font font;
try {
font = Font.createFont(Font.TRUETYPE_FONT, file);
chineseFontMap.put(key, font);
} catch (Exception e) {
log.error("加载默认中文字体失败", e);
// throw new CuscUserException("500", "加载默认中文字体失败: " + e.getMessage());
}
log.info("初始化中文字体完成: {}", key);
}
@PostConstruct
private void initFont() throws Exception {
chineseFontMap = new HashMap<>();
String heiTiFontPath = "font/simhei.ttf";
String kaiTiFontPath = "font/simkai.ttf";
String songTiFontPath = "font/simsun.ttc";
createChineseFont("HeiTi", heiTiFontPath);
createChineseFont("KaiTi", kaiTiFontPath);
createChineseFont("SongTi", songTiFontPath);
}
/**
* 获取中文字体
*/
public Font getChineseFont(String key) {
Font font = chineseFontMap.get(key);
return font == null ? chineseFontMap.get("SongTi") : font;
}
}
\ No newline at end of file
package com.cusc.nirvana.user.rnr.fp.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* Description: resttemplate的连接池配置
* <br />
* CreateDate 2022-05-18 15:00
*
* @author yuy336
**/
@Component
@Data
public class FileHttpPoolConfig {
/**
* 设置整个连接池最大连接数
*/
@Value("${httpPool.rnrBase.maxTotal:200}")
private Integer maxTotal;
/**
* 路由是对maxTotal的细分,针对一个url的最大并发数,每路由最大连接数,默认值是2
*/
@Value("${httpPool.rnrBase.defaultMaxPerRoute:100}")
private Integer defaultMaxPerRoute;
/**
* 服务器返回数据(response)的时间,超过该时间抛出read timeout
*/
@Value("${httpPool.rnrBase.socketTimeout:40000}")
private Integer socketTimeout;
/**
* 连接上服务器(握手成功)的时间,超出该时间抛出connect timeout
*/
@Value("${httpPool.rnrBase.connectTimeout:2000}")
private Integer connectTimeout;
/**
* 从连接池中获取连接的超时时间,超过该时间未拿到可用连接,会抛出org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool
*/
@Value("${httpPool.rnrBase.connectionRequestTimeout:1000}")
private Integer connectionRequestTimeout;
/**
* 线程最大空闲时间
*/
@Value("${httpPool.rnrBase.maxIdleTime:10}")
private Integer maxIdleTime;
}
/*
package com.cusc.nirvana.user.rnr.fp.config;
import com.cusc.nirvana.user.rnr.fp.common.util.MinIOUtils;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
*/
/**
* @Author: wangft
* @CreateTime: 2022/6/2 0002 15:12
* @Description:
*//*
@Data
@Component
@ConfigurationProperties(prefix = "minio")
public class MinIOConfig {
private String endpoint;
private String bucketName;
private String accessKey;
private String secretKey;
private Integer imgSize;
private Integer fileSize;
//@Bean
public MinIOUtils creatMinioClient() {
return new MinIOUtils(endpoint, bucketName, accessKey, secretKey, imgSize, fileSize);
}
}
*/
/*
package com.cusc.nirvana.user.rnr.fp.config;
import com.cusc.nirvana.user.rnr.fp.common.util.OSSUtil;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
*/
/**
* @author fyp
* @CreateTime: 2022/6/10
* @Description: OSS配置类
*//*
@Data
@Component
public class OssConfig {
@Value("${oss.endpoint}")
private String endpoint;
@Value("${oss.accessKeyId}")
private String accessKeyId;
@Value("${oss.accessKeySecret}")
private String accessKeySecret;
@Value("${oss.bucketName}")
private String bucketName;
@Value("${oss.prefix:/}")
private String prefix;
@Bean
public OSSUtil createOssClient() {
return new OSSUtil(endpoint, bucketName, accessKeyId, accessKeySecret,prefix);
}
}
*/
package com.cusc.nirvana.user.rnr.fp.config;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import java.util.concurrent.TimeUnit;
/**
* RestTemplate对象
*
* @author yubo
* @since 2022-04-18 09:54
*/
@Configuration
@Slf4j
public class RestTemplateRnrFileConfig {
@Autowired
private FileHttpPoolConfig httpPoolConstants;
@Bean
RestTemplate nonLoadBalancedFile() {
return new RestTemplate(httpRequestFactoryRnrFile());
}
private ClientHttpRequestFactory httpRequestFactoryRnrFile() {
return new HttpComponentsClientHttpRequestFactory(httpClientRnrFile());
}
private HttpClient httpClientRnrFile() {
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", SSLConnectionSocketFactory.getSocketFactory())
.build();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
//设置整个连接池最大连接数
connectionManager.setMaxTotal(httpPoolConstants.getMaxTotal());
//路由是对maxTotal的细分
connectionManager.setDefaultMaxPerRoute(httpPoolConstants.getDefaultMaxPerRoute());
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(httpPoolConstants.getSocketTimeout()) //返回数据的超时时间
.setConnectTimeout(httpPoolConstants.getConnectTimeout()) //连接上服务器的超时时间
.setConnectionRequestTimeout(httpPoolConstants.getConnectionRequestTimeout()) //从连接池中获取连接的超时时间
.build();
return HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig)
.setConnectionManager(connectionManager)
//设置后台线程剔除失效连接
.evictExpiredConnections().evictIdleConnections(httpPoolConstants.getMaxIdleTime(), TimeUnit.SECONDS)
.build();
}
}
package com.cusc.nirvana.user.rnr.fp.config;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import java.util.concurrent.TimeUnit;
/**
* @author stayAnd
* @date 2022/4/18
*/
@Configuration
@Slf4j
public class RestTemplateT1Config {
@Autowired
private T1HttpPoolConfig httpPoolConstants;
@Bean
public RestTemplate noBalanceRestTemplateRnrFpT1() {
return getRestTemplateRnrFp();
}
public RestTemplate getRestTemplateRnrFp() {
return new RestTemplate(httpRequestFactoryRnrFp());
}
private ClientHttpRequestFactory httpRequestFactoryRnrFp() {
return new HttpComponentsClientHttpRequestFactory(httpClientRnrFp());
}
private HttpClient httpClientRnrFp() {
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", SSLConnectionSocketFactory.getSocketFactory())
.build();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
//设置整个连接池最大连接数
connectionManager.setMaxTotal(httpPoolConstants.getMaxTotal());
//路由是对maxTotal的细分
connectionManager.setDefaultMaxPerRoute(httpPoolConstants.getDefaultMaxPerRoute());
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(httpPoolConstants.getSocketTimeout()) //返回数据的超时时间
.setConnectTimeout(httpPoolConstants.getConnectTimeout()) //连接上服务器的超时时间
.setConnectionRequestTimeout(httpPoolConstants.getConnectionRequestTimeout()) //从连接池中获取连接的超时时间
.build();
return HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig)
.setConnectionManager(connectionManager)
//设置后台线程剔除失效连接
.evictExpiredConnections().evictIdleConnections(httpPoolConstants.getMaxIdleTime(), TimeUnit.SECONDS)
.build();
}
}
package com.cusc.nirvana.user.rnr.fp.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
@Configuration
@Data
public class SimVehicleConfig {
/**接口url地址*/
@Value("${import.simrel.com-api.url:}")
private String url;
/**应用ID*/
@Value("${import.simrel.com-api.app-id:}")
private String appId;
/**用于签名加密*/
@Value("${import.simrel.com-api.app-scret:}")
private String appScret;
/**接口版本号*/
@Value("${import.simrel.com-api.version:1.0.0}")
private String version;
}
package com.cusc.nirvana.user.rnr.fp.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
/**
* @author: jk
* @since: 2023/12/1 14:46
* @description:
*/
@Configuration
@Data
public class T1Config {
@Value("${T1.url:}")
private String dateUrl;
@Value("${T1.cmccUrl:}")
private String cmccUrl;
@Value("${T1.ctccUrl:}")
private String ctccUrl;
@Value("${T1.fileUrl:}")
private String fileUrl;
@Value("${T1.version:1.0.0}")
private String VERSION;
@Value("${T1.appId:}")
private String APPID;
@Value("${T1.appSecret:}")
private String APPSCRET;
}
package com.cusc.nirvana.user.rnr.fp.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* Description: resttemplate的连接池配置
* <br />
* CreateDate 2022-05-18 15:00
*
* @author yuy336
**/
@Component
@Data
public class T1HttpPoolConfig {
/**
* 设置整个连接池最大连接数
*/
@Value("${httpPool.rnrFpT1.maxTotal:200}")
private Integer maxTotal;
/**
* 路由是对maxTotal的细分,针对一个url的最大并发数,每路由最大连接数,默认值是2
*/
@Value("${httpPool.rnrFpT1.defaultMaxPerRoute:100}")
private Integer defaultMaxPerRoute;
/**
* 服务器返回数据(response)的时间,超过该时间抛出read timeout
*/
@Value("${httpPool.rnrFpT1.socketTimeout:30000}")
private Integer socketTimeout;
/**
* 连接上服务器(握手成功)的时间,超出该时间抛出connect timeout
*/
@Value("${httpPool.rnrFpT1.connectTimeout:2000}")
private Integer connectTimeout;
/**
* 从连接池中获取连接的超时时间,超过该时间未拿到可用连接,会抛出org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool
*/
@Value("${httpPool.rnrFpT1.connectionRequestTimeout:1000}")
private Integer connectionRequestTimeout;
/**
* 线程最大空闲时间
*/
@Value("${httpPool.rnrFpT1.maxIdleTime:10}")
private Integer maxIdleTime;
}
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