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-el-builder/src/main/java/com/yomahub/liteflow/builder/el/ELWrapper.java
ELWrapper
toEL
class ELWrapper { private final List<ELWrapper> elWrapperList = new ArrayList<>(); private String tag; private String id; private String dataName; private String data; private Integer maxWaitSeconds; protected void addWrapper(ELWrapper wrapper){ this.elWrapperList.add(wrapper); } protected void addWrapper(ELWrapper... wrappers){ this.elWrapperList.addAll(Arrays.asList(wrappers)); } protected void addWrapper(ELWrapper wrapper, int index){ this.elWrapperList.add(index, wrapper); } protected void setWrapper(ELWrapper wrapper, int index){ this.elWrapperList.set(index, wrapper); } protected ELWrapper getFirstWrapper(){ return this.elWrapperList.get(0); } protected List<ELWrapper> getElWrapperList(){ return this.elWrapperList; } protected void setTag(String tag){ this.tag = tag; } protected String getTag(){ return this.tag; } protected void setId(String id){ this.id = id; } protected String getId(){ return this.id; } protected void setData(String data){ this.data = data; } protected String getData(){ return this.data; } protected void setDataName(String dataName){ this.dataName = dataName; } protected String getDataName(){ return this.dataName; } protected void setMaxWaitSeconds(Integer maxWaitSeconds){ this.maxWaitSeconds = maxWaitSeconds; } protected Integer getMaxWaitSeconds(){ return this.maxWaitSeconds; } /** * 设置组件标记内容 * * @param tag 标记内容 * @return {@link ELWrapper} */ public ELWrapper tag(String tag){ this.setTag(tag); return this; } /** * 设置组件的id * * @param id 编号 * @return {@link ELWrapper} */ public ELWrapper id(String id){ this.setId(id); return this; } /** * 设置表达式data属性 * * @param dataName 数据名称 * @param object JavaBean * @return {@link ELWrapper} */ protected ELWrapper data(String dataName, Object object){ setData("'" + JsonUtil.toJsonString(object) + "'"); setDataName(dataName); return this; } /** * 设置表达式data属性 * * @param dataName 数据名称 * @param jsonString JSON格式字符串 * @return {@link ELWrapper} */ protected ELWrapper data(String dataName, String jsonString){ setData("'" + jsonString + "'"); setDataName(dataName); return this; } /** * 设置data属性 * * @param dataName 数据名称 * @param jsonMap 键值映射 * @return {@link ELWrapper} */ protected ELWrapper data(String dataName, Map<String, Object> jsonMap){ setData("'" + JsonUtil.toJsonString(jsonMap) + "'"); setDataName(dataName); return this; } protected ELWrapper maxWaitSeconds(Integer maxWaitSeconds){ setMaxWaitSeconds(maxWaitSeconds); return this; } /** * 非格式化输出EL表达式 * * @return {@link String} */ public String toEL(){ StringBuilder paramContext = new StringBuilder(); String elContext = toEL(null, paramContext); return paramContext.append(elContext).append(";").toString(); } /** * 是否格式化输出树形结构的表达式 * * @param format 格式 * @return {@link String} */ public String toEL(boolean format){<FILL_FUNCTION_BODY>} /** * 格式化输出EL表达式 * * @param depth 深度 * @param paramContext 参数上下文,用于输出data参数内容 * @return {@link String} */ protected abstract String toEL(Integer depth, StringBuilder paramContext); /** * 处理EL表达式的共有属性 * * @param elContext EL表达式上下文 * @param paramContext 参数上下文 */ protected void processWrapperProperty(StringBuilder elContext, StringBuilder paramContext){ if(this.getId() != null){ elContext.append(StrUtil.format(".id(\"{}\")", this.getId())); } if(this.getTag() != null){ elContext.append(StrUtil.format(".tag(\"{}\")", this.getTag())); } if(this.getMaxWaitSeconds() != null){ elContext.append(StrUtil.format(".maxWaitSeconds({})", String.valueOf(this.getMaxWaitSeconds()))); } } /** * 处理格式化输出 EL表达式换行符 * * @param elContext EL 上下文 * @param depth 深度 */ protected void processWrapperNewLine(StringBuilder elContext, Integer depth){ if(depth != null){ elContext.append("\n"); } } /** * 处理格式化输出 EL表达式制表符 * * @param elContext EL 上下文 * @param depth 深度 */ protected void processWrapperTabs(StringBuilder elContext, Integer depth){ if(depth != null) { elContext.append(StrUtil.repeat(ELBus.TAB, depth)); } } /** * 检查子表达式是否有最长等待秒数定义 */ protected void checkMaxWaitSeconds(){ for(ELWrapper sonElWrapper : this.getElWrapperList()){ if(sonElWrapper != null && sonElWrapper.getMaxWaitSeconds() != null){ throw new IllegalArgumentException("maxWaitSeconds必须定义在完整的语义之后!"); } } } }
StringBuilder paramContext = new StringBuilder(); String elContext; if(!format){ elContext = toEL(null, paramContext); } else { elContext = toEL(0, paramContext); } return paramContext.append(elContext).append(";").toString();
1,653
77
1,730
<no_super_class>
dromara_liteflow
liteflow/liteflow-el-builder/src/main/java/com/yomahub/liteflow/builder/el/FinallyELWrapper.java
FinallyELWrapper
toEL
class FinallyELWrapper extends ELWrapper { public FinallyELWrapper(Object ... objects){ super.addWrapper(ELBus.convertToNonLogicOpt(objects)); } @Override public FinallyELWrapper tag(String tag) { this.setTag(tag); return this; } @Override public FinallyELWrapper id(String id) { this.setId(id); return this; } /** * 后置组件无法设置maxWaitSeconds属性,重载用protected修饰 * * @param maxWaitSeconds 最长等待秒数 * @return {@link FinallyELWrapper} */ @Override protected FinallyELWrapper maxWaitSeconds(Integer maxWaitSeconds){ setMaxWaitSeconds(maxWaitSeconds); return this; } @Override protected String toEL(Integer depth, StringBuilder paramContext) {<FILL_FUNCTION_BODY>} /** * FINALLY不允许maxWaitSeconds属性,重载父类 * * @param elContext EL 上下文 * @param paramContext 参数上下文 */ @Override protected void processWrapperProperty(StringBuilder elContext, StringBuilder paramContext){ if(this.getId() != null){ elContext.append(StrUtil.format(".id(\"{}\")", this.getId())); } if(this.getTag() != null){ elContext.append(StrUtil.format(".tag(\"{}\")", this.getTag())); } } }
checkMaxWaitSeconds(); Integer sonDepth = depth == null ? null : depth + 1; StringBuilder sb = new StringBuilder(); processWrapperTabs(sb, depth); sb.append("FINALLY("); processWrapperNewLine(sb, depth); // 处理子表达式输出 for (int i = 0; i < this.getElWrapperList().size(); i++) { sb.append(this.getElWrapperList().get(i).toEL(sonDepth, paramContext)); if (i != this.getElWrapperList().size() - 1) { sb.append(","); processWrapperNewLine(sb, depth); } } processWrapperNewLine(sb, depth); processWrapperTabs(sb, depth); sb.append(")"); // 处理共用属性 processWrapperProperty(sb, paramContext); return sb.toString();
402
236
638
<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/LoopELWrapper.java
LoopELWrapper
toEL
class LoopELWrapper extends ELWrapper { protected Integer loopNumber; /** * 以loopFunction变量进行区分FOR、WHILE、ITERATOR */ protected String loopFunction; protected boolean parallel; public LoopELWrapper(Integer loopNumber, String loopFunction){ this.loopNumber = loopNumber; this.loopFunction = loopFunction; this.addWrapper(null, 0); } public LoopELWrapper(ELWrapper elWrapper, String loopFunction){ this.loopFunction = loopFunction; this.addWrapper(elWrapper, 0); } public LoopELWrapper doOpt(Object object){ ELWrapper elWrapper = ELBus.convertToNonLogicOpt(object); this.addWrapper(elWrapper, 1); return this; } protected void setParallel(boolean parallel){ this.parallel = parallel; } @Override public LoopELWrapper tag(String tag) { this.setTag(tag); return this; } @Override public LoopELWrapper id(String id) { this.setId(id); return this; } @Override public LoopELWrapper 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(); // 设置循坏组件的类型以及循环节点 processWrapperTabs(sb, depth); sb.append(loopFunction).append("("); if(loopNumber != null){ sb.append(loopNumber.toString()); } else { processWrapperNewLine(sb, depth); sb.append(this.getElWrapperList().get(0).toEL(sonDepth, paramContext)); processWrapperNewLine(sb, depth); processWrapperTabs(sb, depth); } sb.append(")"); // 循环独有的并行语义 if(this.parallel){ sb.append(".parallel(true)"); } // 设置循环组件输出 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(")"); } // 设置退出循环组件输出 if(this.getElWrapperList().size() > 2){ sb.append(".BREAK("); processWrapperNewLine(sb, depth); sb.append(this.getElWrapperList().get(2).toEL(sonDepth, paramContext)); processWrapperNewLine(sb, depth); processWrapperTabs(sb, depth); sb.append(")"); } // 设置共有属性 processWrapperProperty(sb, paramContext); return sb.toString();
381
450
831
<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/NodeELWrapper.java
NodeELWrapper
toEL
class NodeELWrapper extends ELWrapper { private String nodeId; private String tag; public NodeELWrapper(String nodeId) { this.nodeId = nodeId; this.setNodeWrapper(this); } private void setNodeWrapper(ELWrapper elWrapper){ this.addWrapper(elWrapper, 0); } private NodeELWrapper getNodeWrapper(){ return (NodeELWrapper) this.getFirstWrapper(); } protected String getNodeId() { return nodeId; } protected void setNodeId(String nodeId) { this.nodeId = nodeId; } @Override public NodeELWrapper tag(String tag) { this.setTag(tag); return this; } /** * 单节点不允许定义 id,重载为protected修饰 * * @param id 节点id * @return {@link NodeELWrapper} */ @Override public NodeELWrapper id(String id) { this.setId(id); return this; } @Override public NodeELWrapper data(String dataName, Object object) { setData("'" + JsonUtil.toJsonString(object) + "'"); setDataName(dataName); return this; } @Override public NodeELWrapper data(String dataName, String jsonString) { setData("'" + jsonString + "'"); setDataName(dataName); return this; } @Override public NodeELWrapper data(String dataName, Map<String, Object> jsonMap) { setData("'" + JsonUtil.toJsonString(jsonMap) + "'"); setDataName(dataName); return this; } @Override public NodeELWrapper maxWaitSeconds(Integer maxWaitSeconds){ setMaxWaitSeconds(maxWaitSeconds); return this; } @Override protected String toEL(Integer depth, StringBuilder paramContext) {<FILL_FUNCTION_BODY>} /** * Node的公共属性不包括id,对父类方法重载。 * * @param elContext EL 上下文 * @param paramContext 参数上下文 */ @Override protected void processWrapperProperty(StringBuilder elContext, StringBuilder paramContext){ if(this.getTag() != null){ elContext.append(StrUtil.format(".tag(\"{}\")", this.getTag())); } if(this.getData() != null){ elContext.append(StrUtil.format(".data({})", this.getDataName())); paramContext.append(StrUtil.format("{} = {}", this.getDataName(), this.getData())).append(";\n"); } if(this.getMaxWaitSeconds() != null){ elContext.append(StrUtil.format(".maxWaitSeconds({})", String.valueOf(this.getMaxWaitSeconds()))); } } }
NodeELWrapper nodeElWrapper = this.getNodeWrapper(); StringBuilder sb = new StringBuilder(); processWrapperTabs(sb, depth); sb.append(StrUtil.format("node(\"{}\")", nodeElWrapper.getNodeId())); processWrapperProperty(sb, paramContext); return sb.toString();
771
84
855
<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/NotELWrapper.java
NotELWrapper
toEL
class NotELWrapper extends ELWrapper { public NotELWrapper(ELWrapper elWrapper){ this.addWrapper(elWrapper); } @Override public NotELWrapper tag(String tag) { this.setTag(tag); return this; } @Override public NotELWrapper id(String id) { this.setId(id); return this; } @Override public NotELWrapper 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(); processWrapperTabs(sb, depth); sb.append("NOT("); processWrapperNewLine(sb, depth); // 处理子表达式输出 sb.append(this.getElWrapperList().get(0).toEL(sonDepth, paramContext)); processWrapperNewLine(sb, depth); processWrapperTabs(sb, depth); sb.append(")"); // 设置公共属性 processWrapperProperty(sb, paramContext); return sb.toString();
180
162
342
<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/OrELWrapper.java
OrELWrapper
toEL
class OrELWrapper extends ELWrapper { public OrELWrapper(ELWrapper... elWrappers){ this.addWrapper(elWrappers); } public OrELWrapper or(Object ... object){ ELWrapper[] elWrapper = ELBus.convertToLogicOpt(object); this.addWrapper(elWrapper); return this; } @Override public OrELWrapper tag(String tag) { this.setTag(tag); return this; } @Override public OrELWrapper id(String id) { this.setId(id); return this; } @Override public OrELWrapper 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(); processWrapperTabs(sb, depth); sb.append("OR("); 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();
236
220
456
<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/ParELWrapper.java
ParELWrapper
toEL
class ParELWrapper extends ELWrapper { private boolean any; private boolean ignoreError; private String customThreadExecutor; private final List<String> mustExecuteList; public ParELWrapper(ELWrapper... elWrappers) { this.addWrapper(elWrappers); this.mustExecuteList = new ArrayList<>(); } public ParELWrapper par(Object ... objects){ ELWrapper[] elWrappers = ELBus.convertToNonLogicOpt(objects); // 校验与或非表达式 this.addWrapper(elWrappers); return this; } public ParELWrapper any(boolean any) { this.any = any; return this; } public ParELWrapper ignoreError(boolean ignoreError) { this.ignoreError = ignoreError; return this; } public ParELWrapper customThreadExecutor(String customThreadExecutor){ this.customThreadExecutor = customThreadExecutor; return this; } public ParELWrapper must(String ... mustExecuteWrappers){ this.mustExecuteList.addAll(Arrays.asList(mustExecuteWrappers)); return this; } @Override public ParELWrapper tag(String tag) { this.setTag(tag); return this; } @Override public ParELWrapper id(String id) { this.setId(id); return this; } @Override public ParELWrapper 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(); processWrapperTabs(sb, depth); sb.append("PAR("); 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(")"); // WHEN的私有语义输出 if (this.any){ sb.append(".any(true)"); } if(this.ignoreError){ sb.append(".ignoreError(true)"); } if(StrUtil.isNotBlank(customThreadExecutor)){ sb.append(StrUtil.format(".threadPool(\"{}\")", customThreadExecutor)); } if(CollectionUtil.isNotEmpty(mustExecuteList)){ // 校验must 语义与 any语义冲突 if (this.any){ throw new IllegalArgumentException("'.must()' and '.any()' can use in when component at the same time!"); } // 处理must子表达式输出 sb.append(".must("); for(int i = 0; i < mustExecuteList.size(); i++){ if(i > 0){ sb.append(", "); } sb.append(StrUtil.format("\"{}\"", mustExecuteList.get(i))); } sb.append(")"); } // 处理公共属性输出 processWrapperProperty(sb, paramContext); return sb.toString();
445
484
929
<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/PreELWrapper.java
PreELWrapper
toEL
class PreELWrapper extends ELWrapper { public PreELWrapper(Object ... objects){ super.addWrapper(ELBus.convert(objects)); } @Override public PreELWrapper tag(String tag) { this.setTag(tag); return this; } @Override public PreELWrapper id(String id) { this.setId(id); return this; } @Override public PreELWrapper 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(); processWrapperTabs(sb, depth); sb.append("PRE("); processWrapperNewLine(sb, depth); // 处理子表达式输出 for (int i = 0; i < this.getElWrapperList().size(); i++) { sb.append(this.getElWrapperList().get(i).toEL(sonDepth, paramContext)); if (i != this.getElWrapperList().size() - 1) { sb.append(","); processWrapperNewLine(sb, depth); } } processWrapperNewLine(sb, depth); processWrapperTabs(sb, depth); sb.append(")"); // 处理公共属性输出 processWrapperProperty(sb, paramContext); return sb.toString();
183
233
416
<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/SerELWrapper.java
SerELWrapper
toEL
class SerELWrapper extends ELWrapper { private final List<PreELWrapper> preELWrapperList; private final List<FinallyELWrapper> finallyELWrapperList; public SerELWrapper(ELWrapper... elWrappers) { preELWrapperList = new ArrayList<>(); finallyELWrapperList = new ArrayList<>(); this.addWrapper(elWrappers); } public SerELWrapper ser(Object ... objects){ ELWrapper[] elWrappers = ELBus.convertToNonLogicOpt(objects); // 校验与或非表达式 this.addWrapper(elWrappers); return this; } protected void addPreElWrapper(PreELWrapper preElWrapper){ this.preELWrapperList.add(preElWrapper); } protected void addFinallyElWrapper(FinallyELWrapper finallyElWrapper){ this.finallyELWrapperList.add(finallyElWrapper); } /** * 在当前串行组件下创建前置组件 * * @param objects 前置组件的子组件 * @return {@link SerELWrapper} */ public SerELWrapper pre(Object ... objects){ addPreElWrapper(new PreELWrapper(objects)); return this; } /** * 在当前串行组件下创建前置组件 * * @param objects 后置组件的子组件 * @return {@link SerELWrapper} */ public SerELWrapper finallyOpt(Object ... objects){ addFinallyElWrapper(new FinallyELWrapper(objects)); return this; } @Override public SerELWrapper tag(String tag) { this.setTag(tag); return this; } @Override public SerELWrapper id(String id) { this.setId(id); return this; } @Override public SerELWrapper 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(); processWrapperTabs(sb, depth); sb.append("SER("); processWrapperNewLine(sb, depth); // 处理前置组件输出 for (PreELWrapper preElWrapper : this.preELWrapperList) { sb.append(StrUtil.format("{},", preElWrapper.toEL(sonDepth, paramContext))); 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)); } // 处理后置组件输出 for (FinallyELWrapper finallyElWrapper : this.finallyELWrapperList) { sb.append(","); processWrapperNewLine(sb, depth); sb.append(finallyElWrapper.toEL(sonDepth, paramContext)); } processWrapperNewLine(sb, depth); processWrapperTabs(sb, depth); sb.append(")"); // 处理公共属性输出 processWrapperProperty(sb, paramContext); return sb.toString();
552
363
915
<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/SwitchELWrapper.java
SwitchELWrapper
toEL
class SwitchELWrapper extends ELWrapper { /** * default语句的表达式 */ private ELWrapper defaultElWrapper; public SwitchELWrapper(ELWrapper elWrapper){ this.addWrapper(elWrapper, 0); } public SwitchELWrapper to(Object... objects){ ELWrapper[] elWrappers = ELBus.convertToNonLogicOpt(objects); this.addWrapper(elWrappers); return this; } public SwitchELWrapper defaultOpt(Object object){ defaultElWrapper = ELBus.convertToNonLogicOpt(object); return this; } @Override public SwitchELWrapper tag(String tag) { this.setTag(tag); return this; } @Override public SwitchELWrapper id(String id) { this.setId(id); return this; } @Override public SwitchELWrapper 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(); processWrapperTabs(sb, depth); sb.append(StrUtil.format("SWITCH({})", this.getFirstWrapper().toEL(null, paramContext))); // 处理子表达式输出 if(this.getElWrapperList().size() > 1) { sb.append(".TO("); processWrapperNewLine(sb, depth); for (int i = 1; i < this.getElWrapperList().size(); i++) { sb.append(this.getElWrapperList().get(i).toEL(sonDepth, paramContext)); if (i != this.getElWrapperList().size() - 1) { sb.append(","); processWrapperNewLine(sb, depth); } } processWrapperNewLine(sb, depth); processWrapperTabs(sb, depth); sb.append(")"); } // default可以不存在 if(defaultElWrapper != null){ sb.append(".DEFAULT("); processWrapperNewLine(sb, depth); sb.append(defaultElWrapper.toEL(sonDepth, paramContext)); processWrapperNewLine(sb, depth); processWrapperTabs(sb, depth); sb.append(")"); } // 处理表达式的共有属性 processWrapperProperty(sb, paramContext); return sb.toString();
302
375
677
<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/ThenELWrapper.java
ThenELWrapper
toEL
class ThenELWrapper extends ELWrapper { private final List<PreELWrapper> preELWrapperList; private final List<FinallyELWrapper> finallyELWrapperList; public ThenELWrapper(ELWrapper... elWrappers) { preELWrapperList = new ArrayList<>(); finallyELWrapperList = new ArrayList<>(); this.addWrapper(elWrappers); } public ThenELWrapper then(Object ... objects){ ELWrapper[] elWrappers = ELBus.convertToNonLogicOpt(objects); // 校验与或非表达式 this.addWrapper(elWrappers); return this; } protected void addPreElWrapper(PreELWrapper preElWrapper){ this.preELWrapperList.add(preElWrapper); } protected void addFinallyElWrapper(FinallyELWrapper finallyElWrapper){ this.finallyELWrapperList.add(finallyElWrapper); } /** * 在当前串行组件下创建前置组件 * * @param objects 前置组件的子组件 * @return {@link ThenELWrapper} */ public ThenELWrapper pre(Object ... objects){ addPreElWrapper(new PreELWrapper(objects)); return this; } /** * 在当前串行组件下创建前置组件 * * @param objects 后置组件的子组件 * @return {@link ThenELWrapper} */ public ThenELWrapper finallyOpt(Object ... objects){ addFinallyElWrapper(new FinallyELWrapper(objects)); return this; } @Override public ThenELWrapper tag(String tag) { this.setTag(tag); return this; } @Override public ThenELWrapper id(String id) { this.setId(id); return this; } @Override public ThenELWrapper 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(); processWrapperTabs(sb, depth); sb.append("THEN("); processWrapperNewLine(sb, depth); // 处理前置组件输出 for (PreELWrapper preElWrapper : this.preELWrapperList) { sb.append(StrUtil.format("{},", preElWrapper.toEL(sonDepth, paramContext))); 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)); } // 处理后置组件输出 for (FinallyELWrapper finallyElWrapper : this.finallyELWrapperList) { sb.append(","); processWrapperNewLine(sb, depth); sb.append(finallyElWrapper.toEL(sonDepth, paramContext)); } processWrapperNewLine(sb, depth); processWrapperTabs(sb, depth); sb.append(")"); // 处理公共属性输出 processWrapperProperty(sb, paramContext); return sb.toString();
552
364
916
<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/WhenELWrapper.java
WhenELWrapper
toEL
class WhenELWrapper extends ELWrapper { private boolean any; private boolean ignoreError; private String customThreadExecutor; private final List<String> mustExecuteList; public WhenELWrapper(ELWrapper... elWrappers) { this.addWrapper(elWrappers); this.mustExecuteList = new ArrayList<>(); } public WhenELWrapper when(Object ... objects){ ELWrapper[] elWrappers = ELBus.convertToNonLogicOpt(objects); // 校验与或非表达式 this.addWrapper(elWrappers); return this; } public WhenELWrapper any(boolean any) { this.any = any; return this; } public WhenELWrapper ignoreError(boolean ignoreError) { this.ignoreError = ignoreError; return this; } public WhenELWrapper customThreadExecutor(String customThreadExecutor){ this.customThreadExecutor = customThreadExecutor; return this; } public WhenELWrapper must(String ... mustExecuteWrappers){ this.mustExecuteList.addAll(Arrays.asList(mustExecuteWrappers)); return this; } @Override public WhenELWrapper tag(String tag) { this.setTag(tag); return this; } @Override public WhenELWrapper id(String id) { this.setId(id); return this; } @Override public WhenELWrapper 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(); processWrapperTabs(sb, depth); sb.append("WHEN("); 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(")"); // WHEN的私有语义输出 if (this.any){ sb.append(".any(true)"); } if(this.ignoreError){ sb.append(".ignoreError(true)"); } if(StrUtil.isNotBlank(customThreadExecutor)){ sb.append(StrUtil.format(".threadPool(\"{}\")", customThreadExecutor)); } if(CollectionUtil.isNotEmpty(mustExecuteList)){ // 校验must 语义与 any语义冲突 if (this.any){ throw new IllegalArgumentException("'.must()' and '.any()' can use in when component at the same time!"); } // 处理must子表达式输出 sb.append(".must("); for(int i = 0; i < mustExecuteList.size(); i++){ if(i > 0){ sb.append(", "); } sb.append(StrUtil.format("\"{}\"", mustExecuteList.get(i))); } sb.append(")"); } // 处理公共属性输出 processWrapperProperty(sb, paramContext); return sb.toString();
445
485
930
<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-rule-plugin/liteflow-rule-apollo/src/main/java/com/yomahub/liteflow/parser/apollo/ApolloXmlELParser.java
ApolloXmlELParser
parseCustom
class ApolloXmlELParser extends ClassXmlFlowELParser { private final ApolloParseHelper apolloParseHelper; public ApolloXmlELParser() { LiteflowConfig liteflowConfig = LiteflowConfigGetter.get(); try { ApolloParserConfigVO apolloParserConfigVO = null; if (MapUtil.isNotEmpty((liteflowConfig.getRuleSourceExtDataMap()))) { apolloParserConfigVO = BeanUtil.toBean(liteflowConfig.getRuleSourceExtDataMap(), ApolloParserConfigVO.class, CopyOptions.create()); } else if (StrUtil.isNotBlank(liteflowConfig.getRuleSourceExtData())) { apolloParserConfigVO = JsonUtil.parseObject(liteflowConfig.getRuleSourceExtData(), ApolloParserConfigVO.class); } // check config if (Objects.isNull(apolloParserConfigVO)) { throw new ApolloException("ruleSourceExtData or map is empty"); } if (StrUtil.isBlank(apolloParserConfigVO.getChainNamespace())) { throw new ApolloException("chainNamespace is empty, you must configure the chainNamespace property"); } apolloParseHelper = new ApolloParseHelper(apolloParserConfigVO); } catch (Exception e) { throw new ApolloException(e.getMessage()); } } @Override public String parseCustom() {<FILL_FUNCTION_BODY>} }
try { String content = apolloParseHelper.getContent(); FlowInitHook.addHook(() -> { apolloParseHelper.listenApollo(); return true; }); return content; } catch (Exception e) { throw new ApolloException(e.getMessage()); }
384
89
473
<methods>public non-sealed void <init>() ,public abstract java.lang.String parseCustom() ,public void parseMain(List<java.lang.String>) throws java.lang.Exception<variables>
dromara_liteflow
liteflow/liteflow-rule-plugin/liteflow-rule-apollo/src/main/java/com/yomahub/liteflow/parser/apollo/util/ApolloParseHelper.java
ApolloParseHelper
getContent
class ApolloParseHelper { private static final Logger LOG = LoggerFactory.getLogger(ApolloParseHelper.class); private final String NODE_XML_PATTERN = "<nodes>{}</nodes>"; private final String XML_PATTERN = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><flow>{}{}</flow>"; private final ApolloParserConfigVO apolloParserConfigVO; private Config chainConfig; private Config scriptConfig; public ApolloParseHelper(ApolloParserConfigVO apolloParserConfigVO) { this.apolloParserConfigVO = apolloParserConfigVO; try { try { // 这里本身对于程序运行来说没有什么意义,拿到的永远是null // 其实config对象也没有注入到spring容器中 // 这里这样写的目的是为了单测中的mockito,当有@MockBean的时候,这里就能拿到了 this.chainConfig = ContextAwareHolder.loadContextAware().getBean("chainConfig"); this.scriptConfig = ContextAwareHolder.loadContextAware().getBean("scriptConfig"); } catch (Exception ignored) { } if (ObjectUtil.isNull(chainConfig)) { chainConfig = ConfigService.getConfig(apolloParserConfigVO.getChainNamespace()); String scriptNamespace; // scriptConfig is optional if (StrUtil.isNotBlank(scriptNamespace = apolloParserConfigVO.getScriptNamespace())) { scriptConfig = ConfigService.getConfig(scriptNamespace); } } } catch (Exception e) { throw new ApolloException(e.getMessage()); } } public String getContent() {<FILL_FUNCTION_BODY>} /** * listen apollo config change */ public void listenApollo() { // chain chainConfig.addChangeListener(changeEvent -> changeEvent.changedKeys().forEach(changeKey -> { ConfigChange configChange = changeEvent.getChange(changeKey); String newValue = configChange.getNewValue(); PropertyChangeType changeType = configChange.getChangeType(); Pair<Boolean/*启停*/, String/*id*/> pair = RuleParsePluginUtil.parseIdKey(changeKey); String chainId = pair.getValue(); switch (changeType) { case ADDED: case MODIFIED: LOG.info("starting reload flow config... {} key={} value={},", changeType.name(), changeKey, newValue); // 如果是启用,就正常更新 if (pair.getKey()) { LiteFlowChainELBuilder.createChain().setChainId(chainId).setEL(newValue).build(); } // 如果是禁用,就删除 else { FlowBus.removeChain(chainId); } break; case DELETED: LOG.info("starting reload flow config... delete key={}", changeKey); FlowBus.removeChain(chainId); break; default: } })); if (StrUtil.isNotBlank(apolloParserConfigVO.getScriptNamespace())) { scriptConfig.addChangeListener(changeEvent -> changeEvent.changedKeys().forEach(changeKey -> { ConfigChange configChange = changeEvent.getChange(changeKey); String newValue = configChange.getNewValue(); PropertyChangeType changeType = configChange.getChangeType(); if (DELETED.equals(changeType)) { newValue = null; } NodeConvertHelper.NodeSimpleVO nodeSimpleVO = convert(changeKey, newValue); switch (changeType) { case ADDED: case MODIFIED: LOG.info("starting reload flow config... {} key={} value={},", changeType.name(), changeKey, newValue); // 启用就正常更新 if (nodeSimpleVO.getEnable()) { LiteFlowNodeBuilder.createScriptNode() .setId(nodeSimpleVO.getNodeId()) .setType(NodeTypeEnum.getEnumByCode(nodeSimpleVO.getType())) .setName(nodeSimpleVO.getName()) .setScript(newValue) .setLanguage(nodeSimpleVO.getLanguage()) .build(); } // 禁用就删除 else { FlowBus.unloadScriptNode(nodeSimpleVO.getNodeId()); } break; case DELETED: LOG.info("starting reload flow config... delete key={}", changeKey); FlowBus.unloadScriptNode(nodeSimpleVO.getNodeId()); break; default: } })); } } private NodeConvertHelper.NodeSimpleVO convert(String key, String value) { NodeConvertHelper.NodeSimpleVO nodeSimpleVO = NodeConvertHelper.convert(key); // set script nodeSimpleVO.setScript(value); return nodeSimpleVO; } }
try { // 1. handle chain Set<String> propertyNames = chainConfig.getPropertyNames(); List<String> chainItemContentList = propertyNames.stream() .map(item -> RuleParsePluginUtil.parseChainKey(item).toElXml(chainConfig.getProperty(item, StrUtil.EMPTY))) .collect(Collectors.toList()); // merge all chain content String chainAllContent = CollUtil.join(chainItemContentList, StrUtil.EMPTY); // 2. handle script if needed String scriptAllContent = StrUtil.EMPTY; Set<String> scriptNamespaces; if (Objects.nonNull(scriptConfig) && CollectionUtil.isNotEmpty(scriptNamespaces = scriptConfig.getPropertyNames())) { List<String> scriptItemContentList = scriptNamespaces.stream() .map(item -> convert(item, scriptConfig.getProperty(item, StrUtil.EMPTY))) .map(RuleParsePluginUtil::toScriptXml) .collect(Collectors.toList()); scriptAllContent = StrUtil.format(NODE_XML_PATTERN, CollUtil.join(scriptItemContentList, StrUtil.EMPTY)); } return StrUtil.format(XML_PATTERN, scriptAllContent, chainAllContent); } catch (Exception e) { throw new ApolloException(e.getMessage()); }
1,257
356
1,613
<no_super_class>
dromara_liteflow
liteflow/liteflow-rule-plugin/liteflow-rule-apollo/src/main/java/com/yomahub/liteflow/parser/apollo/vo/ApolloParserConfigVO.java
ApolloParserConfigVO
toString
class ApolloParserConfigVO { private String chainNamespace; private String scriptNamespace; public ApolloParserConfigVO() { } public ApolloParserConfigVO(String chainNamespace, String scriptNamespace) { this.chainNamespace = chainNamespace; this.scriptNamespace = scriptNamespace; } public String getChainNamespace() { return chainNamespace; } public void setChainNamespace(String chainNamespace) { this.chainNamespace = chainNamespace; } public String getScriptNamespace() { return scriptNamespace; } public void setScriptNamespace(String scriptNamespace) { this.scriptNamespace = scriptNamespace; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "ApolloParserConfigVO{" + "chainNamespace='" + chainNamespace + '\'' + ", scriptNamespace='" + scriptNamespace + '\'' + '}';
184
43
227
<no_super_class>
dromara_liteflow
liteflow/liteflow-rule-plugin/liteflow-rule-etcd/src/main/java/com/yomahub/liteflow/parser/etcd/EtcdClient.java
EtcdClient
getChildrenKeys
class EtcdClient { private static final Logger LOG = LoggerFactory.getLogger(EtcdClient.class); private final Client client; private final ConcurrentHashMap<String, Watch.Watcher> watchCache = new ConcurrentHashMap<>(); public EtcdClient(final Client client) { this.client = client; } /** * close client. */ public void close() { this.client.close(); } /** * get node value. * @param key node name * @return string */ public String get(final String key) { List<KeyValue> keyValues = null; try { keyValues = client.getKVClient().get(bytesOf(key)).get().getKvs(); } catch (InterruptedException | ExecutionException e) { LOG.error(e.getMessage(), e); } if (CollUtil.isEmpty(keyValues)) { return null; } return keyValues.iterator().next().getValue().toString(UTF_8); } /** * put a key-value pair into etcd. * @param key node name * @param value node value * @return */ public KeyValue put(final String key, final String value) { KeyValue prevKv = null; ByteSequence keyByteSequence = bytesOf(key); ByteSequence valueByteSequence = bytesOf(value); try { prevKv = client.getKVClient().put(keyByteSequence, valueByteSequence).get().getPrevKv(); } catch (InterruptedException | ExecutionException e) { LOG.error(e.getMessage(), e); } return prevKv; } /** * get node sub nodes. * @param prefix node prefix. * @param separator separator char * @return sub nodes * @throws ExecutionException the exception * @throws InterruptedException the exception */ public List<String> getChildrenKeys(final String prefix, final String separator) throws ExecutionException, InterruptedException {<FILL_FUNCTION_BODY>} private String getSubNodeKeyName(final String prefix, final String fullPath, final String separator) { if (prefix.length() > fullPath.length()) { return null; } String pathWithoutPrefix = fullPath.substring(prefix.length()); return pathWithoutPrefix.contains(separator) ? pathWithoutPrefix.substring(1) : pathWithoutPrefix; } /** * subscribe data change. * @param key node name * @param updateHandler node value handler of update * @param deleteHandler node value handler of delete */ public void watchDataChange(final String key, final BiConsumer<String, String> updateHandler, final Consumer<String> deleteHandler) { Watch.Listener listener = watch(updateHandler, deleteHandler); Watch.Watcher watch = client.getWatchClient().watch(bytesOf(key), listener); watchCache.put(key, watch); } /** * subscribe sub node change. * @param key param node name. * @param updateHandler sub node handler of update * @param deleteHandler sub node delete of delete */ public void watchChildChange(final String key, final BiConsumer<String, String> updateHandler, final Consumer<String> deleteHandler) { Watch.Listener listener = watch(updateHandler, deleteHandler); WatchOption option = WatchOption.newBuilder().withPrefix(bytesOf(key)).build(); Watch.Watcher watch = client.getWatchClient().watch(bytesOf(key), option, listener); watchCache.put(key, watch); } /** * bytesOf string. * @param val val. * @return bytes val. */ public ByteSequence bytesOf(final String val) { return ByteSequence.from(val, UTF_8); } private Watch.Listener watch(final BiConsumer<String, String> updateHandler, final Consumer<String> deleteHandler) { return Watch.listener(response -> { for (WatchEvent event : response.getEvents()) { String path = event.getKeyValue().getKey().toString(UTF_8); String value = event.getKeyValue().getValue().toString(UTF_8); switch (event.getEventType()) { case PUT: updateHandler.accept(path, value); continue; case DELETE: deleteHandler.accept(path); continue; default: } } }); } /** * cancel subscribe. * @param key node name */ public void watchClose(final String key) { if (watchCache.containsKey(key)) { watchCache.get(key).close(); watchCache.remove(key); } } }
ByteSequence prefixByteSequence = bytesOf(prefix); GetOption getOption = GetOption.newBuilder() .withPrefix(prefixByteSequence) .withSortField(GetOption.SortTarget.KEY) .withSortOrder(GetOption.SortOrder.ASCEND) .build(); List<KeyValue> keyValues = client.getKVClient().get(prefixByteSequence, getOption).get().getKvs(); return keyValues.stream() .map(e -> getSubNodeKeyName(prefix, e.getKey().toString(UTF_8), separator)) .distinct() .filter(e -> Objects.nonNull(e)) .collect(Collectors.toList());
1,236
184
1,420
<no_super_class>
dromara_liteflow
liteflow/liteflow-rule-plugin/liteflow-rule-etcd/src/main/java/com/yomahub/liteflow/parser/etcd/EtcdXmlELParser.java
EtcdXmlELParser
parseCustom
class EtcdXmlELParser extends ClassXmlFlowELParser { private final EtcdParserHelper etcdParserHelper; public EtcdXmlELParser() { LiteflowConfig liteflowConfig = LiteflowConfigGetter.get(); try { EtcdParserVO etcdParserVO = null; if (MapUtil.isNotEmpty((liteflowConfig.getRuleSourceExtDataMap()))) { etcdParserVO = BeanUtil.toBean(liteflowConfig.getRuleSourceExtDataMap(), EtcdParserVO.class, CopyOptions.create()); } else if (StrUtil.isNotBlank(liteflowConfig.getRuleSourceExtData())) { etcdParserVO = JsonUtil.parseObject(liteflowConfig.getRuleSourceExtData(), EtcdParserVO.class); } if (Objects.isNull(etcdParserVO)) { throw new EtcdException("rule-source-ext-data is empty"); } if (StrUtil.isBlank(etcdParserVO.getChainPath())) { throw new EtcdException("You must configure the chainPath property"); } if (StrUtil.isBlank(etcdParserVO.getEndpoints())) { throw new EtcdException("etcd endpoints is empty"); } etcdParserHelper = new EtcdParserHelper(etcdParserVO); } catch (Exception e) { throw new EtcdException(e.getMessage()); } } @Override public String parseCustom() {<FILL_FUNCTION_BODY>} }
try { String content = etcdParserHelper.getContent(); FlowInitHook.addHook(() -> { etcdParserHelper.listen(); return true; }); return content; } catch (Exception e) { throw new EtcdException(e.getMessage()); }
404
88
492
<methods>public non-sealed void <init>() ,public abstract java.lang.String parseCustom() ,public void parseMain(List<java.lang.String>) throws java.lang.Exception<variables>
dromara_liteflow
liteflow/liteflow-rule-plugin/liteflow-rule-etcd/src/main/java/com/yomahub/liteflow/parser/etcd/util/EtcdParserHelper.java
EtcdParserHelper
hasScript
class EtcdParserHelper { private static final Logger LOG = LoggerFactory.getLogger(EtcdParserHelper.class); private final String NODE_XML_PATTERN = "<nodes>{}</nodes>"; private final String XML_PATTERN = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><flow>{}{}</flow>"; private static final String SEPARATOR = "/"; private final EtcdParserVO etcdParserVO; private EtcdClient client; public EtcdParserHelper(EtcdParserVO etcdParserVO) { this.etcdParserVO = etcdParserVO; try { try { this.client = ContextAwareHolder.loadContextAware().getBean(EtcdClient.class); } catch (Exception ignored) { } if (this.client == null) { ClientBuilder clientBuilder = Client.builder().endpoints(etcdParserVO.getEndpoints().split(",")); if (StrUtil.isNotBlank(etcdParserVO.getNamespace())) { clientBuilder.namespace(ByteSequence.from(etcdParserVO.getNamespace(), CharsetUtil.CHARSET_UTF_8)); } if (StrUtil.isAllNotBlank(etcdParserVO.getUser(), etcdParserVO.getPassword())) { clientBuilder.user(ByteSequence.from(etcdParserVO.getUser(), CharsetUtil.CHARSET_UTF_8)); clientBuilder.password(ByteSequence.from(etcdParserVO.getPassword(), CharsetUtil.CHARSET_UTF_8)); } this.client = new EtcdClient(clientBuilder.build()); } } catch (Exception e) { throw new EtcdException(e.getMessage()); } } public String getContent() { try { // 检查chainPath路径下有没有子节点 List<String> chainNameList = client.getChildrenKeys(etcdParserVO.getChainPath(), SEPARATOR); // 获取chainPath路径下的所有子节点内容List List<String> chainItemContentList = new ArrayList<>(); for (String chainName : chainNameList) { RuleParsePluginUtil.ChainDto chainDto = RuleParsePluginUtil.parseChainKey(chainName); String chainData = client.get(StrUtil.format("{}/{}", etcdParserVO.getChainPath(), chainName)); if (StrUtil.isNotBlank(chainData)) { chainItemContentList.add(chainDto.toElXml(chainData)); } } // 合并成所有chain的xml内容 String chainAllContent = CollUtil.join(chainItemContentList, StrUtil.EMPTY); // 检查是否有脚本内容,如果有,进行脚本内容的获取 String scriptAllContent = StrUtil.EMPTY; if (hasScript()) { List<String> scriptNodeValueList = client.getChildrenKeys(etcdParserVO.getScriptPath(), SEPARATOR) .stream() .filter(StrUtil::isNotBlank) .collect(Collectors.toList()); List<String> scriptItemContentList = new ArrayList<>(); for (String scriptNodeValue : scriptNodeValueList) { NodeConvertHelper.NodeSimpleVO nodeSimpleVO = NodeConvertHelper.convert(scriptNodeValue); if (Objects.isNull(nodeSimpleVO)) { throw new EtcdException( StrUtil.format("The name of the etcd node is invalid:{}", scriptNodeValue)); } String scriptData = client .get(StrUtil.format("{}/{}", etcdParserVO.getScriptPath(), scriptNodeValue)); nodeSimpleVO.setScript(scriptData); scriptItemContentList.add(RuleParsePluginUtil.toScriptXml(nodeSimpleVO)); } scriptAllContent = StrUtil.format(NODE_XML_PATTERN, CollUtil.join(scriptItemContentList, StrUtil.EMPTY)); } return StrUtil.format(XML_PATTERN, scriptAllContent, chainAllContent); } catch (Exception e) { throw new EtcdException(e.getMessage()); } } public boolean hasScript() {<FILL_FUNCTION_BODY>} /** * 监听 etcd 节点 */ public void listen() { this.client.watchChildChange(this.etcdParserVO.getChainPath(), (updatePath, updateValue) -> { LOG.info("starting reload flow config... update path={} value={},", updatePath, updateValue); String changeKey = FileNameUtil.getName(updatePath); Pair<Boolean/*启停*/, String/*id*/> pair = RuleParsePluginUtil.parseIdKey(changeKey); String chainId = pair.getValue(); // 如果是启用,就正常更新 if (pair.getKey()) { LiteFlowChainELBuilder.createChain().setChainId(chainId).setEL(updateValue).build(); } // 如果是禁用,就删除 else { FlowBus.removeChain(chainId); } }, (deletePath) -> { LOG.info("starting reload flow config... delete path={}", deletePath); String chainKey = FileNameUtil.getName(deletePath); Pair<Boolean/*启停*/, String/*id*/> pair = RuleParsePluginUtil.parseIdKey(chainKey); FlowBus.removeChain(pair.getValue()); }); if (StrUtil.isNotBlank(this.etcdParserVO.getScriptPath())) { this.client.watchChildChange(this.etcdParserVO.getScriptPath(), (updatePath, updateValue) -> { LOG.info("starting reload flow config... update path={} value={}", updatePath, updateValue); String scriptNodeValue = FileNameUtil.getName(updatePath); NodeConvertHelper.NodeSimpleVO nodeSimpleVO = NodeConvertHelper.convert(scriptNodeValue); // 启用就正常更新 if (nodeSimpleVO.getEnable()) { LiteFlowNodeBuilder.createScriptNode() .setId(nodeSimpleVO.getNodeId()) .setType(NodeTypeEnum.getEnumByCode(nodeSimpleVO.getType())) .setName(nodeSimpleVO.getName()) .setScript(updateValue) .setLanguage(nodeSimpleVO.getLanguage()) .build(); } // 禁用就删除 else { FlowBus.unloadScriptNode(nodeSimpleVO.getNodeId()); } }, (deletePath) -> { LOG.info("starting reload flow config... delete path={}", deletePath); String scriptNodeValue = FileNameUtil.getName(deletePath); NodeConvertHelper.NodeSimpleVO nodeSimpleVO = NodeConvertHelper.convert(scriptNodeValue); FlowBus.unloadScriptNode(nodeSimpleVO.getNodeId()); }); } } }
// 没有配置scriptPath if (StrUtil.isBlank(etcdParserVO.getScriptPath())) { return false; } try { // 存在这个节点,但是子节点不存在 List<String> chainNameList = client.getChildrenKeys(etcdParserVO.getScriptPath(), SEPARATOR); return !CollUtil.isEmpty(chainNameList); } catch (Exception e) { return false; }
1,750
119
1,869
<no_super_class>
dromara_liteflow
liteflow/liteflow-rule-plugin/liteflow-rule-nacos/src/main/java/com/yomahub/liteflow/parser/nacos/NacosXmlELParser.java
NacosXmlELParser
parseCustom
class NacosXmlELParser extends ClassXmlFlowELParser { private final NacosParserHelper helper; public NacosXmlELParser() { LiteflowConfig liteflowConfig = LiteflowConfigGetter.get(); try { NacosParserVO nacosParserVO = null; if (MapUtil.isNotEmpty((liteflowConfig.getRuleSourceExtDataMap()))) { nacosParserVO = BeanUtil.toBean(liteflowConfig.getRuleSourceExtDataMap(), NacosParserVO.class, CopyOptions.create()); } else if (StrUtil.isNotBlank(liteflowConfig.getRuleSourceExtData())) { nacosParserVO = JsonUtil.parseObject(liteflowConfig.getRuleSourceExtData(), NacosParserVO.class); } if (Objects.isNull(nacosParserVO)) { throw new NacosException("rule-source-ext-data is empty"); } if (StrUtil.isBlank(nacosParserVO.getServerAddr())) { nacosParserVO.setServerAddr("127.0.0.1:8848"); } if (StrUtil.isBlank(nacosParserVO.getNamespace())) { nacosParserVO.setNamespace(""); } if (StrUtil.isBlank(nacosParserVO.getDataId())) { nacosParserVO.setDataId("LiteFlow"); } if (StrUtil.isBlank(nacosParserVO.getGroup())) { nacosParserVO.setGroup("LITE_FLOW_GROUP"); } if (StrUtil.isBlank(nacosParserVO.getUsername())) { nacosParserVO.setUsername(""); } if (StrUtil.isBlank(nacosParserVO.getPassword())) { nacosParserVO.setPassword(""); } if (StrUtil.isBlank(nacosParserVO.getAccessKey())){ nacosParserVO.setAccessKey(""); } if (StrUtil.isBlank(nacosParserVO.getSecretKey())){ nacosParserVO.setSecretKey(""); } helper = new NacosParserHelper(nacosParserVO); } catch (Exception e) { throw new NacosException(e.getMessage()); } } @Override public String parseCustom() {<FILL_FUNCTION_BODY>} }
Consumer<String> parseConsumer = t -> { try { parse(t); } catch (Exception e) { throw new RuntimeException(e); } }; try { String content = helper.getContent(); helper.checkContent(content); helper.listener(parseConsumer); return content; } catch (Exception e) { throw new NacosException(e.getMessage()); }
660
127
787
<methods>public non-sealed void <init>() ,public abstract java.lang.String parseCustom() ,public void parseMain(List<java.lang.String>) throws java.lang.Exception<variables>
dromara_liteflow
liteflow/liteflow-rule-plugin/liteflow-rule-nacos/src/main/java/com/yomahub/liteflow/parser/nacos/util/NacosParserHelper.java
NacosParserHelper
checkContent
class NacosParserHelper { private static final Logger LOG = LoggerFactory.getLogger(NacosParserHelper.class); private final NacosParserVO nacosParserVO; private NacosConfigService configService; public NacosParserHelper(NacosParserVO nacosParserVO) { this.nacosParserVO = nacosParserVO; try { try { this.configService = ContextAwareHolder.loadContextAware().getBean(NacosConfigService.class); } catch (Exception ignored) { } if (this.configService == null) { Properties properties = getProperties(nacosParserVO); this.configService = new NacosConfigService(properties); } } catch (Exception e) { throw new NacosException(e.getMessage()); } } private static Properties getProperties(NacosParserVO nacosParserVO) { Properties properties = new Properties(); properties.put(PropertyKeyConst.SERVER_ADDR, nacosParserVO.getServerAddr()); properties.put(PropertyKeyConst.NAMESPACE, nacosParserVO.getNamespace()); if (StrUtil.isNotEmpty(nacosParserVO.getUsername())) { // 用户名密码模式 填写用户名就必有密码 if (StrUtil.isEmpty(PropertyKeyConst.PASSWORD)){ throw new NacosException("Nacos config password is empty"); } // 历史版本会使用用户名密码 properties.put(PropertyKeyConst.USERNAME, nacosParserVO.getUsername()); properties.put(PropertyKeyConst.PASSWORD, nacosParserVO.getPassword()); } else if (StrUtil.isNotEmpty(PropertyKeyConst.ACCESS_KEY)){ // 以下为阿里云RAM子账号使用 填写了ak就必有sk if (StrUtil.isEmpty(PropertyKeyConst.SECRET_KEY)){ throw new NacosException("Nacos config secretKey is empty"); } properties.put(PropertyKeyConst.ACCESS_KEY, nacosParserVO.getAccessKey()); properties.put(PropertyKeyConst.SECRET_KEY, nacosParserVO.getSecretKey()); } return properties; } public String getContent() { try { return configService.getConfig(nacosParserVO.getDataId(), nacosParserVO.getGroup(), 3000L); } catch (Exception e) { throw new NacosException(e.getMessage()); } } /** * 检查 content 是否合法 */ public void checkContent(String content) {<FILL_FUNCTION_BODY>} /** * 监听 nacos 数据变化 */ public void listener(Consumer<String> parseConsumer) { try { this.configService.addListener(nacosParserVO.getDataId(), nacosParserVO.getGroup(), new Listener() { @Override public void receiveConfigInfo(String configInfo) { LOG.info("stating load flow config.... {} ", configInfo); parseConsumer.accept(configInfo); } @Override public Executor getExecutor() { return null; } }); } catch (Exception ex) { throw new NacosException(ex.getMessage()); } } }
if (StrUtil.isBlank(content)) { String error = StrUtil.format("the node[{}] value is empty", nacosParserVO.toString()); throw new ParseException(error); }
877
58
935
<no_super_class>
dromara_liteflow
liteflow/liteflow-rule-plugin/liteflow-rule-nacos/src/main/java/com/yomahub/liteflow/parser/nacos/vo/NacosParserVO.java
NacosParserVO
toString
class NacosParserVO { private String serverAddr; private String namespace; private String dataId; private String group; private String accessKey; private String secretKey; private String username; private String password; public String getServerAddr() { return serverAddr; } public void setServerAddr(String serverAddr) { this.serverAddr = serverAddr; } public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace = namespace; } public String getDataId() { return dataId; } public void setDataId(String dataId) { this.dataId = dataId; } public String getGroup() { return group; } public void setGroup(String group) { this.group = group; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getAccessKey() { return accessKey; } public void setAccessKey(String accessKey) { this.accessKey = accessKey; } public String getSecretKey() { return secretKey; } public void setSecretKey(String secretKey) { this.secretKey = secretKey; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "NacosParserVO{" + "serverAddr='" + serverAddr + '\'' + ", namespace='" + namespace + '\'' + ", dataId='" + dataId + '\'' + ", group='" + group + '\'' + ", accessKey='" + accessKey + '\'' + ", secretKey='" + secretKey + '\'' + ", username='" + username + '\'' + ", password='" + password + '\'' + '}';
399
130
529
<no_super_class>
dromara_liteflow
liteflow/liteflow-rule-plugin/liteflow-rule-redis/src/main/java/com/yomahub/liteflow/parser/redis/RedisXmlELParser.java
RedisXmlELParser
checkParserVO
class RedisXmlELParser extends ClassXmlFlowELParser { private final RedisParserHelper redisParserHelper; private static final String ERROR_COMMON_MSG = "ruleSourceExtData or map is empty"; private static final String ERROR_MSG_PATTERN = "ruleSourceExtData {} is blank"; public RedisXmlELParser() { LiteflowConfig liteflowConfig = LiteflowConfigGetter.get(); try { RedisParserVO redisParserVO = null; String configJson; if (MapUtil.isNotEmpty((liteflowConfig.getRuleSourceExtDataMap()))) { configJson = JsonUtil.toJsonString(liteflowConfig.getRuleSourceExtDataMap()); }else if (StrUtil.isNotBlank(liteflowConfig.getRuleSourceExtData())) { configJson = liteflowConfig.getRuleSourceExtData(); }else{ throw new RedisException(ERROR_COMMON_MSG); } redisParserVO = JsonUtil.parseObject(configJson, RedisParserVO.class); if (Objects.isNull(redisParserVO)) { throw new RedisException(ERROR_COMMON_MSG); } //检查配置文件 checkParserVO(redisParserVO); //选择订阅机制 or 轮询机制 RedisParserMode mode = redisParserVO.getMode(); switch (mode) { case SUB: case SUBSCRIBE: redisParserHelper = new RedisParserSubscribeMode(redisParserVO); break; case POLL: default: redisParserHelper = new RedisParserPollingMode(redisParserVO); break; } } catch (RedisException redisException) { throw redisException; } catch (Exception e) { throw new RedisException(e.getMessage()); } } @Override public String parseCustom() { try { String content = redisParserHelper.getContent(); FlowInitHook.addHook(() -> { redisParserHelper.listenRedis(); return true; }); return content; } catch (Exception e) { throw new RedisException(e.getMessage()); } } private void checkParserVO(RedisParserVO redisParserVO) {<FILL_FUNCTION_BODY>} }
if (redisParserVO.getRedisMode().equals(RedisMode.SINGLE) && StrUtil.isBlank(redisParserVO.getHost())) { throw new RedisException(StrFormatter.format(ERROR_MSG_PATTERN, "host")); } if (redisParserVO.getRedisMode().equals(RedisMode.SINGLE) && ObjectUtil.isNull(redisParserVO.getPort())) { throw new RedisException(StrFormatter.format(ERROR_MSG_PATTERN, "port")); } if (redisParserVO.getRedisMode().equals(RedisMode.SENTINEL) && StrUtil.isBlank(redisParserVO.getMasterName())) { throw new RedisException(StrFormatter.format(ERROR_MSG_PATTERN, "master name")); } if (redisParserVO.getRedisMode().equals(RedisMode.SENTINEL) && CollectionUtil.isEmpty(redisParserVO.getSentinelAddress())) { throw new RedisException(StrFormatter.format(ERROR_MSG_PATTERN, "sentinel address list")); } if (ObjectUtil.isNull(redisParserVO.getChainDataBase())) { throw new RedisException(StrFormatter.format(ERROR_MSG_PATTERN, "chainDataBase")); } if (StrUtil.isBlank(redisParserVO.getChainKey())) { throw new RedisException(StrFormatter.format(ERROR_MSG_PATTERN, "chainKey")); }
618
394
1,012
<methods>public non-sealed void <init>() ,public abstract java.lang.String parseCustom() ,public void parseMain(List<java.lang.String>) throws java.lang.Exception<variables>
dromara_liteflow
liteflow/liteflow-rule-plugin/liteflow-rule-redis/src/main/java/com/yomahub/liteflow/parser/redis/mode/RClient.java
RClient
evalSha
class RClient { private final RedissonClient redissonClient; private Map<String, String> map = new HashMap<>(); public RClient(RedissonClient redissonClient) { this.redissonClient = redissonClient; } /** * get hashmap of the key * * @param key hash name * @return hashmap */ public Map<String, String> getMap(String key) { RMapCache<String, String> mapCache = redissonClient.getMapCache(key); Set<String> mapFieldSet = mapCache.keySet(); if (CollectionUtil.isEmpty(mapFieldSet)) { return map; } for (String field : mapFieldSet) { String value = mapCache.get(field); map.put(field, value); } return map; } /** * add listener of the key * * @param key hash name * @param listener listener * @return listener id */ public int addListener(String key, MapEntryListener listener) { RMapCache<Object, Object> mapCache = redissonClient.getMapCache(key); return mapCache.addListener(listener); } /** * get all keys of hash * * @param key hash name * @return keySet */ public Set<String> hkeys(String key) { RMap<String, String> map = redissonClient.getMap(key, StringCodec.INSTANCE); return map.readAllKeySet(); } /** * gey value of the key * * @param key hash name * @param field hash field * @return hash value */ public String hget(String key, String field) { RMap<String, String> map = redissonClient.getMap(key, StringCodec.INSTANCE); return map.get(field); } /** * Loads Lua script into Redis scripts cache and returns its SHA-1 digest * @param luaScript script * @return shaDigest */ public String scriptLoad(String luaScript) { RScript script = redissonClient.getScript(StringCodec.INSTANCE); return script.scriptLoad(luaScript); } /** * Executes Lua script stored in Redis scripts cache by SHA-1 digest * @param shaDigest script cache by SHA-1 * @param args script args * @return string */ public String evalSha(String shaDigest, String... args){<FILL_FUNCTION_BODY>} }
RScript script = redissonClient.getScript(StringCodec.INSTANCE); return script.evalSha(RScript.Mode.READ_ONLY, shaDigest, RScript.ReturnType.VALUE, Arrays.asList(args)).toString();
679
67
746
<no_super_class>
dromara_liteflow
liteflow/liteflow-rule-plugin/liteflow-rule-redis/src/main/java/com/yomahub/liteflow/parser/redis/mode/polling/ChainPollingTask.java
ChainPollingTask
run
class ChainPollingTask implements Runnable { private RedisParserVO redisParserVO; private RClient chainClient; private Integer chainNum; private Map<String, String> chainSHAMap; private String keyLua; private String valueLua; LFLog LOG = LFLoggerManager.getLogger(ChainPollingTask.class); public ChainPollingTask(RedisParserVO redisParserVO, RClient chainClient, Integer chainNum, Map<String, String> chainSHAMap, String keyLua, String valueLua) { this.redisParserVO = redisParserVO; this.chainClient = chainClient; this.chainNum = chainNum; this.chainSHAMap = chainSHAMap; this.keyLua = keyLua; this.valueLua = valueLua; } /** * 用于返回chain轮询任务 * 先根据hash中value的SHA值修改变化的和被删除的chain * 再根据hash中field数量的变化拉取新增的chain */ @Override public void run() {<FILL_FUNCTION_BODY>} }
try { String chainKey = redisParserVO.getChainKey(); //Lua获取chainKey中最新的chain数量 String keyNum = chainClient.evalSha(keyLua, chainKey); //修改chainNum为最新chain数量 chainNum = Integer.parseInt(keyNum); List<String> needDelete = new ArrayList<>(); //遍历Map,判断各个chain的value有无变化:修改变化了值的chain和被删除的chain for (Map.Entry<String, String> entry : chainSHAMap.entrySet()) { String chainId = entry.getKey(); String oldSHA = entry.getValue(); Pair<Boolean/*启停*/, String/*id*/> pair = RuleParsePluginUtil.parseIdKey(chainId); // 如果是停用,就直接进删除 if (pair.getKey()){ FlowBus.removeChain(pair.getValue()); needDelete.add(chainId); continue; } //在redis服务端通过Lua脚本计算SHA值 String newSHA = chainClient.evalSha(valueLua, chainKey, chainId); if (StrUtil.equals(newSHA, "nil")) { //新SHA值为nil, 即未获取到该chain,表示该chain已被删除 FlowBus.removeChain(pair.getValue()); LOG.info("starting reload flow config... delete key={}", chainId); //添加到待删除的list 后续统一从SHAMap中移除 //不在这里直接移除是为了避免先删除导致chainSHAMap并没有完全遍历完 chain删除不全 needDelete.add(chainId); } else if (!StrUtil.equals(newSHA, oldSHA)) { //SHA值发生变化,表示该chain的值已被修改,重新拉取变化的chain String chainData = chainClient.hget(chainKey, chainId); LiteFlowChainELBuilder.createChain().setChainId(pair.getValue()).setEL(chainData).build(); LOG.info("starting reload flow config... update key={} new value={},", chainId, chainData); //修改SHAMap chainSHAMap.put(chainId, newSHA); } //SHA值无变化,表示该chain未改变 } //统一从SHAMap中移除要删除的chain for (String chainId : needDelete) { chainSHAMap.remove(chainId); } //处理新添加chain和chainId被修改的情况 if (chainNum > chainSHAMap.size()) { //如果封装的SHAMap数量比最新chain总数少, 说明有两种情况: // 1、添加了新chain // 2、修改了chainId:因为遍历到旧的id时会取到nil,SHAMap会把原来的chainId删掉,但没有机会添加新的chainId // 3、上述两者结合 //在此处重新拉取所有chainId集合,补充添加新chain Set<String> newChainSet = chainClient.hkeys(chainKey); for (String chainId : newChainSet) { Pair<Boolean/*启停*/, String/*id*/> pair = RuleParsePluginUtil.parseIdKey(chainId); if (!chainSHAMap.containsKey(chainId)) { //将新chainId添加到LiteFlowChainELBuilder和SHAMap String chainData = chainClient.hget(chainKey, chainId); // 如果是启用,才装配 if (pair.getKey()){ LiteFlowChainELBuilder.createChain().setChainId(pair.getValue()).setEL(chainData).build(); LOG.info("starting reload flow config... create key={} new value={},", chainId, chainData); chainSHAMap.put(chainId, DigestUtil.sha1Hex(chainData)); } } } } } catch (Exception e) { LOG.error("[Exception during chain polling] " + e.getMessage(), e); }
306
1,038
1,344
<no_super_class>
dromara_liteflow
liteflow/liteflow-rule-plugin/liteflow-rule-redis/src/main/java/com/yomahub/liteflow/parser/redis/mode/polling/ScriptPollingTask.java
ScriptPollingTask
run
class ScriptPollingTask implements Runnable { private RedisParserVO redisParserVO; private RClient scriptClient; private Integer scriptNum; private Map<String, String> scriptSHAMap; private String keyLua; private String valueLua; LFLog LOG = LFLoggerManager.getLogger(ScriptPollingTask.class); public ScriptPollingTask(RedisParserVO redisParserVO, RClient scriptClient, Integer scriptNum, Map<String, String> scriptSHAMap, String keyLua, String valueLua) { this.redisParserVO = redisParserVO; this.scriptClient = scriptClient; this.scriptNum = scriptNum; this.scriptSHAMap = scriptSHAMap; this.keyLua = keyLua; this.valueLua = valueLua; } /** * 用于返回script轮询任务 * 首先根据hash中field数量的变化拉取新增的script * 再根据hash中value的SHA值修改变化的和被删除的script */ @Override public void run() {<FILL_FUNCTION_BODY>} }
try { String scriptKey = redisParserVO.getScriptKey(); //Lua获取scriptKey中最新的script数量 String keyNum = scriptClient.evalSha(keyLua, scriptKey); //修改scriptNum为最新script数量 scriptNum = Integer.parseInt(keyNum); List<String> needDelete = new ArrayList<>(); //遍历Map,判断各个script的value有无变化:修改变化了值的script和被删除的script for (Map.Entry<String, String> entry : scriptSHAMap.entrySet()) { String scriptFieldValue = entry.getKey(); String oldSHA = entry.getValue(); //在redis服务端通过Lua脚本计算SHA值 String newSHA = scriptClient.evalSha(valueLua, scriptKey, scriptFieldValue); if (StrUtil.equals(newSHA, "nil")) { //新SHA值为nil, 即未获取到该script,表示该script已被删除 NodeConvertHelper.NodeSimpleVO nodeSimpleVO = NodeConvertHelper.convert(scriptFieldValue); FlowBus.unloadScriptNode(nodeSimpleVO.getNodeId()); LOG.info("starting reload flow config... delete key={}", scriptFieldValue); //添加到待删除的list 后续统一从SHAMap中移除 //不在这里直接移除是为了避免先删除导致scriptSHAMap并没有完全遍历完 script删除不全 needDelete.add(scriptFieldValue); } else if (!StrUtil.equals(newSHA, oldSHA)) { //SHA值发生变化,表示该script的值已被修改,重新拉取变化的script String scriptData = scriptClient.hget(scriptKey, scriptFieldValue); boolean changeSuccess = RedisParserHelper.changeScriptNode(scriptFieldValue, scriptData); if (BooleanUtil.isTrue(changeSuccess)){ scriptSHAMap.put(scriptFieldValue, newSHA); }else{ needDelete.add(scriptFieldValue); } } //SHA值无变化,表示该script未改变 } //统一从SHAMap中移除要删除的script for (String scriptFieldValue : needDelete) { scriptSHAMap.remove(scriptFieldValue); } //处理新添加script和script名被修改的情况 if (scriptNum > scriptSHAMap.size()) { //如果封装的SHAMap数量比最新script总数少, 说明有两种情况: // 1、添加了新script // 2、修改了script名:因为遍历到旧的id时会取到nil,SHAMap会把原来的script删掉,但没有机会添加新的script // 3、上述两者结合 //在此处重新拉取所有script名集合,补充添加新script Set<String> newScriptSet = scriptClient.hkeys(scriptKey); for (String scriptFieldValue : newScriptSet) { if (!scriptSHAMap.containsKey(scriptFieldValue)) { //将新script添加到LiteFlowChainELBuilder和SHAMap String scriptData = scriptClient.hget(scriptKey, scriptFieldValue); boolean isAddSuccess = RedisParserHelper.changeScriptNode(scriptFieldValue, scriptData); if (BooleanUtil.isTrue(isAddSuccess)){ LOG.info("starting reload flow config... create key={} new value={},", scriptFieldValue, scriptData); scriptSHAMap.put(scriptFieldValue, DigestUtil.sha1Hex(scriptData)); }else{ LOG.info("starting reload flow config... delete key={}", scriptFieldValue); needDelete.add(scriptFieldValue); } } } } } catch (Exception e) { LOG.error("[Exception during script polling] " + e.getMessage(), e); }
304
979
1,283
<no_super_class>
dromara_liteflow
liteflow/liteflow-rule-plugin/liteflow-rule-redis/src/main/java/com/yomahub/liteflow/parser/redis/mode/subscribe/RedisParserSubscribeMode.java
RedisParserSubscribeMode
hasScript
class RedisParserSubscribeMode implements RedisParserHelper { private final RedisParserVO redisParserVO; private RClient chainClient; private RClient scriptClient; public RedisParserSubscribeMode(RedisParserVO redisParserVO) { this.redisParserVO = redisParserVO; try { try { this.chainClient = ContextAwareHolder.loadContextAware().getBean("chainClient"); this.scriptClient = ContextAwareHolder.loadContextAware().getBean("scriptClient"); } catch (Exception ignored) { } if (ObjectUtil.isNull(chainClient)) { RedisMode redisMode = redisParserVO.getRedisMode(); Config config; //Redis单点模式 if (redisMode.equals(RedisMode.SINGLE)) { config = getSingleRedissonConfig(redisParserVO, redisParserVO.getChainDataBase()); this.chainClient = new RClient(Redisson.create(config)); //如果有脚本数据 if (ObjectUtil.isNotNull(redisParserVO.getScriptDataBase())) { config = getSingleRedissonConfig(redisParserVO, redisParserVO.getScriptDataBase()); this.scriptClient = new RClient(Redisson.create(config)); } } //Redis哨兵模式 else if (redisMode.equals(RedisMode.SENTINEL)) { config = getSentinelRedissonConfig(redisParserVO, redisParserVO.getChainDataBase()); this.chainClient = new RClient(Redisson.create(config)); //如果有脚本数据 if (ObjectUtil.isNotNull(redisParserVO.getScriptDataBase())) { config = getSentinelRedissonConfig(redisParserVO, redisParserVO.getScriptDataBase()); this.scriptClient = new RClient(Redisson.create(config)); } } } } catch (Exception e) { throw new RedisException(e.getMessage()); } } @Override public String getContent() { try { // 检查chainKey下有没有子节点 Map<String, String> chainMap = chainClient.getMap(redisParserVO.getChainKey()); // 获取chainKey下的所有子节点内容List List<String> chainItemContentList = new ArrayList<>(); for (Map.Entry<String, String> entry : chainMap.entrySet()) { String chainId = entry.getKey(); String chainData = entry.getValue(); RuleParsePluginUtil.ChainDto chainDto = RuleParsePluginUtil.parseChainKey(chainId); if (StrUtil.isNotBlank(chainData)) { chainItemContentList.add(chainDto.toElXml(chainData)); } } // 合并成所有chain的xml内容 String chainAllContent = CollUtil.join(chainItemContentList, StrUtil.EMPTY); // 检查是否有脚本内容,如果有,进行脚本内容的获取 String scriptAllContent = StrUtil.EMPTY; if (hasScript()) { Map<String, String> scriptMap = scriptClient.getMap(redisParserVO.getScriptKey()); List<String> scriptItemContentList = new ArrayList<>(); for (Map.Entry<String, String> entry : scriptMap.entrySet()) { String scriptFieldValue = entry.getKey(); String scriptData = entry.getValue(); NodeConvertHelper.NodeSimpleVO nodeSimpleVO = NodeConvertHelper.convert(scriptFieldValue); if (ObjectUtil.isNull(nodeSimpleVO)) { throw new RedisException( StrUtil.format("The name of the redis field [{}] in scriptKey [{}] is invalid", scriptFieldValue, redisParserVO.getScriptKey())); } nodeSimpleVO.setScript(scriptData); scriptItemContentList.add(RuleParsePluginUtil.toScriptXml(nodeSimpleVO)); } scriptAllContent = StrUtil.format(NODE_XML_PATTERN, CollUtil.join(scriptItemContentList, StrUtil.EMPTY)); } return StrUtil.format(XML_PATTERN, scriptAllContent, chainAllContent); } catch (Exception e) { throw new RedisException(e.getMessage()); } } public boolean hasScript() {<FILL_FUNCTION_BODY>} /** * 监听 redis key */ @Override public void listenRedis() { //监听 chain String chainKey = redisParserVO.getChainKey(); //添加新 chain chainClient.addListener(chainKey, (EntryCreatedListener<String, String>) event -> { LOG.info("starting modify flow config... create key={} value={},", event.getKey(), event.getValue()); String chainId = event.getKey(); String value = event.getValue(); RedisParserHelper.changeChain(chainId, value); }); //修改 chain chainClient.addListener(chainKey, (EntryUpdatedListener<String, String>) event -> { LOG.info("starting modify flow config... create key={} value={},", event.getKey(), event.getValue()); String chainId = event.getKey(); String value = event.getValue(); RedisParserHelper.changeChain(chainId, value); }); //删除 chain chainClient.addListener(chainKey, (EntryRemovedListener<String, String>) event -> { LOG.info("starting reload flow config... delete key={}", event.getKey()); Pair<Boolean/*启停*/, String/*id*/> pair = RuleParsePluginUtil.parseIdKey(event.getKey()); FlowBus.removeChain(pair.getValue()); }); //监听 script if (ObjectUtil.isNotNull(scriptClient) && ObjectUtil.isNotNull(redisParserVO.getScriptDataBase())) { String scriptKey = redisParserVO.getScriptKey(); //添加 script scriptClient.addListener(scriptKey, (EntryCreatedListener<String, String>) event -> { LOG.info("starting reload flow config... create key={} value={},", event.getKey(), event.getValue()); RedisParserHelper.changeScriptNode(event.getKey(), event.getValue()); }); //修改 script scriptClient.addListener(scriptKey, (EntryUpdatedListener<String, String>) event -> { LOG.info("starting reload flow config... update key={} new value={},", event.getKey(), event.getValue()); RedisParserHelper.changeScriptNode(event.getKey(), event.getValue()); }); //删除 script scriptClient.addListener(scriptKey, (EntryRemovedListener<String, String>) event -> { LOG.info("starting reload flow config... delete key={}", event.getKey()); NodeConvertHelper.NodeSimpleVO nodeSimpleVO = NodeConvertHelper.convert(event.getKey()); FlowBus.unloadScriptNode(nodeSimpleVO.getNodeId()); }); } } }
// 没有scriptClient或没有配置scriptDataBase if (ObjectUtil.isNull(scriptClient) || ObjectUtil.isNull(redisParserVO.getScriptDataBase())) { return false; } try { // 存在这个节点,但是子节点不存在 Map<String, String> scriptMap = scriptClient.getMap(redisParserVO.getScriptKey()); return !CollUtil.isEmpty(scriptMap); } catch (Exception e) { return false; }
1,804
129
1,933
<no_super_class>
dromara_liteflow
liteflow/liteflow-rule-plugin/liteflow-rule-redis/src/main/java/com/yomahub/liteflow/parser/redis/vo/RedisParserVO.java
RedisParserVO
toString
class RedisParserVO { /*Redis配置模式 单点/哨兵, 默认为单点模式*/ private RedisMode redisMode = RedisMode.SINGLE; /*单点模式 连接地址*/ private String host; /*单点模式 端口号*/ private Integer port; /*哨兵模式 主节点名*/ private String masterName; /*哨兵模式 哨兵节点连接地址 ip:port, 可配置多个*/ private List<String> sentinelAddress; /*用户名 需要Redis 6.0及以上*/ private String username; /*密码*/ private String password; /*监听机制 轮询为poll 订阅为subscribe 默认为poll*/ private RedisParserMode mode = RedisParserMode.POLL; /*轮询时间间隔(s) 默认60s 若选择订阅机制可不配置*/ private Integer pollingInterval = 60; /*规则配置后首次轮询的起始时间 默认为60s 若选择订阅机制可不配置*/ private Integer pollingStartTime = 60; /*chain表配置的数据库号*/ private Integer chainDataBase; /*chain配置的键名*/ private String chainKey; /*脚本表配置的数据库号 若没有脚本数据可不配置*/ private Integer scriptDataBase; /*脚本配置的键名 若没有脚本数据可不配置*/ private String scriptKey; public void setRedisMode(String redisMode) { redisMode = redisMode.toUpperCase(); try{ RedisMode m = RedisMode.valueOf(redisMode); this.redisMode = m; } catch (Exception ignored) { //转换出错默认为单点模式 } } public RedisMode getRedisMode() { return redisMode; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } public String getMasterName() { return masterName; } public void setMasterName(String masterName) { this.masterName = masterName; } public List<String> getSentinelAddress() { return sentinelAddress; } public void setSentinelAddress(List<String> sentinelAddress) { this.sentinelAddress = sentinelAddress; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public RedisParserMode getMode() { return mode; } public void setMode(String mode) { mode = mode.toUpperCase(); try{ RedisParserMode m = RedisParserMode.valueOf(mode); this.mode = m; } catch (Exception ignored) { //枚举类转换出错默认为轮询方式 } } public Integer getPollingStartTime() { return pollingStartTime; } public void setPollingStartTime(Integer pollingStartTime) { this.pollingStartTime = pollingStartTime; } public Integer getPollingInterval() { return pollingInterval; } public void setPollingInterval(Integer pollingInterval) { this.pollingInterval = pollingInterval; } public Integer getChainDataBase() { return chainDataBase; } public void setChainDataBase(Integer chainDataBase) { this.chainDataBase = chainDataBase; } public String getChainKey() { return chainKey; } public void setChainKey(String chainKey) { this.chainKey = chainKey; } public Integer getScriptDataBase() { return scriptDataBase; } public void setScriptDataBase(Integer scriptDataBase) { this.scriptDataBase = scriptDataBase; } public String getScriptKey() { return scriptKey; } public void setScriptKey(String scriptKey) { this.scriptKey = scriptKey; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "RedisParserVO{" + "redisMode=" + redisMode + ", host='" + host + '\'' + ", port=" + port + ", masterName=" + masterName + ", sentinelAddress=" + sentinelAddress + ", username='" + username + '\'' + ", password='" + password + '\'' + ", mode=" + mode + ", pollingInterval=" + pollingInterval + ", pollingStartTime=" + pollingStartTime + ", chainDataBase=" + chainDataBase + ", chainKey='" + chainKey + '\'' + ", scriptDataBase=" + scriptDataBase + ", scriptKey='" + scriptKey + '\'' + '}';
1,219
193
1,412
<no_super_class>
dromara_liteflow
liteflow/liteflow-rule-plugin/liteflow-rule-sql/src/main/java/com/yomahub/liteflow/parser/sql/SQLXmlELParser.java
SQLXmlELParser
parseCustom
class SQLXmlELParser extends ClassXmlFlowELParser { private static SQLParserVO sqlParserVO; private static final String ERROR_MSG_PATTERN = "rule-source-ext-data {} is blank"; private static final String ERROR_COMMON_MSG = "rule-source-ext-data is empty"; /** * 构造函数 */ public SQLXmlELParser() { LiteflowConfig liteflowConfig = LiteflowConfigGetter.get(); try { if (MapUtil.isNotEmpty((liteflowConfig.getRuleSourceExtDataMap()))) { sqlParserVO = BeanUtil.toBean(liteflowConfig.getRuleSourceExtDataMap(), SQLParserVO.class, CopyOptions.create()); } else if (StrUtil.isNotBlank(liteflowConfig.getRuleSourceExtData())) { sqlParserVO = JsonUtil.parseObject(liteflowConfig.getRuleSourceExtData(), SQLParserVO.class); } if (Objects.isNull(sqlParserVO)) { throw new ELSQLException(ERROR_COMMON_MSG); } // 检查配置文件 checkParserVO(sqlParserVO); // 初始化 JDBCHelper JDBCHelper.init(sqlParserVO); // 初始化 SqlReadFactory SqlReadFactory.registerRead(sqlParserVO); // 注册轮询任务 SqlReadFactory.registerSqlReadPollTask(ReadType.CHAIN); SqlReadFactory.registerSqlReadPollTask(ReadType.SCRIPT); } catch (ELSQLException elsqlException) { throw elsqlException; } catch (Exception ex) { throw new ELSQLException(ex.getMessage()); } } @Override public String parseCustom() {<FILL_FUNCTION_BODY>} /** * 检查配置文件并设置默认值 * * @param sqlParserVO sqlParserVO */ private void checkParserVO(SQLParserVO sqlParserVO) { if (sqlParserVO.isDefaultDataSource()) { return; } if (StrUtil.isEmpty(sqlParserVO.getUrl())) { throw new ELSQLException(StrFormatter.format(ERROR_MSG_PATTERN, "url")); } if (StrUtil.isEmpty(sqlParserVO.getDriverClassName())) { throw new ELSQLException(StrFormatter.format(ERROR_MSG_PATTERN, "driverClassName")); } if (Objects.isNull(sqlParserVO.getUsername())) { throw new ELSQLException(StrFormatter.format(ERROR_MSG_PATTERN, "username")); } if (Objects.isNull(sqlParserVO.getPassword())) { throw new ELSQLException(StrFormatter.format(ERROR_MSG_PATTERN, "password")); } } }
try { JDBCHelper jdbcHelper = JDBCHelper.getInstance(); String content = jdbcHelper.getContent(); if (sqlParserVO.getPollingEnabled()) { FlowInitHook.addHook(() -> { jdbcHelper.listenSQL(); return true; }); } return content; } catch (Exception ex) { throw new ELSQLException(ex.getMessage()); }
736
113
849
<methods>public non-sealed void <init>() ,public abstract java.lang.String parseCustom() ,public void parseMain(List<java.lang.String>) throws java.lang.Exception<variables>
dromara_liteflow
liteflow/liteflow-rule-plugin/liteflow-rule-sql/src/main/java/com/yomahub/liteflow/parser/sql/polling/AbstractSqlReadPollTask.java
AbstractSqlReadPollTask
execute
class AbstractSqlReadPollTask implements SqlReadPollTask { private final Map<String/*唯一键*/, String/*data-xml的sha1值*/> DATA_SHA_MAP = new HashMap<>(); private final SqlRead read; public AbstractSqlReadPollTask(SqlRead read) { this.read = read; if (!read.type().equals(type())) { throw new ELSQLException("SqlReadPollTask type not match"); } } @Override public void execute() {<FILL_FUNCTION_BODY>} @Override public void initData(Map<String/*唯一键*/, String/*data-xml的数据*/> dataMap) { DATA_SHA_MAP.putAll(shaMapValue(dataMap)); } public abstract void doSave(Map<String, String> saveElementMap); public abstract void doDelete(List<String> deleteElementId); private Map<String/*唯一键*/, String/*data-xml的sha1值*/> shaMapValue(Map<String, String> dataMap) { Map<String, String> result = new HashMap<>(); dataMap.forEach((k, v) -> { result.put(k, DigestUtil.sha1Hex(v)); }); return result; } }
Map<String/*唯一键*/, String/*data-xml*/> newData = read.read(); // 新增或者更新的元素 Map<String, String> saveElementMap = new HashMap<>(); // 删除的元素 List<String> deleteElementIds = new ArrayList<>(); for (Map.Entry<String, String> entry : newData.entrySet()) { String id = entry.getKey(); String element = entry.getValue(); String newSHA = DigestUtil.sha1Hex(element); // 新增 // 如果封装的SHAMap中不存在该chain, 表示该元素为新增 if (!DATA_SHA_MAP.containsKey(id)) { saveElementMap.put(id, element); DATA_SHA_MAP.put(id, newSHA); } // 修改 // SHA值发生变化,表示该元素的值已被修改,重新拉取变化的chain else if (!StrUtil.equals(newSHA, DATA_SHA_MAP.get(id))) { saveElementMap.put(id, element); DATA_SHA_MAP.put(id, newSHA); } } Set<String> oldIdList = DATA_SHA_MAP.keySet(); // 旧的 id 列表 Set<String> newIdList = newData.keySet(); // 新的 id 列表 // 计算单差集 // 计算集合的单差集,即只返回【oldIdList】中有,但是【newIdList】中没有的元素,例如: // subtractToList([1,2,3,4],[2,3,4,5]) -》 [1] deleteElementIds = CollUtil.subtractToList(oldIdList, newIdList); for (String id : deleteElementIds) { DATA_SHA_MAP.remove(id); } if (CollUtil.isNotEmpty(saveElementMap)) { doSave(saveElementMap); } if (CollUtil.isNotEmpty(deleteElementIds)) { doDelete(deleteElementIds); }
335
551
886
<no_super_class>
dromara_liteflow
liteflow/liteflow-rule-plugin/liteflow-rule-sql/src/main/java/com/yomahub/liteflow/parser/sql/polling/impl/ChainReadPollTask.java
ChainReadPollTask
doSave
class ChainReadPollTask extends AbstractSqlReadPollTask { public ChainReadPollTask(SqlRead read) { super(read); } @Override public void doSave(Map<String, String> saveElementMap) {<FILL_FUNCTION_BODY>} @Override public void doDelete(List<String> deleteElementId) { for (String id : deleteElementId) { FlowBus.removeChain(id); } } @Override public ReadType type() { return ReadType.CHAIN; } }
for (Map.Entry<String, String> entry : saveElementMap.entrySet()) { String chainName = entry.getKey(); String newData = entry.getValue(); LiteFlowChainELBuilder.createChain().setChainId(chainName).setEL(newData).build(); }
153
77
230
<methods>public void <init>(com.yomahub.liteflow.parser.sql.read.SqlRead) ,public abstract void doDelete(List<java.lang.String>) ,public abstract void doSave(Map<java.lang.String,java.lang.String>) ,public void execute() ,public void initData(Map<java.lang.String,java.lang.String>) <variables>private final Map<java.lang.String,java.lang.String> DATA_SHA_MAP,private final non-sealed com.yomahub.liteflow.parser.sql.read.SqlRead read
dromara_liteflow
liteflow/liteflow-rule-plugin/liteflow-rule-sql/src/main/java/com/yomahub/liteflow/parser/sql/polling/impl/ScriptReadPollTask.java
ScriptReadPollTask
doDelete
class ScriptReadPollTask extends AbstractSqlReadPollTask { public ScriptReadPollTask(SqlRead read) { super(read); } @Override public void doSave(Map<String, String> saveElementMap) { for (Map.Entry<String, String> entry : saveElementMap.entrySet()) { String scriptKey = entry.getKey(); String newData = entry.getValue(); NodeConvertHelper.NodeSimpleVO scriptVO = NodeConvertHelper.convert(scriptKey); NodeConvertHelper.changeScriptNode(scriptVO, newData); } } @Override public void doDelete(List<String> deleteElementId) {<FILL_FUNCTION_BODY>} @Override public ReadType type() { return ReadType.SCRIPT; } }
for (String id : deleteElementId) { NodeConvertHelper.NodeSimpleVO scriptVO = NodeConvertHelper.convert(id); // 删除script FlowBus.unloadScriptNode(scriptVO.getNodeId()); }
207
64
271
<methods>public void <init>(com.yomahub.liteflow.parser.sql.read.SqlRead) ,public abstract void doDelete(List<java.lang.String>) ,public abstract void doSave(Map<java.lang.String,java.lang.String>) ,public void execute() ,public void initData(Map<java.lang.String,java.lang.String>) <variables>private final Map<java.lang.String,java.lang.String> DATA_SHA_MAP,private final non-sealed com.yomahub.liteflow.parser.sql.read.SqlRead read
dromara_liteflow
liteflow/liteflow-rule-plugin/liteflow-rule-sql/src/main/java/com/yomahub/liteflow/parser/sql/read/AbstractSqlRead.java
AbstractSqlRead
read
class AbstractSqlRead implements SqlRead { public final SQLParserVO config; private static LFLog LOG = LFLoggerManager.getLogger(AbstractSqlRead.class); public AbstractSqlRead(SQLParserVO config) { this.config = config; } @Override public Map<String/*规则唯一键*/, String/*规则内容*/> read() {<FILL_FUNCTION_BODY>} /** * 是否包含启停字段 */ public abstract boolean hasEnableFiled(); /** * 获取启停字段对应的字段值 */ public abstract boolean getEnableFiledValue(ResultSet rs) throws SQLException; public abstract String buildQuerySql(); public abstract String buildXmlElement(ResultSet rs) throws SQLException; public abstract String buildXmlElementUniqueKey(ResultSet rs) throws SQLException; public abstract void checkConfig(); /** * 是否可以读取 * chain 默认可以读取 * script 需要判断是否有配置 * * @return 布尔值 */ public boolean needRead() { return true; } public String getStringFromRs(ResultSet rs, String field) throws SQLException { return rs.getString(field); } public String getStringFromRsWithCheck(ResultSet rs, String field) throws SQLException { String data = getStringFromRs(rs, field); if (StrUtil.isBlank(data)) { throw new ELSQLException(StrUtil.format("field[{}] value is empty", field)); } return data; } private void logSqlIfEnable(String sqlCmd) { if (!config.getSqlLogEnabled()) { return; } StringBuilder strBuilder = new StringBuilder("query sql: "); // 如果包含启停字段 if (config.hasEnableField()) { String replaceAppName = StrUtil.replaceFirst(sqlCmd, "?", "'" + config.getApplicationName() + "'"); String executeSql = StrUtil.replaceFirst(replaceAppName, "?", Boolean.TRUE.toString()); strBuilder.append(executeSql); } // 如果不包含启停字段 else { strBuilder.append(sqlCmd.replace("?", "'" + config.getApplicationName() + "'")); } LOG.info(strBuilder.toString()); } }
// 如果不需要读取直接返回 if (!needRead()) { return new HashMap<>(); } checkConfig(); String sqlCmd = buildQuerySql(); // 如果允许,就打印 sql 语句 logSqlIfEnable(sqlCmd); Map<String/*规则唯一键*/, String/*规则*/> result = new HashMap<>(); Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = LiteFlowJdbcUtil.getConn(config); stmt = conn.prepareStatement(sqlCmd, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); // 设置游标拉取数量 stmt.setFetchSize(SqlReadConstant.FETCH_SIZE_MAX); stmt.setString(1, config.getApplicationName()); rs = stmt.executeQuery(); while (rs.next()) { String xml = buildXmlElement(rs); String uniqueKey = buildXmlElementUniqueKey(rs); if (hasEnableFiled()){ boolean enable = getEnableFiledValue(rs); // 如果停用,直接跳过 if (!enable){ continue; } } result.put(uniqueKey, xml); } } catch (Exception e) { throw new ELSQLException(e.getMessage()); } finally { // 关闭连接 LiteFlowJdbcUtil.close(conn, stmt, rs); } return result;
620
401
1,021
<no_super_class>
dromara_liteflow
liteflow/liteflow-rule-plugin/liteflow-rule-sql/src/main/java/com/yomahub/liteflow/parser/sql/read/SqlReadFactory.java
SqlReadFactory
registerSqlReadPollTask
class SqlReadFactory { private static final Map<ReadType, SqlRead> READ_MAP = new HashMap<>(); private static final Map<ReadType, SqlReadPollTask> POLL_TASK_MAP = new HashMap<>(); public static void registerRead(SQLParserVO config) { READ_MAP.put(ReadType.CHAIN, new ChainRead(config)); READ_MAP.put(ReadType.SCRIPT, new ScriptRead(config)); } public static void registerSqlReadPollTask(ReadType readType) {<FILL_FUNCTION_BODY>} public static SqlRead getSqlRead(ReadType readType) { return READ_MAP.get(readType); } public static SqlReadPollTask getSqlReadPollTask(ReadType readType) { return POLL_TASK_MAP.get(readType); } }
SqlRead sqlRead = getSqlRead(readType); if (ReadType.CHAIN.equals(readType)) { POLL_TASK_MAP.put(ReadType.CHAIN, new ChainReadPollTask(sqlRead)); } else if (ReadType.SCRIPT.equals(readType)) { POLL_TASK_MAP.put(ReadType.SCRIPT, new ScriptReadPollTask(sqlRead)); }
222
109
331
<no_super_class>
dromara_liteflow
liteflow/liteflow-rule-plugin/liteflow-rule-sql/src/main/java/com/yomahub/liteflow/parser/sql/read/impl/ChainRead.java
ChainRead
checkConfig
class ChainRead extends AbstractSqlRead { public ChainRead(SQLParserVO config) { super(config); } @Override public boolean hasEnableFiled() { String chainEnableField = super.config.getChainEnableField(); return StrUtil.isNotBlank(chainEnableField); } @Override public boolean getEnableFiledValue(ResultSet rs) throws SQLException { String chainEnableField = super.config.getChainEnableField(); byte enable = rs.getByte(chainEnableField); return enable == 1; } @Override public String buildQuerySql() { String chainTableName = super.config.getChainTableName(); String chainApplicationNameField = super.config.getChainApplicationNameField(); return StrUtil.format(SqlReadConstant.SQL_PATTERN, chainTableName, chainApplicationNameField); } @Override public void checkConfig() {<FILL_FUNCTION_BODY>} @Override public String buildXmlElement(ResultSet rs) throws SQLException { String elDataField = super.config.getElDataField(); return getStringFromRs(rs, elDataField); } @Override public String buildXmlElementUniqueKey(ResultSet rs) throws SQLException { String chainNameField = super.config.getChainNameField(); return getStringFromRsWithCheck(rs, chainNameField); } @Override public ReadType type() { return ReadType.CHAIN; } }
String chainTableName = super.config.getChainTableName(); String elDataField = super.config.getElDataField(); String chainNameField = super.config.getChainNameField(); String chainApplicationNameField = super.config.getChainApplicationNameField(); String applicationName = super.config.getApplicationName(); if (StrUtil.isBlank(chainTableName)){ throw new ELSQLException("You did not define the chainTableName property"); } if (StrUtil.isBlank(elDataField)){ throw new ELSQLException("You did not define the elDataField property"); } if (StrUtil.isBlank(chainNameField)){ throw new ELSQLException("You did not define the chainNameField property"); } if (StrUtil.isBlank(chainApplicationNameField)){ throw new ELSQLException("You did not define the chainApplicationNameField property"); } if (StrUtil.isBlank(applicationName)){ throw new ELSQLException("You did not define the applicationName property"); }
398
264
662
<methods>public void <init>(com.yomahub.liteflow.parser.sql.vo.SQLParserVO) ,public abstract java.lang.String buildQuerySql() ,public abstract java.lang.String buildXmlElement(java.sql.ResultSet) throws java.sql.SQLException,public abstract java.lang.String buildXmlElementUniqueKey(java.sql.ResultSet) throws java.sql.SQLException,public abstract void checkConfig() ,public abstract boolean getEnableFiledValue(java.sql.ResultSet) throws java.sql.SQLException,public java.lang.String getStringFromRs(java.sql.ResultSet, java.lang.String) throws java.sql.SQLException,public java.lang.String getStringFromRsWithCheck(java.sql.ResultSet, java.lang.String) throws java.sql.SQLException,public abstract boolean hasEnableFiled() ,public boolean needRead() ,public Map<java.lang.String,java.lang.String> read() <variables>private static com.yomahub.liteflow.log.LFLog LOG,public final non-sealed com.yomahub.liteflow.parser.sql.vo.SQLParserVO config
dromara_liteflow
liteflow/liteflow-rule-plugin/liteflow-rule-sql/src/main/java/com/yomahub/liteflow/parser/sql/read/impl/ScriptRead.java
ScriptRead
buildXmlElementUniqueKey
class ScriptRead extends AbstractSqlRead { public ScriptRead(SQLParserVO config) { super(config); } @Override public boolean hasEnableFiled() { String scriptEnableField = super.config.getScriptEnableField(); return StrUtil.isNotBlank(scriptEnableField); } @Override public boolean getEnableFiledValue(ResultSet rs) throws SQLException { String scriptEnableField = super.config.getScriptEnableField(); byte enable = rs.getByte(scriptEnableField); return enable == 1; } @Override public String buildQuerySql() { String scriptTableName = super.config.getScriptTableName(); String scriptApplicationNameField = super.config.getScriptApplicationNameField(); return StrUtil.format( SqlReadConstant.SCRIPT_SQL_PATTERN, scriptTableName, scriptApplicationNameField); } @Override public void checkConfig() { String scriptTableName = super.config.getScriptTableName(); String scriptIdField = super.config.getScriptIdField(); String scriptDataField = super.config.getScriptDataField(); String scriptTypeField = super.config.getScriptTypeField(); String scriptApplicationNameField = super.config.getScriptApplicationNameField(); if(StrUtil.isBlank(scriptTableName)){ throw new ELSQLException("You did not define the scriptTableName property"); } if(StrUtil.isBlank(scriptIdField)){ throw new ELSQLException("You did not define the scriptIdField property"); } if(StrUtil.isBlank(scriptDataField)){ throw new ELSQLException("You did not define the scriptDataField property"); } if(StrUtil.isBlank(scriptTypeField)){ throw new ELSQLException("You did not define the scriptTypeField property"); } if(StrUtil.isBlank(scriptApplicationNameField)){ throw new ELSQLException("You did not define the scriptApplicationNameField property"); } } @Override public String buildXmlElement(ResultSet rs) throws SQLException { String scriptDataField = super.config.getScriptDataField(); return getStringFromRs(rs, scriptDataField); } @Override public String buildXmlElementUniqueKey(ResultSet rs) throws SQLException {<FILL_FUNCTION_BODY>} @Override public boolean needRead() { if (StrUtil.isBlank(super.config.getScriptTableName())) { return false; } String sqlCmd = StrUtil.format( SqlReadConstant.SCRIPT_SQL_CHECK_PATTERN, super.config.getScriptTableName() ); Connection conn = LiteFlowJdbcUtil.getConn(super.config); return LiteFlowJdbcUtil.checkConnectionCanExecuteSql(conn, sqlCmd); } @Override public ReadType type() { return ReadType.SCRIPT; } /** * 脚本是否带语言 */ private boolean withLanguage() { return StrUtil.isNotBlank(super.config.getScriptLanguageField()); } }
String scriptIdField = super.config.getScriptIdField(); String scriptNameField = super.config.getScriptNameField(); String scriptTypeField = super.config.getScriptTypeField(); String scriptLanguageField = super.config.getScriptLanguageField(); String id = getStringFromRsWithCheck(rs, scriptIdField); String name = getStringFromRsWithCheck(rs, scriptNameField); String type = getStringFromRsWithCheck(rs, scriptTypeField); String language = withLanguage() ? getStringFromRs(rs, scriptLanguageField) : null; NodeTypeEnum nodeTypeEnum = NodeTypeEnum.getEnumByCode(type); if (Objects.isNull(nodeTypeEnum)) { throw new ELSQLException(StrUtil.format("Invalid type value[{}]", type)); } if (!nodeTypeEnum.isScript()) { throw new ELSQLException(StrUtil.format("The type value[{}] is not a script type", type)); } if (withLanguage() && !ScriptTypeEnum.checkScriptType(language)) { throw new ELSQLException(StrUtil.format("The language value[{}] is invalid", language)); } List<String> keys = CollUtil.newArrayList(id, type, name); if (StrUtil.isNotBlank(language)) { keys.add(language); } return StrUtil.join(StrUtil.COLON, keys);
811
363
1,174
<methods>public void <init>(com.yomahub.liteflow.parser.sql.vo.SQLParserVO) ,public abstract java.lang.String buildQuerySql() ,public abstract java.lang.String buildXmlElement(java.sql.ResultSet) throws java.sql.SQLException,public abstract java.lang.String buildXmlElementUniqueKey(java.sql.ResultSet) throws java.sql.SQLException,public abstract void checkConfig() ,public abstract boolean getEnableFiledValue(java.sql.ResultSet) throws java.sql.SQLException,public java.lang.String getStringFromRs(java.sql.ResultSet, java.lang.String) throws java.sql.SQLException,public java.lang.String getStringFromRsWithCheck(java.sql.ResultSet, java.lang.String) throws java.sql.SQLException,public abstract boolean hasEnableFiled() ,public boolean needRead() ,public Map<java.lang.String,java.lang.String> read() <variables>private static com.yomahub.liteflow.log.LFLog LOG,public final non-sealed com.yomahub.liteflow.parser.sql.vo.SQLParserVO config
dromara_liteflow
liteflow/liteflow-rule-plugin/liteflow-rule-sql/src/main/java/com/yomahub/liteflow/parser/sql/util/JDBCHelper.java
JDBCHelper
init
class JDBCHelper { private SQLParserVO sqlParserVO; private static JDBCHelper INSTANCE; /** * 定时任务线程池核心线程数 */ private static final int CORE_POOL_SIZE = 2; /** * 定时任务线程池 */ private static ScheduledThreadPoolExecutor pollExecutor; private static LFLog LOG = LFLoggerManager.getLogger(JDBCHelper.class); /** * 初始化 INSTANCE */ public static void init(SQLParserVO sqlParserVO) {<FILL_FUNCTION_BODY>} /** * 获取 INSTANCE * * @return 实例 */ public static JDBCHelper getInstance() { return INSTANCE; } /** * 获取 ElData 数据内容 * * @return 数据内容 */ public String getContent() { SqlRead chainRead = SqlReadFactory.getSqlRead(ReadType.CHAIN); SqlRead scriptRead = SqlReadFactory.getSqlRead(ReadType.SCRIPT); // 获取 chain 数据 Map<String, String> chainMap = chainRead.read(); List<String> chainList = new ArrayList<>(); chainMap.entrySet().stream() .filter(entry -> StrUtil.isNotBlank(entry.getValue())) .forEach( entry -> chainList.add(StrUtil.format(CHAIN_XML_PATTERN, XmlUtil.escape(entry.getKey()), entry.getValue())) ); String chainsContent = CollUtil.join(chainList, StrUtil.EMPTY); // 获取脚本数据 Map<String, String> scriptMap = scriptRead.read(); List<String> scriptList = new ArrayList<>(); scriptMap.forEach((scriptKey, elData) -> { NodeConvertHelper.NodeSimpleVO scriptVO = NodeConvertHelper.convert(scriptKey); String id = scriptVO.getNodeId(); String name = scriptVO.getName(); String type = scriptVO.getType(); String language = scriptVO.getLanguage(); if (StringUtils.isNotBlank(scriptVO.getLanguage())) { scriptList.add(StrUtil.format(NODE_ITEM_WITH_LANGUAGE_XML_PATTERN, XmlUtil.escape(id), XmlUtil.escape(name), type, language, elData)); } else { scriptList.add(StrUtil.format(NODE_ITEM_XML_PATTERN, XmlUtil.escape(id), XmlUtil.escape(name), type, elData)); } }); String nodesContent = StrUtil.format(NODE_XML_PATTERN, CollUtil.join(scriptList, StrUtil.EMPTY)); // 初始化轮询任务 SqlReadFactory.getSqlReadPollTask(ReadType.CHAIN).initData(chainMap); SqlReadFactory.getSqlReadPollTask(ReadType.SCRIPT).initData(scriptMap); return StrUtil.format(XML_PATTERN, nodesContent, chainsContent); } /** * 定时轮询拉取SQL中变化的数据 */ public void listenSQL() { // 添加轮询chain的定时任务 pollExecutor.scheduleAtFixedRate( () -> { try { SqlReadFactory.getSqlReadPollTask(ReadType.CHAIN).execute(); } catch (Exception ex) { LOG.error("poll chain fail", ex); } }, sqlParserVO.getPollingStartSeconds().longValue(), sqlParserVO.getPollingIntervalSeconds().longValue(), TimeUnit.SECONDS ); // 添加轮询script的定时任务 pollExecutor.scheduleAtFixedRate( () -> { try { SqlReadFactory.getSqlReadPollTask(ReadType.SCRIPT).execute(); } catch (Exception ex) { LOG.error("poll script fail", ex); } }, sqlParserVO.getPollingStartSeconds().longValue(), sqlParserVO.getPollingIntervalSeconds().longValue(), TimeUnit.SECONDS ); } private void setSqlParserVO(SQLParserVO sqlParserVO) { this.sqlParserVO = sqlParserVO; } public static ScheduledThreadPoolExecutor getPollExecutor() { return pollExecutor; } public static void setPollExecutor(ScheduledThreadPoolExecutor pollExecutor) { JDBCHelper.pollExecutor = pollExecutor; } }
try { INSTANCE = new JDBCHelper(); if (StrUtil.isNotBlank(sqlParserVO.getDriverClassName())) { Class.forName(sqlParserVO.getDriverClassName()); } INSTANCE.setSqlParserVO(sqlParserVO); // 创建定时任务线程池 if (sqlParserVO.getPollingEnabled() && ObjectUtil.isNull(getPollExecutor())) { ThreadFactory namedThreadFactory = new NamedThreadFactory("SQL-Polling-", false); ScheduledThreadPoolExecutor threadPoolExecutor = new ScheduledThreadPoolExecutor(CORE_POOL_SIZE, namedThreadFactory, new ThreadPoolExecutor.DiscardOldestPolicy()); setPollExecutor(threadPoolExecutor); } } catch (ClassNotFoundException e) { throw new ELSQLException(e.getMessage()); }
1,181
218
1,399
<no_super_class>
dromara_liteflow
liteflow/liteflow-rule-plugin/liteflow-rule-sql/src/main/java/com/yomahub/liteflow/parser/sql/util/LiteFlowJdbcUtil.java
LiteFlowJdbcUtil
getConn
class LiteFlowJdbcUtil { private static final Logger LOG = LoggerFactory.getLogger(LiteFlowJdbcUtil.class); private static final String CHECK_SQL_PATTERN = "SELECT {},{} FROM {}"; /** * 获取链接 * 此方法会根据配置,判读使用指定数据源,还是IOC容器中已有的数据源 * * @param sqlParserVO sql解析器参数 * @return 返回数据库连接 */ public static Connection getConn(SQLParserVO sqlParserVO) {<FILL_FUNCTION_BODY>} /** * 判断连接是否可以执行指定 sql * * @param conn 连接 * @param sql 执行 sql */ public static boolean checkConnectionCanExecuteSql(Connection conn, String sql) { PreparedStatement stmt = null; ResultSet rs = null; try { stmt = conn.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); stmt.setFetchSize(1); rs = stmt.executeQuery(); return true; } catch (Exception e) { return false; } finally { // 关闭连接 close(conn, stmt, rs); } } /** * 关闭 * * @param conn conn * @param rs rs */ public static void close(Connection conn, PreparedStatement stmt, ResultSet rs) { // 关闭结果集 if (rs != null) { try { rs.close(); } catch (SQLException e) { throw new ELSQLException(e.getMessage()); } } // 关闭 statement if (stmt != null) { try { stmt.close(); } catch (SQLException e) { throw new ELSQLException(e.getMessage()); } } // 关闭连接 if (conn != null) { try { conn.close(); } catch (SQLException e) { throw new ELSQLException(e.getMessage()); } } } /** * 构建检查 sql * * @param sqlParserVO sql解析器参数 * @return 返回组合完成的检查sql */ private static String buildCheckSql(SQLParserVO sqlParserVO) { String chainTableName = sqlParserVO.getChainTableName(); String elDataField = sqlParserVO.getElDataField(); String chainNameField = sqlParserVO.getChainNameField(); return StrUtil.format(CHECK_SQL_PATTERN, chainNameField, elDataField, chainTableName); } }
Connection connection = null; String url = sqlParserVO.getUrl(); String username = sqlParserVO.getUsername(); String password = sqlParserVO.getPassword(); try { // 如果不配置 jdbc 连接相关配置,代表使用项目数据源 if (sqlParserVO.isDefaultDataSource()) { String executeSql = buildCheckSql(sqlParserVO); Map<String, DataSource> dataSourceMap = ContextAwareHolder.loadContextAware().getBeansOfType(DataSource.class); // 遍历数据源,多数据源场景下,判断哪个数据源有 liteflow 配置 for (Map.Entry<String, DataSource> entry : dataSourceMap.entrySet()) { String dataSourceName = entry.getKey(); DataSource dataSource = entry.getValue(); if (checkConnectionCanExecuteSql(dataSource.getConnection(), executeSql)) { connection = dataSource.getConnection(); LOG.info("use dataSourceName[{}],has found liteflow config", dataSourceName); } else { LOG.info("check dataSourceName[{}],but not has liteflow config", dataSourceName); } } if (connection == null) { throw new ELSQLException("can not found liteflow config in dataSourceName " + dataSourceMap.keySet()); } } // 如果配置 jdbc 连接相关配置,代表使用指定链接信息 else { connection = DriverManager.getConnection(url, username, password); } } catch (Exception e) { throw new ELSQLException(e.getMessage()); } return connection;
708
412
1,120
<no_super_class>
dromara_liteflow
liteflow/liteflow-rule-plugin/liteflow-rule-zk/src/main/java/com/yomahub/liteflow/parser/zk/ZkXmlELParser.java
ZkXmlELParser
parseCustom
class ZkXmlELParser extends ClassXmlFlowELParser { private final ZkParserHelper zkParserHelper; public ZkXmlELParser() { LiteflowConfig liteflowConfig = LiteflowConfigGetter.get(); try { ZkParserVO zkParserVO = null; if (MapUtil.isNotEmpty((liteflowConfig.getRuleSourceExtDataMap()))) { zkParserVO = BeanUtil.toBean(liteflowConfig.getRuleSourceExtDataMap(), ZkParserVO.class, CopyOptions.create()); } else if (StrUtil.isNotBlank(liteflowConfig.getRuleSourceExtData())) { zkParserVO = JsonUtil.parseObject(liteflowConfig.getRuleSourceExtData(), ZkParserVO.class); } if (Objects.isNull(zkParserVO)) { throw new ZkException("rule-source-ext-data is empty"); } if (StrUtil.isBlank(zkParserVO.getChainPath())) { throw new ZkException("You must configure the chainPath property"); } if (StrUtil.isBlank(zkParserVO.getConnectStr())) { throw new ZkException("zk connect string is empty"); } zkParserHelper = new ZkParserHelper(zkParserVO); } catch (Exception e) { throw new ZkException(e.getMessage()); } } @Override public String parseCustom() {<FILL_FUNCTION_BODY>} }
try { String content = zkParserHelper.getContent(); FlowInitHook.addHook(() -> { zkParserHelper.listenZkNode(); return true; }); return content; } catch (Exception e) { throw new ZkException(e.getMessage()); }
404
90
494
<methods>public non-sealed void <init>() ,public abstract java.lang.String parseCustom() ,public void parseMain(List<java.lang.String>) throws java.lang.Exception<variables>
dromara_liteflow
liteflow/liteflow-script-plugin/liteflow-script-graaljs/src/main/java/com/yomahub/liteflow/script/graaljs/GraalJavaScriptExecutor.java
GraalJavaScriptExecutor
executeScript
class GraalJavaScriptExecutor extends ScriptExecutor { private final Map<String, Source> scriptMap = new CopyOnWriteHashMap<>(); private Engine engine; @Override public ScriptExecutor init() { engine = Engine.create(); return this; } @Override public void load(String nodeId, String script) { try { scriptMap.put(nodeId, Source.create("js", (CharSequence) 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) { scriptMap.remove(nodeId); } @Override public List<String> getNodeIds() { return new ArrayList<>(scriptMap.keySet()); } @Override public Object executeScript(ScriptExecuteWrap wrap) {<FILL_FUNCTION_BODY>} @Override public void cleanCache() { scriptMap.clear(); } @Override public ScriptTypeEnum scriptType() { return ScriptTypeEnum.JS; } @Override public Object compile(String script) throws Exception { String wrapScript = StrUtil.format("function process(){{}} process();", script); Context context = Context.newBuilder().allowAllAccess(true).engine(engine).build(); context.parse(Source.create("js", wrapScript)); return wrapScript; } }
if (!scriptMap.containsKey(wrap.getNodeId())) { String errorMsg = StrUtil.format("script for node[{}] is not loaded", wrap.getNodeId()); throw new ScriptLoadException(errorMsg); } try (Context context = Context.newBuilder().allowAllAccess(true).engine(this.engine).build()) { Value bindings = context.getBindings("js"); bindParam(wrap, bindings::putMember, (s, o) -> { if (!bindings.hasMember(s)) { bindings.putMember(s, o); } }); Value value = context.eval(scriptMap.get(wrap.getNodeId())); if (value.isBoolean()) { return value.asBoolean(); } else if (value.isNumber()) { return value.asInt(); } else if (value.isString()) { return value.asString(); } return value; } catch (Exception e) { throw e; }
389
273
662
<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-script-plugin/liteflow-script-java/src/main/java/com/yomahub/liteflow/script/java/JavaExecutor.java
JavaExecutor
convertScript
class JavaExecutor extends ScriptExecutor { private final Map<String, IScriptEvaluator> compiledScriptMap = new CopyOnWriteHashMap<>(); @Override public void load(String nodeId, String script) { try{ compiledScriptMap.put(nodeId, (IScriptEvaluator) 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); } IScriptEvaluator se = compiledScriptMap.get(wrap.getNodeId()); return se.evaluate(new Object[]{wrap}); } @Override public void cleanCache() { compiledScriptMap.clear(); } @Override public ScriptTypeEnum scriptType() { return ScriptTypeEnum.JAVA; } @Override public Object compile(String script) throws Exception { IScriptEvaluator se = CompilerFactoryFactory.getDefaultCompilerFactory(this.getClass().getClassLoader()).newScriptEvaluator(); se.setTargetVersion(8); se.setReturnType(Object.class); se.setParameters(new String[] {"_meta"}, new Class[] {ScriptExecuteWrap.class}); se.cook(convertScript(script)); return se; } private String convertScript(String script){<FILL_FUNCTION_BODY>} }
//替换掉public,private,protected等修饰词 String script1 = script.replaceAll("public class", "class") .replaceAll("private class", "class") .replaceAll("protected class", "class"); //分析出class的具体名称 String className = ReUtil.getGroup1("class\\s+(\\w+)\\s+implements", script1); if (StrUtil.isBlank(className)){ throw new RuntimeException("cannot find class defined"); } return "import com.yomahub.liteflow.script.body.JaninoCommonScriptBody;\n" + script1 + "\n" + StrUtil.format("{} item = new {}();\n", className, className) + "if (item instanceof JaninoCommonScriptBody){item.body(_meta);return null;}else{return item.body(_meta);}";
514
221
735
<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-script-plugin/liteflow-script-lua/src/main/java/com/yomahub/liteflow/script/lua/LuaScriptExecutor.java
LuaScriptExecutor
convertScript
class LuaScriptExecutor extends JSR223ScriptExecutor { @Override public ScriptTypeEnum scriptType() { return ScriptTypeEnum.LUA; } @Override protected String convertScript(String script) {<FILL_FUNCTION_BODY>} }
String[] lineArray = script.split("\\n"); List<String> noBlankLineList = Arrays.stream(lineArray) .filter(s -> !StrUtil.isBlank(s)) .collect(Collectors.toList()); // 用第一行的缩进的空格数作为整个代码的缩进量 String blankStr = ReUtil.getGroup0("^[ ]*", noBlankLineList.get(0)); // 重新构建脚本 StringBuilder scriptSB = new StringBuilder(); noBlankLineList.forEach(s -> scriptSB.append(StrUtil.format("{}\n", s.replaceFirst(blankStr, StrUtil.EMPTY)))); return scriptSB.toString(); // return StrUtil.format("function // process()\n{}\nend\nprocess()\n",scriptSB.toString());
70
222
292
<methods>public non-sealed void <init>() ,public void cleanCache() ,public java.lang.Object compile(java.lang.String) throws javax.script.ScriptException,public java.lang.Object executeScript(com.yomahub.liteflow.script.ScriptExecuteWrap) throws java.lang.Exception,public List<java.lang.String> getNodeIds() ,public com.yomahub.liteflow.script.ScriptExecutor init() ,public void load(java.lang.String, java.lang.String) ,public void unLoad(java.lang.String) <variables>protected final com.yomahub.liteflow.log.LFLog LOG,private final Map<java.lang.String,javax.script.CompiledScript> compiledScriptMap,private javax.script.ScriptEngine scriptEngine
dromara_liteflow
liteflow/liteflow-script-plugin/liteflow-script-python/src/main/java/com/yomahub/liteflow/script/python/PythonScriptExecutor.java
PythonScriptExecutor
executeScript
class PythonScriptExecutor extends ScriptExecutor { private PythonInterpreter pythonInterpreter; private final String RESULT_KEY = "result"; private final Map<String, PyCode> compiledScriptMap = new HashMap<>(); @Override public ScriptExecutor init(){ PySystemState systemState = new PySystemState(); systemState.setdefaultencoding("UTF-8"); this.pythonInterpreter = new PythonInterpreter(null, systemState); return this; } @Override public void load(String nodeId, String script) { try { PyCode pyCode = (PyCode) compile(script); compiledScriptMap.put(nodeId, pyCode); } 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 {<FILL_FUNCTION_BODY>} @Override public void cleanCache() { compiledScriptMap.clear(); } @Override public ScriptTypeEnum scriptType() { return ScriptTypeEnum.PYTHON; } @Override public Object compile(String script) throws Exception { return pythonInterpreter.compile(convertScript(script)); } private String convertScript(String script) { String[] lineArray = script.split("\\n"); List<String> noBlankLineList = Arrays.stream(lineArray) .filter(s -> !StrUtil.isBlank(s)) .collect(Collectors.toList()); // 用第一行的缩进的空格数作为整个代码的缩进量 String blankStr = ReUtil.getGroup0("^[ ]*", noBlankLineList.get(0)); // 重新构建脚本 StringBuilder scriptSB = new StringBuilder(); noBlankLineList.forEach(s -> scriptSB.append(StrUtil.format("{}\n", s.replaceFirst(blankStr, StrUtil.EMPTY)))); return scriptSB.toString().replace("return", RESULT_KEY + "="); } }
if (!compiledScriptMap.containsKey(wrap.getNodeId())) { String errorMsg = StrUtil.format("script for node[{}] is not loaded", wrap.getNodeId()); throw new ScriptLoadException(errorMsg); } PyCode compiledScript = compiledScriptMap.get(wrap.getNodeId()); bindParam(wrap, pythonInterpreter::set, pythonInterpreter::set); pythonInterpreter.exec(compiledScript); PyObject result = pythonInterpreter.get(RESULT_KEY); if (result == null){ return null; } pythonInterpreter.cleanup(); switch (wrap.getCmp().getType()){ case BOOLEAN_SCRIPT: return result.__tojava__(Boolean.class); case FOR_SCRIPT: return result.__tojava__(Integer.class); default: return result.__tojava__(Object.class); }
635
240
875
<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-script-plugin/liteflow-script-qlexpress/src/main/java/com/yomahub/liteflow/script/qlexpress/QLExpressScriptExecutor.java
QLExpressScriptExecutor
executeScript
class QLExpressScriptExecutor extends ScriptExecutor { private final Logger log = LoggerFactory.getLogger(this.getClass()); private ExpressRunner expressRunner; private final Map<String, InstructionSet> compiledScriptMap = new CopyOnWriteHashMap<>(); @Override public ScriptExecutor init() { expressRunner = new ExpressRunner(true, false); return this; } @Override public void load(String nodeId, String script) { try { compiledScriptMap.put(nodeId, (InstructionSet) 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 {<FILL_FUNCTION_BODY>} @Override public void cleanCache() { compiledScriptMap.clear(); expressRunner.clearExpressCache(); ReflectUtil.setFieldValue(expressRunner, "loader", new ExpressLoader(expressRunner)); } @Override public ScriptTypeEnum scriptType() { return ScriptTypeEnum.QLEXPRESS; } @Override public Object compile(String script) throws Exception { return expressRunner.getInstructionSetFromLocalCache(script); } }
List<String> errorList = new ArrayList<>(); try { if (!compiledScriptMap.containsKey(wrap.getNodeId())) { String errorMsg = StrUtil.format("script for node[{}] is not loaded", wrap.getNodeId()); throw new ScriptLoadException(errorMsg); } InstructionSet instructionSet = compiledScriptMap.get(wrap.getNodeId()); DefaultContext<String, Object> context = new DefaultContext<>(); bindParam(wrap, context::put, context::putIfAbsent); return expressRunner.execute(instructionSet, context, errorList, true, false); } catch (Exception e) { for (String scriptErrorMsg : errorList) { log.error("\n{}", scriptErrorMsg); } throw e; }
414
215
629
<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-solon-plugin/src/main/java/com/yomahub/liteflow/solon/NodeBooleanComponentOfMethod.java
NodeBooleanComponentOfMethod
exec
class NodeBooleanComponentOfMethod extends NodeBooleanComponent { final BeanWrap beanWrap; final Method method; final LiteFlowMethodEnum methodEnum; public NodeBooleanComponentOfMethod(BeanWrap beanWrap, Method method, LiteFlowMethodEnum methodEnum) { this.beanWrap = beanWrap; this.method = method; this.methodEnum = methodEnum; if (method.getParameterCount() > 1) { String methodFullName = beanWrap.clz().getName() + "::" + method.getName(); throw new LiteFlowException("NodeIfComponent method parameter cannot be more than one: " + methodFullName); } if (method.getReturnType() != Boolean.class && method.getReturnType() != boolean.class) { String methodFullName = beanWrap.clz().getName() + "::" + method.getName(); throw new LiteFlowException("NodeIfComponent method returnType can only be boolean: " + methodFullName); } } private Object exec() throws Exception {<FILL_FUNCTION_BODY>} @Override public boolean processBoolean() throws Exception { return (boolean) exec(); } }
if (method.getParameterCount() == 0) { return method.invoke(beanWrap.get()); } else { return method.invoke(beanWrap.get(), this); }
297
53
350
<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-solon-plugin/src/main/java/com/yomahub/liteflow/solon/NodeComponentOfMethod.java
NodeComponentOfMethod
afterProcess
class NodeComponentOfMethod extends NodeComponent { final BeanWrap beanWrap; final Method method; final LiteFlowMethodEnum methodEnum; public NodeComponentOfMethod(BeanWrap beanWrap, Method method, LiteFlowMethodEnum methodEnum) { this.beanWrap = beanWrap; this.method = method; this.methodEnum = methodEnum; if (method.getParameterCount() > 1) { String methodFullName = beanWrap.clz().getName() + "::" + method.getName(); throw new LiteFlowException("NodeComponent method parameter cannot be more than one: " + methodFullName); } if (method.getReturnType() != Void.class && method.getReturnType() != void.class) { String methodFullName = beanWrap.clz().getName() + "::" + method.getName(); throw new LiteFlowException("NodeComponent method returnType can only be void: " + methodFullName); } } private void exec() throws Exception { if (method.getParameterCount() == 0) { method.invoke(beanWrap.get()); } else { method.invoke(beanWrap.get(), this); } } @Override public void process() throws Exception { if (methodEnum != LiteFlowMethodEnum.PROCESS) { return; } exec(); } @Override public void beforeProcess() { if (methodEnum != LiteFlowMethodEnum.BEFORE_PROCESS) { return; } try { exec(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } } @Override public void afterProcess() {<FILL_FUNCTION_BODY>} @Override public void onError(Exception e) throws Exception { if (methodEnum != LiteFlowMethodEnum.ON_ERROR) { return; } exec(); } @Override public void onSuccess() throws Exception { if (methodEnum != LiteFlowMethodEnum.ON_SUCCESS) { return; } exec(); } }
if (methodEnum != LiteFlowMethodEnum.AFTER_PROCESS) { return; } try { exec(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); }
574
86
660
<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-solon-plugin/src/main/java/com/yomahub/liteflow/solon/NodeForComponentOfMethod.java
NodeForComponentOfMethod
exec
class NodeForComponentOfMethod extends NodeForComponent { final BeanWrap beanWrap; final Method method; final LiteFlowMethodEnum methodEnum; public NodeForComponentOfMethod(BeanWrap beanWrap, Method method, LiteFlowMethodEnum methodEnum) { this.beanWrap = beanWrap; this.method = method; this.methodEnum = methodEnum; if (method.getParameterCount() > 1) { String methodFullName = beanWrap.clz().getName() + "::" + method.getName(); throw new LiteFlowException("NodeForComponent method parameter cannot be more than one: " + methodFullName); } if (method.getReturnType() != Integer.class && method.getReturnType() != int.class) { String methodFullName = beanWrap.clz().getName() + "::" + method.getName(); throw new LiteFlowException("NodeForComponent method returnType can only be int: " + methodFullName); } } private Object exec() throws Exception {<FILL_FUNCTION_BODY>} @Override public int processFor() throws Exception { return (int) exec(); } }
if (method.getParameterCount() == 0) { return method.invoke(beanWrap.get()); } else { return method.invoke(beanWrap.get(), this); }
297
53
350
<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-solon-plugin/src/main/java/com/yomahub/liteflow/solon/NodeSwitchComponentOfMethod.java
NodeSwitchComponentOfMethod
exec
class NodeSwitchComponentOfMethod extends NodeSwitchComponent { final BeanWrap beanWrap; final Method method; final LiteFlowMethodEnum methodEnum; public NodeSwitchComponentOfMethod(BeanWrap beanWrap, Method method, LiteFlowMethodEnum methodEnum) { this.beanWrap = beanWrap; this.method = method; this.methodEnum = methodEnum; if (method.getParameterCount() > 1) { String methodFullName = beanWrap.clz().getName() + "::" + method.getName(); throw new LiteFlowException( "NodeSwitchComponent method parameter cannot be more than one: " + methodFullName); } if (method.getReturnType() != String.class) { String methodFullName = beanWrap.clz().getName() + "::" + method.getName(); throw new LiteFlowException("NodeSwitchComponent method returnType can only be string: " + methodFullName); } } private Object exec() throws Exception {<FILL_FUNCTION_BODY>} @Override public String processSwitch() throws Exception { return (String) exec(); } }
if (method.getParameterCount() == 0) { return method.invoke(beanWrap.get()); } else { return method.invoke(beanWrap.get(), this); }
288
53
341
<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-solon-plugin/src/main/java/com/yomahub/liteflow/solon/config/LiteflowAutoConfiguration.java
LiteflowAutoConfiguration
liteflowConfig
class LiteflowAutoConfiguration { @Inject(value = "${liteflow.monitor.enableLog}", required = false) boolean enableLog; @Bean public LiteflowConfig liteflowConfig(LiteflowProperty property, LiteflowMonitorProperty liteflowMonitorProperty) {<FILL_FUNCTION_BODY>} @Bean public MonitorBus monitorBus(LiteflowConfig liteflowConfig) { if (enableLog) { return new MonitorBus(liteflowConfig); } else { return null; // null 即是没创建 } } }
LiteflowConfig liteflowConfig = new LiteflowConfig(); liteflowConfig.setRuleSource(property.getRuleSource()); liteflowConfig.setRuleSourceExtData(property.getRuleSourceExtData()); liteflowConfig.setSlotSize(property.getSlotSize()); liteflowConfig.setThreadExecutorClass(property.getThreadExecutorClass()); liteflowConfig.setWhenMaxWaitSeconds(property.getWhenMaxWaitSeconds()); liteflowConfig.setEnableLog(liteflowMonitorProperty.isEnableLog()); liteflowConfig.setQueueLimit(liteflowMonitorProperty.getQueueLimit()); liteflowConfig.setDelay(liteflowMonitorProperty.getDelay()); liteflowConfig.setPeriod(liteflowMonitorProperty.getPeriod()); liteflowConfig.setWhenMaxWorkers(property.getWhenMaxWorkers()); liteflowConfig.setWhenQueueLimit(property.getWhenQueueLimit()); liteflowConfig.setParseMode(property.getParseMode()); liteflowConfig.setEnable(property.isEnable()); liteflowConfig.setSupportMultipleType(property.isSupportMultipleType()); liteflowConfig.setRetryCount(property.getRetryCount()); liteflowConfig.setPrintBanner(property.isPrintBanner()); liteflowConfig.setNodeExecutorClass(property.getNodeExecutorClass()); liteflowConfig.setRequestIdGeneratorClass(property.getRequestIdGeneratorClass()); liteflowConfig.setMainExecutorWorks(property.getMainExecutorWorks()); liteflowConfig.setMainExecutorClass(property.getMainExecutorClass()); liteflowConfig.setPrintExecutionLog(property.isPrintExecutionLog()); liteflowConfig.setParallelMaxWorkers(property.getParallelMaxWorkers()); liteflowConfig.setParallelQueueLimit(property.getParallelQueueLimit()); liteflowConfig.setParallelLoopExecutorClass(property.getParallelLoopExecutorClass()); liteflowConfig.setFallbackCmpEnable(property.isFallbackCmpEnable()); return liteflowConfig;
152
555
707
<no_super_class>
dromara_liteflow
liteflow/liteflow-solon-plugin/src/main/java/com/yomahub/liteflow/solon/config/LiteflowMainAutoConfiguration.java
LiteflowMainAutoConfiguration
flowExecutor
class LiteflowMainAutoConfiguration { @Inject(value = "${liteflow.parseOnStart}", required = false) boolean parseOnStart; @Inject AppContext appContext; @Inject LiteflowConfig liteflowConfig; @Init public void flowExecutor() {<FILL_FUNCTION_BODY>} }
// // 实例化FlowExecutor // FlowExecutor flowExecutor = new FlowExecutor(); flowExecutor.setLiteflowConfig(liteflowConfig); if (parseOnStart) { flowExecutor.init(true); } appContext.wrapAndPut(FlowExecutor.class, flowExecutor);
94
89
183
<no_super_class>
dromara_liteflow
liteflow/liteflow-solon-plugin/src/main/java/com/yomahub/liteflow/solon/config/LiteflowProperty.java
LiteflowProperty
setRuleSource
class LiteflowProperty { // 是否装配liteflow private boolean enable; // 流程定义资源地址 private String ruleSource; // 流程资源扩展数据 private String ruleSourceExtData; // slot的数量 private int slotSize; // FlowExecutor的execute2Future的线程数 private int mainExecutorWorks; // FlowExecutor的execute2Future的自定义线程池 private String mainExecutorClass; // 并行线程执行器class路径 private String threadExecutorClass; // 异步线程最大等待描述 private int whenMaxWaitSeconds; // 异步线程池最大线程数 private int whenMaxWorkers; // 异步线程池最大队列数量 private int whenQueueLimit; // 解析模式,一共有三种,具体看其定义 private ParseModeEnum parseMode; // 这个属性为true,则支持多种不同的类型的配置 // 但是要注意,不能将主流程和子流程分配在不同类型配置文件中 private boolean supportMultipleType; // 重试次数 private int retryCount; // 是否打印liteflow banner private boolean printBanner; // 节点执行器class全名 private String nodeExecutorClass; // requestId 生成器 private String requestIdGeneratorClass; // 是否打印执行过程中的日志 private boolean printExecutionLog; //并行循环线程池类路径 private String parallelLoopExecutorClass; //使用默认并行循环线程池时,最大线程数 private Integer parallelMaxWorkers; //使用默认并行循环线程池时,最大队列数 private Integer parallelQueueLimit; // 是否启用组件降级 private Boolean fallbackCmpEnable; public boolean isEnable() { return enable; } public void setEnable(boolean enable) { this.enable = enable; } public String getRuleSource() { return ruleSource; } public void setRuleSource(String ruleSource) {<FILL_FUNCTION_BODY>} public int getSlotSize() { return slotSize; } public void setSlotSize(int slotSize) { this.slotSize = slotSize; } public int getWhenMaxWaitSeconds() { return whenMaxWaitSeconds; } public void setWhenMaxWaitSeconds(int whenMaxWaitSeconds) { this.whenMaxWaitSeconds = whenMaxWaitSeconds; } public int getWhenMaxWorkers() { return whenMaxWorkers; } public void setWhenMaxWorkers(int whenMaxWorkers) { this.whenMaxWorkers = whenMaxWorkers; } public int getWhenQueueLimit() { return whenQueueLimit; } public void setWhenQueueLimit(int whenQueueLimit) { this.whenQueueLimit = whenQueueLimit; } public boolean isSupportMultipleType() { return supportMultipleType; } public void setSupportMultipleType(boolean supportMultipleType) { this.supportMultipleType = supportMultipleType; } public int getRetryCount() { return retryCount; } public void setRetryCount(int retryCount) { this.retryCount = retryCount; } public boolean isPrintBanner() { return printBanner; } public void setPrintBanner(boolean printBanner) { this.printBanner = printBanner; } public String getThreadExecutorClass() { return threadExecutorClass; } public void setThreadExecutorClass(String threadExecutorClass) { this.threadExecutorClass = threadExecutorClass; } public String getNodeExecutorClass() { return nodeExecutorClass; } public void setNodeExecutorClass(String nodeExecutorClass) { this.nodeExecutorClass = nodeExecutorClass; } public int getMainExecutorWorks() { return mainExecutorWorks; } public void setMainExecutorWorks(int mainExecutorWorks) { this.mainExecutorWorks = mainExecutorWorks; } public String getMainExecutorClass() { return mainExecutorClass; } public void setMainExecutorClass(String mainExecutorClass) { this.mainExecutorClass = mainExecutorClass; } public boolean isPrintExecutionLog() { return printExecutionLog; } public void setPrintExecutionLog(boolean printExecutionLog) { this.printExecutionLog = printExecutionLog; } public String getRequestIdGeneratorClass() { return requestIdGeneratorClass; } public void setRequestIdGeneratorClass(String requestIdGeneratorClass) { this.requestIdGeneratorClass = requestIdGeneratorClass; } public String getRuleSourceExtData() { return ruleSourceExtData; } public void setRuleSourceExtData(String ruleSourceExtData) { this.ruleSourceExtData = ruleSourceExtData; } public String getParallelLoopExecutorClass() { return parallelLoopExecutorClass; } public void setParallelLoopExecutorClass(String parallelLoopExecutorClass) { this.parallelLoopExecutorClass = parallelLoopExecutorClass; } public Integer getParallelMaxWorkers() { return parallelMaxWorkers; } public void setParallelMaxWorkers(Integer parallelMaxWorkers) { this.parallelMaxWorkers = parallelMaxWorkers; } public Integer getParallelQueueLimit() { return parallelQueueLimit; } public void setParallelQueueLimit(Integer parallelQueueLimit) { this.parallelQueueLimit = parallelQueueLimit; } public Boolean isFallbackCmpEnable() { return fallbackCmpEnable; } public void setFallbackCmpEnable(Boolean fallbackCmpEnable) { this.fallbackCmpEnable = fallbackCmpEnable; } public ParseModeEnum getParseMode() { return parseMode; } public void setParseMode(ParseModeEnum parseMode) { this.parseMode = parseMode; } }
if (ruleSource.contains("*")) { this.ruleSource = String.join(",", PathsUtils.resolvePaths(ruleSource)); } else { this.ruleSource = ruleSource; }
1,508
59
1,567
<no_super_class>
dromara_liteflow
liteflow/liteflow-solon-plugin/src/main/java/com/yomahub/liteflow/solon/config/PathsUtils.java
PathsUtils
resolvePaths
class PathsUtils { public static Collection<String> resolvePaths(String pathExpr) {<FILL_FUNCTION_BODY>} }
List<String> paths = new ArrayList<>(); if(!FileUtil.isAbsolutePath(pathExpr)) { if (pathExpr.contains("/*") == false) { // 说明没有*符 paths.add(pathExpr); return paths; } // 确定目录 int dirIdx = pathExpr.indexOf("/*"); String dir = pathExpr.substring(0, dirIdx); // 确定后缀 int sufIdx = pathExpr.lastIndexOf("."); String suf = null; if (sufIdx > 0) { suf = pathExpr.substring(sufIdx); if (suf.contains("*")) { sufIdx = -1; suf = null; } } int sufIdx2 = sufIdx; String suf2 = suf; // 匹配表达式 String expr = pathExpr.replaceAll("/\\*\\.", "/[^\\.]*\\."); expr = expr.replaceAll("/\\*\\*/", "(/[^/]*)*/"); Pattern pattern = Pattern.compile(expr); List<String> finalPaths = paths; ScanUtil.scan(dir, n -> { // 进行后缀过滤,相对比较快 if (sufIdx2 > 0) { return n.endsWith(suf2); } else { return true; } }).forEach(uri -> { // 再进行表达式过滤 if (pattern.matcher(uri).find()) { finalPaths.add(uri); } }); } else { String[] pathExprs = pathExpr.split(","); paths = PathMatchUtil.searchAbsolutePath(Arrays.asList(pathExprs)); } return paths;
38
488
526
<no_super_class>
dromara_liteflow
liteflow/liteflow-solon-plugin/src/main/java/com/yomahub/liteflow/solon/integration/XPluginImpl.java
XPluginImpl
start
class XPluginImpl implements Plugin { @Override public void start(AppContext context) {<FILL_FUNCTION_BODY>} }
// 加载默认配置 Properties defProps = Utils.loadProperties("META-INF/liteflow-default.properties"); if (defProps != null && defProps.size() > 0) { defProps.forEach((k, v) -> { context.cfg().putIfAbsent(k, v); }); } // 是否启用 boolean enable = context.cfg().getBool("liteflow.enable", false); if (!enable) { return; } // 放到前面 context.beanMake(LiteflowProperty.class); context.beanMake(LiteflowMonitorProperty.class); context.beanMake(LiteflowAutoConfiguration.class); context.beanMake(LiteflowMainAutoConfiguration.class); // 订阅 NodeComponent 组件 context.subWrapsOfType(NodeComponent.class, bw -> { NodeComponent node1 = bw.raw(); node1.setNodeId(bw.name()); FlowBus.addManagedNode(bw.name(), bw.raw()); }); context.beanExtractorAdd(LiteflowMethod.class, (bw, method, anno) -> { NodeComponent node1 = null; switch (anno.value()) { case PROCESS_SWITCH: node1 = new NodeSwitchComponentOfMethod(bw, method, anno.value()); break; case PROCESS_BOOLEAN: node1 = new NodeBooleanComponentOfMethod(bw, method, anno.value()); break; case PROCESS_FOR: node1 = new NodeForComponentOfMethod(bw, method, anno.value()); break; default: node1 = new NodeComponentOfMethod(bw, method, anno.value()); } String nodeId = Utils.annoAlias(anno.nodeId(), bw.name()); node1.setNodeId(nodeId); node1.setType(anno.nodeType()); FlowBus.addManagedNode(nodeId, node1); }); context.beanBuilderAdd(LiteflowComponent.class, (clz, bw, anno) -> { if (NodeComponent.class.isAssignableFrom(clz)) { NodeComponent node1 = bw.raw(); String nodeId = Utils.annoAlias(anno.id(), anno.value()); node1.setNodeId(nodeId); node1.setName(anno.name()); FlowBus.addManagedNode(nodeId, node1); } else { context.beanExtractOrProxy(bw); // 尝试提取 LiteflowMethod 函数,并支持自动代理 } });
38
740
778
<no_super_class>
dromara_liteflow
liteflow/liteflow-solon-plugin/src/main/java/com/yomahub/liteflow/spi/solon/SolonContextAware.java
SolonContextAware
getBean
class SolonContextAware implements ContextAware { @Override public <T> T getBean(String name) { try { return Solon.context().getBean(name); } catch (Exception e) { return null; } } @Override public <T> T getBean(Class<T> clazz) { try { return Solon.context().getBean(clazz); } catch (Exception e) { return null; } } private <T> T getBean(String beanName, Class<T> clazz) {<FILL_FUNCTION_BODY>} @Override public <T> T registerBean(String beanName, Class<T> c) { BeanWrap beanWrap = new BeanWrap(Solon.context(), c, null, beanName); Solon.context().putWrap(beanName, beanWrap); return beanWrap.get(); } @Override public <T> T registerBean(Class<T> c) { return registerBean(c.getName(), c); } @Override public <T> T registerBean(String beanName, Object bean) { BeanWrap beanWrap = new BeanWrap(Solon.context(), bean.getClass(), bean, beanName); Solon.context().putWrap(beanName, beanWrap); return beanWrap.get(); } @Override public Object registerDeclWrapBean(String beanName, DeclWarpBean declWarpBean) { BeanWrap beanWrap = new BeanWrap(Solon.context(), declWarpBean.getClass(), declWarpBean, beanName); Solon.context().putWrap(beanName, beanWrap); return beanWrap.get(); } @Override public <T> T registerOrGet(String beanName, Class<T> clazz) { T t = getBean(beanName, clazz); if (ObjectUtil.isNull(t)) { t = registerBean(beanName, clazz); } return t; } @Override public <T> Map<String, T> getBeansOfType(Class<T> type) { List<BeanWrap> wrapsOfType = Solon.context().getWrapsOfType(type); return CollUtil.toMap(wrapsOfType, new HashMap<String, T>(), BeanWrap::name, BeanWrap::get); } @Override public boolean hasBean(String beanName) { return Solon.context().hasWrap(beanName); } @Override public int priority() { return 1; } }
try { return Solon.context().getBean(beanName); } catch (Exception e) { return null; }
678
38
716
<no_super_class>
dromara_liteflow
liteflow/liteflow-solon-plugin/src/main/java/com/yomahub/liteflow/spi/solon/SolonDeclComponentParser.java
SolonDeclComponentParser
parseDeclBean
class SolonDeclComponentParser implements DeclComponentParser { @Override public List<DeclWarpBean> parseDeclBean(Class<?> clazz) {<FILL_FUNCTION_BODY>} @Override public List<DeclWarpBean> parseDeclBean(Class<?> clazz, String nodeId, String nodeName) { throw new NotSupportDeclException("the declaration component is not supported in solon environment."); } @Override public int priority() { return 1; } }
throw new NotSupportDeclException("the declaration component is not supported in solon environment.");
131
23
154
<no_super_class>
dromara_liteflow
liteflow/liteflow-solon-plugin/src/main/java/com/yomahub/liteflow/spi/solon/SolonLiteflowComponentSupport.java
SolonLiteflowComponentSupport
getCmpName
class SolonLiteflowComponentSupport implements LiteflowComponentSupport { @Override public String getCmpName(Object nodeComponent) {<FILL_FUNCTION_BODY>} @Override public int priority() { return 1; } }
// 判断NodeComponent是否是标识了@LiteflowComponent的标注 // 如果标注了,那么要从中取到name字段 LiteflowComponent liteflowComponent = nodeComponent.getClass().getAnnotation(LiteflowComponent.class); if (ObjectUtil.isNotNull(liteflowComponent)) { return liteflowComponent.name(); } else { return null; }
66
110
176
<no_super_class>
dromara_liteflow
liteflow/liteflow-solon-plugin/src/main/java/com/yomahub/liteflow/spi/solon/SolonPathContentParser.java
SolonPathContentParser
parseContent
class SolonPathContentParser implements PathContentParser { @Override public List<String> parseContent(List<String> pathList) throws Exception {<FILL_FUNCTION_BODY>} @Override public List<String> getFileAbsolutePath(List<String> pathList) throws Exception { List<URL> allResource = getUrls(pathList); return StreamUtil.of(allResource).map(URL::getPath).filter(FileUtil::isFile).collect(Collectors.toList()); } private static List<URL> getUrls(List<String> pathList) throws MalformedURLException { if (CollectionUtil.isEmpty(pathList)) { throw new ConfigErrorException("rule source must not be null"); } List<URL> allResource = new ArrayList<>(); for (String path : pathList) { // 如果 path 是绝对路径且这个文件存在时,我们认为这是一个本地文件路径,而并非classpath路径 if (FileUtil.isAbsolutePath(path) && FileUtil.isFile(path)) { allResource.add(new File(path).toURI().toURL()); } else { if (path.startsWith(ResourceUtils.CLASSPATH_URL_PREFIX)) { path = path.substring(ResourceUtils.CLASSPATH_URL_PREFIX.length()); } if (Utils.getResource(path) != null) { allResource.add(Utils.getResource(path)); } } } // 如果有多个资源,检查资源都是同一个类型,如果出现不同类型的配置,则抛出错误提示 Set<String> fileTypeSet = new HashSet<>(); allResource.forEach(resource -> fileTypeSet.add(FileUtil.extName(resource.getPath()))); if (fileTypeSet.size() > 1) { throw new ConfigErrorException("config error,please use the same type of configuration"); } return allResource; } @Override public int priority() { return 1; } }
List<URL> allResource = getUrls(pathList); // 转换成内容List List<String> contentList = new ArrayList<>(); for (URL resource : allResource) { String content = IoUtil.read(resource.openStream(), CharsetUtil.CHARSET_UTF_8); if (StrUtil.isNotBlank(content)) { contentList.add(content); } } return contentList;
521
119
640
<no_super_class>
dromara_liteflow
liteflow/liteflow-spring-boot-starter/src/main/java/com/yomahub/liteflow/springboot/config/LiteflowPropertyAutoConfiguration.java
LiteflowPropertyAutoConfiguration
liteflowConfig
class LiteflowPropertyAutoConfiguration { @Bean public LiteflowConfig liteflowConfig(LiteflowProperty property, LiteflowMonitorProperty liteflowMonitorProperty) {<FILL_FUNCTION_BODY>} }
LiteflowConfig liteflowConfig = new LiteflowConfig(); liteflowConfig.setRuleSource(property.getRuleSource()); liteflowConfig.setRuleSourceExtData(property.getRuleSourceExtData()); liteflowConfig.setRuleSourceExtDataMap(property.getRuleSourceExtDataMap()); liteflowConfig.setSlotSize(property.getSlotSize()); liteflowConfig.setThreadExecutorClass(property.getThreadExecutorClass()); liteflowConfig.setWhenMaxWaitSeconds(property.getWhenMaxWaitSeconds()); liteflowConfig.setWhenMaxWaitTime(property.getWhenMaxWaitTime()); liteflowConfig.setWhenMaxWaitTimeUnit(property.getWhenMaxWaitTimeUnit()); liteflowConfig.setWhenMaxWorkers(property.getWhenMaxWorkers()); liteflowConfig.setWhenQueueLimit(property.getWhenQueueLimit()); liteflowConfig.setWhenThreadPoolIsolate(property.isWhenThreadPoolIsolate()); liteflowConfig.setParseMode(property.getParseMode()); liteflowConfig.setEnable(property.isEnable()); liteflowConfig.setSupportMultipleType(property.isSupportMultipleType()); liteflowConfig.setRetryCount(property.getRetryCount()); liteflowConfig.setPrintBanner(property.isPrintBanner()); liteflowConfig.setNodeExecutorClass(property.getNodeExecutorClass()); liteflowConfig.setRequestIdGeneratorClass(property.getRequestIdGeneratorClass()); liteflowConfig.setMainExecutorWorks(property.getMainExecutorWorks()); liteflowConfig.setMainExecutorClass(property.getMainExecutorClass()); liteflowConfig.setPrintExecutionLog(property.isPrintExecutionLog()); liteflowConfig.setEnableMonitorFile(property.isEnableMonitorFile()); liteflowConfig.setParallelMaxWorkers(property.getParallelMaxWorkers()); liteflowConfig.setParallelQueueLimit(property.getParallelQueueLimit()); liteflowConfig.setParallelLoopExecutorClass(property.getParallelLoopExecutorClass()); liteflowConfig.setFallbackCmpEnable(property.isFallbackCmpEnable()); liteflowConfig.setFastLoad(property.isFastLoad()); liteflowConfig.setEnableLog(liteflowMonitorProperty.isEnableLog()); liteflowConfig.setQueueLimit(liteflowMonitorProperty.getQueueLimit()); liteflowConfig.setDelay(liteflowMonitorProperty.getDelay()); liteflowConfig.setPeriod(liteflowMonitorProperty.getPeriod()); return liteflowConfig;
57
687
744
<no_super_class>
dromara_liteflow
liteflow/liteflow-spring/src/main/java/com/yomahub/liteflow/spi/spring/SpringAware.java
SpringAware
registerBean
class SpringAware implements ApplicationContextAware, ContextAware { private static ApplicationContext applicationContext = null; public SpringAware() { } @Override public void setApplicationContext(ApplicationContext ac) throws BeansException { applicationContext = ac; } public static ApplicationContext getApplicationContext() { return applicationContext; } @Override public <T> T getBean(String name) { T t = (T) applicationContext.getBean(name); return t; } @Override public <T> Map<String, T> getBeansOfType(Class<T> type) { return applicationContext.getBeansOfType(type); } @Override public <T> T getBean(Class<T> clazz) { T t = applicationContext.getBean(clazz); return t; } private <T> T getBean(String beanName, Class<T> clazz) { T t = applicationContext.getBean(beanName, clazz); return t; } @Override public <T> T registerBean(String beanName, Class<T> c) {<FILL_FUNCTION_BODY>} @Override public Object registerDeclWrapBean(String beanName, DeclWarpBean declWarpBean){ DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) applicationContext .getAutowireCapableBeanFactory(); beanFactory.setAllowBeanDefinitionOverriding(true); GenericBeanDefinition beanDefinition = new GenericBeanDefinition(); beanDefinition.setBeanClass(DeclWarpBean.class); beanDefinition.setScope(ConfigurableBeanFactory.SCOPE_SINGLETON); MutablePropertyValues mutablePropertyValues = new MutablePropertyValues(); mutablePropertyValues.add("nodeId", declWarpBean.getNodeId()); mutablePropertyValues.add("nodeName", declWarpBean.getNodeName()); mutablePropertyValues.add("nodeType", declWarpBean.getNodeType()); mutablePropertyValues.add("rawClazz", declWarpBean.getRawClazz()); mutablePropertyValues.add("methodWrapBeanList", declWarpBean.getMethodWrapBeanList()); mutablePropertyValues.add("rawBean", declWarpBean.getRawBean()); beanDefinition.setPropertyValues(mutablePropertyValues); beanFactory.registerBeanDefinition(beanName, beanDefinition); return getBean(beanName); } @Override public <T> T registerBean(Class<T> c) { return registerBean(c.getName(), c); } @Override public <T> T registerBean(String beanName, Object bean) { ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) applicationContext; DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) configurableApplicationContext .getAutowireCapableBeanFactory(); defaultListableBeanFactory.registerSingleton(beanName, bean); return (T) configurableApplicationContext.getBean(beanName); } @Override public <T> T registerOrGet(String beanName, Class<T> clazz) { if (ObjectUtil.isNull(applicationContext)) { return null; } try { return getBean(beanName, clazz); } catch (Exception e) { return registerBean(beanName, clazz); } } @Override public boolean hasBean(String beanName) { return applicationContext.containsBean(beanName); } @Override public int priority() { return 1; } }
DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) applicationContext .getAutowireCapableBeanFactory(); BeanDefinition beanDefinition = new GenericBeanDefinition(); beanDefinition.setBeanClassName(c.getName()); beanFactory.setAllowBeanDefinitionOverriding(true); beanFactory.registerBeanDefinition(beanName, beanDefinition); return getBean(beanName);
932
101
1,033
<no_super_class>
dromara_liteflow
liteflow/liteflow-spring/src/main/java/com/yomahub/liteflow/spi/spring/SpringDeclComponentParser.java
SpringDeclComponentParser
parseDeclBean
class SpringDeclComponentParser implements DeclComponentParser { @Override public List<DeclWarpBean> parseDeclBean(Class<?> clazz) { return parseDeclBean(clazz, null, null); } @Override public List<DeclWarpBean> parseDeclBean(Class<?> clazz, final String nodeId, final String nodeName) {<FILL_FUNCTION_BODY>} @Override public int priority() { return 1; } public static class DeclInfo{ private String nodeId; private String nodeName; private NodeTypeEnum nodeType; private Class<?> rawClazz; private MethodWrapBean methodWrapBean; public DeclInfo(String nodeId, String nodeName, NodeTypeEnum nodeType, Class<?> rawClazz, MethodWrapBean methodWrapBean) { this.nodeId = nodeId; this.nodeName = nodeName; this.nodeType = nodeType; this.rawClazz = rawClazz; this.methodWrapBean = methodWrapBean; } public String getNodeId() { return nodeId; } public void setNodeId(String nodeId) { this.nodeId = nodeId; } public Class<?> getRawClazz() { return rawClazz; } public void setRawClazz(Class<?> rawClazz) { this.rawClazz = rawClazz; } public String getNodeName() { return nodeName; } public void setNodeName(String nodeName) { this.nodeName = nodeName; } public MethodWrapBean getMethodWrapBean() { return methodWrapBean; } public void setMethodWrapBean(MethodWrapBean methodWrapBean) { this.methodWrapBean = methodWrapBean; } public NodeTypeEnum getNodeType() { return nodeType; } public void setNodeType(NodeTypeEnum nodeType) { this.nodeType = nodeType; } } }
Map<String, List<DeclInfo>> definitionMap = Arrays.stream(clazz.getMethods()).filter( method -> AnnotationUtil.getAnnotation(method, LiteflowMethod.class) != null ).map(method -> { LiteflowMethod liteflowMethod = AnnotationUtil.getAnnotation(method, LiteflowMethod.class); LiteflowRetry liteflowRetry = AnnotationUtil.getAnnotation(method, LiteflowRetry.class); String currNodeId = null; String currNodeName = null; if (nodeId == null){ if (StrUtil.isBlank(liteflowMethod.nodeId())){ LiteflowComponent liteflowComponent = AnnoUtil.getAnnotation(clazz, LiteflowComponent.class); Component component = AnnoUtil.getAnnotation(clazz, Component.class); if(liteflowComponent != null){ currNodeId = liteflowComponent.value(); currNodeName = liteflowComponent.name(); }else if(component != null){ currNodeId = component.value(); }else{ currNodeName = StrUtil.EMPTY; currNodeId = StrUtil.EMPTY; } }else{ currNodeId = liteflowMethod.nodeId(); currNodeName = liteflowMethod.nodeName(); } }else{ currNodeId = nodeId; currNodeName = nodeName; } NodeTypeEnum nodeType; LiteflowCmpDefine liteflowCmpDefine = AnnotationUtil.getAnnotation(method.getDeclaringClass(), LiteflowCmpDefine.class); if (liteflowCmpDefine != null){ nodeType = liteflowCmpDefine.value(); }else{ nodeType = liteflowMethod.nodeType(); } return new DeclInfo(currNodeId, currNodeName, nodeType, method.getDeclaringClass(), new MethodWrapBean(method, liteflowMethod, liteflowRetry)); }).filter(declInfo -> StrUtil.isNotBlank(declInfo.getNodeId())).collect(Collectors.groupingBy(DeclInfo::getNodeId)); return definitionMap.entrySet().stream().map(entry -> { String key = entry.getKey(); List<DeclInfo> declInfos = entry.getValue(); DeclWarpBean declWarpBean = new DeclWarpBean(); declWarpBean.setNodeId(key); DeclInfo processMethodDeclInfo = declInfos.stream().filter(declInfo -> declInfo.getMethodWrapBean().getLiteflowMethod().value().isMainMethod()).findFirst().orElse(null); if (processMethodDeclInfo == null){ throw new CmpDefinitionException(StrUtil.format("Component [{}] does not define the process method", key)); } declWarpBean.setNodeName(processMethodDeclInfo.getNodeName()); declWarpBean.setRawClazz(processMethodDeclInfo.getRawClazz()); declWarpBean.setNodeType(processMethodDeclInfo.getNodeType()); RootBeanDefinition rawClassDefinition = new RootBeanDefinition(clazz); rawClassDefinition.setScope(ConfigurableBeanFactory.SCOPE_SINGLETON); declWarpBean.setRawBean(rawClassDefinition); declWarpBean.setMethodWrapBeanList(declInfos.stream().map(DeclInfo::getMethodWrapBean).collect(Collectors.toList())); return declWarpBean; }).collect(Collectors.toList());
536
914
1,450
<no_super_class>
dromara_liteflow
liteflow/liteflow-spring/src/main/java/com/yomahub/liteflow/spi/spring/SpringLiteflowComponentSupport.java
SpringLiteflowComponentSupport
getCmpName
class SpringLiteflowComponentSupport implements LiteflowComponentSupport { @Override public String getCmpName(Object nodeComponent) {<FILL_FUNCTION_BODY>} @Override public int priority() { return 1; } }
// 判断NodeComponent是否是标识了@LiteflowComponent的标注 // 如果标注了,那么要从中取到name字段 LiteflowComponent liteflowComponent = nodeComponent.getClass().getAnnotation(LiteflowComponent.class); if (ObjectUtil.isNotNull(liteflowComponent)) { return liteflowComponent.name(); } else { return null; }
65
110
175
<no_super_class>
dromara_liteflow
liteflow/liteflow-spring/src/main/java/com/yomahub/liteflow/spi/spring/SpringPathContentParser.java
SpringPathContentParser
parseContent
class SpringPathContentParser implements PathContentParser { @Override public List<String> parseContent(List<String> pathList) throws Exception {<FILL_FUNCTION_BODY>} @Override public List<String> getFileAbsolutePath(List<String> pathList) throws Exception { List<String> absolutePathList = PathMatchUtil.searchAbsolutePath(pathList); List<Resource> allResource = getResources(absolutePathList); return StreamUtil.of(allResource) // 过滤非 file 类型 Resource .filter(Resource::isFile) .map(r -> { try { return r.getFile().getAbsolutePath(); } catch (IOException e) { throw new RuntimeException(e); } }) .collect(Collectors.toList()); } private List<Resource> getResources(List<String> pathList) throws IOException { if (CollectionUtil.isEmpty(pathList)) { throw new ConfigErrorException("rule source must not be null"); } List<Resource> allResource = new ArrayList<>(); for (String path : pathList) { String locationPattern; // 如果path是绝对路径且这个文件存在时,我们认为这是一个本地文件路径,而并非classpath路径 if (FileUtil.isAbsolutePath(path) && FileUtil.isFile(path)) { locationPattern = ResourceUtils.FILE_URL_PREFIX + path; } else { if (!path.startsWith(ResourceUtils.CLASSPATH_URL_PREFIX) && !path.startsWith(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX)) { locationPattern = ResourceUtils.CLASSPATH_URL_PREFIX + path; } else { locationPattern = path; } } PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); Resource[] resources = resolver.getResources(locationPattern); if (ArrayUtil.isNotEmpty(resources)) { allResource.addAll(ListUtil.toList(resources)); } } return allResource; } private void verifyFileExtName(List<Resource> allResource) { // 检查资源都是同一个类型,如果出现不同类型的配置,则抛出错误提示 Set<String> fileTypeSet = new HashSet<>(); allResource.forEach(resource -> fileTypeSet.add(FileUtil.extName(resource.getFilename()))); if (fileTypeSet.size() > 1) { throw new ConfigErrorException("config error,please use the same type of configuration"); } } @Override public int priority() { return 1; } }
List<String> absolutePathList = PathMatchUtil.searchAbsolutePath(pathList); List<Resource> allResource = getResources(absolutePathList); verifyFileExtName(allResource); // 转换成内容List List<String> contentList = new ArrayList<>(); for (Resource resource : allResource) { String content = IoUtil.read(resource.getInputStream(), CharsetUtil.CHARSET_UTF_8); if (StrUtil.isNotBlank(content)) { contentList.add(content); } } return contentList;
695
155
850
<no_super_class>
dromara_liteflow
liteflow/liteflow-spring/src/main/java/com/yomahub/liteflow/spring/ComponentScanner.java
ComponentScanner
postProcessAfterInitialization
class ComponentScanner implements BeanPostProcessor { /** * @RefreshScope 注解 bean 的前缀 */ private static final String REFRESH_SCOPE_ANN_BEAN_PREFIX = "scopedTarget."; /** * @RefreshScope 注解完整类路径 */ private static final String REFRESH_SCOPE_ANN_CLASS_PATH = "org.springframework.cloud.context.config.annotation.RefreshScope"; private static final Logger LOG = LoggerFactory.getLogger(ComponentScanner.class); public static Set<String> nodeComponentSet = new HashSet<>(); private LiteflowConfig liteflowConfig; public static ICmpAroundAspect cmpAroundAspect; public ComponentScanner() { LOGOPrinter.print(); } public ComponentScanner(LiteflowConfig liteflowConfig) { this.liteflowConfig = liteflowConfig; if (liteflowConfig.getPrintBanner()) { // 打印liteflow的LOGO LOGOPrinter.print(); } } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } @SuppressWarnings("rawtypes") @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {<FILL_FUNCTION_BODY>} /** * 用于清除 spring 上下文扫描到的组件实体 */ public static void cleanCache() { nodeComponentSet.clear(); } /** * 获取真实的 beanName 1. @RefreshScope 注解标注的bean 名称前会多加一个 scopedTarget. * * @param clazz clazz * @param beanName beanName */ private String getRealBeanName(Class<?> clazz, String beanName) { if (beanName.startsWith(REFRESH_SCOPE_ANN_BEAN_PREFIX)) { Annotation[] annotations = AnnotationUtil.getAnnotations(clazz, true); for (Annotation annotation : annotations) { String name = annotation.annotationType().getName(); if (REFRESH_SCOPE_ANN_CLASS_PATH.equals(name)) { return beanName.replace(REFRESH_SCOPE_ANN_BEAN_PREFIX, ""); } } } return beanName; } }
Class clazz = LiteFlowProxyUtil.getUserClass(bean.getClass()); //声明式组件 if (bean instanceof DeclWarpBean){ NodeComponent nodeComponent = LiteFlowProxyUtil.proxy2NodeComponent((DeclWarpBean) bean); String nodeId = StrUtil.isEmpty(nodeComponent.getNodeId()) ? getRealBeanName(clazz, beanName) : nodeComponent.getNodeId(); nodeComponentSet.add(nodeId); LOG.info("proxy component[{}] has been found", beanName); return nodeComponent; } // 组件的扫描发现,扫到之后缓存到类属性map中 if (NodeComponent.class.isAssignableFrom(clazz)) { LOG.info("component[{}] has been found", beanName); NodeComponent nodeComponent = (NodeComponent) bean; nodeComponentSet.add(getRealBeanName(clazz, beanName)); return nodeComponent; } // 组件Aop的实现类加载 if (ICmpAroundAspect.class.isAssignableFrom(clazz)) { LOG.info("component aspect implement[{}] has been found", beanName); cmpAroundAspect = (ICmpAroundAspect) bean; return cmpAroundAspect; } // 扫描@ScriptBean修饰的类 ScriptBean scriptBean = AnnoUtil.getAnnotation(clazz, ScriptBean.class); if (ObjectUtil.isNotNull(scriptBean)) { ScriptBeanProxy proxy = new ScriptBeanProxy(bean, clazz, scriptBean); ScriptBeanManager.addScriptBean(scriptBean.value(), proxy.getProxyScriptBean()); return bean; } // 扫描@ScriptMethod修饰的类 List<Method> scriptMethods = Arrays.stream(clazz.getMethods()).filter(method -> { ScriptMethod scriptMethod = AnnoUtil.getAnnotation(method, ScriptMethod.class); return ObjectUtil.isNotNull(scriptMethod) && StrUtil.isNotEmpty(scriptMethod.value()); }).collect(Collectors.toList()); if (CollUtil.isNotEmpty(scriptMethods)) { Map<String, List<Method>> scriptMethodsGroupByValue = CollStreamUtil.groupBy(scriptMethods, method -> { ScriptMethod scriptMethod = AnnoUtil.getAnnotation(method, ScriptMethod.class); return scriptMethod.value(); }, Collectors.toList()); for (Map.Entry<String, List<Method>> entry : scriptMethodsGroupByValue.entrySet()) { String key = entry.getKey(); List<Method> methods = entry.getValue(); ScriptMethodProxy proxy = new ScriptMethodProxy(bean, clazz, methods); ScriptBeanManager.addScriptBean(key, proxy.getProxyScriptMethod()); } return bean; } return bean;
630
738
1,368
<no_super_class>
dromara_liteflow
liteflow/liteflow-spring/src/main/java/com/yomahub/liteflow/spring/DeclBeanDefinition.java
DeclBeanDefinition
postProcessBeanDefinitionRegistry
class DeclBeanDefinition implements BeanDefinitionRegistryPostProcessor { private final LFLog LOG = LFLoggerManager.getLogger(this.getClass()); @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {<FILL_FUNCTION_BODY>} @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { } private Class<?> getRawClassFromBeanDefinition(BeanDefinition beanDefinition){ try{ Method method = ReflectUtil.getMethodByName(DeclBeanDefinition.class, "getResolvableType"); if (method != null){ Object resolvableType = ReflectUtil.invoke(beanDefinition, method); return ReflectUtil.invoke(resolvableType, "getRawClass"); }else{ return ReflectUtil.invoke(beanDefinition, "getTargetType"); } }catch (Exception e){ LOG.error("An error occurred while obtaining the rowClass.",e); return null; } } }
DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) registry; String[] beanDefinitionNames = defaultListableBeanFactory.getBeanDefinitionNames(); Arrays.stream(beanDefinitionNames).filter(beanName -> { BeanDefinition beanDefinition = defaultListableBeanFactory.getMergedBeanDefinition(beanName); Class<?> rawClass = getRawClassFromBeanDefinition(beanDefinition); if (rawClass == null){ return false; }else{ return Arrays.stream(rawClass.getMethods()).anyMatch(method -> AnnotationUtil.getAnnotation(method, LiteflowMethod.class) != null); } }).forEach(beanName -> { BeanDefinition beanDefinition = defaultListableBeanFactory.getMergedBeanDefinition(beanName); Class<?> rawClass = getRawClassFromBeanDefinition(beanDefinition); List<DeclWarpBean> declWarpBeanList = DeclComponentParserHolder.loadDeclComponentParser().parseDeclBean(rawClass); declWarpBeanList.forEach(declWarpBean -> { GenericBeanDefinition newBeanDefinition = new GenericBeanDefinition(); newBeanDefinition.setBeanClass(DeclWarpBean.class); newBeanDefinition.setScope(ConfigurableBeanFactory.SCOPE_SINGLETON); MutablePropertyValues mutablePropertyValues = new MutablePropertyValues(); mutablePropertyValues.add("nodeId", declWarpBean.getNodeId()); mutablePropertyValues.add("nodeName", declWarpBean.getNodeName()); mutablePropertyValues.add("nodeType", declWarpBean.getNodeType()); mutablePropertyValues.add("rawClazz", declWarpBean.getRawClazz()); mutablePropertyValues.add("methodWrapBeanList", declWarpBean.getMethodWrapBeanList()); mutablePropertyValues.add("rawBean", beanDefinition); newBeanDefinition.setPropertyValues(mutablePropertyValues); defaultListableBeanFactory.setAllowBeanDefinitionOverriding(true); defaultListableBeanFactory.registerBeanDefinition(declWarpBean.getNodeId(), newBeanDefinition); }); });
262
535
797
<no_super_class>
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/config/SwaggerConfig.java
SwaggerConfig
swaggerProperties
class SwaggerConfig extends BaseSwaggerConfig { @Override public SwaggerProperties swaggerProperties() {<FILL_FUNCTION_BODY>} @Bean public BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() { return generateBeanPostProcessor(); } }
return SwaggerProperties.builder() .apiBasePackage("com.macro.mall.controller") .title("mall后台系统") .description("mall后台相关接口文档") .contactName("macro") .version("1.0") .enableSecurity(true) .build();
74
86
160
<methods>public non-sealed void <init>() ,public Docket createRestApi() ,public BeanPostProcessor generateBeanPostProcessor() ,public abstract com.macro.mall.common.domain.SwaggerProperties swaggerProperties() <variables>
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/controller/MinioController.java
MinioController
upload
class MinioController { private static final Logger LOGGER = LoggerFactory.getLogger(MinioController.class); @Value("${minio.endpoint}") private String ENDPOINT; @Value("${minio.bucketName}") private String BUCKET_NAME; @Value("${minio.accessKey}") private String ACCESS_KEY; @Value("${minio.secretKey}") private String SECRET_KEY; @ApiOperation("文件上传") @RequestMapping(value = "/upload", method = RequestMethod.POST) @ResponseBody public CommonResult upload(@RequestPart("file") MultipartFile file) {<FILL_FUNCTION_BODY>} private BucketPolicyConfigDto createBucketPolicyConfigDto(String bucketName) { BucketPolicyConfigDto.Statement statement = BucketPolicyConfigDto.Statement.builder() .Effect("Allow") .Principal("*") .Action("s3:GetObject") .Resource("arn:aws:s3:::"+bucketName+"/*.**").build(); return BucketPolicyConfigDto.builder() .Version("2012-10-17") .Statement(CollUtil.toList(statement)) .build(); } @ApiOperation("文件删除") @RequestMapping(value = "/delete", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@RequestParam("objectName") String objectName) { try { MinioClient minioClient = MinioClient.builder() .endpoint(ENDPOINT) .credentials(ACCESS_KEY,SECRET_KEY) .build(); minioClient.removeObject(RemoveObjectArgs.builder().bucket(BUCKET_NAME).object(objectName).build()); return CommonResult.success(null); } catch (Exception e) { e.printStackTrace(); } return CommonResult.failed(); } }
try { //创建一个MinIO的Java客户端 MinioClient minioClient =MinioClient.builder() .endpoint(ENDPOINT) .credentials(ACCESS_KEY,SECRET_KEY) .build(); boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(BUCKET_NAME).build()); if (isExist) { LOGGER.info("存储桶已经存在!"); } else { //创建存储桶并设置只读权限 minioClient.makeBucket(MakeBucketArgs.builder().bucket(BUCKET_NAME).build()); BucketPolicyConfigDto bucketPolicyConfigDto = createBucketPolicyConfigDto(BUCKET_NAME); SetBucketPolicyArgs setBucketPolicyArgs = SetBucketPolicyArgs.builder() .bucket(BUCKET_NAME) .config(JSONUtil.toJsonStr(bucketPolicyConfigDto)) .build(); minioClient.setBucketPolicy(setBucketPolicyArgs); } String filename = file.getOriginalFilename(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); // 设置存储对象名称 String objectName = sdf.format(new Date()) + "/" + filename; // 使用putObject上传一个文件到存储桶中 PutObjectArgs putObjectArgs = PutObjectArgs.builder() .bucket(BUCKET_NAME) .object(objectName) .contentType(file.getContentType()) .stream(file.getInputStream(), file.getSize(), ObjectWriteArgs.MIN_MULTIPART_SIZE).build(); minioClient.putObject(putObjectArgs); LOGGER.info("文件上传成功!"); MinioUploadDto minioUploadDto = new MinioUploadDto(); minioUploadDto.setName(filename); minioUploadDto.setUrl(ENDPOINT + "/" + BUCKET_NAME + "/" + objectName); return CommonResult.success(minioUploadDto); } catch (Exception e) { e.printStackTrace(); LOGGER.info("上传发生错误: {}!", e.getMessage()); } return CommonResult.failed();
510
575
1,085
<no_super_class>
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/controller/OmsOrderController.java
OmsOrderController
close
class OmsOrderController { @Autowired private OmsOrderService orderService; @ApiOperation("查询订单") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<OmsOrder>> list(OmsOrderQueryParam queryParam, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) { List<OmsOrder> orderList = orderService.list(queryParam, pageSize, pageNum); return CommonResult.success(CommonPage.restPage(orderList)); } @ApiOperation("批量发货") @RequestMapping(value = "/update/delivery", method = RequestMethod.POST) @ResponseBody public CommonResult delivery(@RequestBody List<OmsOrderDeliveryParam> deliveryParamList) { int count = orderService.delivery(deliveryParamList); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("批量关闭订单") @RequestMapping(value = "/update/close", method = RequestMethod.POST) @ResponseBody public CommonResult close(@RequestParam("ids") List<Long> ids, @RequestParam String note) {<FILL_FUNCTION_BODY>} @ApiOperation("批量删除订单") @RequestMapping(value = "/delete", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@RequestParam("ids") List<Long> ids) { int count = orderService.delete(ids); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("获取订单详情:订单信息、商品信息、操作记录") @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult<OmsOrderDetail> detail(@PathVariable Long id) { OmsOrderDetail orderDetailResult = orderService.detail(id); return CommonResult.success(orderDetailResult); } @ApiOperation("修改收货人信息") @RequestMapping(value = "/update/receiverInfo", method = RequestMethod.POST) @ResponseBody public CommonResult updateReceiverInfo(@RequestBody OmsReceiverInfoParam receiverInfoParam) { int count = orderService.updateReceiverInfo(receiverInfoParam); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("修改订单费用信息") @RequestMapping(value = "/update/moneyInfo", method = RequestMethod.POST) @ResponseBody public CommonResult updateReceiverInfo(@RequestBody OmsMoneyInfoParam moneyInfoParam) { int count = orderService.updateMoneyInfo(moneyInfoParam); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("备注订单") @RequestMapping(value = "/update/note", method = RequestMethod.POST) @ResponseBody public CommonResult updateNote(@RequestParam("id") Long id, @RequestParam("note") String note, @RequestParam("status") Integer status) { int count = orderService.updateNote(id, note, status); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } }
int count = orderService.close(ids, note); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed();
917
47
964
<no_super_class>
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/controller/OmsOrderReturnApplyController.java
OmsOrderReturnApplyController
updateStatus
class OmsOrderReturnApplyController { @Autowired private OmsOrderReturnApplyService returnApplyService; @ApiOperation("分页查询退货申请") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<OmsOrderReturnApply>> list(OmsReturnApplyQueryParam queryParam, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) { List<OmsOrderReturnApply> returnApplyList = returnApplyService.list(queryParam, pageSize, pageNum); return CommonResult.success(CommonPage.restPage(returnApplyList)); } @ApiOperation("批量删除申请") @RequestMapping(value = "/delete", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@RequestParam("ids") List<Long> ids) { int count = returnApplyService.delete(ids); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("获取退货申请详情") @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult getItem(@PathVariable Long id) { OmsOrderReturnApplyResult result = returnApplyService.getItem(id); return CommonResult.success(result); } @ApiOperation("修改申请状态") @RequestMapping(value = "/update/status/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult updateStatus(@PathVariable Long id, @RequestBody OmsUpdateStatusParam statusParam) {<FILL_FUNCTION_BODY>} }
int count = returnApplyService.updateStatus(id, statusParam); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed();
456
50
506
<no_super_class>
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/controller/OmsOrderReturnReasonController.java
OmsOrderReturnReasonController
updateStatus
class OmsOrderReturnReasonController { @Autowired private OmsOrderReturnReasonService orderReturnReasonService; @ApiOperation("添加退货原因") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public CommonResult create(@RequestBody OmsOrderReturnReason returnReason) { int count = orderReturnReasonService.create(returnReason); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("修改退货原因") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult update(@PathVariable Long id, @RequestBody OmsOrderReturnReason returnReason) { int count = orderReturnReasonService.update(id, returnReason); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("批量删除退货原因") @RequestMapping(value = "/delete", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@RequestParam("ids") List<Long> ids) { int count = orderReturnReasonService.delete(ids); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("分页查询全部退货原因") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<OmsOrderReturnReason>> list(@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) { List<OmsOrderReturnReason> reasonList = orderReturnReasonService.list(pageSize, pageNum); return CommonResult.success(CommonPage.restPage(reasonList)); } @ApiOperation("获取单个退货原因详情信息") @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult<OmsOrderReturnReason> getItem(@PathVariable Long id) { OmsOrderReturnReason reason = orderReturnReasonService.getItem(id); return CommonResult.success(reason); } @ApiOperation("修改退货原因启用状态") @RequestMapping(value = "/update/status", method = RequestMethod.POST) @ResponseBody public CommonResult updateStatus(@RequestParam(value = "status") Integer status, @RequestParam("ids") List<Long> ids) {<FILL_FUNCTION_BODY>} }
int count = orderReturnReasonService.updateStatus(ids, status); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed();
678
50
728
<no_super_class>
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/controller/OmsOrderSettingController.java
OmsOrderSettingController
update
class OmsOrderSettingController { @Autowired private OmsOrderSettingService orderSettingService; @ApiOperation("获取指定订单设置") @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult<OmsOrderSetting> getItem(@PathVariable Long id) { OmsOrderSetting orderSetting = orderSettingService.getItem(id); return CommonResult.success(orderSetting); } @ApiOperation("修改指定订单设置") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult update(@PathVariable Long id, @RequestBody OmsOrderSetting orderSetting) {<FILL_FUNCTION_BODY>} }
int count = orderSettingService.update(id,orderSetting); if(count>0){ return CommonResult.success(count); } return CommonResult.failed();
195
48
243
<no_super_class>
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/controller/PmsBrandController.java
PmsBrandController
updateFactoryStatus
class PmsBrandController { @Autowired private PmsBrandService brandService; @ApiOperation(value = "获取全部品牌列表") @RequestMapping(value = "/listAll", method = RequestMethod.GET) @ResponseBody public CommonResult<List<PmsBrand>> getList() { return CommonResult.success(brandService.listAllBrand()); } @ApiOperation(value = "添加品牌") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public CommonResult create(@Validated @RequestBody PmsBrandParam pmsBrand) { CommonResult commonResult; int count = brandService.createBrand(pmsBrand); if (count == 1) { commonResult = CommonResult.success(count); } else { commonResult = CommonResult.failed(); } return commonResult; } @ApiOperation(value = "更新品牌") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult update(@PathVariable("id") Long id, @Validated @RequestBody PmsBrandParam pmsBrandParam) { CommonResult commonResult; int count = brandService.updateBrand(id, pmsBrandParam); if (count == 1) { commonResult = CommonResult.success(count); } else { commonResult = CommonResult.failed(); } return commonResult; } @ApiOperation(value = "删除品牌") @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult delete(@PathVariable("id") Long id) { int count = brandService.deleteBrand(id); if (count == 1) { return CommonResult.success(null); } else { return CommonResult.failed(); } } @ApiOperation(value = "根据品牌名称分页获取品牌列表") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<PmsBrand>> getList(@RequestParam(value = "keyword", required = false) String keyword, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) { List<PmsBrand> brandList = brandService.listBrand(keyword, pageNum, pageSize); return CommonResult.success(CommonPage.restPage(brandList)); } @ApiOperation(value = "根据编号查询品牌信息") @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult<PmsBrand> getItem(@PathVariable("id") Long id) { return CommonResult.success(brandService.getBrand(id)); } @ApiOperation(value = "批量删除品牌") @RequestMapping(value = "/delete/batch", method = RequestMethod.POST) @ResponseBody public CommonResult deleteBatch(@RequestParam("ids") List<Long> ids) { int count = brandService.deleteBrand(ids); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation(value = "批量更新显示状态") @RequestMapping(value = "/update/showStatus", method = RequestMethod.POST) @ResponseBody public CommonResult updateShowStatus(@RequestParam("ids") List<Long> ids, @RequestParam("showStatus") Integer showStatus) { int count = brandService.updateShowStatus(ids, showStatus); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation(value = "批量更新厂家制造商状态") @RequestMapping(value = "/update/factoryStatus", method = RequestMethod.POST) @ResponseBody public CommonResult updateFactoryStatus(@RequestParam("ids") List<Long> ids, @RequestParam("factoryStatus") Integer factoryStatus) {<FILL_FUNCTION_BODY>} }
int count = brandService.updateFactoryStatus(ids, factoryStatus); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); }
1,085
55
1,140
<no_super_class>
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/controller/PmsProductAttributeCategoryController.java
PmsProductAttributeCategoryController
update
class PmsProductAttributeCategoryController { @Autowired private PmsProductAttributeCategoryService productAttributeCategoryService; @ApiOperation("添加商品属性分类") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public CommonResult create(@RequestParam String name) { int count = productAttributeCategoryService.create(name); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("修改商品属性分类") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult update(@PathVariable Long id, @RequestParam String name) {<FILL_FUNCTION_BODY>} @ApiOperation("删除单个商品属性分类") @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult delete(@PathVariable Long id) { int count = productAttributeCategoryService.delete(id); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("获取单个商品属性分类信息") @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult<PmsProductAttributeCategory> getItem(@PathVariable Long id) { PmsProductAttributeCategory productAttributeCategory = productAttributeCategoryService.getItem(id); return CommonResult.success(productAttributeCategory); } @ApiOperation("分页获取所有商品属性分类") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<PmsProductAttributeCategory>> getList(@RequestParam(defaultValue = "5") Integer pageSize, @RequestParam(defaultValue = "1") Integer pageNum) { List<PmsProductAttributeCategory> productAttributeCategoryList = productAttributeCategoryService.getList(pageSize, pageNum); return CommonResult.success(CommonPage.restPage(productAttributeCategoryList)); } @ApiOperation("获取所有商品属性分类及其下属性") @RequestMapping(value = "/list/withAttr", method = RequestMethod.GET) @ResponseBody public CommonResult<List<PmsProductAttributeCategoryItem>> getListWithAttr() { List<PmsProductAttributeCategoryItem> productAttributeCategoryResultList = productAttributeCategoryService.getListWithAttr(); return CommonResult.success(productAttributeCategoryResultList); } }
int count = productAttributeCategoryService.update(id, name); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); }
653
54
707
<no_super_class>
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/controller/PmsProductCategoryController.java
PmsProductCategoryController
create
class PmsProductCategoryController { @Autowired private PmsProductCategoryService productCategoryService; @ApiOperation("添加产品分类") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public CommonResult create(@Validated @RequestBody PmsProductCategoryParam productCategoryParam) {<FILL_FUNCTION_BODY>} @ApiOperation("修改商品分类") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult update(@PathVariable Long id, @Validated @RequestBody PmsProductCategoryParam productCategoryParam) { int count = productCategoryService.update(id, productCategoryParam); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("分页查询商品分类") @RequestMapping(value = "/list/{parentId}", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<PmsProductCategory>> getList(@PathVariable Long parentId, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) { List<PmsProductCategory> productCategoryList = productCategoryService.getList(parentId, pageSize, pageNum); return CommonResult.success(CommonPage.restPage(productCategoryList)); } @ApiOperation("根据id获取商品分类") @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult<PmsProductCategory> getItem(@PathVariable Long id) { PmsProductCategory productCategory = productCategoryService.getItem(id); return CommonResult.success(productCategory); } @ApiOperation("删除商品分类") @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@PathVariable Long id) { int count = productCategoryService.delete(id); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("修改导航栏显示状态") @RequestMapping(value = "/update/navStatus", method = RequestMethod.POST) @ResponseBody public CommonResult updateNavStatus(@RequestParam("ids") List<Long> ids, @RequestParam("navStatus") Integer navStatus) { int count = productCategoryService.updateNavStatus(ids, navStatus); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("修改显示状态") @RequestMapping(value = "/update/showStatus", method = RequestMethod.POST) @ResponseBody public CommonResult updateShowStatus(@RequestParam("ids") List<Long> ids, @RequestParam("showStatus") Integer showStatus) { int count = productCategoryService.updateShowStatus(ids, showStatus); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("查询所有一级分类及子分类") @RequestMapping(value = "/list/withChildren", method = RequestMethod.GET) @ResponseBody public CommonResult<List<PmsProductCategoryWithChildrenItem>> listWithChildren() { List<PmsProductCategoryWithChildrenItem> list = productCategoryService.listWithChildren(); return CommonResult.success(list); } }
int count = productCategoryService.create(productCategoryParam); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); }
930
53
983
<no_super_class>
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/controller/PmsProductController.java
PmsProductController
create
class PmsProductController { @Autowired private PmsProductService productService; @ApiOperation("创建商品") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public CommonResult create(@RequestBody PmsProductParam productParam) {<FILL_FUNCTION_BODY>} @ApiOperation("根据商品id获取商品编辑信息") @RequestMapping(value = "/updateInfo/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult<PmsProductResult> getUpdateInfo(@PathVariable Long id) { PmsProductResult productResult = productService.getUpdateInfo(id); return CommonResult.success(productResult); } @ApiOperation("更新商品") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult update(@PathVariable Long id, @RequestBody PmsProductParam productParam) { int count = productService.update(id, productParam); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("查询商品") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<PmsProduct>> getList(PmsProductQueryParam productQueryParam, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) { List<PmsProduct> productList = productService.list(productQueryParam, pageSize, pageNum); return CommonResult.success(CommonPage.restPage(productList)); } @ApiOperation("根据商品名称或货号模糊查询") @RequestMapping(value = "/simpleList", method = RequestMethod.GET) @ResponseBody public CommonResult<List<PmsProduct>> getList(String keyword) { List<PmsProduct> productList = productService.list(keyword); return CommonResult.success(productList); } @ApiOperation("批量修改审核状态") @RequestMapping(value = "/update/verifyStatus", method = RequestMethod.POST) @ResponseBody public CommonResult updateVerifyStatus(@RequestParam("ids") List<Long> ids, @RequestParam("verifyStatus") Integer verifyStatus, @RequestParam("detail") String detail) { int count = productService.updateVerifyStatus(ids, verifyStatus, detail); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("批量上下架") @RequestMapping(value = "/update/publishStatus", method = RequestMethod.POST) @ResponseBody public CommonResult updatePublishStatus(@RequestParam("ids") List<Long> ids, @RequestParam("publishStatus") Integer publishStatus) { int count = productService.updatePublishStatus(ids, publishStatus); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("批量推荐商品") @RequestMapping(value = "/update/recommendStatus", method = RequestMethod.POST) @ResponseBody public CommonResult updateRecommendStatus(@RequestParam("ids") List<Long> ids, @RequestParam("recommendStatus") Integer recommendStatus) { int count = productService.updateRecommendStatus(ids, recommendStatus); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("批量设为新品") @RequestMapping(value = "/update/newStatus", method = RequestMethod.POST) @ResponseBody public CommonResult updateNewStatus(@RequestParam("ids") List<Long> ids, @RequestParam("newStatus") Integer newStatus) { int count = productService.updateNewStatus(ids, newStatus); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("批量修改删除状态") @RequestMapping(value = "/update/deleteStatus", method = RequestMethod.POST) @ResponseBody public CommonResult updateDeleteStatus(@RequestParam("ids") List<Long> ids, @RequestParam("deleteStatus") Integer deleteStatus) { int count = productService.updateDeleteStatus(ids, deleteStatus); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } }
int count = productService.create(productParam); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); }
1,219
51
1,270
<no_super_class>
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/controller/PmsSkuStockController.java
PmsSkuStockController
update
class PmsSkuStockController { @Autowired private PmsSkuStockService skuStockService; @ApiOperation("根据商品编号及编号模糊搜索sku库存") @RequestMapping(value = "/{pid}", method = RequestMethod.GET) @ResponseBody public CommonResult<List<PmsSkuStock>> getList(@PathVariable Long pid, @RequestParam(value = "keyword",required = false) String keyword) { List<PmsSkuStock> skuStockList = skuStockService.getList(pid, keyword); return CommonResult.success(skuStockList); } @ApiOperation("批量更新库存信息") @RequestMapping(value ="/update/{pid}",method = RequestMethod.POST) @ResponseBody public CommonResult update(@PathVariable Long pid,@RequestBody List<PmsSkuStock> skuStockList){<FILL_FUNCTION_BODY>} }
int count = skuStockService.update(pid,skuStockList); if(count>0){ return CommonResult.success(count); }else{ return CommonResult.failed(); }
249
58
307
<no_super_class>
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/controller/SmsCouponController.java
SmsCouponController
delete
class SmsCouponController { @Autowired private SmsCouponService couponService; @ApiOperation("添加优惠券") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public CommonResult add(@RequestBody SmsCouponParam couponParam) { int count = couponService.create(couponParam); if(count>0){ return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("删除优惠券") @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@PathVariable Long id) {<FILL_FUNCTION_BODY>} @ApiOperation("修改优惠券") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult update(@PathVariable Long id,@RequestBody SmsCouponParam couponParam) { int count = couponService.update(id,couponParam); if(count>0){ return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("根据优惠券名称和类型分页获取优惠券列表") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<SmsCoupon>> list( @RequestParam(value = "name",required = false) String name, @RequestParam(value = "type",required = false) Integer type, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) { List<SmsCoupon> couponList = couponService.list(name,type,pageSize,pageNum); return CommonResult.success(CommonPage.restPage(couponList)); } @ApiOperation("获取单个优惠券的详细信息") @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult<SmsCouponParam> getItem(@PathVariable Long id) { SmsCouponParam couponParam = couponService.getItem(id); return CommonResult.success(couponParam); } }
int count = couponService.delete(id); if(count>0){ return CommonResult.success(count); } return CommonResult.failed();
590
44
634
<no_super_class>
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/controller/SmsCouponHistoryController.java
SmsCouponHistoryController
list
class SmsCouponHistoryController { @Autowired private SmsCouponHistoryService historyService; @ApiOperation("根据优惠券id,使用状态,订单编号分页获取领取记录") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<SmsCouponHistory>> list(@RequestParam(value = "couponId", required = false) Long couponId, @RequestParam(value = "useStatus", required = false) Integer useStatus, @RequestParam(value = "orderSn", required = false) String orderSn, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {<FILL_FUNCTION_BODY>} }
List<SmsCouponHistory> historyList = historyService.list(couponId, useStatus, orderSn, pageSize, pageNum); return CommonResult.success(CommonPage.restPage(historyList));
217
55
272
<no_super_class>
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/controller/SmsFlashPromotionController.java
SmsFlashPromotionController
update
class SmsFlashPromotionController { @Autowired private SmsFlashPromotionService flashPromotionService; @ApiOperation("添加活动") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public CommonResult create(@RequestBody SmsFlashPromotion flashPromotion) { int count = flashPromotionService.create(flashPromotion); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("编辑活动信息") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public Object update(@PathVariable Long id, @RequestBody SmsFlashPromotion flashPromotion) { int count = flashPromotionService.update(id, flashPromotion); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("删除活动信息") @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST) @ResponseBody public Object delete(@PathVariable Long id) { int count = flashPromotionService.delete(id); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("修改上下线状态") @RequestMapping(value = "/update/status/{id}", method = RequestMethod.POST) @ResponseBody public Object update(@PathVariable Long id, Integer status) {<FILL_FUNCTION_BODY>} @ApiOperation("获取活动详情") @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public Object getItem(@PathVariable Long id) { SmsFlashPromotion flashPromotion = flashPromotionService.getItem(id); return CommonResult.success(flashPromotion); } @ApiOperation("根据活动名称分页查询") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public Object getItem(@RequestParam(value = "keyword", required = false) String keyword, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) { List<SmsFlashPromotion> flashPromotionList = flashPromotionService.list(keyword, pageSize, pageNum); return CommonResult.success(CommonPage.restPage(flashPromotionList)); } }
int count = flashPromotionService.updateStatus(id, status); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed();
659
50
709
<no_super_class>
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/controller/SmsFlashPromotionProductRelationController.java
SmsFlashPromotionProductRelationController
delete
class SmsFlashPromotionProductRelationController { @Autowired private SmsFlashPromotionProductRelationService relationService; @ApiOperation("批量选择商品添加关联") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public CommonResult create(@RequestBody List<SmsFlashPromotionProductRelation> relationList) { int count = relationService.create(relationList); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("修改关联相关信息") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult update(@PathVariable Long id, @RequestBody SmsFlashPromotionProductRelation relation) { int count = relationService.update(id, relation); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("删除关联") @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@PathVariable Long id) {<FILL_FUNCTION_BODY>} @ApiOperation("获取管理商品促销信息") @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult<SmsFlashPromotionProductRelation> getItem(@PathVariable Long id) { SmsFlashPromotionProductRelation relation = relationService.getItem(id); return CommonResult.success(relation); } @ApiOperation("分页查询不同场次关联及商品信息") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<SmsFlashPromotionProduct>> list(@RequestParam(value = "flashPromotionId") Long flashPromotionId, @RequestParam(value = "flashPromotionSessionId") Long flashPromotionSessionId, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) { List<SmsFlashPromotionProduct> flashPromotionProductList = relationService.list(flashPromotionId, flashPromotionSessionId, pageSize, pageNum); return CommonResult.success(CommonPage.restPage(flashPromotionProductList)); } }
int count = relationService.delete(id); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed();
633
45
678
<no_super_class>
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/controller/SmsFlashPromotionSessionController.java
SmsFlashPromotionSessionController
delete
class SmsFlashPromotionSessionController { @Autowired private SmsFlashPromotionSessionService flashPromotionSessionService; @ApiOperation("添加场次") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public CommonResult create(@RequestBody SmsFlashPromotionSession promotionSession) { int count = flashPromotionSessionService.create(promotionSession); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("修改场次") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult update(@PathVariable Long id, @RequestBody SmsFlashPromotionSession promotionSession) { int count = flashPromotionSessionService.update(id, promotionSession); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("修改启用状态") @RequestMapping(value = "/update/status/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult updateStatus(@PathVariable Long id, Integer status) { int count = flashPromotionSessionService.updateStatus(id, status); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("删除场次") @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@PathVariable Long id) {<FILL_FUNCTION_BODY>} @ApiOperation("获取场次详情") @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult<SmsFlashPromotionSession> getItem(@PathVariable Long id) { SmsFlashPromotionSession promotionSession = flashPromotionSessionService.getItem(id); return CommonResult.success(promotionSession); } @ApiOperation("获取全部场次") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<List<SmsFlashPromotionSession>> list() { List<SmsFlashPromotionSession> promotionSessionList = flashPromotionSessionService.list(); return CommonResult.success(promotionSessionList); } @ApiOperation("获取全部可选场次及其数量") @RequestMapping(value = "/selectList", method = RequestMethod.GET) @ResponseBody public CommonResult<List<SmsFlashPromotionSessionDetail>> selectList(Long flashPromotionId) { List<SmsFlashPromotionSessionDetail> promotionSessionList = flashPromotionSessionService.selectList(flashPromotionId); return CommonResult.success(promotionSessionList); } }
int count = flashPromotionSessionService.delete(id); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed();
734
48
782
<no_super_class>
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/controller/SmsHomeAdvertiseController.java
SmsHomeAdvertiseController
update
class SmsHomeAdvertiseController { @Autowired private SmsHomeAdvertiseService advertiseService; @ApiOperation("添加广告") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public CommonResult create(@RequestBody SmsHomeAdvertise advertise) { int count = advertiseService.create(advertise); if (count > 0) return CommonResult.success(count); return CommonResult.failed(); } @ApiOperation("删除广告") @RequestMapping(value = "/delete", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@RequestParam("ids") List<Long> ids) { int count = advertiseService.delete(ids); if (count > 0) return CommonResult.success(count); return CommonResult.failed(); } @ApiOperation("修改上下线状态") @RequestMapping(value = "/update/status/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult updateStatus(@PathVariable Long id, Integer status) { int count = advertiseService.updateStatus(id, status); if (count > 0) return CommonResult.success(count); return CommonResult.failed(); } @ApiOperation("获取广告详情") @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult<SmsHomeAdvertise> getItem(@PathVariable Long id) { SmsHomeAdvertise advertise = advertiseService.getItem(id); return CommonResult.success(advertise); } @ApiOperation("修改广告") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult update(@PathVariable Long id, @RequestBody SmsHomeAdvertise advertise) {<FILL_FUNCTION_BODY>} @ApiOperation("分页查询广告") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<SmsHomeAdvertise>> list(@RequestParam(value = "name", required = false) String name, @RequestParam(value = "type", required = false) Integer type, @RequestParam(value = "endTime", required = false) String endTime, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) { List<SmsHomeAdvertise> advertiseList = advertiseService.list(name, type, endTime, pageSize, pageNum); return CommonResult.success(CommonPage.restPage(advertiseList)); } }
int count = advertiseService.update(id, advertise); if (count > 0) return CommonResult.success(count); return CommonResult.failed();
707
45
752
<no_super_class>
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/controller/SmsHomeBrandController.java
SmsHomeBrandController
delete
class SmsHomeBrandController { @Autowired private SmsHomeBrandService homeBrandService; @ApiOperation("添加首页推荐品牌") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public CommonResult create(@RequestBody List<SmsHomeBrand> homeBrandList) { int count = homeBrandService.create(homeBrandList); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("修改品牌排序") @RequestMapping(value = "/update/sort/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult updateSort(@PathVariable Long id, Integer sort) { int count = homeBrandService.updateSort(id, sort); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("批量删除推荐品牌") @RequestMapping(value = "/delete", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@RequestParam("ids") List<Long> ids) {<FILL_FUNCTION_BODY>} @ApiOperation("批量修改推荐状态") @RequestMapping(value = "/update/recommendStatus", method = RequestMethod.POST) @ResponseBody public CommonResult updateRecommendStatus(@RequestParam("ids") List<Long> ids, @RequestParam Integer recommendStatus) { int count = homeBrandService.updateRecommendStatus(ids, recommendStatus); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("分页查询推荐品牌") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<SmsHomeBrand>> list(@RequestParam(value = "brandName", required = false) String brandName, @RequestParam(value = "recommendStatus", required = false) Integer recommendStatus, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) { List<SmsHomeBrand> homeBrandList = homeBrandService.list(brandName, recommendStatus, pageSize, pageNum); return CommonResult.success(CommonPage.restPage(homeBrandList)); } }
int count = homeBrandService.delete(ids); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed();
641
47
688
<no_super_class>
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/controller/SmsHomeNewProductController.java
SmsHomeNewProductController
updateSort
class SmsHomeNewProductController { @Autowired private SmsHomeNewProductService homeNewProductService; @ApiOperation("添加首页推荐品牌") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public CommonResult create(@RequestBody List<SmsHomeNewProduct> homeBrandList) { int count = homeNewProductService.create(homeBrandList); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("修改推荐排序") @RequestMapping(value = "/update/sort/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult updateSort(@PathVariable Long id, Integer sort) {<FILL_FUNCTION_BODY>} @ApiOperation("批量删除推荐") @RequestMapping(value = "/delete", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@RequestParam("ids") List<Long> ids) { int count = homeNewProductService.delete(ids); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("批量修改推荐状态") @RequestMapping(value = "/update/recommendStatus", method = RequestMethod.POST) @ResponseBody public CommonResult updateRecommendStatus(@RequestParam("ids") List<Long> ids, @RequestParam Integer recommendStatus) { int count = homeNewProductService.updateRecommendStatus(ids, recommendStatus); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("分页查询推荐") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<SmsHomeNewProduct>> list(@RequestParam(value = "productName", required = false) String productName, @RequestParam(value = "recommendStatus", required = false) Integer recommendStatus, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) { List<SmsHomeNewProduct> homeBrandList = homeNewProductService.list(productName, recommendStatus, pageSize, pageNum); return CommonResult.success(CommonPage.restPage(homeBrandList)); } }
int count = homeNewProductService.updateSort(id, sort); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed();
636
50
686
<no_super_class>
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/controller/SmsHomeRecommendProductController.java
SmsHomeRecommendProductController
updateSort
class SmsHomeRecommendProductController { @Autowired private SmsHomeRecommendProductService recommendProductService; @ApiOperation("添加首页推荐") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public CommonResult create(@RequestBody List<SmsHomeRecommendProduct> homeBrandList) { int count = recommendProductService.create(homeBrandList); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("修改推荐排序") @RequestMapping(value = "/update/sort/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult updateSort(@PathVariable Long id, Integer sort) {<FILL_FUNCTION_BODY>} @ApiOperation("批量删除推荐") @RequestMapping(value = "/delete", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@RequestParam("ids") List<Long> ids) { int count = recommendProductService.delete(ids); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("批量修改推荐状态") @RequestMapping(value = "/update/recommendStatus", method = RequestMethod.POST) @ResponseBody public CommonResult updateRecommendStatus(@RequestParam("ids") List<Long> ids, @RequestParam Integer recommendStatus) { int count = recommendProductService.updateRecommendStatus(ids, recommendStatus); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("分页查询推荐") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<SmsHomeRecommendProduct>> list(@RequestParam(value = "productName", required = false) String productName, @RequestParam(value = "recommendStatus", required = false) Integer recommendStatus, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) { List<SmsHomeRecommendProduct> homeBrandList = recommendProductService.list(productName, recommendStatus, pageSize, pageNum); return CommonResult.success(CommonPage.restPage(homeBrandList)); } }
int count = recommendProductService.updateSort(id, sort); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed();
640
49
689
<no_super_class>
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/controller/SmsHomeRecommendSubjectController.java
SmsHomeRecommendSubjectController
list
class SmsHomeRecommendSubjectController { @Autowired private SmsHomeRecommendSubjectService recommendSubjectService; @ApiOperation("添加首页推荐专题") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public CommonResult create(@RequestBody List<SmsHomeRecommendSubject> homeBrandList) { int count = recommendSubjectService.create(homeBrandList); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("修改推荐排序") @RequestMapping(value = "/update/sort/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult updateSort(@PathVariable Long id, Integer sort) { int count = recommendSubjectService.updateSort(id, sort); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("批量删除推荐") @RequestMapping(value = "/delete", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@RequestParam("ids") List<Long> ids) { int count = recommendSubjectService.delete(ids); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("批量修改推荐状态") @RequestMapping(value = "/update/recommendStatus", method = RequestMethod.POST) @ResponseBody public CommonResult updateRecommendStatus(@RequestParam("ids") List<Long> ids, @RequestParam Integer recommendStatus) { int count = recommendSubjectService.updateRecommendStatus(ids, recommendStatus); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("分页查询推荐") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<SmsHomeRecommendSubject>> list(@RequestParam(value = "subjectName", required = false) String subjectName, @RequestParam(value = "recommendStatus", required = false) Integer recommendStatus, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {<FILL_FUNCTION_BODY>} }
List<SmsHomeRecommendSubject> homeBrandList = recommendSubjectService.list(subjectName, recommendStatus, pageSize, pageNum); return CommonResult.success(CommonPage.restPage(homeBrandList));
634
57
691
<no_super_class>
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/controller/UmsAdminController.java
UmsAdminController
updatePassword
class UmsAdminController { @Autowired private UmsAdminService adminService; @Autowired private UmsRoleService roleService; @ApiOperation(value = "用户注册") @RequestMapping(value = "/register", method = RequestMethod.POST) @ResponseBody public CommonResult<UmsAdmin> register(@Validated @RequestBody UmsAdminParam umsAdminParam) { UmsAdmin umsAdmin = adminService.register(umsAdminParam); if (umsAdmin == null) { return CommonResult.failed(); } return CommonResult.success(umsAdmin); } @ApiOperation(value = "登录以后返回token") @RequestMapping(value = "/login", method = RequestMethod.POST) @ResponseBody public CommonResult login(@Validated @RequestBody UmsAdminLoginParam umsAdminLoginParam) { return adminService.login(umsAdminLoginParam.getUsername(),umsAdminLoginParam.getPassword()); } @ApiOperation(value = "获取当前登录用户信息") @RequestMapping(value = "/info", method = RequestMethod.GET) @ResponseBody public CommonResult getAdminInfo() { UmsAdmin umsAdmin = adminService.getCurrentAdmin(); Map<String, Object> data = new HashMap<>(); data.put("username", umsAdmin.getUsername()); data.put("menus", roleService.getMenuList(umsAdmin.getId())); data.put("icon", umsAdmin.getIcon()); List<UmsRole> roleList = adminService.getRoleList(umsAdmin.getId()); if(CollUtil.isNotEmpty(roleList)){ List<String> roles = roleList.stream().map(UmsRole::getName).collect(Collectors.toList()); data.put("roles",roles); } return CommonResult.success(data); } @ApiOperation(value = "登出功能") @RequestMapping(value = "/logout", method = RequestMethod.POST) @ResponseBody public CommonResult logout() { return CommonResult.success(null); } @ApiOperation("根据用户名或姓名分页获取用户列表") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<UmsAdmin>> list(@RequestParam(value = "keyword", required = false) String keyword, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) { List<UmsAdmin> adminList = adminService.list(keyword, pageSize, pageNum); return CommonResult.success(CommonPage.restPage(adminList)); } @ApiOperation("获取指定用户信息") @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult<UmsAdmin> getItem(@PathVariable Long id) { UmsAdmin admin = adminService.getItem(id); return CommonResult.success(admin); } @ApiOperation("修改指定用户信息") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult update(@PathVariable Long id, @RequestBody UmsAdmin admin) { int count = adminService.update(id, admin); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("修改指定用户密码") @RequestMapping(value = "/updatePassword", method = RequestMethod.POST) @ResponseBody public CommonResult updatePassword(@RequestBody UpdateAdminPasswordParam updatePasswordParam) {<FILL_FUNCTION_BODY>} @ApiOperation("删除指定用户信息") @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@PathVariable Long id) { int count = adminService.delete(id); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("修改帐号状态") @RequestMapping(value = "/updateStatus/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult updateStatus(@PathVariable Long id,@RequestParam(value = "status") Integer status) { UmsAdmin umsAdmin = new UmsAdmin(); umsAdmin.setStatus(status); int count = adminService.update(id,umsAdmin); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("给用户分配角色") @RequestMapping(value = "/role/update", method = RequestMethod.POST) @ResponseBody public CommonResult updateRole(@RequestParam("adminId") Long adminId, @RequestParam("roleIds") List<Long> roleIds) { int count = adminService.updateRole(adminId, roleIds); if (count >= 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("获取指定用户的角色") @RequestMapping(value = "/role/{adminId}", method = RequestMethod.GET) @ResponseBody public CommonResult<List<UmsRole>> getRoleList(@PathVariable Long adminId) { List<UmsRole> roleList = adminService.getRoleList(adminId); return CommonResult.success(roleList); } @ApiOperation("根据用户名获取通用用户信息") @RequestMapping(value = "/loadByUsername", method = RequestMethod.GET) @ResponseBody public UserDto loadUserByUsername(@RequestParam String username) { UserDto userDTO = adminService.loadUserByUsername(username); return userDTO; } }
int status = adminService.updatePassword(updatePasswordParam); if (status > 0) { return CommonResult.success(status); } else if (status == -1) { return CommonResult.failed("提交参数不合法"); } else if (status == -2) { return CommonResult.failed("找不到该用户"); } else if (status == -3) { return CommonResult.failed("旧密码错误"); } else { return CommonResult.failed(); }
1,512
129
1,641
<no_super_class>
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/controller/UmsMenuController.java
UmsMenuController
update
class UmsMenuController { @Autowired private UmsMenuService menuService; @ApiOperation("添加后台菜单") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public CommonResult create(@RequestBody UmsMenu umsMenu) { int count = menuService.create(umsMenu); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("修改后台菜单") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult update(@PathVariable Long id, @RequestBody UmsMenu umsMenu) {<FILL_FUNCTION_BODY>} @ApiOperation("根据ID获取菜单详情") @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult<UmsMenu> getItem(@PathVariable Long id) { UmsMenu umsMenu = menuService.getItem(id); return CommonResult.success(umsMenu); } @ApiOperation("根据ID删除后台菜单") @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@PathVariable Long id) { int count = menuService.delete(id); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("分页查询后台菜单") @RequestMapping(value = "/list/{parentId}", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<UmsMenu>> list(@PathVariable Long parentId, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) { List<UmsMenu> menuList = menuService.list(parentId, pageSize, pageNum); return CommonResult.success(CommonPage.restPage(menuList)); } @ApiOperation("树形结构返回所有菜单列表") @RequestMapping(value = "/treeList", method = RequestMethod.GET) @ResponseBody public CommonResult<List<UmsMenuNode>> treeList() { List<UmsMenuNode> list = menuService.treeList(); return CommonResult.success(list); } @ApiOperation("修改菜单显示状态") @RequestMapping(value = "/updateHidden/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult updateHidden(@PathVariable Long id, @RequestParam("hidden") Integer hidden) { int count = menuService.updateHidden(id, hidden); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } }
int count = menuService.update(id, umsMenu); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); }
767
54
821
<no_super_class>
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/controller/UmsResourceCategoryController.java
UmsResourceCategoryController
delete
class UmsResourceCategoryController { @Autowired private UmsResourceCategoryService resourceCategoryService; @ApiOperation("查询所有后台资源分类") @RequestMapping(value = "/listAll", method = RequestMethod.GET) @ResponseBody public CommonResult<List<UmsResourceCategory>> listAll() { List<UmsResourceCategory> resourceList = resourceCategoryService.listAll(); return CommonResult.success(resourceList); } @ApiOperation("添加后台资源分类") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public CommonResult create(@RequestBody UmsResourceCategory umsResourceCategory) { int count = resourceCategoryService.create(umsResourceCategory); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("修改后台资源分类") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult update(@PathVariable Long id, @RequestBody UmsResourceCategory umsResourceCategory) { int count = resourceCategoryService.update(id, umsResourceCategory); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("根据ID删除后台资源") @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@PathVariable Long id) {<FILL_FUNCTION_BODY>} }
int count = resourceCategoryService.delete(id); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); }
414
51
465
<no_super_class>
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/controller/UmsResourceController.java
UmsResourceController
list
class UmsResourceController { @Autowired private UmsResourceService resourceService; @ApiOperation("添加后台资源") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public CommonResult create(@RequestBody UmsResource umsResource) { int count = resourceService.create(umsResource); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("修改后台资源") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult update(@PathVariable Long id, @RequestBody UmsResource umsResource) { int count = resourceService.update(id, umsResource); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("根据ID获取资源详情") @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult<UmsResource> getItem(@PathVariable Long id) { UmsResource umsResource = resourceService.getItem(id); return CommonResult.success(umsResource); } @ApiOperation("根据ID删除后台资源") @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@PathVariable Long id) { int count = resourceService.delete(id); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("分页模糊查询后台资源") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<UmsResource>> list(@RequestParam(required = false) Long categoryId, @RequestParam(required = false) String nameKeyword, @RequestParam(required = false) String urlKeyword, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {<FILL_FUNCTION_BODY>} @ApiOperation("查询所有后台资源") @RequestMapping(value = "/listAll", method = RequestMethod.GET) @ResponseBody public CommonResult<List<UmsResource>> listAll() { List<UmsResource> resourceList = resourceService.listAll(); return CommonResult.success(resourceList); } @ApiOperation("初始化资源角色关联数据") @RequestMapping(value = "/initResourceRolesMap", method = RequestMethod.GET) @ResponseBody public CommonResult initResourceRolesMap() { Map<String, List<String>> resourceRolesMap = resourceService.initResourceRolesMap(); return CommonResult.success(resourceRolesMap); } }
List<UmsResource> resourceList = resourceService.list(categoryId,nameKeyword, urlKeyword, pageSize, pageNum); return CommonResult.success(CommonPage.restPage(resourceList));
777
53
830
<no_super_class>
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/controller/UmsRoleController.java
UmsRoleController
create
class UmsRoleController { @Autowired private UmsRoleService roleService; @ApiOperation("添加角色") @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseBody public CommonResult create(@RequestBody UmsRole role) {<FILL_FUNCTION_BODY>} @ApiOperation("修改角色") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult update(@PathVariable Long id, @RequestBody UmsRole role) { int count = roleService.update(id, role); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("批量删除角色") @RequestMapping(value = "/delete", method = RequestMethod.POST) @ResponseBody public CommonResult delete(@RequestParam("ids") List<Long> ids) { int count = roleService.delete(ids); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("获取所有角色") @RequestMapping(value = "/listAll", method = RequestMethod.GET) @ResponseBody public CommonResult<List<UmsRole>> listAll() { List<UmsRole> roleList = roleService.list(); return CommonResult.success(roleList); } @ApiOperation("根据角色名称分页获取角色列表") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<UmsRole>> list(@RequestParam(value = "keyword", required = false) String keyword, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) { List<UmsRole> roleList = roleService.list(keyword, pageSize, pageNum); return CommonResult.success(CommonPage.restPage(roleList)); } @ApiOperation("修改角色状态") @RequestMapping(value = "/updateStatus/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult updateStatus(@PathVariable Long id, @RequestParam(value = "status") Integer status) { UmsRole umsRole = new UmsRole(); umsRole.setStatus(status); int count = roleService.update(id, umsRole); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed(); } @ApiOperation("获取角色相关菜单") @RequestMapping(value = "/listMenu/{roleId}", method = RequestMethod.GET) @ResponseBody public CommonResult<List<UmsMenu>> listMenu(@PathVariable Long roleId) { List<UmsMenu> roleList = roleService.listMenu(roleId); return CommonResult.success(roleList); } @ApiOperation("获取角色相关资源") @RequestMapping(value = "/listResource/{roleId}", method = RequestMethod.GET) @ResponseBody public CommonResult<List<UmsResource>> listResource(@PathVariable Long roleId) { List<UmsResource> roleList = roleService.listResource(roleId); return CommonResult.success(roleList); } @ApiOperation("给角色分配菜单") @RequestMapping(value = "/allocMenu", method = RequestMethod.POST) @ResponseBody public CommonResult allocMenu(@RequestParam Long roleId, @RequestParam List<Long> menuIds) { int count = roleService.allocMenu(roleId, menuIds); return CommonResult.success(count); } @ApiOperation("给角色分配资源") @RequestMapping(value = "/allocResource", method = RequestMethod.POST) @ResponseBody public CommonResult allocResource(@RequestParam Long roleId, @RequestParam List<Long> resourceIds) { int count = roleService.allocResource(roleId, resourceIds); return CommonResult.success(count); } }
int count = roleService.create(role); if (count > 0) { return CommonResult.success(count); } return CommonResult.failed();
1,050
45
1,095
<no_super_class>
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/service/impl/CmsSubjectServiceImpl.java
CmsSubjectServiceImpl
list
class CmsSubjectServiceImpl implements CmsSubjectService { @Autowired private CmsSubjectMapper subjectMapper; @Override public List<CmsSubject> listAll() { return subjectMapper.selectByExample(new CmsSubjectExample()); } @Override public List<CmsSubject> list(String keyword, Integer pageNum, Integer pageSize) {<FILL_FUNCTION_BODY>} }
PageHelper.startPage(pageNum, pageSize); CmsSubjectExample example = new CmsSubjectExample(); CmsSubjectExample.Criteria criteria = example.createCriteria(); if (!StringUtils.isEmpty(keyword)) { criteria.andTitleLike("%" + keyword + "%"); } return subjectMapper.selectByExample(example);
108
89
197
<no_super_class>
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/service/impl/OmsOrderReturnApplyServiceImpl.java
OmsOrderReturnApplyServiceImpl
updateStatus
class OmsOrderReturnApplyServiceImpl implements OmsOrderReturnApplyService { @Autowired private OmsOrderReturnApplyDao returnApplyDao; @Autowired private OmsOrderReturnApplyMapper returnApplyMapper; @Override public List<OmsOrderReturnApply> list(OmsReturnApplyQueryParam queryParam, Integer pageSize, Integer pageNum) { PageHelper.startPage(pageNum,pageSize); return returnApplyDao.getList(queryParam); } @Override public int delete(List<Long> ids) { OmsOrderReturnApplyExample example = new OmsOrderReturnApplyExample(); example.createCriteria().andIdIn(ids).andStatusEqualTo(3); return returnApplyMapper.deleteByExample(example); } @Override public int updateStatus(Long id, OmsUpdateStatusParam statusParam) {<FILL_FUNCTION_BODY>} @Override public OmsOrderReturnApplyResult getItem(Long id) { return returnApplyDao.getDetail(id); } }
Integer status = statusParam.getStatus(); OmsOrderReturnApply returnApply = new OmsOrderReturnApply(); if(status.equals(1)){ //确认退货 returnApply.setId(id); returnApply.setStatus(1); returnApply.setReturnAmount(statusParam.getReturnAmount()); returnApply.setCompanyAddressId(statusParam.getCompanyAddressId()); returnApply.setHandleTime(new Date()); returnApply.setHandleMan(statusParam.getHandleMan()); returnApply.setHandleNote(statusParam.getHandleNote()); }else if(status.equals(2)){ //完成退货 returnApply.setId(id); returnApply.setStatus(2); returnApply.setReceiveTime(new Date()); returnApply.setReceiveMan(statusParam.getReceiveMan()); returnApply.setReceiveNote(statusParam.getReceiveNote()); }else if(status.equals(3)){ //拒绝退货 returnApply.setId(id); returnApply.setStatus(3); returnApply.setHandleTime(new Date()); returnApply.setHandleMan(statusParam.getHandleMan()); returnApply.setHandleNote(statusParam.getHandleNote()); }else{ return 0; } return returnApplyMapper.updateByPrimaryKeySelective(returnApply);
272
345
617
<no_super_class>
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/service/impl/OmsOrderReturnReasonServiceImpl.java
OmsOrderReturnReasonServiceImpl
updateStatus
class OmsOrderReturnReasonServiceImpl implements OmsOrderReturnReasonService { @Autowired private OmsOrderReturnReasonMapper returnReasonMapper; @Override public int create(OmsOrderReturnReason returnReason) { returnReason.setCreateTime(new Date()); return returnReasonMapper.insert(returnReason); } @Override public int update(Long id, OmsOrderReturnReason returnReason) { returnReason.setId(id); return returnReasonMapper.updateByPrimaryKey(returnReason); } @Override public int delete(List<Long> ids) { OmsOrderReturnReasonExample example = new OmsOrderReturnReasonExample(); example.createCriteria().andIdIn(ids); return returnReasonMapper.deleteByExample(example); } @Override public List<OmsOrderReturnReason> list(Integer pageSize, Integer pageNum) { PageHelper.startPage(pageNum,pageSize); OmsOrderReturnReasonExample example = new OmsOrderReturnReasonExample(); example.setOrderByClause("sort desc"); return returnReasonMapper.selectByExample(example); } @Override public int updateStatus(List<Long> ids, Integer status) {<FILL_FUNCTION_BODY>} @Override public OmsOrderReturnReason getItem(Long id) { return returnReasonMapper.selectByPrimaryKey(id); } }
if(!status.equals(0)&&!status.equals(1)){ return 0; } OmsOrderReturnReason record = new OmsOrderReturnReason(); record.setStatus(status); OmsOrderReturnReasonExample example = new OmsOrderReturnReasonExample(); example.createCriteria().andIdIn(ids); return returnReasonMapper.updateByExampleSelective(record,example);
362
104
466
<no_super_class>
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/service/impl/OmsOrderServiceImpl.java
OmsOrderServiceImpl
delete
class OmsOrderServiceImpl implements OmsOrderService { @Autowired private OmsOrderMapper orderMapper; @Autowired private OmsOrderDao orderDao; @Autowired private OmsOrderOperateHistoryDao orderOperateHistoryDao; @Autowired private OmsOrderOperateHistoryMapper orderOperateHistoryMapper; @Override public List<OmsOrder> list(OmsOrderQueryParam queryParam, Integer pageSize, Integer pageNum) { PageHelper.startPage(pageNum, pageSize); return orderDao.getList(queryParam); } @Override public int delivery(List<OmsOrderDeliveryParam> deliveryParamList) { //批量发货 int count = orderDao.delivery(deliveryParamList); //添加操作记录 List<OmsOrderOperateHistory> operateHistoryList = deliveryParamList.stream() .map(omsOrderDeliveryParam -> { OmsOrderOperateHistory history = new OmsOrderOperateHistory(); history.setOrderId(omsOrderDeliveryParam.getOrderId()); history.setCreateTime(new Date()); history.setOperateMan("后台管理员"); history.setOrderStatus(2); history.setNote("完成发货"); return history; }).collect(Collectors.toList()); orderOperateHistoryDao.insertList(operateHistoryList); return count; } @Override public int close(List<Long> ids, String note) { OmsOrder record = new OmsOrder(); record.setStatus(4); OmsOrderExample example = new OmsOrderExample(); example.createCriteria().andDeleteStatusEqualTo(0).andIdIn(ids); int count = orderMapper.updateByExampleSelective(record, example); List<OmsOrderOperateHistory> historyList = ids.stream().map(orderId -> { OmsOrderOperateHistory history = new OmsOrderOperateHistory(); history.setOrderId(orderId); history.setCreateTime(new Date()); history.setOperateMan("后台管理员"); history.setOrderStatus(4); history.setNote("订单关闭:"+note); return history; }).collect(Collectors.toList()); orderOperateHistoryDao.insertList(historyList); return count; } @Override public int delete(List<Long> ids) {<FILL_FUNCTION_BODY>} @Override public OmsOrderDetail detail(Long id) { return orderDao.getDetail(id); } @Override public int updateReceiverInfo(OmsReceiverInfoParam receiverInfoParam) { OmsOrder order = new OmsOrder(); order.setId(receiverInfoParam.getOrderId()); order.setReceiverName(receiverInfoParam.getReceiverName()); order.setReceiverPhone(receiverInfoParam.getReceiverPhone()); order.setReceiverPostCode(receiverInfoParam.getReceiverPostCode()); order.setReceiverDetailAddress(receiverInfoParam.getReceiverDetailAddress()); order.setReceiverProvince(receiverInfoParam.getReceiverProvince()); order.setReceiverCity(receiverInfoParam.getReceiverCity()); order.setReceiverRegion(receiverInfoParam.getReceiverRegion()); order.setModifyTime(new Date()); int count = orderMapper.updateByPrimaryKeySelective(order); //插入操作记录 OmsOrderOperateHistory history = new OmsOrderOperateHistory(); history.setOrderId(receiverInfoParam.getOrderId()); history.setCreateTime(new Date()); history.setOperateMan("后台管理员"); history.setOrderStatus(receiverInfoParam.getStatus()); history.setNote("修改收货人信息"); orderOperateHistoryMapper.insert(history); return count; } @Override public int updateMoneyInfo(OmsMoneyInfoParam moneyInfoParam) { OmsOrder order = new OmsOrder(); order.setId(moneyInfoParam.getOrderId()); order.setFreightAmount(moneyInfoParam.getFreightAmount()); order.setDiscountAmount(moneyInfoParam.getDiscountAmount()); order.setModifyTime(new Date()); int count = orderMapper.updateByPrimaryKeySelective(order); //插入操作记录 OmsOrderOperateHistory history = new OmsOrderOperateHistory(); history.setOrderId(moneyInfoParam.getOrderId()); history.setCreateTime(new Date()); history.setOperateMan("后台管理员"); history.setOrderStatus(moneyInfoParam.getStatus()); history.setNote("修改费用信息"); orderOperateHistoryMapper.insert(history); return count; } @Override public int updateNote(Long id, String note, Integer status) { OmsOrder order = new OmsOrder(); order.setId(id); order.setNote(note); order.setModifyTime(new Date()); int count = orderMapper.updateByPrimaryKeySelective(order); OmsOrderOperateHistory history = new OmsOrderOperateHistory(); history.setOrderId(id); history.setCreateTime(new Date()); history.setOperateMan("后台管理员"); history.setOrderStatus(status); history.setNote("修改备注信息:"+note); orderOperateHistoryMapper.insert(history); return count; } }
OmsOrder record = new OmsOrder(); record.setDeleteStatus(1); OmsOrderExample example = new OmsOrderExample(); example.createCriteria().andDeleteStatusEqualTo(0).andIdIn(ids); return orderMapper.updateByExampleSelective(record, example);
1,429
77
1,506
<no_super_class>
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/service/impl/OssServiceImpl.java
OssServiceImpl
policy
class OssServiceImpl implements OssService { private static final Logger LOGGER = LoggerFactory.getLogger(OssServiceImpl.class); @Value("${aliyun.oss.policy.expire}") private int ALIYUN_OSS_EXPIRE; @Value("${aliyun.oss.maxSize}") private int ALIYUN_OSS_MAX_SIZE; @Value("${aliyun.oss.callback}") private String ALIYUN_OSS_CALLBACK; @Value("${aliyun.oss.bucketName}") private String ALIYUN_OSS_BUCKET_NAME; @Value("${aliyun.oss.endpoint}") private String ALIYUN_OSS_ENDPOINT; @Value("${aliyun.oss.dir.prefix}") private String ALIYUN_OSS_DIR_PREFIX; @Autowired private OSSClient ossClient; /** * 签名生成 */ @Override public OssPolicyResult policy() {<FILL_FUNCTION_BODY>} @Override public OssCallbackResult callback(HttpServletRequest request) { OssCallbackResult result= new OssCallbackResult(); String filename = request.getParameter("filename"); filename = "http://".concat(ALIYUN_OSS_BUCKET_NAME).concat(".").concat(ALIYUN_OSS_ENDPOINT).concat("/").concat(filename); result.setFilename(filename); result.setSize(request.getParameter("size")); result.setMimeType(request.getParameter("mimeType")); result.setWidth(request.getParameter("width")); result.setHeight(request.getParameter("height")); return result; } }
OssPolicyResult result = new OssPolicyResult(); // 存储目录 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String dir = ALIYUN_OSS_DIR_PREFIX+sdf.format(new Date()); // 签名有效期 long expireEndTime = System.currentTimeMillis() + ALIYUN_OSS_EXPIRE * 1000; Date expiration = new Date(expireEndTime); // 文件大小 long maxSize = ALIYUN_OSS_MAX_SIZE * 1024 * 1024; // 回调 OssCallbackParam callback = new OssCallbackParam(); callback.setCallbackUrl(ALIYUN_OSS_CALLBACK); callback.setCallbackBody("filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}"); callback.setCallbackBodyType("application/x-www-form-urlencoded"); // 提交节点 String action = "http://" + ALIYUN_OSS_BUCKET_NAME + "." + ALIYUN_OSS_ENDPOINT; try { PolicyConditions policyConds = new PolicyConditions(); policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, maxSize); policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir); String postPolicy = ossClient.generatePostPolicy(expiration, policyConds); byte[] binaryData = postPolicy.getBytes("utf-8"); String policy = BinaryUtil.toBase64String(binaryData); String signature = ossClient.calculatePostSignature(postPolicy); String callbackData = BinaryUtil.toBase64String(JSONUtil.parse(callback).toString().getBytes("utf-8")); // 返回结果 result.setAccessKeyId(ossClient.getCredentialsProvider().getCredentials().getAccessKeyId()); result.setPolicy(policy); result.setSignature(signature); result.setDir(dir); result.setCallback(callbackData); result.setHost(action); } catch (Exception e) { LOGGER.error("签名生成失败", e); } return result;
459
626
1,085
<no_super_class>
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/service/impl/PmsBrandServiceImpl.java
PmsBrandServiceImpl
updateShowStatus
class PmsBrandServiceImpl implements PmsBrandService { @Autowired private PmsBrandMapper brandMapper; @Autowired private PmsProductMapper productMapper; @Override public List<PmsBrand> listAllBrand() { return brandMapper.selectByExample(new PmsBrandExample()); } @Override public int createBrand(PmsBrandParam pmsBrandParam) { PmsBrand pmsBrand = new PmsBrand(); BeanUtils.copyProperties(pmsBrandParam, pmsBrand); //如果创建时首字母为空,取名称的第一个为首字母 if (StringUtils.isEmpty(pmsBrand.getFirstLetter())) { pmsBrand.setFirstLetter(pmsBrand.getName().substring(0, 1)); } return brandMapper.insertSelective(pmsBrand); } @Override public int updateBrand(Long id, PmsBrandParam pmsBrandParam) { PmsBrand pmsBrand = new PmsBrand(); BeanUtils.copyProperties(pmsBrandParam, pmsBrand); pmsBrand.setId(id); //如果创建时首字母为空,取名称的第一个为首字母 if (StringUtils.isEmpty(pmsBrand.getFirstLetter())) { pmsBrand.setFirstLetter(pmsBrand.getName().substring(0, 1)); } //更新品牌时要更新商品中的品牌名称 PmsProduct product = new PmsProduct(); product.setBrandName(pmsBrand.getName()); PmsProductExample example = new PmsProductExample(); example.createCriteria().andBrandIdEqualTo(id); productMapper.updateByExampleSelective(product,example); return brandMapper.updateByPrimaryKeySelective(pmsBrand); } @Override public int deleteBrand(Long id) { return brandMapper.deleteByPrimaryKey(id); } @Override public int deleteBrand(List<Long> ids) { PmsBrandExample pmsBrandExample = new PmsBrandExample(); pmsBrandExample.createCriteria().andIdIn(ids); return brandMapper.deleteByExample(pmsBrandExample); } @Override public List<PmsBrand> listBrand(String keyword, int pageNum, int pageSize) { PageHelper.startPage(pageNum, pageSize); PmsBrandExample pmsBrandExample = new PmsBrandExample(); pmsBrandExample.setOrderByClause("sort desc"); PmsBrandExample.Criteria criteria = pmsBrandExample.createCriteria(); if (!StringUtils.isEmpty(keyword)) { criteria.andNameLike("%" + keyword + "%"); } return brandMapper.selectByExample(pmsBrandExample); } @Override public PmsBrand getBrand(Long id) { return brandMapper.selectByPrimaryKey(id); } @Override public int updateShowStatus(List<Long> ids, Integer showStatus) {<FILL_FUNCTION_BODY>} @Override public int updateFactoryStatus(List<Long> ids, Integer factoryStatus) { PmsBrand pmsBrand = new PmsBrand(); pmsBrand.setFactoryStatus(factoryStatus); PmsBrandExample pmsBrandExample = new PmsBrandExample(); pmsBrandExample.createCriteria().andIdIn(ids); return brandMapper.updateByExampleSelective(pmsBrand, pmsBrandExample); } }
PmsBrand pmsBrand = new PmsBrand(); pmsBrand.setShowStatus(showStatus); PmsBrandExample pmsBrandExample = new PmsBrandExample(); pmsBrandExample.createCriteria().andIdIn(ids); return brandMapper.updateByExampleSelective(pmsBrand, pmsBrandExample);
954
95
1,049
<no_super_class>
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/service/impl/PmsProductAttributeCategoryServiceImpl.java
PmsProductAttributeCategoryServiceImpl
update
class PmsProductAttributeCategoryServiceImpl implements PmsProductAttributeCategoryService { @Autowired private PmsProductAttributeCategoryMapper productAttributeCategoryMapper; @Autowired private PmsProductAttributeCategoryDao productAttributeCategoryDao; @Override public int create(String name) { PmsProductAttributeCategory productAttributeCategory = new PmsProductAttributeCategory(); productAttributeCategory.setName(name); return productAttributeCategoryMapper.insertSelective(productAttributeCategory); } @Override public int update(Long id, String name) {<FILL_FUNCTION_BODY>} @Override public int delete(Long id) { return productAttributeCategoryMapper.deleteByPrimaryKey(id); } @Override public PmsProductAttributeCategory getItem(Long id) { return productAttributeCategoryMapper.selectByPrimaryKey(id); } @Override public List<PmsProductAttributeCategory> getList(Integer pageSize, Integer pageNum) { PageHelper.startPage(pageNum,pageSize); return productAttributeCategoryMapper.selectByExample(new PmsProductAttributeCategoryExample()); } @Override public List<PmsProductAttributeCategoryItem> getListWithAttr() { return productAttributeCategoryDao.getListWithAttr(); } }
PmsProductAttributeCategory productAttributeCategory = new PmsProductAttributeCategory(); productAttributeCategory.setName(name); productAttributeCategory.setId(id); return productAttributeCategoryMapper.updateByPrimaryKeySelective(productAttributeCategory);
330
62
392
<no_super_class>
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/service/impl/PmsProductAttributeServiceImpl.java
PmsProductAttributeServiceImpl
create
class PmsProductAttributeServiceImpl implements PmsProductAttributeService { @Autowired private PmsProductAttributeMapper productAttributeMapper; @Autowired private PmsProductAttributeCategoryMapper productAttributeCategoryMapper; @Autowired private PmsProductAttributeDao productAttributeDao; @Override public List<PmsProductAttribute> getList(Long cid, Integer type, Integer pageSize, Integer pageNum) { PageHelper.startPage(pageNum, pageSize); PmsProductAttributeExample example = new PmsProductAttributeExample(); example.setOrderByClause("sort desc"); example.createCriteria().andProductAttributeCategoryIdEqualTo(cid).andTypeEqualTo(type); return productAttributeMapper.selectByExample(example); } @Override public int create(PmsProductAttributeParam pmsProductAttributeParam) {<FILL_FUNCTION_BODY>} @Override public int update(Long id, PmsProductAttributeParam productAttributeParam) { PmsProductAttribute pmsProductAttribute = new PmsProductAttribute(); pmsProductAttribute.setId(id); BeanUtils.copyProperties(productAttributeParam, pmsProductAttribute); return productAttributeMapper.updateByPrimaryKeySelective(pmsProductAttribute); } @Override public PmsProductAttribute getItem(Long id) { return productAttributeMapper.selectByPrimaryKey(id); } @Override public int delete(List<Long> ids) { //获取分类 PmsProductAttribute pmsProductAttribute = productAttributeMapper.selectByPrimaryKey(ids.get(0)); Integer type = pmsProductAttribute.getType(); PmsProductAttributeCategory pmsProductAttributeCategory = productAttributeCategoryMapper.selectByPrimaryKey(pmsProductAttribute.getProductAttributeCategoryId()); PmsProductAttributeExample example = new PmsProductAttributeExample(); example.createCriteria().andIdIn(ids); int count = productAttributeMapper.deleteByExample(example); //删除完成后修改数量 if(type==0){ if(pmsProductAttributeCategory.getAttributeCount()>=count){ pmsProductAttributeCategory.setAttributeCount(pmsProductAttributeCategory.getAttributeCount()-count); }else{ pmsProductAttributeCategory.setAttributeCount(0); } }else if(type==1){ if(pmsProductAttributeCategory.getParamCount()>=count){ pmsProductAttributeCategory.setParamCount(pmsProductAttributeCategory.getParamCount()-count); }else{ pmsProductAttributeCategory.setParamCount(0); } } productAttributeCategoryMapper.updateByPrimaryKey(pmsProductAttributeCategory); return count; } @Override public List<ProductAttrInfo> getProductAttrInfo(Long productCategoryId) { return productAttributeDao.getProductAttrInfo(productCategoryId); } }
PmsProductAttribute pmsProductAttribute = new PmsProductAttribute(); BeanUtils.copyProperties(pmsProductAttributeParam, pmsProductAttribute); int count = productAttributeMapper.insertSelective(pmsProductAttribute); //新增商品属性以后需要更新商品属性分类数量 PmsProductAttributeCategory pmsProductAttributeCategory = productAttributeCategoryMapper.selectByPrimaryKey(pmsProductAttribute.getProductAttributeCategoryId()); if(pmsProductAttribute.getType()==0){ pmsProductAttributeCategory.setAttributeCount(pmsProductAttributeCategory.getAttributeCount()+1); }else if(pmsProductAttribute.getType()==1){ pmsProductAttributeCategory.setParamCount(pmsProductAttributeCategory.getParamCount()+1); } productAttributeCategoryMapper.updateByPrimaryKey(pmsProductAttributeCategory); return count;
727
215
942
<no_super_class>
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/service/impl/PmsProductCategoryServiceImpl.java
PmsProductCategoryServiceImpl
updateShowStatus
class PmsProductCategoryServiceImpl implements PmsProductCategoryService { @Autowired private PmsProductCategoryMapper productCategoryMapper; @Autowired private PmsProductMapper productMapper; @Autowired private PmsProductCategoryAttributeRelationDao productCategoryAttributeRelationDao; @Autowired private PmsProductCategoryAttributeRelationMapper productCategoryAttributeRelationMapper; @Autowired private PmsProductCategoryDao productCategoryDao; @Override public int create(PmsProductCategoryParam pmsProductCategoryParam) { PmsProductCategory productCategory = new PmsProductCategory(); productCategory.setProductCount(0); BeanUtils.copyProperties(pmsProductCategoryParam, productCategory); //没有父分类时为一级分类 setCategoryLevel(productCategory); int count = productCategoryMapper.insertSelective(productCategory); //创建筛选属性关联 List<Long> productAttributeIdList = pmsProductCategoryParam.getProductAttributeIdList(); if(!CollectionUtils.isEmpty(productAttributeIdList)){ insertRelationList(productCategory.getId(), productAttributeIdList); } return count; } /** * 批量插入商品分类与筛选属性关系表 * @param productCategoryId 商品分类id * @param productAttributeIdList 相关商品筛选属性id集合 */ private void insertRelationList(Long productCategoryId, List<Long> productAttributeIdList) { List<PmsProductCategoryAttributeRelation> relationList = new ArrayList<>(); for (Long productAttrId : productAttributeIdList) { PmsProductCategoryAttributeRelation relation = new PmsProductCategoryAttributeRelation(); relation.setProductAttributeId(productAttrId); relation.setProductCategoryId(productCategoryId); relationList.add(relation); } productCategoryAttributeRelationDao.insertList(relationList); } @Override public int update(Long id, PmsProductCategoryParam pmsProductCategoryParam) { PmsProductCategory productCategory = new PmsProductCategory(); productCategory.setId(id); BeanUtils.copyProperties(pmsProductCategoryParam, productCategory); setCategoryLevel(productCategory); //更新商品分类时要更新商品中的名称 PmsProduct product = new PmsProduct(); product.setProductCategoryName(productCategory.getName()); PmsProductExample example = new PmsProductExample(); example.createCriteria().andProductCategoryIdEqualTo(id); productMapper.updateByExampleSelective(product,example); //同时更新筛选属性的信息 if(!CollectionUtils.isEmpty(pmsProductCategoryParam.getProductAttributeIdList())){ PmsProductCategoryAttributeRelationExample relationExample = new PmsProductCategoryAttributeRelationExample(); relationExample.createCriteria().andProductCategoryIdEqualTo(id); productCategoryAttributeRelationMapper.deleteByExample(relationExample); insertRelationList(id,pmsProductCategoryParam.getProductAttributeIdList()); }else{ PmsProductCategoryAttributeRelationExample relationExample = new PmsProductCategoryAttributeRelationExample(); relationExample.createCriteria().andProductCategoryIdEqualTo(id); productCategoryAttributeRelationMapper.deleteByExample(relationExample); } return productCategoryMapper.updateByPrimaryKeySelective(productCategory); } @Override public List<PmsProductCategory> getList(Long parentId, Integer pageSize, Integer pageNum) { PageHelper.startPage(pageNum, pageSize); PmsProductCategoryExample example = new PmsProductCategoryExample(); example.setOrderByClause("sort desc"); example.createCriteria().andParentIdEqualTo(parentId); return productCategoryMapper.selectByExample(example); } @Override public int delete(Long id) { return productCategoryMapper.deleteByPrimaryKey(id); } @Override public PmsProductCategory getItem(Long id) { return productCategoryMapper.selectByPrimaryKey(id); } @Override public int updateNavStatus(List<Long> ids, Integer navStatus) { PmsProductCategory productCategory = new PmsProductCategory(); productCategory.setNavStatus(navStatus); PmsProductCategoryExample example = new PmsProductCategoryExample(); example.createCriteria().andIdIn(ids); return productCategoryMapper.updateByExampleSelective(productCategory, example); } @Override public int updateShowStatus(List<Long> ids, Integer showStatus) {<FILL_FUNCTION_BODY>} @Override public List<PmsProductCategoryWithChildrenItem> listWithChildren() { return productCategoryDao.listWithChildren(); } /** * 根据分类的parentId设置分类的level */ private void setCategoryLevel(PmsProductCategory productCategory) { //没有父分类时为一级分类 if (productCategory.getParentId() == 0) { productCategory.setLevel(0); } else { //有父分类时选择根据父分类level设置 PmsProductCategory parentCategory = productCategoryMapper.selectByPrimaryKey(productCategory.getParentId()); if (parentCategory != null) { productCategory.setLevel(parentCategory.getLevel() + 1); } else { productCategory.setLevel(0); } } } }
PmsProductCategory productCategory = new PmsProductCategory(); productCategory.setShowStatus(showStatus); PmsProductCategoryExample example = new PmsProductCategoryExample(); example.createCriteria().andIdIn(ids); return productCategoryMapper.updateByExampleSelective(productCategory, example);
1,370
78
1,448
<no_super_class>
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/service/impl/PmsSkuStockServiceImpl.java
PmsSkuStockServiceImpl
getList
class PmsSkuStockServiceImpl implements PmsSkuStockService { @Autowired private PmsSkuStockMapper skuStockMapper; @Autowired private PmsSkuStockDao skuStockDao; @Override public List<PmsSkuStock> getList(Long pid, String keyword) {<FILL_FUNCTION_BODY>} @Override public int update(Long pid, List<PmsSkuStock> skuStockList) { return skuStockDao.replaceList(skuStockList); } }
PmsSkuStockExample example = new PmsSkuStockExample(); PmsSkuStockExample.Criteria criteria = example.createCriteria().andProductIdEqualTo(pid); if (!StringUtils.isEmpty(keyword)) { criteria.andSkuCodeLike("%" + keyword + "%"); } return skuStockMapper.selectByExample(example);
158
97
255
<no_super_class>
macrozheng_mall-swarm
mall-swarm/mall-admin/src/main/java/com/macro/mall/service/impl/SmsCouponHistoryServiceImpl.java
SmsCouponHistoryServiceImpl
list
class SmsCouponHistoryServiceImpl implements SmsCouponHistoryService { @Autowired private SmsCouponHistoryMapper historyMapper; @Override public List<SmsCouponHistory> list(Long couponId, Integer useStatus, String orderSn, Integer pageSize, Integer pageNum) {<FILL_FUNCTION_BODY>} }
PageHelper.startPage(pageNum,pageSize); SmsCouponHistoryExample example = new SmsCouponHistoryExample(); SmsCouponHistoryExample.Criteria criteria = example.createCriteria(); if(couponId!=null){ criteria.andCouponIdEqualTo(couponId); } if(useStatus!=null){ criteria.andUseStatusEqualTo(useStatus); } if(!StringUtils.isEmpty(orderSn)){ criteria.andOrderSnEqualTo(orderSn); } return historyMapper.selectByExample(example);
91
153
244
<no_super_class>