blob: 156649ab9e0603af1ce60bbcad1019771ff8f132 [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.DefaultVirtualNetwork;
22import org.onosproject.incubator.net.virtual.NetworkId;
23import org.onosproject.incubator.net.virtual.TenantId;
24import org.onosproject.incubator.net.virtual.VirtualNetwork;
25
26import static com.google.common.base.Preconditions.checkNotNull;
27import static org.onlab.util.Tools.nullIsIllegal;
28
29/**
30 * Codec for the VirtualNetwork class.
31 */
32public class VirtualNetworkCodec extends JsonCodec<VirtualNetwork> {
33
34 // JSON field names
35 private static final String NETWORK_ID = "networkId";
36 private static final String TENANT_ID = "tenantId";
37
38 private static final String NULL_OBJECT_MSG = "VirtualNetwork cannot be null";
39 private static final String MISSING_MEMBER_MSG = " member is required in VirtualNetwork";
40
41 @Override
42 public ObjectNode encode(VirtualNetwork vnet, CodecContext context) {
43 checkNotNull(vnet, NULL_OBJECT_MSG);
44
45 ObjectNode result = context.mapper().createObjectNode()
46 .put(NETWORK_ID, vnet.id().toString())
47 .put(TENANT_ID, vnet.tenantId().toString());
48
49 return result;
50 }
51
52 @Override
53 public VirtualNetwork decode(ObjectNode json, CodecContext context) {
54 if (json == null || !json.isObject()) {
55 return null;
56 }
57
58 NetworkId nId = NetworkId.networkId(Long.parseLong(extractMember(NETWORK_ID, json)));
59 TenantId tId = TenantId.tenantId(extractMember(TENANT_ID, json));
60 return new DefaultVirtualNetwork(nId, tId);
61 }
62
63 private String extractMember(String key, ObjectNode json) {
64 return nullIsIllegal(json.get(key), key + MISSING_MEMBER_MSG).asText();
65 }
66}