blob: 89772841d79d48e785c8dec692d164e476fbd97b [file] [log] [blame]
Jian Lidaa7d6a2021-04-13 17:22:56 +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.node.ObjectNode;
19import org.onosproject.codec.CodecContext;
20import org.onosproject.codec.JsonCodec;
21import org.onosproject.kubevirtnetworking.api.DefaultKubevirtLoadBalancerRule;
22import org.onosproject.kubevirtnetworking.api.KubevirtLoadBalancerRule;
23import org.slf4j.Logger;
24
25import static com.google.common.base.Preconditions.checkNotNull;
26import static org.onlab.util.Tools.nullIsIllegal;
27import static org.slf4j.LoggerFactory.getLogger;
28
29/**
30 * Kubevirt load balancer rule codec used for serializing and de-serializing JSON string.
31 */
32public final class KubevirtLoadBalancerRuleCodec extends JsonCodec<KubevirtLoadBalancerRule> {
33
34 private final Logger log = getLogger(getClass());
35
36 private static final String PROTOCOL = "protocol";
37 private static final String PORT_RANGE_MAX = "portRangeMax";
38 private static final String PORT_RANGE_MIN = "portRangeMin";
39
40 private static final String MISSING_MESSAGE = " is required in KubevirtLoadBalancerRule";
41
42 @Override
43 public ObjectNode encode(KubevirtLoadBalancerRule rule, CodecContext context) {
44 checkNotNull(rule, "Kubevirt load balancer rule cannot be null");
45
46 return context.mapper().createObjectNode()
47 .put(PROTOCOL, rule.protocol())
48 .put(PORT_RANGE_MAX, rule.portRangeMax())
49 .put(PORT_RANGE_MIN, rule.portRangeMin());
50 }
51
52 @Override
53 public KubevirtLoadBalancerRule decode(ObjectNode json, CodecContext context) {
54 if (json == null || !json.isObject()) {
55 return null;
56 }
57
58 String protocol = nullIsIllegal(json.get(PROTOCOL).asText(), PROTOCOL + MISSING_MESSAGE);
59 Integer portRangeMax = json.get(PORT_RANGE_MAX).asInt();
60 Integer portRangeMin = json.get(PORT_RANGE_MIN).asInt();
61
62 return DefaultKubevirtLoadBalancerRule.builder()
63 .protocol(protocol)
64 .portRangeMax(portRangeMax)
65 .portRangeMin(portRangeMin)
66 .build();
67 }
68}