blob: e59de95eefbf202bcf61ff20a2a0c21985d0094b [file] [log] [blame]
Thomas Vachuskade563cf2015-04-01 00:28:50 -07001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
Thomas Vachuskade563cf2015-04-01 00:28:50 -07003 *
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.codec.impl;
17
18import com.fasterxml.jackson.databind.node.ObjectNode;
19import org.onlab.packet.IpAddress;
20import org.onosproject.cluster.ClusterService;
21import org.onosproject.cluster.ControllerNode;
22import org.onosproject.cluster.DefaultControllerNode;
23import org.onosproject.cluster.NodeId;
24import org.onosproject.codec.CodecContext;
25import org.onosproject.codec.JsonCodec;
26
27import static com.google.common.base.Preconditions.checkNotNull;
28import static org.onosproject.cluster.DefaultControllerNode.DEFAULT_PORT;
29
30/**
31 * Device JSON codec.
32 */
33public final class ControllerNodeCodec extends JsonCodec<ControllerNode> {
34
35 @Override
36 public ObjectNode encode(ControllerNode node, CodecContext context) {
37 checkNotNull(node, "Controller node cannot be null");
Ray Milkey3078fc02015-05-06 16:14:14 -070038 ClusterService service = context.getService(ClusterService.class);
pierventre55a5f392021-11-05 15:37:32 +010039 IpAddress nodeIp = node.ip();
Thomas Vachuskade563cf2015-04-01 00:28:50 -070040 return context.mapper().createObjectNode()
41 .put("id", node.id().toString())
pierventre55a5f392021-11-05 15:37:32 +010042 .put("ip", nodeIp != null ? nodeIp.toString() : node.host())
Thomas Vachuskade563cf2015-04-01 00:28:50 -070043 .put("tcpPort", node.tcpPort())
Ray Milkey054e23d2018-03-22 13:37:11 -070044 .put("status", service.getState(node.id()).toString())
45 .put("lastUpdate", Long.toString(service.getLastUpdatedInstant(node.id()).toEpochMilli()))
46 .put("humanReadableLastUpdate", service.localStatus(node.id()));
Thomas Vachuskade563cf2015-04-01 00:28:50 -070047 }
48
49
50 @Override
51 public ControllerNode decode(ObjectNode json, CodecContext context) {
52 checkNotNull(json, "JSON cannot be null");
53 String ip = json.path("ip").asText();
54 return new DefaultControllerNode(new NodeId(json.path("id").asText(ip)),
55 IpAddress.valueOf(ip),
56 json.path("tcpPort").asInt(DEFAULT_PORT));
57 }
58
59
60}