blob: 2d739793eab71ef9f65090959a6091f3e6f0ad65 [file] [log] [blame]
Jian Lifeb84802021-01-12 16:34:49 +09001/*
2 * Copyright 2021-present Open Networking Foundation
3 *
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.kubevirtnetworking.codec;
17
18import com.fasterxml.jackson.databind.JsonNode;
19import com.fasterxml.jackson.databind.node.ObjectNode;
20import org.onlab.packet.IpAddress;
21import org.onlab.packet.IpPrefix;
22import org.onosproject.codec.CodecContext;
23import org.onosproject.codec.JsonCodec;
24import org.onosproject.kubevirtnetworking.api.KubevirtHostRoute;
25import org.slf4j.Logger;
26
27import static com.google.common.base.Preconditions.checkNotNull;
28import static org.onlab.util.Tools.nullIsIllegal;
29import static org.slf4j.LoggerFactory.getLogger;
30
31/**
32 * Kubevirt host route codec used for serializing and de-serializing JSON string.
33 */
34public final class KubevirtHostRouteCodec extends JsonCodec<KubevirtHostRoute> {
35
36 private final Logger log = getLogger(getClass());
37
38 private static final String DESTINATION = "destination";
39 private static final String NEXTHOP = "nexthop";
40
41 private static final String MISSING_MESSAGE = " is required in KubevirtHostRoute";
42
43 @Override
44 public ObjectNode encode(KubevirtHostRoute hostRoute, CodecContext context) {
45 checkNotNull(hostRoute, "Kubernetes network cannot be null");
46
47 ObjectNode result = context.mapper().createObjectNode()
48 .put(DESTINATION, hostRoute.destination().toString());
49
50 if (hostRoute.nexthop() != null) {
51 result.put(NEXTHOP, hostRoute.nexthop().toString());
52 }
53
54 return result;
55 }
56
57 @Override
58 public KubevirtHostRoute decode(ObjectNode json, CodecContext context) {
59 if (json == null || !json.isObject()) {
60 return null;
61 }
62
63 String destination = nullIsIllegal(json.get(DESTINATION).asText(),
64 DESTINATION + MISSING_MESSAGE);
65 JsonNode nexthopJson = json.get(NEXTHOP);
66 IpAddress nexthop = null;
67
68 if (nexthopJson != null) {
69 nexthop = IpAddress.valueOf(nexthopJson.asText());
70 }
71
72 return new KubevirtHostRoute(IpPrefix.valueOf(destination), nexthop);
73 }
74}