vid-automation selenium tests
[vid.git] / vid-automation / src / main / java / vid / automation / test / services / DropTestApiField.java
1 package vid.automation.test.services;
2
3 import com.fasterxml.jackson.databind.JsonNode;
4 import com.fasterxml.jackson.databind.ObjectMapper;
5 import com.fasterxml.jackson.databind.node.ObjectNode;
6 import vid.automation.test.infra.Features;
7
8 import java.io.IOException;
9 import java.util.Arrays;
10 import java.util.function.UnaryOperator;
11
12 public class DropTestApiField {
13
14     public static UnaryOperator<String> dropTestApiFieldFromString() {
15         if (Features.FLAG_ADD_MSO_TESTAPI_FIELD.isActive()) {
16             // do nothing
17             return in -> in;
18         } else {
19             final ObjectMapper objectMapper = new ObjectMapper();
20             return in -> {
21                 if (!in.contains("testApi")) {
22                     // short circuit
23                     return in;
24                 }
25
26                 try {
27                     final JsonNode tree = objectMapper.readTree(in);
28                     final JsonNode node = tree.path("simulatorRequest");
29                     if (removePath(node, "body", "requestDetails", "requestParameters", "testApi") != null) {
30                         // tree modified, write back to string
31                         return objectMapper.writeValueAsString(tree);
32                     } else {
33                         // else...
34                         return in;
35                     }
36                 } catch (IOException e) {
37                     return in;
38                 }
39             };
40         }
41     }
42
43     private static JsonNode removePath(JsonNode tree, String... nodes) {
44         // remove the nodes; remove also the parent, if an empty object was left
45         // returns the removed node
46         // returns null if no modification to tree
47         if (nodes.length > 1) {
48             final JsonNode node = tree.path(nodes[0]);
49             final JsonNode removed = removePath(node, Arrays.copyOfRange(nodes, 1, nodes.length));
50             if (removed != null && node.size() == 0) {
51                 return removePath(tree, nodes[0]);
52             } else {
53                 return removed; // non-null if node.size() != 0
54             }
55         } else {
56             if (tree instanceof ObjectNode) {
57                 return ((ObjectNode) tree).remove(nodes[0]);
58             } else {
59                 return null;
60             }
61         }
62     }
63
64 }