BUG-7996: expose different implementations of JSONCodecFactory
[yangtools.git] / yang / yang-data-codec-gson / src / main / java / org / opendaylight / yangtools / yang / data / codec / gson / LazyJSONCodecFactory.java
1 /*
2  * Copyright (c) 2017 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.yang.data.codec.gson;
9
10 import java.util.IdentityHashMap;
11 import java.util.Map;
12 import javax.annotation.concurrent.NotThreadSafe;
13 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
14 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
15 import org.opendaylight.yangtools.yang.model.api.TypedSchemaNode;
16
17 /**
18  * Lazily-computed JSONCodecFactory. This is a non-thread-safe factory, which performs caching of codecs. It is most
19  * appropriate for one-off encodings of repetitive data.
20  *
21  * @author Robert Varga
22  */
23 @NotThreadSafe
24 final class LazyJSONCodecFactory extends JSONCodecFactory {
25     private final Map<TypedSchemaNode, JSONCodec<?>> complexCodecs = new IdentityHashMap<>();
26     private final Map<TypeDefinition<?>, JSONCodec<?>> simpleCodecs = new IdentityHashMap<>();
27
28     LazyJSONCodecFactory(final SchemaContext context) {
29         super(context);
30     }
31
32     @Override
33     JSONCodec<?> getComplex(final TypedSchemaNode schema, final JSONCodec<?> codec) {
34         return getComplexCodecs().computeIfAbsent(schema, any -> codec);
35     }
36
37     @Override
38     JSONCodec<?> lookupComplex(final TypedSchemaNode schema) {
39         return getComplexCodecs().get(schema);
40     }
41
42     @Override
43     JSONCodec<?> lookupSimple(final TypeDefinition<?> type) {
44         return getSimpleCodecs().get(type);
45     }
46
47     @Override
48     JSONCodec<?> getSimple(final TypeDefinition<?> type, final JSONCodec<?> codec) {
49         return getSimpleCodecs().computeIfAbsent(type, any -> codec);
50     }
51
52     Map<TypeDefinition<?>, JSONCodec<?>> getSimpleCodecs() {
53         return simpleCodecs;
54     }
55
56     Map<TypedSchemaNode, JSONCodec<?>> getComplexCodecs() {
57         return complexCodecs;
58     }
59 }