Jian Li | 789fadb | 2018-07-10 13:59:47 +0900 | [diff] [blame] | 1 | /* |
| 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 | */ |
| 16 | package org.onosproject.openstacknode.codec; |
| 17 | |
| 18 | import com.fasterxml.jackson.databind.node.ObjectNode; |
| 19 | import org.onlab.packet.IpAddress; |
| 20 | import org.onosproject.codec.CodecContext; |
| 21 | import org.onosproject.codec.JsonCodec; |
| 22 | import org.onosproject.net.behaviour.ControllerInfo; |
Jian Li | 789fadb | 2018-07-10 13:59:47 +0900 | [diff] [blame] | 23 | |
| 24 | import static com.google.common.base.Preconditions.checkNotNull; |
| 25 | import static org.onlab.util.Tools.nullIsIllegal; |
Jian Li | 789fadb | 2018-07-10 13:59:47 +0900 | [diff] [blame] | 26 | |
| 27 | /** |
| 28 | * Openstack controller codec used for serializing and de-serializing JSON string. |
| 29 | */ |
| 30 | public class OpenstackControllerCodec extends JsonCodec<ControllerInfo> { |
| 31 | |
Jian Li | 789fadb | 2018-07-10 13:59:47 +0900 | [diff] [blame] | 32 | 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 | } |