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.binding.data.codec.impl;
10 import com.google.common.base.Preconditions;
11 import com.google.common.collect.ImmutableMap;
12 import java.lang.reflect.Constructor;
13 import java.lang.reflect.InvocationTargetException;
14 import java.lang.reflect.Method;
15 import java.lang.reflect.ParameterizedType;
16 import java.lang.reflect.Type;
17 import java.util.AbstractMap.SimpleEntry;
18 import java.util.ArrayList;
19 import java.util.HashMap;
20 import java.util.LinkedList;
21 import java.util.List;
23 import java.util.Map.Entry;
24 import java.util.concurrent.Callable;
25 import org.opendaylight.yangtools.binding.data.codec.impl.NodeCodecContext.CodecContextFactory;
26 import org.opendaylight.yangtools.concepts.Codec;
27 import org.opendaylight.yangtools.concepts.Immutable;
28 import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
29 import org.opendaylight.yangtools.util.ClassLoaderUtils;
30 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
31 import org.opendaylight.yangtools.yang.binding.BindingMapping;
32 import org.opendaylight.yangtools.yang.binding.BindingStreamEventWriter;
33 import org.opendaylight.yangtools.yang.binding.Identifiable;
34 import org.opendaylight.yangtools.yang.binding.Identifier;
35 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
36 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.IdentifiableItem;
37 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
38 import org.opendaylight.yangtools.yang.common.QName;
39 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
40 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
41 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
42 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
43 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
48 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
49 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
50 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
51 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
53 class BindingCodecContext implements CodecContextFactory, Immutable {
55 private static final String GETTER_PREFIX = "get";
56 private final SchemaRootCodecContext root;
57 private final BindingRuntimeContext context;
58 private final Codec<YangInstanceIdentifier, InstanceIdentifier<?>> instanceIdentifierCodec;
59 private final Codec<QName, Class<?>> identityCodec;
61 public BindingCodecContext(final BindingRuntimeContext context) {
62 this.context = Preconditions.checkNotNull(context, "Binding Runtime Context is required.");
63 this.root = SchemaRootCodecContext.create(this);
64 this.instanceIdentifierCodec = new InstanceIdentifierCodec();
65 this.identityCodec = new IdentityCodec();
69 public BindingRuntimeContext getRuntimeContext() {
73 public Codec<YangInstanceIdentifier, InstanceIdentifier<?>> getInstanceIdentifierCodec() {
74 return instanceIdentifierCodec;
77 public Codec<QName, Class<?>> getIdentityCodec() {
81 public Entry<YangInstanceIdentifier, BindingStreamEventWriter> newWriter(final InstanceIdentifier<?> path,
82 final NormalizedNodeStreamWriter domWriter) {
83 LinkedList<YangInstanceIdentifier.PathArgument> yangArgs = new LinkedList<>();
84 DataContainerCodecContext<?> codecContext = getCodecContextNode(path, yangArgs);
85 BindingStreamEventWriter writer = new BindingToNormalizedStreamWriter(codecContext, domWriter);
86 return new SimpleEntry<>(YangInstanceIdentifier.create(yangArgs), writer);
89 public BindingStreamEventWriter newWriterWithoutIdentifier(final InstanceIdentifier<?> path,
90 final NormalizedNodeStreamWriter domWriter) {
91 return new BindingToNormalizedStreamWriter(getCodecContextNode(path, null), domWriter);
94 public DataContainerCodecContext<?> getCodecContextNode(final InstanceIdentifier<?> binding,
95 final List<YangInstanceIdentifier.PathArgument> builder) {
96 DataContainerCodecContext<?> currentNode = root;
97 for (InstanceIdentifier.PathArgument bindingArg : binding.getPathArguments()) {
98 currentNode = currentNode.getIdentifierChild(bindingArg, builder);
103 public NodeCodecContext getCodecContextNode(final YangInstanceIdentifier dom,
104 final List<InstanceIdentifier.PathArgument> builder) {
105 NodeCodecContext currentNode = root;
106 ListNodeCodecContext currentList = null;
107 for (YangInstanceIdentifier.PathArgument domArg : dom.getPathArguments()) {
108 Preconditions.checkArgument(currentNode instanceof DataContainerCodecContext<?>);
109 DataContainerCodecContext<?> previous = (DataContainerCodecContext<?>) currentNode;
110 NodeCodecContext nextNode = previous.getYangIdentifierChild(domArg);
112 * List representation in YANG Instance Identifier consists of two
113 * arguments: first is list as a whole, second is list as an item so
114 * if it is /list it means list as whole, if it is /list/list - it
115 * is wildcarded and if it is /list/list[key] it is concrete item,
116 * all this variations are expressed in Binding Aware Instance
117 * Identifier as Item or IdentifiableItem
119 if (currentList != null) {
121 if (currentList == nextNode) {
123 // We entered list, so now we have all information to emit
125 // path using second list argument.
126 builder.add(currentList.getBindingPathArgument(domArg));
128 currentNode = nextNode;
130 throw new IllegalArgumentException(
131 "List should be referenced two times in YANG Instance Identifier");
133 } else if (nextNode instanceof ListNodeCodecContext) {
134 // We enter list, we do not update current Node yet,
135 // since we need to verify
136 currentList = (ListNodeCodecContext) nextNode;
137 } else if (nextNode instanceof ChoiceNodeCodecContext) {
138 // We do not add path argument for choice, since
139 // it is not supported by binding instance identifier.
140 currentNode = nextNode;
141 } else if (nextNode instanceof DataContainerCodecContext<?>) {
142 builder.add(((DataContainerCodecContext<?>) nextNode).getBindingPathArgument(domArg));
143 currentNode = nextNode;
144 } else if (nextNode instanceof LeafNodeCodecContext) {
145 Preconditions.checkArgument(builder == null, "Instance Identifier for leaf is not representable.");
149 // Algorithm ended in list as whole representation
150 // we sill need to emit identifier for list
152 if (builder != null) {
153 Preconditions.checkArgument(!(currentNode instanceof ChoiceNodeCodecContext),
154 "Instance Identifier for choice is not representable.");
155 Preconditions.checkArgument(!(currentNode instanceof CaseNodeCodecContext),
156 "Instance Identifier for case is not representable.");
158 if (currentList != null) {
159 builder.add(currentList.getBindingPathArgument(null));
166 public ImmutableMap<String, LeafNodeCodecContext> getLeafNodes(final Class<?> parentClass,
167 final DataNodeContainer childSchema) {
168 HashMap<String, DataSchemaNode> getterToLeafSchema = new HashMap<>();
169 for (DataSchemaNode leaf : childSchema.getChildNodes()) {
170 final TypeDefinition<?> typeDef;
171 if (leaf instanceof LeafSchemaNode) {
172 typeDef = ((LeafSchemaNode) leaf).getType();
173 } else if (leaf instanceof LeafListSchemaNode) {
174 typeDef = ((LeafListSchemaNode) leaf).getType();
179 String getterName = getGetterName(leaf.getQName(), typeDef);
180 getterToLeafSchema.put(getterName, leaf);
182 return getLeafNodesUsingReflection(parentClass, getterToLeafSchema);
185 private String getGetterName(final QName qName, TypeDefinition<?> typeDef) {
186 String suffix = BindingMapping.getClassName(qName);
188 while (typeDef.getBaseType() != null) {
189 typeDef = typeDef.getBaseType();
191 if (typeDef instanceof BooleanTypeDefinition) {
192 return "is" + suffix;
194 return GETTER_PREFIX + suffix;
197 private ImmutableMap<String, LeafNodeCodecContext> getLeafNodesUsingReflection(final Class<?> parentClass,
198 final Map<String, DataSchemaNode> getterToLeafSchema) {
199 Map<String, LeafNodeCodecContext> leaves = new HashMap<>();
200 for (Method method : parentClass.getMethods()) {
201 if (method.getParameterTypes().length == 0) {
202 DataSchemaNode schema = getterToLeafSchema.get(method.getName());
203 final Class<?> valueType;
204 if (schema instanceof LeafSchemaNode) {
205 valueType = method.getReturnType();
206 } else if (schema instanceof LeafListSchemaNode) {
207 Type genericType = ClassLoaderUtils.getFirstGenericParameter(method.getGenericReturnType());
209 if (genericType instanceof Class<?>) {
210 valueType = (Class<?>) genericType;
211 } else if (genericType instanceof ParameterizedType) {
212 valueType = (Class<?>) ((ParameterizedType) genericType).getRawType();
214 throw new IllegalStateException("Unexpected return type " + genericType);
217 continue; // We do not have schema for leaf, so we will ignore it (eg. getClass, getImplementedInterface).
219 final LeafNodeCodecContext leafNode = leafNodeFrom(valueType, schema);
220 leaves.put(schema.getQName().getLocalName(), leafNode);
223 return ImmutableMap.copyOf(leaves);
226 private LeafNodeCodecContext leafNodeFrom(final Class<?> returnType, final DataSchemaNode schema) {
227 return new LeafNodeCodecContext(schema, getCodec(returnType, schema));
230 private Codec<Object, Object> getCodec(final Class<?> valueType, final DataSchemaNode schema) {
231 if (Class.class.equals(valueType)) {
232 @SuppressWarnings({ "unchecked", "rawtypes" })
233 final Codec<Object, Object> casted = (Codec) identityCodec;
235 } else if (InstanceIdentifier.class.equals(valueType)) {
236 @SuppressWarnings({ "unchecked", "rawtypes" })
237 final Codec<Object, Object> casted = (Codec) instanceIdentifierCodec;
239 } else if (BindingReflections.isBindingClass(valueType)) {
240 final TypeDefinition<?> instantiatedType;
241 if (schema instanceof LeafSchemaNode) {
242 instantiatedType = ((LeafSchemaNode) schema).getType();
243 } else if (schema instanceof LeafListSchemaNode) {
244 instantiatedType = ((LeafListSchemaNode) schema).getType();
246 instantiatedType = null;
248 if (instantiatedType != null) {
249 return getCodec(valueType, instantiatedType);
252 return ValueTypeCodec.NOOP_CODEC;
255 private Codec<Object, Object> getCodec(final Class<?> valueType, final TypeDefinition<?> instantiatedType) {
256 @SuppressWarnings("rawtypes")
257 TypeDefinition rootType = instantiatedType;
258 while (rootType.getBaseType() != null) {
259 rootType = rootType.getBaseType();
261 if (rootType instanceof IdentityrefTypeDefinition) {
262 return ValueTypeCodec.encapsulatedValueCodecFor(valueType, identityCodec);
263 } else if (rootType instanceof InstanceIdentifierTypeDefinition) {
264 return ValueTypeCodec.encapsulatedValueCodecFor(valueType, instanceIdentifierCodec);
265 } else if (rootType instanceof UnionTypeDefinition) {
266 Callable<UnionTypeCodec> loader = UnionTypeCodec.loader(valueType, (UnionTypeDefinition) rootType,
267 getInstanceIdentifierCodec(), getIdentityCodec());
269 return loader.call();
270 } catch (Exception e) {
271 throw new IllegalStateException("Unable to load codec for "+valueType,e);
274 return ValueTypeCodec.getCodecFor(valueType, instantiatedType);
277 private class InstanceIdentifierCodec implements Codec<YangInstanceIdentifier, InstanceIdentifier<?>> {
280 public YangInstanceIdentifier serialize(final InstanceIdentifier<?> input) {
281 List<YangInstanceIdentifier.PathArgument> domArgs = new LinkedList<>();
282 getCodecContextNode(input, domArgs);
283 return YangInstanceIdentifier.create(domArgs);
287 public InstanceIdentifier<?> deserialize(final YangInstanceIdentifier input) {
288 List<InstanceIdentifier.PathArgument> builder = new LinkedList<>();
289 getCodecContextNode(input, builder);
290 return InstanceIdentifier.create(builder);
294 private class IdentityCodec implements Codec<QName, Class<?>> {
297 public Class<?> deserialize(final QName input) {
298 Preconditions.checkArgument(input != null, "Input must not be null.");
299 return context.getIdentityClass(input);
303 public QName serialize(final Class<?> input) {
304 Preconditions.checkArgument(BaseIdentity.class.isAssignableFrom(input));
305 return BindingReflections.findQName(input);
309 private static class ValueContext {
312 Codec<Object, Object> codec;
314 public ValueContext(final Class<?> identifier, final LeafNodeCodecContext leaf) {
315 final String getterName = GETTER_PREFIX
316 + BindingMapping.getClassName(leaf.getDomPathArgument().getNodeType());
318 getter = identifier.getMethod(getterName);
319 } catch (NoSuchMethodException | SecurityException e) {
320 throw new IllegalStateException(e);
322 codec = leaf.getValueCodec();
325 public Object getAndSerialize(final Object obj) {
327 Object value = getter.invoke(obj);
328 Preconditions.checkArgument(value != null,
329 "All keys must be specified for %s. Missing key is %s. Supplied key is %s",
330 getter.getDeclaringClass(), getter.getName(), obj);
331 return codec.serialize(value);
332 } catch (IllegalAccessException | InvocationTargetException e) {
333 throw new IllegalArgumentException(e);
337 public Object deserialize(final Object obj) {
338 return codec.deserialize(obj);
343 private class IdentifiableItemCodec implements Codec<NodeIdentifierWithPredicates, IdentifiableItem<?, ?>> {
345 private final ImmutableMap<QName, ValueContext> keyValueContexts;
346 private final QName name;
347 private final Constructor<? extends Identifier<?>> constructor;
348 private final Class<?> identifiable;
350 public IdentifiableItemCodec(final QName name, final Class<? extends Identifier<?>> keyClass,
351 final Class<?> identifiable, final Map<QName, ValueContext> keyValueContexts) {
353 this.identifiable = identifiable;
354 this.keyValueContexts = ImmutableMap.copyOf(keyValueContexts);
355 this.constructor = getConstructor(keyClass);
359 public IdentifiableItem<?, ?> deserialize(final NodeIdentifierWithPredicates input) {
360 ArrayList<Object> bindingValues = new ArrayList<>();
361 for (Entry<QName, Object> yangEntry : input.getKeyValues().entrySet()) {
362 QName yangName = yangEntry.getKey();
363 Object yangValue = yangEntry.getValue();
364 bindingValues.add(keyValueContexts.get(yangName).deserialize(yangValue));
367 final Identifier<?> identifier = constructor.newInstance(bindingValues.toArray());
368 @SuppressWarnings({ "rawtypes", "unchecked" })
369 final IdentifiableItem identifiableItem = new IdentifiableItem(identifiable, identifier);
370 return identifiableItem;
371 } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
372 throw new IllegalStateException(e);
377 public NodeIdentifierWithPredicates serialize(final IdentifiableItem<?, ?> input) {
378 Object value = input.getKey();
380 Map<QName, Object> values = new HashMap<>();
381 for (Entry<QName, ValueContext> valueCtx : keyValueContexts.entrySet()) {
382 values.put(valueCtx.getKey(), valueCtx.getValue().getAndSerialize(value));
384 return new NodeIdentifierWithPredicates(name, values);
389 @SuppressWarnings("unchecked")
390 private static Constructor<? extends Identifier<?>> getConstructor(final Class<? extends Identifier<?>> clazz) {
391 for (@SuppressWarnings("rawtypes") Constructor constr : clazz.getConstructors()) {
392 Class<?>[] parameters = constr.getParameterTypes();
393 if (!clazz.equals(parameters[0])) {
394 // It is not copy constructor;
398 throw new IllegalArgumentException("Supplied class " + clazz + "does not have required constructor.");
402 public Codec<NodeIdentifierWithPredicates, IdentifiableItem<?, ?>> getPathArgumentCodec(final Class<?> listClz,
403 final ListSchemaNode schema) {
404 Class<? extends Identifier<?>> identifier = ClassLoaderUtils.findFirstGenericArgument(listClz,
406 Map<QName, ValueContext> valueCtx = new HashMap<>();
407 for (LeafNodeCodecContext leaf : getLeafNodes(identifier, schema).values()) {
408 QName name = leaf.getDomPathArgument().getNodeType();
409 valueCtx.put(name, new ValueContext(identifier, leaf));
411 return new IdentifiableItemCodec(schema.getQName(), identifier, listClz, valueCtx);