blob: bd69ca8ed5fcaabf3be811c24ba58978fe30e6cd [file] [log] [blame]
Jian Lib5d82212017-04-25 01:45:18 +09001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2017-present Open Networking Foundation
Jian Lib5d82212017-04-25 01:45:18 +09003 *
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.mapping.codec;
17
18import com.fasterxml.jackson.databind.node.ObjectNode;
19import org.onosproject.codec.CodecContext;
20import org.onosproject.codec.JsonCodec;
21import org.onosproject.mapping.MappingEntry;
22import org.onosproject.mapping.MappingKey;
23import org.onosproject.mapping.MappingValue;
24
25import static com.google.common.base.Preconditions.checkNotNull;
26
27/**
28 * Mapping entry JSON codec.
29 */
30public 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}