blob: 4338cdeb309e4d8cb93b5fb177c5c4cd0cfb88f3 [file] [log] [blame]
Thomas Vachuskad404c512014-10-23 14:19:46 -07001/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19package org.onlab.onos.codec;
20
21import com.fasterxml.jackson.databind.JsonNode;
22import com.fasterxml.jackson.databind.ObjectMapper;
23import com.fasterxml.jackson.databind.node.ArrayNode;
24import com.fasterxml.jackson.databind.node.ObjectNode;
25
26import java.util.ArrayList;
27import java.util.List;
28
29/**
30 * Abstraction of a codec capable for encoding/decoding arbitrary objects to/from JSON.
31 */
32public abstract class JsonCodec<T> {
33
34 /**
35 * Encodes the specified entity into JSON.
36 *
37 * @param entity entity to encode
38 * @param mapper object mapper
39 * @return JSON node
40 * @throws java.lang.UnsupportedOperationException if the codec does not
41 * support encode operations
42 */
43 public abstract ObjectNode encode(T entity, ObjectMapper mapper);
44
45 /**
46 * Decodes the specified entity from JSON.
47 *
48 * @param json JSON to decode
49 * @return decoded entity
50 * @throws java.lang.UnsupportedOperationException if the codec does not
51 * support decode operations
52 */
53 public abstract T decode(ObjectNode json);
54
55 /**
56 * Encodes the collection of the specified entities.
57 *
58 * @param entities collection of entities to encode
59 * @param mapper object mapper
60 * @return JSON array
61 * @throws java.lang.UnsupportedOperationException if the codec does not
62 * support encode operations
63 */
64 public ArrayNode encode(Iterable<T> entities, ObjectMapper mapper) {
65 ArrayNode result = mapper.createArrayNode();
66 for (T entity : entities) {
67 result.add(encode(entity, mapper));
68 }
69 return result;
70 }
71
72 /**
73 * Decodes the specified JSON array into a collection of entities.
74 *
75 * @param json JSON array to decode
76 * @return collection of decoded entities
77 * @throws java.lang.UnsupportedOperationException if the codec does not
78 * support decode operations
79 */
80 public List<T> decode(ArrayNode json) {
81 List<T> result = new ArrayList<>();
82 for (JsonNode node : json) {
83 result.add(decode((ObjectNode) node));
84 }
85 return result;
86 }
87
88}