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.Verify;
14 import java.util.ArrayList;
15 import java.util.List;
16 import javax.annotation.Nonnull;
17 import javax.annotation.Nullable;
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.model.api.SchemaContext;
26 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
27 import org.opendaylight.yangtools.yang.model.api.TypedSchemaNode;
28 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
29 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
30 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
31 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
32 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
33 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
34 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
35 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
36 import org.opendaylight.yangtools.yang.model.api.type.IntegerTypeDefinition;
37 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
38 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
39 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
40 import org.opendaylight.yangtools.yang.model.api.type.UnknownTypeDefinition;
41 import org.opendaylight.yangtools.yang.model.api.type.UnsignedIntegerTypeDefinition;
42 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
47 * Factory for creating JSON equivalents of codecs. Each instance of this object is bound to
48 * a particular {@link SchemaContext}, but can be reused by multiple {@link JSONNormalizedNodeStreamWriter}s.
50 * There are multiple implementations available, each with distinct thread-safety, CPU/memory trade-offs and reuse
51 * characteristics. See {@link #getShared(SchemaContext)}, {@link #getPrecomputed(SchemaContext)},
52 * {@link #createLazy(SchemaContext)} and {@link #createSimple(SchemaContext)} for details.
55 public abstract class JSONCodecFactory {
56 private static final Logger LOG = LoggerFactory.getLogger(JSONCodecFactory.class);
58 private final SchemaContext schemaContext;
59 private final JSONCodec<?> iidCodec;
61 JSONCodecFactory(final SchemaContext context) {
62 this.schemaContext = Preconditions.checkNotNull(context);
63 iidCodec = new JSONStringInstanceIdentifierCodec(context, this);
67 * Instantiate a new codec factory attached to a particular context.
69 * @param context SchemaContext to which the factory should be bound
70 * @return A codec factory instance.
72 * @deprecated Use {@link #getShared(SchemaContext)} instead.
75 public static JSONCodecFactory create(final SchemaContext context) {
76 return getShared(context);
80 * Get a thread-safe, eagerly-caching {@link JSONCodecFactory} for a SchemaContext. This method can, and will,
81 * return the same instance as long as the associated SchemaContext is present. Returned object can be safely
82 * used by multiple threads concurrently. If the SchemaContext instance does not have a cached instance
83 * of {@link JSONCodecFactory}, it will be completely precomputed before this method will return.
85 * Choosing this implementation is appropriate when the memory overhead of keeping a full codec tree is not as
86 * great a concern as predictable performance. When compared to the implementation returned by
87 * {@link #getShared(SchemaContext)}, this implementation is expected to offer higher performance and have lower
88 * peak memory footprint when most of the SchemaContext is actually in use.
90 * For call sites which do not want to pay the CPU cost of pre-computing this implementation, but still would like
91 * to use it if is available (by being populated by some other caller), you can use
92 * {@link #getPrecomputedIfAvailable(SchemaContext)}.
94 * @param context SchemaContext instance
95 * @return A sharable {@link JSONCodecFactory}
96 * @throws NullPointerException if context is null
98 public static JSONCodecFactory getPrecomputed(final SchemaContext context) {
99 return EagerJSONCodecFactory.get(context);
103 * Get a thread-safe, eagerly-caching {@link JSONCodecFactory} for a SchemaContext, if it is available. This
104 * method is a non-blocking equivalent of {@link #getPrecomputed(SchemaContext)} for use in code paths where
105 * the potential of having to pre-compute the implementation is not acceptable. One such scenario is when the
106 * code base wants to opportunistically take advantage of pre-computed version, but is okay with a fallback to
107 * a different implementation.
109 * @param context SchemaContext instance
110 * @return A sharable {@link JSONCodecFactory}, or absent if such an implementation is not available.
111 * @throws NullPointerException if context is null
113 public static Optional<JSONCodecFactory> getPrecomputedIfAvailable(final SchemaContext context) {
114 return Optional.fromNullable(EagerJSONCodecFactory.getIfPresent(context));
118 * Get a thread-safe, lazily-caching {@link JSONCodecFactory} for a SchemaContext. This method can, and will,
119 * return the same instance as long as the associated SchemaContext is present or the factory is not invalidated
120 * by memory pressure. Returned object can be safely used by multiple threads concurrently.
122 * Choosing this implementation is a safe default, as it will not incur prohibitive blocking, nor will it tie up
123 * memory in face of pressure.
125 * @param context SchemaContext instance
126 * @return A sharable {@link JSONCodecFactory}
127 * @throws NullPointerException if context is null
129 public static JSONCodecFactory getShared(final SchemaContext context) {
130 return SharedJSONCodecFactory.get(context);
134 * Create a new thread-unsafe, lazily-caching {@link JSONCodecFactory} for a SchemaContext. This method will
135 * return distinct objects every time it is invoked. Returned object may not be used from multiple threads
138 * This implementation is appropriate for one-off serialization from a single thread. It will aggressively cache
139 * codecs for reuse and will tie them up in memory until the factory is freed.
141 * @param context SchemaContext instance
142 * @return A non-sharable {@link JSONCodecFactory}
143 * @throws NullPointerException if context is null
145 public static JSONCodecFactory createLazy(final SchemaContext context) {
146 return new LazyJSONCodecFactory(context);
150 * Create a simplistic, thread-safe {@link JSONCodecFactory} for a {@link SchemaContext}. This method will return
151 * distinct objects every time it is invoked. Returned object may be use from multiple threads concurrently.
153 * This implementation exists mostly for completeness only, as it does not perform any caching at all and each codec
154 * is computed every time it is requested. This may be useful in extremely constrained environments, where memory
155 * footprint is more critical than performance.
157 * @param context SchemaContext instance
158 * @return A non-sharable {@link JSONCodecFactory}
159 * @throws NullPointerException if context is null.
161 public static JSONCodecFactory createSimple(final SchemaContext context) {
162 return new SimpleJSONCodecFactory(context);
165 final JSONCodec<?> codecFor(final TypedSchemaNode schema) {
167 * There are many trade-offs to be made here. We need the common case being as fast as possible while reusing
168 * codecs as much as possible.
170 * This gives us essentially four classes of codecs:
171 * - simple codecs, which are based on the type definition only
172 * - complex codecs, which depend on both type definition and the leaf
173 * - null codec, which does not depend on anything
174 * - instance identifier codec, which is based on namespace mapping
176 * We assume prevalence is in above order and that caching is effective. We therefore
178 final TypeDefinition<?> type = schema.getType();
179 JSONCodec<?> ret = lookupSimple(type);
181 LOG.trace("Type {} hit simple {}", type, ret);
184 ret = lookupComplex(schema);
186 LOG.trace("Type {} hit complex {}", type, ret);
190 // Dealing with simple types first...
191 ret = getSimpleCodecFor(type);
193 LOG.trace("Type {} miss simple {}", type, ret);
197 // ... and complex types afterwards
198 ret = createComplexCodecFor(schema, type);
199 LOG.trace("Type {} miss complex {}", type, ret);
200 return getComplex(schema, ret);
203 final SchemaContext getSchemaContext() {
204 return schemaContext;
208 * Lookup a complex codec for schema node.
210 * @param schema Schema node
211 * @return Cached codec, or null if no codec is cached.
213 @Nullable abstract JSONCodec<?> lookupComplex(TypedSchemaNode schema);
216 * Lookup a simple codec for a type definition.
218 * @param type Type definitions
219 * @return Cached codec, or null if no codec is cached.
221 @Nullable abstract JSONCodec<?> lookupSimple(TypeDefinition<?> type);
224 * Lookup-or-store a complex codec for a particular schema node.
226 * @param schema Schema node
227 * @param codec Codec to cache
228 * @return Codec instance, either already-cached, or the codec presented as argument.
230 @Nonnull abstract JSONCodec<?> getComplex(TypedSchemaNode schema, JSONCodec<?> codec);
233 * Lookup-or-store a simple codec for a particular schema node.
235 * @param schema Schema node
236 * @param codec Codec to cache
237 * @return Codec instance, either already-cached, or the codec presented as argument.
239 @Nonnull abstract JSONCodec<?> getSimple(TypeDefinition<?> type, JSONCodec<?> codec);
241 private JSONCodec<?> getSimpleCodecFor(final TypeDefinition<?> type) {
242 if (type instanceof InstanceIdentifierTypeDefinition) {
243 // FIXME: there really are two favors, as 'require-instance true' needs to be validated. In order to deal
244 // with that, though, we need access to the current data store.
246 } else if (type instanceof EmptyTypeDefinition) {
247 return EmptyJSONCodec.INSTANCE;
248 } else if (type instanceof UnknownTypeDefinition) {
249 return NullJSONCodec.INSTANCE;
252 // Now deal with simple types. Note we consider union composed of purely simple types a simple type itself.
253 // The checks here are optimized for common types.
254 final JSONCodec<?> ret;
255 if (type instanceof StringTypeDefinition) {
256 ret = new QuotedJSONCodec<>(StringStringCodec.from((StringTypeDefinition) type));
257 } else if (type instanceof IntegerTypeDefinition) {
258 ret = new NumberJSONCodec<>(AbstractIntegerStringCodec.from((IntegerTypeDefinition) type));
259 } else if (type instanceof UnsignedIntegerTypeDefinition) {
260 ret = new NumberJSONCodec<>(AbstractIntegerStringCodec.from((UnsignedIntegerTypeDefinition) type));
261 } else if (type instanceof BooleanTypeDefinition) {
262 ret = new BooleanJSONCodec(BooleanStringCodec.from((BooleanTypeDefinition) type));
263 } else if (type instanceof DecimalTypeDefinition) {
264 ret = new NumberJSONCodec<>(DecimalStringCodec.from((DecimalTypeDefinition) type));
265 } else if (type instanceof EnumTypeDefinition) {
266 ret = new QuotedJSONCodec<>(EnumStringCodec.from((EnumTypeDefinition) type));
267 } else if (type instanceof BitsTypeDefinition) {
268 ret = new QuotedJSONCodec<>(BitsStringCodec.from((BitsTypeDefinition) type));
269 } else if (type instanceof UnionTypeDefinition) {
270 final UnionTypeDefinition union = (UnionTypeDefinition) type;
271 if (!isSimpleUnion(union)) {
274 ret = createSimpleUnion(union);
275 } else if (type instanceof BinaryTypeDefinition) {
276 ret = new QuotedJSONCodec<>(BinaryStringCodec.from((BinaryTypeDefinition) type));
281 return getSimple(type, Verify.verifyNotNull(ret));
284 private JSONCodec<?> createComplexCodecFor(final TypedSchemaNode schema, final TypeDefinition<?> type) {
285 if (type instanceof UnionTypeDefinition) {
286 return createComplexUnion(schema, (UnionTypeDefinition) type);
287 } else if (type instanceof LeafrefTypeDefinition) {
288 final TypeDefinition<?> target = SchemaContextUtil.getBaseTypeForLeafRef((LeafrefTypeDefinition) type,
289 schemaContext, schema);
290 Verify.verifyNotNull(target, "Unable to find base type for leafref node %s type %s.", schema.getPath(),
293 final JSONCodec<?> ret = getSimpleCodecFor(target);
294 return ret != null ? ret : createComplexCodecFor(schema, target);
295 } else if (type instanceof IdentityrefTypeDefinition) {
296 return new JSONStringIdentityrefCodec(schemaContext, schema.getQName().getModule());
298 throw new IllegalArgumentException("Unsupported type " + type);
302 private static boolean isSimpleUnion(final UnionTypeDefinition union) {
303 for (TypeDefinition<?> t : union.getTypes()) {
304 if (t instanceof IdentityrefTypeDefinition || t instanceof LeafrefTypeDefinition
305 || (t instanceof UnionTypeDefinition && !isSimpleUnion((UnionTypeDefinition) t))) {
306 LOG.debug("Type {} has non-simple subtype", t);
311 LOG.debug("Type {} is simple", union);
315 private JSONCodec<?> createSimpleUnion(final UnionTypeDefinition union) {
316 final List<TypeDefinition<?>> types = union.getTypes();
317 final List<JSONCodec<?>> codecs = new ArrayList<>(types.size());
319 for (TypeDefinition<?> type : types) {
320 JSONCodec<?> codec = lookupSimple(type);
322 codec = Verify.verifyNotNull(getSimpleCodecFor(type), "Type %s did not resolve to a simple codec",
329 return UnionJSONCodec.create(union, codecs);
332 private UnionJSONCodec<?> createComplexUnion(final TypedSchemaNode schema, final UnionTypeDefinition union) {
333 final List<TypeDefinition<?>> types = union.getTypes();
334 final List<JSONCodec<?>> codecs = new ArrayList<>(types.size());
336 for (TypeDefinition<?> type : types) {
337 JSONCodec<?> codec = lookupSimple(type);
339 codec = getSimpleCodecFor(type);
341 codec = createComplexCodecFor(schema, type);
345 codecs.add(Verify.verifyNotNull(codec, "Schema %s subtype %s has no codec", schema, type));
348 return UnionJSONCodec.create(union, codecs);