blob: f3c4ab98d12f14017973f4270a8fd5ff528e332b [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 */
pierventreb37a11a2021-03-18 16:50:04 +010016package org.onosproject.segmentrouting.policy.impl;
Wailok Shumee90c132021-03-11 21:00:11 +080017
18import com.fasterxml.jackson.databind.node.ArrayNode;
19import com.fasterxml.jackson.databind.node.ObjectNode;
20
21import org.onosproject.codec.CodecContext;
22import org.onosproject.codec.JsonCodec;
23import org.onosproject.net.DeviceId;
pierventreb37a11a2021-03-18 16:50:04 +010024import org.onosproject.segmentrouting.policy.api.RedirectPolicy;
Wailok Shumee90c132021-03-11 21:00:11 +080025
26import java.util.LinkedList;
27import java.util.List;
28import java.util.Set;
29
30import static org.onlab.util.Tools.nullIsIllegal;
31
32/**
33 * Codec of RedirectPolicy class.
34 */
35public final class RedirectPolicyCodec extends JsonCodec<RedirectPolicy> {
36
37 // JSON field names
38 public static final String POLICY_ID = "policy_id";
39 public static final String POLICY_TYPE = "policy_type";
40 public static final String SPINES_TO_ENFORCES = "spinesToEnforce";
41 public static final String DEVICE_ID = "deviceId";
42 public static final String MISSING_MEMBER_MESSAGE =
43 " member is required in Redirect Policy";
44
45 @Override
46 public ObjectNode encode(RedirectPolicy policy, CodecContext context) {
47 final ObjectNode result = context.mapper().createObjectNode()
48 .put(POLICY_ID, policy.policyId().toString())
49 .put(POLICY_TYPE, policy.policyType().toString());
50
51 ArrayNode deviceIdArr = result.putObject(SPINES_TO_ENFORCES).putArray(DEVICE_ID);
52 for (DeviceId deviceId : policy.spinesToEnforce()) {
53 deviceIdArr.add(deviceId.toString());
54 }
55
56 return result;
57 }
58
59 @Override
60 public RedirectPolicy decode(ObjectNode json, CodecContext context) {
61 List<DeviceId> spinesToEnforce = new LinkedList<>();
62
63 ObjectNode spinesNode = nullIsIllegal(get(json, SPINES_TO_ENFORCES),
64 SPINES_TO_ENFORCES + MISSING_MEMBER_MESSAGE);
65 ArrayNode deviceIdArr = nullIsIllegal((ArrayNode) spinesNode.get(DEVICE_ID),
66 DEVICE_ID + MISSING_MEMBER_MESSAGE);
67 deviceIdArr.forEach(deviceId -> spinesToEnforce.add(DeviceId.deviceId(deviceId.textValue())));
68
69 return new RedirectPolicy(Set.copyOf(spinesToEnforce));
70 }
71}