yaml解析

  • test测试类
package proxy;

import com.example.util.YmlUtil;
import com.example.yaml.ConstantEnum;
import com.example.yaml.ParseYamlMap;
import com.example.yaml.YamlParserUtil;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Author zhangwen
 * @Date 2022/1/16 13:22
 * @Version 1.0
 */
public class YamlTest {

    private final static DumperOptions OPTIONS = new DumperOptions();

    static {
        //将默认读取的方式设置为块状读取
        OPTIONS.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
    }


    @Test
    public void test1() {
        //加两个attr节点下属性,删addd属性
        String oldContent = "nacos:\n" +
                "  dg: 889990\n" +
                "  addd: 444\n" +
                "spring:\n" +
                "  redis:\n" +
                "    path: 3344\n";
        String newContent = "nacos:\n" +
                "  dg: 889990\n" +
                "spring:\n" +
                "  redis:\n" +
                "    path: 4444\n" +
                "    attr:\n" +
                "      name: 3333\n" +
                "      value: 4444";

        Yaml yaml = new Yaml();
        List<String> addAttr = YamlParserUtil.compareAndGetDiffAttr(oldContent, newContent, ConstantEnum.ADD);
        List<String> removeAttr = YamlParserUtil.compareAndGetDiffAttr(oldContent, newContent, ConstantEnum.REMOVE);
        Map<String, Object> addMap = (Map<String, Object>) YamlParserUtil.transListToLinkMap(addAttr);
        Map<String, Object> removeMap = (Map<String, Object>) YamlParserUtil.transListToLinkMap(removeAttr);

        Map originMap = yaml.loadAs(oldContent, Map.class);
        YamlParserUtil.addAndRemoveYaml(originMap, removeMap, addMap);
        String dump = yaml.dumpAsMap(originMap);
        System.out.println(dump);
    }

    /**
     * @author yichuan@iscas.ac.cn
     * yml编辑工具测试类
     * @version 1.0
     * @date 2020/11/14 17:11
     */
    @Test
    public void test2() throws IOException, URISyntaxException {

        /**
         * 这里修改的是target目录编译后的路径,所以运行调试时。src目录下不会变
         */
        File yml = new File("E:\\application.yml");
        //不管执行什么操作一定要先执行这个
        YmlUtil.setYmlFile(yml);
        System.out.println(YmlUtil.getByKey("heart.agentId"));
        System.out.println("aaaaaa");
        YmlUtil.saveOrUpdateByKey("heart.agentId", "哈哈哈哈");
//        YmlUtil.removeByKey("heart.agentId");
    }

