blob: 1921d43ab6626036a3ad4647c96ae5b672499daf [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;
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 * Openstack controller codec used for serializing and de-serializing JSON string.
31 */
32public class OpenstackControllerCodec extends JsonCodec<ControllerInfo> {
33
34 private final Logger log = getLogger(getClass());
35
36 private static final String IP = "ip";
37 private static final String PORT = "port";
38 private static final String TCP = "tcp"; // controller connection should always be TCP
39
40 private static final String MISSING_MESSAGE = " is required in ControllerInfo";
41
42 @Override
43 public ObjectNode encode(ControllerInfo controller, CodecContext context) {
44 checkNotNull(controller, "Openstack controller cannot be null");
45
46 return context.mapper().createObjectNode()
47 .put(IP, controller.ip().toString())
48 .put(PORT, controller.port());
49 }
50
51 @Override
52 public ControllerInfo decode(ObjectNode json, CodecContext context) {
53 if (json == null || !json.isObject()) {
54 return null;
55 }
56
57 String ip = nullIsIllegal(json.get(IP).asText(),
58 IP + MISSING_MESSAGE);
59 int port = nullIsIllegal(json.get(PORT).asInt(),
60 PORT + MISSING_MESSAGE);
61
62 return new ControllerInfo(IpAddress.valueOf(ip), port, TCP);
63 }
64}