BUG-7833: Fix identityref codecs
[yangtools.git] / yang / yang-data-codec-gson / src / main / java / org / opendaylight / yangtools / yang / data / codec / gson / JSONCodecFactory.java
1 /*
2  * Copyright (c) 2014 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 com.google.common.annotations.Beta;
11 import com.google.common.base.Optional;
12 import com.google.common.base.Stopwatch;
13 import com.google.common.cache.CacheBuilder;
14 import com.google.common.cache.CacheLoader;
15 import com.google.common.cache.LoadingCache;
16 import java.util.List;
17 import org.opendaylight.yangtools.yang.common.QNameModule;
18 import org.opendaylight.yangtools.yang.data.impl.codec.AbstractIntegerStringCodec;
19 import org.opendaylight.yangtools.yang.data.impl.codec.BinaryStringCodec;
20 import org.opendaylight.yangtools.yang.data.impl.codec.BitsStringCodec;
21 import org.opendaylight.yangtools.yang.data.impl.codec.BooleanStringCodec;
22 import org.opendaylight.yangtools.yang.data.impl.codec.DecimalStringCodec;
23 import org.opendaylight.yangtools.yang.data.impl.codec.EnumStringCodec;
24 import org.opendaylight.yangtools.yang.data.impl.codec.StringStringCodec;
25 import org.opendaylight.yangtools.yang.data.util.codec.AbstractCodecFactory;
26 import org.opendaylight.yangtools.yang.data.util.codec.CodecCache;
27 import org.opendaylight.yangtools.yang.data.util.codec.LazyCodecCache;
28 import org.opendaylight.yangtools.yang.data.util.codec.NoopCodecCache;
29 import org.opendaylight.yangtools.yang.data.util.codec.PrecomputedCodecCache;
30 import org.opendaylight.yangtools.yang.data.util.codec.SharedCodecCache;
31 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
32 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
33 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
34 import org.opendaylight.yangtools.yang.model.api.TypedSchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
36 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
37 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
38 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
39 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
40 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
41 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
42 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
43 import org.opendaylight.yangtools.yang.model.api.type.IntegerTypeDefinition;
44 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
45 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
46 import org.opendaylight.yangtools.yang.model.api.type.UnknownTypeDefinition;
47 import org.opendaylight.yangtools.yang.model.api.type.UnsignedIntegerTypeDefinition;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 /**
52  * Factory for creating JSON equivalents of codecs. Each instance of this object is bound to
53  * a particular {@link SchemaContext}, but can be reused by multiple {@link JSONNormalizedNodeStreamWriter}s.
54  *
55  * There are multiple implementations available, each with distinct thread-safety, CPU/memory trade-offs and reuse
56  * characteristics. See {@link #getShared(SchemaContext)}, {@link #getPrecomputed(SchemaContext)},
57  * {@link #createLazy(SchemaContext)} and {@link #createSimple(SchemaContext)} for details.
58  */
59 @Beta
60 public final class JSONCodecFactory extends AbstractCodecFactory<JSONCodec<?>> {
61     private static final class EagerCacheLoader extends CacheLoader<SchemaContext, JSONCodecFactory> {
62         @Override
63         public JSONCodecFactory load(final SchemaContext key) {
64             final Stopwatch sw = Stopwatch.createStarted();
65             final LazyCodecCache<JSONCodec<?>> lazyCache = new LazyCodecCache<>();
66             final JSONCodecFactory lazy = new JSONCodecFactory(key, lazyCache);
67             final int visitedLeaves = requestCodecsForChildren(lazy, key);
68             sw.stop();
69
70             final PrecomputedCodecCache<JSONCodec<?>> cache = lazyCache.toPrecomputed();
71             LOG.debug("{} leaf nodes resulted in {} simple and {} complex codecs in {}", visitedLeaves,
72                 cache.simpleSize(), cache.complexSize(), sw);
73             return new JSONCodecFactory(key, cache);
74         }
75
76         private static int requestCodecsForChildren(final JSONCodecFactory lazy, final DataNodeContainer parent) {
77             int ret = 0;
78             for (DataSchemaNode child : parent.getChildNodes()) {
79                 if (child instanceof TypedSchemaNode) {
80                     lazy.codecFor((TypedSchemaNode) child);
81                     ++ret;
82                 } else if (child instanceof DataNodeContainer) {
83                     ret += requestCodecsForChildren(lazy, (DataNodeContainer) child);
84                 }
85             }
86
87             return ret;
88         }
89     }
90
91     private static final Logger LOG = LoggerFactory.getLogger(JSONCodecFactory.class);
92
93     // Weak keys to retire the entry when SchemaContext goes away
94     private static final LoadingCache<SchemaContext, JSONCodecFactory> PRECOMPUTED = CacheBuilder.newBuilder()
95             .weakKeys().build(new EagerCacheLoader());
96
97     // Weak keys to retire the entry when SchemaContext goes away and to force identity-based lookup
98     private static final LoadingCache<SchemaContext, JSONCodecFactory> SHARED = CacheBuilder.newBuilder()
99             .weakKeys().build(new CacheLoader<SchemaContext, JSONCodecFactory>() {
100                 @Override
101                 public JSONCodecFactory load(final SchemaContext key) {
102                     return new JSONCodecFactory(key, new SharedCodecCache<>());
103                 }
104             });
105
106     private final JSONCodec<?> iidCodec;
107
108     JSONCodecFactory(final SchemaContext context, final CodecCache<JSONCodec<?>> cache) {
109         super(context, cache);
110         iidCodec = new JSONStringInstanceIdentifierCodec(context, this);
111     }
112
113     /**
114      * Instantiate a new codec factory attached to a particular context.
115      *
116      * @param context SchemaContext to which the factory should be bound
117      * @return A codec factory instance.
118      *
119      * @deprecated Use {@link #getShared(SchemaContext)} instead.
120      */
121     @Deprecated
122     public static JSONCodecFactory create(final SchemaContext context) {
123         return getShared(context);
124     }
125
126     /**
127      * Get a thread-safe, eagerly-caching {@link JSONCodecFactory} for a SchemaContext. This method can, and will,
128      * return the same instance as long as the associated SchemaContext is present. Returned object can be safely
129      * used by multiple threads concurrently. If the SchemaContext instance does not have a cached instance
130      * of {@link JSONCodecFactory}, it will be completely precomputed before this method will return.
131      *
132      * Choosing this implementation is appropriate when the memory overhead of keeping a full codec tree is not as
133      * great a concern as predictable performance. When compared to the implementation returned by
134      * {@link #getShared(SchemaContext)}, this implementation is expected to offer higher performance and have lower
135      * peak memory footprint when most of the SchemaContext is actually in use.
136      *
137      * For call sites which do not want to pay the CPU cost of pre-computing this implementation, but still would like
138      * to use it if is available (by being populated by some other caller), you can use
139      * {@link #getPrecomputedIfAvailable(SchemaContext)}.
140      *
141      * @param context SchemaContext instance
142      * @return A sharable {@link JSONCodecFactory}
143      * @throws NullPointerException if context is null
144      */
145     public static JSONCodecFactory getPrecomputed(final SchemaContext context) {
146         return PRECOMPUTED.getUnchecked(context);
147     }
148
149     /**
150      * Get a thread-safe, eagerly-caching {@link JSONCodecFactory} for a SchemaContext, if it is available. This
151      * method is a non-blocking equivalent of {@link #getPrecomputed(SchemaContext)} for use in code paths where
152      * the potential of having to pre-compute the implementation is not acceptable. One such scenario is when the
153      * code base wants to opportunistically take advantage of pre-computed version, but is okay with a fallback to
154      * a different implementation.
155      *
156      * @param context SchemaContext instance
157      * @return A sharable {@link JSONCodecFactory}, or absent if such an implementation is not available.
158      * @throws NullPointerException if context is null
159      */
160     public static Optional<JSONCodecFactory> getPrecomputedIfAvailable(final SchemaContext context) {
161         return Optional.fromNullable(PRECOMPUTED.getIfPresent(context));
162     }
163
164     /**
165      * Get a thread-safe, lazily-caching {@link JSONCodecFactory} for a SchemaContext. This method can, and will,
166      * return the same instance as long as the associated SchemaContext is present or the factory is not invalidated
167      * by memory pressure. Returned object can be safely used by multiple threads concurrently.
168      *
169      * Choosing this implementation is a safe default, as it will not incur prohibitive blocking, nor will it tie up
170      * memory in face of pressure.
171      *
172      * @param context SchemaContext instance
173      * @return A sharable {@link JSONCodecFactory}
174      * @throws NullPointerException if context is null
175      */
176     public static JSONCodecFactory getShared(final SchemaContext context) {
177         return SHARED.getUnchecked(context);
178     }
179
180     /**
181      * Create a new thread-unsafe, lazily-caching {@link JSONCodecFactory} for a SchemaContext. This method will
182      * return distinct objects every time it is invoked. Returned object may not be used from multiple threads
183      * concurrently.
184      *
185      * This implementation is appropriate for one-off serialization from a single thread. It will aggressively cache
186      * codecs for reuse and will tie them up in memory until the factory is freed.
187      *
188      * @param context SchemaContext instance
189      * @return A non-sharable {@link JSONCodecFactory}
190      * @throws NullPointerException if context is null
191      */
192     public static JSONCodecFactory createLazy(final SchemaContext context) {
193         return new JSONCodecFactory(context, new LazyCodecCache<>());
194     }
195
196     /**
197      * Create a simplistic, thread-safe {@link JSONCodecFactory} for a {@link SchemaContext}. This method will return
198      * distinct objects every time it is invoked. Returned object may be use from multiple threads concurrently.
199      *
200      * This implementation exists mostly for completeness only, as it does not perform any caching at all and each codec
201      * is computed every time it is requested. This may be useful in extremely constrained environments, where memory
202      * footprint is more critical than performance.
203      *
204      * @param context SchemaContext instance
205      * @return A non-sharable {@link JSONCodecFactory}
206      * @throws NullPointerException if context is null.
207      */
208     public static JSONCodecFactory createSimple(final SchemaContext context) {
209         return new JSONCodecFactory(context, NoopCodecCache.getInstance());
210     }
211
212     @Override
213     protected JSONCodec<?> binaryCodec(final BinaryTypeDefinition type) {
214         return new QuotedJSONCodec<>(BinaryStringCodec.from(type));
215     }
216
217     @Override
218     protected JSONCodec<?> booleanCodec(final BooleanTypeDefinition type) {
219         return new BooleanJSONCodec(BooleanStringCodec.from(type));
220     }
221
222     @Override
223     protected JSONCodec<?> bitsCodec(final BitsTypeDefinition type) {
224         return new QuotedJSONCodec<>(BitsStringCodec.from(type));
225     }
226
227     @Override
228     protected JSONCodec<?> decimalCodec(final DecimalTypeDefinition type) {
229         return new NumberJSONCodec<>(DecimalStringCodec.from(type));
230     }
231
232     @Override
233     protected JSONCodec<?> emptyCodec(final EmptyTypeDefinition type) {
234         return EmptyJSONCodec.INSTANCE;
235     }
236
237     @Override
238     protected JSONCodec<?> enumCodec(final EnumTypeDefinition type) {
239         return new QuotedJSONCodec<>(EnumStringCodec.from(type));
240     }
241
242     @Override
243     protected JSONCodec<?> identityRefCodec(final IdentityrefTypeDefinition type, final QNameModule module) {
244         return new IdentityrefJSONCodec(getSchemaContext(), module);
245     }
246
247     @Override
248     protected JSONCodec<?> instanceIdentifierCodec(final InstanceIdentifierTypeDefinition type) {
249         // FIXME: there really are two favors, as 'require-instance true' needs to be validated. In order to deal
250         //        with that, though, we need access to the current data store.
251         return iidCodec;
252     }
253
254     @Override
255     protected JSONCodec<?> intCodec(final IntegerTypeDefinition type) {
256         return new NumberJSONCodec<>(AbstractIntegerStringCodec.from(type));
257     }
258
259     @Override
260     protected JSONCodec<?> stringCodec(final StringTypeDefinition type) {
261         return new QuotedJSONCodec<>(StringStringCodec.from(type));
262     }
263
264     @Override
265     protected JSONCodec<?> uintCodec(final UnsignedIntegerTypeDefinition type) {
266         return new NumberJSONCodec<>(AbstractIntegerStringCodec.from(type));
267     }
268
269     @Override
270     protected JSONCodec<?> unionCodec(final UnionTypeDefinition type, final List<JSONCodec<?>> codecs) {
271         return UnionJSONCodec.create(type, codecs);
272     }
273
274     @Override
275     protected JSONCodec<?> unknownCodec(final UnknownTypeDefinition type) {
276         return NullJSONCodec.INSTANCE;
277     }
278 }