blob: 1f4f8be6e4397d36e55f6dc5cd2526d4f1369f99 [file] [log] [blame]
Wailok Shumee90c132021-03-11 21:00:11 +08001/*
2 * Copyright 2021-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.segmentrouting.policy.api;
17
18import com.fasterxml.jackson.databind.node.ObjectNode;
19
20import org.onosproject.codec.CodecContext;
21import org.onosproject.codec.JsonCodec;
22import org.onosproject.net.flow.TrafficSelector;
23
24import static org.onlab.util.Tools.nullIsIllegal;
25
26/**
27 * Codec of TrafficMatch class.
28 */
29public final class TrafficMatchCodec extends JsonCodec<TrafficMatch> {
30
31 // JSON field names
32 public static final String TRAFFIC_MATCH_ID = "traffic_match_id";
33 public static final String TRAFFIC_SELECTOR = "selector";
34 public static final String POLICY_ID = "policy_id";
35 public static final String MISSING_MEMBER_MESSAGE =
36 " member is required in Traffic Match";
37
38 @Override
39 public ObjectNode encode(TrafficMatch trafficMatch, CodecContext context) {
40 final JsonCodec<TrafficSelector> selectorCodec =
41 context.codec(TrafficSelector.class);
42
43 final ObjectNode selector = selectorCodec.encode(trafficMatch.trafficSelector(), context);
44 final ObjectNode result = context.mapper().createObjectNode()
45 .put(TRAFFIC_MATCH_ID, trafficMatch.trafficMatchId().toString())
46 .put(POLICY_ID, trafficMatch.policyId().toString())
47 .set(TRAFFIC_SELECTOR, selector);
48
49 return result;
50 }
51
52 @Override
53 public TrafficMatch decode(ObjectNode json, CodecContext context) {
54 final JsonCodec<TrafficSelector> selectorCodec =
55 context.codec(TrafficSelector.class);
56
57 ObjectNode selectorJson = nullIsIllegal(get(json, TRAFFIC_SELECTOR),
58 TRAFFIC_SELECTOR + MISSING_MEMBER_MESSAGE);
59 TrafficSelector trafficSelector = selectorCodec.decode(selectorJson, context);
60
61 PolicyId policyId = PolicyId.of(nullIsIllegal(json.get(POLICY_ID),
62 POLICY_ID + MISSING_MEMBER_MESSAGE).asText());
63
64 return new TrafficMatch(trafficSelector, policyId);
65 }
66}