yaml工具
import org.yaml.snakeyaml.Yaml;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
-
@Deacription 支持读取${}占位符中的内容
-
@Author levi
-
@Date 2022/06/16 9:43
-
@Version 1.0
**/
public class ReadYmlUtil {// \({} 占位符 正则表达式 private static Pattern p1 = Pattern.compile("\\\)\{.*?\}");
private ReadYmlUtil(){
throw new AssertionError();
}/**
- key:文件索引名
- value:配置文件内容
/
private static Map<String , LinkedHashMap> ymls = new HashMap<>();
/* - String:当前线程需要查询的文件名
*/
private static ThreadLocalnowFileName = new InheritableThreadLocal<>();
private static ThreadLocal
profileLocal = new InheritableThreadLocal<>(); /**
- 主动设置,初始化当前线程的环境
- @param profile
*/
public static void setProfile(String profile) {
profileLocal.set(profile);
}
/**
- 加载配置文件
- @param fileName
*/
private static void loadYml(String fileName){
nowFileName.set(fileName);
if (!ymls.containsKey(fileName)){
ymls.put(fileName , new Yaml().loadAs(ReadYmlUtil.class.getResourceAsStream("/" + fileName),LinkedHashMap.class));
}
}
/**
- 读取yml文件中的某个value。
- 支持解析 yml文件中的 ${} 占位符
- @param key
- @return Object
*/
private static Object getValue(String key){
String[] keys = key.split("[.]");
Map ymlInfo = (Map) ymls.get(nowFileName.get()).clone();
for (int i = 0; i < keys.length; i++) {
Object value = ymlInfo.get(keys[i]);
if (i < keys.length - 1){
ymlInfo = (Map) value;
}else if (value == null){
throw new RuntimeException("key不存在");
}else {
String g;
String keyChild;
String v1 = value+"";
for(Matcher m = p1.matcher(v1); m.find(); value = v1.replace(g, (String)getValue(keyChild))) {
g = m.group();
keyChild = g.replaceAll("\$\{", "").replaceAll("\}", "");
}
return value;
}
}
return "";
}
/**
- 读取yml文件中的某个value
- @param fileName yml名称
- @param key
- @return Object
*/
public static Object getValue(String fileName , String key){
loadYml(fileName);
return getValue(key);
}
/**
- 框架私有方法,非通用。
- 获取 spring.profiles.active的值: test/prod 测试环境/生成环境
- @return
*/
public static String getProfiles(){
if (profileLocal.get() == null) {
String value = (String) getValue("application.yml", "spring.profiles.active");
setProfile(value);
}
return profileLocal.get();
}
/**
- 读取yml文件中的某个value,返回String
- @param fileName
- @param key
- @return String
*/
public static String getValueToString(String fileName , String key){
return (String)getValue(fileName , key);
}
/**
- 获取 application.yml 的配置
- @param key
- @return
*/
public static String getValueToString(String key){
return (String)getValue("application.yml" , key);
}
/**
- 获取 application-test/prod.yml 的配置
- @param key
- @return
*/
public static String getProfileValueToString(String key){
String fileName = "application-" + getProfiles() + ".yml";
return (String)getValue(fileName , key);
}
/**
- Test
- @param args
*/
public static void main(String[] args) {
System.out.println(getProfiles());
System.out.println(ReadYmlUtil.getValueToString("pulsar.topic"));//get application.yml
// System.out.println(ReadYmlUtil.getValueToString("your-yaml-file-name.yml", "key1.key2"));//get other yml
// System.out.println(ReadYmlUtil.getProfileValueToString("Ignite-addr"));// get application-${profile}.yml
// ReadYmlUtil.setProfile("test"); //主动修改环境配置
// System.out.println(ReadYmlUtil.getProfileValueToString("Ignite-addr"));// get application-${profile}.yml
}
}
package com.xx.api;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import java.io.;
import java.nio.file.Files;
import java.util.;
public class YamlApplication {
private static final String EOF_KEY = "$EOF";
public static void main(String[] args) throws IOException {
// assert args.length == 2;
String orginName = "D:\Java_project\xx-git6\xx-api\src\main\resources\config\lizard_sts.yaml";
String updateName = "D:\Java_project\xx-git6\xx-api\src\main\resources\config\lizard_sts_replica.yaml";
// String orginName = args[0];
// String updateName = args[1];
assert orginName != null;
assert updateName != null;
int shellRes = updateYamlFile(orginName, updateName);
System.exit(shellRes);
}
private static int updateYamlFile(String orginName, String updateName) throws IOException {
File orginFile = new File(orginName);
File updateFile = new File(updateName);
DumperOptions dumperOptions = new DumperOptions();
//设置yaml格式 我们常用的那种 DumperOptions.FlowStyle.BLOCK
dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
//设置文本量的输出格式 建议使用 DumperOptions.ScalarStyle.PLAIN(啥都不带,默认值)
dumperOptions.setDefaultScalarStyle(DumperOptions.ScalarStyle.PLAIN);
Yaml yaml = new Yaml(dumperOptions);
Map<String, Object> orgin = yaml.load(new FileInputStream(orginFile));
Map<String, Object> newYaml = yaml.load(new FileInputStream(updateFile));
Map toDump = mergeYamlMap(orgin, newYaml);
File backupFile = getBackupFile(orginFile);
if (backupFile.exists()) {
backupFile.delete();
}
Files.copy(orginFile.toPath(), backupFile.toPath());
File newFile = orginFile;
try (Writer fw = new FileWriter(newFile)) {
yaml.dump(toDump, fw);
}
supplyComment(newFile);
return 0;
}
private static File getBackupFile(File orginFile) {
String orginFileName = orginFile.getName();
int lastIndexOfDot = orginFileName.lastIndexOf(".");
String fileNameNoExtension = orginFileName.substring(0, lastIndexOfDot);
String extension = orginFileName.substring(lastIndexOfDot);
String newName = fileNameNoExtension + "-old333" + extension;
File newFile = new File((orginFile.getParent() == null ? "." : orginFile.getParent()) + File.separator + newName);
return newFile;
}
private static Map<String, Object> mergeYamlMap(Map<String, Object> orginYaml, Map<String, Object> newYaml) {
if (orginYaml == null) {
return newYaml;
}
newYaml.forEach((k, v) -> {
Object oldVal = orginYaml.get(k);
if (oldVal == null) {
orginYaml.put(k, v);
} else if (oldVal instanceof Map) {
mergeYamlMap((Map<String, Object>) oldVal, (Map<String, Object>) v);
}
});
return orginYaml;
}
private static void supplyComment(File meargedFile) throws IOException {
HashMap<String, Stack<String>> commentMap = readComment(getBackupFile(meargedFile));
writeComment(meargedFile, commentMap);
}
private static HashMap<String, Stack<String>> readComment(File file) throws IOException {
String[] lines = readFilesAsLines(file);
HashMap<String, Stack<String>> commentMap = new HashMap<>();
for (int i = 0, linesLength = lines.length; i < linesLength; i++) {
String line = lines[i];
if (line.trim().startsWith("#")) {
Stack<String> stack = commentMap.compute((i == linesLength) ? EOF_KEY : lines[i + 1], (k, v) -> {
if (v == null) {
Stack ns = new Stack<String>();
return ns;
} else {
return v;
}
});
stack.push(line);
}
}
return commentMap;
}
private static void writeComment(File file, HashMap<String, Stack<String>> commentMap) throws IOException {
String[] lines = readFilesAsLines(file);
LinkedList<String> outputList = new LinkedList<String>();
int linesLength = lines.length;
Stack<String> eofComment = commentMap.remove(EOF_KEY);
if (eofComment != null) {
eofComment.forEach(outputList::addFirst);
}
for (int i = linesLength - 1; i >= 0; i--) {
String line = lines[i];
while (line != null) {
outputList.addFirst(line);
Stack<String> stack = commentMap.get(line);
if (stack == null) {
break;
}
if (stack.size() == 1) {
commentMap.remove(line);
}
line = stack.pop();
}
}
try (Writer bw = new BufferedWriter(new FileWriter(file))) {
outputList.forEach(line -> {
try {
bw.append(line).append('\n');
} catch (IOException e) {
e.printStackTrace();
}
});
bw.flush();
}
}
private static String[] readFilesAsLines(File file) throws IOException {
FileReader fileReader = new FileReader(file);
//注意!!流只能用一次,第二次是个空的流了!!
try (BufferedReader br = new BufferedReader(fileReader)) {
String[] lines = br.lines().toArray(String[]::new);
return lines;
}
}
}
package com.xx.api;
import lombok.SneakyThrows;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.util.*;
class YamlConfigs {
private final static DumperOptions OPTIONS = new DumperOptions();
// 重新生成yaml文件,原yaml文件中的注释会消失。
static {
//设置yaml读取方式为块读取
OPTIONS.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
OPTIONS.setDefaultScalarStyle(DumperOptions.ScalarStyle.PLAIN);
OPTIONS.setPrettyFlow(false);
}
public static void main(String[] args) {
String fileName = "D:\\Java_project\\xx-git6\\xx-api\\src\\main\\resources\\config\\lizard_sts.yaml";
String key = "spec.template.spec.containers.command";
List<String> list = new ArrayList<>();
list.add("/bin/sh");
list.add("-ce");
list.add("java -jar lizardTESTSMIAODS.jar");
boolean flag = updateYaml(key, list, fileName);
}
/**
* 将Yaml配置文件转换成map
*
* @param fileName
* @return
*/
public static Map<String, Object> getYamlToMap(String fileName) {
LinkedHashMap<String, Object> yamls = new LinkedHashMap<>();
Yaml yaml = new Yaml();
try {
InputStream inputStream = new FileInputStream(fileName);
yamls = yaml.loadAs(inputStream, LinkedHashMap.class);
} catch (Exception e) {
e.printStackTrace();
}
return yamls;
}
/**
* 根据key获取yaml文件中属性值
*
* @param key
* @param yamlMap
* @return
*/
public static Object getValue(String key, Map<String, Object> yamlMap) {
String[] keys = key.split("[.]");
Object obj = yamlMap.get(keys[0]);
if (key.contains(".")) {
if (obj instanceof Map) {
return getValue(key.substring(key.indexOf(".") + 1), (Map<String, Object>) obj);
} else if (obj instanceof List) {
// return getValue(key.substring(key.indexOf(".") + 1), ((List<?>) obj).get(0));
} else {
return null;
}
}
return obj;
}
/**
* 使用递归的方式更改map中的值
*
* @param map
* @param key 指定哪个键
* @param value 即将更改的值
* @return
*/
@SneakyThrows
public static Map<String, Object> setValue(Map<String, Object> map, String key, Object value) {
String[] keys = key.split("\\.");
int len = keys.length;
Map temp = map;
for (int i = 0; i < len - 1; i++) {
if (temp.containsKey(keys[i])) {
Object obj = temp.get(keys[i]);
if (obj instanceof Map) {
temp = (Map) obj;
} else if (obj instanceof List) {
// temp = ((List<?>) obj).get(0);
} else {
throw new Exception("temp类型错误");
}
} else {
return null;
}
if (i == len - 2) {
temp.put(keys[i + 1], value);
}
}
for (int j = 0; j < len - 1; j++) {
if (j == len - 1) {
map.put(keys[j], temp);
}
}
return map;
}
/**
* 修改yaml中属性的值
*
* @param key key是properties的方式: aaa.bbb.ccc (key不存在不修改)
* @param value 新的属性值 (新属性值和旧属性值一样,不修改)
* @param yamlName
* @return true 修改成功,false 修改失败
*/
public static boolean updateYaml(String key, Object value, String yamlName) {
Map<String, Object> yamlToMap = getYamlToMap(yamlName);
if (null == yamlToMap) {
return false;
}
// Object oldVal = getValue(key, yamlToMap);
//
// // 未找到key,不修改
// if (null == oldVal) {
// System.out.println("key is not found!");
// return false;
// }
//
// // 不是最小节点值,不修改
// if (oldVal instanceof Map) {
// System.out.println("input key is not last node!");
// return false;
// }
//
// if (value == oldVal) {
// System.out.println("newVal equals oldVal!");
// return false;
// }
// Yaml yaml = new Yaml(OPTIONS);
Yaml yaml = new Yaml(OPTIONS);
String path = "D:\Java_project\xx-git6\xx-api\src\main\resources\config\lizard_sts_replica.yaml";
try {
// Map<String, Object> resultMap = setValue(yamlToMap, key, value);
if (yamlToMap != null) {
yaml.dump(yamlToMap, new FileWriter(path));
// yaml.dumpAll((Iterator<? extends Object>) yamlToMap, new FileWriter(path));
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
package com.xx.api;
import org.yaml.snakeyaml.Yaml;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
/**
-
@Author: liyue
-
@Date: 2021/11/23/14:21
-
@Description:
*/
public class YamlUtil {public static void main(String[] args) throws Exception {
Yaml yaml = new Yaml();
String path = "D:\Java_project\xx-git6\xx-api\src\main\resources\test.yaml";
InputStream in = new FileInputStream(path);
Map<String, Object> map = yaml.loadAs(in, Map.class);
System.out.println(get(map, "spec|:template|:spec|-0_containers|:image"));modify(map, "spec|:template|:spec|-0_containers|:image","11111msdd"); System.out.println(get(map, "spec|:template|:spec|-0_containers|:image")); System.out.println(yaml.dump(map));}
public static Map<String, Object> load(String path) {
try {
Yaml yaml = new Yaml();
InputStream in = new FileInputStream(path);
Map<String, Object> map = yaml.loadAs(in, Map.class);
return map;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}private static Object get(Map<String, Object> map, String key) {
if (key.contains("|")) {
String[] ks = key.split("[|]");
String ck;
Map<String, Object> v = (Map<String, Object>) map.get(ks[0]);
for (int i = 1; i < ks.length; i++) {
ck = ks[i];
String type = ck.substring(0, 1);
if (type.equals("😊) {
String k = ck.substring(1);
if (i == ks.length - 1) {
return v.get(k);
} else {
try {
v = (Map<String, Object>) v.get(k);
} catch (Exception e) {
System.out.println();
}
}
} else if (type.equals("-")) {
String[] strings = ck.substring(1).split("_");
String index = strings[0];
String k = strings[1];
List<Map<String, Object>> list = (List<Map<String, Object>>) v.get(k);
Map<String, Object> val = list.get(Integer.parseInt(index));
if (i == ks.length - 1) {
return val.get(k);
} else {
v = list.get(Integer.parseInt(index));
}
}
}
} else {
return map.get(key);
}
return null;
}private static void modify(Map<String, Object> map, String key, String value) {
if (key.contains("|")) {
String[] ks = key.split("[|]");
String ck;
Map<String, Object> v = (Map<String, Object>) map.get(ks[0]);
for (int i = 1; i < ks.length; i++) {
ck = ks[i];
String type = ck.substring(0, 1);
if (type.equals("😊) {
String k = ck.substring(1);
if (i == ks.length - 1) {
v.put(k, value);
} else {
v = (Map<String, Object>) v.get(k);
}
} else if (type.equals("-")) {
String[] strings = ck.substring(1).split("_");
String index = strings[0];
String k = strings[1];
List<Map<String, Object>> list = (List<Map<String, Object>>) v.get(k);
Map<String, Object> val = list.get(Integer.parseInt(index));
if (i == ks.length - 1) {
val.put(k, value);
} else {
v = list.get(Integer.parseInt(index));
}
}
}
} else {
map.put(key, value);
}
}
}
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: lizard
spec:
replicas: 1
selector:
matchLabels:
app: lizard
serviceName: lizard
template:
metadata:
labels:
app: lizard
spec:
containers:
- name: lizard
image: lizard:1.2
ports:
- containerPort: 30001
command:
- /bin/sh
- -ce
- tail -f /dev/null
volumeMounts:
- name: lizard
mountPath: /lizard/
volumes:
- name: lizard
hostPath:
path: /root/lizard/sadfsadfasmiao
-------------------------------------------
个性签名:独学而无友,则孤陋而寡闻,做一个灵魂有趣的人!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!
浙公网安备 33010602011771号