Skip to content
Toggle navigation
Projects
Groups
Snippets
Help
platform
/
platform-process-server
This project
Loading...
Sign in
Toggle navigation
Go to a project
Project
Repository
Issues
0
Merge Requests
0
Pipelines
Wiki
Settings
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Commit a0fd5f51
authored
Sep 21, 2023
by
tiger
Browse Files
Options
Browse Files
Tag
Download
Email Patches
Plain Diff
快照参数标记
1 parent
d7a5ea54
Show whitespace changes
Inline
Side-by-side
Showing
9 changed files
with
518 additions
and
20 deletions
.gitignore
platform-process-api/src/main/java/cn/com/glsx/process/modules/mapper/SopInstMapper.java
platform-process/src/main/java/cn/com/glsx/process/job/xxljob/impl/SopInstExecuteJobHandler.java
platform-process/src/main/java/cn/com/glsx/process/job/xxljob/impl/SopInstNodeExecuteJobHandler.java
platform-process/src/main/java/cn/com/glsx/process/modules/service/SopService.java
platform-process/src/main/java/cn/com/glsx/process/modules/sop/execute/RunResult.java
platform-process/src/main/java/cn/com/glsx/process/modules/sop/execute/SnapshotStruct.java
platform-process/src/main/java/cn/com/glsx/process/modules/sop/execute/SopNodeExecutor.java
platform-process/src/main/java/cn/com/glsx/process/util/JacksonUtils.java
.gitignore
View file @
a0fd5f5
...
@@ -9,3 +9,4 @@
...
@@ -9,3 +9,4 @@
*.container
*.container
*.name
*.name
/platform-process-api/*.factorypath
/platform-process-api/*.factorypath
/platform-process/*.path_IS_UNDEFINED
platform-process-api/src/main/java/cn/com/glsx/process/modules/mapper/SopInstMapper.java
View file @
a0fd5f5
platform-process/src/main/java/cn/com/glsx/process/job/xxljob/impl/SopInstExecuteJobHandler.java
View file @
a0fd5f5
...
@@ -31,7 +31,7 @@ public class SopInstExecuteJobHandler {
...
@@ -31,7 +31,7 @@ public class SopInstExecuteJobHandler {
SopStruct
sop
=
sopService
.
loadSop
(
instId
);
SopStruct
sop
=
sopService
.
loadSop
(
instId
);
// 创建执行批次
// 创建执行批次
SopInstBatch
batch
=
sopService
.
createBatch
(
instId
);
SopInstBatch
batch
=
sopService
.
createBatch
(
sop
.
getInst
()
);
sop
.
setBatch
(
batch
);
sop
.
setBatch
(
batch
);
sop
.
getInst
().
setBatchNo
(
batch
.
getBatchNo
());
sop
.
getInst
().
setBatchNo
(
batch
.
getBatchNo
());
...
...
platform-process/src/main/java/cn/com/glsx/process/job/xxljob/impl/SopInstNodeExecuteJobHandler.java
View file @
a0fd5f5
...
@@ -12,6 +12,7 @@ import com.xxl.job.core.handler.annotation.XxlJob;
...
@@ -12,6 +12,7 @@ import com.xxl.job.core.handler.annotation.XxlJob;
import
cn.com.glsx.process.job.xxljob.core.SopXxlJobUtil
;
import
cn.com.glsx.process.job.xxljob.core.SopXxlJobUtil
;
import
cn.com.glsx.process.job.xxljob.param.SopInstNodeParam
;
import
cn.com.glsx.process.job.xxljob.param.SopInstNodeParam
;
import
cn.com.glsx.process.modules.entity.SopInstBatch
;
import
cn.com.glsx.process.modules.entity.SopInstNode
;
import
cn.com.glsx.process.modules.entity.SopInstNode
;
import
cn.com.glsx.process.modules.entity.SopInstNodeBatch
;
import
cn.com.glsx.process.modules.entity.SopInstNodeBatch
;
import
cn.com.glsx.process.modules.model.SopStruct
;
import
cn.com.glsx.process.modules.model.SopStruct
;
...
@@ -109,6 +110,7 @@ public class SopInstNodeExecuteJobHandler {
...
@@ -109,6 +110,7 @@ public class SopInstNodeExecuteJobHandler {
// 重新加载sop
// 重新加载sop
sop
=
reloadAndCreateBatch
(
sop
,
node
);
sop
=
reloadAndCreateBatch
(
sop
,
node
);
// 预备执行参数
SnapshotStruct
snapshotStruct
=
instance
.
prepare
(
sop
,
node
);
SnapshotStruct
snapshotStruct
=
instance
.
prepare
(
sop
,
node
);
// 执行sop节点
// 执行sop节点
...
@@ -137,8 +139,15 @@ public class SopInstNodeExecuteJobHandler {
...
@@ -137,8 +139,15 @@ public class SopInstNodeExecuteJobHandler {
}
}
private
void
updateBatch
(
SopStruct
sop
,
SopInstNode
node
,
SnapshotStruct
result
)
{
private
void
updateBatch
(
SopStruct
sop
,
SopInstNode
node
,
SnapshotStruct
result
)
{
// TODO 这里需要考虑合并结果
SopInstBatch
batch
=
sop
.
getBatch
();
batch
.
setSnapshot
(
JSONUtil
.
toJsonStr
(
result
));
sop
.
getInst
().
setInstSnapshot
(
batch
.
getSnapshot
());
sopService
.
updateInstBatch
(
sop
.
getInst
(),
batch
);
SopInstNodeBatch
nodeBatch
=
sop
.
getNodeBatch
();
SopInstNodeBatch
nodeBatch
=
sop
.
getNodeBatch
();
nodeBatch
.
setSnapshot
(
JSONUtil
.
toJsonStr
(
result
));
// TODO 这里需要考虑合并结果
nodeBatch
.
setSnapshot
(
JSONUtil
.
toJsonStr
(
result
));
nodeBatch
.
setUpdateTime
(
new
Date
());
nodeBatch
.
setUpdateTime
(
new
Date
());
sopService
.
updateInstNodeBatch
(
nodeBatch
);
sopService
.
updateInstNodeBatch
(
nodeBatch
);
}
}
...
@@ -146,7 +155,7 @@ public class SopInstNodeExecuteJobHandler {
...
@@ -146,7 +155,7 @@ public class SopInstNodeExecuteJobHandler {
private
SopStruct
reloadAndCreateBatch
(
SopStruct
sop
,
SopInstNode
node
)
{
private
SopStruct
reloadAndCreateBatch
(
SopStruct
sop
,
SopInstNode
node
)
{
sop
=
sopService
.
loadSop
(
sop
.
getInst
().
getInstId
());
sop
=
sopService
.
loadSop
(
sop
.
getInst
().
getInstId
());
// 创建节点执行批次
// 创建节点执行批次
SopInstNodeBatch
curBatch
=
sopService
.
createNodeBatch
(
sop
.
getInst
()
.
getBatchNo
()
,
node
.
getInstNodeId
());
SopInstNodeBatch
curBatch
=
sopService
.
createNodeBatch
(
sop
.
getInst
(),
node
.
getInstNodeId
());
sop
.
setNodeBatch
(
curBatch
);
sop
.
setNodeBatch
(
curBatch
);
return
sop
;
return
sop
;
}
}
...
...
platform-process/src/main/java/cn/com/glsx/process/modules/service/SopService.java
View file @
a0fd5f5
...
@@ -197,28 +197,29 @@ public class SopService {
...
@@ -197,28 +197,29 @@ public class SopService {
// }
// }
}
}
public
SopInstBatch
createBatch
(
S
tring
instId
)
{
public
SopInstBatch
createBatch
(
S
opInst
sopInst
)
{
SopInstBatch
batch
=
new
SopInstBatch
();
SopInstBatch
batch
=
new
SopInstBatch
();
batch
.
setBatchNo
(
SnowFlake
.
nextSerialNumber
());
batch
.
setBatchNo
(
SnowFlake
.
nextSerialNumber
());
batch
.
setCreateTime
(
new
Date
());
batch
.
setCreateTime
(
new
Date
());
batch
.
setUpdateTime
(
new
Date
());
batch
.
setUpdateTime
(
new
Date
());
batch
.
setInstId
(
instId
);
batch
.
setInstId
(
sopInst
.
getInstId
()
);
batch
.
setSnapshot
(
""
);
batch
.
setSnapshot
(
sopInst
.
getInstSnapshot
()
);
instBatchMapper
.
insert
(
batch
);
instBatchMapper
.
insert
(
batch
);
instMapper
.
updateInstBatchNo
(
instId
,
batch
.
getBatchNo
());
instMapper
.
updateInstBatchNo
(
sopInst
.
getInstId
(),
batch
.
getBatchNo
());
return
batch
;
return
batch
;
}
}
public
SopInstNodeBatch
createNodeBatch
(
S
tring
batchNo
,
Integer
instNodeId
)
{
public
SopInstNodeBatch
createNodeBatch
(
S
opInst
sopInst
,
Integer
instNodeId
)
{
SopInstNodeBatch
curBatch
=
new
SopInstNodeBatch
();
SopInstNodeBatch
curBatch
=
new
SopInstNodeBatch
();
curBatch
.
setBatchNo
(
batchNo
);
curBatch
.
setBatchNo
(
sopInst
.
getBatchNo
()
);
curBatch
.
setNodeBatchNo
(
SnowFlake
.
nextSerialNumber
());
curBatch
.
setNodeBatchNo
(
SnowFlake
.
nextSerialNumber
());
curBatch
.
setCreateTime
(
new
Date
());
curBatch
.
setCreateTime
(
new
Date
());
curBatch
.
setUpdateTime
(
new
Date
());
curBatch
.
setUpdateTime
(
new
Date
());
curBatch
.
setInstNodeId
(
instNodeId
);
curBatch
.
setInstNodeId
(
instNodeId
);
curBatch
.
setSnapshot
(
""
);
curBatch
.
setSnapshot
(
sopInst
.
getInstSnapshot
()
);
instNodeBatchMapper
.
insert
(
curBatch
);
instNodeBatchMapper
.
insert
(
curBatch
);
...
@@ -229,4 +230,10 @@ public class SopService {
...
@@ -229,4 +230,10 @@ public class SopService {
instNodeBatchMapper
.
updateByPrimaryKey
(
nodeBatch
);
instNodeBatchMapper
.
updateByPrimaryKey
(
nodeBatch
);
}
}
public
void
updateInstBatch
(
SopInst
sopInst
,
SopInstBatch
batch
)
{
instMapper
.
updateByPrimaryKey
(
sopInst
);
instBatchMapper
.
updateByPrimaryKey
(
batch
);
}
}
}
platform-process/src/main/java/cn/com/glsx/process/modules/sop/execute/RunResult.java
View file @
a0fd5f5
...
@@ -17,6 +17,11 @@
...
@@ -17,6 +17,11 @@
package
cn
.
com
.
glsx
.
process
.
modules
.
sop
.
execute
;
package
cn
.
com
.
glsx
.
process
.
modules
.
sop
.
execute
;
import
java.io.Serializable
;
import
java.io.Serializable
;
import
java.util.Map
;
import
com.google.common.collect.Maps
;
import
lombok.Data
;
/**
/**
* 单节点单次执行结果
* 单节点单次执行结果
...
@@ -24,8 +29,12 @@ import java.io.Serializable;
...
@@ -24,8 +29,12 @@ import java.io.Serializable;
* @author kome
* @author kome
* @date 2023年9月20日 下午6:02:22
* @date 2023年9月20日 下午6:02:22
*/
*/
@Data
public
class
RunResult
implements
Serializable
{
public
class
RunResult
implements
Serializable
{
private
static
final
long
serialVersionUID
=
-
1321328867544959522L
;
private
static
final
long
serialVersionUID
=
-
1321328867544959522L
;
private
String
key
;
private
Map
<
String
,
Object
>
map
=
Maps
.
newHashMap
();
}
}
platform-process/src/main/java/cn/com/glsx/process/modules/sop/execute/SnapshotStruct.java
View file @
a0fd5f5
...
@@ -20,15 +20,15 @@ public class SnapshotStruct implements Serializable, Cloneable {
...
@@ -20,15 +20,15 @@ public class SnapshotStruct implements Serializable, Cloneable {
private
static
final
long
serialVersionUID
=
-
1413400196758036960L
;
private
static
final
long
serialVersionUID
=
-
1413400196758036960L
;
//
//
/**
/**
*
各节点的
初始化参数表
*
Sop批次
初始化参数表
*/
*/
private
Map
<
String
,
Object
>
param
Map
=
Maps
.
newHashMap
();
private
Map
<
String
,
Object
>
init
Map
=
Maps
.
newHashMap
();
/**
/**
* 各节点的输入参数表
*
Sop
各节点的输入参数表
*/
*/
private
Map
<
String
,
Object
>
execute
Map
=
Maps
.
newHashMap
();
private
Map
<
String
,
Object
>
param
Map
=
Maps
.
newHashMap
();
/**
/**
* 各节点的执行结果表
*
Sop
各节点的执行结果表
*/
*/
private
Map
<
String
,
Object
>
resultMap
=
Maps
.
newHashMap
();
private
Map
<
String
,
Object
>
resultMap
=
Maps
.
newHashMap
();
...
...
platform-process/src/main/java/cn/com/glsx/process/modules/sop/execute/SopNodeExecutor.java
View file @
a0fd5f5
...
@@ -16,14 +16,20 @@
...
@@ -16,14 +16,20 @@
package
cn
.
com
.
glsx
.
process
.
modules
.
sop
.
execute
;
package
cn
.
com
.
glsx
.
process
.
modules
.
sop
.
execute
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
cn.com.glsx.process.modules.entity.SopInstNode
;
import
cn.com.glsx.process.modules.entity.SopInstNode
;
import
cn.com.glsx.process.modules.model.SopStruct
;
import
cn.com.glsx.process.modules.model.SopStruct
;
import
cn.com.glsx.process.util.JacksonUtils
;
import
cn.hutool.core.util.StrUtil
;
import
cn.hutool.core.util.StrUtil
;
import
cn.hutool.json.JSONObject
;
import
cn.hutool.json.JSONObject
;
import
cn.hutool.json.JSONUtil
;
import
cn.hutool.json.JSONUtil
;
public
interface
SopNodeExecutor
{
public
interface
SopNodeExecutor
{
Logger
log
=
LoggerFactory
.
getLogger
(
SopNodeExecutor
.
class
);
/**
/**
* 通过sop模板+sop实例输入参数+sop跑批快照,获得本节点执行的输入参数
* 通过sop模板+sop实例输入参数+sop跑批快照,获得本节点执行的输入参数
*
*
...
@@ -32,17 +38,25 @@ public interface SopNodeExecutor {
...
@@ -32,17 +38,25 @@ public interface SopNodeExecutor {
*/
*/
default
SnapshotStruct
prepare
(
SopStruct
sop
,
SopInstNode
node
)
{
default
SnapshotStruct
prepare
(
SopStruct
sop
,
SopInstNode
node
)
{
SnapshotStruct
es
=
new
SnapshotStruct
();
SnapshotStruct
es
=
new
SnapshotStruct
();
if
(
StrUtil
.
length
(
sop
.
getBatch
().
getSnapshot
())
>
3
)
{
// 继承参数
es
=
JacksonUtils
.
fromJson
(
sop
.
getBatch
().
getSnapshot
(),
SnapshotStruct
.
class
);
}
else
{
// 启动参数
// 启动参数
if
(
StrUtil
.
isNotEmpty
(
sop
.
getInst
().
getInstParam
()))
{
if
(
StrUtil
.
isNotEmpty
(
sop
.
getInst
().
getInstParam
()))
{
JSONObject
paramObj
=
JSONUtil
.
parseObj
(
sop
.
getInst
().
getInstParam
());
JSONObject
paramObj
=
JSONUtil
.
parseObj
(
sop
.
getInst
().
getInstParam
());
es
.
getParamMap
().
putAll
(
paramObj
);
es
.
getInitMap
().
putAll
(
paramObj
);
}
}
}
// 当前节点需要的参数
// 当前节点需要的参数
if
(
StrUtil
.
isNotEmpty
(
node
.
getNodeParam
()))
{
if
(
StrUtil
.
isNotEmpty
(
node
.
getNodeParam
()))
{
if
(
StrUtil
.
isNotEmpty
(
node
.
getNodeKey
()))
{
JSONObject
nodeParamObj
=
JSONUtil
.
parseObj
(
node
.
getNodeParam
());
JSONObject
nodeParamObj
=
JSONUtil
.
parseObj
(
node
.
getNodeParam
());
es
.
getExecuteMap
().
putAll
(
nodeParamObj
);
es
.
getParamMap
().
put
(
node
.
getNodeKey
(),
nodeParamObj
);
}
else
{
log
.
warn
(
"【{}】nodeKey 为空!!!"
,
node
.
getInstId
()
+
"-"
+
node
.
getNodeId
());
}
}
}
return
es
;
return
es
;
...
@@ -71,13 +85,13 @@ public interface SopNodeExecutor {
...
@@ -71,13 +85,13 @@ public interface SopNodeExecutor {
// 启动参数
// 启动参数
if
(
StrUtil
.
isNotEmpty
(
sop
.
getInst
().
getInstParam
()))
{
if
(
StrUtil
.
isNotEmpty
(
sop
.
getInst
().
getInstParam
()))
{
JSONObject
paramObj
=
JSONUtil
.
parseObj
(
sop
.
getInst
().
getInstParam
());
JSONObject
paramObj
=
JSONUtil
.
parseObj
(
sop
.
getInst
().
getInstParam
());
es
.
get
Param
Map
().
putAll
(
paramObj
);
es
.
get
Init
Map
().
putAll
(
paramObj
);
}
}
// 当前节点需要的参数
// 当前节点需要的参数
if
(
StrUtil
.
isNotEmpty
(
node
.
getNodeParam
()))
{
if
(
StrUtil
.
isNotEmpty
(
node
.
getNodeParam
()))
{
JSONObject
nodeParamObj
=
JSONUtil
.
parseObj
(
node
.
getNodeParam
());
JSONObject
nodeParamObj
=
JSONUtil
.
parseObj
(
node
.
getNodeParam
());
es
.
get
Execute
Map
().
putAll
(
nodeParamObj
);
es
.
get
Param
Map
().
putAll
(
nodeParamObj
);
}
}
return
es
;
return
es
;
...
...
platform-process/src/main/java/cn/com/glsx/process/util/JacksonUtils.java
0 → 100644
View file @
a0fd5f5
package
cn
.
com
.
glsx
.
process
.
util
;
import
java.io.IOException
;
import
java.lang.reflect.Type
;
import
java.text.SimpleDateFormat
;
import
java.time.LocalDateTime
;
import
java.time.ZonedDateTime
;
import
java.time.format.DateTimeFormatter
;
import
java.util.ArrayList
;
import
java.util.Date
;
import
java.util.List
;
import
org.apache.commons.lang3.StringUtils
;
import
com.fasterxml.jackson.annotation.JsonInclude
;
import
com.fasterxml.jackson.core.JsonGenerator
;
import
com.fasterxml.jackson.core.JsonParser
;
import
com.fasterxml.jackson.core.JsonProcessingException
;
import
com.fasterxml.jackson.core.type.TypeReference
;
import
com.fasterxml.jackson.databind.BeanProperty
;
import
com.fasterxml.jackson.databind.DeserializationContext
;
import
com.fasterxml.jackson.databind.DeserializationFeature
;
import
com.fasterxml.jackson.databind.JavaType
;
import
com.fasterxml.jackson.databind.JsonDeserializer
;
import
com.fasterxml.jackson.databind.JsonMappingException
;
import
com.fasterxml.jackson.databind.JsonSerializer
;
import
com.fasterxml.jackson.databind.ObjectMapper
;
import
com.fasterxml.jackson.databind.PropertyNamingStrategy
;
import
com.fasterxml.jackson.databind.PropertyNamingStrategy.SnakeCaseStrategy
;
import
com.fasterxml.jackson.databind.SerializationFeature
;
import
com.fasterxml.jackson.databind.SerializerProvider
;
import
com.fasterxml.jackson.databind.cfg.MapperConfig
;
import
com.fasterxml.jackson.databind.deser.ContextualDeserializer
;
import
com.fasterxml.jackson.databind.deser.std.StdDeserializer
;
import
com.fasterxml.jackson.databind.introspect.AnnotatedField
;
import
com.fasterxml.jackson.databind.introspect.AnnotatedMethod
;
import
com.fasterxml.jackson.databind.module.SimpleModule
;
import
com.fasterxml.jackson.databind.ser.std.StdSerializer
;
import
com.fasterxml.jackson.databind.util.JSONPObject
;
import
cn.hutool.core.codec.Base64
;
import
cn.hutool.core.date.DatePattern
;
import
lombok.val
;
import
lombok.extern.slf4j.Slf4j
;
import
sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl
;
@SuppressWarnings
(
"restriction"
)
public
class
JacksonUtils
{
// 转换全部字段
public
final
static
JsonMapper
normalMapper
=
JsonMapper
.
buildNormalBinder
();
// 不转换默认值的字段
public
final
static
JsonMapper
nodefaultMapper
=
JsonMapper
.
buildNonDefaultBinder
();
// 不转换空字段
public
final
static
JsonMapper
noemptyMapper
=
JsonMapper
.
buildNonEmptyBinder
();
// 不转换null字段
public
final
static
JsonMapper
nonullMapper
=
JsonMapper
.
buildNonNullBinder
();
// 不转换null字段
public
final
static
JsonMapper
null2emptyMapper
=
JsonMapper
.
buildNull2EmptyBinder
();
// 首字母大写
public
final
static
JsonMapper
downCaseMapper
=
JsonMapper
.
buildDownCaseBinder
();
// 下划线
public
final
static
JsonMapper
snakeMapper
=
JsonMapper
.
buildSnakeCaseBinder
();
// // 下划线+base64 decode
// public final static JsonMapper wxMapper = JsonMapper.buildWxCaseBinder();
public
static
<
T
>
String
toJson
(
T
t
)
{
return
normalMapper
.
toJson
(
t
);
}
public
static
<
T
>
T
fromJson
(
String
json
,
Class
<
T
>
clazz
)
{
return
normalMapper
.
fromJson
(
json
,
clazz
);
}
public
static
<
T
,
S
>
T
fromJson
(
String
json
,
Class
<
T
>
owner
,
Class
<
S
>
subClass
)
{
return
normalMapper
.
fromJson
(
json
,
owner
,
subClass
);
}
/**
* <code>
* List<String> list = JsonUtil.fromJson(json, new TypeReference<ArrayList<String>>() {});
* </code>
*
* @param <T>
* @param json
* @param t
* @return
*/
public
static
<
T
>
T
fromJson
(
String
json
,
TypeReference
<
T
>
t
)
{
return
normalMapper
.
fromJson
(
json
,
t
);
}
public
static
<
T
>
T
convertJsonClazz
(
Object
object
,
Class
<
T
>
clazz
)
{
return
normalMapper
.
convertJsonClazz
(
object
,
clazz
);
}
/**
* 构造函数
*/
private
JacksonUtils
()
{
}
@Slf4j
public
static
class
JsonMapper
{
private
ObjectMapper
mapper
;
protected
JsonMapper
()
{
this
(
JsonInclude
.
Include
.
ALWAYS
);
}
public
JsonMapper
(
JsonInclude
.
Include
include
)
{
mapper
=
new
ObjectMapper
();
// 设置输出时包含属性的风格
mapper
.
setSerializationInclusion
(
include
);
// 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
mapper
.
disable
(
DeserializationFeature
.
FAIL_ON_UNKNOWN_PROPERTIES
);
// 空的bean不解析
mapper
.
disable
(
SerializationFeature
.
FAIL_ON_EMPTY_BEANS
);
// 设置日期格式
mapper
.
setDateFormat
(
new
SimpleDateFormat
(
"yyyy-MM-dd HH:mm:ss"
));
//
mapper
.
registerModule
(
simpleModule
());
}
/** 创建输出全部属性到Json字符串的Binder. */
public
static
JsonMapper
buildNormalBinder
()
{
return
new
JsonMapper
(
JsonInclude
.
Include
.
ALWAYS
);
}
/** 创建只输出非空属性到Json字符串的Binder. */
public
static
JsonMapper
buildNonNullBinder
()
{
return
new
JsonMapper
(
JsonInclude
.
Include
.
NON_NULL
);
}
public
static
JsonMapper
buildNull2EmptyBinder
()
{
JsonMapper
m
=
new
JsonMapper
(
JsonInclude
.
Include
.
ALWAYS
);
m
.
mapper
.
getSerializerProvider
().
setNullValueSerializer
(
new
JsonSerializer
<
Object
>()
{
@Override
public
void
serialize
(
Object
value
,
JsonGenerator
jgen
,
SerializerProvider
provider
)
throws
IOException
,
JsonProcessingException
{
jgen
.
writeString
(
""
);
}
});
return
m
;
}
/** 创建只输出初始值被改变的属性到Json字符串的Binder. */
public
static
JsonMapper
buildNonDefaultBinder
()
{
return
new
JsonMapper
(
JsonInclude
.
Include
.
NON_DEFAULT
);
}
/** 创建只输出非Null且非Empty(如List.isEmpty)的属性到Json字符串的Binder */
public
static
JsonMapper
buildNonEmptyBinder
()
{
return
new
JsonMapper
(
JsonInclude
.
Include
.
NON_EMPTY
);
}
/** 首字母大写 */
public
static
JsonMapper
buildDownCaseBinder
()
{
// 首字母默认小写
JsonMapper
mapper
=
new
JsonMapper
(
JsonInclude
.
Include
.
ALWAYS
);
mapper
.
mapper
.
setPropertyNamingStrategy
(
new
JacksonInitialDownCaseStrategy
());
return
mapper
;
}
/** 下划线连接 */
public
static
JsonMapper
buildSnakeCaseBinder
()
{
// 下划线
JsonMapper
mapper
=
new
JsonMapper
(
JsonInclude
.
Include
.
NON_NULL
);
mapper
.
mapper
.
setPropertyNamingStrategy
(
new
SnakeCaseStrategy
());
return
mapper
;
}
// /** 下划线连接+Base64 */
// public static JsonMapper buildWxCaseBinder() {
// // 下划线
// JsonMapper mapper = new JsonMapper(JsonInclude.Include.ALWAYS);
// mapper.mapper.setPropertyNamingStrategy(new SnakeCaseStrategy());
// mapper.mapper.setBase64Variant(Base64Variants.MIME_NO_LINEFEEDS);
// return mapper;
// }
/**
* 反序列化POJO或简单Collection如List<String>. 如果JSON字符串为null或"null"字符串,返回null. 如果JSON字符串为"[]",返回空集合.
* 如需读取集合如List/Map,且不是List<String>这种简单类型时,使用後面的函數.
*/
public
<
T
>
T
fromJson
(
String
jsonString
,
Class
<
T
>
clazz
)
{
if
(
StringUtils
.
isEmpty
(
jsonString
))
{
return
null
;
}
try
{
return
mapper
.
readValue
(
jsonString
,
clazz
);
}
catch
(
IOException
e
)
{
log
.
warn
(
"parse json string error:"
+
jsonString
,
e
);
return
null
;
}
}
public
<
T
>
T
fromJson
(
String
jsonString
,
TypeReference
<
T
>
type
)
{
if
(
StringUtils
.
isEmpty
(
jsonString
))
{
return
null
;
}
try
{
return
mapper
.
readValue
(
jsonString
,
type
);
}
catch
(
IOException
e
)
{
log
.
warn
(
"parse json string error:"
+
jsonString
,
e
);
return
null
;
}
}
public
<
T
,
S
>
T
fromJson
(
String
json
,
Class
<
T
>
owner
,
Class
<
S
>
subClass
)
{
if
(
subClass
==
null
)
{
return
fromJson
(
json
,
owner
);
}
Type
[]
types
=
new
Type
[
1
];
types
[
0
]
=
subClass
;
final
ParameterizedTypeImpl
type
=
ParameterizedTypeImpl
.
make
(
owner
,
types
,
owner
.
getDeclaringClass
());
TypeReference
<
T
>
typeReference
=
new
TypeReference
<
T
>()
{
@Override
public
Type
getType
()
{
return
type
;
}
};
return
fromJson
(
json
,
typeReference
);
}
/**
* 反序列化复杂Collection如List<Bean>, 先使用函數createCollectionType构造类型,然后调. 如果JSON字符串为null或"null"字符串,返回null. 如果JSON字符串为"[]",返回空集合.
*/
@SuppressWarnings
(
"unchecked"
)
public
<
T
>
T
fromJson
(
String
jsonString
,
JavaType
javaType
)
{
if
(
StringUtils
.
isEmpty
(
jsonString
))
{
return
null
;
}
try
{
return
(
T
)
mapper
.
readValue
(
jsonString
,
javaType
);
}
catch
(
IOException
e
)
{
log
.
warn
(
"parse json string error:"
+
jsonString
,
e
);
return
null
;
}
}
/** 構造泛型的Type如List<MyBean>, Map<String,MyBean> */
public
JavaType
createCollectionType
(
Class
<?>
collectionClass
,
Class
<?>...
elementClasses
)
{
return
mapper
.
getTypeFactory
().
constructParametricType
(
collectionClass
,
elementClasses
);
}
/**
* Object可以是POJO,也可以是Collection或数组. 如果对象为null,返回"null". 如果集合为空集合,返回"[]".
*/
public
String
toJson
(
Object
object
)
{
try
{
if
(
object
==
null
)
{
return
null
;
}
return
mapper
.
writeValueAsString
(
object
);
}
catch
(
IOException
e
)
{
log
.
warn
(
"write to json string error:"
+
object
,
e
);
return
null
;
}
}
// 转换类型
public
<
T
>
T
convertJsonClazz
(
Object
object
,
Class
<
T
>
clazz
)
{
String
json
=
toJson
(
object
);
return
fromJson
(
json
,
clazz
);
}
/** 當JSON裡只含有Bean的部分屬性時,更新一個已存在Bean,只覆蓋該部分的屬性. */
@SuppressWarnings
(
"unchecked"
)
public
<
T
>
T
update
(
String
jsonString
,
T
object
)
{
try
{
return
(
T
)
mapper
.
readerForUpdating
(
object
).
readValue
(
jsonString
);
}
catch
(
Exception
e
)
{
log
.
warn
(
"parse json string"
+
jsonString
+
" to object:"
+
object
+
" error."
,
e
);
}
return
null
;
}
/** 輸出JSONP格式數據. */
public
String
toJsonP
(
String
functionName
,
Object
object
)
{
return
toJson
(
new
JSONPObject
(
functionName
,
object
));
}
/** 设定是否使用Enum的toString函數來读写Enum, */
public
void
enableEnumUseToString
()
{
mapper
.
enable
(
SerializationFeature
.
WRITE_ENUMS_USING_TO_STRING
);
mapper
.
enable
(
DeserializationFeature
.
READ_ENUMS_USING_TO_STRING
);
}
}
public
static
SimpleModule
simpleModule
()
{
val
bean
=
new
SimpleModule
();
bean
.
addDeserializer
(
ZonedDateTime
.
class
,
new
JsonDeserializer
<
ZonedDateTime
>()
{
@Override
public
ZonedDateTime
deserialize
(
JsonParser
jsonParser
,
DeserializationContext
deserializationContext
)
throws
IOException
,
JsonProcessingException
{
return
ZonedDateTime
.
parse
(
jsonParser
.
getValueAsString
(),
DateTimeFormatter
.
ISO_ZONED_DATE_TIME
);
}
});
bean
.
addDeserializer
(
LocalDateTime
.
class
,
new
MyLocalDatetimeDeserializer
());
bean
.
addSerializer
(
ZonedDateTime
.
class
,
new
JsonSerializer
<
ZonedDateTime
>()
{
@Override
public
void
serialize
(
ZonedDateTime
zonedDateTime
,
JsonGenerator
jsonGenerator
,
SerializerProvider
serializerProvider
)
throws
IOException
{
jsonGenerator
.
writeString
(
DateTimeFormatter
.
ISO_ZONED_DATE_TIME
.
format
(
zonedDateTime
));
}
});
bean
.
addSerializer
(
LocalDateTime
.
class
,
new
MyLocalDatetimeSerializer
());
return
bean
;
}
@SuppressWarnings
(
"serial"
)
static
class
JacksonInitialDownCaseStrategy
extends
PropertyNamingStrategy
{
@Override
public
String
nameForField
(
@SuppressWarnings
(
"rawtypes"
)
MapperConfig
config
,
AnnotatedField
field
,
String
defaultName
)
{
return
convert
(
defaultName
);
}
@Override
public
String
nameForGetterMethod
(
@SuppressWarnings
(
"rawtypes"
)
MapperConfig
config
,
AnnotatedMethod
method
,
String
defaultName
)
{
return
convert
(
defaultName
);
}
@Override
public
String
nameForSetterMethod
(
@SuppressWarnings
(
"rawtypes"
)
MapperConfig
config
,
AnnotatedMethod
method
,
String
defaultName
)
{
String
a
=
convert
(
defaultName
);
return
a
;
}
public
String
convert
(
String
defaultName
)
{
char
[]
arr
=
defaultName
.
toCharArray
();
if
(
arr
.
length
!=
0
)
{
if
(
Character
.
isLowerCase
(
arr
[
0
]))
{
char
upper
=
Character
.
toUpperCase
(
arr
[
0
]);
arr
[
0
]
=
upper
;
}
}
return
new
StringBuilder
().
append
(
arr
).
toString
();
}
}
@SuppressWarnings
({
"unchecked"
,
"rawtypes"
})
public
static
class
Base64Deserializer
extends
JsonDeserializer
implements
ContextualDeserializer
{
@Override
public
JsonDeserializer
createContextual
(
DeserializationContext
context
,
BeanProperty
property
)
throws
JsonMappingException
{
return
this
;
}
@Override
public
Object
deserialize
(
JsonParser
parser
,
DeserializationContext
context
)
throws
IOException
,
JsonProcessingException
{
String
value
=
parser
.
getValueAsString
();
try
{
if
(
Base64
.
isBase64
(
value
))
{
// 判断是否切换编码格式
// value = Base64.decodeStr(value);
String
decode
=
new
String
(
org
.
apache
.
commons
.
codec
.
binary
.
Base64
.
decodeBase64
(
value
));
// 解码后不是乱码才解码,对emoji表情单独处理
// if (StrUtils.hasNormalCode(decode)) {
// value = decode;
// }
}
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
return
value
;
}
}
@SuppressWarnings
({
"unchecked"
,
"rawtypes"
})
public
static
class
GBKBase64Deserializer
extends
JsonDeserializer
implements
ContextualDeserializer
{
@Override
public
JsonDeserializer
createContextual
(
DeserializationContext
context
,
BeanProperty
property
)
throws
JsonMappingException
{
return
this
;
}
@Override
public
Object
deserialize
(
JsonParser
parser
,
DeserializationContext
context
)
throws
IOException
,
JsonProcessingException
{
String
value
=
parser
.
getValueAsString
();
try
{
if
(
Base64
.
isBase64
(
value
))
{
// TODO 判断是否切换编码格式
// value = new String(Base64.decode(value.getBytes()), "GBK");
value
=
new
String
(
org
.
apache
.
commons
.
codec
.
binary
.
Base64
.
decodeBase64
(
value
),
"GBK"
);
}
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
return
value
;
}
}
public
static
class
MyLocalDatetimeDeserializer
extends
StdDeserializer
<
LocalDateTime
>
{
private
static
final
long
serialVersionUID
=
1L
;
protected
MyLocalDatetimeDeserializer
()
{
super
(
LocalDateTime
.
class
);
}
@Override
public
LocalDateTime
deserialize
(
JsonParser
jp
,
DeserializationContext
ctxt
)
throws
IOException
,
JsonProcessingException
{
return
LocalDateTime
.
parse
(
jp
.
readValueAs
(
String
.
class
),
DateTimeFormatter
.
ofPattern
(
DatePattern
.
NORM_DATETIME_PATTERN
));
}
}
public
static
class
MyLocalDatetimeSerializer
extends
StdSerializer
<
LocalDateTime
>
{
private
static
final
long
serialVersionUID
=
1L
;
public
MyLocalDatetimeSerializer
()
{
super
(
LocalDateTime
.
class
);
}
@Override
public
void
serialize
(
LocalDateTime
value
,
JsonGenerator
gen
,
SerializerProvider
sp
)
throws
IOException
,
JsonProcessingException
{
gen
.
writeString
(
value
.
format
(
DateTimeFormatter
.
ofPattern
(
DatePattern
.
NORM_DATETIME_PATTERN
)));
}
}
// @SuppressWarnings({ "rawtypes" })
// public static class Base64Serializer extends JsonSerializer implements ContextualSerializer {
//
// @Override
// public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
// return this;
// }
//
// @Override
// public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
// if (!Base64.isBase64Pattern((String) value)) {
// value = Base64.decodeStr((String) value);
// }
// gen.writeObject(value);
// }
//
// }
@SuppressWarnings
(
"unchecked"
)
public
static
void
main
(
String
[]
args
)
{
String
json
=
"[\"A\",\"B\"]"
;
List
<
String
>
list
=
JacksonUtils
.
fromJson
(
json
,
ArrayList
.
class
);
System
.
out
.
println
(
list
.
get
(
0
));
list
=
JacksonUtils
.
fromJson
(
json
,
new
TypeReference
<
ArrayList
<
String
>>()
{
});
System
.
out
.
println
(
list
.
get
(
0
));
System
.
out
.
println
(
new
Date
(
10000000000000L
));
}
}
\ No newline at end of file
\ No newline at end of file
Write
Preview
Markdown
is supported
Attach a file
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 post a comment