blob: 0a097b20e51a7702ee73e786f67f54cadde38648 [file] [log] [blame]
Jonathan Hart443ebed2015-05-05 14:02:12 -07001/*
2 * Copyright 2015 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 */
16
17package org.onosproject.cordfabric;
18
19import com.fasterxml.jackson.databind.JsonNode;
20import com.fasterxml.jackson.databind.node.ArrayNode;
21import com.fasterxml.jackson.databind.node.ObjectNode;
22import org.onlab.packet.VlanId;
23import org.onosproject.codec.CodecContext;
24import org.onosproject.codec.JsonCodec;
25import org.onosproject.net.ConnectPoint;
26
27import java.util.ArrayList;
28import java.util.List;
29
30import static com.google.common.base.Preconditions.checkNotNull;
31
32/**
33 * Codec for encoding/decoding a FabricVlan object to/from JSON.
34 */
35public final class FabricVlanCodec extends JsonCodec<FabricVlan> {
36
37 // JSON field names
38 private static final String VLAN = "vlan";
39 private static final String PORTS = "ports";
40
41 @Override
42 public ObjectNode encode(FabricVlan vlan, CodecContext context) {
43 checkNotNull(vlan, "Vlan cannot be null");
44 final ObjectNode result = context.mapper().createObjectNode()
45 .put(VLAN, vlan.vlan().toShort());
46
47 final ArrayNode jsonPorts = result.putArray(PORTS);
48
49 vlan.ports().forEach(cp -> jsonPorts.add(context.codec(ConnectPoint.class).encode(cp, context)));
50
51 return result;
52 }
53
54 @Override
55 public FabricVlan decode(ObjectNode json, CodecContext context) {
56 short vlan = json.path(VLAN).shortValue();
57 List<ConnectPoint> ports = new ArrayList<>();
58
59 ArrayNode portArray = (ArrayNode) json.path(PORTS);
60 for (JsonNode o : portArray) {
61 ports.add(context.codec(ConnectPoint.class).decode((ObjectNode) o, context));
62 }
63
64 return new FabricVlan(VlanId.vlanId(vlan), ports);
65 }
66}