blob: 0f225e9a44ad5371c120ce39c076eb8e64c6b2dd [file] [log] [blame]
Jian Li73c74442017-04-10 23:30:12 +09001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2017-present Open Networking Foundation
Jian Li73c74442017-04-10 23:30:12 +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.JsonNode;
19import com.fasterxml.jackson.databind.node.ArrayNode;
20import com.fasterxml.jackson.databind.node.ObjectNode;
21import com.google.common.collect.Lists;
22import org.onosproject.codec.CodecContext;
23import org.onosproject.codec.JsonCodec;
24import org.onosproject.drivers.lisp.extensions.LispTeAddress;
25
26import java.util.List;
27import java.util.stream.IntStream;
28
29import static com.google.common.base.Preconditions.checkNotNull;
30import static org.onlab.util.Tools.nullIsIllegal;
31
32/**
33 * LISP traffic engineering address codec.
34 */
35public final class LispTeAddressCodec extends JsonCodec<LispTeAddress> {
36
37 protected static final String TE_RECORDS = "records";
38
39 private static final String MISSING_MEMBER_MESSAGE =
40 " member is required in LispTeAddress";
41
42 @Override
43 public ObjectNode encode(LispTeAddress address, CodecContext context) {
44 checkNotNull(address, "LispTeAddress cannot be null");
45
46 final ObjectNode result = context.mapper().createObjectNode();
47 final ArrayNode jsonRecords = result.putArray(TE_RECORDS);
48
49 final JsonCodec<LispTeAddress.TeRecord> recordCodec =
50 context.codec(LispTeAddress.TeRecord.class);
51
52 for (final LispTeAddress.TeRecord record : address.getTeRecords()) {
53 jsonRecords.add(recordCodec.encode(record, context));
54 }
55
56 return result;
57 }
58
59 @Override
60 public LispTeAddress decode(ObjectNode json, CodecContext context) {
61 if (json == null || !json.isObject()) {
62 return null;
63 }
64
65 final JsonCodec<LispTeAddress.TeRecord> recordCodec =
66 context.codec(LispTeAddress.TeRecord.class);
67
68 JsonNode recordsJson = nullIsIllegal(json.get(TE_RECORDS),
69 TE_RECORDS + MISSING_MEMBER_MESSAGE);
70 List<LispTeAddress.TeRecord> records = Lists.newArrayList();
71
72 if (recordsJson != null) {
73 IntStream.range(0, recordsJson.size())
74 .forEach(i -> records.add(
75 recordCodec.decode(get(recordsJson, i), context)));
76 }
77
78 return new LispTeAddress.Builder()
79 .withTeRecords(records)
80 .build();
81 }
82}