2 * Copyright (c) 2017 Pantheon Technologies, s.r.o. 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 static com.google.common.base.Verify.verifyNotNull;
11 import static java.util.Objects.requireNonNull;
13 import com.google.common.annotations.Beta;
14 import com.google.common.base.Stopwatch;
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.Optional;
19 import java.util.function.BiFunction;
20 import org.eclipse.jdt.annotation.NonNull;
21 import org.opendaylight.yangtools.yang.data.util.codec.CodecCache;
22 import org.opendaylight.yangtools.yang.data.util.codec.LazyCodecCache;
23 import org.opendaylight.yangtools.yang.data.util.codec.NoopCodecCache;
24 import org.opendaylight.yangtools.yang.data.util.codec.PrecomputedCodecCache;
25 import org.opendaylight.yangtools.yang.data.util.codec.SharedCodecCache;
26 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
27 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
28 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
29 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
34 * API entry point for acquiring {@link JSONCodecFactory} instances.
36 * @author Robert Varga
39 public enum JSONCodecFactorySupplier {
41 * Source of {@link JSONCodecFactory} instances compliant with RFC7951.
45 JSONCodecFactory createFactory(final SchemaContext context, final CodecCache<JSONCodec<?>> cache) {
46 return new RFC7951JSONCodecFactory(context, cache);
50 * Source of {@link JSONCodecFactory} instances compliant with draft-lhotka-netmod-yang-json-02.
52 DRAFT_LHOTKA_NETMOD_YANG_JSON_02() {
54 JSONCodecFactory createFactory(final SchemaContext context, final CodecCache<JSONCodec<?>> cache) {
55 return new Lhotka02JSONCodecFactory(context, cache);
59 private static final Logger LOG = LoggerFactory.getLogger(JSONCodecFactorySupplier.class);
61 private static final class EagerCacheLoader extends CacheLoader<SchemaContext, JSONCodecFactory> {
62 private final BiFunction<SchemaContext, CodecCache<JSONCodec<?>>, JSONCodecFactory> factorySupplier;
64 EagerCacheLoader(final BiFunction<SchemaContext, CodecCache<JSONCodec<?>>, JSONCodecFactory> factorySupplier) {
65 this.factorySupplier = requireNonNull(factorySupplier);
69 public JSONCodecFactory load(final SchemaContext key) {
70 final Stopwatch sw = Stopwatch.createStarted();
71 final LazyCodecCache<JSONCodec<?>> lazyCache = new LazyCodecCache<>();
72 final JSONCodecFactory lazy = factorySupplier.apply(key, lazyCache);
73 final int visitedLeaves = requestCodecsForChildren(lazy, key);
76 final PrecomputedCodecCache<JSONCodec<?>> cache = lazyCache.toPrecomputed();
77 LOG.debug("{} leaf nodes resulted in {} simple and {} complex codecs in {}", visitedLeaves,
78 cache.simpleSize(), cache.complexSize(), sw);
79 return factorySupplier.apply(key, cache);
82 private static int requestCodecsForChildren(final JSONCodecFactory lazy, final DataNodeContainer parent) {
84 for (DataSchemaNode child : parent.getChildNodes()) {
85 if (child instanceof TypedDataSchemaNode) {
86 lazy.codecFor((TypedDataSchemaNode) child);
88 } else if (child instanceof DataNodeContainer) {
89 ret += requestCodecsForChildren(lazy, (DataNodeContainer) child);
97 // Weak keys to retire the entry when SchemaContext goes away
98 private final LoadingCache<SchemaContext, JSONCodecFactory> precomputed;
100 // Weak keys to retire the entry when SchemaContext goes away and to force identity-based lookup
101 private final LoadingCache<SchemaContext, JSONCodecFactory> shared;
103 JSONCodecFactorySupplier() {
104 precomputed = CacheBuilder.newBuilder().weakKeys().build(new EagerCacheLoader(this::createFactory));
105 shared = CacheBuilder.newBuilder().weakKeys().build(new CacheLoader<SchemaContext, JSONCodecFactory>() {
107 public JSONCodecFactory load(final SchemaContext key) {
108 return createFactory(key, new SharedCodecCache<>());
114 * Get a thread-safe, eagerly-caching {@link JSONCodecFactory} for a SchemaContext. This method can, and will,
115 * return the same instance as long as the associated SchemaContext is present. Returned object can be safely
116 * used by multiple threads concurrently. If the SchemaContext instance does not have a cached instance
117 * of {@link JSONCodecFactory}, it will be completely precomputed before this method will return.
120 * Choosing this implementation is appropriate when the memory overhead of keeping a full codec tree is not as
121 * great a concern as predictable performance. When compared to the implementation returned by
122 * {@link #getShared(SchemaContext)}, this implementation is expected to offer higher performance and have lower
123 * peak memory footprint when most of the SchemaContext is actually in use.
126 * For call sites which do not want to pay the CPU cost of pre-computing this implementation, but still would like
127 * to use it if is available (by being populated by some other caller), you can use
128 * {@link #getPrecomputedIfAvailable(SchemaContext)}.
130 * @param context SchemaContext instance
131 * @return A sharable {@link JSONCodecFactory}
132 * @throws NullPointerException if context is null
134 public @NonNull JSONCodecFactory getPrecomputed(final @NonNull SchemaContext context) {
135 return verifyNotNull(precomputed.getUnchecked(context));
139 * Get a thread-safe, eagerly-caching {@link JSONCodecFactory} for a SchemaContext, if it is available. This
140 * method is a non-blocking equivalent of {@link #getPrecomputed(SchemaContext)} for use in code paths where
141 * the potential of having to pre-compute the implementation is not acceptable. One such scenario is when the
142 * code base wants to opportunistically take advantage of pre-computed version, but is okay with a fallback to
143 * a different implementation.
145 * @param context SchemaContext instance
146 * @return A sharable {@link JSONCodecFactory}, or absent if such an implementation is not available.
147 * @throws NullPointerException if context is null
149 public @NonNull Optional<JSONCodecFactory> getPrecomputedIfAvailable(final @NonNull SchemaContext context) {
150 return Optional.ofNullable(precomputed.getIfPresent(context));
154 * Get a thread-safe, lazily-caching {@link JSONCodecFactory} for a SchemaContext. This method can, and will,
155 * return the same instance as long as the associated SchemaContext is present or the factory is not invalidated
156 * by memory pressure. Returned object can be safely used by multiple threads concurrently.
159 * Choosing this implementation is a safe default, as it will not incur prohibitive blocking, nor will it tie up
160 * memory in face of pressure.
162 * @param context SchemaContext instance
163 * @return A sharable {@link JSONCodecFactory}
164 * @throws NullPointerException if context is null
166 public @NonNull JSONCodecFactory getShared(final @NonNull SchemaContext context) {
167 return verifyNotNull(shared.getUnchecked(context));
171 * Create a new thread-unsafe, lazily-caching {@link JSONCodecFactory} for a SchemaContext. This method will
172 * return distinct objects every time it is invoked. Returned object may not be used from multiple threads
176 * This implementation is appropriate for one-off serialization from a single thread. It will aggressively cache
177 * codecs for reuse and will tie them up in memory until the factory is freed.
179 * @param context SchemaContext instance
180 * @return A non-sharable {@link JSONCodecFactory}
181 * @throws NullPointerException if context is null
183 public @NonNull JSONCodecFactory createLazy(final @NonNull SchemaContext context) {
184 return createFactory(context, new LazyCodecCache<>());
188 * Create a simplistic, thread-safe {@link JSONCodecFactory} for a {@link SchemaContext}. This method will return
189 * distinct objects every time it is invoked. Returned object may be use from multiple threads concurrently.
192 * This implementation exists mostly for completeness only, as it does not perform any caching at all and each codec
193 * is computed every time it is requested. This may be useful in extremely constrained environments, where memory
194 * footprint is more critical than performance.
196 * @param context SchemaContext instance
197 * @return A non-sharable {@link JSONCodecFactory}
198 * @throws NullPointerException if context is null.
200 public @NonNull JSONCodecFactory createSimple(final @NonNull SchemaContext context) {
201 return createFactory(context, NoopCodecCache.getInstance());
204 abstract @NonNull JSONCodecFactory createFactory(SchemaContext context, CodecCache<JSONCodec<?>> cache);