blob: b7609913b5f5aa636a5b981b275c36dbd2c1a5b0 [file] [log] [blame]
Jian Li5baef512017-04-10 20:25:18 +09001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2017-present Open Networking Foundation
Jian Li5baef512017-04-10 20:25:18 +09003 *
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.drivers.lisp.extensions.codec;
17
18import com.fasterxml.jackson.databind.node.ObjectNode;
19import org.onosproject.codec.CodecContext;
20import org.onosproject.codec.JsonCodec;
21import org.onosproject.drivers.lisp.extensions.LispSegmentAddress;
22import org.onosproject.mapping.addresses.MappingAddress;
23
24import static com.google.common.base.Preconditions.checkNotNull;
25import static org.onlab.util.Tools.nullIsIllegal;
26
27/**
28 * LISP segment address codec.
29 */
30public final class LispSegmentAddressCodec extends JsonCodec<LispSegmentAddress> {
31
Ray Milkey9c9cde42018-01-12 14:22:06 -080032 static final String INSTANCE_ID = "instanceId";
33 static final String ADDRESS = "address";
Jian Li5baef512017-04-10 20:25:18 +090034
35 private static final String MISSING_MEMBER_MESSAGE =
36 " member is required in LispSegmentAddress";
37
38 @Override
39 public ObjectNode encode(LispSegmentAddress address, CodecContext context) {
40 checkNotNull(address, "LispSegmentAddress cannot be null");
41
42 final ObjectNode result = context.mapper().createObjectNode()
43 .put(INSTANCE_ID, address.getInstanceId());
44
45 if (address.getAddress() != null) {
46 final JsonCodec<MappingAddress> addressCodec =
47 context.codec(MappingAddress.class);
48 ObjectNode addressNode = addressCodec.encode(address.getAddress(), context);
49 result.set(ADDRESS, addressNode);
50 }
51
52 return result;
53 }
54
55 @Override
56 public LispSegmentAddress decode(ObjectNode json, CodecContext context) {
57 if (json == null || !json.isObject()) {
58 return null;
59 }
60
61 int instanceId = nullIsIllegal(json.get(INSTANCE_ID),
62 INSTANCE_ID + MISSING_MEMBER_MESSAGE).asInt();
63
64 ObjectNode addressJson = get(json, ADDRESS);
65 MappingAddress mappingAddress = null;
66
67 if (addressJson != null) {
68 final JsonCodec<MappingAddress> addressCodec =
69 context.codec(MappingAddress.class);
70 mappingAddress = addressCodec.decode(addressJson, context);
71 }
72
73 return new LispSegmentAddress.Builder()
74 .withInstanceId(instanceId)
75 .withAddress(mappingAddress)
76 .build();
77 }
78}