Cleanup use of Guava library
[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      * Instantiate a new codec factory attached to a particular context.
116      *
117      * @param context SchemaContext to which the factory should be bound
118      * @return A codec factory instance.
119      *
120      * @deprecated Use {@link #getShared(SchemaContext)} instead.
121      */
122     @Deprecated
123     public static JSONCodecFactory create(final SchemaContext context) {
124         return getShared(context);
125     }
126
127     /**
128      * Get a thread-safe, eagerly-caching {@link JSONCodecFactory} for a SchemaContext. This method can, and will,
129      * return the same instance as long as the associated SchemaContext is present. Returned object can be safely
130      * used by multiple threads concurrently. If the SchemaContext instance does not have a cached instance
131      * of {@link JSONCodecFactory}, it will be completely precomputed before this method will return.
132      *
133      * <p>
134      * Choosing this implementation is appropriate when the memory overhead of keeping a full codec tree is not as
135      * great a concern as predictable performance. When compared to the implementation returned by
136      * {@link #getShared(SchemaContext)}, this implementation is expected to offer higher performance and have lower
137      * peak memory footprint when most of the SchemaContext is actually in use.
138      *
139      * <p>
140      * For call sites which do not want to pay the CPU cost of pre-computing this implementation, but still would like
141      * to use it if is available (by being populated by some other caller), you can use
142      * {@link #getPrecomputedIfAvailable(SchemaContext)}.
143      *
144      * @param context SchemaContext instance
145      * @return A sharable {@link JSONCodecFactory}
146      * @throws NullPointerException if context is null
147      */
148     public static JSONCodecFactory getPrecomputed(final SchemaContext context) {
149         return PRECOMPUTED.getUnchecked(context);
150     }
151
152     /**
153      * Get a thread-safe, eagerly-caching {@link JSONCodecFactory} for a SchemaContext, if it is available. This
154      * method is a non-blocking equivalent of {@link #getPrecomputed(SchemaContext)} for use in code paths where
155      * the potential of having to pre-compute the implementation is not acceptable. One such scenario is when the
156      * code base wants to opportunistically take advantage of pre-computed version, but is okay with a fallback to
157      * a different implementation.
158      *
159      * @param context SchemaContext instance
160      * @return A sharable {@link JSONCodecFactory}, or absent if such an implementation is not available.
161      * @throws NullPointerException if context is null
162      */
163     public static Optional<JSONCodecFactory> getPrecomputedIfAvailable(final SchemaContext context) {
164         return Optional.ofNullable(PRECOMPUTED.getIfPresent(context));
165     }
166
167     /**
168      * Get a thread-safe, lazily-caching {@link JSONCodecFactory} for a SchemaContext. This method can, and will,
169      * return the same instance as long as the associated SchemaContext is present or the factory is not invalidated
170      * by memory pressure. Returned object can be safely used by multiple threads concurrently.
171      *
172      * <p>
173      * Choosing this implementation is a safe default, as it will not incur prohibitive blocking, nor will it tie up
174      * memory in face of pressure.
175      *
176      * @param context SchemaContext instance
177      * @return A sharable {@link JSONCodecFactory}
178      * @throws NullPointerException if context is null
179      */
180     public static JSONCodecFactory getShared(final SchemaContext context) {
181         return SHARED.getUnchecked(context);
182     }
183
184     /**
185      * Create a new thread-unsafe, lazily-caching {@link JSONCodecFactory} for a SchemaContext. This method will
186      * return distinct objects every time it is invoked. Returned object may not be used from multiple threads
187      * concurrently.
188      *
189      * <p>
190      * This implementation is appropriate for one-off serialization from a single thread. It will aggressively cache
191      * codecs for reuse and will tie them up in memory until the factory is freed.
192      *
193      * @param context SchemaContext instance
194      * @return A non-sharable {@link JSONCodecFactory}
195      * @throws NullPointerException if context is null
196      */
197     public static JSONCodecFactory createLazy(final SchemaContext context) {
198         return new JSONCodecFactory(context, new LazyCodecCache<>());
199     }
200
201     /**
202      * Create a simplistic, thread-safe {@link JSONCodecFactory} for a {@link SchemaContext}. This method will return
203      * distinct objects every time it is invoked. Returned object may be use from multiple threads concurrently.
204      *
205      * <p>
206      * This implementation exists mostly for completeness only, as it does not perform any caching at all and each codec
207      * is computed every time it is requested. This may be useful in extremely constrained environments, where memory
208      * footprint is more critical than performance.
209      *
210      * @param context SchemaContext instance
211      * @return A non-sharable {@link JSONCodecFactory}
212      * @throws NullPointerException if context is null.
213      */
214     public static JSONCodecFactory createSimple(final SchemaContext context) {
215         return new JSONCodecFactory(context, NoopCodecCache.getInstance());
216     }
217
218     @Override
219     protected JSONCodec<?> binaryCodec(final BinaryTypeDefinition type) {
220         return new QuotedJSONCodec<>(BinaryStringCodec.from(type));
221     }
222
223     @Override
224     protected JSONCodec<?> booleanCodec(final BooleanTypeDefinition type) {
225         return new BooleanJSONCodec(BooleanStringCodec.from(type));
226     }
227
228     @Override
229     protected JSONCodec<?> bitsCodec(final BitsTypeDefinition type) {
230         return new QuotedJSONCodec<>(BitsStringCodec.from(type));
231     }
232
233     @Override
234     protected JSONCodec<?> decimalCodec(final DecimalTypeDefinition type) {
235         return new NumberJSONCodec<>(DecimalStringCodec.from(type));
236     }
237
238     @Override
239     protected JSONCodec<?> emptyCodec(final EmptyTypeDefinition type) {
240         return EmptyJSONCodec.INSTANCE;
241     }
242
243     @Override
244     protected JSONCodec<?> enumCodec(final EnumTypeDefinition type) {
245         return new QuotedJSONCodec<>(EnumStringCodec.from(type));
246     }
247
248     @Override
249     protected JSONCodec<?> identityRefCodec(final IdentityrefTypeDefinition type, final QNameModule module) {
250         return new IdentityrefJSONCodec(getSchemaContext(), module);
251     }
252
253     @Override
254     protected JSONCodec<?> instanceIdentifierCodec(final InstanceIdentifierTypeDefinition type) {
255         // FIXME: there really are two favors, as 'require-instance true' needs to be validated. In order to deal
256         //        with that, though, we need access to the current data store.
257         return iidCodec;
258     }
259
260     @Override
261     protected JSONCodec<?> intCodec(final IntegerTypeDefinition type) {
262         return new NumberJSONCodec<>(AbstractIntegerStringCodec.from(type));
263     }
264
265     @Override
266     protected JSONCodec<?> stringCodec(final StringTypeDefinition type) {
267         return new QuotedJSONCodec<>(StringStringCodec.from(type));
268     }
269
270     @Override
271     protected JSONCodec<?> uintCodec(final UnsignedIntegerTypeDefinition type) {
272         return new NumberJSONCodec<>(AbstractIntegerStringCodec.from(type));
273     }
274
275     @Override
276     protected JSONCodec<?> unionCodec(final UnionTypeDefinition type, final List<JSONCodec<?>> codecs) {
277         return UnionJSONCodec.create(type, codecs);
278     }
279
280     @Override
281     protected JSONCodec<?> unknownCodec(final UnknownTypeDefinition type) {
282         return NullJSONCodec.INSTANCE;
283     }
284 }