NormalizedNode serialization using protocol buffer
[controller.git] / opendaylight / md-sal / sal-protocolbuffer-encoding / src / main / java / org / opendaylight / controller / cluster / datastore / node / utils / NodeIdentifierWithPredicatesGenerator.java
1 package org.opendaylight.controller.cluster.datastore.node.utils;
2
3 import org.opendaylight.yangtools.yang.common.QName;
4 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
5 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
6 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
7 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
8 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
9
10 import java.util.HashMap;
11 import java.util.Map;
12 import java.util.regex.Matcher;
13 import java.util.regex.Pattern;
14
15 public class NodeIdentifierWithPredicatesGenerator{
16     private final String id;
17     private static final Pattern pattern = Pattern.compile("(.*)\\Q[{\\E(.*)\\Q}]\\E");
18     private final Matcher matcher;
19     private final boolean doesMatch;
20     private final ListSchemaNode listSchemaNode;
21
22     public NodeIdentifierWithPredicatesGenerator(String id){
23         this(id, null);
24     }
25
26     public NodeIdentifierWithPredicatesGenerator(String id, ListSchemaNode schemaNode){
27         this.id = id;
28         matcher = pattern.matcher(this.id);
29         doesMatch = matcher.matches();
30         this.listSchemaNode = schemaNode;
31     }
32
33
34     public boolean matches(){
35         return doesMatch;
36     }
37
38     public InstanceIdentifier.NodeIdentifierWithPredicates getPathArgument(){
39         final String group = matcher.group(2);
40         final String[] keyValues = group.split(",");
41         Map<QName, Object> nameValues = new HashMap<>();
42
43         for(String keyValue : keyValues){
44             int eqIndex = keyValue.lastIndexOf('=');
45             try {
46                 final QName key = QNameFactory
47                     .create(keyValue.substring(0, eqIndex));
48                 nameValues.put(key, getValue(key, keyValue.substring(eqIndex + 1)));
49             } catch(IllegalArgumentException e){
50                 System.out.println("Error processing identifier : " + id);
51                 throw e;
52             }
53         }
54
55         return new InstanceIdentifier.NodeIdentifierWithPredicates(QNameFactory.create(matcher.group(1)), nameValues);
56     }
57
58
59     private Object getValue(QName key, String value){
60         if(listSchemaNode != null){
61             for(DataSchemaNode node : listSchemaNode.getChildNodes()){
62                 if(node instanceof LeafSchemaNode && node.getQName().equals(key)){
63                     return TypeDefinitionAwareCodec.from(LeafSchemaNode.class.cast(node).getType()).deserialize(value);
64                 }
65             }
66         }
67         return value;
68     }
69 }