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-core
Commits
9742023a
Commit
9742023a
authored
Jan 18, 2024
by
侯力峰
Browse files
首次开源发布
parent
444abeb0
Pipeline
#2755
canceled with stages
Changes
52
Pipelines
1
Hide whitespace changes
Inline
Side-by-side
src/main/java/cn/spatiotemporal/core/ftp/FtpClientPooledObjectFactory.java
0 → 100644
View file @
9742023a
package
cn.spatiotemporal.core.ftp
;
import
java.io.IOException
;
import
org.apache.commons.net.ftp.FTPClient
;
import
org.apache.commons.pool2.PooledObject
;
import
org.apache.commons.pool2.PooledObjectFactory
;
import
org.apache.commons.pool2.impl.DefaultPooledObject
;
import
cn.spatiotemporal.core.config.ftp.FtpProperties
;
import
lombok.extern.slf4j.Slf4j
;
@Slf4j
public
class
FtpClientPooledObjectFactory
implements
PooledObjectFactory
<
FTPClient
>
{
private
FtpProperties
ftpProperties
;
public
FtpClientPooledObjectFactory
(
FtpProperties
ftpProperties
)
{
this
.
ftpProperties
=
ftpProperties
;
}
@Override
public
PooledObject
<
FTPClient
>
makeObject
()
throws
Exception
{
FTPClient
ftpClient
=
new
FTPClient
();
try
{
ftpClient
.
connect
(
ftpProperties
.
getIp
(),
Integer
.
valueOf
(
ftpProperties
.
getPort
()));
ftpClient
.
login
(
ftpProperties
.
getUsername
(),
ftpProperties
.
getPassword
());
log
.
info
(
"连接ftp服务返回码:"
+
ftpClient
.
getReplyCode
());
ftpClient
.
setBufferSize
(
ftpProperties
.
getBufferSize
());
ftpClient
.
setControlEncoding
(
ftpProperties
.
getEncoding
());
ftpClient
.
setFileType
(
FTPClient
.
BINARY_FILE_TYPE
);
ftpClient
.
enterLocalPassiveMode
();
return
new
DefaultPooledObject
<>(
ftpClient
);
}
catch
(
Exception
e
)
{
if
(
ftpClient
.
isAvailable
())
{
ftpClient
.
disconnect
();
}
ftpClient
=
null
;
log
.
error
(
"建立ftp连接失败!"
,
(
Object
)
e
.
getStackTrace
());
throw
new
Exception
(
"建立ftp连接失败!"
,
e
);
}
}
@Override
public
void
destroyObject
(
PooledObject
<
FTPClient
>
pooledObject
)
throws
Exception
{
FTPClient
ftpClient
=
getObject
(
pooledObject
);
if
(
null
!=
ftpClient
&&
ftpClient
.
isConnected
())
{
ftpClient
.
disconnect
();
}
}
@Override
public
boolean
validateObject
(
PooledObject
<
FTPClient
>
pooledObject
)
{
FTPClient
ftpClient
=
getObject
(
pooledObject
);
if
(
null
==
ftpClient
||
!
ftpClient
.
isConnected
())
{
return
false
;
}
try
{
ftpClient
.
changeWorkingDirectory
(
"/"
);
return
true
;
}
catch
(
IOException
e
)
{
log
.
error
(
"验证ftp连接失败!"
,
(
Object
)
e
.
getStackTrace
());
return
false
;
}
}
@Override
public
void
activateObject
(
PooledObject
<
FTPClient
>
pooledObject
)
throws
Exception
{
}
@Override
public
void
passivateObject
(
PooledObject
<
FTPClient
>
pooledObject
)
throws
Exception
{
}
private
FTPClient
getObject
(
PooledObject
<
FTPClient
>
pooledObject
)
{
if
(
null
==
pooledObject
||
null
==
pooledObject
.
getObject
())
{
return
null
;
}
return
pooledObject
.
getObject
();
}
}
src/main/java/cn/spatiotemporal/core/ftp/FtpConstants.java
0 → 100644
View file @
9742023a
package
cn.spatiotemporal.core.ftp
;
public
interface
FtpConstants
{
//ftp文件路径编码格式
String
DEFAULT_FTP_PATH_ENCODING
=
"ISO-8859-1"
;
}
src/main/java/cn/spatiotemporal/core/ftp/FtpDao.java
0 → 100644
View file @
9742023a
package
cn.spatiotemporal.core.ftp
;
import
java.io.IOException
;
import
java.io.InputStream
;
import
java.util.List
;
import
org.apache.commons.net.ftp.FTPClient
;
public
interface
FtpDao
{
FTPClient
getCurrentClient
();
boolean
uploadFile
(
String
path
,
String
fileName
,
String
originFileName
);
boolean
uploadFile
(
String
path
,
String
fileName
,
InputStream
inputStream
)
throws
IOException
;
boolean
downloadFile
(
String
path
,
String
fileName
,
String
localPath
);
boolean
deleteFile
(
String
path
,
String
fileName
);
boolean
createDirectory
(
String
remote
);
boolean
existFile
(
String
path
);
boolean
makeDirectory
(
String
directory
);
List
<
String
>
retrieveFileNames
(
String
remotePath
);
}
src/main/java/cn/spatiotemporal/core/ftp/FtpTemplate.java
0 → 100644
View file @
9742023a
package
cn.spatiotemporal.core.ftp
;
import
java.io.BufferedReader
;
import
java.io.File
;
import
java.io.FileInputStream
;
import
java.io.FileOutputStream
;
import
java.io.IOException
;
import
java.io.InputStream
;
import
java.io.InputStreamReader
;
import
java.io.OutputStream
;
import
java.io.UnsupportedEncodingException
;
import
java.util.ArrayList
;
import
java.util.Arrays
;
import
java.util.List
;
import
java.util.Objects
;
import
java.util.stream.Collectors
;
import
org.apache.commons.lang.ArrayUtils
;
import
org.apache.commons.lang.StringUtils
;
import
org.apache.commons.net.ftp.FTPClient
;
import
org.apache.commons.net.ftp.FTPFile
;
import
org.apache.commons.pool2.ObjectPool
;
import
org.springframework.stereotype.Component
;
import
org.springframework.util.Assert
;
import
cn.spatiotemporal.core.config.ftp.FtpProperties
;
import
lombok.Getter
;
import
lombok.Setter
;
import
lombok.extern.slf4j.Slf4j
;
@Slf4j
@Getter
@Setter
public
class
FtpTemplate
implements
FtpDao
{
private
final
FtpProperties
ftpProperties
;
//连接池初始化标志
private
boolean
hasInit
=
false
;
//连接池
private
ObjectPool
<
FTPClient
>
ftpClientPool
;
private
FTPClient
currentClient
=
null
;
public
FtpTemplate
(
FtpProperties
ftpProperties
)
{
this
.
ftpProperties
=
ftpProperties
;
}
/**
* 上传文件
*
* @param path ftp服务器保存地址
* @param fileName 上传到ftp的文件名
* @param originFileName 等待上传的文件名(绝对地址或路径)
*/
@Override
public
boolean
uploadFile
(
String
path
,
String
fileName
,
String
originFileName
)
{
boolean
flag
=
false
;
try
{
InputStream
inputStream
=
new
FileInputStream
(
new
File
(
originFileName
));
flag
=
uploadFile
(
path
,
fileName
,
inputStream
);
}
catch
(
Exception
e
)
{
//log.error("上传文件出错!", (Object) e.getStackTrace());
e
.
printStackTrace
();
}
return
flag
;
}
/**
* 上传文件
*
* @param path ftp服务器保存地址
* @param fileName 上传到ftp的文件名
* @param inputStream 文件流
*/
@Override
public
boolean
uploadFile
(
String
path
,
String
fileName
,
InputStream
inputStream
)
throws
IOException
{
boolean
flag
=
false
;
currentClient
=
getFtpClient
();
try
{
currentClient
.
setFileType
(
FTPClient
.
BINARY_FILE_TYPE
);
createDirectory
(
path
);
currentClient
.
makeDirectory
(
path
);
currentClient
.
changeWorkingDirectory
(
path
);
currentClient
.
storeFile
(
fileName
,
inputStream
);
flag
=
true
;
}
catch
(
Exception
e
)
{
//log.error("上传文件出错!:{}", e);
e
.
printStackTrace
();
}
finally
{
if
(
null
!=
inputStream
)
inputStream
.
close
();
releaseFtpClient
(
currentClient
);
currentClient
=
null
;
}
return
flag
;
}
/**
* 下载文件
*
* @param path ftp服务器文件路径
* @param fileName 文件名称
* @param localPath 下载后的路径
*/
@Override
public
boolean
downloadFile
(
String
path
,
String
fileName
,
String
localPath
)
{
boolean
flag
=
false
;
OutputStream
outputStream
=
null
;
currentClient
=
getFtpClient
();
try
{
currentClient
.
changeWorkingDirectory
(
path
);
FTPFile
[]
files
=
currentClient
.
listFiles
();
for
(
FTPFile
file
:
files
)
{
if
(
fileName
.
equalsIgnoreCase
(
file
.
getName
()))
{
File
localFile
=
new
File
(
localPath
+
"/"
+
file
.
getName
());
outputStream
=
new
FileOutputStream
(
localFile
);
currentClient
.
retrieveFile
(
file
.
getName
(),
outputStream
);
outputStream
.
close
();
}
}
flag
=
true
;
}
catch
(
IOException
e
)
{
log
.
error
(
"下载文件出错!"
,
(
Object
)
e
.
getStackTrace
());
}
finally
{
releaseFtpClient
(
currentClient
);
if
(
null
!=
outputStream
)
{
try
{
outputStream
.
close
();
}
catch
(
IOException
e
)
{
log
.
error
(
"关闭输出流出错!"
,
(
Object
)
e
.
getStackTrace
());
}
}
currentClient
=
null
;
}
return
flag
;
}
/**
* 删除文件
*
* @param path ftp文件路径
* @param fileName 文件名
*/
@Override
public
boolean
deleteFile
(
String
path
,
String
fileName
)
{
boolean
flag
=
false
;
currentClient
=
getFtpClient
();
try
{
currentClient
.
changeWorkingDirectory
(
path
);
currentClient
.
dele
(
fileName
);
currentClient
.
logout
();
flag
=
true
;
}
catch
(
IOException
e
)
{
log
.
error
(
"删除文件出错!"
,
(
Object
)
e
.
getStackTrace
());
}
finally
{
releaseFtpClient
(
currentClient
);
currentClient
=
null
;
}
return
flag
;
}
/**
* 创建多层目录,如果ftp服务器已存在该目录,则不创建,如果没有,则创建
*
* @param remote 创建的目录
* @param currentClient
*/
@Override
public
boolean
createDirectory
(
String
remote
)
{
String
directory
=
remote
+
"/"
;
boolean
flag
=
true
;
if
(
currentClient
==
null
)
{
currentClient
=
getFtpClient
();
}
try
{
//如果远程目录不存在,则递归创建远程目录
if
(!
directory
.
equalsIgnoreCase
(
"/"
)
&&
!
changeWorkingDirectory
(
directory
))
{
int
start
=
0
;
int
end
=
0
;
if
(
directory
.
startsWith
(
"/"
))
{
start
=
1
;
}
end
=
directory
.
indexOf
(
"/"
,
start
);
String
path
=
""
;
String
paths
=
""
;
do
{
String
subDirectory
=
new
String
(
remote
.
substring
(
start
,
end
).
getBytes
(
ftpProperties
.
getEncoding
()),
FtpConstants
.
DEFAULT_FTP_PATH_ENCODING
);
path
=
path
+
"/"
+
subDirectory
;
if
(!
existFile
(
path
))
{
if
(
makeDirectory
(
subDirectory
))
{
changeWorkingDirectory
(
subDirectory
);
}
else
{
log
.
warn
(
"创建目录["
+
subDirectory
+
"]失败"
);
changeWorkingDirectory
(
subDirectory
);
flag
=
false
;
}
}
else
{
changeWorkingDirectory
(
subDirectory
);
}
paths
=
paths
+
"/"
+
subDirectory
;
start
=
end
+
1
;
end
=
directory
.
indexOf
(
"/"
,
start
);
}
while
(
end
<=
start
);
}
}
catch
(
IOException
e
)
{
log
.
error
(
"创建目录["
+
remote
+
"]失败!"
,
(
Object
)
e
.
getStackTrace
());
flag
=
false
;
}
return
flag
;
}
/**
* 判断ftp服务器的路径或文件是否存在
*
* @param path
* @param currentClient
*/
@Override
public
boolean
existFile
(
String
path
)
{
boolean
flag
=
false
;
if
(
currentClient
==
null
)
{
currentClient
=
getFtpClient
();
}
try
{
FTPFile
[]
files
=
currentClient
.
listFiles
(
path
);
if
(
files
.
length
>
0
)
{
flag
=
true
;
}
}
catch
(
IOException
e
)
{
log
.
error
(
"判断目录["
+
path
+
"]是否存在失败!"
,
(
Object
)
e
.
getStackTrace
());
flag
=
false
;
}
return
flag
;
}
/**
* 创建目录
*
* @param directory
* @param currentClient
*/
@Override
public
boolean
makeDirectory
(
String
directory
)
{
boolean
flag
=
true
;
if
(
currentClient
==
null
)
{
currentClient
=
getFtpClient
();
}
try
{
flag
=
currentClient
.
makeDirectory
(
directory
);
if
(
flag
)
{
log
.
info
(
"创建文件夹:"
+
directory
);
}
}
catch
(
IOException
e
)
{
log
.
error
(
"创建文件夹"
+
directory
+
"失败!"
,
(
Object
)
e
.
getStackTrace
());
flag
=
false
;
}
return
flag
;
}
/**
* 切换目录
*
* @param directory 要切换的目录
* @param currentClient ftp客户端
*/
public
boolean
changeWorkingDirectory
(
String
directory
)
{
boolean
flag
=
true
;
if
(
currentClient
==
null
)
{
currentClient
=
getFtpClient
();
}
try
{
flag
=
currentClient
.
changeWorkingDirectory
(
directory
);
if
(
flag
)
{
log
.
info
(
"进入文件夹:"
+
directory
);
}
}
catch
(
IOException
e
)
{
log
.
error
(
"进入文件夹:"
+
directory
+
"错误!"
,
(
Object
)
e
.
getStackTrace
());
flag
=
false
;
}
return
flag
;
}
/**
* 按行读取FTP文件
*
* @param remoteFilePath ftp路径
*/
public
List
<
String
>
readFileByLine
(
String
remoteFilePath
)
throws
IOException
{
currentClient
=
getFtpClient
();
try
(
InputStream
inputStream
=
currentClient
.
retrieveFileStream
(
encodingPath
(
remoteFilePath
));
BufferedReader
reader
=
new
BufferedReader
(
new
InputStreamReader
(
inputStream
)))
{
return
reader
.
lines
()
.
map
(
line
->
StringUtils
.
trimToEmpty
(
line
))
.
filter
(
line
->
StringUtils
.
isNotEmpty
(
line
))
.
collect
(
Collectors
.
toList
());
}
finally
{
currentClient
.
completePendingCommand
();
releaseFtpClient
(
currentClient
);
currentClient
=
null
;
}
}
/**
* 获取指定路径下的ftp文件
*
* @param remotePath 指定路径
*/
public
FTPFile
[]
retrieveFtpFiles
(
String
remotePath
)
{
currentClient
=
getFtpClient
();
try
{
return
currentClient
.
listFiles
(
encodingPath
(
remotePath
+
"/"
),
file
->
file
!=
null
&&
file
.
getSize
()
>
0
);
}
catch
(
IOException
e
)
{
log
.
error
(
"获取路径["
+
remotePath
+
"]下的文件列表失败!"
,
(
Object
)
e
.
getStackTrace
());
return
null
;
}
finally
{
releaseFtpClient
(
currentClient
);
currentClient
=
null
;
}
}
/**
* 获取指定ftp路径下的文件名称
*
* @param remotePath 指定ftp路径
*/
@Override
public
List
<
String
>
retrieveFileNames
(
String
remotePath
)
{
FTPFile
[]
files
=
retrieveFtpFiles
(
remotePath
);
if
(
ArrayUtils
.
isEmpty
(
files
))
{
return
new
ArrayList
<>();
}
return
Arrays
.
stream
(
files
).
filter
(
Objects:
:
nonNull
).
map
(
FTPFile:
:
getName
).
collect
(
Collectors
.
toList
());
}
/**
* 获取编码后的文件路径
*/
private
String
encodingPath
(
String
path
)
throws
UnsupportedEncodingException
{
//在FTP协议中,规定文件名编码格式为ISO-8859-1,所以目录名或文件名需要转码
return
new
String
(
path
.
replaceAll
(
"//"
,
"/"
).
getBytes
(
ftpProperties
.
getEncoding
()),
FtpConstants
.
DEFAULT_FTP_PATH_ENCODING
);
}
/**
* 获取ftp客户端
*/
private
FTPClient
getFtpClient
()
{
checkFtpClientPoolAvailable
();
FTPClient
ftpClient
=
null
;
Exception
exception
=
null
;
//获取连接,做多尝试n次
try
{
for
(
int
i
=
0
;
i
<
ftpProperties
.
getRetryCount
();
i
++)
{
ftpClient
=
ftpClientPool
.
borrowObject
();
ftpClient
.
enterLocalPassiveMode
();
//设置为被动模式
ftpClient
.
changeWorkingDirectory
(
"/"
);
break
;
}
}
catch
(
Exception
e
)
{
log
.
error
(
"无法在连接池中获取ftp客户端!"
,
(
Object
)
e
.
getStackTrace
());
exception
=
e
;
}
if
(
null
==
ftpClient
)
{
throw
new
RuntimeException
(
"无法在连接池中获取ftp客户端"
,
exception
);
}
return
ftpClient
;
}
/**
* 释放ftp客户端
*
* @param ftpClient
*/
private
void
releaseFtpClient
(
FTPClient
ftpClient
)
{
if
(
null
!=
ftpClient
)
{
try
{
//从ftp连接池中移除ftp客户端
ftpClientPool
.
returnObject
(
ftpClient
);
}
catch
(
Exception
e
)
{
try
{
//判断客户端是否可用
if
(
ftpClient
.
isAvailable
())
{
//销毁连接
ftpClient
.
disconnect
();
}
}
catch
(
IOException
ex
)
{
log
.
error
(
"销毁ftp连接失败!"
,
(
Object
)
e
.
getStackTrace
());
}
log
.
error
(
"从ftp连接池移除ftp客户端失败!"
,
(
Object
)
e
.
getStackTrace
());
}
}
}
/**
* 检查ftp连接池是否可用
*/
private
void
checkFtpClientPoolAvailable
()
{
Assert
.
state
(
hasInit
,
"ftp未启用或连接失败!"
);
}
}
src/main/java/cn/spatiotemporal/core/redis/RedisDao.java
0 → 100644
View file @
9742023a
package
cn.spatiotemporal.core.redis
;
import
java.io.IOException
;
import
java.util.ArrayList
;
import
java.util.Date
;
import
java.util.HashMap
;
import
java.util.List
;
import
java.util.Map
;
import
java.util.Set
;
import
java.util.concurrent.TimeUnit
;
import
java.util.function.Consumer
;
import
javax.annotation.Resource
;
import
org.springframework.data.redis.connection.RedisConnection
;
import
org.springframework.data.redis.core.Cursor
;
import
org.springframework.data.redis.core.RedisTemplate
;
import
org.springframework.data.redis.core.ScanOptions
;
import
org.springframework.stereotype.Component
;
import
org.springframework.util.CollectionUtils
;
import
com.alibaba.fastjson.JSONObject
;
/**
* Redis访问操作类
*
* @author marquis
*
*/
@Component
public
final
class
RedisDao
{
@Resource
private
RedisTemplate
redisTemplate
;
public
RedisTemplate
template
()
{
return
redisTemplate
;
}
public
Set
<
String
>
keys
(
String
keys
)
{
try
{
return
redisTemplate
.
keys
(
keys
);
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
null
;
}
}
/**
* 指定缓存失效时间
*
* @param key 键
* @param time 时间(秒)
* @return
*/
public
boolean
expire
(
String
key
,
long
time
)
{
try
{
if
(
time
>
0
)
{
redisTemplate
.
expire
(
key
,
time
,
TimeUnit
.
SECONDS
);
}
return
true
;
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
false
;
}
}
/**
* 指定缓存失效时间
*
* @param key 键
* @param time 时间(日期)
* @return
*/
public
boolean
expireAt
(
String
key
,
Date
time
)
{
try
{
redisTemplate
.
expireAt
(
key
,
time
);
return
true
;
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
false
;
}
}
/**
* 根据key 获取过期时间
*
* @param key 键 不能为null
* @return 时间(秒) 返回0代表为永久有效
*/
public
long
getExpire
(
String
key
)
{
return
redisTemplate
.
getExpire
(
key
,
TimeUnit
.
SECONDS
);
}
/**
* 判断key是否存在
*
* @param key 键
* @return true 存在 false不存在
*/
public
boolean
hasKey
(
String
key
)
{
try
{
return
redisTemplate
.
hasKey
(
key
);
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
false
;
}
}
/**
* 删除缓存
*
* @param key 可以传一个值 或多个
*/
@SuppressWarnings
(
"unchecked"
)
public
void
del
(
String
...
key
)
{
if
(
key
!=
null
&&
key
.
length
>
0
)
{
if
(
key
.
length
==
1
)
{
redisTemplate
.
delete
(
key
[
0
]);
}
else
{
redisTemplate
.
delete
(
CollectionUtils
.
arrayToList
(
key
));
}
}
}
/**
* 普通缓存获取
* 由于redisDao添加了自动序列化和反序列化工具(FastJson),如果是对象的话get出来的会成为JSONObject对象,无法直接cast。\n
* 推荐使用getString()或getBean()方法来获取结果。
*
* @param key 键
* @return 值
*/
@Deprecated
public
Object
get
(
String
key
)
{
return
key
==
null
?
null
:
redisTemplate
.
opsForValue
().
get
(
key
);
}
/**
* 普通缓存获取字符串
*
* @param key 键
* @return 值
*/
public
String
getString
(
String
key
)
{
return
key
==
null
?
null
:
(
String
)
redisTemplate
.
opsForValue
().
get
(
key
);
}
/**
* 普通缓存获取对象
*
* @param <T>
* @param key 键
* @return 值
*/
public
<
T
>
T
getBean
(
String
key
,
Class
<
T
>
clazz
)
{
JSONObject
obj
=
(
JSONObject
)
redisTemplate
.
opsForValue
().
get
(
key
);
// 反序列化
return
obj
==
null
?
null
:
obj
.
toJavaObject
(
clazz
);
}
/**
* 普通缓存放入
*
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public
boolean
put
(
String
key
,
Object
value
)
{
try
{
redisTemplate
.
opsForValue
().
set
(
key
,
value
);
return
true
;
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
false
;
}
}
/**
* 普通缓存放入并设置时间
*
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public
boolean
put
(
String
key
,
Object
value
,
long
time
)
{
try
{
if
(
time
>
0
)
{
redisTemplate
.
opsForValue
().
set
(
key
,
value
,
time
,
TimeUnit
.
SECONDS
);
}
else
{
put
(
key
,
value
);
}
return
true
;
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
false
;
}
}
/**
* 递增
*
* @param key 键
* @param delta 要增加几(大于0)
* @return
*/
public
long
incr
(
String
key
,
long
delta
)
{
if
(
delta
<
0
)
{
throw
new
RuntimeException
(
"递增因子必须大于0"
);
}
return
redisTemplate
.
opsForValue
().
increment
(
key
,
delta
);
}
/**
* 递减
*
* @param key 键
* @param delta 要减少几(小于0)
* @return
*/
public
long
decr
(
String
key
,
long
delta
)
{
if
(
delta
<
0
)
{
throw
new
RuntimeException
(
"递减因子必须大于0"
);
}
return
redisTemplate
.
opsForValue
().
increment
(
key
,
-
delta
);
}
// ===============================hash=================================
/**
* 获取HashMap中的值
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return 值
*/
public
Object
getHashValue
(
String
key
,
String
item
)
{
return
key
==
null
||
item
==
null
?
null
:
redisTemplate
.
opsForHash
().
get
(
key
,
item
);
}
/**
* 获取HashMap中的字符串
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return 值
*/
public
String
getHashString
(
String
key
,
String
item
)
{
return
key
==
null
||
item
==
null
?
null
:
(
String
)
redisTemplate
.
opsForHash
().
get
(
key
,
item
);
}
/**
* 获取HashMap中的对象
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return 值
*/
public
<
T
>
T
getHashBean
(
String
key
,
String
item
,
Class
<
T
>
clazz
)
{
JSONObject
obj
=
(
JSONObject
)
redisTemplate
.
opsForHash
().
get
(
key
,
item
);
// 反序列化
return
obj
==
null
?
null
:
obj
.
toJavaObject
(
clazz
);
}
/**
* 获取整个HashMap
*
* @param key 键
* @return HashMap
*/
public
Map
getHashMap
(
String
key
)
{
return
key
==
null
?
null
:
redisTemplate
.
opsForHash
().
entries
(
key
);
}
/**
* 获取整个HashMap
*
* @param key 键
* @return HashMap
*/
public
<
T
>
Map
<
String
,
T
>
getHashMap
(
String
key
,
Class
<
T
>
clazz
)
{
Map
map
=
getHashMap
(
key
);
if
(
map
!=
null
&&
!
map
.
isEmpty
())
{
Map
<
String
,
T
>
hashMap
=
new
HashMap
<
String
,
T
>();
for
(
Object
k
:
map
.
keySet
())
{
JSONObject
jsonObject
=
(
JSONObject
)
map
.
get
(
k
);
hashMap
.
put
(
String
.
valueOf
(
k
),
jsonObject
.
toJavaObject
(
clazz
));
}
return
hashMap
;
}
else
{
return
null
;
}
}
/**
* 保存整个HashMap
*
* @param key 键
* @param map 整个HashMap
* @return true 成功 false 失败
*/
public
boolean
putHashMap
(
String
key
,
Map
map
)
{
try
{
redisTemplate
.
opsForHash
().
putAll
(
key
,
map
);
return
true
;
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
false
;
}
}
/**
* 保存整个HashMap并设置有效期
*
* @param key 键
* @param map 整个HashMap
* @param time 时间(秒)
* @return true成功 false失败
*/
public
boolean
putHashMap
(
String
key
,
Map
map
,
long
time
)
{
try
{
redisTemplate
.
opsForHash
().
putAll
(
key
,
map
);
if
(
time
>
0
)
{
expire
(
key
,
time
);
}
return
true
;
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
false
;
}
}
/**
* 向HashMap中放入数据,如果不存在map将创建
*
* @param key 键
* @param item 项
* @param value 值
* @return true 成功 false失败
*/
public
boolean
putHashValue
(
String
key
,
String
item
,
Object
value
)
{
try
{
redisTemplate
.
opsForHash
().
put
(
key
,
item
,
value
);
return
true
;
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
false
;
}
}
/**
* 向HashMap中放入数据并设置有效期,如果不存在map将创建
*
* @param key 键
* @param item 项
* @param value 值
* @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
* @return true 成功 false失败
*/
public
boolean
putHashValue
(
String
key
,
String
item
,
Object
value
,
long
time
)
{
try
{
redisTemplate
.
opsForHash
().
put
(
key
,
item
,
value
);
if
(
time
>
0
)
{
expire
(
key
,
time
);
}
return
true
;
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
false
;
}
}
/**
* 删除HashMap中的值
*
* @param key 键 不能为null
* @param item 项 可以使多个 不能为null
*/
public
void
delHashItem
(
String
key
,
Object
...
item
)
{
redisTemplate
.
opsForHash
().
delete
(
key
,
item
);
}
/**
* 判断HashMap中是否有该项的值
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return true 存在 false不存在
*/
public
boolean
hasHashItem
(
String
key
,
String
item
)
{
return
redisTemplate
.
opsForHash
().
hasKey
(
key
,
item
);
}
/**
* hash递增 如果不存在,就会创建一个 并把新增后的值返回
*
* @param key 键
* @param item 项
* @param by 要增加几(大于0)
* @return
*/
public
double
incrHash
(
String
key
,
String
item
,
double
by
)
{
return
redisTemplate
.
opsForHash
().
increment
(
key
,
item
,
by
);
}
/**
* hash递减
*
* @param key 键
* @param item 项
* @param by 要减少记(小于0)
* @return
*/
public
double
decrHash
(
String
key
,
String
item
,
double
by
)
{
return
redisTemplate
.
opsForHash
().
increment
(
key
,
item
,
-
by
);
}
// ===============================set=================================
/**
* 获取整个Set
*
* @param key 键
* @return
*/
public
Set
getSet
(
String
key
)
{
try
{
return
redisTemplate
.
opsForSet
().
members
(
key
);
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
null
;
}
}
/**
* 查询Set中是否存在指定的value
*
* @param key 键
* @param value 值
* @return true 存在 false不存在
*/
public
boolean
hasSetValue
(
String
key
,
Object
value
)
{
try
{
return
redisTemplate
.
opsForSet
().
isMember
(
key
,
value
);
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
false
;
}
}
/**
* 弹出Set中的一个值
*
* @param key 键
* @param value 值
* @return true 存在 false不存在
*/
public
Object
popSetValue
(
String
key
)
{
try
{
return
redisTemplate
.
opsForSet
().
pop
(
key
);
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
null
;
}
}
/**
* 弹出Set中的一个字符串
*
* @param key 键
* @param value 值
* @return true 存在 false不存在
*/
public
String
popSetString
(
String
key
)
{
try
{
return
(
String
)
redisTemplate
.
opsForSet
().
pop
(
key
);
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
null
;
}
}
/**
* 弹出Set中的一个对象
*
* @param key 键
* @param value 值
* @return true 存在 false不存在
*/
public
<
T
>
T
popSetBean
(
String
key
,
Class
<
T
>
clazz
)
{
try
{
JSONObject
obj
=
(
JSONObject
)
redisTemplate
.
opsForSet
().
pop
(
key
);
// 反序列化
return
obj
==
null
?
null
:
obj
.
toJavaObject
(
clazz
);
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
null
;
}
}
/**
* 将数据放入set缓存
*
* @param key 键
* @param values 值 可以是多个
* @return 成功个数
*/
public
long
addSetValue
(
String
key
,
Object
...
values
)
{
try
{
return
redisTemplate
.
opsForSet
().
add
(
key
,
values
);
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
0
;
}
}
/**
* 将set数据放入缓存,并设置有效期
*
* @param key 键
* @param time 时间(秒)
* @param values 值 可以是多个
* @return 成功个数
*/
public
long
addSetValue
(
String
key
,
long
time
,
Object
...
values
)
{
try
{
Long
count
=
redisTemplate
.
opsForSet
().
add
(
key
,
values
);
if
(
time
>
0
)
expire
(
key
,
time
);
return
count
;
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
0
;
}
}
/**
* 获取set缓存的长度
*
* @param key 键
* @return
*/
public
long
getSetSize
(
String
key
)
{
try
{
return
redisTemplate
.
opsForSet
().
size
(
key
);
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
0
;
}
}
/**
* 移除值为value的
*
* @param key 键
* @param values 值 可以是多个
* @return 移除的个数
*/
public
long
delSetValue
(
String
key
,
Object
...
values
)
{
try
{
Long
count
=
redisTemplate
.
opsForSet
().
remove
(
key
,
values
);
return
count
;
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
0
;
}
}
// ===============================list=================================
/**
* 获取List的全部值
*
* @param key 键
* @return
*/
public
List
getListAll
(
String
key
)
{
return
getList
(
key
,
0
,
-
1
);
}
/**
* 获取List的全部值
*
* @param key 键
* @return
*/
public
<
T
>
List
<
T
>
getListAll
(
String
key
,
Class
<
T
>
clazz
)
{
return
getList
(
key
,
0
,
-
1
,
clazz
);
}
/**
* 获取List中一定的范围
*
* @param key 键
* @param start 开始
* @param end 结束 0 到 -1代表所有值
* @return
*/
public
List
getList
(
String
key
,
long
start
,
long
end
)
{
try
{
return
redisTemplate
.
opsForList
().
range
(
key
,
start
,
end
);
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
null
;
}
}
/**
* 获取List中一定的范围
*
* @param key 键
* @param start 开始
* @param end 结束 0 到 -1代表所有值
* @return
*/
public
<
T
>
List
<
T
>
getList
(
String
key
,
long
start
,
long
end
,
Class
<
T
>
clazz
)
{
try
{
List
<
T
>
list
=
new
ArrayList
<
T
>();
for
(
Object
obj
:
redisTemplate
.
opsForList
().
range
(
key
,
start
,
end
))
{
list
.
add
(((
JSONObject
)
obj
).
toJavaObject
(
clazz
));
}
return
list
;
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
null
;
}
}
/**
* 获取list缓存的长度
*
* @param key 键
* @return
*/
public
long
getListSize
(
String
key
)
{
try
{
return
redisTemplate
.
opsForList
().
size
(
key
);
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
0
;
}
}
/**
* 通过索引 获取list中的值
*
* @param key 键
* @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
* @return
*/
public
Object
getListValue
(
String
key
,
long
index
)
{
try
{
return
redisTemplate
.
opsForList
().
index
(
key
,
index
);
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
null
;
}
}
/**
* 通过索引 获取list中的字符串
*
* @param key 键
* @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
* @return
*/
public
String
getListString
(
String
key
,
long
index
)
{
try
{
return
(
String
)
redisTemplate
.
opsForList
().
index
(
key
,
index
);
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
null
;
}
}
/**
* 通过索引 获取list中的对象
*
* @param key 键
* @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
* @return
*/
public
<
T
>
T
getListBean
(
String
key
,
long
index
,
Class
<
T
>
clazz
)
{
try
{
JSONObject
obj
=
(
JSONObject
)
redisTemplate
.
opsForList
().
index
(
key
,
index
);
// 反序列化
return
obj
==
null
?
null
:
obj
.
toJavaObject
(
clazz
);
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
null
;
}
}
@Deprecated
public
boolean
pushListValue
(
String
key
,
Object
value
)
{
return
rightPushValue
(
key
,
value
);
}
@Deprecated
public
boolean
pushListValue
(
String
key
,
Object
value
,
long
time
)
{
return
rightPushValue
(
key
,
value
,
time
);
}
/**
* 将值放入list队尾
*
* @param key 键
* @param value 值
* @return
*/
public
boolean
rightPushValue
(
String
key
,
Object
value
)
{
try
{
redisTemplate
.
opsForList
().
rightPush
(
key
,
value
);
return
true
;
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
false
;
}
}
/**
* 将值放入list队尾,并设置有效期
*
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public
boolean
rightPushValue
(
String
key
,
Object
value
,
long
time
)
{
try
{
redisTemplate
.
opsForList
().
rightPush
(
key
,
value
);
if
(
time
>
0
)
expire
(
key
,
time
);
return
true
;
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
false
;
}
}
/**
* 将值放入list队首
*
* @param key 键
* @param value 值
* @return
*/
public
boolean
leftPushValue
(
String
key
,
Object
value
)
{
try
{
redisTemplate
.
opsForList
().
leftPush
(
key
,
value
);
return
true
;
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
false
;
}
}
/**
* 将值放入list队首,并设置有效期
*
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public
boolean
leftPushValue
(
String
key
,
Object
value
,
long
time
)
{
try
{
redisTemplate
.
opsForList
().
leftPush
(
key
,
value
);
if
(
time
>
0
)
expire
(
key
,
time
);
return
true
;
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
false
;
}
}
/**
* 将整个List加入list队尾,如果没有则新建list
*
* @param key 键
* @param value 值
* @return
*/
public
boolean
putList
(
String
key
,
List
value
)
{
try
{
redisTemplate
.
opsForList
().
rightPushAll
(
key
,
value
);
return
true
;
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
false
;
}
}
/**
* 将整个List加入list队尾,并设置有效期,如果没有则新建list
*
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public
boolean
putList
(
String
key
,
List
value
,
long
time
)
{
try
{
redisTemplate
.
opsForList
().
rightPushAll
(
key
,
value
);
if
(
time
>
0
)
expire
(
key
,
time
);
return
true
;
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
false
;
}
}
/**
* 根据索引修改list中的某条数据
*
* @param key 键
* @param index 索引
* @param value 值
* @return
*/
public
boolean
updateListValue
(
String
key
,
long
index
,
Object
value
)
{
try
{
redisTemplate
.
opsForList
().
set
(
key
,
index
,
value
);
return
true
;
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
false
;
}
}
/**
* 从队首弹出一个值
* @param key
* @return
*/
public
Object
leftPopValue
(
String
key
)
{
try
{
return
redisTemplate
.
opsForList
().
leftPop
(
key
);
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
null
;
}
}
/**
* 从队首弹出一个对象
* @param key
* @return
*/
public
<
T
>
T
leftPopBean
(
String
key
,
Class
<
T
>
clazz
)
{
try
{
JSONObject
obj
=
(
JSONObject
)
redisTemplate
.
opsForList
().
leftPop
(
key
);
// 反序列化
return
obj
==
null
?
null
:
obj
.
toJavaObject
(
clazz
);
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
null
;
}
}
/**
* 从队尾弹出一个值
* @param key
* @return
*/
public
Object
rightPopValue
(
String
key
)
{
try
{
return
redisTemplate
.
opsForList
().
rightPop
(
key
);
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
null
;
}
}
/**
* 从队尾弹出一个对象
* @param key
* @return
*/
public
<
T
>
T
rightPopBean
(
String
key
,
Class
<
T
>
clazz
)
{
try
{
JSONObject
obj
=
(
JSONObject
)
redisTemplate
.
opsForList
().
rightPop
(
key
);
// 反序列化
return
obj
==
null
?
null
:
obj
.
toJavaObject
(
clazz
);
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
null
;
}
}
/**
* 移除1个value值
*
* @param key 键
* @param value 值
* @return 移除的个数
*/
public
long
removeListValue
(
String
key
,
Object
value
)
{
return
removeListValue
(
key
,
0
,
value
);
}
/**
* 移除N个value值
*
* @param key 键
* @param count 移除多少个
* @param value 值
* @return 移除的个数
*/
public
long
removeListValue
(
String
key
,
long
count
,
Object
value
)
{
try
{
Long
remove
=
redisTemplate
.
opsForList
().
remove
(
key
,
count
,
value
);
return
remove
;
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
0
;
}
}
// ====================== scan ===========================
/**
* 按照正则表达式遍历
*
* @param pattern
* @param consumer 以key为参数迭代操作
*/
public
void
scan
(
String
pattern
,
Consumer
<
byte
[]>
consumer
)
{
redisTemplate
.
execute
((
RedisConnection
connection
)
->
{
try
(
Cursor
<
byte
[]>
cursor
=
connection
.
scan
(
ScanOptions
.
scanOptions
().
count
(
Long
.
MAX_VALUE
).
match
(
pattern
).
build
()))
{
cursor
.
forEachRemaining
(
consumer
);
cursor
.
close
();
return
null
;
}
catch
(
IOException
e
)
{
e
.
printStackTrace
();
throw
new
RuntimeException
(
e
);
}
});
}
}
src/main/java/cn/spatiotemporal/core/utils/BeanMapUtils.java
0 → 100644
View file @
9742023a
package
cn.spatiotemporal.core.utils
;
import
java.util.HashMap
;
import
java.util.Map
;
import
org.springframework.cglib.beans.BeanMap
;
/**
* bean与map互转工具类
* @author marquis
* @since 2022-02-22
*
*/
public
class
BeanMapUtils
{
/**
* bean转map
* @param <T>
* @param bean
* @return
*/
public
static
<
T
>
Map
<
String
,
Object
>
bean2Map
(
T
bean
)
{
if
(
bean
==
null
)
{
return
null
;
}
Map
<
String
,
Object
>
map
=
new
HashMap
<
String
,
Object
>();
BeanMap
beanMap
=
BeanMap
.
create
(
bean
);
map
.
putAll
(
beanMap
);
return
map
;
}
/**
* map转bean
* @param map
* @param clazz
* @return
*/
public
static
<
T
>
T
map2Bean
(
Map
<
String
,
Object
>
map
,
Class
<
T
>
clazz
)
{
if
(
map
==
null
||
map
.
isEmpty
())
{
return
null
;
}
try
{
T
bean
=
clazz
.
newInstance
();
BeanMap
.
create
(
bean
).
putAll
(
map
);
return
bean
;
}
catch
(
InstantiationException
e
)
{
return
null
;
}
catch
(
IllegalAccessException
e
)
{
return
null
;
}
}
}
src/main/java/cn/spatiotemporal/core/utils/DateUtils.java
0 → 100644
View file @
9742023a
package
cn.spatiotemporal.core.utils
;
import
java.time.LocalDate
;
import
java.time.LocalDateTime
;
import
java.time.LocalTime
;
import
java.time.Year
;
import
java.time.YearMonth
;
import
java.time.ZoneId
;
import
java.time.format.DateTimeFormatter
;
import
java.util.Calendar
;
import
java.util.Date
;
import
java.util.Locale
;
/**
* @ClassName: DateUtils
* @Description: ThreadLocal线程安全的DateUtils
* @date 2020年1月9日 上午10:43:42
*
* @author Q.JI
* @version
* @since JDK 1.8
*/
public
class
DateUtils
{
private
DateUtils
()
{
}
private
static
final
ZoneId
ZONE_ID
=
ZoneId
.
systemDefault
();
/**
* LocalDateTime转化为Date
*
* @param localDateTime
* @return
*/
public
static
Date
toDate
(
LocalDateTime
localDateTime
)
{
return
Date
.
from
(
localDateTime
.
atZone
(
ZONE_ID
).
toInstant
());
}
/**
* LocalDateTime转化为Date
*
* @param localDateTime
* @return
*/
public
static
Date
toDate
(
LocalDate
localDate
)
{
return
Date
.
from
(
localDate
.
atStartOfDay
(
ZONE_ID
).
toInstant
());
}
/**
* Date转化为LocalDateTime
*
* @param date
* @return
*/
public
static
LocalDateTime
toLocalDateTime
(
Date
date
)
{
return
LocalDateTime
.
ofInstant
(
date
.
toInstant
(),
ZONE_ID
);
}
/**
* LocalDate转化为LocalDateTime
*
* @param localDate
* @return
*/
public
static
LocalDateTime
toLocalDateTime
(
LocalDate
localDate
)
{
return
LocalDateTime
.
of
(
localDate
,
LocalTime
.
MIN
);
}
/**
* Date转化为LocalDate
*
* @param date
* @return
*/
public
static
LocalDate
toLocalDate
(
Date
date
)
{
return
date
.
toInstant
().
atZone
(
ZONE_ID
).
toLocalDate
();
}
/**
* Date转化为字符串
*
* @param date
* @param formatter
* @return
*/
public
static
String
format
(
Date
date
,
DateFormatter
formatter
)
{
LocalDateTime
localDateTime
=
LocalDateTime
.
ofInstant
(
date
.
toInstant
(),
ZONE_ID
);
return
formatter
.
getDateTimeFormatter
().
format
(
localDateTime
);
}
/**
* Date转化为字符串
*
* @param date
* @param format
* @return
*/
public
static
String
format
(
Date
date
,
String
format
)
{
LocalDateTime
localDateTime
=
LocalDateTime
.
ofInstant
(
date
.
toInstant
(),
ZONE_ID
);
return
DateTimeFormatter
.
ofPattern
(
format
,
Locale
.
CHINA
).
format
(
localDateTime
);
}
/**
* 字符串转化为Date
*
* @param text
* @param formatter
* @return
*/
public
static
Date
parse
(
String
text
,
DateFormatter
formatter
)
{
return
formatter
.
parse
(
text
);
}
/**
*
* @Title: increase
* @Description: 时间相加减运算
* @param date
* @param dateType
* @param amount
* @param formatter
* @return
* String
*/
public
static
String
increase
(
Date
date
,
int
dateType
,
int
amount
,
DateFormatter
formatter
)
{
Date
myDate
=
null
;
if
(
date
!=
null
)
{
Calendar
calendar
=
Calendar
.
getInstance
();
calendar
.
setTime
(
date
);
calendar
.
add
(
dateType
,
amount
);
myDate
=
calendar
.
getTime
();
}
return
format
(
myDate
,
formatter
);
}
/**
*
* @ClassName: DateFormatter
* @Description: 时间格式枚举
* @date 2020年1月17日 下午4:04:01
*
* @author Q.JI
* @version
* @since JDK 1.8
*/
public
static
enum
DateFormatter
{
/**
* 格式yyyy
*/
YEAR_FORMATTER
(
DateTimeFormatter
.
ofPattern
(
"yyyy"
,
Locale
.
CHINA
))
{
@Override
public
Date
parse
(
String
text
)
{
Year
year
=
Year
.
parse
(
text
,
dateTimeFormatter
);
return
Date
.
from
(
year
.
atDay
(
1
).
atStartOfDay
(
ZONE_ID
).
toInstant
());
}
},
/**
* yyyy-MM
*/
YEAR_MONTH_FORMATTER
(
DateTimeFormatter
.
ofPattern
(
"yyyy-MM"
,
Locale
.
CHINA
))
{
@Override
public
Date
parse
(
String
text
)
{
YearMonth
yearMonth
=
YearMonth
.
parse
(
text
,
dateTimeFormatter
);
return
Date
.
from
(
yearMonth
.
atDay
(
1
).
atStartOfDay
(
ZONE_ID
).
toInstant
());
}
},
/**
* 格式yyyy-MM-dd
*/
DATE_FORMATTER
(
DateTimeFormatter
.
ofPattern
(
"yyyy-MM-dd"
,
Locale
.
CHINA
))
{
@Override
public
Date
parse
(
String
text
)
{
LocalDate
localDate
=
LocalDate
.
parse
(
text
,
dateTimeFormatter
);
return
Date
.
from
(
localDate
.
atStartOfDay
(
ZONE_ID
).
toInstant
());
}
},
/**
* 格式yyyy-MM-dd HH:mm:ss
*/
DATE_TIME_FORMATTER
(
DateTimeFormatter
.
ofPattern
(
"yyyy-MM-dd HH:mm:ss"
,
Locale
.
CHINA
))
{
@Override
public
Date
parse
(
String
text
)
{
LocalDateTime
localDateTime
=
LocalDateTime
.
parse
(
text
,
dateTimeFormatter
);
return
Date
.
from
(
localDateTime
.
atZone
(
ZONE_ID
).
toInstant
());
}
},
/**
* 格式yyyy-MM-dd_HH
*/
DATE_HOUR_FORMATTER
(
DateTimeFormatter
.
ofPattern
(
"yyyy-MM-dd_HH"
,
Locale
.
CHINA
))
{
@Override
public
Date
parse
(
String
text
)
{
LocalDate
localDate
=
LocalDate
.
parse
(
text
,
dateTimeFormatter
);
return
Date
.
from
(
localDate
.
atStartOfDay
(
ZONE_ID
).
toInstant
());
}
},
/**
* 格式yyyyMMdd
*/
YYYYMMDD_FORMATTER
(
DateTimeFormatter
.
ofPattern
(
"yyyyMMdd"
,
Locale
.
CHINA
))
{
@Override
public
Date
parse
(
String
text
)
{
LocalDateTime
localDateTime
=
LocalDateTime
.
parse
(
text
,
dateTimeFormatter
);
return
Date
.
from
(
localDateTime
.
atZone
(
ZONE_ID
).
toInstant
());
}
},
/**
* 格式yyyyMMddHHmmss
*/
YYYYMMDDHHMMSS_FORMATTER
(
DateTimeFormatter
.
ofPattern
(
"yyyyMMddHHmmss"
,
Locale
.
CHINA
))
{
@Override
public
Date
parse
(
String
text
)
{
LocalDateTime
localDateTime
=
LocalDateTime
.
parse
(
text
,
dateTimeFormatter
);
return
Date
.
from
(
localDateTime
.
atZone
(
ZONE_ID
).
toInstant
());
}
},
/**
* 格式yyyyMMdd_HHmmss
*/
YYYYMMDD_HHMMSS_FORMATTER
(
DateTimeFormatter
.
ofPattern
(
"yyyyMMdd_HHmmss"
,
Locale
.
CHINA
))
{
@Override
public
Date
parse
(
String
text
)
{
LocalDateTime
localDateTime
=
LocalDateTime
.
parse
(
text
,
dateTimeFormatter
);
return
Date
.
from
(
localDateTime
.
atZone
(
ZONE_ID
).
toInstant
());
}
};
protected
DateTimeFormatter
dateTimeFormatter
;
private
DateFormatter
(
DateTimeFormatter
dateTimeFormatter
)
{
this
.
dateTimeFormatter
=
dateTimeFormatter
;
}
public
DateTimeFormatter
getDateTimeFormatter
()
{
return
dateTimeFormatter
;
}
public
abstract
Date
parse
(
String
text
);
}
}
src/main/java/cn/spatiotemporal/core/utils/FastJsonUtils.java
0 → 100644
View file @
9742023a
package
cn.spatiotemporal.core.utils
;
import
java.lang.reflect.Array
;
import
java.lang.reflect.GenericArrayType
;
import
java.lang.reflect.ParameterizedType
;
import
java.lang.reflect.Type
;
import
java.lang.reflect.TypeVariable
;
import
java.lang.reflect.WildcardType
;
import
java.util.Collection
;
import
java.util.HashMap
;
import
java.util.List
;
import
java.util.Map
;
import
com.alibaba.fastjson.JSON
;
import
com.alibaba.fastjson.JSONArray
;
import
com.alibaba.fastjson.JSONObject
;
import
com.alibaba.fastjson.serializer.SerializerFeature
;
/**
* 使用fastjson进行POJO的快速序列化/反序列化
* @author marquis
*
*/
public
class
FastJsonUtils
{
/**
* POJO序列化为json
* @param pojo
* @return
*/
public
static
String
object2Json
(
Object
pojo
)
{
return
JSON
.
toJSONString
(
pojo
,
SerializerFeature
.
WriteMapNullValue
);
}
/**
* json反序列化为POJO,需要指定类型
* @param json
* @param clazz
* @return
*/
public
static
<
T
>
T
json2Object
(
String
json
,
Class
<
T
>
clazz
)
{
if
(
clazz
.
isArray
())
{
Class
type
=
clazz
.
getComponentType
();
JSONArray
jarray
=
JSON
.
parseArray
(
json
);
return
(
T
)
json2Array
(
jarray
,
type
);
}
else
if
(
clazz
.
isAssignableFrom
(
List
.
class
))
{
JSONArray
jarray
=
JSON
.
parseArray
(
json
);
Class
type
=
(
Class
)
((
ParameterizedType
)
clazz
.
getGenericSuperclass
())
.
getActualTypeArguments
()[
0
];
//得到泛型类型
return
(
T
)
json2List
(
jarray
,
type
);
}
else
if
(
clazz
.
isAssignableFrom
(
Map
.
class
))
{
JSONObject
jobj
=
JSON
.
parseObject
(
json
);
Class
keyType
=
(
Class
)
((
ParameterizedType
)
clazz
.
getGenericSuperclass
())
.
getActualTypeArguments
()[
0
];
//得到key的泛型类型
Class
valueType
=
(
Class
)
((
ParameterizedType
)
clazz
.
getGenericSuperclass
())
.
getActualTypeArguments
()[
1
];
//得到value的泛型类型
return
(
T
)
json2Map
(
jobj
,
keyType
,
valueType
);
}
else
if
(
isSimple
(
clazz
))
{
return
JSON
.
parseObject
(
json
,
clazz
);
}
// 一般POJO
JSONObject
jobj
=
JSON
.
parseObject
(
json
);
return
json2Bean
(
jobj
,
clazz
);
}
/**
* json反序列化为单个POJO
* @param jobj
* @param clazz
* @return
*/
public
static
<
T
>
T
json2Bean
(
JSONObject
jobj
,
Class
<
T
>
clazz
)
{
try
{
return
JSON
.
parseObject
(
jobj
.
toJSONString
(),
clazz
);
// T obj = clazz.newInstance();
// PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(clazz);
// for (PropertyDescriptor pd : pds) {
// String fieldName = pd.getName();
// if (!"class".equals(fieldName) && ! jobj.containsKey(fieldName)) {
// Class type = pd.getPropertyType();
//// if (type) {
////
//// }
// }
//
// }
// return obj;
}
catch
(
Exception
e
)
{
// TODO Auto-generated catch block
e
.
printStackTrace
();
return
null
;
}
}
/**
* json反序列化为指定类型的数组
* @param jarray
* @param clazz
* @return
*/
public
static
<
T
>
T
[]
json2Array
(
JSONArray
jarray
,
Class
<
T
>
clazz
)
{
T
[]
array
=
(
T
[])
Array
.
newInstance
(
clazz
,
jarray
.
size
());
jarray
.
toArray
(
array
);
// for (int i = 0; i < jarray.size(); i++) {
// array[i] = obj2Bean(jarray.getJSONObject(i), clazz);
// }
return
array
;
}
/**
* json反序列化为指定泛型的List
* @param jarray
* @param clazz
* @return
*/
public
static
<
T
>
List
json2List
(
JSONArray
jarray
,
Class
<
T
>
clazz
)
{
return
(
List
)
jarray
.
toJavaList
(
clazz
);
// List list = (List) new ArrayList<T>();
// for (int i = 0; i < jarray.size(); i++) {
// list.add(json2Bean(jarray.getJSONObject(i), clazz));
// }
// return list;
}
public
static
<
K
,
V
>
Map
json2Map
(
JSONObject
jobj
,
Class
<
K
>
keyClazz
,
Class
<
V
>
valueClazz
)
{
Map
map
=
new
HashMap
<
K
,
V
>();
for
(
String
key
:
jobj
.
keySet
())
{
V
value
=
jobj
.
toJavaObject
(
valueClazz
);
map
.
put
(
key
,
value
);
//map.put(key, obj2Bean(jobj.getJSONObject(key), valueClazz));
}
return
map
;
}
/**
* 是否是简单类型
* @param clazz
* @return
*/
public
static
boolean
isSimple
(
Class
clazz
)
{
return
clazz
.
isPrimitive
()
||
clazz
==
java
.
lang
.
String
.
class
||
clazz
==
java
.
util
.
Date
.
class
||
clazz
==
java
.
lang
.
Boolean
.
class
||
clazz
==
java
.
lang
.
Byte
.
class
||
clazz
==
java
.
lang
.
Character
.
class
||
clazz
==
java
.
lang
.
Double
.
class
||
clazz
==
java
.
lang
.
Float
.
class
||
clazz
==
java
.
lang
.
Integer
.
class
||
clazz
==
java
.
lang
.
Long
.
class
||
clazz
==
java
.
lang
.
Short
.
class
;
}
/**
* 是否是复杂类型
* @param clazz
* @return
*/
public
static
boolean
isComplex
(
Class
clazz
)
{
Type
type
=
clazz
;
return
type
instanceof
GenericArrayType
&&
type
instanceof
ParameterizedType
&&
type
instanceof
TypeVariable
&&
type
instanceof
WildcardType
;
}
/**
* 是否是集合类型
* @param clazz
* @return
*/
public
static
boolean
isCollection
(
Class
clazz
)
{
return
clazz
==
Collection
.
class
||
clazz
==
java
.
util
.
List
.
class
||
clazz
==
java
.
util
.
Set
.
class
||
clazz
==
java
.
util
.
Map
.
class
||
clazz
==
java
.
util
.
SortedSet
.
class
||
clazz
==
java
.
util
.
SortedMap
.
class
;
}
}
src/main/java/cn/spatiotemporal/core/utils/Pack.java
0 → 100644
View file @
9742023a
package
cn.spatiotemporal.core.utils
;
import
java.util.List
;
import
java.util.Map
;
/**
* @ClassName: Pack
* @Description: protostuff pack
* @date 2020年1月11日 上午10:44:56
*
* @author Q.JI
* @version
* @since JDK 1.8
*/
public
class
Pack
{
List
<?>
list
;
Map
<?,
?>
map
;
/**
* @return the list
*/
public
List
<?>
getList
()
{
return
list
;
}
/**
* @param list the list to set
*/
public
void
setList
(
List
<?>
list
)
{
this
.
list
=
list
;
}
/**
* @return the map
*/
public
Map
<?,
?>
getMap
()
{
return
map
;
}
/**
* @param map the map to set
*/
public
void
setMap
(
Map
<?,
?>
map
)
{
this
.
map
=
map
;
}
}
src/main/java/cn/spatiotemporal/core/utils/ProtostuffUtils.java
0 → 100644
View file @
9742023a
package
cn.spatiotemporal.core.utils
;
import
io.protostuff.LinkedBuffer
;
import
io.protostuff.ProtostuffIOUtil
;
import
io.protostuff.Schema
;
import
io.protostuff.runtime.RuntimeSchema
;
import
java.util.List
;
import
java.util.Map
;
import
java.util.concurrent.ConcurrentHashMap
;
import
org.objenesis.Objenesis
;
import
org.objenesis.ObjenesisStd
;
/**
* @ClassName: ProtostuffUtils
* @Description: protostuff序列化器工具
* @date 2020年1月11日 上午10:41:59
*
* @author Q.JI
* @version
* @since JDK 1.8
*/
public
class
ProtostuffUtils
{
private
static
ProtostuffUtils
instance
=
null
;
private
static
Map
<
Class
<?>,
Schema
<?>>
cachedSchema
=
new
ConcurrentHashMap
<>();
private
static
Objenesis
objenesis
=
new
ObjenesisStd
(
true
);
private
ProtostuffUtils
()
{}
/**
*
* @Title: getInstance
* @Description: TODO(这里用一句话描述这个方法的作用)
* @return
* ProtostuffSerializer
*/
public
static
ProtostuffUtils
getInstance
()
{
if
(
instance
==
null
)
{
synchronized
(
ProtostuffUtils
.
class
)
{
if
(
instance
==
null
)
{
instance
=
new
ProtostuffUtils
();
}
}
}
return
instance
;
}
/**
*
* @Title: serializer
* @Description: TODO(这里用一句话描述这个方法的作用)
* @param obj
* @return
* byte[]
*/
@SuppressWarnings
(
"unchecked"
)
public
<
T
>
byte
[]
serializer
(
T
obj
)
{
if
(
obj
==
null
){
return
new
byte
[
0
];
}
Class
<
T
>
cls
=
(
Class
<
T
>)
obj
.
getClass
();
LinkedBuffer
buffer
=
LinkedBuffer
.
allocate
(
LinkedBuffer
.
DEFAULT_BUFFER_SIZE
);
try
{
Schema
<
T
>
schema
=
getSchema
(
cls
);
return
ProtostuffIOUtil
.
toByteArray
(
obj
,
schema
,
buffer
);
}
catch
(
Exception
e
)
{
throw
new
IllegalStateException
(
e
.
getMessage
(),
e
);
}
finally
{
buffer
.
clear
();
}
}
/**
*
* @Title: deserializer
* @Description: TODO(这里用一句话描述这个方法的作用)
* @param data
* @param cls
* @return
* T
*/
public
<
T
>
T
deserializer
(
byte
[]
data
,
Class
<
T
>
cls
)
{
if
(
isEmpty
(
data
)){
return
null
;
}
try
{
T
message
=
(
T
)
objenesis
.
newInstance
(
cls
);
Schema
<
T
>
schema
=
getSchema
(
cls
);
ProtostuffIOUtil
.
mergeFrom
(
data
,
message
,
schema
);
return
message
;
}
catch
(
Exception
e
)
{
throw
new
IllegalStateException
(
e
.
getMessage
(),
e
);
}
}
/**
*
* @Title: serializerList
* @Description: TODO(这里用一句话描述这个方法的作用)
* @param list
* @return
* byte[]
*/
public
<
T
>
byte
[]
serializerList
(
List
<
T
>
list
)
{
if
(
null
==
list
||
list
.
isEmpty
())
{
return
new
byte
[
0
];
}
Pack
pack
=
new
Pack
();
pack
.
setList
(
list
);
return
serializer
(
pack
);
}
/**
*
* @Title: deserializerList
* @Description: TODO(这里用一句话描述这个方法的作用)
* @param byteArr
* @return
* List<?>
*/
public
<
T
>
List
<?>
deserializerList
(
byte
[]
byteArr
)
{
if
(
isEmpty
(
byteArr
))
{
return
null
;
}
Pack
pack
=
deserializer
(
byteArr
,
Pack
.
class
);
if
(
null
!=
pack
){
return
pack
.
getList
();
}
else
{
return
null
;
}
}
/**
*
* @Title: serializerMap
* @Description: TODO(这里用一句话描述这个方法的作用)
* @param map
* @return
* byte[]
*/
public
<
T
>
byte
[]
serializerMap
(
Map
<?,
?>
map
)
{
if
(
null
==
map
||
map
.
size
()
<
1
)
{
return
new
byte
[
0
];
}
Pack
pack
=
new
Pack
();
pack
.
setMap
(
map
);
return
serializer
(
pack
);
}
/**
*
* @Title: deserializerMap
* @Description: TODO(这里用一句话描述这个方法的作用)
* @param byteArr
* @return
* Map<?,?>
*/
public
<
T
>
Map
<?,
?>
deserializerMap
(
byte
[]
byteArr
)
{
if
(
isEmpty
(
byteArr
))
{
return
null
;
}
Pack
pack
=
deserializer
(
byteArr
,
Pack
.
class
);
if
(
null
!=
pack
){
return
pack
.
getMap
();
}
else
{
return
null
;
}
}
@SuppressWarnings
(
"unchecked"
)
private
<
T
>
Schema
<
T
>
getSchema
(
Class
<
T
>
cls
)
{
Schema
<
T
>
schema
=
(
Schema
<
T
>)
cachedSchema
.
get
(
cls
);
if
(
schema
==
null
)
{
schema
=
RuntimeSchema
.
createFrom
(
cls
);
if
(
schema
!=
null
)
{
cachedSchema
.
put
(
cls
,
schema
);
}
}
return
schema
;
}
private
boolean
isEmpty
(
byte
[]
data
)
{
return
(
data
==
null
||
data
.
length
==
0
);
}
}
src/main/java/cn/spatiotemporal/core/utils/SpringBeanUtils.java
0 → 100644
View file @
9742023a
package
cn.spatiotemporal.core.utils
;
import
org.springframework.beans.BeansException
;
import
org.springframework.context.ApplicationContext
;
import
org.springframework.context.ApplicationContextAware
;
import
org.springframework.context.annotation.Configuration
;
import
org.springframework.stereotype.Component
;
@Component
@Configuration
public
class
SpringBeanUtils
implements
ApplicationContextAware
{
private
static
ApplicationContext
applicationContext
;
@Override
public
void
setApplicationContext
(
ApplicationContext
applicationContext
)
throws
BeansException
{
if
(
SpringBeanUtils
.
applicationContext
==
null
)
SpringBeanUtils
.
applicationContext
=
applicationContext
;
}
public
static
void
putApplicationContext
(
ApplicationContext
applicationContext
)
{
SpringBeanUtils
.
applicationContext
=
applicationContext
;
}
public
static
ApplicationContext
getApplicationContext
()
{
return
applicationContext
;
}
public
static
<
T
>
T
getBean
(
Class
<
T
>
cls
)
{
if
(
applicationContext
==
null
)
{
throw
new
RuntimeException
(
"applicationContext注入失败"
);
}
return
applicationContext
.
getBean
(
cls
);
}
public
static
Object
getBean
(
String
name
)
{
if
(
applicationContext
==
null
)
{
throw
new
RuntimeException
(
"applicationContext注入失败"
);
}
return
applicationContext
.
getBean
(
name
);
}
public
static
<
T
>
T
getBean
(
String
name
,
Class
<
T
>
cls
)
{
if
(
applicationContext
==
null
)
{
throw
new
RuntimeException
(
"applicationContext注入失败"
);
}
return
applicationContext
.
getBean
(
name
,
cls
);
}
}
src/main/java/cn/spatiotemporal/core/utils/StringUtils.java
0 → 100644
View file @
9742023a
package
cn.spatiotemporal.core.utils
;
import
java.io.UnsupportedEncodingException
;
/**
* @ClassName: StringUtils
* @Description: TODO(这里用一句话描述这个类的作用)
* @date 2020年1月6日 下午4:40:40
*
* @author Q.JI
* @version
* @since JDK 1.8
*/
public
class
StringUtils
extends
org
.
apache
.
commons
.
lang
.
StringUtils
{
private
static
final
char
SEPARATOR
=
'_'
;
private
static
final
String
CHARSET_NAME
=
"UTF-8"
;
/**
* 转换为字节数组
* @param str
* @return
*/
public
static
String
toString
(
byte
[]
bytes
){
try
{
return
new
String
(
bytes
,
CHARSET_NAME
);
}
catch
(
UnsupportedEncodingException
e
)
{
return
EMPTY
;
}
}
/**
* 如果对象为空,则使用defaultVal值
* see: ObjectUtils.toString(obj, defaultVal)
* @param obj
* @param defaultVal
* @return
*/
public
static
String
toString
(
final
Object
obj
,
final
String
defaultVal
)
{
return
obj
==
null
?
defaultVal
:
obj
.
toString
();
}
/**
*
* @Title: nvl
* @Description: change string to "" if it is null
* @param sInput
* @return
* String
*/
public
static
String
nvl
(
String
sInput
)
{
if
(
sInput
==
null
)
{
return
""
;
}
else
{
return
sInput
;
}
}
}
Prev
1
2
3
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