blob: 2f85afd513dcdbebc779e5971c2db3807b1dd11d [file] [log] [blame]
sangho1e575652015-05-14 00:39:53 -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 */
16package org.onosproject.segmentrouting.web;
17
18import com.fasterxml.jackson.databind.JsonNode;
19import com.fasterxml.jackson.databind.node.ArrayNode;
20import org.onosproject.codec.CodecContext;
21import org.onosproject.codec.JsonCodec;
22import com.fasterxml.jackson.databind.node.ObjectNode;
23import org.onosproject.segmentrouting.DefaultTunnel;
24import org.onosproject.segmentrouting.Tunnel;
25
26import java.util.ArrayList;
27import java.util.List;
28
29public final class TunnelCodec extends JsonCodec<Tunnel> {
30
31 // JSON field names
32 private static final String TUNNEL_ID = "tunnel_id";
33 private static final String GROUP_ID = "group_id";
34 private static final String LABEL_PATH = "label_path";
35
36 @Override
37 public ObjectNode encode(Tunnel tunnel, CodecContext context) {
38 final ObjectNode result = context.mapper().createObjectNode()
39 .put(TUNNEL_ID, tunnel.id());
40
41 result.put(GROUP_ID, tunnel.groupId());
42
43 final ArrayNode jsonLabelIds = result.putArray(LABEL_PATH);
44
45 tunnel.labelIds().forEach(label -> jsonLabelIds.add(label.intValue()));
46
47 return result;
48 }
49
50 @Override
51 public DefaultTunnel decode(ObjectNode json, CodecContext context) {
52
53 String tid = json.path(TUNNEL_ID).asText();
54 List<Integer> labels = new ArrayList<>();
55
56 if (!json.path(LABEL_PATH).isMissingNode()) {
57 ArrayNode labelArray = (ArrayNode) json.path(LABEL_PATH);
58 for (JsonNode o : labelArray) {
59 labels.add(o.asInt());
60 }
61 }
62
63 return new DefaultTunnel(tid, labels);
64 }
65
66}