Merge "Make Raft messages serializable"
[controller.git] / opendaylight / md-sal / sal-protocolbuffer-encoding / src / main / java / org / opendaylight / controller / cluster / datastore / node / NormalizedNodeToNodeCodec.java
1 package org.opendaylight.controller.cluster.datastore.node;
2
3 import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages;
4 import org.opendaylight.controller.cluster.datastore.node.utils.PathUtils;
5 import org.opendaylight.yangtools.yang.common.QName;
6 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
7 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
8 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
9 import org.slf4j.Logger;
10 import org.slf4j.LoggerFactory;
11
12 public class NormalizedNodeToNodeCodec {
13     private final SchemaContext ctx;
14     private static final Logger logger = LoggerFactory.getLogger(NormalizedNodeToNodeCodec.class);
15
16     public NormalizedNodeToNodeCodec(final SchemaContext ctx){
17         this.ctx = ctx;
18
19     }
20
21     public NormalizedNodeMessages.Container encode(YangInstanceIdentifier id, NormalizedNode node){
22         String parentPath = "";
23
24         if(id != null){
25             parentPath = PathUtils.getParentPath(id.toString());
26         }
27
28
29         NormalizedNodeToProtocolBufferNode encoder = new NormalizedNodeToProtocolBufferNode();
30         encoder.encode(parentPath, node);
31
32         return encoder.getContainer();
33
34
35     }
36
37     public NormalizedNode<?,?> decode(YangInstanceIdentifier id, NormalizedNodeMessages.Node node){
38             NodeToNormalizedNodeBuilder currentOp = NodeToNormalizedNodeBuilder.from(ctx);
39
40             for(YangInstanceIdentifier.PathArgument pathArgument : id.getPathArguments()){
41                 currentOp = currentOp.getChild(pathArgument);
42             }
43
44             QName nodeType = null;
45
46             if(id.getPath().size() < 1){
47                 nodeType = null;
48             } else {
49                 final YangInstanceIdentifier.PathArgument pathArgument = id.getPath().get(id.getPath().size() - 1);
50                 if(pathArgument instanceof YangInstanceIdentifier.AugmentationIdentifier){
51                     nodeType = null;
52                 } else {
53                     nodeType = pathArgument.getNodeType();
54                 }
55             }
56             if((node != null)&& (!node.getType().isEmpty())){
57                return currentOp.normalize(nodeType, node);
58             } else{
59               return null;
60             }
61     }
62
63
64 }