blob: b2d74b1e1c4758a8a2ee6ee58bf4e1b5e45bb176 [file] [log] [blame]
sangho1e575652015-05-14 00:39:53 -07001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
sangho1e575652015-05-14 00:39:53 -07003 *
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
Charles Chane849c192016-01-11 18:28:54 -080029/**
30 * Codec of Tunnel class.
31 */
sangho1e575652015-05-14 00:39:53 -070032public final class TunnelCodec extends JsonCodec<Tunnel> {
33
34 // JSON field names
35 private static final String TUNNEL_ID = "tunnel_id";
36 private static final String GROUP_ID = "group_id";
37 private static final String LABEL_PATH = "label_path";
38
39 @Override
40 public ObjectNode encode(Tunnel tunnel, CodecContext context) {
41 final ObjectNode result = context.mapper().createObjectNode()
42 .put(TUNNEL_ID, tunnel.id());
43
44 result.put(GROUP_ID, tunnel.groupId());
45
46 final ArrayNode jsonLabelIds = result.putArray(LABEL_PATH);
47
48 tunnel.labelIds().forEach(label -> jsonLabelIds.add(label.intValue()));
49
50 return result;
51 }
52
53 @Override
54 public DefaultTunnel decode(ObjectNode json, CodecContext context) {
55
56 String tid = json.path(TUNNEL_ID).asText();
57 List<Integer> labels = new ArrayList<>();
58
59 if (!json.path(LABEL_PATH).isMissingNode()) {
60 ArrayNode labelArray = (ArrayNode) json.path(LABEL_PATH);
61 for (JsonNode o : labelArray) {
62 labels.add(o.asInt());
63 }
64 }
65
66 return new DefaultTunnel(tid, labels);
67 }
68
69}