依赖:
<!-- velocity -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
工具类:
package com.yunphant.iie.utils;
import com.yunphant.iie.networkSimulation.dto.NetworkYamlDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
@Slf4j
public class YamlUtils {
/**
* 根据文件路径读取文件内容
* @param filePath
* @return
*/
public static String readFile(String filePath) {
StringBuilder result = new StringBuilder();
try {
// BufferedReader bfr = new BufferedReader(new FileReader(new File(filePath)));
BufferedReader bfr = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filePath)), "UTF-8"));
String lineTxt = null;
while ((lineTxt = bfr.readLine()) != null) {
result.append(lineTxt).append("\n");
}
bfr.close();
} catch (Exception e) {
e.printStackTrace();
}
return result.toString();
}
/**
* 创建 Network yaml
* @param dto 模版所需实体类
* @param templatePath 模版路径
* @param saveFliePath 模版保存路径
* @return
*/
public static Map<String,Object> creatyNetworkYaml(NetworkYamlDTO dto, String templatePath,String saveFliePath) {
//初始化配置
Template template = getVelocityEngine(templatePath);
//定义替换规则
VelocityContext context = new VelocityContext();
Map<String, Object> stringObjectMap = EntityMapTransUtils.entityToMap1(dto);
for (Map.Entry<String, Object> entry : stringObjectMap.entrySet()) {
if (Objects.nonNull(entry.getValue())){
context.put(entry.getKey(),entry.getValue());
}
}
//存储合并后的结果
StringWriter sw = new StringWriter();
template.merge(context,sw);
Path savePath = Paths.get(saveFliePath, dto.getPumbaName() + ".yaml");
File createFilePath = new File(savePath.toUri());
try {
String filePath = writeTemplateToNewFile(createFilePath, sw);
log.info("文件存储路径:{}",filePath);
String r = sw.toString();
// log.info("##r: \n" +r);
HashMap<String, Object> map = new HashMap<>();
map.put("filePath",filePath);
map.put("script",r);
return map;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* 创建模版文件 返回文件路径
* @param createFilePath
* @param assignedValueTemplate
* @return
* @throws IOException
*/
private static String writeTemplateToNewFile(File createFilePath, StringWriter assignedValueTemplate) throws IOException {
FileWriter fileWriter = new FileWriter(createFilePath);
fileWriter.append(assignedValueTemplate.toString());
fileWriter.flush();
fileWriter.close();
return createFilePath.getAbsolutePath();
}
/**
* 初始化 模版配置
* @return
*/
private static Template getVelocityEngine(String templatePath) {
Properties props = new Properties();
props.setProperty(Velocity.ENCODING_DEFAULT, "GBK");//全局编码,如果以下编码不设置它就生效
props.setProperty(Velocity.INPUT_ENCODING, "UTF-8");//输入流的编码,其实是打酱油!非模板文件编码
props.setProperty(Velocity.OUTPUT_ENCODING, "GBK");//输入流编码,很关键!
props.setProperty(VelocityEngine.RESOURCE_LOADER,"file");//模板文件加载方式
VelocityEngine ve = new VelocityEngine(props);
//设置资源路径
ve.setProperty(RuntimeConstants.RESOURCE_LOADER,"classpath");
ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
//初始化
ve.init();
return ve.getTemplate(templatePath);
}
}