blob: 446be58cc882163675fabe6d36006b80bc5a7935 [file] [log] [blame]
Jian Lie1c1c8d2016-05-09 16:24:40 -07001/*
2 * Copyright 2016-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 */
16package org.onosproject.codec.impl;
17
18import com.fasterxml.jackson.databind.node.ObjectNode;
19import org.onosproject.codec.CodecContext;
20import org.onosproject.codec.JsonCodec;
21import org.onosproject.core.ApplicationId;
22import org.onosproject.core.DefaultApplicationId;
23
24import static com.google.common.base.Preconditions.checkNotNull;
25import static org.onlab.util.Tools.nullIsIllegal;
26
27/**
28 * ApplicationId JSON codec.
29 */
30public final class ApplicationIdCodec extends JsonCodec<ApplicationId> {
31
32 private static final String APP_ID = "id";
33 private static final String APP_NAME = "name";
34
35 private static final String MISSING_MEMBER_MESSAGE = " member is required in ApplicationId";
36
37 @Override
38 public ObjectNode encode(ApplicationId appId, CodecContext context) {
39 checkNotNull(appId, "ApplicationId cannot be null");
40
41 ObjectNode result = context.mapper().createObjectNode()
42 .put("id", appId.id())
43 .put("name", appId.name());
44
45 return result;
46 }
47
48 @Override
49 public ApplicationId decode(ObjectNode json, CodecContext context) {
50 if (json == null || !json.isObject()) {
51 return null;
52 }
53
54 // parse application identifier
55 int id = nullIsIllegal(json.get(APP_ID), APP_ID + MISSING_MEMBER_MESSAGE).asInt();
56
57 // parse application name
58 String name = nullIsIllegal(json.get(APP_NAME), APP_NAME + MISSING_MEMBER_MESSAGE).asText();
59
60 return new DefaultApplicationId(id, name);
61 }
62}