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.EffectiveModelContext;
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 EffectiveModelContext 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 EffectiveModelContext 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<EffectiveModelContext, JSONCodecFactory> {
62 private final BiFunction<EffectiveModelContext, CodecCache<JSONCodec<?>>, JSONCodecFactory> factorySupplier;
64 EagerCacheLoader(final BiFunction<EffectiveModelContext,
65 CodecCache<JSONCodec<?>>, JSONCodecFactory> factorySupplier) {
66 this.factorySupplier = requireNonNull(factorySupplier);
70 public JSONCodecFactory load(final EffectiveModelContext key) {
71 final Stopwatch sw = Stopwatch.createStarted();
72 final LazyCodecCache<JSONCodec<?>> lazyCache = new LazyCodecCache<>();
73 final JSONCodecFactory lazy = factorySupplier.apply(key, lazyCache);
74 final int visitedLeaves = requestCodecsForChildren(lazy, key);
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 factorySupplier.apply(key, cache);
83 private static int requestCodecsForChildren(final JSONCodecFactory lazy, final DataNodeContainer parent) {
85 for (DataSchemaNode child : parent.getChildNodes()) {
86 if (child instanceof TypedDataSchemaNode) {
87 lazy.codecFor((TypedDataSchemaNode) child);
89 } else if (child instanceof DataNodeContainer) {
90 ret += requestCodecsForChildren(lazy, (DataNodeContainer) child);
98 // Weak keys to retire the entry when SchemaContext goes away
99 private final LoadingCache<EffectiveModelContext, JSONCodecFactory> precomputed;
101 // Weak keys to retire the entry when SchemaContext goes away and to force identity-based lookup
102 private final LoadingCache<EffectiveModelContext, JSONCodecFactory> shared;
104 JSONCodecFactorySupplier() {
105 precomputed = CacheBuilder.newBuilder().weakKeys().build(new EagerCacheLoader(this::createFactory));
106 shared = CacheBuilder.newBuilder().weakKeys().build(new CacheLoader<EffectiveModelContext, JSONCodecFactory>() {
108 public JSONCodecFactory load(final EffectiveModelContext key) {
109 return createFactory(key, new SharedCodecCache<>());
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.
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(EffectiveModelContext)}, this implementation is expected to offer higher performance and have
124 * lower peak memory footprint when most of the SchemaContext is actually in use.
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(EffectiveModelContext)}.
131 * @param context SchemaContext instance
132 * @return A sharable {@link JSONCodecFactory}
133 * @throws NullPointerException if context is null
135 public @NonNull JSONCodecFactory getPrecomputed(final @NonNull EffectiveModelContext context) {
136 return verifyNotNull(precomputed.getUnchecked(context));
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(EffectiveModelContext)} 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.
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
150 public @NonNull Optional<JSONCodecFactory> getPrecomputedIfAvailable(final @NonNull EffectiveModelContext context) {
151 return Optional.ofNullable(precomputed.getIfPresent(context));
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 EffectiveModelContext is present or the factory is not
157 * invalidated by memory pressure. Returned object can be safely used by multiple threads concurrently.
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.
163 * @param context SchemaContext instance
164 * @return A sharable {@link JSONCodecFactory}
165 * @throws NullPointerException if context is null
167 public @NonNull JSONCodecFactory getShared(final @NonNull EffectiveModelContext context) {
168 return verifyNotNull(shared.getUnchecked(context));
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
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.
180 * @param context SchemaContext instance
181 * @return A non-sharable {@link JSONCodecFactory}
182 * @throws NullPointerException if context is null
184 public @NonNull JSONCodecFactory createLazy(final @NonNull EffectiveModelContext context) {
185 return createFactory(context, new LazyCodecCache<>());
189 * Create a simplistic, thread-safe {@link JSONCodecFactory} for a {@link EffectiveModelContext}. This method will
190 * return distinct objects every time it is invoked. Returned object may be use from multiple threads concurrently.
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.
197 * @param context SchemaContext instance
198 * @return A non-sharable {@link JSONCodecFactory}
199 * @throws NullPointerException if context is null.
201 public @NonNull JSONCodecFactory createSimple(final @NonNull EffectiveModelContext context) {
202 return createFactory(context, NoopCodecCache.getInstance());
205 abstract @NonNull JSONCodecFactory createFactory(EffectiveModelContext context, CodecCache<JSONCodec<?>> cache);