blob: c8f3915a4b9c193106e2a8e163fd686559b24f05 [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.cluster.NodeId;
20import org.onosproject.codec.CodecContext;
21import org.onosproject.codec.JsonCodec;
22import org.onosproject.mastership.MastershipTerm;
23
24import static com.google.common.base.Preconditions.checkNotNull;
25import static org.onlab.util.Tools.nullIsIllegal;
26
27/**
28 * Codec for mastership term.
29 */
30public class MastershipTermCodec extends JsonCodec<MastershipTerm> {
31
32 // JSON field names
33 private static final String MASTER = "master";
34 private static final String TERM_NUMBER = "termNumber";
35
36 private static final String MISSING_MEMBER_MESSAGE = " member is required in MastershipTerm";
37
38 @Override
39 public ObjectNode encode(MastershipTerm term, CodecContext context) {
40 checkNotNull(term, "Mastership term cannot be null");
41 ObjectNode result = context.mapper().createObjectNode()
42 .put(MASTER, term.master().id())
43 .put(TERM_NUMBER, term.termNumber());
44
45 return result;
46 }
47
48 @Override
49 public MastershipTerm decode(ObjectNode json, CodecContext context) {
50 if (json == null || !json.isObject()) {
51 return null;
52 }
53
54 // node identifier of master
55 NodeId nodeId = NodeId.nodeId(nullIsIllegal(json.get(MASTER),
56 MASTER + MISSING_MEMBER_MESSAGE).asText());
57
58 // term number
59 long termNumber = nullIsIllegal(json.get(TERM_NUMBER),
60 TERM_NUMBER + MISSING_MEMBER_MESSAGE).asLong();
61
62 return MastershipTerm.of(nodeId, termNumber);
63 }
64}