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