blob: 54f51e7c516bcb104730a4e2973e7299198d6b1d [file] [log] [blame]
Claudine Chiuf6bf8d52016-04-08 01:31:54 +00001package org.onosproject.codec.impl;
2
3import com.fasterxml.jackson.databind.node.ObjectNode;
4import org.onosproject.codec.CodecContext;
5import org.onosproject.codec.JsonCodec;
6import org.onosproject.incubator.net.tunnel.TunnelId;
7import org.onosproject.incubator.net.virtual.DefaultVirtualLink;
8import org.onosproject.incubator.net.virtual.NetworkId;
9import org.onosproject.incubator.net.virtual.VirtualLink;
10import org.onosproject.net.Link;
11
12import static com.google.common.base.Preconditions.checkNotNull;
13import static org.onlab.util.Tools.nullIsIllegal;
14
15/**
16 * Codec for the VirtualLink class.
17 */
18public class VirtualLinkCodec extends JsonCodec<VirtualLink> {
19
20 // JSON field names
21 private static final String NETWORK_ID = "networkId";
22 private static final String TUNNEL_ID = "tunnelId";
23
24 private static final String NULL_OBJECT_MSG = "VirtualLink cannot be null";
25 private static final String MISSING_MEMBER_MSG = " member is required in VirtualLink";
26
27 @Override
28 public ObjectNode encode(VirtualLink vLink, CodecContext context) {
29 checkNotNull(vLink, NULL_OBJECT_MSG);
30
31 JsonCodec<Link> codec = context.codec(Link.class);
32 ObjectNode result = codec.encode(vLink, context);
33 result.put(NETWORK_ID, vLink.networkId().toString());
34 // TODO check if tunnelId needs to be part of VirtualLink interface.
35 if (vLink instanceof DefaultVirtualLink) {
36 result.put(TUNNEL_ID, ((DefaultVirtualLink) vLink).tunnelId().toString());
37 }
38 return result;
39 }
40
41 @Override
42 public VirtualLink decode(ObjectNode json, CodecContext context) {
43 if (json == null || !json.isObject()) {
44 return null;
45 }
46 JsonCodec<Link> codec = context.codec(Link.class);
47 Link link = codec.decode(json, context);
48 NetworkId nId = NetworkId.networkId(Long.parseLong(extractMember(NETWORK_ID, json)));
49 String tunnelIdStr = json.path(TUNNEL_ID).asText();
50 TunnelId tunnelId = tunnelIdStr != null ? TunnelId.valueOf(tunnelIdStr)
51 : TunnelId.valueOf(0);
52 return new DefaultVirtualLink(nId, link.src(), link.dst(), tunnelId);
53 }
54
55 /**
56 * Extract member from JSON ObjectNode.
57 *
58 * @param key key for which value is needed
59 * @param json JSON ObjectNode
60 * @return member value
61 */
62 private String extractMember(String key, ObjectNode json) {
63 return nullIsIllegal(json.get(key), key + MISSING_MEMBER_MSG).asText();
64 }
65}