blob: ed63f9bdf9f701378532536f05e2f4dda4a1de8e [file] [log] [blame]
Jian Lif9ec0832017-04-09 20:49:48 +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.LispNonceAddress;
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 nonce address codec.
29 */
30public final class LispNonceAddressCodec extends JsonCodec<LispNonceAddress> {
31
32 protected static final String NONCE = "nonce";
33 protected static final String ADDRESS = "address";
34
35 private static final String MISSING_MEMBER_MESSAGE =
36 " member is required in LispGcAddress";
37
38 @Override
39 public ObjectNode encode(LispNonceAddress address, CodecContext context) {
40 checkNotNull(address, "LispListAddress cannot be null");
41
42 final ObjectNode result = context.mapper().createObjectNode()
43 .put(NONCE, address.getNonce());
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 LispNonceAddress decode(ObjectNode json, CodecContext context) {
57 if (json == null || !json.isObject()) {
58 return null;
59 }
60
61 int nonce = nullIsIllegal(json.get(NONCE), NONCE +
62 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 LispNonceAddress.Builder()
74 .withNonce(nonce)
75 .withAddress(mappingAddress)
76 .build();
77 }
78}