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;
13 import java.lang.reflect.Constructor;
14 import java.lang.reflect.InvocationTargetException;
15 import java.lang.reflect.Method;
16 import java.lang.reflect.ParameterizedType;
17 import java.lang.reflect.Type;
18 import java.util.AbstractMap.SimpleEntry;
19 import java.util.ArrayList;
20 import java.util.Collection;
21 import java.util.HashMap;
22 import java.util.LinkedHashMap;
23 import java.util.LinkedList;
24 import java.util.List;
26 import java.util.Map.Entry;
27 import java.util.concurrent.Callable;
29 import javax.annotation.Nonnull;
30 import javax.annotation.Nullable;
32 import org.opendaylight.yangtools.binding.data.codec.impl.NodeCodecContext.CodecContextFactory;
33 import org.opendaylight.yangtools.concepts.Codec;
34 import org.opendaylight.yangtools.concepts.Immutable;
35 import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
36 import org.opendaylight.yangtools.util.ClassLoaderUtils;
37 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
38 import org.opendaylight.yangtools.yang.binding.BindingMapping;
39 import org.opendaylight.yangtools.yang.binding.BindingStreamEventWriter;
40 import org.opendaylight.yangtools.yang.binding.Identifiable;
41 import org.opendaylight.yangtools.yang.binding.Identifier;
42 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
43 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.IdentifiableItem;
44 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
45 import org.opendaylight.yangtools.yang.common.QName;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
48 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
49 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
50 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
55 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
56 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
57 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
58 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
62 class BindingCodecContext implements CodecContextFactory, Immutable {
63 private static final Logger LOG = LoggerFactory.getLogger(BindingCodecContext.class);
64 private static final String GETTER_PREFIX = "get";
66 private final SchemaRootCodecContext root;
67 private final BindingRuntimeContext context;
68 private final Codec<YangInstanceIdentifier, InstanceIdentifier<?>> instanceIdentifierCodec =
69 new InstanceIdentifierCodec();
70 private final Codec<QName, Class<?>> identityCodec = new IdentityCodec();
72 public BindingCodecContext(final BindingRuntimeContext context) {
73 this.context = Preconditions.checkNotNull(context, "Binding Runtime Context is required.");
74 this.root = SchemaRootCodecContext.create(this);
78 public BindingRuntimeContext getRuntimeContext() {
82 Codec<YangInstanceIdentifier, InstanceIdentifier<?>> getInstanceIdentifierCodec() {
83 return instanceIdentifierCodec;
86 public Codec<QName, Class<?>> getIdentityCodec() {
90 public Entry<YangInstanceIdentifier, BindingStreamEventWriter> newWriter(final InstanceIdentifier<?> path,
91 final NormalizedNodeStreamWriter domWriter) {
92 LinkedList<YangInstanceIdentifier.PathArgument> yangArgs = new LinkedList<>();
93 DataContainerCodecContext<?> codecContext = getCodecContextNode(path, yangArgs);
94 BindingStreamEventWriter writer = new BindingToNormalizedStreamWriter(codecContext, domWriter);
95 return new SimpleEntry<>(YangInstanceIdentifier.create(yangArgs), writer);
98 public BindingStreamEventWriter newWriterWithoutIdentifier(final InstanceIdentifier<?> path,
99 final NormalizedNodeStreamWriter domWriter) {
100 return new BindingToNormalizedStreamWriter(getCodecContextNode(path, null), domWriter);
103 public DataContainerCodecContext<?> getCodecContextNode(final InstanceIdentifier<?> binding,
104 final List<YangInstanceIdentifier.PathArgument> builder) {
105 DataContainerCodecContext<?> currentNode = root;
106 for (InstanceIdentifier.PathArgument bindingArg : binding.getPathArguments()) {
107 currentNode = currentNode.getIdentifierChild(bindingArg, builder);
113 * Multi-purpose utility function. Traverse the codec tree, looking for
114 * the appropriate codec for the specified {@link YangInstanceIdentifier}.
115 * As a side-effect, gather all traversed binding {@link InstanceIdentifier.PathArgument}s
116 * into the supplied collection.
118 * @param dom {@link YangInstanceIdentifier} which is to be translated
119 * @param bindingArguments Collection for traversed path arguments
120 * @return Codec for target node, or @null if the node does not have a
121 * binding representation (choice, case, leaf).
123 @Nullable NodeCodecContext getCodecContextNode(final @Nonnull YangInstanceIdentifier dom,
124 final @Nonnull Collection<InstanceIdentifier.PathArgument> bindingArguments) {
125 NodeCodecContext currentNode = root;
126 ListNodeCodecContext currentList = null;
128 for (YangInstanceIdentifier.PathArgument domArg : dom.getPathArguments()) {
129 Preconditions.checkArgument(currentNode instanceof DataContainerCodecContext<?>, "Unexpected child of non-container node %s", currentNode);
130 final DataContainerCodecContext<?> previous = (DataContainerCodecContext<?>) currentNode;
131 final NodeCodecContext nextNode = previous.getYangIdentifierChild(domArg);
134 * List representation in YANG Instance Identifier consists of two
135 * arguments: first is list as a whole, second is list as an item so
136 * if it is /list it means list as whole, if it is /list/list - it
137 * is wildcarded and if it is /list/list[key] it is concrete item,
138 * all this variations are expressed in Binding Aware Instance
139 * Identifier as Item or IdentifiableItem
141 if (currentList != null) {
142 Preconditions.checkArgument(currentList == nextNode, "List should be referenced two times in YANG Instance Identifier %s", dom);
144 // We entered list, so now we have all information to emit
145 // list path using second list argument.
146 bindingArguments.add(currentList.getBindingPathArgument(domArg));
148 currentNode = nextNode;
149 } else if (nextNode instanceof ListNodeCodecContext) {
150 // We enter list, we do not update current Node yet,
151 // since we need to verify
152 currentList = (ListNodeCodecContext) nextNode;
153 } else if (nextNode instanceof ChoiceNodeCodecContext) {
154 // We do not add path argument for choice, since
155 // it is not supported by binding instance identifier.
156 currentNode = nextNode;
157 } else if (nextNode instanceof DataContainerCodecContext<?>) {
158 bindingArguments.add(((DataContainerCodecContext<?>) nextNode).getBindingPathArgument(domArg));
159 currentNode = nextNode;
160 } else if (nextNode instanceof LeafNodeCodecContext) {
161 LOG.debug("Instance identifier referencing a leaf is not representable (%s)", dom);
166 // Algorithm ended in list as whole representation
167 // we sill need to emit identifier for list
168 if (currentNode instanceof ChoiceNodeCodecContext) {
169 LOG.debug("Instance identifier targeting a choice is not representable (%s)", dom);
172 if (currentNode instanceof CaseNodeCodecContext) {
173 LOG.debug("Instance identifier targeting a case is not representable (%s)", dom);
177 if (currentList != null) {
178 bindingArguments.add(currentList.getBindingPathArgument(null));
185 public ImmutableMap<String, LeafNodeCodecContext> getLeafNodes(final Class<?> parentClass,
186 final DataNodeContainer childSchema) {
187 HashMap<String, DataSchemaNode> getterToLeafSchema = new HashMap<>();
188 for (DataSchemaNode leaf : childSchema.getChildNodes()) {
189 final TypeDefinition<?> typeDef;
190 if (leaf instanceof LeafSchemaNode) {
191 typeDef = ((LeafSchemaNode) leaf).getType();
192 } else if (leaf instanceof LeafListSchemaNode) {
193 typeDef = ((LeafListSchemaNode) leaf).getType();
198 String getterName = getGetterName(leaf.getQName(), typeDef);
199 getterToLeafSchema.put(getterName, leaf);
201 return getLeafNodesUsingReflection(parentClass, getterToLeafSchema);
204 private String getGetterName(final QName qName, TypeDefinition<?> typeDef) {
205 String suffix = BindingMapping.getClassName(qName);
207 while (typeDef.getBaseType() != null) {
208 typeDef = typeDef.getBaseType();
210 if (typeDef instanceof BooleanTypeDefinition) {
211 return "is" + suffix;
213 return GETTER_PREFIX + suffix;
216 private ImmutableMap<String, LeafNodeCodecContext> getLeafNodesUsingReflection(final Class<?> parentClass,
217 final Map<String, DataSchemaNode> getterToLeafSchema) {
218 Map<String, LeafNodeCodecContext> leaves = new HashMap<>();
219 for (Method method : parentClass.getMethods()) {
220 if (method.getParameterTypes().length == 0) {
221 DataSchemaNode schema = getterToLeafSchema.get(method.getName());
222 final Class<?> valueType;
223 if (schema instanceof LeafSchemaNode) {
224 valueType = method.getReturnType();
225 } else if (schema instanceof LeafListSchemaNode) {
226 Type genericType = ClassLoaderUtils.getFirstGenericParameter(method.getGenericReturnType());
228 if (genericType instanceof Class<?>) {
229 valueType = (Class<?>) genericType;
230 } else if (genericType instanceof ParameterizedType) {
231 valueType = (Class<?>) ((ParameterizedType) genericType).getRawType();
233 throw new IllegalStateException("Unexpected return type " + genericType);
236 continue; // We do not have schema for leaf, so we will ignore it (eg. getClass, getImplementedInterface).
238 Codec<Object, Object> codec = getCodec(valueType, schema);
239 final LeafNodeCodecContext leafNode = new LeafNodeCodecContext(schema, codec, method);
240 leaves.put(schema.getQName().getLocalName(), leafNode);
243 return ImmutableMap.copyOf(leaves);
248 private Codec<Object, Object> getCodec(final Class<?> valueType, final DataSchemaNode schema) {
249 if (Class.class.equals(valueType)) {
250 @SuppressWarnings({ "unchecked", "rawtypes" })
251 final Codec<Object, Object> casted = (Codec) identityCodec;
253 } else if (InstanceIdentifier.class.equals(valueType)) {
254 @SuppressWarnings({ "unchecked", "rawtypes" })
255 final Codec<Object, Object> casted = (Codec) instanceIdentifierCodec;
257 } else if (BindingReflections.isBindingClass(valueType)) {
258 final TypeDefinition<?> instantiatedType;
259 if (schema instanceof LeafSchemaNode) {
260 instantiatedType = ((LeafSchemaNode) schema).getType();
261 } else if (schema instanceof LeafListSchemaNode) {
262 instantiatedType = ((LeafListSchemaNode) schema).getType();
264 instantiatedType = null;
266 if (instantiatedType != null) {
267 return getCodec(valueType, instantiatedType);
270 return ValueTypeCodec.NOOP_CODEC;
273 private Codec<Object, Object> getCodec(final Class<?> valueType, final TypeDefinition<?> instantiatedType) {
274 @SuppressWarnings("rawtypes")
275 TypeDefinition rootType = instantiatedType;
276 while (rootType.getBaseType() != null) {
277 rootType = rootType.getBaseType();
279 if (rootType instanceof IdentityrefTypeDefinition) {
280 return ValueTypeCodec.encapsulatedValueCodecFor(valueType, identityCodec);
281 } else if (rootType instanceof InstanceIdentifierTypeDefinition) {
282 return ValueTypeCodec.encapsulatedValueCodecFor(valueType, instanceIdentifierCodec);
283 } else if (rootType instanceof UnionTypeDefinition) {
284 Callable<UnionTypeCodec> loader = UnionTypeCodec.loader(valueType, (UnionTypeDefinition) rootType);
286 return loader.call();
287 } catch (Exception e) {
288 throw new IllegalStateException("Unable to load codec for " + valueType, e);
291 return ValueTypeCodec.getCodecFor(valueType, instantiatedType);
294 private class InstanceIdentifierCodec implements Codec<YangInstanceIdentifier, InstanceIdentifier<?>> {
297 public YangInstanceIdentifier serialize(final InstanceIdentifier<?> input) {
298 List<YangInstanceIdentifier.PathArgument> domArgs = new ArrayList<>();
299 getCodecContextNode(input, domArgs);
300 return YangInstanceIdentifier.create(domArgs);
304 public InstanceIdentifier<?> deserialize(final YangInstanceIdentifier input) {
305 final List<InstanceIdentifier.PathArgument> builder = new ArrayList<>();
306 final NodeCodecContext codec = getCodecContextNode(input, builder);
307 return codec == null ? null : InstanceIdentifier.create(builder);
311 private class IdentityCodec implements Codec<QName, Class<?>> {
314 public Class<?> deserialize(final QName input) {
315 Preconditions.checkArgument(input != null, "Input must not be null.");
316 return context.getIdentityClass(input);
320 public QName serialize(final Class<?> input) {
321 Preconditions.checkArgument(BaseIdentity.class.isAssignableFrom(input));
322 return BindingReflections.findQName(input);
326 private static class ValueContext {
329 Codec<Object, Object> codec;
331 public ValueContext(final Class<?> identifier, final LeafNodeCodecContext leaf) {
332 final String getterName = GETTER_PREFIX
333 + BindingMapping.getClassName(leaf.getDomPathArgument().getNodeType());
335 getter = identifier.getMethod(getterName);
336 } catch (NoSuchMethodException | SecurityException e) {
337 throw new IllegalStateException(e);
339 codec = leaf.getValueCodec();
342 public Object getAndSerialize(final Object obj) {
344 Object value = getter.invoke(obj);
345 Preconditions.checkArgument(value != null,
346 "All keys must be specified for %s. Missing key is %s. Supplied key is %s",
347 getter.getDeclaringClass(), getter.getName(), obj);
348 return codec.serialize(value);
349 } catch (IllegalAccessException | InvocationTargetException e) {
350 throw new IllegalArgumentException(e);
354 public Object deserialize(final Object obj) {
355 return codec.deserialize(obj);
360 private static class IdentifiableItemCodec implements Codec<NodeIdentifierWithPredicates, IdentifiableItem<?, ?>> {
362 private final Map<QName, ValueContext> keyValueContexts;
363 private final ListSchemaNode schema;
364 private final Constructor<? extends Identifier<?>> constructor;
365 private final Class<?> identifiable;
367 public IdentifiableItemCodec(final ListSchemaNode schema, final Class<? extends Identifier<?>> keyClass,
368 final Class<?> identifiable, final Map<QName, ValueContext> keyValueContexts) {
369 this.schema = schema;
370 this.identifiable = identifiable;
371 this.constructor = getConstructor(keyClass);
374 * We need to re-index to make sure we instantiate nodes in the order in which
377 final Map<QName, ValueContext> keys = new LinkedHashMap<>();
378 for (QName qname : schema.getKeyDefinition()) {
379 keys.put(qname, keyValueContexts.get(qname));
381 this.keyValueContexts = ImmutableMap.copyOf(keys);
385 public IdentifiableItem<?, ?> deserialize(final NodeIdentifierWithPredicates input) {
386 final Collection<QName> keys = schema.getKeyDefinition();
387 final ArrayList<Object> bindingValues = new ArrayList<>(keys.size());
388 for (QName key : keys) {
389 Object yangValue = input.getKeyValues().get(key);
390 bindingValues.add(keyValueContexts.get(key).deserialize(yangValue));
393 final Identifier<?> identifier;
395 identifier = constructor.newInstance(bindingValues.toArray());
396 } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
397 throw new IllegalStateException(String.format("Failed to instantiate key class %s", constructor.getDeclaringClass()), e);
400 @SuppressWarnings({ "rawtypes", "unchecked" })
401 final IdentifiableItem identifiableItem = new IdentifiableItem(identifiable, identifier);
402 return identifiableItem;
406 public NodeIdentifierWithPredicates serialize(final IdentifiableItem<?, ?> input) {
407 Object value = input.getKey();
409 Map<QName, Object> values = new LinkedHashMap<>();
410 for (Entry<QName, ValueContext> valueCtx : keyValueContexts.entrySet()) {
411 values.put(valueCtx.getKey(), valueCtx.getValue().getAndSerialize(value));
413 return new NodeIdentifierWithPredicates(schema.getQName(), values);
417 @SuppressWarnings("unchecked")
418 private static Constructor<? extends Identifier<?>> getConstructor(final Class<? extends Identifier<?>> clazz) {
419 for (@SuppressWarnings("rawtypes") Constructor constr : clazz.getConstructors()) {
420 Class<?>[] parameters = constr.getParameterTypes();
421 if (!clazz.equals(parameters[0])) {
422 // It is not copy constructor;
426 throw new IllegalArgumentException("Supplied class " + clazz + "does not have required constructor.");
430 public Codec<NodeIdentifierWithPredicates, IdentifiableItem<?, ?>> getPathArgumentCodec(final Class<?> listClz,
431 final ListSchemaNode schema) {
432 Class<? extends Identifier<?>> identifier = ClassLoaderUtils.findFirstGenericArgument(listClz,
434 Map<QName, ValueContext> valueCtx = new HashMap<>();
435 for (LeafNodeCodecContext leaf : getLeafNodes(identifier, schema).values()) {
436 QName name = leaf.getDomPathArgument().getNodeType();
437 valueCtx.put(name, new ValueContext(identifier, leaf));
439 return new IdentifiableItemCodec(schema, identifier, listClz, valueCtx);