blob: 176ec36fa85be7c64ef09ec5f17a235f12a7f3de [file] [log] [blame]
Jian Li5a577a32017-04-04 12:37:53 +09001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2017-present Open Networking Foundation
Jian Li5a577a32017-04-04 12:37:53 +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 */
Jian Li2e818b02017-04-12 19:28:30 +090016package org.onosproject.mapping.codec;
Jian Li5a577a32017-04-04 12:37:53 +090017
18import com.fasterxml.jackson.databind.node.ObjectNode;
19import org.onosproject.codec.CodecContext;
20import org.onosproject.codec.JsonCodec;
21import org.onosproject.mapping.DefaultMappingKey;
22import org.onosproject.mapping.MappingKey;
23import org.onosproject.mapping.addresses.MappingAddress;
24
25import static com.google.common.base.Preconditions.checkNotNull;
26
27/**
28 * Mapping key codec.
29 */
30public 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}