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