I am reading a YAML file, converting it to an object, update part of this object with new data, convert it back to YAML and write this into a file.
This is part of my code that does this update and writing back the object into the YAML file:
File repoDir = new File("/Users/somePath");
File targetFile = new File(repoDir, filePath);
Yaml yaml = new Yaml();
DeploymentHelmValuesConfig deploymentHelmValuesConfig = yaml.loadAs(new FileReader(targetFile), DeploymentHelmValuesConfig.class);
HelmConfig targetHelmConfig = new HelmConfig();
targetHelmConfig.setName("hero_oswald_comp");
targetHelmConfig.setVersion("0.1.0");
targetHelmConfig.setProtocol("http");
targetHelmConfig.setRuntime("custom");
ResourceParams resourceParams = new ResourceParams("12","25Gi",250);
targetHelmConfig.setResources(resourceParams);
Optional<Map.Entry<String, HelmConfig>> modelDetails = deploymentHelmValuesConfig.getModels().entrySet().stream()
.filter(e-> e.getValue().getName().equals(targetHelmConfig.getName())
&& e.getValue().getVersion().equals(targetHelmConfig.getVersion())).findFirst();
System.out.println("config map - "+modelDetails);
if(modelDetails.isPresent()) {
HelmConfig config = modelDetails.get().getValue();
config.setResources(targetHelmConfig.getResources() !=null? targetHelmConfig.getResources() : config.getResources());
config.setProtocol(targetHelmConfig.getProtocol()!=null? targetHelmConfig.getProtocol() : config.getProtocol());
config.setRuntime(targetHelmConfig.getRuntime()!=null? targetHelmConfig.getRuntime() : config.getRuntime());
deploymentHelmValuesConfig.getModels().put(modelDetails.get().getKey(), config);
}
DumperOptions options = new DumperOptions();
options.setIndent(4);
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
options.setIndentWithIndicator(true);
options.setPrettyFlow(true);
Representer representer = new Representer(options);
representer.addClassTag(DeploymentHelmValuesConfig.class, Tag.MAP);
Yaml outputYaml = new Yaml(representer, options);
try (FileWriter writer = new FileWriter(targetFile)) {
outputYaml.dump(deploymentHelmValuesConfig, writer);
}
After it is written, I see that the order of the fields are mixed and the original order is not preserved. This is the output:
account: prod
base:
app_name: default
image:
repo: default
tag: latest
env: sandbox
models:
da54c1623aec72ef:
name: echo
protocol: http
resources:
cpu: '4'
memory: 4Gi
replicaCount: 3
runtime: custom
version: 0.1.0
But the original order is:
account: prod
base:
app_name: default
image:
repo: default
tag: latest
env: sandbox
region: us-east-2
models:
da54c1623aec72ef:
name: echo
version: 0.1.0
runtime: custom
protocol: http
resources:
cpu: "4"
memory: 4Gi
replicaCount: 3
How can I preserve the order of the fields here? Is there an alternative to using snakeYaml to achieve this?
This is my gradle dependency I am consuming:
implementation '.yaml:snakeyaml:2.0'