Jian Li | feb8480 | 2021-01-12 16:34:49 +0900 | [diff] [blame] | 1 | /* |
| 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 | */ |
| 16 | package org.onosproject.kubevirtnetworking.codec; |
| 17 | |
| 18 | import com.fasterxml.jackson.databind.node.ObjectNode; |
| 19 | import org.onlab.packet.IpAddress; |
| 20 | import org.onosproject.codec.CodecContext; |
| 21 | import org.onosproject.codec.JsonCodec; |
| 22 | import org.onosproject.kubevirtnetworking.api.KubevirtIpPool; |
| 23 | import org.slf4j.Logger; |
| 24 | |
| 25 | import static com.google.common.base.Preconditions.checkNotNull; |
| 26 | import static org.onlab.util.Tools.nullIsIllegal; |
| 27 | import static org.slf4j.LoggerFactory.getLogger; |
| 28 | |
| 29 | /** |
| 30 | * Kubevirt IP pool codec used for serializing and de-serializing JSON string. |
| 31 | */ |
| 32 | public final class KubevirtIpPoolCodec extends JsonCodec<KubevirtIpPool> { |
| 33 | |
| 34 | private final Logger log = getLogger(getClass()); |
| 35 | |
| 36 | private static final String START = "start"; |
| 37 | private static final String END = "end"; |
| 38 | |
| 39 | private static final String MISSING_MESSAGE = " is required in KubevirtIpPool"; |
| 40 | |
| 41 | @Override |
| 42 | public ObjectNode encode(KubevirtIpPool ipPool, CodecContext context) { |
| 43 | checkNotNull(ipPool, "Kubevirt IP pool cannot be null"); |
| 44 | |
| 45 | return context.mapper().createObjectNode() |
| 46 | .put(START, ipPool.start().toString()) |
| 47 | .put(END, ipPool.end().toString()); |
| 48 | } |
| 49 | |
| 50 | @Override |
| 51 | public KubevirtIpPool decode(ObjectNode json, CodecContext context) { |
| 52 | if (json == null || !json.isObject()) { |
| 53 | return null; |
| 54 | } |
| 55 | |
| 56 | String start = nullIsIllegal(json.get(START).asText(), START + MISSING_MESSAGE); |
| 57 | String end = nullIsIllegal(json.get(END).asText(), END + MISSING_MESSAGE); |
| 58 | |
| 59 | return new KubevirtIpPool(IpAddress.valueOf(start), IpAddress.valueOf(end)); |
| 60 | } |
| 61 | } |