    @Test
    public void test3() {
        /**
         * 这里修改的是target目录编译后的路径,所以运行调试时。src目录下不会变
         */
        File yml = new File("E:\\application.yml");
        //不管执行什么操作一定要先执行这个
        try {
            YmlUtil.setYmlFile(yml);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        File sourceFile = new File("E:\\application.yml");
        File changeFile = new File("E:\\application2.yml");
        Yaml yaml = new Yaml(OPTIONS);
        try {
            Map<String, Object> sourceMap = yaml.load(new FileInputStream(sourceFile));
            Map<String, Object> sourceKeyMap = ParseYamlMap.parseYamlToMap(sourceMap, null, new HashMap<>());

            Map<String, Object> changeMap = yaml.load(new FileInputStream(changeFile));
            Map<String, Object> changeKeyMap = ParseYamlMap.parseYamlToMap(changeMap, null, new HashMap<>());

            System.out.println("sourceKeyMap=  " + sourceKeyMap);
            System.out.println("changeKeyMap=  " + changeKeyMap);

            for (Map.Entry<String, Object> changeEntry : changeKeyMap.entrySet()) {
                for (Map.Entry<String, Object> sourceEntry : sourceKeyMap.entrySet()) {
                    System.out.println("changeEntry.getKey()= " + changeEntry.getKey() + " ; sourceEntry.getKey()= " + sourceEntry.getKey());
                    if (StringUtils.equals(changeEntry.getKey(), sourceEntry.getKey())) {
                        System.out.println("butong");
                        YmlUtil.saveOrUpdateByKey(changeEntry.getKey(), changeEntry.getValue());
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

工具类:

package com.example.yaml;

import com.sun.org.apache.regexp.internal.RE;
import org.ehcache.core.internal.util.CollectionUtil;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Author zhangwen
 * @Date 2022/1/16 14:36
 * @Version 1.0
 */
public class ParseYamlMap {

    private static final Map<String, String> cacheYamlMap = new HashMap<>();

    /**
     * {spring={redis={host=},rabbit={host=}}} to {spring.redis.host= ,spring.rabbit.host=}
     * <p>
     * trans yaml map to key map
     *
     * @param item
     * @param key
     */
    public static Map<String, Object> parseYamlToMap(Map<String, Object> item, String key, Map<String, Object> outPutMap) {
        if (CollectionUtils.isEmpty(item)) {
            return new HashMap<String, Object>();
        }
        item.forEach((k, v) -> {
            if (Objects.isNull(v)) {
                if (key == null) {
                    outPutMap.put(k, "");
                } else {
                    outPutMap.put(key.concat(".").concat(k), "");
                }
            } else if (v instanceof LinkedHashMap) {
                if (key == null) {
                    parseYamlToMap((Map<String, Object>) v, k, outPutMap);
                } else {
                    parseYamlToMap((Map<String, Object>) v, key.concat(".").concat(k), outPutMap);
                }
            } else if (key == null) {
                outPutMap.put(k, v.toString());
            } else {
                outPutMap.put(key.concat(".").concat(k), v.toString());
            }
        });
        return outPutMap;
    }


}

package com.example.util;

import com.example.yaml.ParseYamlMap;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;

import java.io.*;
import java.util.*;

/**
 * @author yichuan@iscas.ac.cn
 * 修改YmL文件的工具类
 * @version 1.0
 * @date 2020/11/14 17:01
 */
public class YmlUtil {
    private final static DumperOptions OPTIONS = new DumperOptions();

    private static File file;

    private static InputStream ymlInputSteam;

    private static Object CONFIG_MAP;

    private static Yaml yaml;

    static {
        //将默认读取的方式设置为块状读取
        OPTIONS.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
    }

    /**
     * 使用其他方法之前必须调用一次 设置yml的输出文件,当没有设置输入流时可以不设置输入流,默认以此文件读入
     *
     * @param file 输出的文件
     */
    public static void setYmlFile(File file) throws FileNotFoundException {
        YmlUtil.file = file;
        if (ymlInputSteam == null) {
            setYmlInputSteam(new FileInputStream(file));
        }
    }


    /**
     * 使用其他方法之前必须调用一次 设置yml的输入流
     *
     * @param inputSteam 输入流
     */
    public static void setYmlInputSteam(InputStream inputSteam) {
        ymlInputSteam = inputSteam;
        yaml = new Yaml(OPTIONS);
        CONFIG_MAP = yaml.load(ymlInputSteam);
    }

    /**
     * 根据键获取值
     *
     * @param key 键
     * @return 查询到的值
     */
    @SuppressWarnings("unchecked")
    public static Object getByKey(String key) {
        if (ymlInputSteam == null) {
            return null;
        }
        String[] keys = key.split("\\.");
        Object configMap = CONFIG_MAP;
        for (String s : keys) {
            if (configMap instanceof Map) {
                configMap = ((Map<String, Object>) configMap).get(s);
            } else {
                break;
            }
        }
        Map hashMap = ParseYamlMap.parseYamlToMap((Map<String, Object>) CONFIG_MAP, null, new HashMap<>());
        System.out.println("cacheYamlMap= " + hashMap);
        return configMap == null ? "" : configMap;
    }

    public static void saveOrUpdateByKey(String key, Object value) throws IOException {
        KeyAndMap keyAndMap = new KeyAndMap(key).invoke();
        key = keyAndMap.getKey();
        Map<String, Object> map = keyAndMap.getMap();
        System.out.println("key= "+ key);
        map.put(key, value);
        //将数据重新写回文件
        yaml.dump(CONFIG_MAP, new FileWriter(file));
    }

    public static void removeByKey(String key) throws Exception {
        KeyAndMap keyAndMap = new KeyAndMap(key).invoke();
        key = keyAndMap.getKey();
        Map<String, Object> map = keyAndMap.getMap();
        Map<String, Object> fatherMap = keyAndMap.getFatherMap();
        map.remove(key);
        if (map.size() == 0) {
            Set<Map.Entry<String, Object>> entries = fatherMap.entrySet();
            for (Map.Entry<String, Object> entry : entries) {
                if (entry.getValue() == map) {
                    fatherMap.remove(entry.getKey());
                }
            }
        }
        yaml.dump(CONFIG_MAP, new FileWriter(file));
    }


    private static class KeyAndMap {
        private String key;
        private Map<String, Object> map;
        private Map<String, Object> fatherMap;

        public KeyAndMap(String key) {
            this.key = key;
        }

        public String getKey() {
            return key;
        }

        public Map<String, Object> getMap() {
            return map;
        }

        public Map<String, Object> getFatherMap() {
            return fatherMap;
        }

        @SuppressWarnings("unchecked")
        public KeyAndMap invoke() {
            if (file == null) {
                System.err.println("请设置文件路径");
            }
            if (null == CONFIG_MAP) {
                CONFIG_MAP = new LinkedHashMap<>();
            }
            String[] keys = key.split("\\.");
            key = keys[keys.length - 1];
            map = (Map<String, Object>) CONFIG_MAP;
            for (int i = 0; i < keys.length - 1; i++) {
                String s = keys[i];
                if (map.get(s) == null || !(map.get(s) instanceof Map)) {
                    map.put(s, new HashMap<>(4));
                }
                fatherMap = map;
                map = (Map<String, Object>) map.get(s);
            }
            return this;
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值