blob: 6eb3b73a46d3e4d6a47e683d82cf834386b4cb06 [file] [log] [blame]
Claudine Chiufb8b8162016-04-01 23:50:51 +00001/*
Brian O'Connor5ab426f2016-04-09 01:19:45 -07002 * Copyright 2016-present Open Networking Laboratory
Claudine Chiufb8b8162016-04-01 23:50:51 +00003 *
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.incubator.net.virtual.TenantId;
22
23
24import static com.google.common.base.Preconditions.checkNotNull;
25import static org.onlab.util.Tools.nullIsIllegal;
26
27/**
28 * Codec for the TenantId class.
29 */
30public class TenantIdCodec extends JsonCodec<TenantId> {
31
32 // JSON field names
33 private static final String TENANT_ID = "id";
34
35 private static final String NULL_TENANT_MSG = "TenantId cannot be null";
36 private static final String MISSING_MEMBER_MSG = " member is required in TenantId";
37
38 @Override
39 public ObjectNode encode(TenantId tenantId, CodecContext context) {
40 checkNotNull(tenantId, NULL_TENANT_MSG);
41
42 ObjectNode result = context.mapper().createObjectNode()
43 .put(TENANT_ID, tenantId.id().toString());
44
45 return result;
46 }
47
48 @Override
49 public TenantId decode(ObjectNode json, CodecContext context) {
50 if (json == null || !json.isObject()) {
51 return null;
52 }
53
54 TenantId tenantId = TenantId.tenantId(extractMember(TENANT_ID, json));
55
56 return tenantId;
57 }
58
59 private String extractMember(String key, ObjectNode json) {
60 return nullIsIllegal(json.get(key), key + MISSING_MEMBER_MSG).asText();
61 }
62}