blob: 2edb66d484122ef11ac924071ceb0fd485039ecb [file] [log] [blame]
Jian Lie2a04ce2020-07-01 19:07:02 +09001/*
2 * Copyright 2020-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.k8snode.codec;
17
18import com.fasterxml.jackson.databind.node.ArrayNode;
19import com.fasterxml.jackson.databind.node.ObjectNode;
20import org.onlab.packet.IpAddress;
21import org.onosproject.codec.CodecContext;
22import org.onosproject.codec.JsonCodec;
23import org.onosproject.k8snode.api.DefaultK8sHost;
24import org.onosproject.k8snode.api.K8sHost;
25import org.onosproject.k8snode.api.K8sHostState;
26import org.slf4j.Logger;
27
28import java.util.HashSet;
29import java.util.Set;
30
31import static com.google.common.base.Preconditions.checkNotNull;
32import static org.onlab.util.Tools.nullIsIllegal;
33import static org.slf4j.LoggerFactory.getLogger;
34
35/**
36 * Kubernetes host codec used for serializing and de-serializing JSON string.
37 */
38public final class K8sHostCodec extends JsonCodec<K8sHost> {
39
40 private final Logger log = getLogger(getClass());
41
42 private static final String HOST_IP = "hostIp";
43 private static final String NODE_NAMES = "nodeNames";
44 private static final String STATE = "state";
45
46 private static final String MISSING_MESSAGE = " is required in K8sHost";
47
48 @Override
49 public ObjectNode encode(K8sHost entity, CodecContext context) {
50 checkNotNull(entity, "Kubernetes host cannot be null");
51
52 ObjectNode result = context.mapper().createObjectNode()
53 .put(HOST_IP, entity.hostIp().toString())
54 .put(STATE, entity.state().name());
55
56 ArrayNode nodes = context.mapper().createArrayNode();
57 entity.nodeNames().forEach(nodes::add);
58 result.set(NODE_NAMES, nodes);
59
60 return result;
61 }
62
63 @Override
64 public K8sHost decode(ObjectNode json, CodecContext context) {
65 if (json == null || !json.isObject()) {
66 return null;
67 }
68
69 IpAddress hostIp = IpAddress.valueOf(nullIsIllegal(json.get(HOST_IP).asText(),
70 HOST_IP + MISSING_MESSAGE));
71 ArrayNode nodeNamesJson = (ArrayNode) json.get(NODE_NAMES);
72 Set<String> nodeNames = new HashSet<>();
73 nodeNamesJson.forEach(n -> nodeNames.add(n.asText()));
74
75 return DefaultK8sHost.builder()
76 .hostIp(hostIp)
77 .state(K8sHostState.INIT)
78 .nodeNames(nodeNames)
79 .build();
80 }
81}