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.Collection;
20 import java.util.HashMap;
21 import java.util.LinkedHashMap;
22 import java.util.LinkedList;
23 import java.util.List;
25 import java.util.Map.Entry;
26 import java.util.concurrent.Callable;
27 import javax.annotation.Nonnull;
28 import javax.annotation.Nullable;
29 import org.opendaylight.yangtools.binding.data.codec.impl.NodeCodecContext.CodecContextFactory;
30 import org.opendaylight.yangtools.concepts.Codec;
31 import org.opendaylight.yangtools.concepts.Immutable;
32 import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
33 import org.opendaylight.yangtools.util.ClassLoaderUtils;
34 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
35 import org.opendaylight.yangtools.yang.binding.BindingMapping;
36 import org.opendaylight.yangtools.yang.binding.BindingStreamEventWriter;
37 import org.opendaylight.yangtools.yang.binding.Identifiable;
38 import org.opendaylight.yangtools.yang.binding.Identifier;
39 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
40 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.IdentifiableItem;
41 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
42 import org.opendaylight.yangtools.yang.common.QName;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
45 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
46 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
47 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
52 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
53 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
54 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
55 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
56 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
60 class BindingCodecContext implements CodecContextFactory, Immutable {
61 private static final Logger LOG = LoggerFactory.getLogger(BindingCodecContext.class);
62 private static final String GETTER_PREFIX = "get";
64 private final SchemaRootCodecContext root;
65 private final BindingRuntimeContext context;
66 private final Codec<YangInstanceIdentifier, InstanceIdentifier<?>> instanceIdentifierCodec =
67 new InstanceIdentifierCodec();
68 private final Codec<QName, Class<?>> identityCodec = new IdentityCodec();
70 public BindingCodecContext(final BindingRuntimeContext context) {
71 this.context = Preconditions.checkNotNull(context, "Binding Runtime Context is required.");
72 this.root = SchemaRootCodecContext.create(this);
76 public BindingRuntimeContext getRuntimeContext() {
80 Codec<YangInstanceIdentifier, InstanceIdentifier<?>> getInstanceIdentifierCodec() {
81 return instanceIdentifierCodec;
84 public Codec<QName, Class<?>> getIdentityCodec() {
88 public Entry<YangInstanceIdentifier, BindingStreamEventWriter> newWriter(final InstanceIdentifier<?> path,
89 final NormalizedNodeStreamWriter domWriter) {
90 LinkedList<YangInstanceIdentifier.PathArgument> yangArgs = new LinkedList<>();
91 DataContainerCodecContext<?> codecContext = getCodecContextNode(path, yangArgs);
92 BindingStreamEventWriter writer = new BindingToNormalizedStreamWriter(codecContext, domWriter);
93 return new SimpleEntry<>(YangInstanceIdentifier.create(yangArgs), writer);
96 public BindingStreamEventWriter newWriterWithoutIdentifier(final InstanceIdentifier<?> path,
97 final NormalizedNodeStreamWriter domWriter) {
98 return new BindingToNormalizedStreamWriter(getCodecContextNode(path, null), domWriter);
101 public DataContainerCodecContext<?> getCodecContextNode(final InstanceIdentifier<?> binding,
102 final List<YangInstanceIdentifier.PathArgument> builder) {
103 DataContainerCodecContext<?> currentNode = root;
104 for (InstanceIdentifier.PathArgument bindingArg : binding.getPathArguments()) {
105 currentNode = currentNode.getIdentifierChild(bindingArg, builder);
111 * Multi-purpose utility function. Traverse the codec tree, looking for
112 * the appropriate codec for the specified {@link YangInstanceIdentifier}.
113 * As a side-effect, gather all traversed binding {@link InstanceIdentifier.PathArgument}s
114 * into the supplied collection.
116 * @param dom {@link YangInstanceIdentifier} which is to be translated
117 * @param bindingArguments Collection for traversed path arguments
118 * @return Codec for target node, or @null if the node does not have a
119 * binding representation (choice, case, leaf).
121 @Nullable NodeCodecContext getCodecContextNode(final @Nonnull YangInstanceIdentifier dom,
122 final @Nonnull Collection<InstanceIdentifier.PathArgument> bindingArguments) {
123 NodeCodecContext currentNode = root;
124 ListNodeCodecContext currentList = null;
126 for (YangInstanceIdentifier.PathArgument domArg : dom.getPathArguments()) {
127 Preconditions.checkArgument(currentNode instanceof DataContainerCodecContext<?>, "Unexpected child of non-container node %s", currentNode);
128 final DataContainerCodecContext<?> previous = (DataContainerCodecContext<?>) currentNode;
129 final NodeCodecContext nextNode = previous.getYangIdentifierChild(domArg);
132 * List representation in YANG Instance Identifier consists of two
133 * arguments: first is list as a whole, second is list as an item so
134 * if it is /list it means list as whole, if it is /list/list - it
135 * is wildcarded and if it is /list/list[key] it is concrete item,
136 * all this variations are expressed in Binding Aware Instance
137 * Identifier as Item or IdentifiableItem
139 if (currentList != null) {
140 Preconditions.checkArgument(currentList == nextNode, "List should be referenced two times in YANG Instance Identifier %s", dom);
142 // We entered list, so now we have all information to emit
143 // list path using second list argument.
144 bindingArguments.add(currentList.getBindingPathArgument(domArg));
146 currentNode = nextNode;
147 } else if (nextNode instanceof ListNodeCodecContext) {
148 // We enter list, we do not update current Node yet,
149 // since we need to verify
150 currentList = (ListNodeCodecContext) nextNode;
151 } else if (nextNode instanceof ChoiceNodeCodecContext) {
152 // We do not add path argument for choice, since
153 // it is not supported by binding instance identifier.
154 currentNode = nextNode;
155 } else if (nextNode instanceof DataContainerCodecContext<?>) {
156 bindingArguments.add(((DataContainerCodecContext<?>) nextNode).getBindingPathArgument(domArg));
157 currentNode = nextNode;
158 } else if (nextNode instanceof LeafNodeCodecContext) {
159 LOG.debug("Instance identifier referencing a leaf is not representable (%s)", dom);
164 // Algorithm ended in list as whole representation
165 // we sill need to emit identifier for list
166 if (currentNode instanceof ChoiceNodeCodecContext) {
167 LOG.debug("Instance identifier targeting a choice is not representable (%s)", dom);
170 if (currentNode instanceof CaseNodeCodecContext) {
171 LOG.debug("Instance identifier targeting a case is not representable (%s)", dom);
175 if (currentList != null) {
176 bindingArguments.add(currentList.getBindingPathArgument(null));
183 public ImmutableMap<String, LeafNodeCodecContext> getLeafNodes(final Class<?> parentClass,
184 final DataNodeContainer childSchema) {
185 HashMap<String, DataSchemaNode> getterToLeafSchema = new HashMap<>();
186 for (DataSchemaNode leaf : childSchema.getChildNodes()) {
187 final TypeDefinition<?> typeDef;
188 if (leaf instanceof LeafSchemaNode) {
189 typeDef = ((LeafSchemaNode) leaf).getType();
190 } else if (leaf instanceof LeafListSchemaNode) {
191 typeDef = ((LeafListSchemaNode) leaf).getType();
196 String getterName = getGetterName(leaf.getQName(), typeDef);
197 getterToLeafSchema.put(getterName, leaf);
199 return getLeafNodesUsingReflection(parentClass, getterToLeafSchema);
202 private String getGetterName(final QName qName, TypeDefinition<?> typeDef) {
203 String suffix = BindingMapping.getClassName(qName);
205 while (typeDef.getBaseType() != null) {
206 typeDef = typeDef.getBaseType();
208 if (typeDef instanceof BooleanTypeDefinition || typeDef instanceof EmptyTypeDefinition) {
209 return "is" + suffix;
211 return GETTER_PREFIX + suffix;
214 private ImmutableMap<String, LeafNodeCodecContext> getLeafNodesUsingReflection(final Class<?> parentClass,
215 final Map<String, DataSchemaNode> getterToLeafSchema) {
216 Map<String, LeafNodeCodecContext> leaves = new HashMap<>();
217 for (Method method : parentClass.getMethods()) {
218 if (method.getParameterTypes().length == 0) {
219 DataSchemaNode schema = getterToLeafSchema.get(method.getName());
220 final Class<?> valueType;
221 if (schema instanceof LeafSchemaNode) {
222 valueType = method.getReturnType();
223 } else if (schema instanceof LeafListSchemaNode) {
224 Type genericType = ClassLoaderUtils.getFirstGenericParameter(method.getGenericReturnType());
226 if (genericType instanceof Class<?>) {
227 valueType = (Class<?>) genericType;
228 } else if (genericType instanceof ParameterizedType) {
229 valueType = (Class<?>) ((ParameterizedType) genericType).getRawType();
231 throw new IllegalStateException("Unexpected return type " + genericType);
234 continue; // We do not have schema for leaf, so we will ignore it (eg. getClass, getImplementedInterface).
236 Codec<Object, Object> codec = getCodec(valueType, schema);
237 final LeafNodeCodecContext leafNode = new LeafNodeCodecContext(schema, codec, method);
238 leaves.put(schema.getQName().getLocalName(), leafNode);
241 return ImmutableMap.copyOf(leaves);
246 private Codec<Object, Object> getCodec(final Class<?> valueType, final DataSchemaNode schema) {
247 final TypeDefinition<?> instantiatedType;
248 if (schema instanceof LeafSchemaNode) {
249 instantiatedType = ((LeafSchemaNode) schema).getType();
250 } else if (schema instanceof LeafListSchemaNode) {
251 instantiatedType = ((LeafListSchemaNode) schema).getType();
253 throw new IllegalArgumentException("Unsupported leaf node type " + schema.getClass());
255 if (Class.class.equals(valueType)) {
256 @SuppressWarnings({ "unchecked", "rawtypes" })
257 final Codec<Object, Object> casted = (Codec) identityCodec;
259 } else if (InstanceIdentifier.class.equals(valueType)) {
260 @SuppressWarnings({ "unchecked", "rawtypes" })
261 final Codec<Object, Object> casted = (Codec) instanceIdentifierCodec;
263 } else if (Boolean.class.equals(valueType)) {
264 if(instantiatedType instanceof EmptyTypeDefinition) {
265 return ValueTypeCodec.EMPTY_CODEC;
267 } else if (BindingReflections.isBindingClass(valueType)) {
268 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);