Im beginner in JAVA and trying to learn data structure and object conversion. I have below data structure in yaml file.
ingress: {backendServiceName: serv-abc-lc002, cluster_issuer: letsencrypt-oe-dev-001,
ingressClassName: nginx-lc002, tls_acme: 'true'}
route:
hosts:
abcygyPM:
active: false
host: cir11.abc.com
logicalclustername: lc002
offboardtimestamp: null
physicalclustername: oe-dev-001
region: us-east-1
status: Triggered
timestamp: |-
{
"timestamp": "2024-02-05T14:43:18.00847359Z"
}
hXDmziFYnT:
active: false
host: sign.abc.com
logicalclustername: lc002
offboardtimestamp: null
physicalclustername: oe-dev-001
region: us-east-1
status: Triggered
timestamp: |-
{
"timestamp": "2024-02-08T05:45:35.615793284Z"
}
Using snakeyaml library, Im able to load yaml content in POJO
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
InputStream inputStream = new FileInputStream(new File("C:\\Automation\\values.yaml"));
Yaml yamlrm = new Yaml(new Constructor(Values1.class));
Values1 datarm = yamlrm.load(inputStream);
String url = "cir11.abc.com";
Iterator<Entry<String, Host>> iterator = datarm.getRoute().getHosts().entrySet().iterator();
while (iterator.hasNext()) {
if (iterator.next().getValue().getHost().equals(url)) {
<< need to write the code here >> ??
}
}
}
Host.java
public class Host {
private String host;
private String physicalclustername;
private String logicalclustername;
private String status;
@Expose
private String onboardtimestamp;
private String offboardtimestamp;
private boolean active;
<<getter and setter >>
}
Values1.java
public class Values1 {
private Route route;
private Ingress ingress;
<<getter setter >>
}
Route.java
public class Route {
private Map<String, Host> hosts;
<<geter setter>>
}
what Im trying to do is , set the value of field active
to true
if the url
matches to "cir11.abc.com"
I learn about iterator but not able to understand , how can i use Iterator to set the values in array of hashmap
if not through iterator, what is the way to set the values , please suggest
update 1
it is not going in if loop
for (Map.Entry<String, Host> entry : datarm.getRoute().getHosts().entrySet()) {
if (entry.getValue().getHost().equals(url)) {
System.out.println("in loop");
entry.getValue().setActive(true);
}
}
When running through the entries you can just set the active
property:
Iterator<Entry<String, Host>> iterator = datarm.getRoute().getHosts().entrySet().iterator();
while (iterator.hasNext()) {
Host host = iterator.next().getValue().getHost();
if (host.equals(url)) {
host.setActive(true);
}
}
You could optimize your code further by using a for-loop on the map entries instead of the while:
for (Map.Entry<String, Host> entry : datarm.getRoute().getHosts()) {
if (entry.getValue().getHost().equals(url)) {
entry.getValue().setActive(true);
}
}