proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/builder/el/operator/MaxWaitTimeOperator.java
|
MaxWaitTimeOperator
|
wrappedByTimeout
|
class MaxWaitTimeOperator extends BaseOperator<Condition> {
@Override
public Condition build(Object[] objects) throws Exception {
OperatorHelper.checkObjectSizeEqTwo(objects);
Executable executable = OperatorHelper.convert(objects[0], Executable.class);
// 获取传入的时间参数
Integer maxWaitTime = OperatorHelper.convert(objects[1], Integer.class);
if (executable instanceof WhenCondition) {
// WhenCondition,直接设置等待时间
WhenCondition whenCondition = OperatorHelper.convert(executable, WhenCondition.class);
whenCondition.setMaxWaitTime(maxWaitTime);
whenCondition.setMaxWaitTimeUnit(getMaxWaitTimeUnit());
return whenCondition;
} else if (executable instanceof FinallyCondition) {
// FINALLY,报错
String errorMsg = StrFormatter.format("The caller [{}] cannot use the keyword \"{}'\"", executable.toString(), operatorName());
throw new QLException(errorMsg);
} else if (containsFinally(executable)) {
// 处理 THEN 中的 FINALLY
ThenCondition thenCondition = OperatorHelper.convert(executable, ThenCondition.class);
return handleFinally(thenCondition, maxWaitTime);
} else {
// 其他情况,被 WHEN 包装
return wrappedByTimeout(executable, maxWaitTime);
}
}
/**
* 将一个 Executable 包装为带有单独超时控制的 TimeoutCondition
*
* @param executable 待包装对象
* @param maxWaitTime 最大等待时间
* @return 包装后的 TimeoutCondition
*/
private TimeoutCondition wrappedByTimeout(Executable executable, Integer maxWaitTime) {<FILL_FUNCTION_BODY>}
/**
* 判断 THEN 中是否含有 FINALLY 组件
*
* @param executable 判断对象
* @return 含有 FINALLY 组件返回 true,否则返回 false
*/
private boolean containsFinally(Executable executable) {
return executable instanceof ThenCondition
&& CollUtil.isNotEmpty(((ThenCondition) executable).getFinallyConditionList());
}
/**
* 将 FINALLY 排除在超时控制之外
*
* @param thenCondition 待处理的 ThenCondition
* @param maxWaitTime 最大等待时间
* @return 处理后的 ThenCondition
*/
private ThenCondition handleFinally(ThenCondition thenCondition, Integer maxWaitTime) {
// 进行如下转换
// THEN(PRE(a),b,FINALLY(c))
// => THEN(
// WHEN(THEN(PRE(a),b)),
// FINALLY(c))
// 定义外层 THEN
ThenCondition outerThenCondition = new ThenCondition();
// 把 FINALLY 转移到外层 THEN
List<Executable> finallyList = thenCondition.getExecutableList(ConditionKey.FINALLY_KEY);
finallyList.forEach(executable
-> outerThenCondition
.addFinallyCondition((FinallyCondition) executable));
finallyList.clear();
// 包装内部 THEN
WhenCondition whenCondition = wrappedByTimeout(thenCondition, maxWaitTime);
outerThenCondition.addExecutable(whenCondition);
return outerThenCondition;
}
/**
* 获取等待时间单位
*/
abstract TimeUnit getMaxWaitTimeUnit();
/**
* 操作符名称
*/
abstract String operatorName();
}
|
TimeoutCondition timeoutCondition = new TimeoutCondition();
timeoutCondition.addExecutable(executable);
timeoutCondition.setMaxWaitTime(maxWaitTime);
timeoutCondition.setMaxWaitTimeUnit(getMaxWaitTimeUnit());
return timeoutCondition;
| 878
| 65
| 943
|
<methods>public non-sealed void <init>() ,public abstract com.yomahub.liteflow.flow.element.Condition build(java.lang.Object[]) throws java.lang.Exception,public com.yomahub.liteflow.flow.element.Condition executeInner(java.lang.Object[]) throws java.lang.Exception<variables>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/builder/el/operator/MustOperator.java
|
MustOperator
|
build
|
class MustOperator extends BaseOperator<WhenCondition> {
@Override
public WhenCondition build(Object[] objects) throws Exception {<FILL_FUNCTION_BODY>}
}
|
OperatorHelper.checkObjectSizeGteTwo(objects);
String errorMsg = "The caller must be WhenCondition item";
WhenCondition whenCondition = OperatorHelper.convert(objects[0], WhenCondition.class, errorMsg);
// 解析指定完成的任务 ID 集合
Set<String> specifyIdSet = new HashSet<>();
for (int i = 1; i < objects.length; i++) {
Object task = objects[i];
if (task instanceof String) {
specifyIdSet.add(OperatorHelper.convert(task, String.class));
} else if (task instanceof Executable) {
specifyIdSet.add(OperatorHelper.convert(task, Executable.class).getId());
}
}
whenCondition.setSpecifyIdSet(specifyIdSet);
whenCondition.setParallelStrategy(ParallelStrategyEnum.SPECIFY);
return whenCondition;
| 44
| 241
| 285
|
<methods>public non-sealed void <init>() ,public abstract com.yomahub.liteflow.flow.element.condition.WhenCondition build(java.lang.Object[]) throws java.lang.Exception,public com.yomahub.liteflow.flow.element.condition.WhenCondition executeInner(java.lang.Object[]) throws java.lang.Exception<variables>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/builder/el/operator/NodeOperator.java
|
NodeOperator
|
build
|
class NodeOperator extends BaseOperator<Node> {
@Override
public Node build(Object[] objects) throws Exception {<FILL_FUNCTION_BODY>}
}
|
OperatorHelper.checkObjectSizeEqOne(objects);
String nodeId = OperatorHelper.convert(objects[0], String.class);
if (FlowBus.containNode(nodeId)) {
// 找到对应节点
return FlowBus.getNode(nodeId);
} else {
// 生成代理节点
return new FallbackNode(nodeId);
}
| 44
| 101
| 145
|
<methods>public non-sealed void <init>() ,public abstract com.yomahub.liteflow.flow.element.Node build(java.lang.Object[]) throws java.lang.Exception,public com.yomahub.liteflow.flow.element.Node executeInner(java.lang.Object[]) throws java.lang.Exception<variables>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/builder/el/operator/NotOperator.java
|
NotOperator
|
build
|
class NotOperator extends BaseOperator<NotCondition> {
@Override
public NotCondition build(Object[] objects) throws Exception {<FILL_FUNCTION_BODY>}
}
|
OperatorHelper.checkObjectSizeEqOne(objects);
Object object = objects[0];
OperatorHelper.checkObjMustBeBooleanTypeItem(object);
Executable item = OperatorHelper.convert(object, Executable.class);
NotCondition notCondition = new NotCondition();
notCondition.setItem(item);
return notCondition;
| 44
| 91
| 135
|
<methods>public non-sealed void <init>() ,public abstract com.yomahub.liteflow.flow.element.condition.NotCondition build(java.lang.Object[]) throws java.lang.Exception,public com.yomahub.liteflow.flow.element.condition.NotCondition executeInner(java.lang.Object[]) throws java.lang.Exception<variables>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/builder/el/operator/OrOperator.java
|
OrOperator
|
build
|
class OrOperator extends BaseOperator<AndOrCondition> {
@Override
public AndOrCondition build(Object[] objects) throws Exception {<FILL_FUNCTION_BODY>}
}
|
OperatorHelper.checkObjectSizeGteTwo(objects);
AndOrCondition andOrCondition = new AndOrCondition();
andOrCondition.setBooleanConditionType(BooleanConditionTypeEnum.OR);
for (Object object : objects){
OperatorHelper.checkObjMustBeBooleanTypeItem(object);
Executable item = OperatorHelper.convert(object, Executable.class);
andOrCondition.addItem(item);
}
return andOrCondition;
| 46
| 119
| 165
|
<methods>public non-sealed void <init>() ,public abstract com.yomahub.liteflow.flow.element.condition.AndOrCondition build(java.lang.Object[]) throws java.lang.Exception,public com.yomahub.liteflow.flow.element.condition.AndOrCondition executeInner(java.lang.Object[]) throws java.lang.Exception<variables>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/builder/el/operator/ParallelOperator.java
|
ParallelOperator
|
build
|
class ParallelOperator extends BaseOperator<LoopCondition> {
@Override
public LoopCondition build(Object[] objects) throws Exception {<FILL_FUNCTION_BODY>}
}
|
OperatorHelper.checkObjectSizeEqTwo(objects);
String errorMsg = "The caller must be LoopCondition item";
LoopCondition loopCondition = OperatorHelper.convert(objects[0], LoopCondition.class, errorMsg);
Boolean parallel = OperatorHelper.convert(objects[1], Boolean.class);
loopCondition.setParallel(parallel);
return loopCondition;
| 46
| 99
| 145
|
<methods>public non-sealed void <init>() ,public abstract com.yomahub.liteflow.flow.element.condition.LoopCondition build(java.lang.Object[]) throws java.lang.Exception,public com.yomahub.liteflow.flow.element.condition.LoopCondition executeInner(java.lang.Object[]) throws java.lang.Exception<variables>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/builder/el/operator/PreOperator.java
|
PreOperator
|
build
|
class PreOperator extends BaseOperator<PreCondition> {
@Override
public PreCondition build(Object[] objects) throws Exception {<FILL_FUNCTION_BODY>}
}
|
OperatorHelper.checkObjectSizeGtZero(objects);
PreCondition preCondition = new PreCondition();
for (Object obj : objects) {
OperatorHelper.checkObjMustBeCommonTypeItem(obj);
preCondition.addExecutable(OperatorHelper.convert(obj, Executable.class));
}
return preCondition;
| 44
| 88
| 132
|
<methods>public non-sealed void <init>() ,public abstract com.yomahub.liteflow.flow.element.condition.PreCondition build(java.lang.Object[]) throws java.lang.Exception,public com.yomahub.liteflow.flow.element.condition.PreCondition executeInner(java.lang.Object[]) throws java.lang.Exception<variables>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/builder/el/operator/RetryOperator.java
|
RetryOperator
|
build
|
class RetryOperator extends BaseOperator<Condition> {
@Override
public Condition build(Object[] objects) throws Exception {<FILL_FUNCTION_BODY>}
}
|
OperatorHelper.checkObjectSizeGteTwo(objects);
Executable executable = OperatorHelper.convert(objects[0], Executable.class);
Integer retryTimes = OperatorHelper.convert(objects[1], Integer.class);
RetryCondition retryCondition = new RetryCondition();
retryCondition.addExecutable(executable);
retryCondition.setRetryTimes(retryTimes);
if(objects.length > 2) {
Class[] forExceptions = new Class[objects.length - 2];
for(int i = 2; i < objects.length; i ++) {
String className = OperatorHelper.convert(objects[i], String.class);
forExceptions[i - 2] = Class.forName(className);
}
retryCondition.setRetryForExceptions(forExceptions);
}
return retryCondition;
| 44
| 218
| 262
|
<methods>public non-sealed void <init>() ,public abstract com.yomahub.liteflow.flow.element.Condition build(java.lang.Object[]) throws java.lang.Exception,public com.yomahub.liteflow.flow.element.Condition executeInner(java.lang.Object[]) throws java.lang.Exception<variables>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/builder/el/operator/SwitchOperator.java
|
SwitchOperator
|
build
|
class SwitchOperator extends BaseOperator<SwitchCondition> {
@Override
public SwitchCondition build(Object[] objects) throws Exception {<FILL_FUNCTION_BODY>}
}
|
OperatorHelper.checkObjectSizeEqOne(objects);
OperatorHelper.checkObjMustBeSwitchTypeItem(objects[0]);
Node switchNode = OperatorHelper.convert(objects[0], Node.class);
SwitchCondition switchCondition = new SwitchCondition();
switchCondition.setSwitchNode(switchNode);
return switchCondition;
| 44
| 90
| 134
|
<methods>public non-sealed void <init>() ,public abstract com.yomahub.liteflow.flow.element.condition.SwitchCondition build(java.lang.Object[]) throws java.lang.Exception,public com.yomahub.liteflow.flow.element.condition.SwitchCondition executeInner(java.lang.Object[]) throws java.lang.Exception<variables>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/builder/el/operator/TagOperator.java
|
TagOperator
|
build
|
class TagOperator extends BaseOperator<Executable> {
@Override
public Executable build(Object[] objects) throws Exception {<FILL_FUNCTION_BODY>}
}
|
OperatorHelper.checkObjectSizeEqTwo(objects);
Executable refObj = OperatorHelper.convert(objects[0], Executable.class);
String tag = OperatorHelper.convert(objects[1], String.class);
//如果解析的对象是一个Chain,由于Chain对象全局唯一,无法再进行复制
//所以如果要给chain设置tag,则需要套上一个THEN,在THEN上面设置tag
if (refObj instanceof Chain){
ThenCondition wrapperChainCondition = new ThenCondition();
wrapperChainCondition.setExecutableList(ListUtil.toList(refObj));
wrapperChainCondition.setTag(tag);
return wrapperChainCondition;
}else{
refObj.setTag(tag);
return refObj;
}
| 43
| 198
| 241
|
<methods>public non-sealed void <init>() ,public abstract com.yomahub.liteflow.flow.element.Executable build(java.lang.Object[]) throws java.lang.Exception,public com.yomahub.liteflow.flow.element.Executable executeInner(java.lang.Object[]) throws java.lang.Exception<variables>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/builder/el/operator/ThenOperator.java
|
ThenOperator
|
build
|
class ThenOperator extends BaseOperator<ThenCondition> {
@Override
public ThenCondition build(Object[] objects) throws Exception {<FILL_FUNCTION_BODY>}
}
|
OperatorHelper.checkObjectSizeGtZero(objects);
ThenCondition thenCondition = new ThenCondition();
for (Object obj : objects) {
OperatorHelper.checkObjMustBeCommonTypeItem(obj);
thenCondition.addExecutable(OperatorHelper.convert(obj, Executable.class));
}
return thenCondition;
| 44
| 88
| 132
|
<methods>public non-sealed void <init>() ,public abstract com.yomahub.liteflow.flow.element.condition.ThenCondition build(java.lang.Object[]) throws java.lang.Exception,public com.yomahub.liteflow.flow.element.condition.ThenCondition executeInner(java.lang.Object[]) throws java.lang.Exception<variables>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/builder/el/operator/ThreadPoolOperator.java
|
ThreadPoolOperator
|
build
|
class ThreadPoolOperator extends BaseOperator<WhenCondition> {
@Override
public WhenCondition build(Object[] objects) throws Exception {<FILL_FUNCTION_BODY>}
}
|
OperatorHelper.checkObjectSizeEqTwo(objects);
String errorMsg = "The caller must be WhenCondition item";
WhenCondition whenCondition = OperatorHelper.convert(objects[0], WhenCondition.class, errorMsg);
whenCondition.setThreadExecutorClass(OperatorHelper.convert(objects[1], String.class));
return whenCondition;
| 45
| 92
| 137
|
<methods>public non-sealed void <init>() ,public abstract com.yomahub.liteflow.flow.element.condition.WhenCondition build(java.lang.Object[]) throws java.lang.Exception,public com.yomahub.liteflow.flow.element.condition.WhenCondition executeInner(java.lang.Object[]) throws java.lang.Exception<variables>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/builder/el/operator/ToOperator.java
|
ToOperator
|
build
|
class ToOperator extends BaseOperator<SwitchCondition> {
@Override
public SwitchCondition build(Object[] objects) throws Exception {<FILL_FUNCTION_BODY>}
}
|
OperatorHelper.checkObjectSizeGteTwo(objects);
String errorMsg = "The caller must be SwitchCondition item";
SwitchCondition switchCondition = OperatorHelper.convert(objects[0], SwitchCondition.class, errorMsg);
for (int i = 1; i < objects.length; i++) {
OperatorHelper.checkObjMustBeCommonTypeItem(objects[i]);
Executable target = OperatorHelper.convert(objects[i], Executable.class);
switchCondition.addTargetItem(target);
}
return switchCondition;
| 44
| 142
| 186
|
<methods>public non-sealed void <init>() ,public abstract com.yomahub.liteflow.flow.element.condition.SwitchCondition build(java.lang.Object[]) throws java.lang.Exception,public com.yomahub.liteflow.flow.element.condition.SwitchCondition executeInner(java.lang.Object[]) throws java.lang.Exception<variables>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/builder/el/operator/WhenOperator.java
|
WhenOperator
|
build
|
class WhenOperator extends BaseOperator<WhenCondition> {
@Override
public WhenCondition build(Object[] objects) throws Exception {<FILL_FUNCTION_BODY>}
}
|
OperatorHelper.checkObjectSizeGtZero(objects);
WhenCondition whenCondition = new WhenCondition();
LiteflowConfig liteflowConfig = LiteflowConfigGetter.get();
for (Object obj : objects) {
OperatorHelper.checkObjMustBeCommonTypeItem(obj);
whenCondition.addExecutable(OperatorHelper.convert(obj, Executable.class));
whenCondition.setThreadExecutorClass(liteflowConfig.getThreadExecutorClass());
}
return whenCondition;
| 44
| 131
| 175
|
<methods>public non-sealed void <init>() ,public abstract com.yomahub.liteflow.flow.element.condition.WhenCondition build(java.lang.Object[]) throws java.lang.Exception,public com.yomahub.liteflow.flow.element.condition.WhenCondition executeInner(java.lang.Object[]) throws java.lang.Exception<variables>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/builder/el/operator/WhileOperator.java
|
WhileOperator
|
build
|
class WhileOperator extends BaseOperator<WhileCondition> {
@Override
public WhileCondition build(Object[] objects) throws Exception {<FILL_FUNCTION_BODY>}
}
|
OperatorHelper.checkObjectSizeEqOne(objects);
OperatorHelper.checkObjMustBeBooleanTypeItem(objects[0]);
Executable whileItem = OperatorHelper.convert(objects[0], Executable.class);
WhileCondition whileCondition = new WhileCondition();
whileCondition.setWhileItem(whileItem);
return whileCondition;
| 44
| 91
| 135
|
<methods>public non-sealed void <init>() ,public abstract com.yomahub.liteflow.flow.element.condition.WhileCondition build(java.lang.Object[]) throws java.lang.Exception,public com.yomahub.liteflow.flow.element.condition.WhileCondition executeInner(java.lang.Object[]) throws java.lang.Exception<variables>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/builder/el/operator/base/BaseOperator.java
|
BaseOperator
|
executeInner
|
class BaseOperator<T extends Executable> extends Operator {
@Override
public T executeInner(Object[] objects) throws Exception {<FILL_FUNCTION_BODY>}
/**
* 构建 EL 条件
* @param objects objects
* @return Condition
* @throws Exception Exception
*/
public abstract T build(Object[] objects) throws Exception;
}
|
try {
OperatorHelper.checkItemNotNull(objects);
return build(objects);
}
catch (QLException e) {
throw e;
}
catch (Exception e) {
throw new ELParseException("errors occurred in EL parsing");
}
| 93
| 77
| 170
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/core/ComponentInitializer.java
|
ComponentInitializer
|
buildNodeExecutorClass
|
class ComponentInitializer {
private static ComponentInitializer instance;
public static ComponentInitializer loadInstance() {
if (ObjectUtil.isNull(instance)) {
instance = new ComponentInitializer();
}
return instance;
}
public NodeComponent initComponent(NodeComponent nodeComponent, NodeTypeEnum type, String name, String nodeId) {
nodeComponent.setNodeId(nodeId);
nodeComponent.setSelf(nodeComponent);
nodeComponent.setType(type);
// 设置MonitorBus,如果没有就不注入
if (ContextAwareHolder.loadContextAware().hasBean(ChainConstant.MONITOR_BUS)) {
MonitorBus monitorBus = ContextAwareHolder.loadContextAware().getBean(MonitorBus.class);
if (ObjectUtil.isNotNull(monitorBus)) {
nodeComponent.setMonitorBus(monitorBus);
}
}
// 先取传进来的name值(配置文件中配置的),再看有没有配置@LiteflowComponent标注
// @LiteflowComponent标注只在spring体系下生效,这里用了spi机制取到相应环境下的实现类
nodeComponent.setName(name);
if (!type.isScript() && StrUtil.isBlank(nodeComponent.getName())) {
nodeComponent
.setName(LiteflowComponentSupportHolder.loadLiteflowComponentSupport().getCmpName(nodeComponent));
}
// 先从组件上取@RetryCount标注,如果没有,则看全局配置,全局配置如果不配置的话,默认是0
// 默认retryForExceptions为Exception.class
LiteflowRetry liteFlowRetryAnnotation = AnnoUtil.getAnnotation(nodeComponent.getClass(), LiteflowRetry.class);
LiteflowConfig liteflowConfig = LiteflowConfigGetter.get();
if (liteFlowRetryAnnotation != null) {
nodeComponent.setRetryCount(liteFlowRetryAnnotation.retry());
nodeComponent.setRetryForExceptions(liteFlowRetryAnnotation.forExceptions());
}
else {
nodeComponent.setRetryCount(liteflowConfig.getRetryCount());
}
nodeComponent.setNodeExecutorClass(buildNodeExecutorClass(liteflowConfig));
return nodeComponent;
}
private Class<? extends NodeExecutor> buildNodeExecutorClass(LiteflowConfig liteflowConfig) {<FILL_FUNCTION_BODY>}
}
|
Class<?> nodeExecutorClass;
try {
nodeExecutorClass = Class.forName(liteflowConfig.getNodeExecutorClass());
}
catch (ClassNotFoundException e) {
throw new RuntimeException(e.getMessage());
}
return (Class<? extends NodeExecutor>) nodeExecutorClass;
| 625
| 86
| 711
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/core/FlowExecutorHolder.java
|
FlowExecutorHolder
|
loadInstance
|
class FlowExecutorHolder {
private static FlowExecutor flowExecutor;
public static FlowExecutor loadInstance(LiteflowConfig liteflowConfig) {
if (ObjectUtil.isNull(flowExecutor)) {
flowExecutor = new FlowExecutor(liteflowConfig);
}
return flowExecutor;
}
public static FlowExecutor loadInstance() {<FILL_FUNCTION_BODY>}
public static void setHolder(FlowExecutor flowExecutor) {
FlowExecutorHolder.flowExecutor = flowExecutor;
}
public static void clean() {
flowExecutor = null;
}
}
|
if (ObjectUtil.isNull(flowExecutor)) {
throw new FlowExecutorNotInitException("flow executor is not initialized yet");
}
return flowExecutor;
| 146
| 45
| 191
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/core/NodeForComponent.java
|
NodeForComponent
|
process
|
class NodeForComponent extends NodeComponent {
@Override
public void process() throws Exception {<FILL_FUNCTION_BODY>}
public abstract int processFor() throws Exception;
@Override
@SuppressWarnings("unchecked")
public Integer getItemResultMetaValue(Integer slotIndex) {
return DataBus.getSlot(slotIndex).getForResult(this.getMetaValueKey());
}
}
|
int forCount = processFor();
Slot slot = this.getSlot();
slot.setForResult(this.getMetaValueKey(), forCount);
| 103
| 45
| 148
|
<methods>public void <init>() ,public void afterProcess() ,public void beforeProcess() ,public void doRollback() throws java.lang.Exception,public void execute() throws java.lang.Exception,public java.lang.String getChainId() ,public java.lang.String getChainName() ,public T getCmpData(Class<T>) ,public T getContextBean(Class<T>) ,public T getContextBean(java.lang.String) ,public java.lang.String getCurrChainId() ,public T getCurrLoopObj() ,public java.lang.String getDisplayName() ,public T getFirstContextBean() ,public T getItemResultMetaValue(java.lang.Integer) ,public java.lang.Integer getLoopIndex() ,public com.yomahub.liteflow.monitor.MonitorBus getMonitorBus() ,public java.lang.String getName() ,public Class<? extends com.yomahub.liteflow.flow.executor.NodeExecutor> getNodeExecutorClass() ,public java.lang.String getNodeId() ,public T getPrivateDeliveryData() ,public com.yomahub.liteflow.flow.element.Node getRefNode() ,public T getRequestData() ,public int getRetryCount() ,public Class<? extends java.lang.Exception>[] getRetryForExceptions() ,public com.yomahub.liteflow.core.NodeComponent getSelf() ,public com.yomahub.liteflow.slot.Slot getSlot() ,public java.lang.Integer getSlotIndex() ,public T getSubChainReqData() ,public T getSubChainReqDataInAsync() ,public java.lang.String getTag() ,public com.yomahub.liteflow.enums.NodeTypeEnum getType() ,public void invoke(java.lang.String, java.lang.Object) throws java.lang.Exception,public com.yomahub.liteflow.flow.LiteflowResponse invoke2Resp(java.lang.String, java.lang.Object) ,public com.yomahub.liteflow.flow.LiteflowResponse invoke2RespInAsync(java.lang.String, java.lang.Object) ,public void invokeInAsync(java.lang.String, java.lang.Object) throws java.lang.Exception,public boolean isAccess() ,public boolean isContinueOnError() ,public boolean isEnd() ,public boolean isRollback() ,public void onError(java.lang.Exception) throws java.lang.Exception,public void onSuccess() throws java.lang.Exception,public abstract void process() throws java.lang.Exception,public void removeRefNode() ,public void rollback() throws java.lang.Exception,public void sendPrivateDeliveryData(java.lang.String, T) ,public void setIsContinueOnError(boolean) ,public void setIsEnd(boolean) ,public void setMonitorBus(com.yomahub.liteflow.monitor.MonitorBus) ,public void setName(java.lang.String) ,public void setNodeExecutorClass(Class<? extends com.yomahub.liteflow.flow.executor.NodeExecutor>) ,public void setNodeId(java.lang.String) ,public void setRefNode(com.yomahub.liteflow.flow.element.Node) ,public void setRetryCount(int) ,public void setRetryForExceptions(Class<? extends java.lang.Exception>[]) ,public void setRollback(boolean) ,public void setSelf(com.yomahub.liteflow.core.NodeComponent) ,public void setType(com.yomahub.liteflow.enums.NodeTypeEnum) <variables>private final com.yomahub.liteflow.log.LFLog LOG,private boolean isRollback,private com.yomahub.liteflow.monitor.MonitorBus monitorBus,private java.lang.String name,private Class<? extends com.yomahub.liteflow.flow.executor.NodeExecutor> nodeExecutorClass,private java.lang.String nodeId,private final TransmittableThreadLocal<com.yomahub.liteflow.flow.element.Node> refNodeTL,private int retryCount,private Class<? extends java.lang.Exception>[] retryForExceptions,private com.yomahub.liteflow.core.NodeComponent self,private com.yomahub.liteflow.enums.NodeTypeEnum type
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/core/NodeIteratorComponent.java
|
NodeIteratorComponent
|
process
|
class NodeIteratorComponent extends NodeComponent {
@Override
public void process() throws Exception {<FILL_FUNCTION_BODY>}
public abstract Iterator<?> processIterator() throws Exception;
@Override
@SuppressWarnings("unchecked")
public Iterator<?> getItemResultMetaValue(Integer slotIndex) {
return DataBus.getSlot(slotIndex).getIteratorResult(this.getMetaValueKey());
}
}
|
Iterator<?> it = processIterator();
Slot slot = this.getSlot();
slot.setIteratorResult(this.getMetaValueKey(), it);
| 111
| 47
| 158
|
<methods>public void <init>() ,public void afterProcess() ,public void beforeProcess() ,public void doRollback() throws java.lang.Exception,public void execute() throws java.lang.Exception,public java.lang.String getChainId() ,public java.lang.String getChainName() ,public T getCmpData(Class<T>) ,public T getContextBean(Class<T>) ,public T getContextBean(java.lang.String) ,public java.lang.String getCurrChainId() ,public T getCurrLoopObj() ,public java.lang.String getDisplayName() ,public T getFirstContextBean() ,public T getItemResultMetaValue(java.lang.Integer) ,public java.lang.Integer getLoopIndex() ,public com.yomahub.liteflow.monitor.MonitorBus getMonitorBus() ,public java.lang.String getName() ,public Class<? extends com.yomahub.liteflow.flow.executor.NodeExecutor> getNodeExecutorClass() ,public java.lang.String getNodeId() ,public T getPrivateDeliveryData() ,public com.yomahub.liteflow.flow.element.Node getRefNode() ,public T getRequestData() ,public int getRetryCount() ,public Class<? extends java.lang.Exception>[] getRetryForExceptions() ,public com.yomahub.liteflow.core.NodeComponent getSelf() ,public com.yomahub.liteflow.slot.Slot getSlot() ,public java.lang.Integer getSlotIndex() ,public T getSubChainReqData() ,public T getSubChainReqDataInAsync() ,public java.lang.String getTag() ,public com.yomahub.liteflow.enums.NodeTypeEnum getType() ,public void invoke(java.lang.String, java.lang.Object) throws java.lang.Exception,public com.yomahub.liteflow.flow.LiteflowResponse invoke2Resp(java.lang.String, java.lang.Object) ,public com.yomahub.liteflow.flow.LiteflowResponse invoke2RespInAsync(java.lang.String, java.lang.Object) ,public void invokeInAsync(java.lang.String, java.lang.Object) throws java.lang.Exception,public boolean isAccess() ,public boolean isContinueOnError() ,public boolean isEnd() ,public boolean isRollback() ,public void onError(java.lang.Exception) throws java.lang.Exception,public void onSuccess() throws java.lang.Exception,public abstract void process() throws java.lang.Exception,public void removeRefNode() ,public void rollback() throws java.lang.Exception,public void sendPrivateDeliveryData(java.lang.String, T) ,public void setIsContinueOnError(boolean) ,public void setIsEnd(boolean) ,public void setMonitorBus(com.yomahub.liteflow.monitor.MonitorBus) ,public void setName(java.lang.String) ,public void setNodeExecutorClass(Class<? extends com.yomahub.liteflow.flow.executor.NodeExecutor>) ,public void setNodeId(java.lang.String) ,public void setRefNode(com.yomahub.liteflow.flow.element.Node) ,public void setRetryCount(int) ,public void setRetryForExceptions(Class<? extends java.lang.Exception>[]) ,public void setRollback(boolean) ,public void setSelf(com.yomahub.liteflow.core.NodeComponent) ,public void setType(com.yomahub.liteflow.enums.NodeTypeEnum) <variables>private final com.yomahub.liteflow.log.LFLog LOG,private boolean isRollback,private com.yomahub.liteflow.monitor.MonitorBus monitorBus,private java.lang.String name,private Class<? extends com.yomahub.liteflow.flow.executor.NodeExecutor> nodeExecutorClass,private java.lang.String nodeId,private final TransmittableThreadLocal<com.yomahub.liteflow.flow.element.Node> refNodeTL,private int retryCount,private Class<? extends java.lang.Exception>[] retryForExceptions,private com.yomahub.liteflow.core.NodeComponent self,private com.yomahub.liteflow.enums.NodeTypeEnum type
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/core/ScriptBooleanComponent.java
|
ScriptBooleanComponent
|
processBoolean
|
class ScriptBooleanComponent extends NodeBooleanComponent implements ScriptComponent {
@Override
public boolean processBoolean() throws Exception {<FILL_FUNCTION_BODY>}
@Override
public void loadScript(String script, String language) {
ScriptExecutorFactory.loadInstance().getScriptExecutor(language).load(getNodeId(), script);
}
}
|
ScriptExecuteWrap wrap = this.buildWrap(this);
return (boolean) ScriptExecutorFactory.loadInstance()
.getScriptExecutor(this.getRefNode().getLanguage())
.execute(wrap);
| 84
| 54
| 138
|
<methods>public non-sealed void <init>() ,public java.lang.Boolean getItemResultMetaValue(java.lang.Integer) ,public void process() throws java.lang.Exception,public abstract boolean processBoolean() throws java.lang.Exception<variables>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/core/ScriptForComponent.java
|
ScriptForComponent
|
processFor
|
class ScriptForComponent extends NodeForComponent implements ScriptComponent {
@Override
public int processFor() throws Exception {<FILL_FUNCTION_BODY>}
@Override
public void loadScript(String script, String language) {
ScriptExecutorFactory.loadInstance().getScriptExecutor(language).load(getNodeId(), script);
}
}
|
ScriptExecuteWrap wrap = this.buildWrap(this);
return (int) ScriptExecutorFactory.loadInstance()
.getScriptExecutor(this.getRefNode().getLanguage())
.execute(wrap);
| 84
| 54
| 138
|
<methods>public non-sealed void <init>() ,public java.lang.Integer getItemResultMetaValue(java.lang.Integer) ,public void process() throws java.lang.Exception,public abstract int processFor() throws java.lang.Exception<variables>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/core/ScriptSwitchComponent.java
|
ScriptSwitchComponent
|
processSwitch
|
class ScriptSwitchComponent extends NodeSwitchComponent implements ScriptComponent {
@Override
public String processSwitch() throws Exception {<FILL_FUNCTION_BODY>}
@Override
public void loadScript(String script, String language) {
ScriptExecutorFactory.loadInstance().getScriptExecutor(language).load(getNodeId(), script);
}
}
|
ScriptExecuteWrap wrap = this.buildWrap(this);
return (String) ScriptExecutorFactory.loadInstance()
.getScriptExecutor(this.getRefNode().getLanguage())
.execute(wrap);
| 84
| 54
| 138
|
<methods>public non-sealed void <init>() ,public java.lang.String getItemResultMetaValue(java.lang.Integer) ,public void process() throws java.lang.Exception,public abstract java.lang.String processSwitch() throws java.lang.Exception<variables>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/core/proxy/DeclComponentProxy.java
|
AopInvocationHandler
|
invoke
|
class AopInvocationHandler implements InvocationHandler {
private DeclWarpBean declWarpBean;
public AopInvocationHandler(DeclWarpBean declWarpBean) {
this.declWarpBean = declWarpBean;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {<FILL_FUNCTION_BODY>}
}
|
// 获取当前调用方法,是否在被代理的对象方法里面(根据@LiteFlowMethod这个标注去判断)
// 如果在里面,则返回那个LiteFlowMethodBean,不在则返回null
MethodWrapBean currentMethodWrapBean = declWarpBean.getMethodWrapBeanList().stream()
.filter(methodWrapBean -> methodWrapBean.getLiteflowMethod().value().getMethodName().equals(method.getName()))
.findFirst()
.orElse(null);
// 如果被代理的对象里有此标注标的方法,则调用此被代理的对象里的方法,如果没有,则调用父类里的方法
// 进行检查,检查被代理的bean里是否第一个参数为NodeComponent这个类型的
boolean checkFlag = currentMethodWrapBean.getMethod().getParameterTypes().length > 0
&& currentMethodWrapBean.getMethod().getParameterTypes()[0].equals(NodeComponent.class);
if (!checkFlag) {
String errMsg = StrUtil.format(
"Method[{}.{}] must have NodeComponent parameter(first parameter is NodeComponent)",
declWarpBean.getRawClazz().getName(), currentMethodWrapBean.getMethod().getName());
LOG.error(errMsg);
throw new ComponentMethodDefineErrorException(errMsg);
}
try {
if (args != null && args.length > 0){
Object[] wrapArgs = ArrayUtil.insert(args, 0, proxy);
return ReflectUtil.invoke(declWarpBean.getRawBean(), currentMethodWrapBean.getMethod(), wrapArgs);
}else{
return ReflectUtil.invoke(declWarpBean.getRawBean(), currentMethodWrapBean.getMethod(), proxy);
}
}catch (InvocationTargetRuntimeException e) {
InvocationTargetException targetEx = (InvocationTargetException) e.getCause();
throw targetEx.getTargetException();
}
| 104
| 475
| 579
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/core/proxy/LiteFlowProxyUtil.java
|
LiteFlowProxyUtil
|
getUserClass
|
class LiteFlowProxyUtil {
private static final LFLog LOG = LFLoggerManager.getLogger(LiteFlowProxyUtil.class);
/**
* 判断一个bean是否是声明式组件
*/
public static boolean isDeclareCmp(Class<?> clazz) {
// 查看bean里的method是否有方法标记了@LiteflowMethod标注
// 这里的bean有可能是cglib加强过的class,所以要先进行个判断
Class<?> targetClass = getUserClass(clazz);
// 判断是否有方法标记了@LiteflowMethod标注,有则为声明式组件
return Arrays.stream(targetClass.getMethods())
.anyMatch(method -> method.getAnnotation(LiteflowMethod.class) != null);
}
/**
* 对一个满足声明式的bean进行代理,生成代理类
*/
public static NodeComponent proxy2NodeComponent(DeclWarpBean declWarpBean) {
try {
DeclComponentProxy proxy = new DeclComponentProxy(declWarpBean);
return proxy.getProxy();
}catch (LiteFlowException liteFlowException) {
throw liteFlowException;
}catch (Exception e) {
String errMsg = StrUtil.format("Error while proxying bean[{}]", declWarpBean.getRawClazz().getName());
LOG.error(errMsg);
throw new ComponentProxyErrorException(errMsg);
}
}
public static boolean isCglibProxyClass(Class<?> clazz) {
return (clazz != null && isCglibProxyClassName(clazz.getName()));
}
public static Class<?> getUserClass(Class<?> clazz) {<FILL_FUNCTION_BODY>}
private static boolean isCglibProxyClassName(String className) {
return (className != null && className.contains("$$"));
}
}
|
if (clazz.getName().contains("$$")) {
Class<?> superclass = clazz.getSuperclass();
if (superclass != null && superclass != Object.class) {
return superclass;
}
}
return clazz;
| 480
| 71
| 551
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/flow/LiteflowResponse.java
|
LiteflowResponse
|
newResponse
|
class LiteflowResponse {
private String chainId;
private boolean success;
private String code;
private String message;
private Exception cause;
private Slot slot;
public LiteflowResponse() {
}
public static LiteflowResponse newMainResponse(Slot slot) {
return newResponse(slot, slot.getException());
}
public static LiteflowResponse newInnerResponse(String chainId, Slot slot) {
return newResponse(slot, slot.getSubException(chainId));
}
private static LiteflowResponse newResponse(Slot slot, Exception e) {<FILL_FUNCTION_BODY>}
public boolean isSuccess() {
return success;
}
public void setSuccess(final boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(final String message) {
this.message = message;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Exception getCause() {
return cause;
}
public void setCause(final Exception cause) {
this.cause = cause;
}
public Slot getSlot() {
return slot;
}
public void setSlot(Slot slot) {
this.slot = slot;
}
public <T> T getFirstContextBean() {
return this.getSlot().getFirstContextBean();
}
public <T> T getContextBean(Class<T> contextBeanClazz) {
return this.getSlot().getContextBean(contextBeanClazz);
}
public <T> T getContextBean(String contextName) {
return this.getSlot().getContextBean(contextName);
}
public Map<String, List<CmpStep>> getExecuteSteps() {
Map<String, List<CmpStep>> map = new LinkedHashMap<>();
this.getSlot().getExecuteSteps().forEach(cmpStep -> {
if (map.containsKey(cmpStep.getNodeId())){
map.get(cmpStep.getNodeId()).add(cmpStep);
}else{
map.put(cmpStep.getNodeId(), ListUtil.toList(cmpStep));
}
});
return map;
}
public Queue<CmpStep> getRollbackStepQueue() {
return this.getSlot().getRollbackSteps();
}
public String getRollbackStepStr() {
return getRollbackStepStrWithoutTime();
}
public String getRollbackStepStrWithTime() {
return this.getSlot().getRollbackStepStr(true);
}
public String getRollbackStepStrWithoutTime() {
return this.getSlot().getRollbackStepStr(false);
}
public Map<String, List<CmpStep>> getRollbackSteps() {
Map<String, List<CmpStep>> map = new LinkedHashMap<>();
this.getSlot().getRollbackSteps().forEach(cmpStep -> {
if (map.containsKey(cmpStep.getNodeId())){
map.get(cmpStep.getNodeId()).add(cmpStep);
}else{
map.put(cmpStep.getNodeId(), ListUtil.toList(cmpStep));
}
});
return map;
}
public Queue<CmpStep> getExecuteStepQueue() {
return this.getSlot().getExecuteSteps();
}
public String getExecuteStepStr() {
return getExecuteStepStrWithoutTime();
}
public String getExecuteStepStrWithTime() {
return this.getSlot().getExecuteStepStr(true);
}
public String getExecuteStepStrWithoutTime() {
return this.getSlot().getExecuteStepStr(false);
}
public String getRequestId() {
return this.getSlot().getRequestId();
}
public String getChainId() {
return chainId;
}
public void setChainId(String chainId) {
this.chainId = chainId;
}
}
|
LiteflowResponse response = new LiteflowResponse();
response.setChainId(slot.getChainId());
if (e != null) {
response.setSuccess(false);
response.setCause(e);
response.setMessage(response.getCause().getMessage());
response.setCode(response.getCause() instanceof LiteFlowException
? ((LiteFlowException) response.getCause()).getCode() : null);
}
else {
response.setSuccess(true);
}
response.setSlot(slot);
return response;
| 1,057
| 159
| 1,216
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/flow/element/Chain.java
|
Chain
|
execute
|
class Chain implements Executable{
private static final LFLog LOG = LFLoggerManager.getLogger(Chain.class);
private String chainId;
private Executable routeItem;
private List<Condition> conditionList = new ArrayList<>();
private String el;
private boolean isCompiled = true;
public Chain(String chainName) {
this.chainId = chainName;
}
public Chain() {
}
public Chain(String chainName, List<Condition> conditionList) {
this.chainId = chainName;
this.conditionList = conditionList;
}
public List<Condition> getConditionList() {
return conditionList;
}
public void setConditionList(List<Condition> conditionList) {
this.conditionList = conditionList;
}
/**
* @deprecated 请使用{@link #getChainId()}
*/
@Deprecated
public String getChainName() {
return chainId;
}
/**
* @param chainName
* @deprecated 请使用 {@link #setChainId(String)}
*/
public void setChainName(String chainName) {
this.chainId = chainName;
}
public String getChainId() {
return chainId;
}
public void setChainId(String chainId) {
this.chainId = chainId;
}
// 执行chain的主方法
@Override
public void execute(Integer slotIndex) throws Exception {<FILL_FUNCTION_BODY>}
public void executeRoute(Integer slotIndex) throws Exception {
if (routeItem == null) {
throw new FlowSystemException("no route condition or node in this chain[" + chainId + "]");
}
Slot slot = DataBus.getSlot(slotIndex);
try {
// 设置主ChainName
slot.setChainId(chainId);
// 执行决策路由
routeItem.setCurrChainId(chainId);
routeItem.execute(slotIndex);
boolean routeResult = routeItem.getItemResultMetaValue(slotIndex);
slot.setRouteResult(routeResult);
}
catch (ChainEndException e) {
throw e;
}
catch (Exception e) {
slot.setException(e);
throw e;
}
}
@Override
public ExecuteableTypeEnum getExecuteType() {
return ExecuteableTypeEnum.CHAIN;
}
@Override
public void setId(String id) {
this.chainId = id;
}
@Override
public String getId() {
return chainId;
}
@Override
public void setTag(String tag) {
//do nothing
}
@Override
public String getTag() {
return null;
}
public Executable getRouteItem() {
return routeItem;
}
public void setRouteItem(Executable routeItem) {
this.routeItem = routeItem;
}
public String getEl() {
return el;
}
public void setEl(String el) {
this.el = el;
}
public boolean isCompiled() {
return isCompiled;
}
public void setCompiled(boolean compiled) {
isCompiled = compiled;
}
}
|
if (BooleanUtil.isFalse(isCompiled)) {
LiteFlowChainELBuilder.buildUnCompileChain(this);
}
if (CollUtil.isEmpty(conditionList)) {
throw new FlowSystemException("no conditionList in this chain[" + chainId + "]");
}
Slot slot = DataBus.getSlot(slotIndex);
try {
// 设置主ChainName
slot.setChainId(chainId);
// 执行主体Condition
for (Condition condition : conditionList) {
condition.setCurrChainId(chainId);
condition.execute(slotIndex);
}
}
catch (ChainEndException e) {
// 这里单独catch ChainEndException是因为ChainEndException是用户自己setIsEnd抛出的异常
// 是属于正常逻辑,所以会在FlowExecutor中判断。这里不作为异常处理
throw e;
}
catch (Exception e) {
// 这里事先取到exception set到slot里,为了方便finally取到exception
if (slot.isSubChain(chainId)) {
slot.setSubException(chainId, e);
}
else {
slot.setException(e);
}
throw e;
}
| 826
| 330
| 1,156
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/flow/element/Condition.java
|
Condition
|
getExecutableOne
|
class Condition implements Executable{
private String id;
private String tag;
/**
* 可执行元素的集合
*/
private final Map<String, List<Executable>> executableGroup = new HashMap<>();
/**
* 当前所在的ChainName 如果对于子流程来说,那这个就是子流程所在的Chain
*/
private String currChainId;
@Override
public void execute(Integer slotIndex) throws Exception {
Slot slot = DataBus.getSlot(slotIndex);
try {
// 当前 Condition 入栈
slot.pushCondition(this);
executeCondition(slotIndex);
}
catch (ChainEndException e) {
// 这里单独catch ChainEndException是因为ChainEndException是用户自己setIsEnd抛出的异常
// 是属于正常逻辑,所以会在FlowExecutor中判断。这里不作为异常处理
throw e;
}
catch (Exception e) {
String chainId = this.getCurrChainId();
// 这里事先取到exception set到slot里,为了方便finally取到exception
if (slot.isSubChain(chainId)) {
slot.setSubException(chainId, e);
}
else {
slot.setException(e);
}
throw e;
} finally {
// 当前 Condition 出栈
slot.popCondition();
}
}
public abstract void executeCondition(Integer slotIndex) throws Exception;
@Override
public ExecuteableTypeEnum getExecuteType() {
return ExecuteableTypeEnum.CONDITION;
}
public List<Executable> getExecutableList() {
return getExecutableList(ConditionKey.DEFAULT_KEY);
}
public List<Executable> getExecutableList(String groupKey) {
List<Executable> executableList = this.executableGroup.get(groupKey);
if (CollUtil.isEmpty(executableList)) {
executableList = new ArrayList<>();
}
return executableList;
}
public Executable getExecutableOne(String groupKey) {<FILL_FUNCTION_BODY>}
public List<Node> getAllNodeInCondition(){
List<Executable> executableList = this.executableGroup.entrySet().stream().flatMap(
(Function<Map.Entry<String, List<Executable>>, Stream<Executable>>) entry -> entry.getValue().stream()
).collect(Collectors.toList());
List<Node> resultList = new ArrayList<>();
executableList.stream().forEach(executable -> {
if (executable instanceof Condition){
resultList.addAll(((Condition)executable).getAllNodeInCondition());
}else if(executable instanceof Node){
resultList.add((Node)executable);
}
});
return resultList;
}
public void setExecutableList(List<Executable> executableList) {
this.executableGroup.put(ConditionKey.DEFAULT_KEY, executableList);
}
public void addExecutable(Executable executable) {
addExecutable(ConditionKey.DEFAULT_KEY, executable);
}
public void addExecutable(String groupKey, Executable executable) {
if (ObjectUtil.isNull(executable)) {
return;
}
List<Executable> executableList = this.executableGroup.get(groupKey);
if (CollUtil.isEmpty(executableList)) {
this.executableGroup.put(groupKey, ListUtil.toList(executable));
}
else {
this.executableGroup.get(groupKey).add(executable);
}
}
public abstract ConditionTypeEnum getConditionType();
@Override
public String getId() {
if (StrUtil.isBlank(this.id)){
return StrUtil.format("condition-{}",this.getConditionType().getName());
}else{
return id;
}
}
@Override
public void setId(String id) {
this.id = id;
}
@Override
public String getTag() {
return tag;
}
@Override
public void setTag(String tag) {
this.tag = tag;
}
/**
* 请使用 {@link #setCurrChainId(String)}
*/
@Deprecated
public String getCurrChainName() {
return currChainId;
}
public String getCurrChainId() {
return currChainId;
}
@Override
public void setCurrChainId(String currChainId) {
this.currChainId = currChainId;
}
public Map<String, List<Executable>> getExecutableGroup() {
return executableGroup;
}
}
|
List<Executable> list = getExecutableList(groupKey);
if (CollUtil.isEmpty(list)) {
return null;
}
else {
return list.get(0);
}
| 1,192
| 57
| 1,249
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/flow/element/FallbackNode.java
|
FallbackNode
|
loadFallBackNode
|
class FallbackNode extends Node {
// 原节点 id
private String expectedNodeId;
// 降级节点
private Node fallbackNode;
public FallbackNode() {
this.setType(NodeTypeEnum.FALLBACK);
}
public FallbackNode(String expectedNodeId) {
this();
this.expectedNodeId = expectedNodeId;
}
@Override
public void execute(Integer slotIndex) throws Exception {
Node node = FlowBus.getNode(this.expectedNodeId);
if (node != null){
this.fallbackNode = node;
}else{
loadFallBackNode(slotIndex);
}
this.fallbackNode.setCurrChainId(this.getCurrChainId());
this.fallbackNode.execute(slotIndex);
}
private void loadFallBackNode(Integer slotIndex) throws Exception {<FILL_FUNCTION_BODY>}
private Node findFallbackNode(Condition condition) {
ConditionTypeEnum conditionType = condition.getConditionType();
switch (conditionType) {
case TYPE_THEN:
case TYPE_WHEN:
case TYPE_PRE:
case TYPE_FINALLY:
case TYPE_CATCH:
return FlowBus.getFallBackNode(NodeTypeEnum.COMMON);
case TYPE_IF:
return findNodeInIf((IfCondition) condition);
case TYPE_SWITCH:
return findNodeInSwitch((SwitchCondition) condition);
case TYPE_FOR:
return findNodeInFor((ForCondition) condition);
case TYPE_WHILE:
return findNodeInWhile((WhileCondition) condition);
case TYPE_ITERATOR:
return findNodeInIterator((IteratorCondition) condition);
case TYPE_NOT_OPT:
case TYPE_AND_OR_OPT:
//组件降级用在与并或中,只能用在IF表达式中
return FlowBus.getFallBackNode(NodeTypeEnum.BOOLEAN);
default:
return null;
}
}
private Node findNodeInIf(IfCondition ifCondition) {
Executable ifItem = ifCondition.getIfItem();
if (ifItem == this) {
// 需要条件组件
return FlowBus.getFallBackNode(NodeTypeEnum.BOOLEAN);
}
// 需要普通组件
return FlowBus.getFallBackNode(NodeTypeEnum.COMMON);
}
private Node findNodeInSwitch(SwitchCondition switchCondition) {
Node switchNode = switchCondition.getSwitchNode();
if (switchNode == this) {
return FlowBus.getFallBackNode(NodeTypeEnum.SWITCH);
}
return FlowBus.getFallBackNode(NodeTypeEnum.COMMON);
}
private Node findNodeInFor(ForCondition forCondition) {
Node forNode = forCondition.getForNode();
if (forNode == this) {
return FlowBus.getFallBackNode(NodeTypeEnum.FOR);
}
return findNodeInLoop(forCondition);
}
private Node findNodeInWhile(WhileCondition whileCondition) {
Executable whileItem = whileCondition.getWhileItem();
if (whileItem == this) {
return FlowBus.getFallBackNode(NodeTypeEnum.BOOLEAN);
}
return findNodeInLoop(whileCondition);
}
private Node findNodeInIterator(IteratorCondition iteratorCondition) {
Node iteratorNode = iteratorCondition.getIteratorNode();
if (iteratorNode == this) {
return FlowBus.getFallBackNode(NodeTypeEnum.ITERATOR);
}
return findNodeInLoop(iteratorCondition);
}
private Node findNodeInLoop(LoopCondition loopCondition) {
Executable breakItem = loopCondition.getExecutableOne(ConditionKey.BREAK_KEY);
if (breakItem == this) {
return FlowBus.getFallBackNode(NodeTypeEnum.BOOLEAN);
}
return FlowBus.getFallBackNode(NodeTypeEnum.COMMON);
}
@Override
public <T> T getItemResultMetaValue(Integer slotIndex) {
return this.fallbackNode.getItemResultMetaValue(slotIndex);
}
@Override
public boolean isAccess(Integer slotIndex) throws Exception {
// 可能会先访问这个方法,所以在这里就要加载降级节点
loadFallBackNode(slotIndex);
return this.fallbackNode.isAccess(slotIndex);
}
@Override
public NodeComponent getInstance() {
if (fallbackNode == null){
return null;
}
return fallbackNode.getInstance();
}
@Override
public String getId() {
return this.fallbackNode == null ? null : this.fallbackNode.getId();
}
@Override
public Node clone() {
// 代理节点不复制
return this;
}
@Override
public NodeTypeEnum getType() {
return NodeTypeEnum.FALLBACK;
}
public String getExpectedNodeId() {
return expectedNodeId;
}
public void setExpectedNodeId(String expectedNodeId) {
this.expectedNodeId = expectedNodeId;
}
}
|
if (ObjectUtil.isNotNull(this.fallbackNode)) {
// 已经加载过了
return;
}
Slot slot = DataBus.getSlot(slotIndex);
Condition curCondition = slot.getCurrentCondition();
if (ObjectUtil.isNull(curCondition)) {
throw new FlowSystemException("The current executing condition could not be found.");
}
Node node = findFallbackNode(curCondition);
if (ObjectUtil.isNull(node)) {
throw new FallbackCmpNotFoundException(
StrFormatter.format("No fallback component found for [{}] in chain[{}].", this.expectedNodeId,
this.getCurrChainId()));
}
// 使用 node 的副本
this.fallbackNode = node.clone();
| 1,352
| 200
| 1,552
|
<methods>public void <init>() ,public void <init>(com.yomahub.liteflow.core.NodeComponent) ,public com.yomahub.liteflow.flow.element.Node clone() throws java.lang.CloneNotSupportedException,public void execute(java.lang.Integer) throws java.lang.Exception,public boolean getAccessResult() ,public java.lang.String getClazz() ,public java.lang.String getCmpData() ,public java.lang.String getCurrChainId() ,public T getCurrLoopObject() ,public com.yomahub.liteflow.enums.ExecuteableTypeEnum getExecuteType() ,public java.lang.String getId() ,public com.yomahub.liteflow.core.NodeComponent getInstance() ,public boolean getIsContinueOnErrorResult() ,public java.lang.Boolean getIsEnd() ,public T getItemResultMetaValue(java.lang.Integer) ,public java.lang.String getLanguage() ,public java.lang.Integer getLoopIndex() ,public java.lang.String getName() ,public java.lang.String getScript() ,public java.lang.Integer getSlotIndex() ,public java.lang.String getTag() ,public com.yomahub.liteflow.enums.NodeTypeEnum getType() ,public boolean isAccess(java.lang.Integer) throws java.lang.Exception,public void removeAccessResult() ,public void removeCurrLoopObject() ,public void removeIsContinueOnErrorResult() ,public void removeIsEnd() ,public void removeLoopIndex() ,public void removeSlotIndex() ,public void rollback(java.lang.Integer) throws java.lang.Exception,public void setAccessResult(boolean) ,public void setClazz(java.lang.String) ,public void setCmpData(java.lang.String) ,public void setCurrChainId(java.lang.String) ,public void setCurrLoopObject(java.lang.Object) ,public void setId(java.lang.String) ,public void setInstance(com.yomahub.liteflow.core.NodeComponent) ,public void setIsContinueOnErrorResult(boolean) ,public void setIsEnd(java.lang.Boolean) ,public void setLanguage(java.lang.String) ,public void setLoopIndex(int) ,public void setName(java.lang.String) ,public void setScript(java.lang.String) ,public void setSlotIndex(java.lang.Integer) ,public void setTag(java.lang.String) ,public void setType(com.yomahub.liteflow.enums.NodeTypeEnum) <variables>private static final com.yomahub.liteflow.log.LFLog LOG,private TransmittableThreadLocal<java.lang.Boolean> accessResult,private java.lang.String clazz,private java.lang.String cmpData,private java.lang.String currChainId,private TransmittableThreadLocal<java.lang.Object> currLoopObject,private java.lang.String id,private com.yomahub.liteflow.core.NodeComponent instance,private TransmittableThreadLocal<java.lang.Boolean> isContinueOnErrorResult,private TransmittableThreadLocal<java.lang.Boolean> isEndTL,private java.lang.String language,private TransmittableThreadLocal<java.lang.Integer> loopIndexTL,private java.lang.String name,private java.lang.String script,private TransmittableThreadLocal<java.lang.Integer> slotIndexTL,private java.lang.String tag,private com.yomahub.liteflow.enums.NodeTypeEnum type
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/flow/element/condition/AbstractCondition.java
|
AbstractCondition
|
executeCondition
|
class AbstractCondition extends Condition {
@Override
public void executeCondition(Integer slotIndex) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public ConditionTypeEnum getConditionType() {
return ConditionTypeEnum.TYPE_ABSTRACT;
}
}
|
throw new ChainNotImplementedException(StrUtil.format("chain[{}] contains unimplemented variables, cannot be executed", this.getCurrChainId()));
| 71
| 43
| 114
|
<methods>public non-sealed void <init>() ,public void addExecutable(com.yomahub.liteflow.flow.element.Executable) ,public void addExecutable(java.lang.String, com.yomahub.liteflow.flow.element.Executable) ,public void execute(java.lang.Integer) throws java.lang.Exception,public abstract void executeCondition(java.lang.Integer) throws java.lang.Exception,public List<com.yomahub.liteflow.flow.element.Node> getAllNodeInCondition() ,public abstract com.yomahub.liteflow.enums.ConditionTypeEnum getConditionType() ,public java.lang.String getCurrChainId() ,public java.lang.String getCurrChainName() ,public Map<java.lang.String,List<com.yomahub.liteflow.flow.element.Executable>> getExecutableGroup() ,public List<com.yomahub.liteflow.flow.element.Executable> getExecutableList() ,public List<com.yomahub.liteflow.flow.element.Executable> getExecutableList(java.lang.String) ,public com.yomahub.liteflow.flow.element.Executable getExecutableOne(java.lang.String) ,public com.yomahub.liteflow.enums.ExecuteableTypeEnum getExecuteType() ,public java.lang.String getId() ,public java.lang.String getTag() ,public void setCurrChainId(java.lang.String) ,public void setExecutableList(List<com.yomahub.liteflow.flow.element.Executable>) ,public void setId(java.lang.String) ,public void setTag(java.lang.String) <variables>private java.lang.String currChainId,private final Map<java.lang.String,List<com.yomahub.liteflow.flow.element.Executable>> executableGroup,private java.lang.String id,private java.lang.String tag
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/flow/element/condition/AndOrCondition.java
|
AndOrConditionPredicate
|
getItemResultMetaValue
|
class AndOrConditionPredicate implements Predicate<Executable> {
private final Integer slotIndex;
public AndOrConditionPredicate(Integer slotIndex) {
this.slotIndex = slotIndex;
}
@Override
public boolean test(Executable executable) {
try {
executable.setCurrChainId(getCurrChainId());
executable.execute(slotIndex);
return executable.getItemResultMetaValue(slotIndex);
} catch (Exception e) {
throw new AndOrConditionException(e.getMessage());
}
}
}
@Override
@SuppressWarnings("unchecked")
public Boolean getItemResultMetaValue(Integer slotIndex) {<FILL_FUNCTION_BODY>
|
Slot slot = DataBus.getSlot(slotIndex);
String resultKey = StrUtil.format("{}_{}",this.getClass().getName(),this.hashCode());
return slot.getAndOrResult(resultKey);
| 190
| 60
| 250
|
<methods>public non-sealed void <init>() ,public void addExecutable(com.yomahub.liteflow.flow.element.Executable) ,public void addExecutable(java.lang.String, com.yomahub.liteflow.flow.element.Executable) ,public void execute(java.lang.Integer) throws java.lang.Exception,public abstract void executeCondition(java.lang.Integer) throws java.lang.Exception,public List<com.yomahub.liteflow.flow.element.Node> getAllNodeInCondition() ,public abstract com.yomahub.liteflow.enums.ConditionTypeEnum getConditionType() ,public java.lang.String getCurrChainId() ,public java.lang.String getCurrChainName() ,public Map<java.lang.String,List<com.yomahub.liteflow.flow.element.Executable>> getExecutableGroup() ,public List<com.yomahub.liteflow.flow.element.Executable> getExecutableList() ,public List<com.yomahub.liteflow.flow.element.Executable> getExecutableList(java.lang.String) ,public com.yomahub.liteflow.flow.element.Executable getExecutableOne(java.lang.String) ,public com.yomahub.liteflow.enums.ExecuteableTypeEnum getExecuteType() ,public java.lang.String getId() ,public java.lang.String getTag() ,public void setCurrChainId(java.lang.String) ,public void setExecutableList(List<com.yomahub.liteflow.flow.element.Executable>) ,public void setId(java.lang.String) ,public void setTag(java.lang.String) <variables>private java.lang.String currChainId,private final Map<java.lang.String,List<com.yomahub.liteflow.flow.element.Executable>> executableGroup,private java.lang.String id,private java.lang.String tag
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/flow/element/condition/CatchCondition.java
|
CatchCondition
|
executeCondition
|
class CatchCondition extends Condition {
private final LFLog LOG = LFLoggerManager.getLogger(this.getClass());
@Override
public void executeCondition(Integer slotIndex) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public ConditionTypeEnum getConditionType() {
return ConditionTypeEnum.TYPE_CATCH;
}
public Executable getCatchItem() {
return this.getExecutableOne(ConditionKey.CATCH_KEY);
}
public void setCatchItem(Executable executable) {
this.addExecutable(ConditionKey.CATCH_KEY, executable);
}
public Executable getDoItem() {
return this.getExecutableOne(ConditionKey.DO_KEY);
}
public void setDoItem(Executable executable) {
this.addExecutable(ConditionKey.DO_KEY, executable);
}
}
|
Slot slot = DataBus.getSlot(slotIndex);
try {
Executable catchExecutable = this.getCatchItem();
if (ObjectUtil.isNull(catchExecutable)) {
String errorInfo = "no catch item find";
throw new CatchErrorException(errorInfo);
}
catchExecutable.setCurrChainId(this.getCurrChainId());
catchExecutable.execute(slotIndex);
}catch (ChainEndException e){
//ChainEndException属于用户主动结束流程,不应该进入Catch的流程
throw e;
}catch (Exception e) {
LOG.error("catch exception:" + e.getMessage(), e);
Executable doExecutable = this.getDoItem();
if (ObjectUtil.isNotNull(doExecutable)) {
doExecutable.setCurrChainId(this.getCurrChainId());
doExecutable.execute(slotIndex);
}
// catch之后需要把exception给清除掉
// 正如同java的catch一样,异常自己处理了,属于正常流程了,整个流程状态应该是成功的
DataBus.getSlot(slotIndex).removeException();
}
| 216
| 306
| 522
|
<methods>public non-sealed void <init>() ,public void addExecutable(com.yomahub.liteflow.flow.element.Executable) ,public void addExecutable(java.lang.String, com.yomahub.liteflow.flow.element.Executable) ,public void execute(java.lang.Integer) throws java.lang.Exception,public abstract void executeCondition(java.lang.Integer) throws java.lang.Exception,public List<com.yomahub.liteflow.flow.element.Node> getAllNodeInCondition() ,public abstract com.yomahub.liteflow.enums.ConditionTypeEnum getConditionType() ,public java.lang.String getCurrChainId() ,public java.lang.String getCurrChainName() ,public Map<java.lang.String,List<com.yomahub.liteflow.flow.element.Executable>> getExecutableGroup() ,public List<com.yomahub.liteflow.flow.element.Executable> getExecutableList() ,public List<com.yomahub.liteflow.flow.element.Executable> getExecutableList(java.lang.String) ,public com.yomahub.liteflow.flow.element.Executable getExecutableOne(java.lang.String) ,public com.yomahub.liteflow.enums.ExecuteableTypeEnum getExecuteType() ,public java.lang.String getId() ,public java.lang.String getTag() ,public void setCurrChainId(java.lang.String) ,public void setExecutableList(List<com.yomahub.liteflow.flow.element.Executable>) ,public void setId(java.lang.String) ,public void setTag(java.lang.String) <variables>private java.lang.String currChainId,private final Map<java.lang.String,List<com.yomahub.liteflow.flow.element.Executable>> executableGroup,private java.lang.String id,private java.lang.String tag
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/flow/element/condition/FinallyCondition.java
|
FinallyCondition
|
executeCondition
|
class FinallyCondition extends Condition {
@Override
public void executeCondition(Integer slotIndex) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public ConditionTypeEnum getConditionType() {
return ConditionTypeEnum.TYPE_FINALLY;
}
}
|
for (Executable executableItem : this.getExecutableList()) {
executableItem.setCurrChainId(this.getCurrChainId());
executableItem.execute(slotIndex);
}
| 69
| 57
| 126
|
<methods>public non-sealed void <init>() ,public void addExecutable(com.yomahub.liteflow.flow.element.Executable) ,public void addExecutable(java.lang.String, com.yomahub.liteflow.flow.element.Executable) ,public void execute(java.lang.Integer) throws java.lang.Exception,public abstract void executeCondition(java.lang.Integer) throws java.lang.Exception,public List<com.yomahub.liteflow.flow.element.Node> getAllNodeInCondition() ,public abstract com.yomahub.liteflow.enums.ConditionTypeEnum getConditionType() ,public java.lang.String getCurrChainId() ,public java.lang.String getCurrChainName() ,public Map<java.lang.String,List<com.yomahub.liteflow.flow.element.Executable>> getExecutableGroup() ,public List<com.yomahub.liteflow.flow.element.Executable> getExecutableList() ,public List<com.yomahub.liteflow.flow.element.Executable> getExecutableList(java.lang.String) ,public com.yomahub.liteflow.flow.element.Executable getExecutableOne(java.lang.String) ,public com.yomahub.liteflow.enums.ExecuteableTypeEnum getExecuteType() ,public java.lang.String getId() ,public java.lang.String getTag() ,public void setCurrChainId(java.lang.String) ,public void setExecutableList(List<com.yomahub.liteflow.flow.element.Executable>) ,public void setId(java.lang.String) ,public void setTag(java.lang.String) <variables>private java.lang.String currChainId,private final Map<java.lang.String,List<com.yomahub.liteflow.flow.element.Executable>> executableGroup,private java.lang.String id,private java.lang.String tag
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/flow/element/condition/ForCondition.java
|
ForCondition
|
executeCondition
|
class ForCondition extends LoopCondition {
@Override
public void executeCondition(Integer slotIndex) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public ConditionTypeEnum getConditionType() {
return ConditionTypeEnum.TYPE_FOR;
}
public Node getForNode() {
return (Node) this.getExecutableOne(ConditionKey.FOR_KEY);
}
public void setForNode(Node forNode) {
this.addExecutable(ConditionKey.FOR_KEY, forNode);
}
}
|
Slot slot = DataBus.getSlot(slotIndex);
Node forNode = this.getForNode();
if (ObjectUtil.isNull(forNode)) {
String errorInfo = StrUtil.format("[{}]:no for-node found", slot.getRequestId());
throw new NoForNodeException(errorInfo);
}
// 提前设置 chainId,避免无法在 isAccess 方法中获取到
forNode.setCurrChainId(this.getCurrChainId());
// 先去判断isAccess方法,如果isAccess方法都返回false,整个FOR表达式不执行
if (!forNode.isAccess(slotIndex)) {
return;
}
// 执行forCount组件
forNode.execute(slotIndex);
// 获得循环次数
int forCount = forNode.getItemResultMetaValue(slotIndex);
// 获得要循环的可执行对象
Executable executableItem = this.getDoExecutor();
// 获取Break节点
Executable breakItem = this.getBreakItem();
try {
if (!isParallel()) {
//串行循环执行
for (int i = 0; i < forCount; i++) {
executableItem.setCurrChainId(this.getCurrChainId());
// 设置循环index
setLoopIndex(executableItem, i);
executableItem.execute(slotIndex);
// 如果break组件不为空,则去执行
if (ObjectUtil.isNotNull(breakItem)) {
breakItem.setCurrChainId(this.getCurrChainId());
setLoopIndex(breakItem, i);
breakItem.execute(slotIndex);
boolean isBreak = breakItem.getItemResultMetaValue(slotIndex);
if (isBreak) {
break;
}
}
}
}else{
//并行循环执行
//存储所有的并行执行子项的CompletableFuture
List<CompletableFuture<LoopFutureObj>> futureList = new ArrayList<>();
//获取并行循环的线程池
ExecutorService parallelExecutor = ExecutorHelper.loadInstance().buildLoopParallelExecutor();
for (int i = 0; i < forCount; i++){
//提交异步任务
CompletableFuture<LoopFutureObj> future =
CompletableFuture.supplyAsync(new LoopParallelSupplier(executableItem, this.getCurrChainId(), slotIndex, i), parallelExecutor);
futureList.add(future);
if (ObjectUtil.isNotNull(breakItem)) {
breakItem.setCurrChainId(this.getCurrChainId());
setLoopIndex(breakItem, i);
breakItem.execute(slotIndex);
boolean isBreak = breakItem.getItemResultMetaValue(slotIndex);
if (isBreak) {
break;
}
}
}
//等待所有的异步执行完毕
handleFutureList(futureList);
}
} finally {
removeLoopIndex(executableItem);
}
| 141
| 766
| 907
|
<methods>public non-sealed void <init>() ,public boolean isParallel() ,public void setBreakItem(com.yomahub.liteflow.flow.element.Executable) ,public void setDoExecutor(com.yomahub.liteflow.flow.element.Executable) ,public void setParallel(boolean) <variables>private boolean parallel
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/flow/element/condition/IfCondition.java
|
IfCondition
|
executeCondition
|
class IfCondition extends Condition {
@Override
public void executeCondition(Integer slotIndex) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public ConditionTypeEnum getConditionType() {
return ConditionTypeEnum.TYPE_IF;
}
public Executable getTrueCaseExecutableItem() {
return this.getExecutableOne(ConditionKey.IF_TRUE_CASE_KEY);
}
public void setTrueCaseExecutableItem(Executable trueCaseExecutableItem) {
this.addExecutable(ConditionKey.IF_TRUE_CASE_KEY, trueCaseExecutableItem);
}
public Executable getFalseCaseExecutableItem() {
return this.getExecutableOne(ConditionKey.IF_FALSE_CASE_KEY);
}
public void setFalseCaseExecutableItem(Executable falseCaseExecutableItem) {
this.addExecutable(ConditionKey.IF_FALSE_CASE_KEY, falseCaseExecutableItem);
}
public void setIfItem(Executable ifNode) {
this.addExecutable(ConditionKey.IF_KEY, ifNode);
}
public Executable getIfItem() {
return this.getExecutableOne(ConditionKey.IF_KEY);
}
}
|
Executable ifItem = this.getIfItem();
// 提前设置 chainId,避免无法在 isAccess 方法中获取到
ifItem.setCurrChainId(this.getCurrChainId());
// 先去判断isAccess方法,如果isAccess方法都返回false,整个IF表达式不执行
if (!ifItem.isAccess(slotIndex)) {
return;
}
// 先执行IF节点
ifItem.execute(slotIndex);
// 拿到If执行过的结果
boolean ifResult = ifItem.getItemResultMetaValue(slotIndex);
Executable trueCaseExecutableItem = this.getTrueCaseExecutableItem();
Executable falseCaseExecutableItem = this.getFalseCaseExecutableItem();
Slot slot = DataBus.getSlot(slotIndex);
if (ifResult) {
// trueCaseExecutableItem这个不能为空,否则执行什么呢
if (ObjectUtil.isNull(trueCaseExecutableItem)) {
String errorInfo = StrUtil.format("[{}]:no if-true node found for the component[{}]",
slot.getRequestId(), ifItem.getId());
throw new NoIfTrueNodeException(errorInfo);
}
// trueCaseExecutableItem 不能为前置或者后置组件
if (trueCaseExecutableItem instanceof PreCondition
|| trueCaseExecutableItem instanceof FinallyCondition) {
String errorInfo = StrUtil.format(
"[{}]:if component[{}] error, if true node cannot be pre or finally", slot.getRequestId(),
ifItem.getId());
throw new IfTargetCannotBePreOrFinallyException(errorInfo);
}
// 执行trueCaseExecutableItem
trueCaseExecutableItem.setCurrChainId(this.getCurrChainId());
trueCaseExecutableItem.execute(slotIndex);
}
else {
// falseCaseExecutableItem可以为null,但是不为null时就执行否的情况
if (ObjectUtil.isNotNull(falseCaseExecutableItem)) {
// falseCaseExecutableItem 不能为前置或者后置组件
if (falseCaseExecutableItem instanceof PreCondition
|| falseCaseExecutableItem instanceof FinallyCondition) {
String errorInfo = StrUtil.format(
"[{}]:if component[{}] error, if true node cannot be pre or finally",
slot.getRequestId(), ifItem.getId());
throw new IfTargetCannotBePreOrFinallyException(errorInfo);
}
// 执行falseCaseExecutableItem
falseCaseExecutableItem.setCurrChainId(this.getCurrChainId());
falseCaseExecutableItem.execute(slotIndex);
}
}
| 298
| 688
| 986
|
<methods>public non-sealed void <init>() ,public void addExecutable(com.yomahub.liteflow.flow.element.Executable) ,public void addExecutable(java.lang.String, com.yomahub.liteflow.flow.element.Executable) ,public void execute(java.lang.Integer) throws java.lang.Exception,public abstract void executeCondition(java.lang.Integer) throws java.lang.Exception,public List<com.yomahub.liteflow.flow.element.Node> getAllNodeInCondition() ,public abstract com.yomahub.liteflow.enums.ConditionTypeEnum getConditionType() ,public java.lang.String getCurrChainId() ,public java.lang.String getCurrChainName() ,public Map<java.lang.String,List<com.yomahub.liteflow.flow.element.Executable>> getExecutableGroup() ,public List<com.yomahub.liteflow.flow.element.Executable> getExecutableList() ,public List<com.yomahub.liteflow.flow.element.Executable> getExecutableList(java.lang.String) ,public com.yomahub.liteflow.flow.element.Executable getExecutableOne(java.lang.String) ,public com.yomahub.liteflow.enums.ExecuteableTypeEnum getExecuteType() ,public java.lang.String getId() ,public java.lang.String getTag() ,public void setCurrChainId(java.lang.String) ,public void setExecutableList(List<com.yomahub.liteflow.flow.element.Executable>) ,public void setId(java.lang.String) ,public void setTag(java.lang.String) <variables>private java.lang.String currChainId,private final Map<java.lang.String,List<com.yomahub.liteflow.flow.element.Executable>> executableGroup,private java.lang.String id,private java.lang.String tag
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/flow/element/condition/IteratorCondition.java
|
IteratorCondition
|
executeCondition
|
class IteratorCondition extends LoopCondition {
@Override
public void executeCondition(Integer slotIndex) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public ConditionTypeEnum getConditionType() {
return ConditionTypeEnum.TYPE_ITERATOR;
}
public Node getIteratorNode() {
return (Node) this.getExecutableOne(ConditionKey.ITERATOR_KEY);
}
public void setIteratorNode(Node iteratorNode) {
this.addExecutable(ConditionKey.ITERATOR_KEY, iteratorNode);
}
}
|
Slot slot = DataBus.getSlot(slotIndex);
Node iteratorNode = this.getIteratorNode();
if (ObjectUtil.isNull(iteratorNode)) {
String errorInfo = StrUtil.format("[{}]:no iterator-node found", slot.getRequestId());
throw new NoIteratorNodeException(errorInfo);
}
// 提前设置 chainId,避免无法在 isAccess 方法中获取到
iteratorNode.setCurrChainId(this.getCurrChainId());
// 先去判断isAccess方法,如果isAccess方法都返回false,整个ITERATOR表达式不执行
if (!iteratorNode.isAccess(slotIndex)) {
return;
}
// 执行Iterator组件
iteratorNode.execute(slotIndex);
Iterator<?> it = iteratorNode.getItemResultMetaValue(slotIndex);
// 获得要循环的可执行对象
Executable executableItem = this.getDoExecutor();
// 获取Break节点
Executable breakItem = this.getBreakItem();
try {
int index = 0;
if (!this.isParallel()) {
//原本的串行循环执行
while (it.hasNext()) {
Object itObj = it.next();
executableItem.setCurrChainId(this.getCurrChainId());
// 设置循环index
setLoopIndex(executableItem, index);
// 设置循环迭代器对象
setCurrLoopObject(executableItem, itObj);
// 执行可执行对象
executableItem.execute(slotIndex);
// 如果break组件不为空,则去执行
if (ObjectUtil.isNotNull(breakItem)) {
breakItem.setCurrChainId(this.getCurrChainId());
setLoopIndex(breakItem, index);
setCurrLoopObject(breakItem, itObj);
breakItem.execute(slotIndex);
boolean isBreak = breakItem.getItemResultMetaValue(slotIndex);
if (isBreak) {
break;
}
}
index++;
}
} else {
//并行循环执行
//存储所有的并行执行子项的CompletableFuture
List<CompletableFuture<LoopFutureObj>> futureList = new ArrayList<>();
//获取并行循环的线程池
ExecutorService parallelExecutor = ExecutorHelper.loadInstance().buildLoopParallelExecutor();
while (it.hasNext()) {
Object itObj = it.next();
//提交异步任务
CompletableFuture<LoopFutureObj> future =
CompletableFuture.supplyAsync(new LoopParallelSupplier(executableItem, this.getCurrChainId(), slotIndex, index, itObj), parallelExecutor);
futureList.add(future);
//break判断
if (ObjectUtil.isNotNull(breakItem)) {
breakItem.setCurrChainId(this.getCurrChainId());
setLoopIndex(breakItem, index);
setCurrLoopObject(breakItem, itObj);
breakItem.execute(slotIndex);
boolean isBreak = breakItem.getItemResultMetaValue(slotIndex);
if (isBreak) {
break;
}
}
index++;
}
//等待所有的异步执行完毕
handleFutureList(futureList);
}
} finally {
removeLoopIndex(executableItem);
removeCurrLoopObject(executableItem);
}
| 150
| 877
| 1,027
|
<methods>public non-sealed void <init>() ,public boolean isParallel() ,public void setBreakItem(com.yomahub.liteflow.flow.element.Executable) ,public void setDoExecutor(com.yomahub.liteflow.flow.element.Executable) ,public void setParallel(boolean) <variables>private boolean parallel
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/flow/element/condition/LoopCondition.java
|
LoopCondition
|
setCurrLoopObject
|
class LoopCondition extends Condition {
//判断循环是否并行执行,默认为false
private boolean parallel = false;
protected Executable getBreakItem() {
return this.getExecutableOne(ConditionKey.BREAK_KEY);
}
public void setBreakItem(Executable breakNode) {
this.addExecutable(ConditionKey.BREAK_KEY, breakNode);
}
protected Executable getDoExecutor() {
return this.getExecutableOne(ConditionKey.DO_KEY);
}
public void setDoExecutor(Executable executable) {
this.addExecutable(ConditionKey.DO_KEY, executable);
}
protected void setLoopIndex(Executable executableItem, int index) {
if (executableItem instanceof Chain) {
((Chain) executableItem).getConditionList().forEach(condition -> setLoopIndex(condition, index));
} else if (executableItem instanceof Condition) {
((Condition) executableItem).getExecutableGroup()
.forEach((key, value) -> value.forEach(executable -> setLoopIndex(executable, index)));
} else if (executableItem instanceof Node) {
((Node) executableItem).setLoopIndex(index);
}
}
protected void setCurrLoopObject(Executable executableItem, Object obj) {<FILL_FUNCTION_BODY>}
protected void removeLoopIndex(Executable executableItem) {
if (executableItem instanceof Chain) {
((Chain) executableItem).getConditionList().forEach(this::removeLoopIndex);
} else if (executableItem instanceof Condition) {
((Condition) executableItem).getExecutableGroup()
.forEach((key, value) -> value.forEach(this::removeLoopIndex));
} else if (executableItem instanceof Node) {
((Node) executableItem).removeLoopIndex();
}
}
protected void removeCurrLoopObject(Executable executableItem) {
if (executableItem instanceof Chain) {
((Chain) executableItem).getConditionList().forEach(this::removeCurrLoopObject);
} else if (executableItem instanceof Condition) {
((Condition) executableItem).getExecutableGroup()
.forEach((key, value) -> value.forEach(this::removeCurrLoopObject));
} else if (executableItem instanceof Node) {
((Node) executableItem).removeCurrLoopObject();
}
}
public boolean isParallel() {
return parallel;
}
public void setParallel(boolean parallel) {
this.parallel = parallel;
}
//循环并行执行的futureList处理
protected void handleFutureList(List<CompletableFuture<LoopFutureObj>> futureList)throws Exception{
CompletableFuture<?> resultCompletableFuture = CompletableFuture.allOf(futureList.toArray(new CompletableFuture[]{}));
resultCompletableFuture.get();
//获取所有的执行结果,如果有失败的,那么需要抛出异常
for (CompletableFuture<LoopFutureObj> future : futureList) {
LoopFutureObj loopFutureObj = future.get();
if (!loopFutureObj.isSuccess()) {
throw loopFutureObj.getEx();
}
}
}
// 循环并行执行的Supplier封装
public class LoopParallelSupplier implements Supplier<LoopFutureObj> {
private final Executable executableItem;
private final String currChainId;
private final Integer slotIndex;
private final Integer loopIndex;
private final Object itObj;
public LoopParallelSupplier(Executable executableItem, String currChainId, Integer slotIndex, Integer loopIndex) {
this.executableItem = executableItem;
this.currChainId = currChainId;
this.slotIndex = slotIndex;
this.loopIndex = loopIndex;
this.itObj = null;
}
public LoopParallelSupplier(Executable executableItem, String currChainId, Integer slotIndex, Integer loopIndex, Object itObj) {
this.executableItem = executableItem;
this.currChainId = currChainId;
this.slotIndex = slotIndex;
this.loopIndex = loopIndex;
this.itObj = itObj;
}
@Override
public LoopFutureObj get() {
try {
executableItem.setCurrChainId(this.currChainId);
// 设置循环index
setLoopIndex(executableItem, loopIndex);
//IteratorCondition的情况下,需要设置当前循环对象
if(itObj != null){
setCurrLoopObject(executableItem, itObj);
}
executableItem.execute(slotIndex);
return LoopFutureObj.success(executableItem.getId());
} catch (Exception e) {
return LoopFutureObj.fail(executableItem.getId(), e);
}
}
}
}
|
if (executableItem instanceof Chain) {
((Chain) executableItem).getConditionList().forEach(condition -> setCurrLoopObject(condition, obj));
} else if (executableItem instanceof Condition) {
((Condition) executableItem).getExecutableGroup()
.forEach((key, value) -> value.forEach(executable -> setCurrLoopObject(executable, obj)));
} else if (executableItem instanceof Node) {
((Node) executableItem).setCurrLoopObject(obj);
}
| 1,221
| 130
| 1,351
|
<methods>public non-sealed void <init>() ,public void addExecutable(com.yomahub.liteflow.flow.element.Executable) ,public void addExecutable(java.lang.String, com.yomahub.liteflow.flow.element.Executable) ,public void execute(java.lang.Integer) throws java.lang.Exception,public abstract void executeCondition(java.lang.Integer) throws java.lang.Exception,public List<com.yomahub.liteflow.flow.element.Node> getAllNodeInCondition() ,public abstract com.yomahub.liteflow.enums.ConditionTypeEnum getConditionType() ,public java.lang.String getCurrChainId() ,public java.lang.String getCurrChainName() ,public Map<java.lang.String,List<com.yomahub.liteflow.flow.element.Executable>> getExecutableGroup() ,public List<com.yomahub.liteflow.flow.element.Executable> getExecutableList() ,public List<com.yomahub.liteflow.flow.element.Executable> getExecutableList(java.lang.String) ,public com.yomahub.liteflow.flow.element.Executable getExecutableOne(java.lang.String) ,public com.yomahub.liteflow.enums.ExecuteableTypeEnum getExecuteType() ,public java.lang.String getId() ,public java.lang.String getTag() ,public void setCurrChainId(java.lang.String) ,public void setExecutableList(List<com.yomahub.liteflow.flow.element.Executable>) ,public void setId(java.lang.String) ,public void setTag(java.lang.String) <variables>private java.lang.String currChainId,private final Map<java.lang.String,List<com.yomahub.liteflow.flow.element.Executable>> executableGroup,private java.lang.String id,private java.lang.String tag
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/flow/element/condition/NotCondition.java
|
NotCondition
|
executeCondition
|
class NotCondition extends Condition {
private final LFLog LOG = LFLoggerManager.getLogger(this.getClass());
@Override
public void executeCondition(Integer slotIndex) throws Exception {<FILL_FUNCTION_BODY>}
@Override
@SuppressWarnings("unchecked")
public Boolean getItemResultMetaValue(Integer slotIndex) {
Slot slot = DataBus.getSlot(slotIndex);
String resultKey = StrUtil.format("{}_{}",this.getClass().getName(),this.hashCode());
return slot.getNotResult(resultKey);
}
@Override
public ConditionTypeEnum getConditionType() {
return ConditionTypeEnum.TYPE_NOT_OPT;
}
public void setItem(Executable item){
this.addExecutable(ConditionKey.NOT_ITEM_KEY, item);
}
public Executable getItem(){
return this.getExecutableOne(ConditionKey.NOT_ITEM_KEY);
}
}
|
Executable item = this.getItem();
item.setCurrChainId(this.getCurrChainId());
item.execute(slotIndex);
boolean flag = item.getItemResultMetaValue(slotIndex);
LOG.info("the result of boolean component [{}] is [{}]", item.getId(), flag);
Slot slot = DataBus.getSlot(slotIndex);
String resultKey = StrUtil.format("{}_{}",this.getClass().getName(),this.hashCode());
slot.setNotResult(resultKey, !flag);
| 255
| 146
| 401
|
<methods>public non-sealed void <init>() ,public void addExecutable(com.yomahub.liteflow.flow.element.Executable) ,public void addExecutable(java.lang.String, com.yomahub.liteflow.flow.element.Executable) ,public void execute(java.lang.Integer) throws java.lang.Exception,public abstract void executeCondition(java.lang.Integer) throws java.lang.Exception,public List<com.yomahub.liteflow.flow.element.Node> getAllNodeInCondition() ,public abstract com.yomahub.liteflow.enums.ConditionTypeEnum getConditionType() ,public java.lang.String getCurrChainId() ,public java.lang.String getCurrChainName() ,public Map<java.lang.String,List<com.yomahub.liteflow.flow.element.Executable>> getExecutableGroup() ,public List<com.yomahub.liteflow.flow.element.Executable> getExecutableList() ,public List<com.yomahub.liteflow.flow.element.Executable> getExecutableList(java.lang.String) ,public com.yomahub.liteflow.flow.element.Executable getExecutableOne(java.lang.String) ,public com.yomahub.liteflow.enums.ExecuteableTypeEnum getExecuteType() ,public java.lang.String getId() ,public java.lang.String getTag() ,public void setCurrChainId(java.lang.String) ,public void setExecutableList(List<com.yomahub.liteflow.flow.element.Executable>) ,public void setId(java.lang.String) ,public void setTag(java.lang.String) <variables>private java.lang.String currChainId,private final Map<java.lang.String,List<com.yomahub.liteflow.flow.element.Executable>> executableGroup,private java.lang.String id,private java.lang.String tag
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/flow/element/condition/PreCondition.java
|
PreCondition
|
executeCondition
|
class PreCondition extends Condition {
@Override
public void executeCondition(Integer slotIndex) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public ConditionTypeEnum getConditionType() {
return ConditionTypeEnum.TYPE_PRE;
}
}
|
for (Executable executableItem : this.getExecutableList()) {
executableItem.setCurrChainId(this.getCurrChainId());
executableItem.execute(slotIndex);
}
| 66
| 57
| 123
|
<methods>public non-sealed void <init>() ,public void addExecutable(com.yomahub.liteflow.flow.element.Executable) ,public void addExecutable(java.lang.String, com.yomahub.liteflow.flow.element.Executable) ,public void execute(java.lang.Integer) throws java.lang.Exception,public abstract void executeCondition(java.lang.Integer) throws java.lang.Exception,public List<com.yomahub.liteflow.flow.element.Node> getAllNodeInCondition() ,public abstract com.yomahub.liteflow.enums.ConditionTypeEnum getConditionType() ,public java.lang.String getCurrChainId() ,public java.lang.String getCurrChainName() ,public Map<java.lang.String,List<com.yomahub.liteflow.flow.element.Executable>> getExecutableGroup() ,public List<com.yomahub.liteflow.flow.element.Executable> getExecutableList() ,public List<com.yomahub.liteflow.flow.element.Executable> getExecutableList(java.lang.String) ,public com.yomahub.liteflow.flow.element.Executable getExecutableOne(java.lang.String) ,public com.yomahub.liteflow.enums.ExecuteableTypeEnum getExecuteType() ,public java.lang.String getId() ,public java.lang.String getTag() ,public void setCurrChainId(java.lang.String) ,public void setExecutableList(List<com.yomahub.liteflow.flow.element.Executable>) ,public void setId(java.lang.String) ,public void setTag(java.lang.String) <variables>private java.lang.String currChainId,private final Map<java.lang.String,List<com.yomahub.liteflow.flow.element.Executable>> executableGroup,private java.lang.String id,private java.lang.String tag
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/flow/element/condition/RetryCondition.java
|
RetryCondition
|
executeCondition
|
class RetryCondition extends ThenCondition{
private final LFLog LOG = LFLoggerManager.getLogger(this.getClass());
private Integer retryTimes;
private Class<? extends Exception>[] retryForExceptions = new Class[] { Exception.class };
public Class<? extends Exception>[] getRetryForExceptions() {
return retryForExceptions;
}
public void setRetryForExceptions(Class<? extends Exception>[] retryForExceptions) {
this.retryForExceptions = retryForExceptions;
}
public Integer getRetryTimes() {
return retryTimes;
}
public void setRetryTimes(Integer retryTimes) {
this.retryTimes = retryTimes;
}
@Override
public void executeCondition(Integer slotIndex) throws Exception {<FILL_FUNCTION_BODY>}
private void retry(Integer slotIndex, int retryTime) throws Exception {
LOG.info("{} performs {} retry ", this.getCurrentExecutableId(), retryTime);
super.executeCondition(slotIndex);
}
/**
* 获取当前组件的 id
*
* @return
*/
private String getCurrentExecutableId() {
// retryCondition 只有一个 Executable
Executable executable = this.getExecutableList().get(0);
if (ObjectUtil.isNotNull(executable.getId())) {
// 已经有 id 了
return executable.getId();
}
// 定义 id
switch (executable.getExecuteType()) {
// chain 和 node 一般都有 id
case CHAIN:
return ((Chain) executable).getChainId();
case CONDITION:
return "condition-" + ((Condition) executable).getConditionType().getName();
case NODE:
return "node-" + ((Node) executable).getType().getCode();
default:
return "unknown-executable";
}
}
}
|
int retryTimes = this.getRetryTimes() < 0 ? 0 : this.getRetryTimes();
List<Class<? extends Exception>> forExceptions = Arrays.asList(this.getRetryForExceptions());
for (int i = 0; i <= retryTimes; i ++) {
try {
if(i == 0) {
super.executeCondition(slotIndex);
} else {
retry(slotIndex, i);
}
break;
} catch (ChainEndException e) {
throw e;
} catch (Exception e) {
// 判断抛出的异常是不是指定异常的子类
boolean flag = forExceptions.stream().anyMatch(clazz -> clazz.isAssignableFrom(e.getClass()));
if(!flag || i >= retryTimes) {
if(retryTimes > 0) {
String retryFailMsg = StrFormatter.format("retry fail when executing the chain[{}] because {} occurs {}.",
this.getCurrChainId(), this.getCurrentExecutableId(), e);
LOG.error(retryFailMsg);
}
throw e;
} else {
DataBus.getSlot(slotIndex).removeException();
}
}
}
| 500
| 319
| 819
|
<methods>public non-sealed void <init>() ,public void addExecutable(com.yomahub.liteflow.flow.element.Executable) ,public void addFinallyCondition(com.yomahub.liteflow.flow.element.condition.FinallyCondition) ,public void addPreCondition(com.yomahub.liteflow.flow.element.condition.PreCondition) ,public void executeCondition(java.lang.Integer) throws java.lang.Exception,public com.yomahub.liteflow.enums.ConditionTypeEnum getConditionType() ,public List<com.yomahub.liteflow.flow.element.condition.FinallyCondition> getFinallyConditionList() ,public List<com.yomahub.liteflow.flow.element.condition.PreCondition> getPreConditionList() <variables>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/flow/element/condition/SwitchCondition.java
|
SwitchCondition
|
executeCondition
|
class SwitchCondition extends Condition {
private final String TAG_PREFIX = "tag";
private final String TAG_FLAG = ":";
@Override
public void executeCondition(Integer slotIndex) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public ConditionTypeEnum getConditionType() {
return ConditionTypeEnum.TYPE_SWITCH;
}
public void addTargetItem(Executable executable) {
this.addExecutable(ConditionKey.SWITCH_TARGET_KEY, executable);
}
public List<Executable> getTargetList() {
return this.getExecutableList(ConditionKey.SWITCH_TARGET_KEY);
}
public void setSwitchNode(Node switchNode) {
this.addExecutable(ConditionKey.SWITCH_KEY, switchNode);
}
public Node getSwitchNode() {
return (Node) this.getExecutableOne(ConditionKey.SWITCH_KEY);
}
public Executable getDefaultExecutor() {
return this.getExecutableOne(ConditionKey.SWITCH_DEFAULT_KEY);
}
public void setDefaultExecutor(Executable defaultExecutor) {
this.addExecutable(ConditionKey.SWITCH_DEFAULT_KEY, defaultExecutor);
}
}
|
// 获取switch node
Node switchNode = this.getSwitchNode();
// 获取target List
List<Executable> targetList = this.getTargetList();
// 提前设置 chainId,避免无法在 isAccess 方法中获取到
switchNode.setCurrChainId(this.getCurrChainId());
// 先去判断isAccess方法,如果isAccess方法都返回false,整个SWITCH表达式不执行
if (!switchNode.isAccess(slotIndex)) {
return;
}
// 先执行switch节点
switchNode.execute(slotIndex);
// 拿到switch节点的结果
String targetId = switchNode.getItemResultMetaValue(slotIndex);
Slot slot = DataBus.getSlot(slotIndex);
Executable targetExecutor = null;
if (StrUtil.isNotBlank(targetId)) {
// 这里要判断是否使用tag模式跳转
if (targetId.contains(TAG_FLAG)) {
String[] target = targetId.split(TAG_FLAG, 2);
String _targetId = target[0];
String _targetTag = target[1];
targetExecutor = targetList.stream().filter(executable -> {
return (StrUtil.startWith(_targetId, TAG_PREFIX) && ObjectUtil.equal(_targetTag,executable.getTag()))
|| ((StrUtil.isEmpty(_targetId) || _targetId.equals(executable.getId()))
&& (StrUtil.isEmpty(_targetTag) || _targetTag.equals(executable.getTag())));
}).findFirst().orElse(null);
}
else {
targetExecutor = targetList.stream()
.filter(executable -> ObjectUtil.equal(executable.getId(),targetId) )
.findFirst()
.orElse(null);
}
}
if (ObjectUtil.isNull(targetExecutor)) {
// 没有匹配到执行节点,则走默认的执行节点
targetExecutor = this.getDefaultExecutor();
}
if (ObjectUtil.isNotNull(targetExecutor)) {
// switch的目标不能是Pre节点或者Finally节点
if (targetExecutor instanceof PreCondition || targetExecutor instanceof FinallyCondition) {
String errorInfo = StrUtil.format(
"[{}]:switch component[{}] error, switch target node cannot be pre or finally",
slot.getRequestId(), this.getSwitchNode().getInstance().getDisplayName());
throw new SwitchTargetCannotBePreOrFinallyException(errorInfo);
}
targetExecutor.setCurrChainId(this.getCurrChainId());
targetExecutor.execute(slotIndex);
}
else {
String errorInfo = StrUtil.format("[{}]:no target node find for the component[{}],target str is [{}]",
slot.getRequestId(), this.getSwitchNode().getInstance().getDisplayName(), targetId);
throw new NoSwitchTargetNodeException(errorInfo);
}
| 310
| 763
| 1,073
|
<methods>public non-sealed void <init>() ,public void addExecutable(com.yomahub.liteflow.flow.element.Executable) ,public void addExecutable(java.lang.String, com.yomahub.liteflow.flow.element.Executable) ,public void execute(java.lang.Integer) throws java.lang.Exception,public abstract void executeCondition(java.lang.Integer) throws java.lang.Exception,public List<com.yomahub.liteflow.flow.element.Node> getAllNodeInCondition() ,public abstract com.yomahub.liteflow.enums.ConditionTypeEnum getConditionType() ,public java.lang.String getCurrChainId() ,public java.lang.String getCurrChainName() ,public Map<java.lang.String,List<com.yomahub.liteflow.flow.element.Executable>> getExecutableGroup() ,public List<com.yomahub.liteflow.flow.element.Executable> getExecutableList() ,public List<com.yomahub.liteflow.flow.element.Executable> getExecutableList(java.lang.String) ,public com.yomahub.liteflow.flow.element.Executable getExecutableOne(java.lang.String) ,public com.yomahub.liteflow.enums.ExecuteableTypeEnum getExecuteType() ,public java.lang.String getId() ,public java.lang.String getTag() ,public void setCurrChainId(java.lang.String) ,public void setExecutableList(List<com.yomahub.liteflow.flow.element.Executable>) ,public void setId(java.lang.String) ,public void setTag(java.lang.String) <variables>private java.lang.String currChainId,private final Map<java.lang.String,List<com.yomahub.liteflow.flow.element.Executable>> executableGroup,private java.lang.String id,private java.lang.String tag
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/flow/element/condition/ThenCondition.java
|
ThenCondition
|
executeCondition
|
class ThenCondition extends Condition {
@Override
public ConditionTypeEnum getConditionType() {
return ConditionTypeEnum.TYPE_THEN;
}
@Override
public void executeCondition(Integer slotIndex) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public void addExecutable(Executable executable) {
if (executable instanceof PreCondition) {
this.addPreCondition((PreCondition) executable);
}
else if (executable instanceof FinallyCondition) {
this.addFinallyCondition((FinallyCondition) executable);
}
else {
super.addExecutable(executable);
}
}
public List<PreCondition> getPreConditionList() {
return this.getExecutableList(ConditionKey.PRE_KEY)
.stream()
.map(executable -> (PreCondition) executable)
.collect(Collectors.toList());
}
public void addPreCondition(PreCondition preCondition) {
this.addExecutable(ConditionKey.PRE_KEY, preCondition);
}
public List<FinallyCondition> getFinallyConditionList() {
return this.getExecutableList(ConditionKey.FINALLY_KEY)
.stream()
.map(executable -> (FinallyCondition) executable)
.collect(Collectors.toList());
}
public void addFinallyCondition(FinallyCondition finallyCondition) {
this.addExecutable(ConditionKey.FINALLY_KEY, finallyCondition);
}
}
|
List<PreCondition> preConditionList = this.getPreConditionList();
List<FinallyCondition> finallyConditionList = this.getFinallyConditionList();
try {
for (PreCondition preCondition : preConditionList) {
preCondition.setCurrChainId(this.getCurrChainId());
preCondition.execute(slotIndex);
}
for (Executable executableItem : this.getExecutableList()) {
executableItem.setCurrChainId(this.getCurrChainId());
executableItem.execute(slotIndex);
}
}
catch (ChainEndException e) {
// 这里单独catch ChainEndException是因为ChainEndException是用户自己setIsEnd抛出的异常
// 是属于正常逻辑,所以会在FlowExecutor中判断。这里不作为异常处理
throw e;
}
catch (Exception e) {
Slot slot = DataBus.getSlot(slotIndex);
//正常情况下slot不可能为null
//当设置了超时后,还在运行的组件就有可能因为主流程已经结束释放slot而导致slot为null
if (slot != null){
String chainId = this.getCurrChainId();
// 这里事先取到exception set到slot里,为了方便finally取到exception
if (slot.isSubChain(chainId)) {
slot.setSubException(chainId, e);
}
else {
slot.setException(e);
}
}
throw e;
}
finally {
for (FinallyCondition finallyCondition : finallyConditionList) {
finallyCondition.setCurrChainId(this.getCurrChainId());
finallyCondition.execute(slotIndex);
}
}
| 361
| 458
| 819
|
<methods>public non-sealed void <init>() ,public void addExecutable(com.yomahub.liteflow.flow.element.Executable) ,public void addExecutable(java.lang.String, com.yomahub.liteflow.flow.element.Executable) ,public void execute(java.lang.Integer) throws java.lang.Exception,public abstract void executeCondition(java.lang.Integer) throws java.lang.Exception,public List<com.yomahub.liteflow.flow.element.Node> getAllNodeInCondition() ,public abstract com.yomahub.liteflow.enums.ConditionTypeEnum getConditionType() ,public java.lang.String getCurrChainId() ,public java.lang.String getCurrChainName() ,public Map<java.lang.String,List<com.yomahub.liteflow.flow.element.Executable>> getExecutableGroup() ,public List<com.yomahub.liteflow.flow.element.Executable> getExecutableList() ,public List<com.yomahub.liteflow.flow.element.Executable> getExecutableList(java.lang.String) ,public com.yomahub.liteflow.flow.element.Executable getExecutableOne(java.lang.String) ,public com.yomahub.liteflow.enums.ExecuteableTypeEnum getExecuteType() ,public java.lang.String getId() ,public java.lang.String getTag() ,public void setCurrChainId(java.lang.String) ,public void setExecutableList(List<com.yomahub.liteflow.flow.element.Executable>) ,public void setId(java.lang.String) ,public void setTag(java.lang.String) <variables>private java.lang.String currChainId,private final Map<java.lang.String,List<com.yomahub.liteflow.flow.element.Executable>> executableGroup,private java.lang.String id,private java.lang.String tag
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/flow/element/condition/TimeoutCondition.java
|
TimeoutCondition
|
getCurrentExecutableId
|
class TimeoutCondition extends WhenCondition {
@Override
public void executeCondition(Integer slotIndex) throws Exception {
try {
super.executeCondition(slotIndex);
} catch (WhenTimeoutException ex) {
// 将 WhenTimeoutException 转换为 TimeoutException
String errMsg = StrFormatter.format("Timed out when executing the chain [{}] because [{}] exceeded {} {}.",
this.getCurrChainId(), this.getCurrentExecutableId(), this.getMaxWaitTime(), this.getMaxWaitTimeUnit().toString().toLowerCase());
throw new TimeoutException(errMsg);
}
}
/**
* 获取当前组件的 id
*
* @return
*/
private String getCurrentExecutableId() {<FILL_FUNCTION_BODY>}
}
|
// TimeoutCondition 只有一个 Executable
Executable executable = this.getExecutableList().get(0);
if (ObjectUtil.isNotNull(executable.getId())) {
// 已经有 id 了
return executable.getId();
}
// 定义 id
switch (executable.getExecuteType()) {
// chain 和 node 一般都有 id
case CHAIN:
return ((Chain) executable).getChainId();
case CONDITION:
return "condition-" + ((Condition) executable).getConditionType().getName();
case NODE:
return "node-" + ((Node) executable).getType().getCode();
default:
return "unknown-executable";
}
| 206
| 179
| 385
|
<methods>public non-sealed void <init>() ,public void executeCondition(java.lang.Integer) throws java.lang.Exception,public com.yomahub.liteflow.enums.ConditionTypeEnum getConditionType() ,public java.lang.String getGroup() ,public java.lang.Integer getMaxWaitTime() ,public java.util.concurrent.TimeUnit getMaxWaitTimeUnit() ,public com.yomahub.liteflow.enums.ParallelStrategyEnum getParallelStrategy() ,public Set<java.lang.String> getSpecifyIdSet() ,public java.lang.String getThreadExecutorClass() ,public boolean isIgnoreError() ,public void setGroup(java.lang.String) ,public void setIgnoreError(boolean) ,public void setMaxWaitTime(java.lang.Integer) ,public void setMaxWaitTimeUnit(java.util.concurrent.TimeUnit) ,public void setParallelStrategy(com.yomahub.liteflow.enums.ParallelStrategyEnum) ,public void setSpecifyIdSet(Set<java.lang.String>) ,public void setThreadExecutorClass(java.lang.String) <variables>private final com.yomahub.liteflow.log.LFLog LOG,private java.lang.String group,private boolean ignoreError,private java.lang.Integer maxWaitTime,private java.util.concurrent.TimeUnit maxWaitTimeUnit,private com.yomahub.liteflow.enums.ParallelStrategyEnum parallelStrategy,private Set<java.lang.String> specifyIdSet,private java.lang.String threadExecutorClass
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/flow/element/condition/WhenCondition.java
|
WhenCondition
|
executeAsyncCondition
|
class WhenCondition extends Condition {
private final LFLog LOG = LFLoggerManager.getLogger(this.getClass());
// 只在when类型下有效,以区分当when调用链调用失败时是否继续往下执行 默认false不继续执行
private boolean ignoreError = false;
// 只在when类型下有效,用于不同node进行同组合并,相同的组会进行合并,不同的组不会进行合并
// 此属性已弃用
private String group = LocalDefaultFlowConstant.DEFAULT;
// 当前 When 对应并行策略,默认为 ALL
private ParallelStrategyEnum parallelStrategy;
// 只有 must 条件下,才会赋值 specifyIdSet
private Set<String> specifyIdSet;
// when单独的线程池名称
private String threadExecutorClass;
// 异步线程最⻓的等待时间
private Integer maxWaitTime;
// 等待时间单位
private TimeUnit maxWaitTimeUnit;
@Override
public void executeCondition(Integer slotIndex) throws Exception {
executeAsyncCondition(slotIndex);
}
@Override
public ConditionTypeEnum getConditionType() {
return ConditionTypeEnum.TYPE_WHEN;
}
// 使用线程池执行 when 并发流程
// 这块涉及到挺多的多线程逻辑,所以注释比较详细,看到这里的童鞋可以仔细阅读
private void executeAsyncCondition(Integer slotIndex) throws Exception {<FILL_FUNCTION_BODY>}
public boolean isIgnoreError() {
return ignoreError;
}
public void setIgnoreError(boolean ignoreError) {
this.ignoreError = ignoreError;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public ParallelStrategyEnum getParallelStrategy() {
return parallelStrategy;
}
public void setParallelStrategy(ParallelStrategyEnum parallelStrategy) {
this.parallelStrategy = parallelStrategy;
}
public Set<String> getSpecifyIdSet() {
return specifyIdSet;
}
public void setSpecifyIdSet(Set<String> specifyIdSet) {
this.specifyIdSet = specifyIdSet;
}
public String getThreadExecutorClass() {
return threadExecutorClass;
}
public void setThreadExecutorClass(String threadExecutorClass) {
// #I7G6BB 初始化的时候即创建线程池,避免运行时获取导致并发问题
ExecutorHelper.loadInstance().buildWhenExecutor(threadExecutorClass);
this.threadExecutorClass = threadExecutorClass;
}
public Integer getMaxWaitTime() {
return maxWaitTime;
}
public void setMaxWaitTime(Integer maxWaitTime) {
this.maxWaitTime = maxWaitTime;
}
public TimeUnit getMaxWaitTimeUnit() {
return maxWaitTimeUnit;
}
public void setMaxWaitTimeUnit(TimeUnit maxWaitTimeUnit) {
this.maxWaitTimeUnit = maxWaitTimeUnit;
}
}
|
// 获取并发执行策略
ParallelStrategyExecutor parallelStrategyExecutor = ParallelStrategyHelper.loadInstance().buildParallelExecutor(this.getParallelStrategy());
// 执行并发逻辑
parallelStrategyExecutor.execute(this, slotIndex);
| 744
| 68
| 812
|
<methods>public non-sealed void <init>() ,public void addExecutable(com.yomahub.liteflow.flow.element.Executable) ,public void addExecutable(java.lang.String, com.yomahub.liteflow.flow.element.Executable) ,public void execute(java.lang.Integer) throws java.lang.Exception,public abstract void executeCondition(java.lang.Integer) throws java.lang.Exception,public List<com.yomahub.liteflow.flow.element.Node> getAllNodeInCondition() ,public abstract com.yomahub.liteflow.enums.ConditionTypeEnum getConditionType() ,public java.lang.String getCurrChainId() ,public java.lang.String getCurrChainName() ,public Map<java.lang.String,List<com.yomahub.liteflow.flow.element.Executable>> getExecutableGroup() ,public List<com.yomahub.liteflow.flow.element.Executable> getExecutableList() ,public List<com.yomahub.liteflow.flow.element.Executable> getExecutableList(java.lang.String) ,public com.yomahub.liteflow.flow.element.Executable getExecutableOne(java.lang.String) ,public com.yomahub.liteflow.enums.ExecuteableTypeEnum getExecuteType() ,public java.lang.String getId() ,public java.lang.String getTag() ,public void setCurrChainId(java.lang.String) ,public void setExecutableList(List<com.yomahub.liteflow.flow.element.Executable>) ,public void setId(java.lang.String) ,public void setTag(java.lang.String) <variables>private java.lang.String currChainId,private final Map<java.lang.String,List<com.yomahub.liteflow.flow.element.Executable>> executableGroup,private java.lang.String id,private java.lang.String tag
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/flow/element/condition/WhileCondition.java
|
WhileCondition
|
executeCondition
|
class WhileCondition extends LoopCondition {
@Override
public void executeCondition(Integer slotIndex) throws Exception {<FILL_FUNCTION_BODY>}
private boolean getWhileResult(Integer slotIndex, int loopIndex) throws Exception {
Executable whileItem = this.getWhileItem();
// 执行while组件
setLoopIndex(whileItem, loopIndex);
whileItem.execute(slotIndex);
return whileItem.getItemResultMetaValue(slotIndex);
}
@Override
public ConditionTypeEnum getConditionType() {
return ConditionTypeEnum.TYPE_WHILE;
}
public Executable getWhileItem() {
return this.getExecutableOne(ConditionKey.WHILE_KEY);
}
public void setWhileItem(Executable whileItem) {
this.addExecutable(ConditionKey.WHILE_KEY, whileItem);
}
}
|
Executable whileItem = this.getWhileItem();
// 提前设置 chainId,避免无法在 isAccess 方法中获取到
whileItem.setCurrChainId(this.getCurrChainId());
// 先去判断isAccess方法,如果isAccess方法都返回false,整个WHILE表达式不执行
if (!whileItem.isAccess(slotIndex)) {
return;
}
// 获得要循环的可执行对象
Executable executableItem = this.getDoExecutor();
// 获取Break节点
Executable breakItem = this.getBreakItem();
// 循环执行
int index = 0;
if(!this.isParallel()){
//串行循环
while (getWhileResult(slotIndex, index)) {
executableItem.setCurrChainId(this.getCurrChainId());
setLoopIndex(executableItem, index);
executableItem.execute(slotIndex);
// 如果break组件不为空,则去执行
if (ObjectUtil.isNotNull(breakItem)) {
breakItem.setCurrChainId(this.getCurrChainId());
setLoopIndex(breakItem, index);
breakItem.execute(slotIndex);
boolean isBreak = breakItem.getItemResultMetaValue(slotIndex);
if (isBreak) {
break;
}
}
index++;
}
}else{
//并行循环逻辑
List<CompletableFuture<LoopFutureObj>> futureList = new ArrayList<>();
//获取并行循环的线程池
ExecutorService parallelExecutor = ExecutorHelper.loadInstance().buildLoopParallelExecutor();
while (getWhileResult(slotIndex, index)){
CompletableFuture<LoopFutureObj> future =
CompletableFuture.supplyAsync(new LoopParallelSupplier(executableItem, this.getCurrChainId(), slotIndex, index), parallelExecutor);
futureList.add(future);
//break判断
if (ObjectUtil.isNotNull(breakItem)) {
breakItem.setCurrChainId(this.getCurrChainId());
setLoopIndex(breakItem, index);
breakItem.execute(slotIndex);
boolean isBreak = breakItem.getItemResultMetaValue(slotIndex);
if (isBreak) {
break;
}
}
index++;
}
//等待所有的异步执行完毕
handleFutureList(futureList);
}
| 219
| 640
| 859
|
<methods>public non-sealed void <init>() ,public boolean isParallel() ,public void setBreakItem(com.yomahub.liteflow.flow.element.Executable) ,public void setDoExecutor(com.yomahub.liteflow.flow.element.Executable) ,public void setParallel(boolean) <variables>private boolean parallel
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/flow/entity/CmpStep.java
|
CmpStep
|
equals
|
class CmpStep {
private String nodeId;
private String nodeName;
private String tag;
private CmpStepTypeEnum stepType;
private Date startTime;
private Date endTime;
// 消耗的时间,毫秒为单位
private Long timeSpent;
// 是否成功
private boolean success;
// 有exception,success一定为false
// 但是success为false,不一定有exception,因为有可能没执行到,或者没执行结束(any)
private Exception exception;
private NodeComponent instance;
// 回滚消耗的时间
private Long rollbackTimeSpent;
// 当前执行的node
private Node refNode;
public CmpStep(String nodeId, String nodeName, CmpStepTypeEnum stepType) {
this.nodeId = nodeId;
this.nodeName = nodeName;
this.stepType = stepType;
}
public String getNodeId() {
return nodeId;
}
public void setNodeId(String nodeId) {
this.nodeId = nodeId;
}
public CmpStepTypeEnum getStepType() {
return stepType;
}
public void setStepType(CmpStepTypeEnum stepType) {
this.stepType = stepType;
}
public String getNodeName() {
return nodeName;
}
public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
public Long getTimeSpent() {
return timeSpent;
}
public void setTimeSpent(Long timeSpent) {
this.timeSpent = timeSpent;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public Exception getException() {
return exception;
}
public void setException(Exception exception) {
this.exception = exception;
}
public NodeComponent getInstance() {
return instance;
}
public void setInstance(NodeComponent instance) {
this.instance = instance;
}
public Long getRollbackTimeSpent() {
return rollbackTimeSpent;
}
public void setRollbackTimeSpent(Long rollbackTimeSpent) {
this.rollbackTimeSpent = rollbackTimeSpent;
}
public Node getRefNode() {
return refNode;
}
public void setRefNode(Node refNode) {
this.refNode = refNode;
}
public String buildString() {
if (stepType.equals(CmpStepTypeEnum.SINGLE)) {
if (StrUtil.isBlank(nodeName)) {
return StrUtil.format("{}", nodeId);
}
else {
return StrUtil.format("{}[{}]", nodeId, nodeName);
}
}
else {
// 目前没有其他的类型
return null;
}
}
public String buildStringWithTime() {
if (stepType.equals(CmpStepTypeEnum.SINGLE)) {
if (StrUtil.isBlank(nodeName)) {
if (timeSpent != null) {
return StrUtil.format("{}<{}>", nodeId, timeSpent);
}
else {
return StrUtil.format("{}", nodeId);
}
}
else {
if (timeSpent != null) {
return StrUtil.format("{}[{}]<{}>", nodeId, nodeName, timeSpent);
}
else {
return StrUtil.format("{}[{}]", nodeId, nodeName);
}
}
}
else {
// 目前没有其他的类型
return null;
}
}
public String buildRollbackStringWithTime() {
if (stepType.equals(CmpStepTypeEnum.SINGLE)) {
if (StrUtil.isBlank(nodeName)) {
if (rollbackTimeSpent != null) {
return StrUtil.format("{}<{}>", nodeId, rollbackTimeSpent);
}
else {
return StrUtil.format("{}", nodeId);
}
}
else {
if (rollbackTimeSpent != null) {
return StrUtil.format("{}[{}]<{}>", nodeId, nodeName, rollbackTimeSpent);
}
else {
return StrUtil.format("{}[{}]", nodeId, nodeName);
}
}
}
else {
// 目前没有其他的类型
return null;
}
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
}
|
if (ObjectUtil.isNull(obj)) {
return false;
}
else {
if (getClass() != obj.getClass()) {
return false;
}
else {
if (((CmpStep) obj).getNodeId().equals(this.getNodeId())) {
return true;
}
else {
return false;
}
}
}
| 1,290
| 105
| 1,395
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/flow/executor/NodeExecutor.java
|
NodeExecutor
|
execute
|
class NodeExecutor {
protected final LFLog LOG = LFLoggerManager.getLogger(this.getClass());
/**
* 执行器执行入口-若需要更大维度的执行方式可以重写该方法
*/
public void execute(NodeComponent instance) throws Exception {<FILL_FUNCTION_BODY>}
/**
* 执行重试逻辑 - 子类通过实现该方法进行重试逻辑的控制
*/
protected void retry(NodeComponent instance, int currentRetryCount) throws Exception {
Slot slot = DataBus.getSlot(instance.getSlotIndex());
LOG.info("component[{}] performs {} retry", instance.getDisplayName(), currentRetryCount + 1);
// 执行业务逻辑的主要入口
instance.execute();
}
}
|
int retryCount = instance.getRetryCount();
List<Class<? extends Exception>> forExceptions = Arrays.asList(instance.getRetryForExceptions());
for (int i = 0; i <= retryCount; i++) {
try {
// 先执行一次
if (i == 0) {
instance.execute();
}
else {
// 进入重试逻辑
retry(instance, i);
}
break;
}
catch (ChainEndException e) {
// 如果是ChainEndException,则无需重试
throw e;
}
catch (Exception e) {
// 判断抛出的异常是不是指定异常的子类
boolean flag = forExceptions.stream().anyMatch(clazz -> clazz.isAssignableFrom(e.getClass()));
// 两种情况不重试,1)抛出异常不在指定异常范围内 2)已经重试次数大于等于配置次数
if (!flag || i >= retryCount) {
throw e;
}
}
}
| 202
| 283
| 485
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/flow/executor/NodeExecutorHelper.java
|
Holder
|
buildNodeExecutor
|
class Holder {
static final NodeExecutorHelper INSTANCE = new NodeExecutorHelper();
}
/**
* 获取帮助者的实例
* @return
*/
public static NodeExecutorHelper loadInstance() {
// 外围类能直接访问内部类(不管是否是静态的)的私有变量
return Holder.INSTANCE;
}
public NodeExecutor buildNodeExecutor(Class<? extends NodeExecutor> nodeExecutorClass) {<FILL_FUNCTION_BODY>
|
if (nodeExecutorClass == null) {
// 此处使用默认的节点执行器进行执行
nodeExecutorClass = DefaultNodeExecutor.class;
}
NodeExecutor nodeExecutor = nodeExecutorMap.get(nodeExecutorClass);
// 此处无需使用同步锁进行同步-因为即使同时创建了两个实例,但是添加到缓存中的只会存在一个且不会存在并发问题-具体是由ConcurrentMap保证
if (ObjectUtil.isNull(nodeExecutor)) {
// 获取重试执行器实例
nodeExecutor = ContextAwareHolder.loadContextAware().registerBean(nodeExecutorClass);
// 缓存
nodeExecutorMap.put(nodeExecutorClass, nodeExecutor);
}
return nodeExecutorMap.get(nodeExecutorClass);
| 127
| 198
| 325
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/flow/id/IdGeneratorHolder.java
|
IdGeneratorHolder
|
init
|
class IdGeneratorHolder {
private RequestIdGenerator requestIdGenerator;
private static IdGeneratorHolder INSTANCE = new IdGeneratorHolder();
public static void init() {<FILL_FUNCTION_BODY>}
public static IdGeneratorHolder getInstance() {
return INSTANCE;
}
public String generate() {
if (ObjectUtil.isNull(requestIdGenerator)){
init();
}
return requestIdGenerator.generate();
}
public RequestIdGenerator getRequestIdGenerator() {
return requestIdGenerator;
}
public void setRequestIdGenerator(RequestIdGenerator requestIdGenerator) {
this.requestIdGenerator = requestIdGenerator;
}
}
|
try {
LiteflowConfig liteflowConfig = LiteflowConfigGetter.get();
String requestIdGeneratorClass = liteflowConfig.getRequestIdGeneratorClass();
RequestIdGenerator requestIdGenerator;
if (StrUtil.isBlank(requestIdGeneratorClass)) {
requestIdGenerator = new DefaultRequestIdGenerator();
}
else {
Class<RequestIdGenerator> idGenerateClass = (Class<RequestIdGenerator>) Class
.forName(requestIdGeneratorClass);
requestIdGenerator = ContextAwareHolder.loadContextAware().registerBean(idGenerateClass);
}
INSTANCE.setRequestIdGenerator(requestIdGenerator);
}
catch (Exception e) {
throw new RequestIdGeneratorException(e.getMessage());
}
| 167
| 202
| 369
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/flow/parallel/CompletableFutureExpand.java
|
Canceller
|
accept
|
class Canceller implements BiConsumer<Object, Throwable> {
final Future<?> future;
Canceller(Future<?> future) {
this.future = future;
}
public void accept(Object ignore, Throwable ex) {<FILL_FUNCTION_BODY>}
}
|
if (null == ex && null != future && !future.isDone()) {
future.cancel(false);
}
| 81
| 34
| 115
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/flow/parallel/CompletableFutureTimeout.java
|
DaemonThreadFactory
|
timeoutAfter
|
class DaemonThreadFactory implements ThreadFactory {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setDaemon(true);
t.setName("CompletableFutureDelayScheduler");
return t;
}
}
static final ScheduledThreadPoolExecutor delayer;
// 注意,这里使用一个线程就可以搞定 因为这个线程并不真的执行请求 而是仅仅抛出一个异常
static {
delayer = new ScheduledThreadPoolExecutor(1, new CompletableFutureTimeout.Delayer.DaemonThreadFactory());
delayer.setRemoveOnCancelPolicy(true);
}
}
public static <T> CompletableFuture<T> timeoutAfter(long timeout, TimeUnit unit) {<FILL_FUNCTION_BODY>
|
CompletableFuture<T> result = new CompletableFuture<T>();
// timeout 时间后 抛出TimeoutException 类似于sentinel / watcher
CompletableFutureTimeout.Delayer.delayer.schedule(() -> result.completeExceptionally(new TimeoutException()),
timeout, unit);
return result;
| 211
| 85
| 296
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/flow/parallel/LoopFutureObj.java
|
LoopFutureObj
|
fail
|
class LoopFutureObj {
private String executorName;
private boolean success;
private Exception ex;
public static LoopFutureObj success(String executorName) {
LoopFutureObj result = new LoopFutureObj();
result.setSuccess(true);
result.setExecutorName(executorName);
return result;
}
public static LoopFutureObj fail(String executorName, Exception ex) {<FILL_FUNCTION_BODY>}
public Exception getEx() {
return ex;
}
public String getExecutorName() {
return executorName;
}
public boolean isSuccess() {
return success;
}
public void setEx(Exception ex) {
this.ex = ex;
}
public void setExecutorName(String executorName) {
this.executorName = executorName;
}
public void setSuccess(boolean success) {
this.success = success;
}
}
|
LoopFutureObj result = new LoopFutureObj();
result.setSuccess(false);
result.setExecutorName(executorName);
result.setEx(ex);
return result;
| 252
| 52
| 304
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/flow/parallel/ParallelSupplier.java
|
ParallelSupplier
|
get
|
class ParallelSupplier implements Supplier<WhenFutureObj> {
private static final LFLog LOG = LFLoggerManager.getLogger(ParallelSupplier.class);
private final Executable executableItem;
private final String currChainId;
private final Integer slotIndex;
public ParallelSupplier(Executable executableItem, String currChainId, Integer slotIndex) {
this.executableItem = executableItem;
this.currChainId = currChainId;
this.slotIndex = slotIndex;
}
@Override
public WhenFutureObj get() {<FILL_FUNCTION_BODY>}
}
|
try {
executableItem.setCurrChainId(currChainId);
executableItem.execute(slotIndex);
return WhenFutureObj.success(executableItem.getId());
}
catch (Exception e) {
return WhenFutureObj.fail(executableItem.getId(), e);
}
| 156
| 86
| 242
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/flow/parallel/WhenFutureObj.java
|
WhenFutureObj
|
success
|
class WhenFutureObj {
private boolean success;
private boolean timeout;
private String executorId;
private Exception ex;
public static WhenFutureObj success(String executorId) {<FILL_FUNCTION_BODY>}
public static WhenFutureObj fail(String executorId, Exception ex) {
WhenFutureObj result = new WhenFutureObj();
result.setSuccess(false);
result.setTimeout(false);
result.setExecutorId(executorId);
result.setEx(ex);
return result;
}
public static WhenFutureObj timeOut(String executorId) {
WhenFutureObj result = new WhenFutureObj();
result.setSuccess(false);
result.setTimeout(true);
result.setExecutorId(executorId);
result.setEx(new WhenTimeoutException(
StrUtil.format("Timed out when executing the component[{}]",executorId)));
return result;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getExecutorId() {
return executorId;
}
public void setExecutorId(String executorId) {
this.executorId = executorId;
}
public Exception getEx() {
return ex;
}
public void setEx(Exception ex) {
this.ex = ex;
}
public boolean isTimeout() {
return timeout;
}
public void setTimeout(boolean timeout) {
this.timeout = timeout;
}
}
|
WhenFutureObj result = new WhenFutureObj();
result.setSuccess(true);
result.setTimeout(false);
result.setExecutorId(executorId);
return result;
| 402
| 54
| 456
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/flow/parallel/strategy/AllOfParallelExecutor.java
|
AllOfParallelExecutor
|
execute
|
class AllOfParallelExecutor extends ParallelStrategyExecutor {
@Override
public void execute(WhenCondition whenCondition, Integer slotIndex) throws Exception {<FILL_FUNCTION_BODY>}
// 在 allOf 这个场景中,不需要过滤
@Override
protected Stream<Executable> filterAccess(Stream<Executable> stream, Integer slotIndex, String currentChainId) {
return stream;
}
}
|
// 获取所有 CompletableFuture 任务
List<CompletableFuture<WhenFutureObj>> whenAllTaskList = this.getWhenAllTaskList(whenCondition, slotIndex);
// 把这些 CompletableFuture 通过 allOf 合成一个 CompletableFuture,表明完成所有任务
CompletableFuture<?> specifyTask = CompletableFuture.allOf(whenAllTaskList.toArray(new CompletableFuture[] {}));
// 结果处理
this.handleTaskResult(whenCondition, slotIndex, whenAllTaskList, specifyTask);
| 107
| 136
| 243
|
<methods>public non-sealed void <init>() ,public abstract void execute(com.yomahub.liteflow.flow.element.condition.WhenCondition, java.lang.Integer) throws java.lang.Exception<variables>protected final com.yomahub.liteflow.log.LFLog LOG
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/flow/parallel/strategy/AnyOfParallelExecutor.java
|
AnyOfParallelExecutor
|
execute
|
class AnyOfParallelExecutor extends ParallelStrategyExecutor {
@Override
public void execute(WhenCondition whenCondition, Integer slotIndex) throws Exception {<FILL_FUNCTION_BODY>}
}
|
// 获取所有 CompletableFuture 任务
List<CompletableFuture<WhenFutureObj>> whenAllTaskList = this.getWhenAllTaskList(whenCondition, slotIndex);
// 把这些 CompletableFuture 通过 anyOf 合成一个 CompletableFuture,表明完成任一任务
CompletableFuture<?> specifyTask = CompletableFuture.anyOf(whenAllTaskList.toArray(new CompletableFuture[] {}));
// 结果处理
this.handleTaskResult(whenCondition, slotIndex, whenAllTaskList, specifyTask);
| 51
| 137
| 188
|
<methods>public non-sealed void <init>() ,public abstract void execute(com.yomahub.liteflow.flow.element.condition.WhenCondition, java.lang.Integer) throws java.lang.Exception<variables>protected final com.yomahub.liteflow.log.LFLog LOG
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/flow/parallel/strategy/ParallelStrategyHelper.java
|
Holder
|
getParallelStrategyExecutor
|
class Holder {
static final ParallelStrategyHelper INSTANCE = new ParallelStrategyHelper();
}
public static ParallelStrategyHelper loadInstance() {
return ParallelStrategyHelper.Holder.INSTANCE;
}
private ParallelStrategyExecutor getParallelStrategyExecutor(ParallelStrategyEnum parallelStrategyEnum) {<FILL_FUNCTION_BODY>
|
try {
ParallelStrategyExecutor strategyExecutor = strategyExecutorMap.get(parallelStrategyEnum);
if (ObjUtil.isNotNull(strategyExecutor)) return strategyExecutor;
Class<ParallelStrategyExecutor> executorClass = (Class<ParallelStrategyExecutor>) Class.forName(parallelStrategyEnum.getClazz().getName());
strategyExecutor = ContextAwareHolder.loadContextAware().registerBean(executorClass);
strategyExecutorMap.put(parallelStrategyEnum, strategyExecutor);
return strategyExecutor;
} catch (Exception e) {
LOG.error(e.getMessage());
throw new ParallelExecutorCreateException(e.getMessage());
}
| 91
| 161
| 252
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/flow/parallel/strategy/SpecifyParallelExecutor.java
|
SpecifyParallelExecutor
|
execute
|
class SpecifyParallelExecutor extends ParallelStrategyExecutor {
@Override
public void execute(WhenCondition whenCondition, Integer slotIndex) throws Exception {<FILL_FUNCTION_BODY>}
}
|
String currChainId = whenCondition.getCurrChainId();
// 设置 whenCondition 参数
this.setWhenConditionParams(whenCondition);
// 获取 WHEN 所需线程池
ExecutorService parallelExecutor = getWhenExecutorService(whenCondition);
// 指定完成的任务
CompletableFuture<?> specifyTask;
// 已存在的任务 ID 集合
Set<String> exitingTaskIdSet = new HashSet<>();
// 指定任务列表,可以为 0 或者多个
List<CompletableFuture<?>> specifyTaskList = new ArrayList<>();
// 所有任务集合
List<CompletableFuture<WhenFutureObj>> allTaskList = new ArrayList<>();
// 遍历 when 所有 node,进行筛选及处理
filterWhenTaskList(whenCondition.getExecutableList(), slotIndex, currChainId)
.forEach(executable -> {
// 处理 task,封装成 CompletableFuture 对象
CompletableFuture<WhenFutureObj> completableFutureTask = wrappedFutureObj(executable, parallelExecutor, whenCondition, currChainId, slotIndex);
// 存在 must 指定 ID 的 task,且该任务只会有一个或者没有
if (whenCondition.getSpecifyIdSet().contains(executable.getId())) {
// 设置指定任务 future 对象
specifyTaskList.add(completableFutureTask);
// 记录已存在的任务 ID
exitingTaskIdSet.add(executable.getId());
}
// 组合所有任务
allTaskList.add(completableFutureTask);
});
if (CollUtil.isEmpty(specifyTaskList)) {
LOG.warn("The specified task{} was not found, waiting for all tasks to complete by default.", whenCondition.getSpecifyIdSet());
// 不存在指定任务,则需要等待所有任务都执行完成
specifyTask = CompletableFuture.allOf(allTaskList.toArray(new CompletableFuture[] {}));
} else {
// 判断 specifyIdSet 中有哪些任务是不存在的,给出提示
Collection<String> absentTaskIdSet = CollUtil.subtract(whenCondition.getSpecifyIdSet(), exitingTaskIdSet);
if (CollUtil.isNotEmpty(absentTaskIdSet)) {
LOG.warn("The specified task{} was not found, you need to define and register it.", absentTaskIdSet);
}
// 将指定要完成的任务通过 allOf 合成一个 CompletableFuture,表示需要等待 must 方法里面所有任务完成
specifyTask = CompletableFuture.allOf(specifyTaskList.toArray(new CompletableFuture[]{}));
}
// 结果处理
this.handleTaskResult(whenCondition, slotIndex, allTaskList, specifyTask);
| 51
| 697
| 748
|
<methods>public non-sealed void <init>() ,public abstract void execute(com.yomahub.liteflow.flow.element.condition.WhenCondition, java.lang.Integer) throws java.lang.Exception<variables>protected final com.yomahub.liteflow.log.LFLog LOG
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/log/LFLoggerManager.java
|
LFLoggerManager
|
getLogger
|
class LFLoggerManager {
private static final Map<String, LFLog> logMap = new HashMap<>();
private static final TransmittableThreadLocal<String> requestIdTL = new TransmittableThreadLocal<>();
public static LFLog getLogger(Class<?> clazz){<FILL_FUNCTION_BODY>}
public static void setRequestId(String requestId){
requestIdTL.set(requestId);
}
public static String getRequestId(){
return requestIdTL.get();
}
public static void removeRequestId(){
requestIdTL.remove();
}
}
|
if (logMap.containsKey(clazz.getName())){
return logMap.get(clazz.getName());
}else{
Logger log = LoggerFactory.getLogger(clazz.getName());
LFLog lfLog = new LFLog(log);
logMap.put(clazz.getName(), lfLog);
return lfLog;
}
| 158
| 97
| 255
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/monitor/CompStatistics.java
|
CompStatistics
|
compareTo
|
class CompStatistics implements Comparable<CompStatistics> {
private String componentClazzName;
private long timeSpent;
private long memorySpent;
private long recordTime;
public CompStatistics(String componentClazzName, long timeSpent) {
this.componentClazzName = componentClazzName;
this.timeSpent = timeSpent;
this.recordTime = System.currentTimeMillis();
}
public String getComponentClazzName() {
return componentClazzName;
}
public void setComponentClazzName(String componentClazzName) {
this.componentClazzName = componentClazzName;
}
public long getTimeSpent() {
return timeSpent;
}
public void setTimeSpent(long timeSpent) {
this.timeSpent = timeSpent;
}
public long getMemorySpent() {
return memorySpent;
}
public void setMemorySpent(long memorySpent) {
this.memorySpent = memorySpent;
}
public long getRecordTime() {
return recordTime;
}
@Override
public int compareTo(CompStatistics o) {<FILL_FUNCTION_BODY>}
}
|
if (o != null) {
return this.recordTime >= o.getRecordTime() ? -1 : 1;
}
return 1;
| 306
| 43
| 349
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/monitor/MonitorBus.java
|
MonitorBus
|
printStatistics
|
class MonitorBus {
private LiteflowConfig liteflowConfig;
private final LFLog LOG = LFLoggerManager.getLogger(this.getClass());
private final ConcurrentHashMap<String, BoundedPriorityBlockingQueue<CompStatistics>> statisticsMap = new ConcurrentHashMap<>();
private final ScheduledExecutorService printLogScheduler = Executors.newScheduledThreadPool(1);
public MonitorBus(LiteflowConfig liteflowConfig) {
this.liteflowConfig = liteflowConfig;
if (BooleanUtil.isTrue(liteflowConfig.getEnableLog())) {
this.printLogScheduler.scheduleAtFixedRate(new MonitorTimeTask(this), liteflowConfig.getDelay(),
liteflowConfig.getPeriod(), TimeUnit.MILLISECONDS);
}
}
public void addStatistics(CompStatistics statistics) {
if (statisticsMap.containsKey(statistics.getComponentClazzName())) {
statisticsMap.get(statistics.getComponentClazzName()).add(statistics);
}
else {
BoundedPriorityBlockingQueue<CompStatistics> queue = new BoundedPriorityBlockingQueue<>(
liteflowConfig.getQueueLimit());
queue.offer(statistics);
statisticsMap.put(statistics.getComponentClazzName(), queue);
}
}
public void printStatistics() {<FILL_FUNCTION_BODY>}
public LiteflowConfig getLiteflowConfig() {
return liteflowConfig;
}
public void setLiteflowConfig(LiteflowConfig liteflowConfig) {
this.liteflowConfig = liteflowConfig;
}
public void closeScheduler() {
this.printLogScheduler.shutdown();
}
public ConcurrentHashMap<String, BoundedPriorityBlockingQueue<CompStatistics>> getStatisticsMap() {
return statisticsMap;
}
}
|
try {
Map<String, BigDecimal> compAverageTimeSpent = new HashMap<String, BigDecimal>();
for (Entry<String, BoundedPriorityBlockingQueue<CompStatistics>> entry : statisticsMap.entrySet()) {
long totalTimeSpent = 0;
for (CompStatistics statistics : entry.getValue()) {
totalTimeSpent += statistics.getTimeSpent();
}
compAverageTimeSpent.put(entry.getKey(), new BigDecimal(totalTimeSpent)
.divide(new BigDecimal(entry.getValue().size()), 2, RoundingMode.HALF_UP));
}
List<Entry<String, BigDecimal>> compAverageTimeSpentEntryList = new ArrayList<>(
compAverageTimeSpent.entrySet());
Collections.sort(compAverageTimeSpentEntryList, (o1, o2) -> o2.getValue().compareTo(o1.getValue()));
StringBuilder logStr = new StringBuilder();
logStr.append("以下为LiteFlow中间件统计信息:\n");
logStr.append("======================================================================================\n");
logStr.append("===================================SLOT INFO==========================================\n");
logStr.append(MessageFormat.format("SLOT TOTAL SIZE : {0}\n", liteflowConfig.getSlotSize()));
logStr.append(MessageFormat.format("SLOT OCCUPY COUNT : {0}\n", DataBus.OCCUPY_COUNT));
logStr.append("===============================TIME AVERAGE SPENT=====================================\n");
for (Entry<String, BigDecimal> entry : compAverageTimeSpentEntryList) {
logStr.append(MessageFormat.format("COMPONENT[{0}] AVERAGE TIME SPENT : {1}\n", entry.getKey(),
entry.getValue()));
}
logStr.append("======================================================================================\n");
LOG.info(logStr.toString());
}
catch (Exception e) {
LOG.error("print statistics cause error", e);
}
| 482
| 538
| 1,020
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/monitor/MonitorFile.java
|
MonitorFile
|
reloadRule
|
class MonitorFile {
private final LFLog LOG = LFLoggerManager.getLogger(this.getClass());
private final Set<String> PATH_SET = new HashSet<>();
public static MonitorFile getInstance() {
return Singleton.get(MonitorFile.class);
}
/**
* 添加监听文件路径
* @param path 文件路径
*/
public void addMonitorFilePath(String path) {
if (FileUtil.isFile(path)) {
String parentFolder = FileUtil.getParent(path, 1);
PATH_SET.add(parentFolder);
}
else {
PATH_SET.add(path);
}
}
/**
* 添加监听文件路径
* @param filePaths 文件路径
*/
public void addMonitorFilePaths(List<String> filePaths) {
filePaths.forEach(this::addMonitorFilePath);
}
/**
* 创建文件监听
*/
public void create() throws Exception {
for (String path : PATH_SET) {
long interval = TimeUnit.MILLISECONDS.toMillis(2);
// 不使用过滤器
FileAlterationObserver observer = new FileAlterationObserver(new File(path));
observer.addListener(new FileAlterationListenerAdaptor() {
@Override
public void onFileChange(File file) {
LOG.info("file modify,filePath={}", file.getAbsolutePath());
this.reloadRule();
}
@Override
public void onFileDelete(File file) {
LOG.info("file delete,filePath={}", file.getAbsolutePath());
this.reloadRule();
}
private void reloadRule() {<FILL_FUNCTION_BODY>}
});
// 创建文件变化监听器
FileAlterationMonitor monitor = new FileAlterationMonitor(interval, observer);
// 开始监控
monitor.start();
}
}
}
|
try {
FlowExecutorHolder.loadInstance().reloadRule();
} catch (Exception e) {
LOG.error("reload rule error", e);
}
| 518
| 45
| 563
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/parser/base/BaseJsonFlowParser.java
|
BaseJsonFlowParser
|
parse
|
class BaseJsonFlowParser implements FlowParser {
private final Set<String> CHAIN_NAME_SET = new CopyOnWriteArraySet<>();
public void parse(String content) throws Exception {
parse(ListUtil.toList(content));
}
@Override
public void parse(List<String> contentList) throws Exception {<FILL_FUNCTION_BODY>}
/**
* 解析一个chain的过程
* @param chainObject chain 节点
*/
public abstract void parseOneChain(JsonNode chainObject);
}
|
if (CollectionUtil.isEmpty(contentList)) {
return;
}
List<JsonNode> jsonObjectList = ListUtil.toList();
for (String content : contentList) {
JsonNode flowJsonNode = JsonUtil.parseObject(content);
jsonObjectList.add(flowJsonNode);
}
ParserHelper.parseNodeJson(jsonObjectList);
ParserHelper.parseChainJson(jsonObjectList, CHAIN_NAME_SET, this::parseOneChain);
| 133
| 127
| 260
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/parser/base/BaseXmlFlowParser.java
|
BaseXmlFlowParser
|
parse
|
class BaseXmlFlowParser implements FlowParser {
private final Set<String> CHAIN_NAME_SET = new HashSet<>();
public void parse(String content) throws Exception {
parse(ListUtil.toList(content));
}
@Override
public void parse(List<String> contentList) throws Exception {<FILL_FUNCTION_BODY>}
/**
* 解析一个 chain 的过程
* @param chain chain
*/
public abstract void parseOneChain(Element chain);
}
|
if (CollectionUtil.isEmpty(contentList)) {
return;
}
List<Document> documentList = ListUtil.toList();
for (String content : contentList) {
Document document = DocumentHelper.parseText(content);
documentList.add(document);
}
ParserHelper.parseNodeDocument(documentList);
ParserHelper.parseChainDocument(documentList, CHAIN_NAME_SET, this::parseOneChain);
| 125
| 117
| 242
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/parser/base/BaseYmlFlowParser.java
|
BaseYmlFlowParser
|
parse
|
class BaseYmlFlowParser implements FlowParser {
private final Set<String> CHAIN_NAME_SET = new HashSet<>();
public void parse(String content) throws Exception {
parse(ListUtil.toList(content));
}
@Override
public void parse(List<String> contentList) throws Exception {<FILL_FUNCTION_BODY>}
protected JsonNode convertToJson(String yamlString) {
Yaml yaml = new Yaml();
Map<String, Object> map = yaml.load(yamlString);
return JsonUtil.parseObject(JsonUtil.toJsonString(map));
}
/**
* 解析一个 chain 的过程
* @param chain chain
*/
public abstract void parseOneChain(JsonNode chain);
}
|
if (CollectionUtil.isEmpty(contentList)) {
return;
}
List<JsonNode> jsonObjectList = ListUtil.toList();
for (String content : contentList) {
JsonNode ruleObject = convertToJson(content);
jsonObjectList.add(ruleObject);
}
Consumer<JsonNode> parseOneChainConsumer = this::parseOneChain;
ParserHelper.parseNodeJson(jsonObjectList);
ParserHelper.parseChainJson(jsonObjectList, CHAIN_NAME_SET, parseOneChainConsumer);
| 195
| 142
| 337
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/parser/factory/ClassParserFactory.java
|
ClassParserFactory
|
forName
|
class ClassParserFactory implements FlowParserFactory {
@Override
public BaseJsonFlowParser createJsonELParser(String path) {
Class<?> c = forName(path);
return (JsonFlowELParser) ContextAwareHolder.loadContextAware().registerBean(c);
}
@Override
public BaseXmlFlowParser createXmlELParser(String path) {
Class<?> c = forName(path);
return (XmlFlowELParser) ContextAwareHolder.loadContextAware().registerBean(c);
}
@Override
public BaseYmlFlowParser createYmlELParser(String path) {
Class<?> c = forName(path);
return (YmlFlowELParser) ContextAwareHolder.loadContextAware().registerBean(c);
}
private Class<?> forName(String path) {<FILL_FUNCTION_BODY>}
}
|
try {
return Class.forName(path);
}
catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
| 219
| 45
| 264
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/parser/factory/FlowParserProvider.java
|
FlowParserProvider
|
lookup
|
class FlowParserProvider {
private static final LFLog LOG = LFLoggerManager.getLogger(FlowExecutor.class);
private static final FlowParserFactory LOCAL_PARSER_FACTORY = new LocalParserFactory();
/**
* 使用 map 枚举不同类型的 Parser,用于解耦如下的 if 判断 <pre>
* if (ReUtil.isMatch(LOCAL_XML_CONFIG_REGEX, path)) {
* return factory.createXmlParser(path);
* }
* </pre>
*/
private static final Map<Predicate<String>, Function<String, FlowParser>> LOCAL_PARSER_DICT = new HashMap<Predicate<String>, Function<String, FlowParser>>() {
{
put(path -> ReUtil.isMatch(LOCAL_XML_CONFIG_REGEX, path), LOCAL_PARSER_FACTORY::createXmlELParser);
put(path -> ReUtil.isMatch(LOCAL_JSON_CONFIG_REGEX, path), LOCAL_PARSER_FACTORY::createJsonELParser);
put(path -> ReUtil.isMatch(LOCAL_YML_CONFIG_REGEX, path), LOCAL_PARSER_FACTORY::createYmlELParser);
put(path -> ReUtil.isMatch(LOCAL_EL_XML_CONFIG_REGEX, path), LOCAL_PARSER_FACTORY::createXmlELParser);
put(path -> ReUtil.isMatch(LOCAL_EL_JSON_CONFIG_REGEX, path), LOCAL_PARSER_FACTORY::createJsonELParser);
put(path -> ReUtil.isMatch(LOCAL_EL_YML_CONFIG_REGEX, path), LOCAL_PARSER_FACTORY::createYmlELParser);
}
};
private static final FlowParserFactory CLASS_PARSER_FACTORY = new ClassParserFactory();
/**
* 使用 map 枚举不同类型的 Parser,用于解耦如下的 if 判断 <pre>
* if (ClassXmlFlowParser.class.isAssignableFrom(clazz)) {
* return factory.createXmlParser(className);
* }
* </pre>
*/
private static final Map<Predicate<Class<?>>, Function<String, FlowParser>> CLASS_PARSER_DICT = new HashMap<Predicate<Class<?>>, Function<String, FlowParser>>() {
{
put(ClassXmlFlowELParser.class::isAssignableFrom, CLASS_PARSER_FACTORY::createXmlELParser);
put(ClassJsonFlowELParser.class::isAssignableFrom, CLASS_PARSER_FACTORY::createJsonELParser);
put(ClassYmlFlowELParser.class::isAssignableFrom, CLASS_PARSER_FACTORY::createYmlELParser);
}
};
/**
* 根据配置的地址找到对应的解析器
*/
public static FlowParser lookup(String path) throws Exception {<FILL_FUNCTION_BODY>}
/**
* 判定是否为本地文件
*/
private static boolean isLocalConfig(String path) {
return ReUtil.isMatch(LOCAL_XML_CONFIG_REGEX, path) || ReUtil.isMatch(LOCAL_JSON_CONFIG_REGEX, path)
|| ReUtil.isMatch(LOCAL_YML_CONFIG_REGEX, path) || ReUtil.isMatch(LOCAL_EL_XML_CONFIG_REGEX, path)
|| ReUtil.isMatch(LOCAL_EL_JSON_CONFIG_REGEX, path) || ReUtil.isMatch(LOCAL_EL_YML_CONFIG_REGEX, path);
}
/**
* 判定是否为自定义class配置
*/
private static boolean isClassConfig(String path) {
return ReUtil.isMatch(CLASS_CONFIG_REGEX, path);
}
/**
* 统一管理类的常量
*/
protected static class ConfigRegexConstant {
public static final String LOCAL_XML_CONFIG_REGEX = "^[\\w\\:\\-\\.\\@\\/\\\\\\*]+\\.xml$";
public static final String LOCAL_JSON_CONFIG_REGEX = "^[\\w\\:\\-\\.\\@\\/\\\\\\*]+\\.json$";
public static final String LOCAL_YML_CONFIG_REGEX = "^[\\w\\:\\-\\.\\@\\/\\\\\\*]+\\.yml$";
public static final String LOCAL_EL_XML_CONFIG_REGEX = "^[\\w\\:\\-\\.\\@\\/\\\\\\*]+\\.el\\.xml$";
public static final String LOCAL_EL_JSON_CONFIG_REGEX = "^[\\w\\:\\-\\.\\@\\/\\\\\\*]+\\.el\\.json$";
public static final String LOCAL_EL_YML_CONFIG_REGEX = "^[\\w\\:\\-\\.\\@\\/\\\\\\*]+\\.el\\.yml$";
public static final String PREFIX_FORMAT_CONFIG_REGEX = "xml:|json:|yml:|el_xml:|el_json:|el_yml:";
public static final String CLASS_CONFIG_REGEX = "^(xml:|json:|yml:|el_xml:|el_json:|el_yml:)?\\w+(\\.\\w+)*$";
}
}
|
// 自定义类必须实现以上实现类,否则报错
String errorMsg = StrUtil.format("can't support the format {}", path);
// 本地文件
if (isLocalConfig(path)) {
// 遍历枚举 map 找到对应 factory
Predicate<String> dictKey = LOCAL_PARSER_DICT.keySet()
.stream()
.filter(key -> key.test(path))
.findFirst()
.orElseThrow(() -> new ErrorSupportPathException(errorMsg));
LOG.info("flow info loaded from local file,path={}", path);
return LOCAL_PARSER_DICT.get(dictKey).apply(path);
}
// 自定义 class 配置
else if (isClassConfig(path)) {
// 获取最终的className,因为有些可能className前面带了文件类型的标识,比如json:x.x.x.x
String className = ReUtil.replaceAll(path, PREFIX_FORMAT_CONFIG_REGEX, "");
Class<?> clazz = Class.forName(className);
// 遍历枚举 map 找到对应 factory
Predicate<Class<?>> dictKey = CLASS_PARSER_DICT.keySet()
.stream()
.filter(key -> key.test(clazz))
.findFirst()
.orElseThrow(() -> new ErrorSupportPathException(errorMsg));
LOG.info("flow info loaded from class config with el,class={}", className);
return CLASS_PARSER_DICT.get(dictKey).apply(className);
}
// not found
throw new ErrorSupportPathException(errorMsg);
| 1,363
| 434
| 1,797
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/parser/helper/NodeConvertHelper.java
|
NodeConvertHelper
|
convert
|
class NodeConvertHelper {
/*script节点的修改/添加*/
public static void changeScriptNode(NodeSimpleVO nodeSimpleVO, String newValue) {
// 有语言类型
if (StrUtil.isNotBlank(nodeSimpleVO.getLanguage())) {
LiteFlowNodeBuilder.createScriptNode()
.setId(nodeSimpleVO.getNodeId())
.setType(NodeTypeEnum.getEnumByCode(nodeSimpleVO.getType()))
.setName(nodeSimpleVO.getName())
.setScript(newValue)
.setLanguage(nodeSimpleVO.getLanguage())
.build();
}
// 没有语言类型
else {
LiteFlowNodeBuilder.createScriptNode()
.setId(nodeSimpleVO.getNodeId())
.setType(NodeTypeEnum.getEnumByCode(nodeSimpleVO.getType()))
.setName(nodeSimpleVO.getName())
.setScript(newValue)
.build();
}
}
public static NodeSimpleVO convert(String scriptKey){<FILL_FUNCTION_BODY>}
public static class NodeSimpleVO {
private String nodeId;
private String type;
private String name = StrUtil.EMPTY;
private String language;
private Boolean enable = Boolean.TRUE;
private String script;
public String getNodeId() {
return nodeId;
}
public void setNodeId(String nodeId) {
this.nodeId = nodeId;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public Boolean getEnable() {
return enable;
}
public void setEnable(Boolean enable) {
this.enable = enable;
}
public String getScript() {
return script;
}
public void setScript(String script) {
this.script = script;
}
}
}
|
// 不需要去理解这串正则,就是一个匹配冒号的
// 一定得是a:b,或是a:b:c...这种完整类型的字符串的
List<String> matchItemList = ReUtil.findAllGroup0("(?<=[^:]:)[^:]+|[^:]+(?=:[^:])", scriptKey);
if (CollUtil.isEmpty(matchItemList)) {
return null;
}
NodeSimpleVO nodeSimpleVO = new NodeSimpleVO();
if (matchItemList.size() > 1) {
nodeSimpleVO.setNodeId(matchItemList.get(0));
nodeSimpleVO.setType(matchItemList.get(1));
}
if (matchItemList.size() > 2) {
nodeSimpleVO.setName(matchItemList.get(2));
}
if (matchItemList.size() > 3) {
nodeSimpleVO.setLanguage(matchItemList.get(3));
}
if (matchItemList.size() > 4) {
nodeSimpleVO.setEnable(Boolean.TRUE.toString().equalsIgnoreCase(matchItemList.get(4)));
}
return nodeSimpleVO;
| 589
| 304
| 893
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/property/LiteflowConfigGetter.java
|
LiteflowConfigGetter
|
get
|
class LiteflowConfigGetter {
private static LiteflowConfig liteflowConfig;
public static LiteflowConfig get() {<FILL_FUNCTION_BODY>}
public static void clean() {
liteflowConfig = null;
}
public static void setLiteflowConfig(LiteflowConfig liteflowConfig) {
LiteflowConfigGetter.liteflowConfig = liteflowConfig;
}
}
|
if (ObjectUtil.isNull(liteflowConfig)) {
liteflowConfig = ContextAwareHolder.loadContextAware().getBean(LiteflowConfig.class);
// 这里liteflowConfig不可能为null
// 如果在springboot环境,由于自动装配,所以不可能为null
// 在spring环境,如果xml没配置,在FlowExecutor的init时候就已经报错了
// 非spring环境下,FlowExecutorHolder.loadInstance(config)的时候,会把config放入这个类的静态属性中
if (ObjectUtil.isNull(liteflowConfig)) {
liteflowConfig = new LiteflowConfig();
}
}
return liteflowConfig;
| 111
| 178
| 289
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/script/ScriptExecutor.java
|
ScriptExecutor
|
bindParam
|
class ScriptExecutor {
public ScriptExecutor init(){
return this;
}
public abstract void load(String nodeId, String script);
// 卸载脚本(不包含 node)
public abstract void unLoad(String nodeId);
// 获取该执行器下的所有 nodeId
public abstract List<String> getNodeIds();
public Object execute(ScriptExecuteWrap wrap) throws Exception{
try {
return executeScript(wrap);
}catch (Exception e) {
if (ObjectUtil.isNotNull(e.getCause()) && e.getCause() instanceof LiteFlowException) {
throw (LiteFlowException) e.getCause();
}
else if (ObjectUtil.isNotNull(e.getCause()) && e.getCause() instanceof RuntimeException) {
throw (RuntimeException) e.getCause();
}
else {
throw e;
}
}
}
public abstract Object executeScript(ScriptExecuteWrap wrap) throws Exception;
public abstract void cleanCache();
public abstract ScriptTypeEnum scriptType();
public void bindParam(ScriptExecuteWrap wrap, BiConsumer<String, Object> putConsumer, BiConsumer<String, Object> putIfAbsentConsumer){<FILL_FUNCTION_BODY>}
/**
* 利用相应框架编译脚本
*
* @param script 脚本
* @return boolean
* @throws Exception 例外
*/
public abstract Object compile(String script) throws Exception;
}
|
// 往脚本语言绑定表里循环增加绑定上下文的key
// key的规则为自定义上下文的simpleName
// 比如你的自定义上下文为AbcContext,那么key就为:abcContext
// 这里不统一放一个map的原因是考虑到有些用户会调用上下文里的方法,而不是参数,所以脚本语言的绑定表里也是放多个上下文
DataBus.getContextBeanList(wrap.getSlotIndex()).forEach(tuple -> putConsumer.accept(tuple.get(0), tuple.get(1)));
// 把wrap对象转换成元数据map
Map<String, Object> metaMap = BeanUtil.beanToMap(wrap);
// 在元数据里放入主Chain的流程参数
Slot slot = DataBus.getSlot(wrap.getSlotIndex());
metaMap.put("requestData", slot.getRequestData());
// 如果有隐式流程,则放入隐式流程的流程参数
Object subRequestData = slot.getChainReqData(wrap.getCurrChainId());
if (ObjectUtil.isNotNull(subRequestData)) {
metaMap.put("subRequestData", subRequestData);
}
// 往脚本上下文里放入元数据
putConsumer.accept("_meta", metaMap);
// 放入用户自己定义的bean
ScriptBeanManager.getScriptBeanMap().forEach(putIfAbsentConsumer);
| 372
| 373
| 745
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/script/ScriptExecutorFactory.java
|
ScriptExecutorFactory
|
loadInstance
|
class ScriptExecutorFactory {
private static ScriptExecutorFactory scriptExecutorFactory;
private final Map<String, ScriptExecutor> scriptExecutorMap = new HashMap<>();
private final String NONE_LANGUAGE = "none";
public static ScriptExecutorFactory loadInstance() {<FILL_FUNCTION_BODY>}
public ScriptExecutor getScriptExecutor(String language) {
if (StrUtil.isBlank(language)) {
language = NONE_LANGUAGE;
}
if (!scriptExecutorMap.containsKey(language)) {
ServiceLoader<ScriptExecutor> loader = ServiceLoader.load(ScriptExecutor.class);
ScriptExecutor scriptExecutor;
Iterator<ScriptExecutor> it = loader.iterator();
while (it.hasNext()) {
scriptExecutor = it.next().init();
if (language.equals(NONE_LANGUAGE)) {
scriptExecutorMap.put(language, scriptExecutor);
break;
}
else {
ScriptTypeEnum scriptType = ScriptTypeEnum.getEnumByDisplayName(language);
if (ObjectUtil.isNull(scriptType)) {
throw new ScriptSpiException("script language config error");
}
if (scriptType.equals(scriptExecutor.scriptType())) {
scriptExecutorMap.put(language, scriptExecutor);
break;
}
}
}
}
if (scriptExecutorMap.containsKey(language)) {
return scriptExecutorMap.get(language);
}
else {
throw new ScriptSpiException("script spi component failed to load");
}
}
public void cleanScriptCache() {
this.scriptExecutorMap.forEach((key, value) -> value.cleanCache());
}
}
|
if (ObjectUtil.isNull(scriptExecutorFactory)) {
scriptExecutorFactory = new ScriptExecutorFactory();
}
return scriptExecutorFactory;
| 433
| 40
| 473
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/script/jsr223/JSR223ScriptExecutor.java
|
JSR223ScriptExecutor
|
compile
|
class JSR223ScriptExecutor extends ScriptExecutor {
protected final LFLog LOG = LFLoggerManager.getLogger(this.getClass());
private ScriptEngine scriptEngine;
private final Map<String, CompiledScript> compiledScriptMap = new CopyOnWriteHashMap<>();
@Override
public ScriptExecutor init() {
ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
scriptEngine = scriptEngineManager.getEngineByName(this.scriptType().getEngineName());
return this;
}
protected String convertScript(String script) {
return script;
}
@Override
public void load(String nodeId, String script) {
try {
compiledScriptMap.put(nodeId, (CompiledScript) compile(script));
}
catch (Exception e) {
String errorMsg = StrUtil.format("script loading error for node[{}], error msg:{}", nodeId, e.getMessage());
throw new ScriptLoadException(errorMsg);
}
}
@Override
public void unLoad(String nodeId) {
compiledScriptMap.remove(nodeId);
}
@Override
public List<String> getNodeIds() {
return new ArrayList<>(compiledScriptMap.keySet());
}
@Override
public Object executeScript(ScriptExecuteWrap wrap) throws Exception {
if (!compiledScriptMap.containsKey(wrap.getNodeId())) {
String errorMsg = StrUtil.format("script for node[{}] is not loaded", wrap.getNodeId());
throw new ScriptLoadException(errorMsg);
}
CompiledScript compiledScript = compiledScriptMap.get(wrap.getNodeId());
Bindings bindings = new SimpleBindings();
bindParam(wrap, bindings::put, bindings::putIfAbsent);
return compiledScript.eval(bindings);
}
@Override
public void cleanCache() {
compiledScriptMap.clear();
}
@Override
public Object compile(String script) throws ScriptException {<FILL_FUNCTION_BODY>}
}
|
if(scriptEngine == null) {
LOG.error("script engine has not init");
}
return ((Compilable) scriptEngine).compile(convertScript(script));
| 514
| 47
| 561
|
<methods>public non-sealed void <init>() ,public void bindParam(com.yomahub.liteflow.script.ScriptExecuteWrap, BiConsumer<java.lang.String,java.lang.Object>, BiConsumer<java.lang.String,java.lang.Object>) ,public abstract void cleanCache() ,public abstract java.lang.Object compile(java.lang.String) throws java.lang.Exception,public java.lang.Object execute(com.yomahub.liteflow.script.ScriptExecuteWrap) throws java.lang.Exception,public abstract java.lang.Object executeScript(com.yomahub.liteflow.script.ScriptExecuteWrap) throws java.lang.Exception,public abstract List<java.lang.String> getNodeIds() ,public com.yomahub.liteflow.script.ScriptExecutor init() ,public abstract void load(java.lang.String, java.lang.String) ,public abstract com.yomahub.liteflow.enums.ScriptTypeEnum scriptType() ,public abstract void unLoad(java.lang.String) <variables>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/script/proxy/ScriptBeanProxy.java
|
ScriptBeanProxy
|
getProxyScriptBean
|
class ScriptBeanProxy {
private final LFLog LOG = LFLoggerManager.getLogger(this.getClass());
private final Object bean;
private final Class<?> orignalClass;
private final ScriptBean scriptBeanAnno;
public ScriptBeanProxy(Object bean, Class<?> orignalClass, ScriptBean scriptBeanAnno) {
this.bean = bean;
this.orignalClass = orignalClass;
this.scriptBeanAnno = scriptBeanAnno;
}
public Object getProxyScriptBean() {<FILL_FUNCTION_BODY>}
public class AopInvocationHandler implements InvocationHandler {
private final Object bean;
private final Class<?> clazz;
private final List<String> canExecuteMethodNameList;
public AopInvocationHandler(Object bean, List<String> canExecuteMethodNameList) {
this.bean = bean;
this.clazz = LiteFlowProxyUtil.getUserClass(bean.getClass());
this.canExecuteMethodNameList = canExecuteMethodNameList;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Method invokeMethod = Arrays.stream(clazz.getMethods())
.filter(m -> m.getName().equals(method.getName())
&& m.getParameterCount() == method.getParameterCount())
.findFirst()
.orElse(null);
if (invokeMethod == null) {
String errorMsg = StrUtil.format("cannot find method[{}]", clazz.getName(), method.getName());
throw new ScriptBeanMethodInvokeException(errorMsg);
}
if (!canExecuteMethodNameList.contains(method.getName())) {
String errorMsg = StrUtil.format("script bean method[{}.{}] cannot be executed", clazz.getName(),
method.getName());
throw new ScriptBeanMethodInvokeException(errorMsg);
}
return invokeMethod.invoke(bean, args);
}
}
}
|
// 获取bean里所有的method,包括超类里的
List<String> methodNameList = Arrays.stream(orignalClass.getMethods())
.map(Method::getName)
.collect(Collectors.toList());
// 首先看@ScriptBean标注里的includeMethodName属性
// 如果没有配置,则认为是全部的method,如果有配置,就取配置的method
if (ArrayUtil.isNotEmpty(scriptBeanAnno.includeMethodName())) {
methodNameList = methodNameList.stream()
.filter(methodName -> ListUtil.toList(scriptBeanAnno.includeMethodName()).contains(methodName))
.collect(Collectors.toList());
}
// 其次看excludeMethodName的配置
if (ArrayUtil.isNotEmpty(scriptBeanAnno.excludeMethodName())) {
methodNameList = methodNameList.stream()
.filter(methodName -> !ListUtil.toList(scriptBeanAnno.excludeMethodName()).contains(methodName))
.collect(Collectors.toList());
}
try {
Class<?> c = new ByteBuddy().subclass(orignalClass).name(StrUtil.format("{}.ByteBuddy${}", ClassUtil.getPackage(orignalClass),SerialsUtil.generateShortUUID()))
.implement(bean.getClass().getInterfaces())
.method(ElementMatchers.any())
.intercept(InvocationHandlerAdapter.of(new AopInvocationHandler(bean, methodNameList)))
.annotateType(orignalClass.getAnnotations())
.make()
.load(ScriptBeanProxy.class.getClassLoader(), ClassLoadingStrategy.Default.INJECTION)
.getLoaded();
return ReflectUtil.newInstanceIfPossible(c);
}
catch (Exception e) {
throw new ProxyException(e);
}
| 510
| 487
| 997
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/script/proxy/ScriptMethodProxy.java
|
ScriptMethodProxy
|
getProxyScriptMethod
|
class ScriptMethodProxy {
/**
* 被代理的 bean
*/
private final Object bean;
/**
* 原始的类
*/
private final Class<?> orignalClass;
private final List<Method> scriptMethods;
public ScriptMethodProxy(Object bean, Class<?> orignalClass, List<Method> scriptMethods) {
this.bean = bean;
this.orignalClass = orignalClass;
this.scriptMethods = scriptMethods;
}
public Object getProxyScriptMethod() {<FILL_FUNCTION_BODY>}
private String buildClassName() {
return StrUtil.format("{}.ByteBuddy${}", ClassUtil.getPackage(orignalClass), SerialsUtil.generateShortUUID());
}
public static class AopInvocationHandler implements InvocationHandler {
private final Object bean;
private final Class<?> clazz;
private final Set<Method> methodSet;
public AopInvocationHandler(Object bean, List<Method> methods) {
this.bean = bean;
this.clazz = LiteFlowProxyUtil.getUserClass(bean.getClass());
this.methodSet = new HashSet<>(methods);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Optional<Method> invokeMethodOp = Arrays.stream(clazz.getMethods()).filter(method::equals).findFirst();
if (!invokeMethodOp.isPresent()) {
String errorMsg = StrUtil.format("cannot find method[{}]", clazz.getName(), method.getName());
throw new ScriptBeanMethodInvokeException(errorMsg);
}
if (!methodSet.contains(method)) {
String errorMsg = StrUtil.format("script method[{}.{}] cannot be executed", clazz.getName(),
method.getName());
throw new ScriptBeanMethodInvokeException(errorMsg);
}
return invokeMethodOp.get().invoke(bean, args);
}
}
}
|
try {
return new ByteBuddy().subclass(orignalClass)
.name(buildClassName()) // 设置生成的类名
.implement(bean.getClass().getInterfaces())
.method(ElementMatchers.any())
.intercept(InvocationHandlerAdapter.of(new AopInvocationHandler(bean, scriptMethods)))
.annotateType(orignalClass.getAnnotations())
.make()
.load(ScriptBeanProxy.class.getClassLoader(), ClassLoadingStrategy.Default.INJECTION)
.getLoaded()
.newInstance();
}
catch (Exception e) {
throw new LiteFlowException(e);
}
| 512
| 181
| 693
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/script/validator/ScriptValidator.java
|
ScriptValidator
|
validateScript
|
class ScriptValidator {
private static final LFLog LOG = LFLoggerManager.getLogger(ScriptValidator.class);
private static Map<ScriptTypeEnum, ScriptExecutor> scriptExecutors;
static {
List<ScriptExecutor> scriptExecutorList = new ArrayList<>();
scriptExecutors = new HashMap<>();
ServiceLoader.load(ScriptExecutor.class).forEach(scriptExecutorList::add);
scriptExecutorList.stream()
.peek(ScriptExecutor::init)
.forEach(scriptExecutor -> scriptExecutors.put(scriptExecutor.scriptType(), scriptExecutor));
}
/**
* 验证脚本逻辑的公共部分
*
* @param script 脚本
* @param scriptType 脚本类型
* @return boolean
*/
private static boolean validateScript(String script, ScriptTypeEnum scriptType){<FILL_FUNCTION_BODY>}
/**
* 只引入一种脚本语言时,可以不指定语言验证
*
* @param script 脚本
* @return boolean
*/
public static boolean validate(String script){
return validateScript(script, null);
}
/**
* 指定脚本语言验证
*
* @param script 脚本
* @param scriptType 脚本类型
* @return boolean
*/
public static boolean validate(String script, ScriptTypeEnum scriptType){
return validateScript(script, scriptType);
}
/**
* 多语言脚本批量验证
*
* @param scripts 脚本
* @return boolean
*/
public static boolean validate(Map<ScriptTypeEnum, String> scripts){
for(Map.Entry<ScriptTypeEnum, String> script : scripts.entrySet()){
if(!validate(script.getValue(), script.getKey())){
return false;
}
}
return true;
}
}
|
// 未加载任何脚本模块
if(scriptExecutors.isEmpty()){
LOG.error("The loaded script modules not found.");
return false;
}
// 指定脚本语言未加载
if (scriptType != null && !scriptExecutors.containsKey(scriptType)) {
LOG.error(StrUtil.format("Specified script language {} was not found.", scriptType));
return false;
}
// 加载多个脚本语言需要指定语言验证
if (scriptExecutors.size() > 1 && scriptType == null) {
LOG.error("The loaded script modules more than 1. Please specify the script language.");
return false;
}
ScriptExecutor scriptExecutor = (scriptType != null) ? scriptExecutors.get(scriptType) : scriptExecutors.values().iterator().next();
try {
scriptExecutor.compile(script);
} catch (Exception e) {
LOG.error(StrUtil.format("{} Script component validate failure. ", scriptExecutor.scriptType()) + e.getMessage());
return false;
}
return true;
| 481
| 278
| 759
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/slot/DataBus.java
|
DataBus
|
offerIndex
|
class DataBus {
private static final LFLog LOG = LFLoggerManager.getLogger(DataBus.class);
public static AtomicInteger OCCUPY_COUNT = new AtomicInteger(0);
/**
* 这里为什么采用ConcurrentHashMap作为slot存放的容器?
* 因为ConcurrentHashMap的随机取值复杂度也和数组一样为O(1),并且没有并发问题,还有自动扩容的功能
* 用数组的话,扩容涉及copy,线程安全问题还要自己处理
*/
private static ConcurrentHashMap<Integer, Slot> SLOTS;
private static ConcurrentLinkedQueue<Integer> QUEUE;
/**
* 当前slot的下标index的最大值
*/
private static Integer currentIndexMaxValue;
/**
* 这里原先版本中是static块,现在改成init静态方法,由FlowExecutor中的init去调用
* 这样的改动对项目来说没有什么实际意义,但是在单元测试中,却有意义。
* 因为单元测试中所有的一起跑,jvm是不退出的,所以如果是static块的话,跑多个testsuite只会执行一次。
* 而由FlowExecutor中的init去调用,是会被执行多次的。保证了每个单元测试都能初始化一遍
*/
public static void init() {
if (MapUtil.isEmpty(SLOTS)) {
LiteflowConfig liteflowConfig = LiteflowConfigGetter.get();
currentIndexMaxValue = liteflowConfig.getSlotSize();
SLOTS = new ConcurrentHashMap<>();
QUEUE = IntStream.range(0, currentIndexMaxValue)
.boxed()
.collect(Collectors.toCollection(ConcurrentLinkedQueue::new));
}
}
public static int offerSlotByClass(List<Class<?>> contextClazzList) {
// 把classList通过反射初始化成对象列表
// 这里用newInstanceIfPossible这个方法,是为了兼容当没有无参构造方法所报的错
List<Object> contextBeanList = contextClazzList.stream()
.map((Function<Class<?>, Object>) ReflectUtil::newInstanceIfPossible)
.collect(Collectors.toList());
return offerSlotByBean(contextBeanList);
}
public static int offerSlotByBean(List<Object> contextList) {
List<Tuple> contextBeanList = contextList.stream().map(object -> {
ContextBean contextBean = AnnoUtil.getAnnotation(object.getClass(), ContextBean.class);
String contextKey;
if (contextBean != null && StrUtil.isNotBlank(contextBean.value())){
contextKey = contextBean.value();
}else{
contextKey = StrUtil.lowerFirst(object.getClass().getSimpleName());
}
return new Tuple(contextKey, object);
}).collect(Collectors.toList());
Slot slot = new Slot(contextBeanList);
return offerIndex(slot);
}
private static int offerIndex(Slot slot) {<FILL_FUNCTION_BODY>}
public static Slot getSlot(int slotIndex) {
return SLOTS.get(slotIndex);
}
public static List<Tuple> getContextBeanList(int slotIndex) {
Slot slot = getSlot(slotIndex);
return slot.getContextBeanList();
}
public static void releaseSlot(int slotIndex) {
if (ObjectUtil.isNotNull(SLOTS.get(slotIndex))) {
LOG.info("slot[{}] released", slotIndex);
SLOTS.remove(slotIndex);
QUEUE.add(slotIndex);
OCCUPY_COUNT.decrementAndGet();
}
else {
LOG.warn("slot[{}] already has been released", slotIndex);
}
}
}
|
try {
// 这里有没有并发问题?
// 没有,因为QUEUE的类型为ConcurrentLinkedQueue,并发情况下,每次取到的index不会相同
// 当然前提是QUEUE里面的值不会重复,但是这个是由其他机制来保证的
Integer slotIndex = QUEUE.poll();
if (ObjectUtil.isNull(slotIndex)) {
// 只有在扩容的时候需要用到synchronized重量级锁
// 扩一次容,增强原来size的0.75,因为初始slot容量为1024,从某种层面来说,即便并发很大。但是扩容的次数不会很多。
// 因为单个机器的tps上限总归是有一个极限的,不可能无限制的增长。
synchronized (DataBus.class) {
// 在扩容的一刹那,去竞争这个锁的线程还是有一些,所以获得这个锁的线程这里要再次取一次。如果为null,再真正扩容
slotIndex = QUEUE.poll();
if (ObjectUtil.isNull(slotIndex)) {
int nextMaxIndex = (int) Math.round(currentIndexMaxValue * 1.75);
QUEUE.addAll(IntStream.range(currentIndexMaxValue, nextMaxIndex)
.boxed()
.collect(Collectors.toCollection(ConcurrentLinkedQueue::new)));
currentIndexMaxValue = nextMaxIndex;
// 扩容好,从队列里再取出扩容好的index
slotIndex = QUEUE.poll();
}
}
}
if (ObjectUtil.isNotNull(slotIndex)) {
SLOTS.put(slotIndex, slot);
OCCUPY_COUNT.incrementAndGet();
return slotIndex;
}
}
catch (Exception e) {
LOG.error("offer slot error", e);
return -1;
}
return -1;
| 1,003
| 505
| 1,508
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/slot/DefaultContext.java
|
DefaultContext
|
putDataMap
|
class DefaultContext {
private final ConcurrentHashMap<String, Object> dataMap = new ConcurrentHashMap<>();
private <T> void putDataMap(String key, T t) {<FILL_FUNCTION_BODY>}
public boolean hasData(String key) {
return dataMap.containsKey(key);
}
public <T> T getData(String key) {
return (T) dataMap.get(key);
}
public <T> void setData(String key, T t) {
putDataMap(key, t);
}
}
|
if (ObjectUtil.isNull(t)) {
throw new NullParamException("data can't accept null param");
}
dataMap.put(key, t);
| 144
| 48
| 192
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/spi/holder/CmpAroundAspectHolder.java
|
CmpAroundAspectHolder
|
loadCmpAroundAspect
|
class CmpAroundAspectHolder {
private static CmpAroundAspect cmpAroundAspect;
public static CmpAroundAspect loadCmpAroundAspect() {<FILL_FUNCTION_BODY>}
public static void clean() {
cmpAroundAspect = null;
}
}
|
if (ObjectUtil.isNull(cmpAroundAspect)) {
List<CmpAroundAspect> list = new ArrayList<>();
ServiceLoader.load(CmpAroundAspect.class).forEach(list::add);
list.sort(Comparator.comparingInt(CmpAroundAspect::priority));
cmpAroundAspect = list.get(0);
}
return cmpAroundAspect;
| 82
| 115
| 197
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/spi/holder/ContextAwareHolder.java
|
ContextAwareHolder
|
loadContextAware
|
class ContextAwareHolder {
private static ContextAware contextAware;
public static ContextAware loadContextAware() {<FILL_FUNCTION_BODY>}
public static void clean() {
contextAware = null;
}
}
|
if (ObjectUtil.isNull(contextAware)) {
List<ContextAware> list = new ArrayList<>();
ServiceLoader.load(ContextAware.class).forEach(list::add);
list.sort(Comparator.comparingInt(ContextAware::priority));
contextAware = list.get(0);
}
return contextAware;
| 65
| 98
| 163
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/spi/holder/ContextCmpInitHolder.java
|
ContextCmpInitHolder
|
loadContextCmpInit
|
class ContextCmpInitHolder {
private static ContextCmpInit contextCmpInit;
public static ContextCmpInit loadContextCmpInit() {<FILL_FUNCTION_BODY>}
public static void clean() {
contextCmpInit = null;
}
}
|
if (ObjectUtil.isNull(contextCmpInit)) {
List<ContextCmpInit> list = new ArrayList<>();
ServiceLoader.load(ContextCmpInit.class).forEach(list::add);
list.sort(Comparator.comparingInt(ContextCmpInit::priority));
contextCmpInit = list.get(0);
}
return contextCmpInit;
| 71
| 104
| 175
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/spi/holder/DeclComponentParserHolder.java
|
DeclComponentParserHolder
|
loadDeclComponentParser
|
class DeclComponentParserHolder {
private static DeclComponentParser declComponentParser;
public static DeclComponentParser loadDeclComponentParser(){<FILL_FUNCTION_BODY>}
}
|
if (ObjectUtil.isNull(declComponentParser)) {
List<DeclComponentParser> list = new ArrayList<>();
ServiceLoader.load(DeclComponentParser.class).forEach(list::add);
list.sort(Comparator.comparingInt(DeclComponentParser::priority));
declComponentParser = list.get(0);
}
return declComponentParser;
| 46
| 94
| 140
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/spi/holder/LiteflowComponentSupportHolder.java
|
LiteflowComponentSupportHolder
|
loadLiteflowComponentSupport
|
class LiteflowComponentSupportHolder {
private static LiteflowComponentSupport liteflowComponentSupport;
public static LiteflowComponentSupport loadLiteflowComponentSupport() {<FILL_FUNCTION_BODY>}
public static void clean() {
liteflowComponentSupport = null;
}
}
|
if (ObjectUtil.isNull(liteflowComponentSupport)) {
List<LiteflowComponentSupport> list = new ArrayList<>();
ServiceLoader.load(LiteflowComponentSupport.class).forEach(list::add);
list.sort(Comparator.comparingInt(LiteflowComponentSupport::priority));
liteflowComponentSupport = list.get(0);
}
return liteflowComponentSupport;
| 77
| 110
| 187
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/spi/holder/PathContentParserHolder.java
|
PathContentParserHolder
|
loadContextAware
|
class PathContentParserHolder {
private static PathContentParser pathContentParser;
public static PathContentParser loadContextAware() {<FILL_FUNCTION_BODY>}
public static void clean() {
pathContentParser = null;
}
}
|
if (ObjectUtil.isNull(pathContentParser)) {
List<PathContentParser> list = new ArrayList<>();
ServiceLoader.load(PathContentParser.class).forEach(list::add);
list.sort(Comparator.comparingInt(PathContentParser::priority));
pathContentParser = list.get(0);
}
return pathContentParser;
| 65
| 98
| 163
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/spi/local/LocalDeclComponentParser.java
|
LocalDeclComponentParser
|
parseDeclBean
|
class LocalDeclComponentParser implements DeclComponentParser {
@Override
public List<DeclWarpBean> parseDeclBean(Class<?> clazz) {
throw new NotSupportDeclException("the declaration component is not supported in non-spring environment.");
}
@Override
public List<DeclWarpBean> parseDeclBean(Class<?> clazz, String nodeId, String nodeName) {<FILL_FUNCTION_BODY>}
@Override
public int priority() {
return 2;
}
}
|
throw new NotSupportDeclException("the declaration component is not supported in non-spring environment.");
| 131
| 24
| 155
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/spi/local/LocalPathContentParser.java
|
LocalPathContentParser
|
parseContent
|
class LocalPathContentParser implements PathContentParser {
private final static String FILE_URL_PREFIX = "file:";
private final static String CLASSPATH_URL_PREFIX = "classpath:";
@Override
public List<String> parseContent(List<String> pathList) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public List<String> getFileAbsolutePath(List<String> pathList) throws Exception {
if (CollectionUtil.isEmpty(pathList)) {
throw new ConfigErrorException("rule source must not be null");
}
List<String> absolutePathList = PathMatchUtil.searchAbsolutePath(pathList);
List<String> result = new ArrayList<>();
for (String path : absolutePathList) {
if (FileUtil.isAbsolutePath(path) && FileUtil.isFile(path)) {
path = FILE_URL_PREFIX + path;
result.add(new FileResource(path).getFile().getAbsolutePath());
}
else {
if (!path.startsWith(CLASSPATH_URL_PREFIX)) {
path = CLASSPATH_URL_PREFIX + path;
// 这里会有自定义解析器
if (ClassLoaderUtil.isPresent(path)) {
result.add(new ClassPathResource(path).getAbsolutePath());
}
}
}
}
return result;
}
@Override
public int priority() {
return 2;
}
}
|
if (CollectionUtil.isEmpty(pathList)) {
throw new ConfigErrorException("rule source must not be null");
}
List<String> absolutePathList = PathMatchUtil.searchAbsolutePath(pathList);
List<String> contentList = new ArrayList<>();
for (String path : absolutePathList) {
if (FileUtil.isAbsolutePath(path) && FileUtil.isFile(path)) {
path = FILE_URL_PREFIX + path;
}
else {
if (!path.startsWith(CLASSPATH_URL_PREFIX)) {
path = CLASSPATH_URL_PREFIX + path;
}
}
String content = ResourceUtil.readUtf8Str(path);
if (StrUtil.isNotBlank(content)) {
contentList.add(content);
}
}
return contentList;
| 376
| 225
| 601
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/thread/ExecutorHelper.java
|
Holder
|
getExecutorService
|
class Holder {
static final ExecutorHelper INSTANCE = new ExecutorHelper();
}
public static ExecutorHelper loadInstance() {
return Holder.INSTANCE;
}
/**
*
* <p>
* @param pool 需要关闭的线程组.
*/
public void shutdownAwaitTermination(ExecutorService pool) {
shutdownAwaitTermination(pool, 60L);
}
/**
* <p>
* 关闭ExecutorService的线程管理者
* <p>
* @param pool 需要关闭的管理者
* @param timeout 等待时间
*/
public void shutdownAwaitTermination(ExecutorService pool, long timeout) {
pool.shutdown();
try {
if (!pool.awaitTermination(timeout, TimeUnit.SECONDS)) {
pool.shutdownNow();
if (!pool.awaitTermination(timeout, TimeUnit.SECONDS)) {
LOG.error("Pool did not terminate.");
}
}
}
catch (InterruptedException ie) {
pool.shutdownNow();
Thread.currentThread().interrupt();
}
}
// 构建默认when线程池
public ExecutorService buildWhenExecutor() {
LiteflowConfig liteflowConfig = LiteflowConfigGetter.get();
return buildWhenExecutor(liteflowConfig.getThreadExecutorClass());
}
// 构建when线程池 - 支持多个when公用一个线程池
public ExecutorService buildWhenExecutor(String clazz) {
if (StrUtil.isBlank(clazz)) {
return buildWhenExecutor();
}
return getExecutorService(clazz);
}
// 构建when线程池 - clazz和condition的hash值共同作为缓存key
public ExecutorService buildWhenExecutorWithHash(String conditionHash) {
LiteflowConfig liteflowConfig = LiteflowConfigGetter.get();
return buildWhenExecutorWithHash(liteflowConfig.getThreadExecutorClass(), conditionHash);
}
// 构建when线程池 - clazz和condition的hash值共同作为缓存key
public ExecutorService buildWhenExecutorWithHash(String clazz, String conditionHash) {
if (StrUtil.isBlank(clazz)) {
return buildWhenExecutorWithHash(conditionHash);
}
return getExecutorService(clazz, conditionHash);
}
// 构建默认的FlowExecutor线程池,用于execute2Future方法
public ExecutorService buildMainExecutor() {
LiteflowConfig liteflowConfig = LiteflowConfigGetter.get();
return buildMainExecutor(liteflowConfig.getMainExecutorClass());
}
public ExecutorService buildMainExecutor(String clazz) {
if (StrUtil.isBlank(clazz)) {
return buildMainExecutor();
}
return getExecutorService(clazz);
}
//构造并行循环的线程池
public ExecutorService buildLoopParallelExecutor(){
LiteflowConfig liteflowConfig = LiteflowConfigGetter.get();
return getExecutorService(liteflowConfig.getParallelLoopExecutorClass());
}
private ExecutorService getExecutorService(String clazz){
return getExecutorService(clazz, null);
}
/**
* 根据线程执行构建者Class类名获取ExecutorService实例
*/
private ExecutorService getExecutorService(String clazz, String conditionHash) {<FILL_FUNCTION_BODY>
|
try {
String key;
if (StrUtil.isBlank(conditionHash)){
key = clazz;
}else{
key = StrUtil.format("{}_{}", clazz, conditionHash);
}
ExecutorService executorServiceFromCache = executorServiceMap.get(key);
if (ObjectUtil.isNotNull(executorServiceFromCache)) {
return executorServiceFromCache;
}
else {
Class<ExecutorBuilder> executorClass = (Class<ExecutorBuilder>) Class.forName(clazz);
ExecutorBuilder executorBuilder = ContextAwareHolder.loadContextAware().registerBean(executorClass);
ExecutorService executorService = executorBuilder.buildExecutor();
executorServiceMap.put(key, executorService);
return executorService;
}
}
catch (Exception e) {
LOG.error(e.getMessage());
throw new ThreadExecutorServiceCreateException(e.getMessage());
}
| 873
| 253
| 1,126
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/thread/LiteFlowDefaultMainExecutorBuilder.java
|
LiteFlowDefaultMainExecutorBuilder
|
buildExecutor
|
class LiteFlowDefaultMainExecutorBuilder implements ExecutorBuilder {
@Override
public ExecutorService buildExecutor() {<FILL_FUNCTION_BODY>}
}
|
LiteflowConfig liteflowConfig = LiteflowConfigGetter.get();
// 只有在非spring的场景下liteflowConfig才会为null
if (ObjectUtil.isNull(liteflowConfig)) {
liteflowConfig = new LiteflowConfig();
}
return buildDefaultExecutor(liteflowConfig.getMainExecutorWorks(), liteflowConfig.getMainExecutorWorks()*2, 200,
"main-thread-");
| 42
| 118
| 160
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/thread/LiteFlowDefaultParallelLoopExecutorBuilder.java
|
LiteFlowDefaultParallelLoopExecutorBuilder
|
buildExecutor
|
class LiteFlowDefaultParallelLoopExecutorBuilder implements ExecutorBuilder {
@Override
public ExecutorService buildExecutor() {<FILL_FUNCTION_BODY>}
}
|
LiteflowConfig liteflowConfig = LiteflowConfigGetter.get();
// 只有在非spring的场景下liteflowConfig才会为null
if (ObjectUtil.isNull(liteflowConfig)) {
liteflowConfig = new LiteflowConfig();
}
return buildDefaultExecutor(liteflowConfig.getParallelMaxWorkers(), liteflowConfig.getParallelMaxWorkers(),
liteflowConfig.getParallelQueueLimit(), "loop-thread-");
| 44
| 123
| 167
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/thread/LiteFlowDefaultWhenExecutorBuilder.java
|
LiteFlowDefaultWhenExecutorBuilder
|
buildExecutor
|
class LiteFlowDefaultWhenExecutorBuilder implements ExecutorBuilder {
@Override
public ExecutorService buildExecutor() {<FILL_FUNCTION_BODY>}
}
|
LiteflowConfig liteflowConfig = LiteflowConfigGetter.get();
// 只有在非spring的场景下liteflowConfig才会为null
if (ObjectUtil.isNull(liteflowConfig)) {
liteflowConfig = new LiteflowConfig();
}
return buildDefaultExecutor(liteflowConfig.getWhenMaxWorkers(), liteflowConfig.getWhenMaxWorkers(),
liteflowConfig.getWhenQueueLimit(), "when-thread-");
| 42
| 123
| 165
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/util/BoundedPriorityBlockingQueue.java
|
BoundedPriorityBlockingQueue
|
offer
|
class BoundedPriorityBlockingQueue<E> extends PriorityBlockingQueue<E> {
private static final long serialVersionUID = -1;
// 容量
private final int capacity;
private final Comparator<? super E> comparator;
public BoundedPriorityBlockingQueue(int capacity) {
this(capacity, null);
}
/**
* 构造
* @param capacity 容量
* @param comparator 比较器
*/
public BoundedPriorityBlockingQueue(int capacity, final Comparator<? super E> comparator) {
super(capacity, (o1, o2) -> {
int cResult;
if (comparator != null) {
cResult = comparator.compare(o1, o2);
}
else {
@SuppressWarnings("unchecked")
Comparable<E> o1c = (Comparable<E>) o1;
cResult = o1c.compareTo(o2);
}
return -cResult;
});
this.capacity = capacity;
this.comparator = comparator;
}
/**
* 加入元素,当队列满时,淘汰末尾元素
* @param e 元素
* @return 加入成功与否
*/
@Override
public boolean offer(E e) {<FILL_FUNCTION_BODY>}
/**
* 添加多个元素<br>
* 参数为集合的情况请使用{@link PriorityQueue#addAll}
* @param c 元素数组
* @return 是否发生改变
*/
public boolean addAll(E[] c) {
return this.addAll(Arrays.asList(c));
}
/**
* @return 返回排序后的列表
*/
public ArrayList<E> toList() {
final ArrayList<E> list = new ArrayList<>(this);
list.sort(comparator);
return list;
}
@Override
public Iterator<E> iterator() {
return toList().iterator();
}
}
|
if (size() >= capacity) {
E head = peek();
if (this.comparator().compare(e, head) <= 0) {
return true;
}
// 当队列满时,就要淘汰顶端队列
poll();
}
return super.offer(e);
| 531
| 86
| 617
|
<methods>public void <init>() ,public void <init>(int) ,public void <init>(Collection<? extends E>) ,public void <init>(int, Comparator<? super E>) ,public boolean add(E) ,public void clear() ,public Comparator<? super E> comparator() ,public boolean contains(java.lang.Object) ,public int drainTo(Collection<? super E>) ,public int drainTo(Collection<? super E>, int) ,public void forEach(Consumer<? super E>) ,public Iterator<E> iterator() ,public boolean offer(E) ,public boolean offer(E, long, java.util.concurrent.TimeUnit) ,public E peek() ,public E poll() ,public E poll(long, java.util.concurrent.TimeUnit) throws java.lang.InterruptedException,public void put(E) ,public int remainingCapacity() ,public boolean remove(java.lang.Object) ,public boolean removeAll(Collection<?>) ,public boolean removeIf(Predicate<? super E>) ,public boolean retainAll(Collection<?>) ,public int size() ,public Spliterator<E> spliterator() ,public E take() throws java.lang.InterruptedException,public java.lang.Object[] toArray() ,public T[] toArray(T[]) ,public java.lang.String toString() <variables>private static final java.lang.invoke.VarHandle ALLOCATIONSPINLOCK,private static final int DEFAULT_INITIAL_CAPACITY,private volatile transient int allocationSpinLock,private transient Comparator<? super E> comparator,private final java.util.concurrent.locks.ReentrantLock lock,private final java.util.concurrent.locks.Condition notEmpty,private PriorityQueue<E> q,private transient java.lang.Object[] queue,private static final long serialVersionUID,private transient int size
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/util/CopyOnWriteHashMap.java
|
CopyOnWriteHashMap
|
duplicate
|
class CopyOnWriteHashMap<K, V> extends ConcurrentHashMap<K, V> {
volatile ConcurrentHashMap<K, V> view;
private ConcurrentHashMap<K, V> duplicate(ConcurrentHashMap<K, V> original) {<FILL_FUNCTION_BODY>}
public CopyOnWriteHashMap(ConcurrentHashMap<K, V> that) {
this.view = duplicate(that);
}
public CopyOnWriteHashMap() {
this(new ConcurrentHashMap<>());
}
@Override
public CopyOnWriteHashMap<K, V> clone() {
return new CopyOnWriteHashMap(view);
}
/*
* ********************** READ-ONLY OPERATIONS
**********************/
@Override
public int size() {
return view.size();
}
@Override
public boolean isEmpty() {
return view.isEmpty();
}
@Override
public boolean containsKey(Object key) {
return view.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return view.containsValue(value);
}
@Override
public V get(Object key) {
return view.get(key);
}
@Override
public KeySetView<K, V> keySet() {
return view.keySet();
}
@Override
public Collection<V> values() {
return view.values();
}
@Override
public Set<Map.Entry<K, V>> entrySet() {
return view.entrySet();
}
@Override
public String toString() {
return view.toString();
}
/*
* ********************** UPDATING OPERATIONS
*
* These operations all follow a common pattern:
*
* 1. Create a copy of the existing view. 2. Update the copy. 3. Perform a volatile
* write to replace the existing view.
*
* Note that if you are not concerned about lost updates, you could dispense with the
* synchronization entirely.
**********************/
@Override
public V put(K key, V value) {
synchronized (this) {
ConcurrentHashMap<K, V> newCore = duplicate(view);
V result = newCore.put(key, value);
view = newCore; // volatile write
return result;
}
}
@Override
public V remove(Object key) {
synchronized (this) {
ConcurrentHashMap<K, V> newCore = duplicate(view);
V result = newCore.remove(key);
view = newCore; // volatile write
return result;
}
}
@Override
public void putAll(Map<? extends K, ? extends V> t) {
synchronized (this) {
ConcurrentHashMap<K, V> newCore = duplicate(view);
newCore.putAll(t);
view = newCore; // volatile write
}
}
@Override
public void clear() {
synchronized (this) {
view = new ConcurrentHashMap<>(); // volatile write
}
}
}
|
// SUBTLETY: note that original.entrySet() grabs the entire contents of the
// original Map in a
// single call. This means that if the original map is Thread-safe or another
// CopyOnWriteHashMap,
// we can safely iterate over the list of entries.
return new ConcurrentHashMap<>(original);
| 789
| 87
| 876
|
<methods>public void <init>() ,public void <init>(int) ,public void <init>(Map<? extends K,? extends V>) ,public void <init>(int, float) ,public void <init>(int, float, int) ,public void clear() ,public V compute(K, BiFunction<? super K,? super V,? extends V>) ,public V computeIfAbsent(K, Function<? super K,? extends V>) ,public V computeIfPresent(K, BiFunction<? super K,? super V,? extends V>) ,public boolean contains(java.lang.Object) ,public boolean containsKey(java.lang.Object) ,public boolean containsValue(java.lang.Object) ,public Enumeration<V> elements() ,public Set<Entry<K,V>> entrySet() ,public boolean equals(java.lang.Object) ,public void forEach(BiConsumer<? super K,? super V>) ,public void forEach(long, BiConsumer<? super K,? super V>) ,public void forEach(long, BiFunction<? super K,? super V,? extends U>, Consumer<? super U>) ,public void forEachEntry(long, Consumer<? super Entry<K,V>>) ,public void forEachEntry(long, Function<Entry<K,V>,? extends U>, Consumer<? super U>) ,public void forEachKey(long, Consumer<? super K>) ,public void forEachKey(long, Function<? super K,? extends U>, Consumer<? super U>) ,public void forEachValue(long, Consumer<? super V>) ,public void forEachValue(long, Function<? super V,? extends U>, Consumer<? super U>) ,public V get(java.lang.Object) ,public V getOrDefault(java.lang.Object, V) ,public int hashCode() ,public boolean isEmpty() ,public KeySetView<K,V> keySet() ,public KeySetView<K,V> keySet(V) ,public Enumeration<K> keys() ,public long mappingCount() ,public V merge(K, V, BiFunction<? super V,? super V,? extends V>) ,public static KeySetView<K,java.lang.Boolean> newKeySet() ,public static KeySetView<K,java.lang.Boolean> newKeySet(int) ,public V put(K, V) ,public void putAll(Map<? extends K,? extends V>) ,public V putIfAbsent(K, V) ,public U reduce(long, BiFunction<? super K,? super V,? extends U>, BiFunction<? super U,? super U,? extends U>) ,public Entry<K,V> reduceEntries(long, BiFunction<Entry<K,V>,Entry<K,V>,? extends Entry<K,V>>) ,public U reduceEntries(long, Function<Entry<K,V>,? extends U>, BiFunction<? super U,? super U,? extends U>) ,public double reduceEntriesToDouble(long, ToDoubleFunction<Entry<K,V>>, double, java.util.function.DoubleBinaryOperator) ,public int reduceEntriesToInt(long, ToIntFunction<Entry<K,V>>, int, java.util.function.IntBinaryOperator) ,public long reduceEntriesToLong(long, ToLongFunction<Entry<K,V>>, long, java.util.function.LongBinaryOperator) ,public K reduceKeys(long, BiFunction<? super K,? super K,? extends K>) ,public U reduceKeys(long, Function<? super K,? extends U>, BiFunction<? super U,? super U,? extends U>) ,public double reduceKeysToDouble(long, ToDoubleFunction<? super K>, double, java.util.function.DoubleBinaryOperator) ,public int reduceKeysToInt(long, ToIntFunction<? super K>, int, java.util.function.IntBinaryOperator) ,public long reduceKeysToLong(long, ToLongFunction<? super K>, long, java.util.function.LongBinaryOperator) ,public double reduceToDouble(long, ToDoubleBiFunction<? super K,? super V>, double, java.util.function.DoubleBinaryOperator) ,public int reduceToInt(long, ToIntBiFunction<? super K,? super V>, int, java.util.function.IntBinaryOperator) ,public long reduceToLong(long, ToLongBiFunction<? super K,? super V>, long, java.util.function.LongBinaryOperator) ,public V reduceValues(long, BiFunction<? super V,? super V,? extends V>) ,public U reduceValues(long, Function<? super V,? extends U>, BiFunction<? super U,? super U,? extends U>) ,public double reduceValuesToDouble(long, ToDoubleFunction<? super V>, double, java.util.function.DoubleBinaryOperator) ,public int reduceValuesToInt(long, ToIntFunction<? super V>, int, java.util.function.IntBinaryOperator) ,public long reduceValuesToLong(long, ToLongFunction<? super V>, long, java.util.function.LongBinaryOperator) ,public V remove(java.lang.Object) ,public boolean remove(java.lang.Object, java.lang.Object) ,public V replace(K, V) ,public boolean replace(K, V, V) ,public void replaceAll(BiFunction<? super K,? super V,? extends V>) ,public U search(long, BiFunction<? super K,? super V,? extends U>) ,public U searchEntries(long, Function<Entry<K,V>,? extends U>) ,public U searchKeys(long, Function<? super K,? extends U>) ,public U searchValues(long, Function<? super V,? extends U>) ,public int size() ,public java.lang.String toString() ,public Collection<V> values() <variables>private static final int ABASE,private static final int ASHIFT,private static final long BASECOUNT,private static final long CELLSBUSY,private static final long CELLVALUE,private static final int DEFAULT_CAPACITY,private static final int DEFAULT_CONCURRENCY_LEVEL,static final int HASH_BITS,private static final float LOAD_FACTOR,private static final int MAXIMUM_CAPACITY,static final int MAX_ARRAY_SIZE,private static final int MAX_RESIZERS,private static final int MIN_TRANSFER_STRIDE,static final int MIN_TREEIFY_CAPACITY,static final int MOVED,static final int NCPU,static final int RESERVED,private static final int RESIZE_STAMP_BITS,private static final int RESIZE_STAMP_SHIFT,private static final long SIZECTL,private static final long TRANSFERINDEX,static final int TREEBIN,static final int TREEIFY_THRESHOLD,private static final jdk.internal.misc.Unsafe U,static final int UNTREEIFY_THRESHOLD,private volatile transient long baseCount,private volatile transient int cellsBusy,private volatile transient java.util.concurrent.ConcurrentHashMap.CounterCell[] counterCells,private transient EntrySetView<K,V> entrySet,private transient KeySetView<K,V> keySet,private volatile transient Node<K,V>[] nextTable,private static final java.io.ObjectStreamField[] serialPersistentFields,private static final long serialVersionUID,private volatile transient int sizeCtl,volatile transient Node<K,V>[] table,private volatile transient int transferIndex,private transient ValuesView<K,V> values
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/util/ElRegexUtil.java
|
ElRegexUtil
|
replaceAbstractChain
|
class ElRegexUtil {
// java 注释的正则表达式
private static final String REGEX_COMMENT = "(?<!(:|@))\\/\\/.*|\\/\\*(\\s|.)*?\\*\\/";
// abstractChain 占位符正则表达式
private static final String REGEX_ABSTRACT_HOLDER = "\\{\\{\\s*([a-zA-Z_][a-zA-Z_\\d]*|\\d+)\\s*\\}\\}(?![\\s]*=)";
/**
* 移除 el 表达式中的注释,支持 java 的注释,包括单行注释、多行注释, 会压缩字符串,移除空格和换行符
*
* @param elStr el 表达式
* @return 移除注释后的 el 表达式
*/
public static String removeComments(String elStr) {
if (StrUtil.isBlank(elStr)) {
return elStr;
}
return Pattern.compile(REGEX_COMMENT)
.matcher(elStr)
// 移除注释
.replaceAll(CharSequenceUtil.EMPTY);
}
/**
* 根据抽象EL和实现EL,替换抽象EL中的占位符
*
* @param abstractChain 抽象EL
* @param implChain 抽象EL对应的一个实现
* @return 替换后的EL
*/
public static String replaceAbstractChain(String abstractChain, String implChain) {<FILL_FUNCTION_BODY>}
/**
* 判断某个Chain是否为抽象EL,判断依据是是否包含未实现的占位符
*
* @param elStr EL表达式
* @return 判断结果,true为抽象EL,false为非抽象EL
*/
public static boolean isAbstractChain(String elStr) {
return Pattern.compile(REGEX_ABSTRACT_HOLDER).matcher(elStr).find();
}
}
|
//匹配抽象chain的占位符
Pattern placeHolder = Pattern.compile(REGEX_ABSTRACT_HOLDER);
Matcher placeHolderMatcher = placeHolder.matcher(abstractChain);
while (placeHolderMatcher.find()) {
//到implChain中找到对应的占位符实现
String holder = placeHolderMatcher.group(1);
Pattern placeHolderImpl = Pattern.compile("\\s*\\{\\{" + holder + "\\}\\}\\s*=\\s*(.*?);");
Matcher implMatcher = placeHolderImpl.matcher(implChain);
if (implMatcher.find()) {
String replacement = implMatcher.group(1).trim();
abstractChain = abstractChain.replace("{{" + holder + "}}", replacement);
} else {
throw new ParseException("missing implementation of {{" + holder + "}} in expression \r\n" + implChain);
}
}
return abstractChain;
| 523
| 246
| 769
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/util/JsonUtil.java
|
JsonUtil
|
parseObject
|
class JsonUtil {
private static final LFLog LOG = LFLoggerManager.getLogger(JsonUtil.class);
private static final ObjectMapper objectMapper = new ObjectMapper();
private JsonUtil() {
}
static {
objectMapper.setTimeZone(TimeZone.getDefault());
}
public static String toJsonString(Object object) {
if (ObjectUtil.isNull(object)) {
return null;
}
try {
return objectMapper.writeValueAsString(object);
}
catch (JsonProcessingException e) {
String errMsg = StrUtil.format("Error while writing value as string[{}],reason: {}",
object.getClass().getName(), e.getMessage());
LOG.error(e.getMessage(), e);
throw new JsonProcessException(errMsg);
}
}
public static JsonNode parseObject(String text) {
if (StrUtil.isEmpty(text)) {
return null;
}
try {
return objectMapper.readTree(text);
}
catch (IOException e) {
String errMsg = StrUtil.format("Error while parsing text [{}],reason: {}", text, e.getMessage());
LOG.error(e.getMessage(), e);
throw new JsonProcessException(errMsg);
}
}
public static <T> T parseObject(String json, Class<T> clazz) {<FILL_FUNCTION_BODY>}
}
|
if (StrUtil.isEmpty(json)) {
return null;
}
try {
return objectMapper.readValue(json, clazz);
}
catch (IOException e) {
String errMsg = StrUtil.format("Error while parsing text [{}],reason: {}", json, e.getMessage());
LOG.error(e.getMessage(), e);
throw new JsonProcessException(errMsg);
}
| 366
| 111
| 477
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/util/LOGOPrinter.java
|
LOGOPrinter
|
print
|
class LOGOPrinter {
private static final LFLog LOG = LFLoggerManager.getLogger(LOGOPrinter.class);
/**
* LiteFlow 当前版本号
*/
private static final String VERSION_NO = getVersion();
public static void print() {<FILL_FUNCTION_BODY>}
private static String getVersion() {
return Optional.ofNullable(LOGOPrinter.class.getPackage()).map(Package::getImplementationVersion).orElse("DEV");
}
}
|
StringBuilder str = new StringBuilder("\n");
str.append(
"================================================================================================\n");
str.append(" _ ___ _____ _____ _____ _ _____ __\n");
str.append(" | | |_ _|_ _| ____| | ___| | / _ \\ \\ / /\n");
str.append(" | | | | | | | _| _____| |_ | | | | | \\ \\ /\\ / / \n");
str.append(" | |___ | | | | | |__|_____| _| | |__| |_| |\\ V V / \n");
str.append(" |_____|___| |_| |_____| |_| |_____\\___/ \\_/\\_/ \n\n");
str.append(" Version: " + VERSION_NO + "\n");
str.append(" Make your code amazing.\n");
str.append(" website:https://liteflow.cc\n");
str.append(" wechat:bryan_31\n");
str.append(
"================================================================================================\n");
LOG.info(str.toString());
| 130
| 325
| 455
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/util/LimitQueue.java
|
LimitQueue
|
offer
|
class LimitQueue<E> implements Queue<E> {
/**
* 队列长度,实例化类的时候指定
*/
private int limit;
Queue<E> queue = new ConcurrentLinkedQueue<>();
public LimitQueue(int limit) {
this.limit = limit;
}
@Override
public boolean offer(E e) {<FILL_FUNCTION_BODY>}
@Override
public E poll() {
return queue.poll();
}
public Queue<E> getQueue() {
return queue;
}
public int getLimit() {
return limit;
}
@Override
public boolean add(E e) {
return queue.add(e);
}
@Override
public E element() {
return queue.element();
}
@Override
public E peek() {
return queue.peek();
}
@Override
public boolean isEmpty() {
return queue.size() == 0 ? true : false;
}
@Override
public int size() {
return queue.size();
}
@Override
public E remove() {
return queue.remove();
}
@Override
public boolean addAll(Collection<? extends E> c) {
return queue.addAll(c);
}
@Override
public void clear() {
queue.clear();
}
@Override
public boolean contains(Object o) {
return queue.contains(o);
}
@Override
public boolean containsAll(Collection<?> c) {
return queue.containsAll(c);
}
@Override
public Iterator<E> iterator() {
return queue.iterator();
}
@Override
public boolean remove(Object o) {
return queue.remove(o);
}
@Override
public boolean removeAll(Collection<?> c) {
return queue.removeAll(c);
}
@Override
public boolean retainAll(Collection<?> c) {
return queue.retainAll(c);
}
@Override
public Object[] toArray() {
return queue.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return queue.toArray(a);
}
}
|
if (queue.size() >= limit) {
// 如果超出长度,入队时,先出队
queue.poll();
}
return queue.offer(e);
| 554
| 53
| 607
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/util/LiteFlowExecutorPoolShutdown.java
|
LiteFlowExecutorPoolShutdown
|
destroy
|
class LiteFlowExecutorPoolShutdown {
private static final LFLog LOG = LFLoggerManager.getLogger(LiteFlowExecutorPoolShutdown.class);
public void destroy() throws Exception {<FILL_FUNCTION_BODY>}
}
|
ExecutorService executorService = ContextAwareHolder.loadContextAware().getBean("whenExecutors");
LOG.info("Start closing the liteflow-when-calls...");
ExecutorHelper.loadInstance().shutdownAwaitTermination(executorService);
LOG.info("Succeed closing the liteflow-when-calls ok...");
| 62
| 93
| 155
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/util/PathMatchUtil.java
|
PathMatchUtil
|
searchAbsolutePath
|
class PathMatchUtil {
public static List<String> searchAbsolutePath(List<String> pathList) {<FILL_FUNCTION_BODY>}
private static void searchAbsolutePath(String baseDir, String path, List<String> absolutePathList) {
AntPathMatcher pathMatcher = new AntPathMatcher();
File dir = new File(baseDir);
File[] files = dir.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
searchAbsolutePath(file.getAbsolutePath(), path, absolutePathList);
} else {
String absolutePath = file.getAbsolutePath().replace("\\", "/");
if (pathMatcher.match(path, absolutePath)) {
absolutePathList.add(absolutePath);
}
}
}
}
}
}
|
List<String> absolutePathList = new ArrayList<>();
for (String path : pathList) {
// 只对绝对路径进行处理
if(FileUtil.isAbsolutePath(path)) {
if(!path.contains("*")) {
absolutePathList.add(path);
}
else {
String[] pathSegments = path.split("/");
StringBuilder baseDir = new StringBuilder();
// 找到最大基础路径
for(int i = 0; i < pathSegments.length; i ++) {
if(!pathSegments[i].contains("*")) {
baseDir.append(pathSegments[i]).append(File.separator);
} else {
baseDir.deleteCharAt(baseDir.length() - 1);
searchAbsolutePath(baseDir.toString(), path, absolutePathList);
break;
}
}
}
} else {
absolutePathList.add(path);
}
}
// 路径去重
List<String> newAbsolutePathList = absolutePathList.stream()
.distinct()
.collect(Collectors.toList());
return newAbsolutePathList;
| 225
| 302
| 527
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-core/src/main/java/com/yomahub/liteflow/util/RuleParsePluginUtil.java
|
RuleParsePluginUtil
|
parseIdKey
|
class RuleParsePluginUtil {
private static final String CHAIN_XML_PATTERN = "<chain id=\"{}\" enable=\"{}\">{}</chain>";
private static final String NODE_ITEM_XML_PATTERN = "<node id=\"{}\" name=\"{}\" type=\"{}\" enable=\"{}\"><![CDATA[{}]]></node>";
private static final String NODE_ITEM_WITH_LANGUAGE_XML_PATTERN = "<node id=\"{}\" name=\"{}\" type=\"{}\" language=\"{}\" enable=\"{}\"><![CDATA[{}]]></node>";
public static ChainDto parseChainKey(String chainKey) {
String[] chainProp = chainKey.split(StrPool.COLON);
if (chainProp.length == 2) {
return new ChainDto(chainProp[0], chainProp[1]);
}
return new ChainDto(chainKey);
}
public static String toScriptXml(NodeConvertHelper.NodeSimpleVO simpleVO) {
if (StrUtil.isNotBlank(simpleVO.getLanguage())) {
return StrUtil.format(NODE_ITEM_WITH_LANGUAGE_XML_PATTERN,
simpleVO.getNodeId(),
simpleVO.getName(),
simpleVO.getType(),
simpleVO.getLanguage(),
simpleVO.getEnable(),
simpleVO.getScript()
);
} else {
return StrUtil.format(NODE_ITEM_XML_PATTERN,
simpleVO.getNodeId(),
simpleVO.getName(),
simpleVO.getType(),
simpleVO.getEnable(),
simpleVO.getScript()
);
}
}
public static Pair<Boolean/*启停*/, String/*id*/> parseIdKey(String idKey) {<FILL_FUNCTION_BODY>}
public static class ChainDto {
/**
* chain id
*/
private String id;
/**
* chain 启用状态,默认启用
*/
private String enable = Boolean.TRUE.toString();
public boolean isDisable() {
return !isEnable();
}
public boolean isEnable() {
return Boolean.TRUE.toString().equalsIgnoreCase(enable);
}
public ChainDto(String chainId) {
ChainDto chainDto = new ChainDto(chainId, null);
this.enable = chainDto.getEnable();
this.id = chainDto.getId();
}
public ChainDto(String chainId, String enable) {
this.id = chainId;
if (StrUtil.isBlank(enable)) {
this.enable = Boolean.TRUE.toString();
return;
}
if (Boolean.TRUE.toString().equalsIgnoreCase(enable)) {
this.enable = Boolean.TRUE.toString();
return;
}
this.enable = Boolean.FALSE.toString();
}
public String getId() {
return id;
}
public String getEnable() {
return enable;
}
public String toElXml(String elContent) {
return StrUtil.format(CHAIN_XML_PATTERN, id, enable, elContent);
}
}
}
|
String[] idProp = idKey.split(StrPool.COLON);
if (idProp.length == 2) {
String id = idProp[0];
String enableStr = idProp[1];
return new Pair<>(Boolean.TRUE.toString().equalsIgnoreCase(enableStr), id);
}
return new Pair<>(Boolean.TRUE, idKey);
| 849
| 95
| 944
|
<no_super_class>
|
dromara_liteflow
|
liteflow/liteflow-el-builder/src/main/java/com/yomahub/liteflow/builder/el/AndELWrapper.java
|
AndELWrapper
|
toEL
|
class AndELWrapper extends ELWrapper {
public AndELWrapper(ELWrapper... elWrappers){
this.addWrapper(elWrappers);
}
public AndELWrapper and(Object ... object){
ELWrapper[] wrapper = ELBus.convertToLogicOpt(object);
this.addWrapper(wrapper);
return this;
}
@Override
public AndELWrapper tag(String tag) {
this.setTag(tag);
return this;
}
@Override
public AndELWrapper id(String id) {
this.setId(id);
return this;
}
@Override
public AndELWrapper maxWaitSeconds(Integer maxWaitSeconds){
setMaxWaitSeconds(maxWaitSeconds);
return this;
}
@Override
protected String toEL(Integer depth, StringBuilder paramContext) {<FILL_FUNCTION_BODY>}
}
|
checkMaxWaitSeconds();
// 根据depth是否为null,决定输出是否格式化
Integer sonDepth = depth == null ? null : depth + 1;
StringBuilder sb = new StringBuilder();
processWrapperTabs(sb, depth);
sb.append("AND(");
processWrapperNewLine(sb, depth);
// 处理子表达式的输出并串接
for (int i = 0; i < this.getElWrapperList().size(); i++) {
if (i > 0){
sb.append(",");
processWrapperNewLine(sb, depth);
}
sb.append(this.getElWrapperList().get(i).toEL(sonDepth, paramContext));
}
processWrapperNewLine(sb, depth);
processWrapperTabs(sb, depth);
sb.append(")");
// 设置共有属性
processWrapperProperty(sb, paramContext);
return sb.toString();
| 234
| 238
| 472
|
<methods>public non-sealed void <init>() ,public com.yomahub.liteflow.builder.el.ELWrapper id(java.lang.String) ,public com.yomahub.liteflow.builder.el.ELWrapper tag(java.lang.String) ,public java.lang.String toEL() ,public java.lang.String toEL(boolean) <variables>private java.lang.String data,private java.lang.String dataName,private final List<com.yomahub.liteflow.builder.el.ELWrapper> elWrapperList,private java.lang.String id,private java.lang.Integer maxWaitSeconds,private java.lang.String tag
|
dromara_liteflow
|
liteflow/liteflow-el-builder/src/main/java/com/yomahub/liteflow/builder/el/CatchELWrapper.java
|
CatchELWrapper
|
toEL
|
class CatchELWrapper extends ELWrapper {
public CatchELWrapper(ELWrapper elWrapper){
this.addWrapper(elWrapper);
}
public CatchELWrapper doOpt(Object object){
ELWrapper elWrapper = ELBus.convertToNonLogicOpt(object);
this.addWrapper(elWrapper);
return this;
}
@Override
public CatchELWrapper tag(String tag) {
this.setTag(tag);
return this;
}
@Override
public CatchELWrapper id(String id) {
this.setId(id);
return this;
}
@Override
public CatchELWrapper maxWaitSeconds(Integer maxWaitSeconds){
setMaxWaitSeconds(maxWaitSeconds);
return this;
}
@Override
protected String toEL(Integer depth, StringBuilder paramContext) {<FILL_FUNCTION_BODY>}
}
|
checkMaxWaitSeconds();
Integer sonDepth = depth == null ? null : depth + 1;
StringBuilder sb = new StringBuilder();
// 处理 CATCH() 语句的输出
processWrapperTabs(sb, depth);
sb.append("CATCH(");
processWrapperNewLine(sb, depth);
sb.append(this.getElWrapperList().get(0).toEL(sonDepth, paramContext));
processWrapperNewLine(sb, depth);
processWrapperTabs(sb, depth);
sb.append(")");
// 处理 DO()语句输出
if(this.getElWrapperList().size() > 1){
sb.append(".DO(");
processWrapperNewLine(sb, depth);
sb.append(this.getElWrapperList().get(1).toEL(sonDepth, paramContext));
processWrapperNewLine(sb, depth);
processWrapperTabs(sb, depth);
sb.append(")");
}
// 处理共有属性输出
processWrapperProperty(sb, paramContext);
return sb.toString();
| 237
| 274
| 511
|
<methods>public non-sealed void <init>() ,public com.yomahub.liteflow.builder.el.ELWrapper id(java.lang.String) ,public com.yomahub.liteflow.builder.el.ELWrapper tag(java.lang.String) ,public java.lang.String toEL() ,public java.lang.String toEL(boolean) <variables>private java.lang.String data,private java.lang.String dataName,private final List<com.yomahub.liteflow.builder.el.ELWrapper> elWrapperList,private java.lang.String id,private java.lang.Integer maxWaitSeconds,private java.lang.String tag
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.