Reimplement SchemaContextUtil.getBaseTypeForLeafRef()
[yangtools.git] / yang / yang-data-codec-gson / src / main / java / org / opendaylight / yangtools / yang / data / codec / gson / JSONCodecFactory.java
index 9df9b347dc16c59a19931c650814420d59a8c221..aaa67301959ca07ec457108de875cd5a8f889889 100644 (file)
 package org.opendaylight.yangtools.yang.data.codec.gson;
 
 import com.google.common.annotations.Beta;
-import com.google.common.base.Preconditions;
-import com.google.common.cache.CacheBuilder;
-import com.google.common.cache.CacheLoader;
-import com.google.common.cache.LoadingCache;
-import com.google.gson.stream.JsonWriter;
-import java.io.IOException;
-import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+import java.util.List;
+import org.eclipse.jdt.annotation.NonNull;
+import org.opendaylight.yangtools.yang.common.QNameModule;
+import org.opendaylight.yangtools.yang.data.impl.codec.AbstractIntegerStringCodec;
+import org.opendaylight.yangtools.yang.data.impl.codec.BinaryStringCodec;
+import org.opendaylight.yangtools.yang.data.impl.codec.BitsStringCodec;
+import org.opendaylight.yangtools.yang.data.impl.codec.BooleanStringCodec;
+import org.opendaylight.yangtools.yang.data.impl.codec.DecimalStringCodec;
+import org.opendaylight.yangtools.yang.data.impl.codec.EnumStringCodec;
+import org.opendaylight.yangtools.yang.data.impl.codec.StringStringCodec;
+import org.opendaylight.yangtools.yang.data.util.codec.AbstractCodecFactory;
+import org.opendaylight.yangtools.yang.data.util.codec.CodecCache;
+import org.opendaylight.yangtools.yang.data.util.codec.LazyCodecCache;
+import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
+import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
-import org.opendaylight.yangtools.yang.model.util.DerivedType;
-import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import org.opendaylight.yangtools.yang.model.api.type.Int16TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.Int32TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.Int64TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.Int8TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.Uint16TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.Uint32TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.Uint64TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.Uint8TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.UnknownTypeDefinition;
 
 /**
  * Factory for creating JSON equivalents of codecs. Each instance of this object is bound to
- * a particular {@link SchemaContext}, but can be reused by multiple {@link JSONNormalizedNodeStreamWriter}s.
+ * a particular {@link EffectiveModelContext}, but can be reused by multiple {@link JSONNormalizedNodeStreamWriter}s.
  */
 @Beta
