blob: 7ac0659707f7b63bea164506b10a731c37bc77b9 [file] [log] [blame]
Jian Li789fadb2018-07-10 13:59:47 +09001/*
2 * Copyright 2018-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.openstacknode.codec;
17
18import com.fasterxml.jackson.databind.node.ObjectNode;
19import org.onlab.packet.IpAddress;
20import org.onosproject.codec.CodecContext;
21import org.onosproject.codec.JsonCodec;
22import org.onosproject.net.behaviour.ControllerInfo;
Jian Li789fadb2018-07-10 13:59:47 +090023
24import static com.google.common.base.Preconditions.checkNotNull;
25import static org.onlab.util.Tools.nullIsIllegal;
Jian Li789fadb2018-07-10 13:59:47 +090026
27/**
28 * Openstack controller codec used for serializing and de-serializing JSON string.
29 */
30public class OpenstackControllerCodec extends JsonCodec<ControllerInfo> {
31
Jian Li789fadb2018-07-10 13:59:47 +090032 private static final String IP = "ip";
33 private static final String PORT = "port";
34 private static final String TCP = "tcp"; // controller connection should always be TCP
35
36 private static final String MISSING_MESSAGE = " is required in ControllerInfo";
37
38 @Override
39 public ObjectNode encode(ControllerInfo controller, CodecContext context) {
40 checkNotNull(controller, "Openstack controller cannot be null");
41
42 return context.mapper().createObjectNode()
43 .put(IP, controller.ip().toString())
44 .put(PORT, controller.port());
45 }
46
47 @Override
48 public ControllerInfo decode(ObjectNode json, CodecContext context) {
49 if (json == null || !json.isObject()) {
50 return null;
51 }
52
53 String ip = nullIsIllegal(json.get(IP).asText(),
54 IP + MISSING_MESSAGE);
55 int port = nullIsIllegal(json.get(PORT).asInt(),
56 PORT + MISSING_MESSAGE);
57
58 return new ControllerInfo(IpAddress.valueOf(ip), port, TCP);
59 }
60}