简体   繁体   中英

Check if regex pattern matches with another property value

I have the following two JSON objects:


{
  "policies" : [
     {
        "vhost": "/",
        "name": "Policy-1",
        "pattern": "^queue\\.number\\.1",
        "apply-to": "queues",
        "definition": {
          "message-ttl": 60000
        },
        "priority": 0
      }
  ],
  "queues" : [
    {
      "name" : "queue.number.1",
       "vhost": "/",
       "durable": true,
        "auto_delete": false,
        "arguments": {       
        }
    }
  ]
}    

Now the problem is the following:

I have a list of policies, for which I have to check for the pattern property (which is a regex) if it matches to any of the queues name. If there is no match between a policy's pattern and the queue name, false should be returned (this indicates that all policies that are defined in the list should have a match with the pattern).

The pattern is meant to represent the queue's name.

Any suggestions on how to solve it?

You can try library Josson to do the job.

https://github.com/octomix/josson

Deserialization

Josson josson = Josson.fromJsonString(
    "{" +
    "  \"policies\" : [" +
    "    {" +
    "       \"vhost\": \"/\"," +
    "       \"name\": \"Policy-1\"," +
    "       \"pattern\": \"^queue.number.1\"," +
    "       \"apply-to\": \"queues\"," +
    "       \"definition\": {" +
    "         \"message-ttl\": 60000" +
    "       }," +
    "       \"priority\": 0" +
    "    }," +
    "    {" +
    "       \"name\": \"Policy-2\"," +
    "       \"pattern\": \"^queue.xyz.1\"" +
    "    }," +
    "    {" +
    "       \"name\": \"Policy-3\"," +
    "       \"pattern\": \"^queue.number.2\"" +
    "    }" +
    "  ]," +
    "  \"queues\" : [" +
    "    {" +
    "      \"name\" : \"queue.number.1\"," +
    "      \"vhost\": \"/\"," +
    "      \"durable\": true," +
    "      \"auto_delete\": false," +
    "      \"arguments\": {}" +
    "    }," +
    "    {" +
    "      \"name\" : \"queue.number.2\"" +
    "    }" +
    "  ]" +
    "}");

Query

For each policy object, set a variable $p to store the pattern and then apply a validation filter [] to check whether the queues from the root $. do not contain a name matches =~ the $p pattern.

JsonNode noMatchPolicies = josson.getNode(
    "policies@.let($p:pattern).[$.queues[name =~ $p] = null]");
boolean result = noMatchPolicies.isEmpty();
System.out.println("Result: " + result);
System.out.println(noMatchPolicies.toPrettyString());

Output

Result: false
[ {
  "name" : "Policy-2",
  "pattern" : "^queue.xyz.1"
} ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM