Jian Li | 5a577a3 | 2017-04-04 12:37:53 +0900 | [diff] [blame] | 1 | /* |
Brian O'Connor | a09fe5b | 2017-08-03 21:12:30 -0700 | [diff] [blame] | 2 | * Copyright 2017-present Open Networking Foundation |
Jian Li | 5a577a3 | 2017-04-04 12:37:53 +0900 | [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 | */ |
Jian Li | 2e818b0 | 2017-04-12 19:28:30 +0900 | [diff] [blame] | 16 | package org.onosproject.mapping.codec; |
Jian Li | 5a577a3 | 2017-04-04 12:37:53 +0900 | [diff] [blame] | 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.mapping.DefaultMappingKey; |
| 22 | import org.onosproject.mapping.MappingKey; |
| 23 | import org.onosproject.mapping.addresses.MappingAddress; |
| 24 | |
| 25 | import static com.google.common.base.Preconditions.checkNotNull; |
| 26 | |
| 27 | /** |
| 28 | * Mapping key codec. |
| 29 | */ |
| 30 | public final class MappingKeyCodec extends JsonCodec<MappingKey> { |
| 31 | |
| 32 | protected static final String ADDRESS = "address"; |
| 33 | |
| 34 | @Override |
| 35 | public ObjectNode encode(MappingKey key, CodecContext context) { |
| 36 | checkNotNull(key, "Mapping key cannot be null"); |
| 37 | |
| 38 | final ObjectNode result = context.mapper().createObjectNode(); |
| 39 | final JsonCodec<MappingAddress> addressCodec = |
| 40 | context.codec(MappingAddress.class); |
| 41 | |
| 42 | result.set(ADDRESS, addressCodec.encode(key.address(), context)); |
| 43 | |
| 44 | return result; |
| 45 | } |
| 46 | |
| 47 | @Override |
| 48 | public MappingKey decode(ObjectNode json, CodecContext context) { |
| 49 | if (json == null || !json.isObject()) { |
| 50 | return null; |
| 51 | } |
| 52 | |
| 53 | MappingKey.Builder builder = DefaultMappingKey.builder(); |
| 54 | |
| 55 | ObjectNode addressJson = get(json, ADDRESS); |
| 56 | if (addressJson != null) { |
| 57 | final JsonCodec<MappingAddress> addressCodec = |
| 58 | context.codec(MappingAddress.class); |
| 59 | builder.withAddress(addressCodec.decode(addressJson, context)); |
| 60 | } |
| 61 | |
| 62 | return builder.build(); |
| 63 | } |
| 64 | } |