blob: a673719915dfd8b4d402bba1d807857f123e6be2 [file] [log] [blame]
Sean Condon0e89bda2017-03-21 14:23:19 +00001/*
2 * Copyright 2017-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.cfm.web;
17
18import static org.onlab.util.Tools.nullIsIllegal;
19
20import java.util.ArrayList;
21import java.util.List;
22
23import org.onlab.packet.VlanId;
24import org.onosproject.codec.CodecContext;
25import org.onosproject.codec.JsonCodec;
26
27import com.fasterxml.jackson.databind.JsonNode;
28import com.fasterxml.jackson.databind.node.ArrayNode;
29import com.fasterxml.jackson.databind.node.ObjectNode;
30
31/**
32 * Encode and decode to/from JSON to Vid object.
33 */
34public class VidCodec extends JsonCodec<VlanId> {
35
36 @Override
37 public ObjectNode encode(VlanId vid, CodecContext context) {
38 return context.mapper().createObjectNode().put("vid", vid.toString());
39 }
40
41 @Override
42 public ArrayNode encode(Iterable<VlanId> vids, CodecContext context) {
43 ArrayNode an = context.mapper().createArrayNode();
44 vids.forEach(vid -> {
45 an.add(encode(vid, context));
46 });
47 return an;
48 }
49
50 @Override
51 public VlanId decode(ObjectNode json, CodecContext context) {
52 if (json == null || !json.isObject()) {
53 return null;
54 }
55
56 JsonNode vidNode = json.get("vid");
57
58 int vid = (nullIsIllegal(vidNode.asInt(), "vid is required"));
59 if (vid < 0 || vid > 4095) {
60 throw new IllegalArgumentException("VID values must be between 0 and 4095");
61 }
62 return VlanId.vlanId((short) vid);
63 }
64
65 @Override
66 public List<VlanId> decode(ArrayNode json, CodecContext context) {
67 List<VlanId> vidList = new ArrayList<>();
68 json.forEach(node -> vidList.add(decode((ObjectNode) node, context)));
69 return vidList;
70 }
71}