Jian Li | e2a04ce | 2020-07-01 19:07:02 +0900 | [diff] [blame] | 1 | /* |
| 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 | */ |
| 16 | package org.onosproject.k8snode.codec; |
| 17 | |
| 18 | import com.fasterxml.jackson.databind.JsonNode; |
| 19 | import com.fasterxml.jackson.databind.node.ArrayNode; |
| 20 | import com.fasterxml.jackson.databind.node.ObjectNode; |
| 21 | import org.onlab.packet.IpAddress; |
| 22 | import org.onosproject.codec.CodecContext; |
| 23 | import org.onosproject.codec.JsonCodec; |
| 24 | import org.onosproject.k8snode.api.DefaultHostNodesInfo; |
| 25 | import org.onosproject.k8snode.api.HostNodesInfo; |
| 26 | |
| 27 | import java.util.HashSet; |
| 28 | import java.util.Set; |
| 29 | |
| 30 | import static org.onlab.util.Tools.nullIsIllegal; |
| 31 | |
| 32 | /** |
| 33 | * HostNodesInfo codec used for serializing and de-serializing JSON. |
| 34 | */ |
| 35 | public final class HostNodesInfoCodec extends JsonCodec<HostNodesInfo> { |
| 36 | |
| 37 | private static final String HOST_IP = "hostIp"; |
| 38 | private static final String NODES = "nodes"; |
| 39 | |
| 40 | private static final String MISSING_MESSAGE = " is required in HostNodesInfo"; |
| 41 | |
| 42 | @Override |
| 43 | public ObjectNode encode(HostNodesInfo entity, CodecContext context) { |
| 44 | ObjectNode node = context.mapper().createObjectNode() |
| 45 | .put(HOST_IP, entity.hostIp().toString()); |
| 46 | |
| 47 | ArrayNode nodes = context.mapper().createArrayNode(); |
| 48 | entity.nodes().forEach(nodes::add); |
| 49 | node.set(NODES, nodes); |
| 50 | return node; |
| 51 | } |
| 52 | |
| 53 | @Override |
| 54 | public HostNodesInfo decode(ObjectNode json, CodecContext context) { |
| 55 | if (json == null || !json.isObject()) { |
| 56 | return null; |
| 57 | } |
| 58 | |
| 59 | IpAddress hostIp = IpAddress.valueOf(nullIsIllegal( |
| 60 | json.get(HOST_IP).asText(), HOST_IP + MISSING_MESSAGE)); |
| 61 | |
| 62 | Set<String> nodes = new HashSet<>(); |
| 63 | ArrayNode nodesJson = (ArrayNode) json.get(NODES); |
| 64 | |
| 65 | for (JsonNode cidrJson : nodesJson) { |
| 66 | nodes.add(cidrJson.asText()); |
| 67 | } |
| 68 | |
| 69 | return new DefaultHostNodesInfo.Builder() |
| 70 | .hostIp(hostIp) |
| 71 | .nodes(nodes) |
| 72 | .build(); |
| 73 | } |
| 74 | } |