blob: b33dca1a1620dc621a1258b9355a9d7ea5c4a00b [file] [log] [blame]
Jonathan Hart8338b8d2017-08-15 15:46:14 -07001/*
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.routeservice.rest;
17
18import com.fasterxml.jackson.databind.node.ObjectNode;
19import org.onlab.packet.IpAddress;
20import org.onlab.packet.IpPrefix;
21import org.onosproject.codec.CodecContext;
22import org.onosproject.codec.JsonCodec;
23import org.onosproject.routeservice.Route;
24
25import static com.google.common.base.Preconditions.checkNotNull;
26
27/**
28 * Codec to encode and decode a unicast route to and from JSON.
29 */
30public class RouteCodec extends JsonCodec<Route> {
31
32 private static final String SOURCE = "source";
33 private static final String PREFIX = "prefix";
34 private static final String NEXT_HOP = "nextHop";
35
36 @Override
37 public ObjectNode encode(Route route, CodecContext context) {
38 checkNotNull(route);
39 ObjectNode root = context.mapper().createObjectNode()
40 .put(SOURCE, route.source().toString())
41 .put(PREFIX, route.prefix().toString())
42 .put(NEXT_HOP, route.nextHop().toString());
43
44 return root;
45 }
46
47 @Override
48 public Route decode(ObjectNode json, CodecContext context) {
49 if (json == null || !json.isObject()) {
50 return null;
51 }
52
53 IpPrefix prefix = IpPrefix.valueOf(json.path(PREFIX).asText());
54 IpAddress nextHop = IpAddress.valueOf(json.path(NEXT_HOP).asText());
psneha36b60f92018-08-29 08:56:08 -040055 String source = json.path(SOURCE).asText();
Jonathan Hart8338b8d2017-08-15 15:46:14 -070056
psneha36b60f92018-08-29 08:56:08 -040057 // Routes through the REST API without mentioning source in the json are created as STATIC,
58 // otherwise routes are created with corresponding source.
Jonathan Hart8338b8d2017-08-15 15:46:14 -070059
psneha36b60f92018-08-29 08:56:08 -040060 Route route = source.isEmpty() ?
61 new Route(Route.Source.STATIC, prefix, nextHop) :
62 new Route(Route.Source.valueOf(source), prefix, nextHop);
Jonathan Hart8338b8d2017-08-15 15:46:14 -070063 return route;
64 }
65}