001/** 002 * Copyright (c) 2025-2026, Michael Yang 杨福海 (fuhai999@gmail.com). 003 * <p> 004 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * <p> 008 * http://www.gnu.org/licenses/lgpl-3.0.txt 009 * <p> 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package dev.tinyflow.core.node; 017 018import com.jfinal.template.Engine; 019import com.jfinal.template.Template; 020import dev.tinyflow.core.chain.Chain; 021import dev.tinyflow.core.chain.Parameter; 022import dev.tinyflow.core.util.Maps; 023import dev.tinyflow.core.util.StringUtil; 024 025import java.io.ByteArrayOutputStream; 026import java.util.List; 027import java.util.Map; 028 029public class TemplateNode extends BaseNode { 030 031 private static final Engine engine; 032 private String template; 033 034 static { 035 engine = Engine.create("template", e -> { 036 e.addSharedStaticMethod(StringUtil.class); 037 }); 038 } 039 040 public String getTemplate() { 041 return template; 042 } 043 044 public void setTemplate(String template) { 045 this.template = template; 046 } 047 048 049 @Override 050 public Map<String, Object> execute(Chain chain) { 051 Map<String, Object> parameters = chain.getState().resolveParameters(this); 052 053 ByteArrayOutputStream result = new ByteArrayOutputStream(); 054 055 Template templateByString = engine.getTemplateByString(template); 056 templateByString.render(parameters, result); 057 058 String outputDef = "output"; 059 List<Parameter> outputDefs = getOutputDefs(); 060 if (outputDefs != null && !outputDefs.isEmpty()) { 061 String parameterName = outputDefs.get(0).getName(); 062 if (StringUtil.hasText(parameterName)) outputDef = parameterName; 063 } 064 065 return Maps.of(outputDef, result.toString()); 066 } 067 068 069 @Override 070 public String toString() { 071 return "TemplateNode{" + 072 "template='" + template + '\'' + 073 ", parameters=" + parameters + 074 ", outputDefs=" + outputDefs + 075 ", id='" + id + '\'' + 076 ", name='" + name + '\'' + 077 ", description='" + description + '\'' + 078 ", condition=" + condition + 079 ", validator=" + validator + 080 ", loopEnable=" + loopEnable + 081 ", loopIntervalMs=" + loopIntervalMs + 082 ", loopBreakCondition=" + loopBreakCondition + 083 ", maxLoopCount=" + maxLoopCount + 084 ", retryEnable=" + retryEnable + 085 ", resetRetryCountAfterNormal=" + resetRetryCountAfterNormal + 086 ", maxRetryCount=" + maxRetryCount + 087 ", retryIntervalMs=" + retryIntervalMs + 088 ", computeCostExpr='" + computeCostExpr + '\'' + 089 '}'; 090 } 091}