-public final class JSONCodecFactory {
-    private static final Logger LOG = LoggerFactory.getLogger(JSONCodecFactory.class);
-    private static final JSONCodec<Object> NULL_CODEC = new JSONCodec<Object>() {
-        @Override
-        public Object deserialize(final String input) {
-            return null;
-        }
-
-        @Override
-        public String serialize(final Object input) {
-            return null;
-        }
-
-        @Override
-        public boolean needQuotes() {
-            return false;
-        }
-
-        @Override
-        public void serializeToWriter(final JsonWriter writer, final Object value) throws IOException {
-            // NOOP since codec is unkwown.
-            LOG.warn("Call of the serializeToWriter method on JSONCodecFactory.NULL_CODEC object. No operation performed.");
-        }
-    };
-
-    private final LoadingCache<DataSchemaNode, JSONCodec<Object>> codecs =
-            CacheBuilder.newBuilder().softValues().build(new CacheLoader<DataSchemaNode, JSONCodec<Object>>() {
-        @Override
-        public JSONCodec<Object> load(final DataSchemaNode key) throws Exception {
-            final TypeDefinition<?> type;
-            if (key instanceof LeafSchemaNode) {
-                type = ((LeafSchemaNode) key).getType();
-            } else if (key instanceof LeafListSchemaNode) {
-                type = ((LeafListSchemaNode) key).getType();
-            } else {
-                throw new IllegalArgumentException("Not supported node type " + key.getClass().getName());
-            }
-            return createCodec(key,type);
-        }
-    });
-
-    private final SchemaContext schemaContext;
-    private final JSONCodec<?> iidCodec;
-
-    private JSONCodecFactory(final SchemaContext context) {
-        this.schemaContext = Preconditions.checkNotNull(context);
-        iidCodec = new JSONStringInstanceIdentifierCodec(context);
-    }
-
-    /**
-     * Instantiate a new codec factory attached to a particular context.
-     *
-     * @param context SchemaContext to which the factory should be bound
-     * @return A codec factory instance.
-     */
-    public static JSONCodecFactory create(final SchemaContext context) {
-        return new JSONCodecFactory(context);
-    }
-
-    @SuppressWarnings("unchecked")
-    private JSONCodec<Object> createCodec(final DataSchemaNode key, final TypeDefinition<?> type) {
-        final TypeDefinition<?> normalizedType = DerivedType.from(type);
-        if (normalizedType instanceof LeafrefTypeDefinition) {
-            return createReferencedTypeCodec(key, (LeafrefTypeDefinition) normalizedType);
-        } else if (normalizedType instanceof IdentityrefTypeDefinition) {
-            final JSONCodec<?> jsonStringIdentityrefCodec =
-                    new JSONStringIdentityrefCodec(schemaContext, key.getQName().getModule());
-            return (JSONCodec<Object>) jsonStringIdentityrefCodec;
-        }
-        return createFromSimpleType(normalizedType);
-    }
-
-    private JSONCodec<Object> createReferencedTypeCodec(final DataSchemaNode schema,
-            final LeafrefTypeDefinition type) {
-        // FIXME: Verify if this does indeed support leafref of leafref
-        final TypeDefinition<?> referencedType =
-                SchemaContextUtil.getBaseTypeForLeafRef(type, getSchemaContext(), schema);
-        return createCodec(schema, referencedType);
-    }
-
-    @SuppressWarnings("unchecked")
-    private JSONCodec<Object> createFromSimpleType(final TypeDefinition<?> type) {
-        if (type instanceof InstanceIdentifierTypeDefinition) {
-            return (JSONCodec<Object>) iidCodec;
-        }
-        if (type instanceof EmptyTypeDefinition) {
-            return (JSONCodec<Object>) JSONEmptyCodec.INSTANCE;
-        }
-
-        final TypeDefinitionAwareCodec<Object, ?> codec = TypeDefinitionAwareCodec.from(type);
-        if (codec == null) {
-            LOG.debug("Codec for type \"{}\" is not implemented yet.", type.getQName()
-                    .getLocalName());
-            return NULL_CODEC;
-        }
-        return (JSONCodec<Object>) AbstractJSONCodec.create(codec);
-    }
-
-    SchemaContext getSchemaContext() {
-        return schemaContext;
-    }
-
-    JSONCodec<Object> codecFor(final DataSchemaNode schema) {
-        return codecs.getUnchecked(schema);
+public abstract class JSONCodecFactory extends AbstractCodecFactory<JSONCodec<?>> {
+    JSONCodecFactory(final @NonNull EffectiveModelContext context, final @NonNull CodecCache<JSONCodec<?>> cache) {
+        super(context, cache);
     }
 
+    @Override
+    protected final JSONCodec<?> binaryCodec(final BinaryTypeDefinition type) {
+        return new QuotedJSONCodec<>(BinaryStringCodec.from(type));
+    }
+
+    @Override
+    protected final JSONCodec<?> booleanCodec(final BooleanTypeDefinition type) {
+        return new BooleanJSONCodec(BooleanStringCodec.from(type));
+    }
+
+    @Override
+    protected final JSONCodec<?> bitsCodec(final BitsTypeDefinition type) {
+        return new QuotedJSONCodec<>(BitsStringCodec.from(type));
+    }
+
+    @Override
+    protected final JSONCodec<?> decimalCodec(final DecimalTypeDefinition type) {
+        return wrapDecimalCodec(DecimalStringCodec.from(type));
+    }
+
+    @Override
+    protected final JSONCodec<?> emptyCodec(final EmptyTypeDefinition type) {
+        return EmptyJSONCodec.INSTANCE;
+    }
+
+    @Override
+    protected final JSONCodec<?> enumCodec(final EnumTypeDefinition type) {
+        return new QuotedJSONCodec<>(EnumStringCodec.from(type));
+    }
+
+    @Override
+    protected final JSONCodec<?> identityRefCodec(final IdentityrefTypeDefinition type, final QNameModule module) {
+        return new IdentityrefJSONCodec(getEffectiveModelContext(), module);
+    }
+
+    @Override
+    protected final JSONCodec<?> int8Codec(final Int8TypeDefinition type) {
+        return new NumberJSONCodec<>(AbstractIntegerStringCodec.from(type));
+    }
+
+    @Override
+    protected final JSONCodec<?> int16Codec(final Int16TypeDefinition type) {
+        return new NumberJSONCodec<>(AbstractIntegerStringCodec.from(type));
+    }
+
+    @Override
+    protected final JSONCodec<?> int32Codec(final Int32TypeDefinition type) {
+        return new NumberJSONCodec<>(AbstractIntegerStringCodec.from(type));
+    }
+
+    @Override
+    protected final JSONCodec<?> int64Codec(final Int64TypeDefinition type) {
+        return wrapIntegerCodec(AbstractIntegerStringCodec.from(type));
+    }
+
+    @Override
+    protected final JSONCodec<?> stringCodec(final StringTypeDefinition type) {
+        return new QuotedJSONCodec<>(StringStringCodec.from(type));
+    }
+
+    @Override
+    protected final JSONCodec<?> uint8Codec(final Uint8TypeDefinition type) {
+        return new NumberJSONCodec<>(AbstractIntegerStringCodec.from(type));
+    }
+
+    @Override
+    protected final JSONCodec<?> uint16Codec(final Uint16TypeDefinition type) {
+        return new NumberJSONCodec<>(AbstractIntegerStringCodec.from(type));
+    }
+
+    @Override
+    protected final JSONCodec<?> uint32Codec(final Uint32TypeDefinition type) {
+        return new NumberJSONCodec<>(AbstractIntegerStringCodec.from(type));
+    }
+
+    @Override
+    protected final JSONCodec<?> uint64Codec(final Uint64TypeDefinition type) {
+        return wrapIntegerCodec(AbstractIntegerStringCodec.from(type));
+    }
+
+    @Override
+    protected final JSONCodec<?> unionCodec(final UnionTypeDefinition type, final List<JSONCodec<?>> codecs) {
+        return UnionJSONCodec.create(type, codecs);
+    }
+
+    @Override
+    protected final JSONCodec<?> unknownCodec(final UnknownTypeDefinition type) {
+        return NullJSONCodec.INSTANCE;
+    }
+
+    @Override
+    protected abstract JSONCodec<?> instanceIdentifierCodec(InstanceIdentifierTypeDefinition type);
+
+    // Returns a one-off factory for the purposes of normalizing an anydata tree.
+    //
+    // FIXME: 7.0.0: this is really ugly, as we should be able to tell if the new context is the same as ours and
+    //               whether our cache is thread-safe -- in which case we should just return this.
+    //               The supplier/cache/factory layout needs to be reworked so that this call ends up being equivalent
+    //               to JSONCodecFactorySupplier.getShared() in case this factory is not thread safe.
+    //
+    //               The above is not currently possible, as we cannot reference JSONCodecFactorySupplier from the
+    //               factory due to that potentially creating a circular reference.
+    final JSONCodecFactory rebaseTo(final EffectiveModelContext newSchemaContext) {
+        return rebaseTo(newSchemaContext, new LazyCodecCache<>());
+    }
+
+    abstract JSONCodecFactory rebaseTo(EffectiveModelContext newSchemaContext, CodecCache<JSONCodec<?>> newCache);
+
+    abstract JSONCodec<?> wrapDecimalCodec(DecimalStringCodec decimalCodec);
+
+    abstract JSONCodec<?> wrapIntegerCodec(AbstractIntegerStringCodec<?, ?> integerCodec);
 }