blob: 87859064de8d7d2408921dff90bdcecc28d125d3 [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
Jian Li9b199162019-02-10 18:00:35 +090037 private static final String IPAM_ID = "ipamId";
Jian Li9ee9c8b2019-01-24 11:48:12 +090038 private static final String IP_ADDRESS = "ipAddress";
39 private static final String NETWORK_ID = "networkId";
40
41 private static final String MISSING_MESSAGE = " is required in K8sIPAM";
42
43 @Override
44 public ObjectNode encode(K8sIpam ipam, CodecContext context) {
45 checkNotNull(ipam, "Kubernetes IPAM cannot be null");
46
47 return context.mapper().createObjectNode()
Jian Li9b199162019-02-10 18:00:35 +090048 .put(IPAM_ID, ipam.ipamId())
Jian Li9ee9c8b2019-01-24 11:48:12 +090049 .put(IP_ADDRESS, ipam.ipAddress().toString())
50 .put(NETWORK_ID, ipam.networkId());
51 }
52
53 @Override
54 public K8sIpam decode(ObjectNode json, CodecContext context) {
55 if (json == null || !json.isObject()) {
56 return null;
57 }
58
Jian Li9b199162019-02-10 18:00:35 +090059 String ipamId = nullIsIllegal(json.get(IPAM_ID).asText(),
60 IPAM_ID + MISSING_MESSAGE);
Jian Li9ee9c8b2019-01-24 11:48:12 +090061 String ipAddress = nullIsIllegal(json.get(IP_ADDRESS).asText(),
62 IP_ADDRESS + MISSING_MESSAGE);
63 String networkId = nullIsIllegal(json.get(NETWORK_ID).asText(),
64 NETWORK_ID + MISSING_MESSAGE);
65
Jian Li9b199162019-02-10 18:00:35 +090066 return new DefaultK8sIpam(ipamId, IpAddress.valueOf(ipAddress), networkId);
Jian Li9ee9c8b2019-01-24 11:48:12 +090067 }
68}