2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.data.codec.gson;
10 import com.google.common.annotations.Beta;
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Stopwatch;
14 import com.google.common.base.Verify;
15 import com.google.common.cache.CacheBuilder;
16 import com.google.common.cache.CacheLoader;
17 import com.google.common.cache.LoadingCache;
18 import java.util.ArrayList;
19 import java.util.List;
20 import org.opendaylight.yangtools.yang.data.impl.codec.AbstractIntegerStringCodec;
21 import org.opendaylight.yangtools.yang.data.impl.codec.BinaryStringCodec;
22 import org.opendaylight.yangtools.yang.data.impl.codec.BitsStringCodec;
23 import org.opendaylight.yangtools.yang.data.impl.codec.BooleanStringCodec;
24 import org.opendaylight.yangtools.yang.data.impl.codec.DecimalStringCodec;
25 import org.opendaylight.yangtools.yang.data.impl.codec.EnumStringCodec;
26 import org.opendaylight.yangtools.yang.data.impl.codec.StringStringCodec;
27 import org.opendaylight.yangtools.yang.data.util.codec.CodecCache;
28 import org.opendaylight.yangtools.yang.data.util.codec.LazyCodecCache;
29 import org.opendaylight.yangtools.yang.data.util.codec.NoopCodecCache;
30 import org.opendaylight.yangtools.yang.data.util.codec.PrecomputedCodecCache;
31 import org.opendaylight.yangtools.yang.data.util.codec.SharedCodecCache;
32 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
33 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
35 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
36 import org.opendaylight.yangtools.yang.model.api.TypedSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
38 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
39 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
40 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
41 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
42 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
43 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
44 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
45 import org.opendaylight.yangtools.yang.model.api.type.IntegerTypeDefinition;
46 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
47 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
48 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
49 import org.opendaylight.yangtools.yang.model.api.type.UnknownTypeDefinition;
50 import org.opendaylight.yangtools.yang.model.api.type.UnsignedIntegerTypeDefinition;
51 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
56 * Factory for creating JSON equivalents of codecs. Each instance of this object is bound to
57 * a particular {@link SchemaContext}, but can be reused by multiple {@link JSONNormalizedNodeStreamWriter}s.
59 * There are multiple implementations available, each with distinct thread-safety, CPU/memory trade-offs and reuse
60 * characteristics. See {@link #getShared(SchemaContext)}, {@link #getPrecomputed(SchemaContext)},
61 * {@link #createLazy(SchemaContext)} and {@link #createSimple(SchemaContext)} for details.
64 public final class JSONCodecFactory {
65 private static final class EagerCacheLoader extends CacheLoader<SchemaContext, JSONCodecFactory> {
67 public JSONCodecFactory load(final SchemaContext key) {
68 final Stopwatch sw = Stopwatch.createStarted();
69 final LazyCodecCache<JSONCodec<?>> lazyCache = new LazyCodecCache<>();
70 final JSONCodecFactory lazy = new JSONCodecFactory(key, lazyCache);
71 final int visitedLeaves = requestCodecsForChildren(lazy, key);
74 final PrecomputedCodecCache<JSONCodec<?>> cache = lazyCache.toPrecomputed();
75 LOG.debug("{} leaf nodes resulted in {} simple and {} complex codecs in {}", visitedLeaves,
76 cache.simpleSize(), cache.complexSize(), sw);
77 return new JSONCodecFactory(key, cache);
80 private static int requestCodecsForChildren(final JSONCodecFactory lazy, final DataNodeContainer parent) {
82 for (DataSchemaNode child : parent.getChildNodes()) {
83 if (child instanceof TypedSchemaNode) {
84 lazy.codecFor((TypedSchemaNode) child);
86 } else if (child instanceof DataNodeContainer) {
87 ret += requestCodecsForChildren(lazy, (DataNodeContainer) child);
95 private static final Logger LOG = LoggerFactory.getLogger(JSONCodecFactory.class);
97 // Weak keys to retire the entry when SchemaContext goes away
98 private static final LoadingCache<SchemaContext, JSONCodecFactory> PRECOMPUTED = CacheBuilder.newBuilder()
99 .weakKeys().build(new EagerCacheLoader());
101 // Weak keys to retire the entry when SchemaContext goes away and to force identity-based lookup
102 private static final LoadingCache<SchemaContext, JSONCodecFactory> SHARED = CacheBuilder.newBuilder()
103 .weakKeys().build(new CacheLoader<SchemaContext, JSONCodecFactory>() {
105 public JSONCodecFactory load(final SchemaContext key) {
106 return new JSONCodecFactory(key, new SharedCodecCache<>());
111 private final CodecCache<JSONCodec<?>> cache;
112 private final SchemaContext schemaContext;
113 private final JSONCodec<?> iidCodec;
115 JSONCodecFactory(final SchemaContext context, final CodecCache<JSONCodec<?>> cache) {
116 this.schemaContext = Preconditions.checkNotNull(context);
117 this.cache = Preconditions.checkNotNull(cache);
118 iidCodec = new JSONStringInstanceIdentifierCodec(context, this);
122 * Instantiate a new codec factory attached to a particular context.
124 * @param context SchemaContext to which the factory should be bound
125 * @return A codec factory instance.
127 * @deprecated Use {@link #getShared(SchemaContext)} instead.
130 public static JSONCodecFactory create(final SchemaContext context) {
131 return getShared(context);
135 * Get a thread-safe, eagerly-caching {@link JSONCodecFactory} for a SchemaContext. This method can, and will,
136 * return the same instance as long as the associated SchemaContext is present. Returned object can be safely
137 * used by multiple threads concurrently. If the SchemaContext instance does not have a cached instance
138 * of {@link JSONCodecFactory}, it will be completely precomputed before this method will return.
140 * Choosing this implementation is appropriate when the memory overhead of keeping a full codec tree is not as
141 * great a concern as predictable performance. When compared to the implementation returned by
142 * {@link #getShared(SchemaContext)}, this implementation is expected to offer higher performance and have lower
143 * peak memory footprint when most of the SchemaContext is actually in use.
145 * For call sites which do not want to pay the CPU cost of pre-computing this implementation, but still would like
146 * to use it if is available (by being populated by some other caller), you can use
147 * {@link #getPrecomputedIfAvailable(SchemaContext)}.
149 * @param context SchemaContext instance
150 * @return A sharable {@link JSONCodecFactory}
151 * @throws NullPointerException if context is null
153 public static JSONCodecFactory getPrecomputed(final SchemaContext context) {
154 return PRECOMPUTED.getUnchecked(context);
158 * Get a thread-safe, eagerly-caching {@link JSONCodecFactory} for a SchemaContext, if it is available. This
159 * method is a non-blocking equivalent of {@link #getPrecomputed(SchemaContext)} for use in code paths where
160 * the potential of having to pre-compute the implementation is not acceptable. One such scenario is when the
161 * code base wants to opportunistically take advantage of pre-computed version, but is okay with a fallback to
162 * a different implementation.
164 * @param context SchemaContext instance
165 * @return A sharable {@link JSONCodecFactory}, or absent if such an implementation is not available.
166 * @throws NullPointerException if context is null
168 public static Optional<JSONCodecFactory> getPrecomputedIfAvailable(final SchemaContext context) {
169 return Optional.fromNullable(PRECOMPUTED.getIfPresent(context));
173 * Get a thread-safe, lazily-caching {@link JSONCodecFactory} for a SchemaContext. This method can, and will,
174 * return the same instance as long as the associated SchemaContext is present or the factory is not invalidated
175 * by memory pressure. Returned object can be safely used by multiple threads concurrently.
177 * Choosing this implementation is a safe default, as it will not incur prohibitive blocking, nor will it tie up
178 * memory in face of pressure.
180 * @param context SchemaContext instance
181 * @return A sharable {@link JSONCodecFactory}
182 * @throws NullPointerException if context is null
184 public static JSONCodecFactory getShared(final SchemaContext context) {
185 return SHARED.getUnchecked(context);
189 * Create a new thread-unsafe, lazily-caching {@link JSONCodecFactory} for a SchemaContext. This method will
190 * return distinct objects every time it is invoked. Returned object may not be used from multiple threads
193 * This implementation is appropriate for one-off serialization from a single thread. It will aggressively cache
194 * codecs for reuse and will tie them up in memory until the factory is freed.
196 * @param context SchemaContext instance
197 * @return A non-sharable {@link JSONCodecFactory}
198 * @throws NullPointerException if context is null
200 public static JSONCodecFactory createLazy(final SchemaContext context) {
201 return new JSONCodecFactory(context, new LazyCodecCache<>());
205 * Create a simplistic, thread-safe {@link JSONCodecFactory} for a {@link SchemaContext}. This method will return
206 * distinct objects every time it is invoked. Returned object may be use from multiple threads concurrently.
208 * This implementation exists mostly for completeness only, as it does not perform any caching at all and each codec
209 * is computed every time it is requested. This may be useful in extremely constrained environments, where memory
210 * footprint is more critical than performance.
212 * @param context SchemaContext instance
213 * @return A non-sharable {@link JSONCodecFactory}
214 * @throws NullPointerException if context is null.
216 public static JSONCodecFactory createSimple(final SchemaContext context) {
217 return new JSONCodecFactory(context, NoopCodecCache.getInstance());
220 final JSONCodec<?> codecFor(final TypedSchemaNode schema) {
222 * There are many trade-offs to be made here. We need the common case being as fast as possible while reusing
223 * codecs as much as possible.
225 * This gives us essentially four classes of codecs:
226 * - simple codecs, which are based on the type definition only
227 * - complex codecs, which depend on both type definition and the leaf
228 * - null codec, which does not depend on anything
229 * - instance identifier codec, which is based on namespace mapping
231 * We assume prevalence is in above order and that caching is effective. We therefore
233 final TypeDefinition<?> type = schema.getType();
234 JSONCodec<?> ret = cache.lookupSimple(type);
236 LOG.trace("Type {} hit simple {}", type, ret);
239 ret = cache.lookupComplex(schema);
241 LOG.trace("Type {} hit complex {}", type, ret);
245 // Dealing with simple types first...
246 ret = getSimpleCodecFor(type);
248 LOG.trace("Type {} miss simple {}", type, ret);
252 // ... and complex types afterwards
253 ret = createComplexCodecFor(schema, type);
254 LOG.trace("Type {} miss complex {}", type, ret);
255 return cache.getComplex(schema, ret);
258 final SchemaContext getSchemaContext() {
259 return schemaContext;
262 private JSONCodec<?> getSimpleCodecFor(final TypeDefinition<?> type) {
263 if (type instanceof InstanceIdentifierTypeDefinition) {
264 // FIXME: there really are two favors, as 'require-instance true' needs to be validated. In order to deal
265 // with that, though, we need access to the current data store.
267 } else if (type instanceof EmptyTypeDefinition) {
268 return EmptyJSONCodec.INSTANCE;
269 } else if (type instanceof UnknownTypeDefinition) {
270 return NullJSONCodec.INSTANCE;
273 // Now deal with simple types. Note we consider union composed of purely simple types a simple type itself.
274 // The checks here are optimized for common types.
275 final JSONCodec<?> ret;
276 if (type instanceof StringTypeDefinition) {
277 ret = new QuotedJSONCodec<>(StringStringCodec.from((StringTypeDefinition) type));
278 } else if (type instanceof IntegerTypeDefinition) {
279 ret = new NumberJSONCodec<>(AbstractIntegerStringCodec.from((IntegerTypeDefinition) type));
280 } else if (type instanceof UnsignedIntegerTypeDefinition) {
281 ret = new NumberJSONCodec<>(AbstractIntegerStringCodec.from((UnsignedIntegerTypeDefinition) type));
282 } else if (type instanceof BooleanTypeDefinition) {
283 ret = new BooleanJSONCodec(BooleanStringCodec.from((BooleanTypeDefinition) type));
284 } else if (type instanceof DecimalTypeDefinition) {
285 ret = new NumberJSONCodec<>(DecimalStringCodec.from((DecimalTypeDefinition) type));
286 } else if (type instanceof EnumTypeDefinition) {
287 ret = new QuotedJSONCodec<>(EnumStringCodec.from((EnumTypeDefinition) type));
288 } else if (type instanceof BitsTypeDefinition) {
289 ret = new QuotedJSONCodec<>(BitsStringCodec.from((BitsTypeDefinition) type));
290 } else if (type instanceof UnionTypeDefinition) {
291 final UnionTypeDefinition union = (UnionTypeDefinition) type;
292 if (!isSimpleUnion(union)) {
295 ret = createSimpleUnion(union);
296 } else if (type instanceof BinaryTypeDefinition) {
297 ret = new QuotedJSONCodec<>(BinaryStringCodec.from((BinaryTypeDefinition) type));
302 return cache.getSimple(type, Verify.verifyNotNull(ret));
305 private JSONCodec<?> createComplexCodecFor(final TypedSchemaNode schema, final TypeDefinition<?> type) {
306 if (type instanceof UnionTypeDefinition) {
307 return createComplexUnion(schema, (UnionTypeDefinition) type);
308 } else if (type instanceof LeafrefTypeDefinition) {
309 final TypeDefinition<?> target = SchemaContextUtil.getBaseTypeForLeafRef((LeafrefTypeDefinition) type,
310 schemaContext, schema);
311 Verify.verifyNotNull(target, "Unable to find base type for leafref node %s type %s.", schema.getPath(),
314 final JSONCodec<?> ret = getSimpleCodecFor(target);
315 return ret != null ? ret : createComplexCodecFor(schema, target);
316 } else if (type instanceof IdentityrefTypeDefinition) {
317 return new JSONStringIdentityrefCodec(schemaContext, schema.getQName().getModule());
319 throw new IllegalArgumentException("Unsupported type " + type);
323 private static boolean isSimpleUnion(final UnionTypeDefinition union) {
324 for (TypeDefinition<?> t : union.getTypes()) {
325 if (t instanceof IdentityrefTypeDefinition || t instanceof LeafrefTypeDefinition
326 || (t instanceof UnionTypeDefinition && !isSimpleUnion((UnionTypeDefinition) t))) {
327 LOG.debug("Type {} has non-simple subtype", t);
332 LOG.debug("Type {} is simple", union);
336 private JSONCodec<?> createSimpleUnion(final UnionTypeDefinition union) {
337 final List<TypeDefinition<?>> types = union.getTypes();
338 final List<JSONCodec<?>> codecs = new ArrayList<>(types.size());
340 for (TypeDefinition<?> type : types) {
341 JSONCodec<?> codec = cache.lookupSimple(type);
343 codec = Verify.verifyNotNull(getSimpleCodecFor(type), "Type %s did not resolve to a simple codec",
350 return UnionJSONCodec.create(union, codecs);
353 private UnionJSONCodec<?> createComplexUnion(final TypedSchemaNode schema, final UnionTypeDefinition union) {
354 final List<TypeDefinition<?>> types = union.getTypes();
355 final List<JSONCodec<?>> codecs = new ArrayList<>(types.size());
357 for (TypeDefinition<?> type : types) {
358 JSONCodec<?> codec = cache.lookupSimple(type);
360 codec = getSimpleCodecFor(type);
362 codec = createComplexCodecFor(schema, type);
366 codecs.add(Verify.verifyNotNull(codec, "Schema %s subtype %s has no codec", schema, type));
369 return UnionJSONCodec.create(union, codecs);