blob: 89612e908fff14707e16689dd37271c085a0f72d [file] [log] [blame]
Thomas Vachuskaca60f2b2014-11-06 01:34:28 -08001/*
Brian O'Connor5ab426f2016-04-09 01:19:45 -07002 * Copyright 2015-present Open Networking Laboratory
Thomas Vachuskaca60f2b2014-11-06 01:34:28 -08003 *
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 */
Brian O'Connorabafb502014-12-02 22:26:20 -080016package org.onosproject.codec.impl;
Thomas Vachuskaca60f2b2014-11-06 01:34:28 -080017
18import com.fasterxml.jackson.databind.node.ObjectNode;
HIGUCHI Yuta5bb99a42015-03-19 16:52:15 -070019
Brian O'Connorabafb502014-12-02 22:26:20 -080020import org.onosproject.codec.CodecContext;
21import org.onosproject.codec.JsonCodec;
22import org.onosproject.net.Annotated;
23import org.onosproject.net.Annotations;
HIGUCHI Yuta5bb99a42015-03-19 16:52:15 -070024import org.onosproject.net.DefaultAnnotations;
Thomas Vachuskaca60f2b2014-11-06 01:34:28 -080025
26/**
27 * Base JSON codec for annotated entities.
28 */
29public abstract class AnnotatedCodec<T extends Annotated> extends JsonCodec<T> {
30
31 /**
32 * Adds JSON encoding of the given item annotations to the specified node.
33 *
34 * @param node node to add annotations to
35 * @param entity annotated entity
36 * @param context encode context
37 * @return the given node
38 */
39 protected ObjectNode annotate(ObjectNode node, T entity, CodecContext context) {
40 if (!entity.annotations().keys().isEmpty()) {
41 JsonCodec<Annotations> codec = context.codec(Annotations.class);
42 node.set("annotations", codec.encode(entity.annotations(), context));
43 }
44 return node;
45 }
46
HIGUCHI Yuta5bb99a42015-03-19 16:52:15 -070047 /**
48 * Extracts annotations of given Object.
49 *
50 * @param objNode annotated JSON object node
51 * @param context decode context
52 * @return extracted Annotations
53 */
54 protected Annotations extractAnnotations(ObjectNode objNode, CodecContext context) {
55
56 JsonCodec<Annotations> codec = context.codec(Annotations.class);
57 if (objNode.has("annotations") && objNode.isObject()) {
Ray Milkeyb82c42b2015-06-30 09:42:20 -070058 return codec.decode(get(objNode, "annotations"), context);
HIGUCHI Yuta5bb99a42015-03-19 16:52:15 -070059 } else {
60 return DefaultAnnotations.EMPTY;
61 }
62 }
63
Thomas Vachuskaca60f2b2014-11-06 01:34:28 -080064}