blob: 9a7f7f9fcfc021bc692cc1eb6ddf5a8450a72c6a [file] [log] [blame]
Jian Lib68a2b02016-05-02 11:23:32 -07001/*
2 * Copyright 2016-present 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.codec.impl;
17
18import com.fasterxml.jackson.databind.node.ObjectNode;
19import org.onosproject.codec.CodecContext;
20import org.onosproject.codec.JsonCodec;
21import org.onosproject.net.MastershipRole;
22import org.slf4j.Logger;
23
24import static com.google.common.base.Preconditions.checkNotNull;
25import static org.onlab.util.Tools.nullIsIllegal;
26import static org.onosproject.net.MastershipRole.MASTER;
27import static org.onosproject.net.MastershipRole.NONE;
28import static org.onosproject.net.MastershipRole.STANDBY;
29import static org.slf4j.LoggerFactory.getLogger;
30
31/**
32 * Codec for mastership role.
33 */
34public final class MastershipRoleCodec extends JsonCodec<MastershipRole> {
35 private final Logger log = getLogger(getClass());
36
37 // JSON field names
38 private static final String ROLE = "role";
39
40 private static final String MISSING_MEMBER_MESSAGE = " member is required in MastershipRole";
41
42 @Override
43 public ObjectNode encode(MastershipRole mastershipRole, CodecContext context) {
44 checkNotNull(mastershipRole, "MastershipRole cannot be null");
45 ObjectNode result = context.mapper().createObjectNode()
46 .put(ROLE, mastershipRole.name());
47 return result;
48 }
49
50 @Override
51 public MastershipRole decode(ObjectNode json, CodecContext context) {
52 if (json == null || !json.isObject()) {
53 return null;
54 }
55
56 String roleJson = nullIsIllegal(json.get(ROLE),
57 ROLE + MISSING_MEMBER_MESSAGE).asText();
58 MastershipRole mastershipRole;
59 switch (roleJson) {
60 case "MASTER":
61 mastershipRole = MASTER;
62 break;
63 case "STANDBY":
64 mastershipRole = STANDBY;
65 break;
66 case "NONE":
67 mastershipRole = NONE;
68 break;
69 default:
70 log.warn("The mastership role {} is not defined.", roleJson);
71 return null;
72 }
73
74 return mastershipRole;
75 }
76}