blob: e77c0efbd3c53c706d2a798269722a42a6231a6b [file] [log] [blame]
Jian Li5e2ad4a2018-07-16 13:40:53 +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.openstacknetworking.codec;
17
18import com.fasterxml.jackson.databind.node.ObjectNode;
19import org.onlab.packet.IpAddress;
20import org.onlab.packet.MacAddress;
21import org.onlab.packet.VlanId;
22import org.onosproject.codec.CodecContext;
23import org.onosproject.codec.JsonCodec;
24import org.onosproject.openstacknetworking.api.ExternalPeerRouter;
25import org.onosproject.openstacknetworking.impl.DefaultExternalPeerRouter;
26import org.slf4j.Logger;
27
28import static com.google.common.base.Preconditions.checkNotNull;
29import static org.onlab.util.Tools.nullIsIllegal;
30import static org.slf4j.LoggerFactory.getLogger;
31
32/**
33 * Openstack external peer router codec used for serializing and de-serializing JSON string.
34 */
35public class ExternalPeerRouterCodec extends JsonCodec<ExternalPeerRouter> {
36
37 private final Logger log = getLogger(getClass());
38
39 private static final String IP_ADDRESS = "ipAddress";
40 private static final String MAC_ADDRESS = "macAddress";
41 private static final String VLAN_ID = "vlanId";
42
43 private static final String MISSING_MESSAGE = " is required in ExternalPeerRouter";
44
45 @Override
46 public ObjectNode encode(ExternalPeerRouter router, CodecContext context) {
47 checkNotNull(router, "External peer router cannot be null");
48
49 return context.mapper().createObjectNode()
50 .put(IP_ADDRESS, router.ipAddress().toString())
51 .put(MAC_ADDRESS, router.macAddress().toString())
52 .put(VLAN_ID, router.vlanId().toString());
53 }
54
55 @Override
56 public ExternalPeerRouter decode(ObjectNode json, CodecContext context) {
57 if (json == null || !json.isObject()) {
58 return null;
59 }
60
61 String ipAddress = nullIsIllegal(json.get(IP_ADDRESS).asText(),
62 IP_ADDRESS + MISSING_MESSAGE);
63 String macAddress = nullIsIllegal(json.get(MAC_ADDRESS).asText(),
64 MAC_ADDRESS + MISSING_MESSAGE);
65 String vlanId = nullIsIllegal(json.get(VLAN_ID).asText(),
66 VLAN_ID + MISSING_MESSAGE);
67
68 return DefaultExternalPeerRouter.builder()
69 .ipAddress(IpAddress.valueOf(ipAddress))
70 .macAddress(MacAddress.valueOf(macAddress))
71 .vlanId(VlanId.vlanId(vlanId)).build();
72 }
73}