Java 常用工具类(30) : YamlUtil

Java 常用工具类(30) : YamlUtil,第1张

Java 常用工具类(30) : YamlUtil
import org.yaml.snakeyaml.Yaml;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Map;


public class YamlUtil {

    public static void main(String[] args) throws Exception {
        Yaml yaml = new Yaml();
        String path = "/Users/test/test.yaml";
        InputStream in = new FileInputStream(path);
        Map 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","11111");
        System.out.println(get(map, "spec|:template|:spec|-0_containers|:image"));
        System.out.println(yaml.dump(map));
    }

    public static Map load(String path) {
        try {
            Yaml yaml = new Yaml();
            InputStream in = new FileInputStream(path);
            Map map = yaml.loadAs(in, Map.class);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    private static Object get(Map map, String key) {
        if (key.contains("|")) {
            String[] ks = key.split("[|]");
            String ck;
            Map v = (Map) 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) 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> list = (List>) v.get(k);
                    Map 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 map, String key, String value) {
        if (key.contains("|")) {
            String[] ks = key.split("[|]");
            String ck;
            Map v = (Map) 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) v.get(k);
                    }
                } else if (type.equals("-")) {
                    String[] strings = ck.substring(1).split("_");
                    String index = strings[0];
                    String k = strings[1];
                    List> list = (List>) v.get(k);
                    Map 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);
        }
    }

}

maven

        
            org.yaml
            snakeyaml
            1.27
        

 

YAML文件 

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  annotations:
    deployment.kubernetes.io/revision: "4"
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"apps/v1","kind":"Deployment","metadata":{"annotations":{},"name":"test","namespace":"test-ns"},"spec":{"replicas":1,"selector":{"matchLabels":{"app":"test"}},"template":{"metadata":{"labels":{"app":"test"}},"spec":{"containers":[{"image":"127.0.0.1:4000/library/test:2.3","name":"test","ports":[{"containerPort":7999,"protocol":"TCP"}]}],"imagePullSecrets":[{"name":"myregistrykey"}]}}}}
  creationTimestamp: "2021-11-21T04:08:28Z"
  generation: 4
  name: test
  namespace: test-ns
  resourceVersion: "3855313"
  selflink: /apis/extensions/v1beta1/namespaces/test-ns/deployments/test
  uid: adcf4929-8d4c-49e1-a132-8ef3a032f2aa
spec:
  progressDeadlineSeconds: 600
  replicas: 1
  revisionHistoryLimit: 10
  selector:
    matchLabels:
      app: test
  strategy:
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 25%
    type: RollingUpdate
  template:
    metadata:
      annotations:
        kubesphere.io/restartedAt: "2021-11-22T10:06:33.546Z"
      creationTimestamp: null
      labels:
        app: test
    spec:
      containers:
      - image: 127.0.0.1:4000/library/test:2.3
        imagePullPolicy: IfNotPresent
        name: test
        ports:
        - containerPort: 7999
          protocol: TCP
        resources: {}
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
      dnsPolicy: ClusterFirst
      imagePullSecrets:
      - name: myregistrykey
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext: {}
      terminationGracePeriodSeconds: 30
status:
  availableReplicas: 1
  conditions:
  - lastTransitionTime: "2021-11-22T10:07:05Z"
    lastUpdateTime: "2021-11-22T10:07:05Z"
    message: Deployment has minimum availability.
    reason: MinimumReplicasAvailable
    status: "True"
    type: Available
  - lastTransitionTime: "2021-11-21T04:08:52Z"
    lastUpdateTime: "2021-11-23T03:28:22Z"
    message: ReplicaSet "test-6d6998b97c" has successfully progressed.
    reason: NewReplicaSetAvailable
    status: "True"
    type: Progressing
  observedGeneration: 4
  readyReplicas: 1
  replicas: 1
  updatedReplicas: 1

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5637574.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存