blob: f482a4833309a4ea2b3be0d1f33ed4affd579a0e [file] [log] [blame]
Thomas Vachuskad404c512014-10-23 14:19:46 -07001/*
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07002 * Copyright 2014 Open Networking Laboratory
Thomas Vachuskad404c512014-10-23 14:19:46 -07003 *
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07004 * 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
Thomas Vachuskad404c512014-10-23 14:19:46 -07007 *
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07008 * 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.
Thomas Vachuskad404c512014-10-23 14:19:46 -070015 */
16package org.onlab.onos.codec;
17
18import com.fasterxml.jackson.databind.ObjectMapper;
19import com.fasterxml.jackson.databind.node.ArrayNode;
20import com.fasterxml.jackson.databind.node.ObjectNode;
21import com.google.common.collect.ImmutableList;
22import org.junit.Test;
23
24import java.util.List;
25import java.util.Objects;
26
27import static org.junit.Assert.assertEquals;
28
29/**
30 * Test of the base JSON codec abstraction.
31 */
32public class JsonCodecTest {
33
34 private static class Foo {
35 final String name;
36
37 Foo(String name) {
38 this.name = name;
39 }
40
41 @Override
42 public int hashCode() {
43 return Objects.hash(name);
44 }
45
46 @Override
47 public boolean equals(Object obj) {
48 if (this == obj) {
49 return true;
50 }
51 if (obj == null || getClass() != obj.getClass()) {
52 return false;
53 }
54 final Foo other = (Foo) obj;
55 return Objects.equals(this.name, other.name);
56 }
57 }
58
59 private static class FooCodec extends JsonCodec<Foo> {
60 @Override
61 public ObjectNode encode(Foo entity, ObjectMapper mapper) {
62 return mapper.createObjectNode().put("name", entity.name);
63 }
64
65 @Override
66 public Foo decode(ObjectNode json) {
67 return new Foo(json.get("name").asText());
68 }
69 }
70
71 @Test
72 public void encode() {
73 Foo f1 = new Foo("foo");
74 Foo f2 = new Foo("bar");
75 FooCodec codec = new FooCodec();
76 ImmutableList<Foo> entities = ImmutableList.of(f1, f2);
77 ArrayNode json = codec.encode(entities, new ObjectMapper());
78 List<Foo> foos = codec.decode(json);
79 assertEquals("incorrect encode/decode", entities, foos);
80 }
81
82}