blob: add4fd327aba26b6582007a5443b07068c7bd119 [file] [log] [blame]
Jian Li944e3a92017-04-07 23:53:36 +09001/*
2 * Copyright 2017-present Open Networking Laboratory
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.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.LispAsAddress;
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 AS address codec.
29 */
30public final class LispAsAddressCodec extends JsonCodec<LispAsAddress> {
31
32 protected static final String AS_NUMBER = "asNumber";
33 protected static final String ADDRESS = "address";
34 private static final String MISSING_MEMBER_MESSAGE =
35 " member is required in LispAsAddress";
36
37 @Override
38 public ObjectNode encode(LispAsAddress address, CodecContext context) {
39 checkNotNull(address, "LispAsAddress cannot be null");
40
41 final ObjectNode result = context.mapper().createObjectNode()
42 .put(AS_NUMBER, address.getAsNumber());
43
44 if (address.getAddress() != null) {
45 final JsonCodec<MappingAddress> addressCodec =
46 context.codec(MappingAddress.class);
47 ObjectNode addressNode = addressCodec.encode(address.getAddress(), context);
48 result.set(ADDRESS, addressNode);
49 }
50
51 return result;
52 }
53
54 @Override
55 public LispAsAddress decode(ObjectNode json, CodecContext context) {
56 if (json == null || !json.isObject()) {
57 return null;
58 }
59
60 int asNumber = nullIsIllegal(json.get(AS_NUMBER),
61 AS_NUMBER + MISSING_MEMBER_MESSAGE).asInt();
62
63 ObjectNode addressJson = get(json, ADDRESS);
64 MappingAddress mappingAddress = null;
65
66 if (addressJson != null) {
67 final JsonCodec<MappingAddress> addressCodec =
68 context.codec(MappingAddress.class);
69 mappingAddress = addressCodec.decode(addressJson, context);
70 }
71
72 return new LispAsAddress.Builder()
73 .withAsNumber(asNumber)
74 .withAddress(mappingAddress)
75 .build();
76 }
77}