blob: 79053ecd2766fdc70a7b69e41f87308945edea3e [file] [log] [blame]
Claudine Chiufb8b8162016-04-01 23:50:51 +00001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2016-present Open Networking Foundation
Claudine Chiufb8b8162016-04-01 23:50:51 +00003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onosproject.codec.impl;
17
18import com.fasterxml.jackson.databind.node.ObjectNode;
19import org.onosproject.codec.CodecContext;
20import org.onosproject.codec.JsonCodec;
21import org.onosproject.incubator.net.virtual.DefaultVirtualDevice;
22import org.onosproject.incubator.net.virtual.NetworkId;
23import org.onosproject.incubator.net.virtual.VirtualDevice;
24import org.onosproject.net.DeviceId;
25
26import static com.google.common.base.Preconditions.checkNotNull;
27import static org.onlab.util.Tools.nullIsIllegal;
28
29/**
30 * Codec for the VirtualDevice class.
31 */
32public class VirtualDeviceCodec extends JsonCodec<VirtualDevice> {
33
34 // JSON field names
35 private static final String ID = "deviceId";
36 private static final String NETWORK_ID = "networkId";
37
38 private static final String NULL_OBJECT_MSG = "VirtualDevice cannot be null";
39 private static final String MISSING_MEMBER_MSG = " member is required in VirtualDevice";
40
41 @Override
42 public ObjectNode encode(VirtualDevice vDev, CodecContext context) {
43 checkNotNull(vDev, NULL_OBJECT_MSG);
44
45 ObjectNode result = context.mapper().createObjectNode()
Claudine Chiu1decd532016-04-19 18:30:01 +000046 .put(NETWORK_ID, vDev.networkId().toString())
47 .put(ID, vDev.id().toString());
Claudine Chiufb8b8162016-04-01 23:50:51 +000048
49 return result;
50 }
51
52 @Override
53 public VirtualDevice decode(ObjectNode json, CodecContext context) {
54 if (json == null || !json.isObject()) {
55 return null;
56 }
57
58 DeviceId dId = DeviceId.deviceId(extractMember(ID, json));
59 NetworkId nId = NetworkId.networkId(Long.parseLong(extractMember(NETWORK_ID, json)));
60 return new DefaultVirtualDevice(nId, dId);
61 }
62
Claudine Chiu1decd532016-04-19 18:30:01 +000063 /**
64 * Extract member from JSON ObjectNode.
65 *
66 * @param key key for which value is needed
67 * @param json JSON ObjectNode
68 * @return member value
69 */
Claudine Chiufb8b8162016-04-01 23:50:51 +000070 private String extractMember(String key, ObjectNode json) {
71 return nullIsIllegal(json.get(key), key + MISSING_MEMBER_MSG).asText();
72 }
73}