Claudine Chiu | fb8b816 | 2016-04-01 23:50:51 +0000 | [diff] [blame] | 1 | /* |
Brian O'Connor | a09fe5b | 2017-08-03 21:12:30 -0700 | [diff] [blame] | 2 | * Copyright 2016-present Open Networking Foundation |
Claudine Chiu | fb8b816 | 2016-04-01 23:50:51 +0000 | [diff] [blame] | 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 | */ |
| 16 | package org.onosproject.codec.impl; |
| 17 | |
| 18 | import com.fasterxml.jackson.databind.node.ObjectNode; |
| 19 | import org.onosproject.codec.CodecContext; |
| 20 | import org.onosproject.codec.JsonCodec; |
| 21 | import org.onosproject.incubator.net.virtual.TenantId; |
| 22 | |
| 23 | |
| 24 | import static com.google.common.base.Preconditions.checkNotNull; |
| 25 | import static org.onlab.util.Tools.nullIsIllegal; |
| 26 | |
| 27 | /** |
| 28 | * Codec for the TenantId class. |
| 29 | */ |
| 30 | public 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() |
Sho SHIMIZU | ef17cbd | 2016-08-12 17:19:10 -0700 | [diff] [blame] | 43 | .put(TENANT_ID, tenantId.id()); |
Claudine Chiu | fb8b816 | 2016-04-01 23:50:51 +0000 | [diff] [blame] | 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 | } |