Jian Li | b5d8221 | 2017-04-25 01:45:18 +0900 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2017-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 | */ |
| 16 | package org.onosproject.mapping.codec; |
| 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.MappingEntry; |
| 22 | import org.onosproject.mapping.MappingKey; |
| 23 | import org.onosproject.mapping.MappingValue; |
| 24 | |
| 25 | import static com.google.common.base.Preconditions.checkNotNull; |
| 26 | |
| 27 | /** |
| 28 | * Mapping entry JSON codec. |
| 29 | */ |
| 30 | public final class MappingEntryCodec extends JsonCodec<MappingEntry> { |
| 31 | |
| 32 | protected static final String KEY = "key"; |
| 33 | protected static final String VALUE = "value"; |
| 34 | protected static final String ID = "id"; |
| 35 | protected static final String DEVICE_ID = "deviceId"; |
| 36 | protected static final String STATE = "state"; |
| 37 | |
| 38 | @Override |
| 39 | public ObjectNode encode(MappingEntry mappingEntry, CodecContext context) { |
| 40 | |
| 41 | checkNotNull(mappingEntry, "Mapping entry cannot be null"); |
| 42 | |
| 43 | final ObjectNode result = context.mapper().createObjectNode() |
| 44 | .put(ID, Long.toString(mappingEntry.id().value())) |
| 45 | .put(DEVICE_ID, mappingEntry.deviceId().toString()) |
| 46 | .put(STATE, mappingEntry.state().toString()); |
| 47 | |
| 48 | if (mappingEntry.key() != null) { |
| 49 | final JsonCodec<MappingKey> keyCodec = |
| 50 | context.codec(MappingKey.class); |
| 51 | result.set(KEY, keyCodec.encode(mappingEntry.key(), context)); |
| 52 | } |
| 53 | |
| 54 | if (mappingEntry.value() != null) { |
| 55 | final JsonCodec<MappingValue> valueCodec = |
| 56 | context.codec(MappingValue.class); |
| 57 | result.set(VALUE, valueCodec.encode(mappingEntry.value(), context)); |
| 58 | } |
| 59 | |
| 60 | return result; |
| 61 | } |
| 62 | } |