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