Skip to content
GitLab
Menu
Projects
Groups
Snippets
Loading...
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in / Register
Toggle navigation
Menu
Open sidebar
时空开放平台
spatiotemporal-commons
Commits
403bc21d
Commit
403bc21d
authored
Jan 18, 2024
by
侯力峰
Browse files
首次开源发布
parent
fdfe0676
Pipeline
#2762
failed with stages
in 0 seconds
Changes
37
Pipelines
2
Hide whitespace changes
Inline
Side-by-side
commons-file/src/main/java/cn/spatiotemporal/commons/file/controller/FileController.java
0 → 100644
View file @
403bc21d
package
cn.spatiotemporal.commons.file.controller
;
import
org.springframework.web.bind.annotation.DeleteMapping
;
import
org.springframework.web.bind.annotation.PostMapping
;
import
org.springframework.web.bind.annotation.RequestMapping
;
import
org.springframework.web.bind.annotation.RequestParam
;
import
org.springframework.web.bind.annotation.RestController
;
import
org.springframework.web.multipart.MultipartFile
;
import
cn.spatiotemporal.commons.enums.ReturnEnum
;
import
cn.spatiotemporal.commons.file.service.FileService
;
import
cn.spatiotemporal.commons.file.vo.FileInfo
;
import
cn.spatiotemporal.commons.result.ReturnVO
;
import
io.swagger.annotations.Api
;
import
io.swagger.annotations.ApiOperation
;
import
io.swagger.annotations.ApiParam
;
import
lombok.RequiredArgsConstructor
;
import
lombok.SneakyThrows
;
/**
*
* @ClassName: FileController
* @Description: 文件服务控制器
* @date 2023年9月13日 上午11:08:30
*
* @author Q.JI
* @version
* @since JDK 1.8
*/
@Api
(
tags
=
"文件接口"
)
@RestController
@RequestMapping
(
"/api/v1/files"
)
@RequiredArgsConstructor
public
class
FileController
{
private
final
FileService
fileService
;
@PostMapping
(
"/upload"
)
@ApiOperation
(
value
=
"文件上传"
)
public
ReturnVO
<
FileInfo
>
uploadFile
(
@ApiParam
(
"表单文件对象"
)
@RequestParam
(
value
=
"file"
)
MultipartFile
file
)
{
return
new
ReturnVO
<
FileInfo
>(
ReturnEnum
.
SUCCESS
,
fileService
.
uploadFile
(
file
));
}
@DeleteMapping
(
"/delete"
)
@ApiOperation
(
value
=
"文件删除"
)
@SneakyThrows
public
ReturnVO
<
Boolean
>
deleteFile
(
@ApiParam
(
"文件路径"
)
@RequestParam
String
filePath
)
{
return
new
ReturnVO
<
Boolean
>(
ReturnEnum
.
SUCCESS
,
fileService
.
deleteFile
(
filePath
));
}
}
commons-file/src/main/java/cn/spatiotemporal/commons/file/service/FileService.java
0 → 100644
View file @
403bc21d
package
cn.spatiotemporal.commons.file.service
;
import
org.springframework.web.multipart.MultipartFile
;
import
cn.spatiotemporal.commons.file.vo.FileInfo
;
/**
*
* @ClassName: FileService
* @Description: 文件接口(计划实现minio/ftp)
* @date 2023年9月13日 上午10:07:40
*
* @author Q.JI
* @version
* @since JDK 1.8
*/
public
interface
FileService
{
/**
* 上传文件
*
* @param file 表单文件对象
* @return
*/
FileInfo
uploadFile
(
MultipartFile
file
);
/**
* 删除文件
*
* @param filePath 文件路径
* @return
*/
boolean
deleteFile
(
String
filePath
);
}
commons-file/src/main/java/cn/spatiotemporal/commons/file/service/impl/FtpServiceImpl.java
0 → 100644
View file @
403bc21d
package
cn.spatiotemporal.commons.file.service.impl
;
import
java.io.File
;
import
java.io.FileNotFoundException
;
import
java.io.InputStream
;
import
java.time.LocalDateTime
;
import
org.apache.commons.io.FileUtils
;
import
org.springframework.beans.factory.InitializingBean
;
import
org.springframework.boot.context.properties.ConfigurationProperties
;
import
org.springframework.context.annotation.Conditional
;
import
org.springframework.stereotype.Component
;
import
org.springframework.util.ResourceUtils
;
import
org.springframework.web.multipart.MultipartFile
;
import
cn.spatiotemporal.commons.file.service.FileService
;
import
cn.spatiotemporal.commons.file.support.FtpUploadCondition
;
import
cn.spatiotemporal.commons.file.util.FtpUtil
;
import
cn.spatiotemporal.commons.file.vo.FileInfo
;
import
cn.hutool.core.date.DateUtil
;
import
cn.hutool.core.io.FileUtil
;
import
cn.hutool.core.lang.Assert
;
import
cn.hutool.core.util.IdUtil
;
import
cn.hutool.core.util.StrUtil
;
import
lombok.Setter
;
import
lombok.SneakyThrows
;
import
lombok.extern.slf4j.Slf4j
;
/**
*
* @ClassName: FtpServiceImpl
* @Description: ftp实现
* @date 2023年9月14日 上午11:30:23
*
* @author Q.JI
* @version
* @since JDK 1.8
*
* <p> 选用ftp配置示例
uploadservice:
#(minio/ftp)
type: ftp
# ftp配置
ftp:
host: 192.168.59.181
port: 21
username: ftp
password: ftp
requestDir: upload
encoding: GBK
*/
@Component
(
"uploadFileServiceFtp"
)
@Conditional
(
FtpUploadCondition
.
class
)
@ConfigurationProperties
(
prefix
=
"uploadservice.ftp"
)
@Slf4j
public
class
FtpServiceImpl
implements
FileService
,
InitializingBean
{
/**
* ftp服务地址
*/
@Setter
private
String
host
;
/**
* 端口
*/
@Setter
private
String
port
;
/**
* 用户名
*/
@Setter
private
String
userName
;
/**
* 密钥
*/
@Setter
private
String
password
;
/**
* 请求路径
*/
@Setter
private
String
requestDir
;
/**
* 自定义文件服务域名(非必须)
*/
@Setter
private
String
customDomain
;
private
static
String
UPLOADED_FOLDER
=
getLocalStaticPath
()
+
File
.
separator
;
@Override
public
void
afterPropertiesSet
()
{
log
.
info
(
"Ftp Client init..."
);
Assert
.
notBlank
(
host
,
"Ftp hot can not be null"
);
Assert
.
notBlank
(
port
,
"Ftp port can not be null"
);
Assert
.
notBlank
(
userName
,
"Ftp userName can not be null"
);
Assert
.
notBlank
(
password
,
"Ftp password can not be null"
);
Assert
.
notBlank
(
requestDir
,
"Ftp requestDir can not be null"
);
}
/**
* 上传文件
*
* @param file 表单文件对象
* @return
*/
@Override
@SneakyThrows
public
FileInfo
uploadFile
(
MultipartFile
file
)
{
// 生成文件名(日期文件夹)
String
suffix
=
FileUtil
.
getSuffix
(
file
.
getOriginalFilename
());
String
uuid
=
IdUtil
.
simpleUUID
();
String
location
=
DateUtil
.
format
(
LocalDateTime
.
now
(),
"yyyy/MM/dd"
);
String
fileName
=
uuid
+
"."
+
suffix
;
// String outputFile = "";
// boolean result = File.separatorChar == '\\';
// if(result) {
// outputFile = "c:" + File.separatorChar + "tmp" + File.separator + fileName;
// }else {
// outputFile = File.separatorChar + "tmp" + File.separatorChar + fileName;
// }
String
localLocation
=
location
.
replaceAll
(
"\\/"
,
"\\"
+
File
.
separator
);
File
uploadOutFile
=
new
File
(
UPLOADED_FOLDER
+
localLocation
);
if
(!
uploadOutFile
.
exists
())
{
uploadOutFile
.
mkdirs
();
}
String
outputFile
=
uploadOutFile
.
getAbsolutePath
()
+
File
.
separator
+
fileName
;
InputStream
inputStream
=
file
.
getInputStream
();
FileUtils
.
copyInputStreamToFile
(
inputStream
,
new
File
(
outputFile
));
// 文件上传
FtpUtil
.
ftpPutFile
(
host
,
port
,
userName
,
password
,
new
String
[]
{
outputFile
},
requestDir
+
"/"
+
location
);
FileUtils
.
deleteQuietly
(
new
File
(
outputFile
));
// 返回文件路径
String
fileUrl
;
if
(
StrUtil
.
isBlank
(
customDomain
))
{
// 未配置自定义域名
fileUrl
=
String
.
format
(
"ftp://%s:%s/%s/%s"
,
host
,
port
,
location
,
fileName
);
}
else
{
// 配置自定义文件路径域名
fileUrl
=
String
.
format
(
"%s/%s/s"
,
customDomain
,
location
,
fileName
);
}
FileInfo
fileInfo
=
new
FileInfo
();
fileInfo
.
setName
(
fileName
);
fileInfo
.
setUrl
(
"/"
+
requestDir
+
"/"
+
location
+
"/"
+
fileName
);
fileInfo
.
setType
(
file
.
getContentType
());
fileInfo
.
setSize
(
file
.
getSize
());
fileInfo
.
setOriginalName
(
file
.
getOriginalFilename
());
return
fileInfo
;
}
/**
* 删除文件
*
* @param filePath 文件路径
* eg: /upload/2023/09/13/4b50e00c14524f8cadb14478f9c1ffbf.jpg
*
* @return
*/
@Override
@SneakyThrows
public
boolean
deleteFile
(
String
filePath
)
{
Assert
.
notBlank
(
filePath
,
"删除文件路径不能为空"
);
String
fileSignimgPath
=
filePath
.
substring
(
0
,
filePath
.
lastIndexOf
(
"/"
));
String
overFileSignimgName
=
filePath
.
substring
(
filePath
.
lastIndexOf
(
"/"
)+
1
);
return
FtpUtil
.
ftpDeleteFile
(
host
,
port
,
userName
,
password
,
fileSignimgPath
,
new
String
[]{
overFileSignimgName
})
==
0
?
true
:
false
;
}
/**
*
* @Title: getLocalStaticPath
* @Description: 获得本地static资源路径
* @return String
*/
private
static
String
getLocalStaticPath
()
{
File
path
=
null
;
try
{
path
=
new
File
(
ResourceUtils
.
getURL
(
"classpath:"
).
getPath
());
}
catch
(
FileNotFoundException
e
)
{
log
.
error
(
"获取系统根目录发生异常"
,
e
);
}
if
(!
path
.
exists
())
{
path
=
new
File
(
""
);
}
File
upload
=
new
File
(
path
.
getAbsolutePath
(),
"static"
);
if
(!
upload
.
exists
())
{
upload
.
mkdirs
();
}
return
upload
.
getAbsolutePath
();
}
}
commons-file/src/main/java/cn/spatiotemporal/commons/file/service/impl/MinioServiceImpl.java
0 → 100644
View file @
403bc21d
package
cn.spatiotemporal.commons.file.service.impl
;
import
java.io.InputStream
;
import
java.time.LocalDateTime
;
import
org.springframework.beans.factory.InitializingBean
;
import
org.springframework.boot.context.properties.ConfigurationProperties
;
import
org.springframework.context.annotation.Conditional
;
import
org.springframework.stereotype.Component
;
import
org.springframework.web.multipart.MultipartFile
;
import
cn.spatiotemporal.commons.file.service.FileService
;
import
cn.spatiotemporal.commons.file.support.MinioUploadCondition
;
import
cn.spatiotemporal.commons.file.vo.FileInfo
;
import
cn.hutool.core.date.DateUtil
;
import
cn.hutool.core.io.FileUtil
;
import
cn.hutool.core.lang.Assert
;
import
cn.hutool.core.util.IdUtil
;
import
cn.hutool.core.util.StrUtil
;
import
io.minio.BucketExistsArgs
;
import
io.minio.GetPresignedObjectUrlArgs
;
import
io.minio.MakeBucketArgs
;
import
io.minio.MinioClient
;
import
io.minio.PutObjectArgs
;
import
io.minio.RemoveObjectArgs
;
import
io.minio.SetBucketPolicyArgs
;
import
io.minio.http.Method
;
import
lombok.Setter
;
import
lombok.SneakyThrows
;
import
lombok.extern.slf4j.Slf4j
;
/**
*
* @ClassName: MinioServiceImpl
* @Description: mioio实现
* @date 2023年9月13日 下午14:30:23
*
* @author Q.JI
* @version
* @since JDK 1.8
*
* <p> 选用minio配置示例
uploadservice:
#(minio/ftp)
type: minio
# minio配置
minio:
endpoint: http://192.168.60.102:9000
accessKey: minioadmin
secretKey: minioadmin
bucketName: uploads
*/
@Component
(
"uploadFileServiceMinIo"
)
@Conditional
(
MinioUploadCondition
.
class
)
@ConfigurationProperties
(
prefix
=
"uploadservice.minio"
)
@Slf4j
public
class
MinioServiceImpl
implements
FileService
,
InitializingBean
{
/**
* MinIO的API地址
*/
@Setter
private
String
endpoint
;
/**
* 用户名
*/
@Setter
private
String
accessKey
;
/**
* 密钥
*/
@Setter
private
String
secretKey
;
/**
* 存储桶名称
*/
@Setter
private
String
bucketName
;
/**
* 自定义域名(非必须)
*/
@Setter
private
String
customDomain
;
private
MinioClient
minioClient
;
@Override
public
void
afterPropertiesSet
()
{
log
.
info
(
"MinIO Client init..."
);
Assert
.
notBlank
(
endpoint
,
"MinIO endpoint can not be null"
);
Assert
.
notBlank
(
accessKey
,
"MinIO accessKey can not be null"
);
Assert
.
notBlank
(
secretKey
,
"MinIO secretKey can not be null"
);
Assert
.
notBlank
(
bucketName
,
"MinIO bucketName can not be null"
);
this
.
minioClient
=
MinioClient
.
builder
()
.
endpoint
(
endpoint
)
.
credentials
(
accessKey
,
secretKey
)
.
build
();
}
/**
* 上传文件
*
* @param file 表单文件对象
* @return
*/
@Override
@SneakyThrows
public
FileInfo
uploadFile
(
MultipartFile
file
)
{
// 存储桶不存在则创建
createBucketIfAbsent
(
bucketName
);
// 生成文件名(日期文件夹)
String
suffix
=
FileUtil
.
getSuffix
(
file
.
getOriginalFilename
());
String
uuid
=
IdUtil
.
simpleUUID
();
String
fileName
=
DateUtil
.
format
(
LocalDateTime
.
now
(),
"yyyy/MM/dd"
)
+
"/"
+
uuid
+
"."
+
suffix
;
InputStream
inputStream
=
file
.
getInputStream
();
// 文件上传
PutObjectArgs
putObjectArgs
=
PutObjectArgs
.
builder
()
.
bucket
(
bucketName
)
.
object
(
fileName
)
.
contentType
(
file
.
getContentType
())
.
stream
(
inputStream
,
inputStream
.
available
(),
-
1
)
.
build
();
minioClient
.
putObject
(
putObjectArgs
);
// 返回文件路径
String
fileUrl
;
if
(
StrUtil
.
isBlank
(
customDomain
))
{
// 未配置自定义域名
GetPresignedObjectUrlArgs
getPresignedObjectUrlArgs
=
GetPresignedObjectUrlArgs
.
builder
()
.
bucket
(
bucketName
).
object
(
fileName
)
.
method
(
Method
.
GET
)
.
build
();
fileUrl
=
minioClient
.
getPresignedObjectUrl
(
getPresignedObjectUrlArgs
);
fileUrl
=
fileUrl
.
substring
(
0
,
fileUrl
.
indexOf
(
"?"
));
}
else
{
// 配置自定义文件路径域名
fileUrl
=
customDomain
+
'/'
+
bucketName
+
"/"
+
fileName
;
}
FileInfo
fileInfo
=
new
FileInfo
();
fileInfo
.
setName
(
uuid
+
"."
+
suffix
);
fileInfo
.
setUrl
(
"/"
+
bucketName
+
"/"
+
fileName
);
fileInfo
.
setType
(
file
.
getContentType
());
fileInfo
.
setSize
(
file
.
getSize
());
fileInfo
.
setOriginalName
(
file
.
getOriginalFilename
());
return
fileInfo
;
}
/**
* 删除文件
*
* @param filePath 文件路径
* eg: /${bucketName}/2023/09/13/44e707ce4ee44fc7b55b5aedf1a7f511.jpg
*
* @return
*/
@Override
@SneakyThrows
public
boolean
deleteFile
(
String
filePath
)
{
Assert
.
notBlank
(
filePath
,
"删除文件路径不能为空"
);
String
tempStr
=
"/"
+
bucketName
+
"/"
;
String
fileName
=
filePath
.
substring
(
filePath
.
indexOf
(
tempStr
)
+
tempStr
.
length
());
// 2023/09/13/44e707ce4ee44fc7b55b5aedf1a7f511.jpg
RemoveObjectArgs
removeObjectArgs
=
RemoveObjectArgs
.
builder
()
.
bucket
(
bucketName
)
.
object
(
fileName
)
.
build
();
minioClient
.
removeObject
(
removeObjectArgs
);
return
true
;
}
/**
* PUBLIC桶策略
* 如果不配置,则新建的存储桶默认是PRIVATE,则存储桶文件会拒绝访问 Access Denied
*
* @param bucketName
* @return
*/
private
static
String
publicBucketPolicy
(
String
bucketName
)
{
/**
* AWS的S3存储桶策略
* Principal: 生效用户对象
* Resource: 指定存储桶
* Action: 操作行为
*/
StringBuilder
builder
=
new
StringBuilder
();
builder
.
append
(
"{\"Version\":\"2012-10-17\","
+
"\"Statement\":[{\"Effect\":\"Allow\","
+
"\"Principal\":{\"AWS\":[\"*\"]},"
+
"\"Action\":[\"s3:ListBucketMultipartUploads\",\"s3:GetBucketLocation\",\"s3:ListBucket\"],"
+
"\"Resource\":[\"arn:aws:s3:::"
+
bucketName
+
"\"]},"
+
"{\"Effect\":\"Allow\","
+
"\"Principal\":{\"AWS\":[\"*\"]},"
+
"\"Action\":[\"s3:ListMultipartUploadParts\",\"s3:PutObject\",\"s3:AbortMultipartUpload\",\"s3:DeleteObject\",\"s3:GetObject\"],"
+
"\"Resource\":[\"arn:aws:s3:::"
+
bucketName
+
"/*\"]}]}"
);
return
builder
.
toString
();
}
/**
* 创建存储桶(存储桶不存在)
*
* @param bucketName
*/
@SneakyThrows
private
void
createBucketIfAbsent
(
String
bucketName
)
{
BucketExistsArgs
bucketExistsArgs
=
BucketExistsArgs
.
builder
().
bucket
(
bucketName
).
build
();
if
(!
minioClient
.
bucketExists
(
bucketExistsArgs
))
{
MakeBucketArgs
makeBucketArgs
=
MakeBucketArgs
.
builder
().
bucket
(
bucketName
).
build
();
minioClient
.
makeBucket
(
makeBucketArgs
);
// 设置存储桶访问权限为PUBLIC, 如果不配置,则新建的存储桶默认是PRIVATE,则存储桶文件会拒绝访问 Access Denied
SetBucketPolicyArgs
setBucketPolicyArgs
=
SetBucketPolicyArgs
.
builder
()
.
bucket
(
bucketName
)
.
config
(
publicBucketPolicy
(
bucketName
))
.
build
();
minioClient
.
setBucketPolicy
(
setBucketPolicyArgs
);
}
}
}
commons-file/src/main/java/cn/spatiotemporal/commons/file/support/FtpUploadCondition.java
0 → 100644
View file @
403bc21d
package
cn.spatiotemporal.commons.file.support
;
import
org.springframework.context.annotation.Condition
;
import
org.springframework.context.annotation.ConditionContext
;
import
org.springframework.core.type.AnnotatedTypeMetadata
;
/**
*
* @ClassName: FtpUploadCondition
* @Description: TODO(这里用一句话描述这个类的作用)
* @date 2023年9月13日 下午5:04:31
*
* @author Q.JI
* @version
* @since JDK 1.8
*/
public
class
FtpUploadCondition
implements
Condition
{
/* (non-Javadoc)
* @see org.springframework.context.annotation.Condition#matches(org.springframework.context.annotation.ConditionContext, org.springframework.core.type.AnnotatedTypeMetadata)
*/
@Override
public
boolean
matches
(
ConditionContext
context
,
AnnotatedTypeMetadata
metadata
)
{
return
"ftp"
.
equals
(
context
.
getEnvironment
().
getProperty
(
"uploadservice.type"
));
}
}
commons-file/src/main/java/cn/spatiotemporal/commons/file/support/MinioUploadCondition.java
0 → 100644
View file @
403bc21d
package
cn.spatiotemporal.commons.file.support
;
import
org.springframework.context.annotation.Condition
;
import
org.springframework.context.annotation.ConditionContext
;
import
org.springframework.core.type.AnnotatedTypeMetadata
;
/**
* @ClassName: MinioUploadCondition
* @Description: TODO(这里用一句话描述这个类的作用)
* @date 2023年9月14日 下午4:47:26
*
* @author Q.JI
* @version
* @since JDK 1.8
*/
public
class
MinioUploadCondition
implements
Condition
{
/* (non-Javadoc)
* @see org.springframework.context.annotation.Condition#matches(org.springframework.context.annotation.ConditionContext, org.springframework.core.type.AnnotatedTypeMetadata)
*/
@Override
public
boolean
matches
(
ConditionContext
context
,
AnnotatedTypeMetadata
metadata
)
{
return
"minio"
.
equals
(
context
.
getEnvironment
().
getProperty
(
"uploadservice.type"
));
}
}
commons-file/src/main/java/cn/spatiotemporal/commons/file/util/FtpUtil.java
0 → 100644
View file @
403bc21d
package
cn.spatiotemporal.commons.file.util
;
import
java.io.File
;
import
java.io.IOException
;
import
java.util.ArrayList
;
import
java.util.List
;
import
com.enterprisedt.net.ftp.*
;
import
lombok.extern.slf4j.Slf4j
;
/**
*
* @ClassName: FtpUtil
* @Description: ftp工具类
* @date 2018年10月16日 下午3:18:28
*
* @author Q.JI
* @version
* @since JDK 1.7
*/
@Slf4j
public
class
FtpUtil
{
private
static
final
int
FTP_TIMEOUT
=
30000
;
public
static
final
int
FTP_OK
=
0
;
public
static
final
int
FTP_CONNECT_ERROR
=
-
1
;
public
static
final
int
FTP_LOGIN_ERROR
=
-
2
;
public
static
final
int
FTP_LOCAL_FILE_ERROR
=
-
3
;
public
static
final
int
FTP_LOGOUT_ERROR
=
-
4
;
public
static
final
int
FTP_TRANSFER_ERROR
=
-
9
;
public
static
final
int
FTP_NO_FILE_TRANSFER
=
99
;
public
static
int
ftpPutFile
(
String
_strHost
,
String
_strPort
,
String
_strFtpUser
,
String
_strFtpPwd
,
String
[]
_strSrcFiles
)
{
return
ftpPutFile
(
_strHost
,
_strPort
,
_strFtpUser
,
_strFtpPwd
,
_strSrcFiles
,
""
);
}
public
static
int
ftpPutFile
(
String
_strHost
,
String
_strPort
,
String
_strFtpUser
,
String
_strFtpPwd
,
String
[]
_strSrcFiles
,
String
_strEntryDesDir
)
{
int
iRtn
=
FTP_NO_FILE_TRANSFER
;
log
.
info
(
"ip="
+
_strHost
+
", port="
+
_strPort
+
", user="
+
_strFtpUser
+
", passwd="
+
_strFtpPwd
+
", files="
+
_strSrcFiles
.
length
+
", entryDir="
+
_strEntryDesDir
);
String
strfilename
=
""
;
if
(
_strSrcFiles
.
length
<=
0
)
{
return
iRtn
;
}
FTPClient
ftp
=
null
;
try
{
iRtn
=
FTP_CONNECT_ERROR
;
ftp
=
new
FTPClient
();
ftp
.
setRemoteHost
(
_strHost
);
ftp
.
setRemotePort
(
Integer
.
parseInt
(
_strPort
));
ftp
.
setTimeout
(
FTP_TIMEOUT
);
ftp
.
connect
();
iRtn
=
FTP_LOGIN_ERROR
;
ftp
.
login
(
_strFtpUser
,
_strFtpPwd
);
log
.
info
(
"Login OK!["
+
_strHost
+
":"
+
_strPort
+
":"
+
_strFtpUser
+
"]"
);
ftp
.
setType
(
FTPTransferType
.
BINARY
);
if
(
_strEntryDesDir
.
trim
().
length
()
>
0
)
{
String
[]
strDirs
=
_strEntryDesDir
.
split
(
"/"
,
-
1
);
if
(
strDirs
!=
null
)
{
String
strCurDir
=
""
;
for
(
int
i
=
0
;
i
<
strDirs
.
length
;
i
++)
{
if
(
strCurDir
.
length
()
>
0
)
{
strCurDir
=
strCurDir
+
"/"
+
strDirs
[
i
];
}
else
{
strCurDir
=
strDirs
[
i
];
}
try
{
ftp
.
mkdir
(
strDirs
[
i
]);
log
.
info
(
"Create Dir : "
+
strCurDir
+
" OK!"
);
}
catch
(
FTPException
ex1
)
{
}
ftp
.
chdir
(
strDirs
[
i
]);
}
log
.
info
(
"Change Dir : "
+
strCurDir
+
" OK!"
);
}
}
ftp
.
setConnectMode
(
FTPConnectMode
.
PASV
);
for
(
int
i
=
0
;
i
<
_strSrcFiles
.
length
;
i
++)
{
if
(
_strSrcFiles
[
i
].
length
()
<=
0
)
{
continue
;
}
else
{
if
(!
dirIsExist
(
_strSrcFiles
[
i
]))
{
iRtn
=
FTP_LOCAL_FILE_ERROR
;
throw
new
IOException
(
_strSrcFiles
[
i
]
+
" : not such file!"
);
}
}
int
index
=
_strSrcFiles
[
i
].
lastIndexOf
(
File
.
separator
);
strfilename
=
_strSrcFiles
[
i
].
substring
(
index
+
1
);
iRtn
=
FTP_TRANSFER_ERROR
;
ftp
.
put
(
_strSrcFiles
[
i
],
strfilename
);
log
.
info
(
"Put file "
+
_strSrcFiles
[
i
]
+
" OK!"
);
}
iRtn
=
FTP_LOGOUT_ERROR
;
ftp
.
quit
();
log
.
info
(
"Logout!"
+
"\n"
);
iRtn
=
FTP_OK
;
}
catch
(
FTPException
ex
)
{
log
.
error
(
"ftpPutFile : "
+
ex
.
getMessage
());
}
catch
(
IOException
ex1
)
{
log
.
error
(
"ftpPutFile : "
+
ex1
.
getMessage
());
}
catch
(
NumberFormatException
ex2
)
{
log
.
error
(
"ftpPutFile : "
+
ex2
.
getMessage
());
}
log
.
info
(
"ftpFile end. iRtn = "
+
iRtn
);
return
iRtn
;
}
/**
*
* dirIsExist:(这里用一句话描述这个方法的作用). <br/>
*
* @param _strDir
* @return boolean
* @since 1.0
*/
public
static
boolean
dirIsExist
(
String
_strDir
)
{
File
dir
=
new
File
(
_strDir
);
if
(
dir
.
exists
())
return
true
;
return
false
;
}
public
static
List
ftpGetFileNameList
(
String
_strHost
,
String
_strPort
,
String
_strFtpUser
,
String
_strFtpPwd
,
String
_strEntryDesDir
,
String
_strFileName
)
{
List
<
String
>
fileNameList
=
new
ArrayList
<
String
>();
log
.
info
(
"ip="
+
_strHost
+
", port="
+
_strPort
+
", user="
+
_strFtpUser
+
", passwd="
+
_strFtpPwd
+
", entryDir="
+
_strEntryDesDir
+
", file="
+
_strFileName
);
if
(
_strFileName
==
null
)
{
return
null
;
}
FTPClient
ftp
=
null
;
try
{
ftp
=
new
FTPClient
();
ftp
.
setRemoteHost
(
_strHost
);
ftp
.
setRemotePort
(
Integer
.
parseInt
(
_strPort
));
ftp
.
setTimeout
(
FTP_TIMEOUT
);
ftp
.
connect
();
ftp
.
login
(
_strFtpUser
,
_strFtpPwd
);
log
.
info
(
"Login OK!["
+
_strHost
+
":"
+
_strPort
+
":"
+
_strFtpUser
+
"]"
);
ftp
.
setType
(
FTPTransferType
.
BINARY
);
if
(
_strEntryDesDir
.
trim
().
length
()
>
0
&&
!
_strEntryDesDir
.
trim
().
equals
(
"."
))
{
if
(
_strEntryDesDir
.
substring
(
0
,
1
).
equals
(
"/"
)){
//绝对路径
ftp
.
chdir
(
_strEntryDesDir
.
trim
());
log
.
info
(
"Change Dir : "
+
_strEntryDesDir
.
trim
()
+
" OK!"
);
}
else
{
//相对路径
String
[]
strDirs
=
_strEntryDesDir
.
split
(
"/"
,
-
1
);
if
(
strDirs
!=
null
)
{
String
strCurDir
=
""
;
for
(
int
i
=
0
;
i
<
strDirs
.
length
;
i
++)
{
if
(
strCurDir
.
length
()
>
0
)
{
strCurDir
=
strCurDir
+
"/"
+
strDirs
[
i
];
}
else
{
strCurDir
=
strDirs
[
i
];
}
try
{
ftp
.
mkdir
(
strDirs
[
i
]);
log
.
info
(
"Create Dir : "
+
strCurDir
+
" OK!"
);
}
catch
(
FTPException
ex1
)
{
}
ftp
.
chdir
(
strDirs
[
i
]);
}
log
.
info
(
"Change Dir : "
+
strCurDir
+
" OK!"
);
}
}
}
ftp
.
setConnectMode
(
FTPConnectMode
.
PASV
);
// ftp.setConnectMode(FTPConnectMode.ACTIVE);
String
[]
remortFileNames
=
ftp
.
dir
(
_strFileName
+
"*"
);
for
(
int
i
=
0
;
i
<
remortFileNames
.
length
;
i
++)
{
String
fileName
=
remortFileNames
[
i
];
fileNameList
.
add
(
fileName
);
}
ftp
.
quit
();
log
.
info
(
"Logout!"
+
"\n"
);
}
catch
(
FTPException
ex
)
{
if
(
ex
.
getMessage
().
indexOf
(
"No such file"
)
>=
0
){
return
fileNameList
;
}
else
if
(
ex
.
getMessage
().
indexOf
(
"Bad directory"
)
>=
0
){
return
fileNameList
;
}
else
if
(
ex
.
getMessage
().
indexOf
(
"Unexpected null reply received"
)
>=
0
){
return
fileNameList
;
}
else
{
log
.
info
(
"ftpGetFileNameList :"
+
ex
.
getMessage
());
return
null
;
}
}
catch
(
IOException
ex1
)
{
log
.
info
(
"ftpGetFileNameList :"
+
ex1
.
getMessage
());
return
null
;
}
catch
(
NumberFormatException
ex2
)
{
log
.
info
(
"ftpGetFileNameList :"
+
ex2
.
getMessage
());
return
null
;
}
log
.
info
(
"ftpGetFileNameList end. get filenames num="
+
fileNameList
.
size
());
return
fileNameList
;
}
// dir list
public
static
List
ftpGetDirList
(
String
_strHost
,
String
_strPort
,
String
_strFtpUser
,
String
_strFtpPwd
,
String
_strEntryDesDir
)
{
List
<
String
>
fileNameList
=
new
ArrayList
<
String
>();
log
.
info
(
"ip="
+
_strHost
+
", port="
+
_strPort
+
", user="
+
_strFtpUser
+
", passwd="
+
_strFtpPwd
+
", entryDir="
+
_strEntryDesDir
);
FTPClient
ftp
=
null
;
try
{
ftp
=
new
FTPClient
();
ftp
.
setRemoteHost
(
_strHost
);
ftp
.
setRemotePort
(
Integer
.
parseInt
(
_strPort
));
ftp
.
setTimeout
(
FTP_TIMEOUT
);
ftp
.
connect
();
ftp
.
login
(
_strFtpUser
,
_strFtpPwd
);
log
.
info
(
"Login OK!["
+
_strHost
+
":"
+
_strPort
+
":"
+
_strFtpUser
+
"]"
);
ftp
.
setType
(
FTPTransferType
.
BINARY
);
if
(
_strEntryDesDir
.
trim
().
length
()
>
0
&&
!
_strEntryDesDir
.
trim
().
equals
(
"."
))
{
if
(
_strEntryDesDir
.
substring
(
0
,
1
).
equals
(
"/"
)){
//绝对路径
ftp
.
chdir
(
_strEntryDesDir
.
trim
());
log
.
info
(
"Change Dir : "
+
_strEntryDesDir
.
trim
()
+
" OK!"
);
}
else
{
//相对路径
String
[]
strDirs
=
_strEntryDesDir
.
split
(
"/"
,
-
1
);
if
(
strDirs
!=
null
)
{
String
strCurDir
=
""
;
for
(
int
i
=
0
;
i
<
strDirs
.
length
;
i
++)
{
if
(
strCurDir
.
length
()
>
0
)
{
strCurDir
=
strCurDir
+
"/"
+
strDirs
[
i
];
}
else
{
strCurDir
=
strDirs
[
i
];
}
try
{
ftp
.
mkdir
(
strDirs
[
i
]);
log
.
info
(
"Create Dir : "
+
strCurDir
+
" OK!"
);
}
catch
(
FTPException
ex1
)
{
}
ftp
.
chdir
(
strDirs
[
i
]);
}
log
.
info
(
"Change Dir : "
+
strCurDir
+
" OK!"
);
}
}
}
ftp
.
setConnectMode
(
FTPConnectMode
.
PASV
);
// ftp.setConnectMode(FTPConnectMode.ACTIVE);
String
[]
remortFileNames
=
ftp
.
dir
(
"."
,
true
);
String
[]
remortFileNameList
=
ftp
.
dir
();
for
(
int
i
=
0
;
i
<
remortFileNames
.
length
;
i
++)
{
String
fileName
=
remortFileNames
[
i
];
if
(
isDir
(
fileName
)){
fileNameList
.
add
(
remortFileNameList
[
i
]);
}
}
ftp
.
quit
();
log
.
info
(
"Logout!"
+
"\n"
);
}
catch
(
FTPException
ex
)
{
if
(
ex
.
getMessage
().
indexOf
(
"No such file"
)
>=
0
){
return
fileNameList
;
}
else
if
(
ex
.
getMessage
().
indexOf
(
"Bad directory"
)
>=
0
){
return
fileNameList
;
}
else
if
(
ex
.
getMessage
().
indexOf
(
"Unexpected null reply received"
)
>=
0
){
return
fileNameList
;
}
else
{
log
.
info
(
"ftpGetDirList :"
+
ex
.
getMessage
());
return
null
;
}
}
catch
(
IOException
ex1
)
{
log
.
info
(
"ftpGetDirList :"
+
ex1
.
getMessage
());
return
null
;
}
catch
(
NumberFormatException
ex2
)
{
log
.
info
(
"ftpGetDirList :"
+
ex2
.
getMessage
());
return
null
;
}
log
.
info
(
"ftpGetDirList end. get dirnames num="
+
fileNameList
.
size
());
return
fileNameList
;
}
private
static
boolean
isDir
(
String
remortFileName
){
boolean
flag
=
false
;
if
(
"d"
.
equals
(
remortFileName
.
substring
(
0
,
1
))){
flag
=
true
;
}
return
flag
;
}
// public static List ftpGetFile(String _strHost, String _strPort,
// String _strFtpUser, String _strFtpPwd,
// String _strEntryDesDir, String _strFileName, int _iFileNum, String _strLocalFileDir) {
// return ftpGetFile(_strHost, _strPort,
// _strFtpUser, _strFtpPwd,
// _strEntryDesDir, _strFileName, _iFileNum, _strLocalFileDir , "");
// }
// public static List ftpGetFile(String _strHost, String _strPort,
// String _strFtpUser, String _strFtpPwd,
// String _strEntryDesDir, String _strFileName, int _iFileNum, String _strLocalFileDir, String _strIgnoreFileName) {
//
// int iRtn = FTP_NO_FILE_TRANSFER;
// List<String> fileList = new ArrayList<String>();
//
// log.info("ip=" + _strHost + ", port=" + _strPort + ", user="
// + _strFtpUser + ", passwd=" + _strFtpPwd + ", entryDir="
// + _strEntryDesDir + ", file=" + _strFileName + ", num=" + _iFileNum );
//
// if (_strFileName == null || _iFileNum == 0 || _strLocalFileDir == null) {
// return null;
// }
//
// FTPClient ftp = null;
//
// try {
// iRtn = FTP_CONNECT_ERROR;
// ftp = new FTPClient();
// ftp.setRemoteHost(_strHost);
// ftp.setRemotePort(Integer.parseInt(_strPort));
// ftp.setTimeout(FTP_TIMEOUT);
// ftp.connect();
// iRtn = FTP_LOGIN_ERROR;
// ftp.login(_strFtpUser, _strFtpPwd);
// log.info("Login OK![" + _strHost + ":" + _strPort + ":" + _strFtpUser + "]");
// ftp.setType(FTPTransferType.BINARY);
// if (_strEntryDesDir.trim().length() > 0 && !_strEntryDesDir.trim().equals(".")) {
// if(_strEntryDesDir.substring(0, 1).equals("/")){ //绝对路径
// ftp.chdir(_strEntryDesDir.trim());
// log.info("Change Dir : " + _strEntryDesDir.trim() + " OK!");
// }
// else{ //相对路径
// String[] strDirs = _strEntryDesDir.split("/", -1);
// if (strDirs != null) {
// String strCurDir = "";
// for (int i = 0; i < strDirs.length; i++) {
// if (strCurDir.length() > 0) {
// strCurDir = strCurDir + "/" + strDirs[i];
// } else {
// strCurDir = strDirs[i];
// }
// try {
// ftp.mkdir(strDirs[i]);
// log.info("Create Dir : " + strCurDir + " OK!");
// } catch (FTPException ex1) {
// }
// ftp.chdir(strDirs[i]);
// }
// log.info("Change Dir : " + strCurDir + " OK!");
// }
// }
// }
//
// if(!dirIsExist(_strLocalFileDir)){
// SystemUtil.createDir(_strLocalFileDir);
// }
//
// ftp.setConnectMode(FTPConnectMode.PASV);
//
// String[] remortFileNames = ftp.dir(_strFileName + "*");
// for (int i = 0; i < remortFileNames.length; i++) {
// if(!ConvertUtil.nvl(_strIgnoreFileName).equals("")){
// if(remortFileNames[i].indexOf(_strIgnoreFileName) >= 0){
// continue;
// }
// }
// String localFile = _strLocalFileDir + File.separator + remortFileNames[i];
// iRtn = FTP_TRANSFER_ERROR;
// ftp.get(localFile, remortFileNames[i]);
// log.info("Get file " + remortFileNames[i]);
// fileList.add(localFile);
//
// if(i + 1 == _iFileNum){
// break;
// }
// }
// iRtn = FTP_LOGOUT_ERROR;
// ftp.quit();
// log.info("Logout!" + "\n");
// }
// catch (FTPException ex) {
// if(iRtn == FTP_LOGOUT_ERROR){
// return fileList;
// }else{
// if(ex.getMessage().indexOf("No such file") >= 0){
// return fileList;
// }
// else if(ex.getMessage().indexOf("Bad directory") >= 0){
// return fileList;
// }
// else{
// log.error("ftpGetFile :" + ex.getMessage());
// return null;
// }
// }
// }
// catch (IOException ex1) {
// if(iRtn == FTP_LOGOUT_ERROR){
// return fileList;
// }else{
// log.info("ftpGetFile :" + ex1.getMessage());
// return null;
// }
// }
// catch (NumberFormatException ex2) {
// if(iRtn == FTP_LOGOUT_ERROR){
// return fileList;
// }else{
// log.info("ftpGetFile :" + ex2.getMessage());
// return null;
// }
// }
//
// log.info("ftpGetFile end. get files num=" + fileList.size());
// return fileList;
// }
public
static
int
ftpDeleteFile
(
String
_strHost
,
String
_strPort
,
String
_strFtpUser
,
String
_strFtpPwd
,
String
_strEntryDesDir
,
String
[]
_strFileNames
)
{
int
iRtn
=
FTP_NO_FILE_TRANSFER
;
if
(
_strFileNames
.
length
<=
0
)
{
return
0
;
}
FTPClient
ftp
=
null
;
try
{
ftp
=
new
FTPClient
();
ftp
.
setRemoteHost
(
_strHost
);
ftp
.
setRemotePort
(
Integer
.
parseInt
(
_strPort
));
ftp
.
setTimeout
(
FTP_TIMEOUT
);
ftp
.
connect
();
ftp
.
login
(
_strFtpUser
,
_strFtpPwd
);
log
.
info
(
"Login OK!["
+
_strHost
+
":"
+
_strPort
+
":"
+
_strFtpUser
+
"]"
);
ftp
.
setType
(
FTPTransferType
.
BINARY
);
ftp
.
setConnectMode
(
FTPConnectMode
.
PASV
);
if
(
_strEntryDesDir
.
trim
().
length
()
>
0
)
{
if
(
_strEntryDesDir
.
substring
(
0
,
1
).
equals
(
"/"
)){
//绝对路径
ftp
.
chdir
(
_strEntryDesDir
.
trim
());
log
.
info
(
"Change Dir : "
+
_strEntryDesDir
.
trim
()
+
" OK!"
);
}
else
{
//相对路径
String
[]
strDirs
=
_strEntryDesDir
.
split
(
"/"
,
-
1
);
if
(
strDirs
!=
null
)
{
String
strCurDir
=
""
;
for
(
int
i
=
0
;
i
<
strDirs
.
length
;
i
++)
{
if
(
strCurDir
.
length
()
>
0
)
{
strCurDir
=
strCurDir
+
"/"
+
strDirs
[
i
];
}
else
{
strCurDir
=
strDirs
[
i
];
}
ftp
.
chdir
(
strDirs
[
i
]);
}
log
.
info
(
"Change Dir : "
+
strCurDir
+
" OK!"
);
}
}
}
for
(
int
i
=
0
;
i
<
_strFileNames
.
length
;
i
++)
{
if
(
_strFileNames
[
i
].
length
()
<=
0
)
continue
;
try
{
ftp
.
delete
(
_strFileNames
[
i
]);
log
.
info
(
"Delete file "
+
_strFileNames
[
i
]
+
" OK!"
);
}
catch
(
FTPException
ex1
)
{
log
.
info
(
"Delete file "
+
_strFileNames
[
i
]
+
" FAIL!"
+
ex1
.
getMessage
());
}
catch
(
IOException
ex1
)
{
log
.
info
(
"Delete file "
+
_strFileNames
[
i
]
+
" FAIL!"
+
ex1
.
getMessage
());
}
}
iRtn
=
FTP_LOGOUT_ERROR
;
ftp
.
quit
();
log
.
info
(
"Logout!"
+
"\n"
);
}
catch
(
FTPException
ex
)
{
log
.
info
(
"ftpDeleteFile : "
+
ex
.
getMessage
());
return
-
1
;
}
catch
(
IOException
ex1
)
{
log
.
info
(
"ftpDeleteFile : "
+
ex1
.
getMessage
());
return
-
2
;
}
catch
(
NumberFormatException
ex2
)
{
log
.
info
(
"ftpDeleteFile : "
+
ex2
.
getMessage
());
return
-
3
;
}
return
0
;
}
public
static
int
ftpRenameFile
(
String
_strHost
,
String
_strPort
,
String
_strFtpUser
,
String
_strFtpPwd
,
String
_strEntryDir
,
String
[]
_strEntrySrcFilePaths
,
String
[]
_strEntryDesFilePaths
)
{
int
iRtn
=
FTP_NO_FILE_TRANSFER
;
if
(
_strEntrySrcFilePaths
.
length
<=
0
)
{
return
0
;
}
if
(
_strEntryDesFilePaths
.
length
<=
0
)
{
return
0
;
}
FTPClient
ftp
=
null
;
try
{
iRtn
=
FTP_CONNECT_ERROR
;
ftp
=
new
FTPClient
();
ftp
.
setRemoteHost
(
_strHost
);
ftp
.
setRemotePort
(
Integer
.
parseInt
(
_strPort
));
ftp
.
setTimeout
(
FTP_TIMEOUT
);
ftp
.
connect
();
iRtn
=
FTP_LOGIN_ERROR
;
ftp
.
login
(
_strFtpUser
,
_strFtpPwd
);
log
.
info
(
"Login OK!["
+
_strHost
+
":"
+
_strPort
+
":"
+
_strFtpUser
+
"]"
);
ftp
.
setType
(
FTPTransferType
.
BINARY
);
ftp
.
setConnectMode
(
FTPConnectMode
.
PASV
);
if
(
_strEntryDir
.
trim
().
length
()
>
0
)
{
String
[]
strDirs
=
_strEntryDir
.
split
(
"/"
,
-
1
);
if
(
strDirs
!=
null
)
{
String
strCurDir
=
""
;
for
(
int
i
=
0
;
i
<
strDirs
.
length
;
i
++)
{
if
(
strCurDir
.
length
()
>
0
)
{
strCurDir
=
strCurDir
+
"/"
+
strDirs
[
i
];
}
else
{
strCurDir
=
strDirs
[
i
];
}
ftp
.
chdir
(
strDirs
[
i
]);
}
log
.
info
(
"Change Dir : "
+
strCurDir
+
" OK!"
);
}
}
for
(
int
i
=
0
;
i
<
_strEntrySrcFilePaths
.
length
;
i
++)
{
if
(
_strEntrySrcFilePaths
[
i
].
length
()
<=
0
)
continue
;
if
(
_strEntryDesFilePaths
[
i
].
length
()
<=
0
)
continue
;
String
[]
strDirs
=
_strEntryDesFilePaths
[
i
].
split
(
"/"
,
-
1
);
if
(
strDirs
!=
null
)
{
String
strDesDir
=
""
;
for
(
int
j
=
0
;
j
<
strDirs
.
length
-
1
;
j
++)
{
if
(
j
==
0
)
{
strDesDir
+=
strDirs
[
j
];
}
else
{
strDesDir
+=
"/"
+
strDirs
[
j
];
}
try
{
ftp
.
mkdir
(
strDesDir
);
log
.
info
(
"Create Dir : "
+
strDesDir
+
" OK!"
);
}
catch
(
FTPException
ex1
)
{
}
}
}
try
{
iRtn
=
FTP_TRANSFER_ERROR
;
ftp
.
rename
(
_strEntrySrcFilePaths
[
i
],
_strEntryDesFilePaths
[
i
]);
log
.
info
(
"Rename file "
+
_strEntrySrcFilePaths
[
i
]
+
" to "
+
_strEntryDesFilePaths
[
i
]
+
" OK!"
);
}
catch
(
FTPException
ex1
)
{
log
.
error
(
"Rename file "
+
_strEntrySrcFilePaths
[
i
]
+
" to "
+
_strEntryDesFilePaths
[
i
]
+
" FAIL! "
+
ex1
.
getMessage
());
}
catch
(
IOException
ex1
)
{
log
.
error
(
"Rename file "
+
_strEntrySrcFilePaths
[
i
]
+
" to "
+
_strEntryDesFilePaths
[
i
]
+
" FAIL! b"
+
ex1
.
getMessage
());
}
}
iRtn
=
FTP_LOGOUT_ERROR
;
ftp
.
quit
();
iRtn
=
FTP_OK
;
log
.
info
(
"Logout!"
+
"\n"
);
}
catch
(
FTPException
ex
)
{
log
.
error
(
ex
.
getMessage
(),
ex
);
ex
.
printStackTrace
();
// return -1;
}
catch
(
IOException
ex
)
{
log
.
error
(
ex
.
getMessage
(),
ex
);
ex
.
printStackTrace
();
// return -2;
}
catch
(
NumberFormatException
ex2
)
{
log
.
error
(
ex2
.
getMessage
(),
ex2
);
ex2
.
printStackTrace
();
// return -3;
}
return
iRtn
;
}
}
commons-file/src/main/java/cn/spatiotemporal/commons/file/vo/FileInfo.java
0 → 100644
View file @
403bc21d
package
cn.spatiotemporal.commons.file.vo
;
import
lombok.Data
;
/**
*
* @ClassName: FileInfo
* @Description: 文件基础信息
* @date 2023年9月13日 上午9:52:43
*
* @author Q.JI
* @version
* @since JDK 1.8
*/
@Data
public
class
FileInfo
{
private
String
name
;
private
String
url
;
private
String
type
;
private
Long
size
;
private
String
originalName
;
}
commons-file/src/main/resources/META-INF/spring.factories
0 → 100644
View file @
403bc21d
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
cn.spatiotemporal.commons.file.service.impl.MinioServiceImpl,\
cn.spatiotemporal.commons.file.service.impl.FtpServiceImpl,\
cn.spatiotemporal.commons.file.controller.FileController
\ No newline at end of file
commons-register/README.md
0 → 100644
View file @
403bc21d
# spatiotemporal-commons-register
**时空开放平台 公用组件-服务自注册**
服务自注册到redis,供其它服务调用
## 使用方法
*
在工程pom.xml文件添加以下依赖
```
xml
<dependency>
<groupId>
cn.spatiotemporal
</groupId>
<artifactId>
spatiotemporal-commons-register
</artifactId>
<version>
1.0.0-RELEASE
</version>
</dependency>
```
***注意选择合适的版本**
*
*
在Application启动类添加
`@EnableServerRegister`
注解
```
java
@EnableServerRegister
(
autoRegister
=
true
,
period
=
60
)
//参数说明:
// autoRegister:是否启用服务自注册,false-不启用;true-启用(default true)
// period:存续心跳,单位秒。(default 30)
```
## License
时空开放平台是一个基于
[
Apache 2.0 license
](
https://www.apache.org/licenses/LICENSE-2.0.html
)
发布的开源软件。
commons-register/pom.xml
0 → 100644
View file @
403bc21d
<?xml version="1.0" encoding="UTF-8"?>
<project
xmlns=
"http://maven.apache.org/POM/4.0.0"
xmlns:xsi=
"http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=
"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
>
<parent>
<groupId>
cn.spatiotemporal
</groupId>
<artifactId>
spatiotemporal-commons
</artifactId>
<version>
1.0.0-RELEASE
</version>
</parent>
<modelVersion>
4.0.0
</modelVersion>
<artifactId>
spatiotemporal-commons-register
</artifactId>
<properties>
<project.build.sourceEncoding>
UTF-8
</project.build.sourceEncoding>
<java.version>
1.8
</java.version>
<maven-jar-plugin.version>
3.1.1
</maven-jar-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>
com.github.oshi
</groupId>
<artifactId>
oshi-core
</artifactId>
<version>
5.8.2
</version>
</dependency>
</dependencies>
</project>
commons-register/src/main/java/cn/spatiotemporal/commons/config/EnableServerCorn.java
0 → 100644
View file @
403bc21d
package
cn.spatiotemporal.commons.config
;
import
java.util.concurrent.Executors
;
import
java.util.concurrent.ThreadFactory
;
import
java.util.concurrent.TimeUnit
;
import
javax.annotation.PostConstruct
;
import
javax.annotation.Resource
;
import
org.apache.commons.lang3.concurrent.BasicThreadFactory
;
import
org.springframework.beans.factory.annotation.Value
;
import
org.springframework.data.redis.core.RedisTemplate
;
import
cn.spatiotemporal.commons.constant.RegisterConstants
;
import
cn.spatiotemporal.commons.util.IpUtil
;
import
lombok.extern.slf4j.Slf4j
;
/**
*
* @ClassName: EnableServerCorn
* @Description: 服务配置
* @date 2023年8月29日 下午5:24:27
*
* @author Q.JI
* @version
* @since JDK 1.8
*/
@Slf4j
public
class
EnableServerCorn
{
/**
* 服务端口
*/
@Value
(
"${server.port}"
)
private
String
port
;
@Value
(
"${server.name}"
)
private
String
serveName
;
@Value
(
"${server.servlet.context-path}"
)
private
String
contextPath
;
public
Integer
getPeriod
()
{
return
period
;
}
public
void
setPeriod
(
Integer
period
)
{
this
.
period
=
period
;
}
/**
* 轮询时间 = period 过期时间=period+5
*/
private
Integer
period
;
/**
* 本机ip
*/
private
String
ip
=
IpUtil
.
getEthIp4
(
"127.0.0.1"
);
@Resource
RedisTemplate
<
String
,
Object
>
redisTemplate
;
@PostConstruct
public
void
initMethod
()
{
if
(
redisTemplate
==
null
)
{
log
.
error
(
"redisTemplate在容器中不存在"
);
throw
new
RuntimeException
();
}
// 获取间隔时间
if
(
period
==
null
)
{
period
=
30
;
}
if
(!
ip
.
equals
(
"127.0.0.1"
))
{
String
key
=
RegisterConstants
.
SERVICE_REGISTER_KEY
+
serveName
+
":"
+
ip
+
":"
+
port
+
contextPath
;
ThreadFactory
threadFactory
=
new
BasicThreadFactory
.
Builder
().
namingPattern
(
serveName
+
"_Thread-%d"
).
build
();
Executors
.
newSingleThreadScheduledExecutor
(
threadFactory
).
scheduleAtFixedRate
(()
->
{
try
{
boolean
exist
=
redisTemplate
.
opsForValue
().
setIfAbsent
(
key
,
""
,
period
+
5
,
TimeUnit
.
SECONDS
);
if
(!
exist
)
redisTemplate
.
expire
(
key
,
period
+
5
,
TimeUnit
.
SECONDS
);
log
.
debug
(
"===== {} 服务续期 ===="
,
key
);
}
catch
(
Exception
ex
)
{
log
.
error
(
serveName
+
"服务注册发生错误!"
,
ex
);
}
},
5
,
period
,
TimeUnit
.
SECONDS
);
log
.
info
(
"========== ‘{}’ 服务注册. =========="
,
serveName
);
}
else
{
log
.
warn
(
"服务:{}所在主机IP:{}获取无效,服务无法注册!"
,
serveName
,
ip
);
}
}
public
EnableServerCorn
()
{
}
}
commons-register/src/main/java/cn/spatiotemporal/commons/config/EnableServerRegister.java
0 → 100644
View file @
403bc21d
package
cn.spatiotemporal.commons.config
;
import
java.lang.annotation.Documented
;
import
java.lang.annotation.ElementType
;
import
java.lang.annotation.Inherited
;
import
java.lang.annotation.Retention
;
import
java.lang.annotation.RetentionPolicy
;
import
java.lang.annotation.Target
;
import
org.springframework.context.annotation.Import
;
/**
*
* @ClassName: EnableServerRegister2
* @Description: 服务器注册开启注解
* @date 2023年8月29日 下午5:08:01
*
* @author Q.JI
* @version
* @since JDK 1.8
*/
@Target
(
ElementType
.
TYPE
)
@Retention
(
RetentionPolicy
.
RUNTIME
)
@Import
(
ServerRegisterAutoConfig
.
class
)
@Documented
@Inherited
public
@interface
EnableServerRegister
{
//是否启用 默认启用
boolean
autoRegister
()
default
true
;
//间隔时间 时间单位(second) 默认30second
int
period
()
default
30
;
}
\ No newline at end of file
commons-register/src/main/java/cn/spatiotemporal/commons/config/ServerRegisterAutoConfig.java
0 → 100644
View file @
403bc21d
package
cn.spatiotemporal.commons.config
;
import
java.util.Map
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
org.springframework.beans.MutablePropertyValues
;
import
org.springframework.beans.factory.support.AbstractBeanDefinition
;
import
org.springframework.beans.factory.support.BeanDefinitionBuilder
;
import
org.springframework.beans.factory.support.BeanDefinitionRegistry
;
import
org.springframework.context.annotation.ImportBeanDefinitionRegistrar
;
import
org.springframework.core.Ordered
;
import
org.springframework.core.annotation.Order
;
import
org.springframework.core.type.AnnotationMetadata
;
import
lombok.extern.slf4j.Slf4j
;
/**
*
* @ClassName: ServerRegisterAutoConfig2
* @Description: 服务器注册自动配置类 可以加入间隔时间参数
* @date 2023年8月29日 下午5:08:29
*
* @author Q.JI
* @version
* @since JDK 1.8
*/
@Slf4j
@Order
(
Ordered
.
LOWEST_PRECEDENCE
)
public
class
ServerRegisterAutoConfig
implements
ImportBeanDefinitionRegistrar
{
Logger
logger
=
LoggerFactory
.
getLogger
(
ServerRegisterAutoConfig
.
class
);
@Override
public
void
registerBeanDefinitions
(
AnnotationMetadata
annotationMetadata
,
BeanDefinitionRegistry
beanDefinitionRegistry
)
{
// 获取EnableServerRegister注解的所有属性的value
Map
<
String
,
Object
>
attributes
=
annotationMetadata
.
getAnnotationAttributes
(
EnableServerRegister
.
class
.
getName
());
if
(
attributes
==
null
)
{
return
;
}
// 获取autoRegister属性的value
Boolean
autoRegister
=
(
Boolean
)
attributes
.
get
(
"autoRegister"
);
if
(
autoRegister
==
null
||
autoRegister
==
false
)
{
return
;
}
Integer
period
=
(
Integer
)
attributes
.
get
(
"period"
);
BeanDefinitionBuilder
beanDefinitionBuilder
=
BeanDefinitionBuilder
.
rootBeanDefinition
(
EnableServerCorn
.
class
);
AbstractBeanDefinition
definition
=
beanDefinitionBuilder
.
getBeanDefinition
();
MutablePropertyValues
values
=
definition
.
getPropertyValues
();
values
.
addPropertyValue
(
"period"
,
period
);
beanDefinitionRegistry
.
registerBeanDefinition
(
"enableServerCorn"
,
definition
);
logger
.
info
(
"enableServerRegister服务注册成功!"
);
}
}
\ No newline at end of file
commons-register/src/main/java/cn/spatiotemporal/commons/constant/RegisterConstants.java
0 → 100644
View file @
403bc21d
package
cn.spatiotemporal.commons.constant
;
/**
* @ClassName: RegisterConstants
* @Description: RegisterConstants
* @date 2023年9月12日 上午8:46:58
*
* @author Q.JI
* @version
* @since JDK 1.8
*/
public
class
RegisterConstants
{
/**
* 服务自注册前缀KEY
*/
public
static
String
SERVICE_REGISTER_KEY
=
"cn.spatiotemporal:svcregister:"
;
}
commons-register/src/main/java/cn/spatiotemporal/commons/util/IpUtil.java
0 → 100644
View file @
403bc21d
package
cn.spatiotemporal.commons.util
;
import
java.net.InetAddress
;
import
java.util.List
;
import
javax.servlet.http.HttpServletRequest
;
import
cn.hutool.core.net.NetUtil
;
import
cn.hutool.system.HostInfo
;
import
cn.hutool.system.SystemUtil
;
import
cn.hutool.system.oshi.OshiUtil
;
import
oshi.hardware.NetworkIF
;
/**
*
* @ClassName:IpUtil
* @Description: IpUtil
* @date 2022年12月14日 下午午6:10:00
*
* @author yifan.wang
* @version
* @since JDK 1.8
*/
public
class
IpUtil
{
/**
* 获取用户真实IP地址,不使用request.getRemoteAddr();的原因是有可能用户使用了代理软件方式避免真实IP地址,
*
* 可是,如果通过了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP值,究竟哪个才是真正的用户端的真实IP呢?
* 答案是取X-Forwarded-For中第一个非unknown的有效IP字符串。
*
* 如:X-Forwarded-For:192.168.1.110, 192.168.1.120, 192.168.1.130,
* 192.168.1.100
*
* 用户真实IP为: 192.168.1.110
*
* @param request
* @return
*/
public
static
String
getIpAddress
(
HttpServletRequest
request
)
{
String
ip
=
request
.
getHeader
(
"x-forwarded-for"
);
if
(
ip
==
null
||
ip
.
length
()
==
0
||
"unknown"
.
equalsIgnoreCase
(
ip
))
{
ip
=
request
.
getHeader
(
"Proxy-Client-IP"
);
}
if
(
ip
==
null
||
ip
.
length
()
==
0
||
"unknown"
.
equalsIgnoreCase
(
ip
))
{
ip
=
request
.
getHeader
(
"WL-Proxy-Client-IP"
);
}
if
(
ip
==
null
||
ip
.
length
()
==
0
||
"unknown"
.
equalsIgnoreCase
(
ip
))
{
ip
=
request
.
getHeader
(
"HTTP_CLIENT_IP"
);
}
if
(
ip
==
null
||
ip
.
length
()
==
0
||
"unknown"
.
equalsIgnoreCase
(
ip
))
{
ip
=
request
.
getHeader
(
"HTTP_X_FORWARDED_FOR"
);
}
if
(
ip
==
null
||
ip
.
length
()
==
0
||
"unknown"
.
equalsIgnoreCase
(
ip
))
{
ip
=
request
.
getRemoteAddr
();
}
return
ip
;
}
/**
*
* @Title: getEthIp4
* @Description:
* 网卡名称为eth
* en标识ethernet
o:主板板载网卡,集成是的设备索引号
p:独立网卡,PCI网卡
s:热插拔网卡,USB之类的扩展槽索引号
nnn(数字):MAC地址+主板信息计算得出唯一序列
* @param ip
* @return
* String
*/
public
static
String
getEthIp4
(
String
ip
)
{
String
ethip
=
ip
;
List
<
NetworkIF
>
networkIFs
=
OshiUtil
.
getNetworkIFs
();
for
(
NetworkIF
networkIF
:
networkIFs
)
{
// System.out.println("networkIF.getName():" + networkIF.getName() + "|" + String.join(",", networkIF.getIPv4addr()) );
if
(
networkIF
.
getName
().
startsWith
(
"eth"
)
||
networkIF
.
getName
().
startsWith
(
"en"
))
{
String
[]
iPv4addr
=
networkIF
.
getIPv4addr
();
if
(
null
!=
iPv4addr
&&
iPv4addr
.
length
>
0
)
{
ethip
=
iPv4addr
[
0
];
return
ethip
;
}
}
}
return
ethip
;
}
// public static void main(String[] args) {
// HostInfo hostInfo = SystemUtil.getHostInfo();
// System.out.println(hostInfo.getAddress());
// System.out.println("=====================");
// InetAddress inetAddress = NetUtil.getLocalhost();
// System.out.println(inetAddress.getHostAddress());
// System.out.println("=====================");
// System.out.println(IpUtil.getEthIp4("127.0.0.1"));
// }
}
pom.xml
0 → 100644
View file @
403bc21d
<?xml version="1.0" encoding="UTF-8"?>
<project
xmlns=
"http://maven.apache.org/POM/4.0.0"
xmlns:xsi=
"http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=
"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
>
<modelVersion>
4.0.0
</modelVersion>
<groupId>
cn.spatiotemporal
</groupId>
<artifactId>
spatiotemporal-commons
</artifactId>
<version>
1.0.0-RELEASE
</version>
<packaging>
pom
</packaging>
<name>
时空开放平台 公用套件
</name>
<properties>
<project.build.sourceEncoding>
UTF-8
</project.build.sourceEncoding>
<project.reporting.outputEncoding>
UTF-8
</project.reporting.outputEncoding>
<java.version>
1.8
</java.version>
<!-- tools -->
<hutool.version>
5.8.21
</hutool.version>
<!-- api doc -->
<swagger.version>
1.6.2
</swagger.version>
</properties>
<parent>
<groupId>
org.springframework.boot
</groupId>
<artifactId>
spring-boot-starter-parent
</artifactId>
<version>
2.3.12.RELEASE
</version>
<relativePath
/>
</parent>
<dependencies>
<dependency>
<groupId>
org.projectlombok
</groupId>
<artifactId>
lombok
</artifactId>
<scope>
provided
</scope>
</dependency>
<dependency>
<groupId>
ch.qos.logback
</groupId>
<artifactId>
logback-classic
</artifactId>
<scope>
provided
</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>
javax.servlet
</groupId>
<artifactId>
javax.servlet-api
</artifactId>
<scope>
provided
</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>
org.springframework
</groupId>
<artifactId>
spring-context
</artifactId>
<scope>
provided
</scope>
</dependency>
<dependency>
<groupId>
org.springframework.boot
</groupId>
<artifactId>
spring-boot-starter-data-redis
</artifactId>
<scope>
provided
</scope>
</dependency>
<dependency>
<groupId>
org.springframework.boot
</groupId>
<artifactId>
spring-boot-starter-cache
</artifactId>
<scope>
provided
</scope>
</dependency>
<dependency>
<groupId>
org.apache.commons
</groupId>
<artifactId>
commons-lang3
</artifactId>
</dependency>
<dependency>
<groupId>
com.fasterxml.jackson.core
</groupId>
<artifactId>
jackson-databind
</artifactId>
<scope>
provided
</scope>
</dependency>
<dependency>
<groupId>
com.fasterxml.jackson.core
</groupId>
<artifactId>
jackson-core
</artifactId>
<scope>
provided
</scope>
</dependency>
<dependency>
<groupId>
cn.hutool
</groupId>
<artifactId>
hutool-all
</artifactId>
<version>
${hutool.version}
</version>
</dependency>
<dependency>
<groupId>
io.swagger
</groupId>
<artifactId>
swagger-annotations
</artifactId>
<version>
${swagger.version}
</version>
</dependency>
</dependencies>
<!-- ========================modules============================== -->
<modules>
<module>
commons-core
</module>
<module>
commons-register
</module>
<module>
commons-file
</module>
</modules>
<distributionManagement>
<!-- 发布到快照版本的仓库,即测试版本仓库 -->
<snapshotRepository>
<id>
inzyme-snapshots
</id>
<url>
https://tydicdata.com/nexus/repository/maven-snapshots/
</url>
</snapshotRepository>
<!-- 发布到发行版本的仓库中,即正式版本仓库 -->
<repository>
<id>
inzyme-releases
</id>
<url>
https://tydicdata.com/nexus/repository/maven-releases/
</url>
</repository>
</distributionManagement>
</project>
Prev
1
2
Next
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment