Bug 2964 - ClassCastException when querying -
[yangtools.git] / yang / yang-data-codec-gson / src / main / java / org / opendaylight / yangtools / yang / data / codec / gson / JSONCodecFactory.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.yang.data.codec.gson;
9
10 import com.google.common.annotations.Beta;
11 import com.google.common.base.Preconditions;
12 import com.google.common.cache.CacheBuilder;
13 import com.google.common.cache.CacheLoader;
14 import com.google.common.cache.LoadingCache;
15 import com.google.gson.stream.JsonWriter;
16 import java.io.IOException;
17 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
18 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
19 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
20 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
21 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
22 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
23 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
24 import org.opendaylight.yangtools.yang.model.util.IdentityrefType;
25 import org.opendaylight.yangtools.yang.model.util.InstanceIdentifierType;
26 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29
30 /**
31  * Factory for creating JSON equivalents of codecs. Each instance of this object is bound to
32  * a particular {@link SchemaContext}, but can be reused by multiple {@link JSONNormalizedNodeStreamWriter}s.
33  */
34 @Beta
35 public final class JSONCodecFactory {
36     private static final Logger LOG = LoggerFactory.getLogger(JSONCodecFactory.class);
37     private static final JSONCodec<Object> NULL_CODEC = new JSONCodec<Object>() {
38         @Override
39         public Object deserialize(final String input) {
40             return null;
41         }
42
43         @Override
44         public String serialize(final Object input) {
45             return null;
46         }
47
48         @Override
49         public boolean needQuotes() {
50             return false;
51         }
52
53         @Override
54         public void serializeToWriter(JsonWriter writer, Object value) throws IOException {
55             // NOOP since codec is unkwown.
56             LOG.warn("Call of the serializeToWriter method on JSONCodecFactory.NULL_CODEC object. No operation performed.");
57         }
58     };
59
60     private final LoadingCache<DataSchemaNode, JSONCodec<Object>> codecs =
61             CacheBuilder.newBuilder().softValues().build(new CacheLoader<DataSchemaNode, JSONCodec<Object>>() {
62         @Override
63         public JSONCodec<Object> load(final DataSchemaNode key) throws Exception {
64             final TypeDefinition<?> type;
65             if (key instanceof LeafSchemaNode) {
66                 type = ((LeafSchemaNode) key).getType();
67             } else if (key instanceof LeafListSchemaNode) {
68                 type = ((LeafListSchemaNode) key).getType();
69             } else {
70                 throw new IllegalArgumentException("Not supported node type " + key.getClass().getName());
71             }
72             return createCodec(key,type);
73         }
74     });
75
76     private final SchemaContext schemaContext;
77     private final JSONCodec<?> iidCodec;
78
79     private JSONCodecFactory(final SchemaContext context) {
80         this.schemaContext = Preconditions.checkNotNull(context);
81         iidCodec = new JSONStringInstanceIdentifierCodec(context);
82     }
83
84     /**
85      * Instantiate a new codec factory attached to a particular context.
86      *
87      * @param context SchemaContext to which the factory should be bound
88      * @return A codec factory instance.
89      */
90     public static JSONCodecFactory create(final SchemaContext context) {
91         return new JSONCodecFactory(context);
92     }
93
94     private static TypeDefinition<?> resolveBaseTypeFrom(final TypeDefinition<?> type) {
95         TypeDefinition<?> superType = type;
96         while (superType.getBaseType() != null) {
97             superType = superType.getBaseType();
98         }
99         return superType;
100     }
101
102     @SuppressWarnings("unchecked")
103     private JSONCodec<Object> createCodec(DataSchemaNode key, TypeDefinition<?> type) {
104         TypeDefinition<?> baseType = resolveBaseTypeFrom(type);
105         if (baseType instanceof LeafrefTypeDefinition) {
106             return createReferencedTypeCodec(key, (LeafrefTypeDefinition) baseType);
107         } else if (baseType instanceof IdentityrefType) {
108             final JSONCodec<?> jsonStringIdentityrefCodec = new JSONStringIdentityrefCodec(schemaContext,
109                     key.getQName().getModule());
110             return (JSONCodec<Object>) jsonStringIdentityrefCodec;
111         }
112         return createFromSimpleType(type);
113     }
114
115     private JSONCodec<Object> createReferencedTypeCodec(DataSchemaNode schema,
116             LeafrefTypeDefinition type) {
117         // FIXME: Verify if this does indeed support leafref of leafref
118         TypeDefinition<?> referencedType =
119                 SchemaContextUtil.getBaseTypeForLeafRef(type, getSchemaContext(), schema);
120         return createCodec(schema, referencedType);
121     }
122
123     @SuppressWarnings("unchecked")
124     private JSONCodec<Object> createFromSimpleType(TypeDefinition<?> type) {
125         final TypeDefinition<?> baseType = resolveBaseTypeFrom(type);
126         if (baseType instanceof InstanceIdentifierType) {
127             return (JSONCodec<Object>) iidCodec;
128         }
129
130         final TypeDefinitionAwareCodec<Object, ?> codec = TypeDefinitionAwareCodec.from(type);
131         if (codec == null) {
132             LOG.debug("Codec for type \"{}\" is not implemented yet.", type.getQName()
133                     .getLocalName());
134             return NULL_CODEC;
135         }
136         return (JSONCodec<Object>) AbstractJSONCodec.create(codec);
137     }
138
139     SchemaContext getSchemaContext() {
140         return schemaContext;
141     }
142
143     JSONCodec<Object> codecFor(DataSchemaNode schema) {
144         return codecs.getUnchecked(schema);
145     }
146
147 }