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 b8bd7677
authored
Sep 21, 2023
by
tiger
Browse Files
Options
Browse Files
Tag
Download
Email Patches
Plain Diff
sql执行
1 parent
c88f694c
Hide whitespace changes
Inline
Side-by-side
Showing
10 changed files
with
462 additions
and
96 deletions
platform-process/src/main/java/cn/com/glsx/process/job/xxljob/core/SopXxlJobUtil.java
platform-process/src/main/java/cn/com/glsx/process/job/xxljob/core/XxlJobUtil.java
platform-process/src/main/java/cn/com/glsx/process/job/xxljob/impl/SopInstLoadJobHandler.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/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/modules/sop/execute/executor/SqlExecutor.java
platform-process/src/main/java/cn/com/glsx/process/modules/sop/execute/executor/SqlQueryExecutor.java
platform-process/src/main/java/cn/com/glsx/process/modules/sop/java/example/ControllerXblcCustomerQuery.java
platform-process/src/main/java/cn/com/glsx/process/util/FreemarkerUtil.java
platform-process/src/main/java/cn/com/glsx/process/job/xxljob/core/SopXxlJobUtil.java
View file @
b8bd767
...
@@ -61,9 +61,7 @@ public class SopXxlJobUtil {
...
@@ -61,9 +61,7 @@ public class SopXxlJobUtil {
if
(
job
==
null
)
{
if
(
job
==
null
)
{
job
=
new
XxlJobInfo
();
job
=
new
XxlJobInfo
();
}
}
job
.
setExecutorParam
(
""
);
job
.
setJobDesc
(
"加载所有SOP实例任务"
);
job
.
setJobDesc
(
"加载所有SOP实例任务"
);
job
.
setAuthor
(
"admin"
);
job
.
setScheduleConf
(
"10 */5 * * * ?"
);
job
.
setScheduleConf
(
"10 */5 * * * ?"
);
job
.
setExecutorHandler
(
SOP_LOAD_JOB_ID
);
job
.
setExecutorHandler
(
SOP_LOAD_JOB_ID
);
job
.
setBusKey
(
SOP_LOAD_JOB_ID
);
job
.
setBusKey
(
SOP_LOAD_JOB_ID
);
...
...
platform-process/src/main/java/cn/com/glsx/process/job/xxljob/core/XxlJobUtil.java
View file @
b8bd767
...
@@ -66,6 +66,7 @@ public class XxlJobUtil {
...
@@ -66,6 +66,7 @@ public class XxlJobUtil {
**/
**/
public
static
String
add
(
XxlJobInfo
jobInfo
)
{
public
static
String
add
(
XxlJobInfo
jobInfo
)
{
jobInfo
.
setJobGroup
(
groupId
);
jobInfo
.
setJobGroup
(
groupId
);
jobInfo
.
setAuthor
(
"admin"
);
jobInfo
.
setGlueType
(
"BEAN"
);
jobInfo
.
setGlueType
(
"BEAN"
);
jobInfo
.
setExecutorBlockStrategy
(
"SERIAL_EXECUTION"
);
jobInfo
.
setExecutorBlockStrategy
(
"SERIAL_EXECUTION"
);
jobInfo
.
setExecutorRouteStrategy
(
"RANDOM"
);
jobInfo
.
setExecutorRouteStrategy
(
"RANDOM"
);
...
...
platform-process/src/main/java/cn/com/glsx/process/job/xxljob/impl/SopInstLoadJobHandler.java
View file @
b8bd767
package
cn
.
com
.
glsx
.
process
.
job
.
xxljob
.
impl
;
package
cn
.
com
.
glsx
.
process
.
job
.
xxljob
.
impl
;
import
java.util.Date
;
import
java.util.List
;
import
java.util.List
;
import
javax.annotation.Resource
;
import
javax.annotation.Resource
;
...
@@ -29,9 +30,13 @@ public class SopInstLoadJobHandler {
...
@@ -29,9 +30,13 @@ public class SopInstLoadJobHandler {
List
<
SopInst
>
all
=
sopService
.
loadAllInst
();
List
<
SopInst
>
all
=
sopService
.
loadAllInst
();
for
(
SopInst
inst
:
all
)
{
for
(
SopInst
inst
:
all
)
{
if
(
inst
.
getInstStatus
()
==
0
)
{
// 过期机制
// 停止实例任务以及所有子任务
if
(
inst
.
getExpireTime
()
!=
null
&&
inst
.
getExpireTime
().
before
(
new
Date
()))
{
inst
.
setInstStatus
((
byte
)
-
1
);
}
if
(
inst
.
getInstStatus
()
!=
1
)
{
// 停止实例任务以及所有子任务
SopStruct
sop
=
sopService
.
loadSop
(
inst
.
getInstId
());
SopStruct
sop
=
sopService
.
loadSop
(
inst
.
getInstId
());
SopXxlJobUtil
.
pauseSop
(
sop
);
SopXxlJobUtil
.
pauseSop
(
sop
);
continue
;
continue
;
...
...
platform-process/src/main/java/cn/com/glsx/process/modules/service/SopService.java
View file @
b8bd767
...
@@ -105,6 +105,11 @@ public class SopService {
...
@@ -105,6 +105,11 @@ public class SopService {
return
null
;
return
null
;
}
}
// 过期机制
if
(
inst
.
getExpireTime
()
!=
null
&&
inst
.
getExpireTime
().
before
(
new
Date
()))
{
inst
.
setInstStatus
((
byte
)
-
1
);
}
SopTplGrant
grant
=
grantMapper
.
selectByPrimaryKey
(
inst
.
getGrantId
());
SopTplGrant
grant
=
grantMapper
.
selectByPrimaryKey
(
inst
.
getGrantId
());
sop
.
setGrant
(
grant
);
sop
.
setGrant
(
grant
);
...
...
platform-process/src/main/java/cn/com/glsx/process/modules/sop/execute/SnapshotStruct.java
View file @
b8bd767
...
@@ -32,4 +32,10 @@ public class SnapshotStruct implements Serializable, Cloneable {
...
@@ -32,4 +32,10 @@ public class SnapshotStruct implements Serializable, Cloneable {
*/
*/
private
Map
<
String
,
Object
>
resultMap
=
Maps
.
newHashMap
();
private
Map
<
String
,
Object
>
resultMap
=
Maps
.
newHashMap
();
public
Map
<
String
,
Object
>
toMap
()
{
Map
<
String
,
Object
>
map
=
Maps
.
newHashMap
();
map
.
putAll
(
getInitMap
());
map
.
putAll
(
getResultMap
());
return
map
;
}
}
}
\ No newline at end of file
\ No newline at end of file
platform-process/src/main/java/cn/com/glsx/process/modules/sop/execute/SopNodeExecutor.java
View file @
b8bd767
...
@@ -21,6 +21,7 @@ import org.slf4j.LoggerFactory;
...
@@ -21,6 +21,7 @@ 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.FreemarkerUtil
;
import
cn.com.glsx.process.util.JacksonUtils
;
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
;
...
@@ -51,8 +52,11 @@ public interface SopNodeExecutor {
...
@@ -51,8 +52,11 @@ public interface SopNodeExecutor {
// 当前节点需要的参数
// 当前节点需要的参数
if
(
StrUtil
.
isNotEmpty
(
node
.
getNodeParam
()))
{
if
(
StrUtil
.
isNotEmpty
(
node
.
getNodeParam
()))
{
// 节点入参按freemarker语法替换
String
source
=
FreemarkerUtil
.
processContent
(
node
.
getNodeParam
(),
es
.
toMap
());
if
(
StrUtil
.
isNotEmpty
(
node
.
getNodeKey
()))
{
if
(
StrUtil
.
isNotEmpty
(
node
.
getNodeKey
()))
{
JSONObject
nodeParamObj
=
JSONUtil
.
parseObj
(
node
.
getNodeParam
()
);
JSONObject
nodeParamObj
=
JSONUtil
.
parseObj
(
source
);
es
.
getParamMap
().
put
(
node
.
getNodeKey
(),
nodeParamObj
);
es
.
getParamMap
().
put
(
node
.
getNodeKey
(),
nodeParamObj
);
}
else
{
}
else
{
log
.
warn
(
"【{}】nodeKey 为空!!!"
,
node
.
getInstId
()
+
"-"
+
node
.
getNodeId
());
log
.
warn
(
"【{}】nodeKey 为空!!!"
,
node
.
getInstId
()
+
"-"
+
node
.
getNodeId
());
...
...
platform-process/src/main/java/cn/com/glsx/process/modules/sop/execute/executor/SqlExecutor.java
View file @
b8bd767
package
cn
.
com
.
glsx
.
process
.
modules
.
sop
.
execute
.
executor
;
package
cn
.
com
.
glsx
.
process
.
modules
.
sop
.
execute
.
executor
;
import
java.util.Map
;
import
java.util.Map
;
...
@@ -12,83 +11,51 @@ import com.alibaba.fastjson.JSONObject;
...
@@ -12,83 +11,51 @@ import com.alibaba.fastjson.JSONObject;
import
cn.com.glsx.process.common.constant.Constants
;
import
cn.com.glsx.process.common.constant.Constants
;
import
cn.com.glsx.process.modules.entity.SopDataSource
;
import
cn.com.glsx.process.modules.entity.SopDataSource
;
import
cn.com.glsx.process.modules.entity.SopInst
;
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.modules.service.SopDataSourceService
;
import
cn.com.glsx.process.modules.service.SopDataSourceService
;
import
cn.com.glsx.process.modules.sop.execute.SnapshotStruct
;
import
cn.com.glsx.process.modules.sop.execute.RunResult
;
import
cn.com.glsx.process.modules.sop.execute.RunResult
;
import
cn.com.glsx.process.modules.sop.execute.SnapshotStruct
;
import
cn.com.glsx.process.modules.sop.execute.SopNodeExecutor
;
import
cn.com.glsx.process.modules.sop.execute.SopNodeExecutor
;
import
cn.com.glsx.process.modules.sop.execute.plugin.dbconn.FlowDataAdapterImpl
;
import
cn.com.glsx.process.modules.sop.execute.plugin.dbconn.FlowDataAdapterImpl
;
import
cn.com.glsx.process.modules.sop.execute.plugin.dbconn.SopBizAdapter
;
import
cn.com.glsx.process.modules.sop.execute.plugin.dbconn.SopBizAdapter
;
import
cn.com.glsx.process.util.FreemarkerUtil
;
import
lombok.extern.slf4j.Slf4j
;
import
lombok.extern.slf4j.Slf4j
;
@Slf4j
@Slf4j
@Service
@Service
public
class
SqlExecutor
implements
SopNodeExecutor
{
public
class
SqlExecutor
implements
SopNodeExecutor
{
@Autowired
@Autowired
private
SopDataSourceService
sopDataSourceService
;
private
SopDataSourceService
sopDataSourceService
;
@Override
@Override
public
RunResult
execute
(
SopStruct
sop
,
SopInstNode
node
,
SnapshotStruct
executeStruct
)
throws
Exception
{
public
RunResult
execute
(
SopStruct
sop
,
SopInstNode
node
,
SnapshotStruct
executeStruct
)
throws
Exception
{
Map
<
String
,
Object
>
resultMap
=
executeStruct
.
getResultMap
();
Map
<
String
,
Object
>
resultMap
=
executeStruct
.
getResultMap
();
try
{
try
{
// 获取配置参数信息
// 获取配置参数信息
String
nodeContent
=
node
.
getNodeContent
();
String
nodeContent
=
node
.
getNodeContent
();
JSONObject
paramMap
=
JSON
.
parseObject
(
nodeContent
);
JSONObject
paramMap
=
JSON
.
parseObject
(
nodeContent
);
String
sqlTemplate
=
paramMap
.
get
(
"source"
)
+
""
;
String
sqlcode
=
paramMap
.
get
(
"source"
)
+
""
;
String
dataSourceId
=
paramMap
.
get
(
"dataSourceId"
)
+
""
;
String
dataSourceId
=
paramMap
.
get
(
"dataSourceId"
)
+
""
;
// 执行sql插件
// 执行sql插件
SopDataSource
byId
=
sopDataSourceService
.
findByName
(
dataSourceId
);
SopDataSource
byId
=
sopDataSourceService
.
findByName
(
dataSourceId
);
SopBizAdapter
mcgBizAdapter
=
new
FlowDataAdapterImpl
(
byId
);
SopBizAdapter
mcgBizAdapter
=
new
FlowDataAdapterImpl
(
byId
);
String
sql
=
FreemarkerUtil
.
processContent
(
sqlTemplate
,
executeStruct
.
toMap
());
codeReplace
(
sqlcode
,
sop
,
node
);
int
i
=
mcgBizAdapter
.
executeUpdate
(
sql
);
int
i
=
mcgBizAdapter
.
executeUpdate
(
sqlcode
);
// 处理执行结果
// 处理执行结果
resultMap
.
put
(
Constants
.
RES_DATE_KEY
,
i
);
resultMap
.
put
(
Constants
.
RES_DATE_KEY
,
i
);
resultMap
.
put
(
Constants
.
RES_KEY
,
Constants
.
RES_SUCCESS
);
resultMap
.
put
(
Constants
.
RES_KEY
,
Constants
.
RES_SUCCESS
);
}
catch
(
Exception
e
)
{
}
catch
(
Exception
e
)
{
String
message
=
e
.
getMessage
();
String
message
=
e
.
getMessage
();
resultMap
.
put
(
Constants
.
RES_FAIL_MESSAGE
,
message
);
resultMap
.
put
(
Constants
.
RES_FAIL_MESSAGE
,
message
);
resultMap
.
put
(
Constants
.
RES_KEY
,
Constants
.
RES_FAIL
);
resultMap
.
put
(
Constants
.
RES_KEY
,
Constants
.
RES_FAIL
);
}
}
return
null
;
return
null
;
}
}
/**
* 替换sql里面的通配符
*
* @param sqlcode sql脚本
* @param sop sop实例
* @param node sop节点
*/
private
void
codeReplace
(
String
sqlcode
,
SopStruct
sop
,
SopInstNode
node
)
{
SopInst
inst
=
sop
.
getInst
();
String
instSnapshot
=
inst
.
getInstSnapshot
();
JSONObject
jsonObject
=
JSONObject
.
parseObject
(
instSnapshot
);
// 替换关联业务的活动id
String
activityId
=
jsonObject
.
get
(
"activityId"
)
+
""
;
if
(
activityId
!=
null
)
{
sqlcode
.
replace
(
"#{activityId}"
,
activityId
);
}
// 替换关联的instId
if
(
activityId
!=
null
)
{
sqlcode
.
replace
(
"#{instId}"
,
inst
.
getInstId
());
}
String
nodeParam
=
node
.
getNodeParam
();
JSONObject
nodeJsonObject
=
JSONObject
.
parseObject
(
nodeParam
);
for
(
Map
.
Entry
<
String
,
Object
>
entry
:
nodeJsonObject
.
entrySet
())
{
sqlcode
.
replace
(
"#{"
+
entry
.
getKey
()
+
"}"
,
entry
.
getValue
()
+
""
);
}
}
}
}
\ No newline at end of file
\ No newline at end of file
platform-process/src/main/java/cn/com/glsx/process/modules/sop/execute/executor/SqlQueryExecutor.java
View file @
b8bd767
...
@@ -12,15 +12,15 @@ import com.alibaba.fastjson.JSONObject;
...
@@ -12,15 +12,15 @@ import com.alibaba.fastjson.JSONObject;
import
cn.com.glsx.process.common.constant.Constants
;
import
cn.com.glsx.process.common.constant.Constants
;
import
cn.com.glsx.process.modules.entity.SopDataSource
;
import
cn.com.glsx.process.modules.entity.SopDataSource
;
import
cn.com.glsx.process.modules.entity.SopInst
;
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.modules.service.SopDataSourceService
;
import
cn.com.glsx.process.modules.service.SopDataSourceService
;
import
cn.com.glsx.process.modules.sop.execute.SnapshotStruct
;
import
cn.com.glsx.process.modules.sop.execute.RunResult
;
import
cn.com.glsx.process.modules.sop.execute.RunResult
;
import
cn.com.glsx.process.modules.sop.execute.SnapshotStruct
;
import
cn.com.glsx.process.modules.sop.execute.SopNodeExecutor
;
import
cn.com.glsx.process.modules.sop.execute.SopNodeExecutor
;
import
cn.com.glsx.process.modules.sop.execute.plugin.dbconn.FlowDataAdapterImpl
;
import
cn.com.glsx.process.modules.sop.execute.plugin.dbconn.FlowDataAdapterImpl
;
import
cn.com.glsx.process.modules.sop.execute.plugin.dbconn.SopBizAdapter
;
import
cn.com.glsx.process.modules.sop.execute.plugin.dbconn.SopBizAdapter
;
import
cn.com.glsx.process.util.FreemarkerUtil
;
import
lombok.extern.slf4j.Slf4j
;
import
lombok.extern.slf4j.Slf4j
;
@Slf4j
@Slf4j
...
@@ -37,14 +37,16 @@ public class SqlQueryExecutor implements SopNodeExecutor {
...
@@ -37,14 +37,16 @@ public class SqlQueryExecutor implements SopNodeExecutor {
// 获取配置参数信息
// 获取配置参数信息
String
nodeContent
=
node
.
getNodeContent
();
String
nodeContent
=
node
.
getNodeContent
();
JSONObject
paramMap
=
JSON
.
parseObject
(
nodeContent
);
JSONObject
paramMap
=
JSON
.
parseObject
(
nodeContent
);
String
sqlcod
e
=
paramMap
.
get
(
"source"
)
+
""
;
String
sqlTemplat
e
=
paramMap
.
get
(
"source"
)
+
""
;
String
dataSourceId
=
paramMap
.
get
(
"dataSourceId"
)
+
""
;
String
dataSourceId
=
paramMap
.
get
(
"dataSourceId"
)
+
""
;
// 执行sql插件
// 执行sql插件
SopDataSource
byId
=
sopDataSourceService
.
findByName
(
dataSourceId
);
SopDataSource
byId
=
sopDataSourceService
.
findByName
(
dataSourceId
);
SopBizAdapter
mcgBizAdapter
=
new
FlowDataAdapterImpl
(
byId
);
SopBizAdapter
mcgBizAdapter
=
new
FlowDataAdapterImpl
(
byId
);
List
<
Map
<
String
,
Object
>>
maps
=
mcgBizAdapter
.
tableQuery
(
sqlcode
);
codeReplace
(
sqlcode
,
sop
,
node
);
String
sql
=
FreemarkerUtil
.
processContent
(
sqlTemplate
,
executeStruct
.
toMap
());
List
<
Map
<
String
,
Object
>>
maps
=
mcgBizAdapter
.
tableQuery
(
sql
);
// 处理执行结果
// 处理执行结果
resultMap
.
put
(
Constants
.
RES_DATE_KEY
,
maps
);
resultMap
.
put
(
Constants
.
RES_DATE_KEY
,
maps
);
...
@@ -57,28 +59,5 @@ public class SqlQueryExecutor implements SopNodeExecutor {
...
@@ -57,28 +59,5 @@ public class SqlQueryExecutor implements SopNodeExecutor {
return
null
;
return
null
;
}
}
private
void
codeReplace
(
String
sqlcode
,
SopStruct
sop
,
SopInstNode
node
)
{
SopInst
inst
=
sop
.
getInst
();
String
instSnapshot
=
inst
.
getInstSnapshot
();
JSONObject
jsonObject
=
JSONObject
.
parseObject
(
instSnapshot
);
// 替换关联业务的活动id
String
activityId
=
jsonObject
.
get
(
"activityId"
)
+
""
;
if
(
activityId
!=
null
)
{
sqlcode
.
replace
(
"#{activityId}"
,
activityId
);
}
// 替换关联的instId
if
(
activityId
!=
null
)
{
sqlcode
.
replace
(
"#{instId}"
,
inst
.
getInstId
());
}
String
nodeParam
=
node
.
getNodeParam
();
JSONObject
nodeJsonObject
=
JSONObject
.
parseObject
(
nodeParam
);
for
(
Map
.
Entry
<
String
,
Object
>
entry
:
nodeJsonObject
.
entrySet
())
{
sqlcode
.
replace
(
"#{"
+
entry
.
getKey
()
+
"}"
,
entry
.
getValue
()
+
""
);
}
}
}
}
\ No newline at end of file
\ No newline at end of file
platform-process/src/main/java/cn/com/glsx/process/modules/sop/java/example/ControllerXblcCustomerQuery.java
0 → 100644
View file @
b8bd767
package
cn
.
com
.
glsx
.
process
.
modules
.
sop
.
java
.
example
;
import
org.springframework.web.client.RestTemplate
;
import
com.alibaba.fastjson.JSON
;
import
com.alibaba.fastjson.JSONObject
;
/**
* 续保旅程中,圈人节点,按输入参数中的标签来圈人
*
* @author kome
* @date 2023年9月21日 下午2:04:17
*/
public
class
ControllerXblcCustomerQuery
{
private
static
String
baseurl
=
"http://192.168.0.63:9823/process/sop/xxljob/testJava"
;
/**
* <code>
{
"merchantId": "M153312087",
"stages": {
...
},
"sopTag": "xblc" // select * from cdp_user where tag_xblc=1
}
* </code>
*
* @param param
* @return
*/
public
static
JSON
execute
(
JSON
param
)
{
// 走sql或http查询用户列表
RestTemplate
restTemplate
=
new
RestTemplate
();
Object
o
=
restTemplate
.
postForObject
(
baseurl
+
"?busKey="
+
11
,
param
,
Object
.
class
);
return
(
JSONObject
)
JSONObject
.
toJSON
(
o
);
}
}
\ No newline at end of file
\ No newline at end of file
platform-process/src/main/java/cn/com/glsx/process/util/FreemarkerUtil.java
0 → 100644
View file @
b8bd767
package
cn
.
com
.
glsx
.
process
.
util
;
import
java.io.IOException
;
import
java.io.StringWriter
;
import
java.lang.reflect.Field
;
import
java.util.HashMap
;
import
java.util.HashSet
;
import
java.util.Map
;
import
java.util.Set
;
import
org.springframework.ui.freemarker.FreeMarkerTemplateUtils
;
import
com.google.common.collect.Sets
;
import
cn.hutool.json.JSONUtil
;
import
freemarker.cache.StringTemplateLoader
;
import
freemarker.core.Environment
;
import
freemarker.core.InvalidReferenceException
;
import
freemarker.core.NonSequenceOrCollectionException
;
import
freemarker.core.TemplateElement
;
import
freemarker.ext.beans.StringModel
;
import
freemarker.template.Configuration
;
import
freemarker.template.Template
;
import
freemarker.template.TemplateCollectionModel
;
import
freemarker.template.TemplateException
;
import
freemarker.template.TemplateHashModelEx
;
import
freemarker.template.TemplateModel
;
import
freemarker.template.TemplateModelException
;
import
freemarker.template.TemplateModelIterator
;
import
freemarker.template.TemplateScalarModel
;
import
freemarker.template.TemplateSequenceModel
;
import
lombok.extern.slf4j.Slf4j
;
@Slf4j
public
class
FreemarkerUtil
{
static
Configuration
configuration
=
new
Configuration
(
Configuration
.
VERSION_2_3_31
);
static
{
configuration
.
setLogTemplateExceptions
(
false
);
// configuration.setTemplateExceptionHandler(TemplateExceptionHandler.DEBUG_HANDLER);
}
public
static
Set
<
String
>
extractVariables
(
String
templateContent
)
throws
IOException
,
TemplateException
{
Set
<
String
>
variables
=
new
HashSet
<>();
Template
template
=
generateTemplate
(
templateContent
);
StringWriter
writer
=
new
StringWriter
();
Map
<
String
,
Object
>
dataModel
=
new
HashMap
<>();
template
.
process
(
dataModel
,
writer
);
Environment
environment
=
template
.
createProcessingEnvironment
(
dataModel
,
writer
);
TemplateModel
templateModel
=
environment
.
getDataModel
();
extractVariablesFromTemplateModel
(
templateModel
,
variables
);
return
variables
;
}
private
static
void
extractVariablesFromTemplateModel
(
TemplateModel
templateModel
,
Set
<
String
>
variables
)
throws
TemplateModelException
{
if
(
templateModel
instanceof
TemplateHashModelEx
)
{
TemplateHashModelEx
hashModelEx
=
(
TemplateHashModelEx
)
templateModel
;
TemplateCollectionModel
keys
=
hashModelEx
.
keys
();
TemplateModelIterator
keyIterator
=
keys
.
iterator
();
while
(
keyIterator
.
hasNext
())
{
TemplateModel
key
=
keyIterator
.
next
();
if
(
key
instanceof
TemplateScalarModel
)
{
String
variable
=
((
TemplateScalarModel
)
key
).
getAsString
();
variables
.
add
(
variable
);
}
}
}
if
(
templateModel
instanceof
TemplateCollectionModel
)
{
TemplateCollectionModel
hashModel
=
(
TemplateCollectionModel
)
templateModel
;
// TemplateCollectionModel values = hashModel.values();
TemplateModelIterator
valueIterator
=
hashModel
.
iterator
();
while
(
valueIterator
.
hasNext
())
{
TemplateModel
value
=
valueIterator
.
next
();
extractVariablesFromTemplateModel
(
value
,
variables
);
}
}
if
(
templateModel
instanceof
TemplateSequenceModel
)
{
TemplateSequenceModel
sequenceModel
=
(
TemplateSequenceModel
)
templateModel
;
int
size
=
sequenceModel
.
size
();
for
(
int
i
=
0
;
i
<
size
;
i
++)
{
TemplateModel
element
=
sequenceModel
.
get
(
i
);
extractVariablesFromTemplateModel
(
element
,
variables
);
}
}
}
/**
* Find all the variables used in the Freemarker Template
*
* @param templateName
* @return
*/
public
static
Set
<
String
>
getTemplateVariables
(
Template
template
)
{
StringWriter
stringWriter
=
new
StringWriter
();
Map
<
String
,
Object
>
dataModel
=
new
HashMap
<>();
boolean
exceptionCaught
;
do
{
exceptionCaught
=
false
;
try
{
template
.
process
(
dataModel
,
stringWriter
);
}
catch
(
InvalidReferenceException
e
)
{
exceptionCaught
=
true
;
dataModel
.
put
(
e
.
getBlamedExpressionString
(),
""
);
}
catch
(
NonSequenceOrCollectionException
e
)
{
}
catch
(
Exception
e
)
{
// throw new IllegalStateException("Failed to Load Template: " + template.getName(), e);
}
}
while
(
exceptionCaught
);
return
dataModel
.
keySet
();
}
private
static
Template
getTemplate
(
String
templateName
)
{
try
{
return
configuration
.
getTemplate
(
templateName
);
}
catch
(
IOException
e
)
{
throw
new
IllegalStateException
(
"Failed to Load Template: "
+
templateName
,
e
);
}
}
private
static
Template
generateTemplate
(
String
templateContent
)
{
try
{
StringTemplateLoader
templateLoader
=
new
StringTemplateLoader
();
templateLoader
.
putTemplate
(
"__testTemplate"
,
templateContent
);
configuration
.
setTemplateLoader
(
templateLoader
);
Template
template
=
configuration
.
getTemplate
(
"__testTemplate"
);
return
template
;
}
catch
(
IOException
e
)
{
throw
new
IllegalStateException
(
"Failed to generate Template: "
+
templateContent
,
e
);
}
}
public
static
Set
<
String
>
referenceSet
(
Template
template
)
throws
TemplateModelException
{
Set
<
String
>
result
=
new
HashSet
<>();
TemplateElement
rootTreeNode
=
template
.
getRootTreeNode
();
for
(
int
i
=
0
;
i
<
rootTreeNode
.
getChildCount
();
i
++)
{
TemplateModel
templateModel
=
rootTreeNode
.
getChildNodes
().
get
(
i
);
if
(!(
templateModel
instanceof
StringModel
))
{
continue
;
}
Object
wrappedObject
=
((
StringModel
)
templateModel
).
getWrappedObject
();
if
(!
"DollarVariable"
.
equals
(
wrappedObject
.
getClass
().
getSimpleName
()))
{
continue
;
}
try
{
Object
expression
=
getInternalState
(
wrappedObject
,
"expression"
);
switch
(
expression
.
getClass
().
getSimpleName
())
{
case
"Identifier"
:
result
.
add
(
getInternalState
(
expression
,
"name"
).
toString
());
break
;
case
"DefaultToExpression"
:
result
.
add
(
getInternalState
(
expression
,
"lho"
).
toString
());
break
;
case
"BuiltinVariable"
:
break
;
default
:
throw
new
IllegalStateException
(
"Unable to introspect variable"
);
}
}
catch
(
NoSuchFieldException
|
IllegalAccessException
e
)
{
throw
new
TemplateModelException
(
"Unable to reflect template model"
);
}
}
return
result
;
}
private
static
Object
getInternalState
(
Object
o
,
String
fieldName
)
throws
NoSuchFieldException
,
IllegalAccessException
{
Field
field
=
o
.
getClass
().
getDeclaredField
(
fieldName
);
boolean
wasAccessible
=
field
.
isAccessible
();
try
{
field
.
setAccessible
(
true
);
return
field
.
get
(
o
);
}
finally
{
field
.
setAccessible
(
wasAccessible
);
}
}
public
static
Set
<
String
>
getNecessaryTemplateVariables
(
String
templateName
)
throws
TemplateModelException
{
Set
<
String
>
result
=
new
HashSet
<>();
TemplateElement
rootTreeNode
=
getTemplate
(
templateName
).
getRootTreeNode
();
if
(
"IteratorBlock"
.
equals
(
rootTreeNode
.
getClass
().
getSimpleName
()))
{
introspectFromIteratorBlock
(
result
,
rootTreeNode
);
return
result
;
}
for
(
int
i
=
0
;
i
<
rootTreeNode
.
getChildCount
();
i
++)
{
TemplateModel
templateModel
=
rootTreeNode
.
getChildNodes
().
get
(
i
);
if
(!(
templateModel
instanceof
StringModel
))
{
continue
;
}
Object
wrappedObject
=
((
StringModel
)
templateModel
).
getWrappedObject
();
if
(
"DollarVariable"
.
equals
(
wrappedObject
.
getClass
().
getSimpleName
()))
{
introspectFromDollarVariable
(
result
,
wrappedObject
);
}
else
if
(
"ConditionalBlock"
.
equals
(
wrappedObject
.
getClass
().
getSimpleName
()))
{
introspectFromConditionalBlock
(
result
,
wrappedObject
);
}
else
if
(
"IfBlock"
.
equals
(
wrappedObject
.
getClass
().
getSimpleName
()))
{
introspectFromIfBlock
(
result
,
wrappedObject
);
}
else
if
(
"IteratorBlock"
.
equals
(
wrappedObject
.
getClass
().
getSimpleName
()))
{
introspectFromIteratorBlock
(
result
,
wrappedObject
);
}
}
return
result
;
}
public
static
Set
<
String
>
getNecessaryTemplateVariables
(
Template
template
)
throws
TemplateModelException
{
Set
<
String
>
result
=
new
HashSet
<>();
TemplateElement
rootTreeNode
=
template
.
getRootTreeNode
();
if
(
"IteratorBlock"
.
equals
(
rootTreeNode
.
getClass
().
getSimpleName
()))
{
introspectFromIteratorBlock
(
result
,
rootTreeNode
);
return
result
;
}
for
(
int
i
=
0
;
i
<
rootTreeNode
.
getChildCount
();
i
++)
{
TemplateModel
templateModel
=
rootTreeNode
.
getChildNodes
().
get
(
i
);
if
(!(
templateModel
instanceof
StringModel
))
{
continue
;
}
Object
wrappedObject
=
((
StringModel
)
templateModel
).
getWrappedObject
();
if
(
"DollarVariable"
.
equals
(
wrappedObject
.
getClass
().
getSimpleName
()))
{
introspectFromDollarVariable
(
result
,
wrappedObject
);
}
else
if
(
"ConditionalBlock"
.
equals
(
wrappedObject
.
getClass
().
getSimpleName
()))
{
introspectFromConditionalBlock
(
result
,
wrappedObject
);
}
else
if
(
"IfBlock"
.
equals
(
wrappedObject
.
getClass
().
getSimpleName
()))
{
introspectFromIfBlock
(
result
,
wrappedObject
);
}
else
if
(
"IteratorBlock"
.
equals
(
wrappedObject
.
getClass
().
getSimpleName
()))
{
introspectFromIteratorBlock
(
result
,
wrappedObject
);
}
}
return
result
;
}
private
static
void
introspectFromIteratorBlock
(
Set
<
String
>
result
,
Object
wrappedObject
)
{
try
{
Object
expression
=
getInternalState
(
wrappedObject
,
"listedExp"
);
result
.
add
(
getInternalState
(
expression
,
"name"
).
toString
());
}
catch
(
NoSuchFieldException
|
IllegalAccessException
ignored
)
{
ignored
.
printStackTrace
();
}
}
private
static
void
introspectFromConditionalBlock
(
Set
<
String
>
result
,
Object
wrappedObject
)
throws
TemplateModelException
{
try
{
Object
expression
=
getInternalState
(
wrappedObject
,
"condition"
);
if
(
expression
==
null
)
{
return
;
}
result
.
addAll
(
dealCommonExpression
(
expression
));
String
nested
=
getInternalState
(
wrappedObject
,
"nestedBlock"
).
toString
();
result
.
addAll
(
getNecessaryTemplateVariables
(
nested
));
}
catch
(
NoSuchFieldException
|
IllegalAccessException
ignored
)
{
}
}
private
static
Set
<
String
>
dealCommonExpression
(
Object
expression
)
throws
NoSuchFieldException
,
IllegalAccessException
{
Set
<
String
>
ret
=
Sets
.
newHashSet
();
switch
(
expression
.
getClass
().
getSimpleName
())
{
case
"ComparisonExpression"
:
String
reference
=
dealComparisonExpression
(
expression
);
ret
.
add
(
reference
);
break
;
case
"ExistsExpression"
:
reference
=
dealExistsExpression
(
expression
);
ret
.
add
(
reference
);
break
;
case
"AndExpression"
:
ret
.
addAll
(
dealAndExpression
(
expression
));
default
:
break
;
}
return
ret
;
}
private
static
String
dealComparisonExpression
(
Object
expression
)
throws
NoSuchFieldException
,
IllegalAccessException
{
Object
left
=
getInternalState
(
expression
,
"left"
);
Object
right
=
getInternalState
(
expression
,
"right"
);
String
reference
;
if
(
"Identifier"
.
equals
(
left
.
getClass
().
getSimpleName
()))
{
reference
=
getInternalState
(
left
,
"name"
).
toString
();
}
else
{
reference
=
getInternalState
(
right
,
"name"
).
toString
();
}
return
reference
;
}
private
static
String
dealExistsExpression
(
Object
expression
)
throws
NoSuchFieldException
,
IllegalAccessException
{
Object
exp
=
getInternalState
(
expression
,
"exp"
);
return
getInternalState
(
exp
,
"name"
).
toString
();
}
private
static
Set
<
String
>
dealAndExpression
(
Object
expression
)
throws
NoSuchFieldException
,
IllegalAccessException
{
Set
<
String
>
ret
=
Sets
.
newHashSet
();
Object
lho
=
getInternalState
(
expression
,
"lho"
);
ret
.
addAll
(
dealCommonExpression
(
lho
));
Object
rho
=
getInternalState
(
expression
,
"rho"
);
ret
.
addAll
(
dealCommonExpression
(
rho
));
return
ret
;
}
private
static
void
introspectFromIfBlock
(
Set
<
String
>
result
,
Object
wrappedObject
)
throws
TemplateModelException
{
result
.
addAll
(
getNecessaryTemplateVariables
(
wrappedObject
.
toString
()));
}
private
static
void
introspectFromDollarVariable
(
Set
<
String
>
result
,
Object
wrappedObject
)
throws
TemplateModelException
{
try
{
Object
expression
=
getInternalState
(
wrappedObject
,
"expression"
);
switch
(
expression
.
getClass
().
getSimpleName
())
{
case
"Identifier"
:
result
.
add
(
getInternalState
(
expression
,
"name"
).
toString
());
break
;
case
"DefaultToExpression"
:
result
.
add
(
getInternalState
(
expression
,
"lho"
).
toString
());
break
;
case
"BuiltinVariable"
:
break
;
default
:
break
;
}
}
catch
(
NoSuchFieldException
|
IllegalAccessException
e
)
{
throw
new
TemplateModelException
(
"Unable to reflect template model"
);
}
}
public
void
test
()
throws
Exception
{
String
templateContent
=
"Hello, ${name}! <#list users as u>${u.name}</#list>"
;
Template
template
=
generateTemplate
(
templateContent
);
System
.
out
.
println
(
JSONUtil
.
toJsonStr
(
getTemplateVariables
(
template
)));
System
.
out
.
println
(
JSONUtil
.
toJsonStr
(
referenceSet
(
template
)));
System
.
out
.
println
(
JSONUtil
.
toJsonStr
(
getNecessaryTemplateVariables
(
template
)));
}
public
static
void
main
(
String
[]
args
)
throws
IOException
,
TemplateException
{
String
templateContent
=
"<#assign name = 'Alice'>Hello, ${name}!"
;
Set
<
String
>
variables
=
extractVariables
(
templateContent
);
for
(
String
variable
:
variables
)
{
System
.
out
.
println
(
variable
);
}
}
public
static
String
processContent
(
String
sqlTemplate
,
Map
<
String
,
Object
>
params
)
{
try
{
Template
template
=
generateTemplate
(
sqlTemplate
);
return
FreeMarkerTemplateUtils
.
processTemplateIntoString
(
template
,
params
);
}
catch
(
Exception
e
)
{
log
.
warn
(
sqlTemplate
,
params
,
e
);
return
null
;
}
}
}
\ 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