blob: 695156c030042c408198f7f7b403d4afd051ad71 [file] [log] [blame]
Jian Li9ee9c8b2019-01-24 11:48:12 +09001/*
2 * Copyright 2019-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.k8snetworking.codec;
17
18import com.fasterxml.jackson.databind.node.ObjectNode;
19import org.onlab.packet.IpAddress;
20import org.onosproject.codec.CodecContext;
21import org.onosproject.codec.JsonCodec;
22import org.onosproject.k8snetworking.api.DefaultK8sIpam;
23import org.onosproject.k8snetworking.api.K8sIpam;
24import org.slf4j.Logger;
25
26import static com.google.common.base.Preconditions.checkNotNull;
27import static org.onlab.util.Tools.nullIsIllegal;
28import static org.slf4j.LoggerFactory.getLogger;
29
30/**
31 * Kubernetes IPAM codec used for serializing and de-serializing JSON string.
32 */
33public final class K8sIpamCodec extends JsonCodec<K8sIpam> {
34
35 private final Logger log = getLogger(getClass());
36
37 private static final String IP_ADDRESS = "ipAddress";
38 private static final String NETWORK_ID = "networkId";
39
40 private static final String MISSING_MESSAGE = " is required in K8sIPAM";
41
42 @Override
43 public ObjectNode encode(K8sIpam ipam, CodecContext context) {
44 checkNotNull(ipam, "Kubernetes IPAM cannot be null");
45
46 return context.mapper().createObjectNode()
47 .put(IP_ADDRESS, ipam.ipAddress().toString())
48 .put(NETWORK_ID, ipam.networkId());
49 }
50
51 @Override
52 public K8sIpam decode(ObjectNode json, CodecContext context) {
53 if (json == null || !json.isObject()) {
54 return null;
55 }
56
57 String ipAddress = nullIsIllegal(json.get(IP_ADDRESS).asText(),
58 IP_ADDRESS + MISSING_MESSAGE);
59 String networkId = nullIsIllegal(json.get(NETWORK_ID).asText(),
60 NETWORK_ID + MISSING_MESSAGE);
61
62 return new DefaultK8sIpam(IpAddress.valueOf(ipAddress), networkId);
63 }
64}