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.Method;
13 import java.lang.reflect.ParameterizedType;
14 import java.lang.reflect.Type;
15 import java.util.AbstractMap.SimpleEntry;
16 import java.util.Collection;
17 import java.util.HashMap;
18 import java.util.LinkedList;
19 import java.util.List;
21 import java.util.Map.Entry;
22 import java.util.concurrent.Callable;
23 import javax.annotation.Nonnull;
24 import javax.annotation.Nullable;
25 import org.opendaylight.mdsal.binding.dom.codec.api.BindingCodecTree;
26 import org.opendaylight.mdsal.binding.dom.codec.api.BindingCodecTreeNode;
27 import org.opendaylight.yangtools.binding.data.codec.impl.NodeCodecContext.CodecContextFactory;
28 import org.opendaylight.yangtools.concepts.Codec;
29 import org.opendaylight.yangtools.concepts.Immutable;
30 import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
31 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType;
32 import org.opendaylight.yangtools.util.ClassLoaderUtils;
33 import org.opendaylight.yangtools.yang.binding.BindingMapping;
34 import org.opendaylight.yangtools.yang.binding.BindingStreamEventWriter;
35 import org.opendaylight.yangtools.yang.binding.DataContainer;
36 import org.opendaylight.yangtools.yang.binding.DataObject;
37 import org.opendaylight.yangtools.yang.binding.DataObjectSerializer;
38 import org.opendaylight.yangtools.yang.binding.Identifiable;
39 import org.opendaylight.yangtools.yang.binding.Identifier;
40 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
41 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.IdentifiableItem;
42 import org.opendaylight.yangtools.yang.binding.Notification;
43 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
44 import org.opendaylight.yangtools.yang.common.QName;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
47 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
48 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
49 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
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.EmptyTypeDefinition;
57 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
58 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
59 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
60 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
64 final class BindingCodecContext implements CodecContextFactory, BindingCodecTree, Immutable {
65 private static final Logger LOG = LoggerFactory.getLogger(BindingCodecContext.class);
67 private final Codec<YangInstanceIdentifier, InstanceIdentifier<?>> instanceIdentifierCodec;
68 private final Codec<QName, Class<?>> identityCodec;
69 private final BindingNormalizedNodeCodecRegistry registry;
70 private final BindingRuntimeContext context;
71 private final SchemaRootCodecContext<?> root;
73 BindingCodecContext(final BindingRuntimeContext context, final BindingNormalizedNodeCodecRegistry registry) {
74 this.context = Preconditions.checkNotNull(context, "Binding Runtime Context is required.");
75 this.root = SchemaRootCodecContext.create(this);
76 this.identityCodec = new IdentityCodec(context);
77 this.instanceIdentifierCodec = new InstanceIdentifierCodec(this);
78 this.registry = Preconditions.checkNotNull(registry);
82 public BindingRuntimeContext getRuntimeContext() {
86 Codec<YangInstanceIdentifier, InstanceIdentifier<?>> getInstanceIdentifierCodec() {
87 return instanceIdentifierCodec;
90 public Codec<QName, Class<?>> getIdentityCodec() {
94 @SuppressWarnings({"rawtypes", "unchecked"})
96 public DataObjectSerializer getEventStreamSerializer(final Class<?> type) {
97 return registry.getSerializer((Class) type);
100 public Entry<YangInstanceIdentifier, BindingStreamEventWriter> newWriter(final InstanceIdentifier<?> path,
101 final NormalizedNodeStreamWriter domWriter) {
102 final List<YangInstanceIdentifier.PathArgument> yangArgs = new LinkedList<>();
103 final DataContainerCodecContext<?,?> codecContext = getCodecContextNode(path, yangArgs);
104 return new SimpleEntry<>(YangInstanceIdentifier.create(yangArgs), codecContext.createWriter(domWriter));
107 public BindingStreamEventWriter newWriterWithoutIdentifier(final InstanceIdentifier<?> path,
108 final NormalizedNodeStreamWriter domWriter) {
109 return getCodecContextNode(path, null).createWriter(domWriter);
112 BindingStreamEventWriter newRpcWriter(final Class<? extends DataContainer> rpcInputOrOutput,
113 final NormalizedNodeStreamWriter domWriter) {
114 return root.getRpc(rpcInputOrOutput).createWriter(domWriter);
117 BindingStreamEventWriter newNotificationWriter(final Class<? extends Notification> notification,
118 final NormalizedNodeStreamWriter domWriter) {
119 return root.getNotification(notification).createWriter(domWriter);
122 public DataContainerCodecContext<?,?> getCodecContextNode(final InstanceIdentifier<?> binding,
123 final List<YangInstanceIdentifier.PathArgument> builder) {
124 DataContainerCodecContext<?,?> currentNode = root;
125 for (final InstanceIdentifier.PathArgument bindingArg : binding.getPathArguments()) {
126 currentNode = currentNode.bindingPathArgumentChild(bindingArg, builder);
127 Preconditions.checkArgument(currentNode != null, "Supplied Instance Identifier %s is not valid.",binding);
133 * Multi-purpose utility function. Traverse the codec tree, looking for
134 * the appropriate codec for the specified {@link YangInstanceIdentifier}.
135 * As a side-effect, gather all traversed binding {@link InstanceIdentifier.PathArgument}s
136 * into the supplied collection.
138 * @param dom {@link YangInstanceIdentifier} which is to be translated
139 * @param bindingArguments Collection for traversed path arguments
140 * @return Codec for target node, or @null if the node does not have a
141 * binding representation (choice, case, leaf).
144 @Nullable NodeCodecContext<?> getCodecContextNode(final @Nonnull YangInstanceIdentifier dom,
145 final @Nullable Collection<InstanceIdentifier.PathArgument> bindingArguments) {
146 NodeCodecContext<?> currentNode = root;
147 ListNodeCodecContext<?> currentList = null;
149 for (final YangInstanceIdentifier.PathArgument domArg : dom.getPathArguments()) {
150 Preconditions.checkArgument(currentNode instanceof DataContainerCodecContext<?,?>, "Unexpected child of non-container node %s", currentNode);
151 final DataContainerCodecContext<?,?> previous = (DataContainerCodecContext<?,?>) currentNode;
152 final NodeCodecContext<?> nextNode = previous.yangPathArgumentChild(domArg);
155 * List representation in YANG Instance Identifier consists of two
156 * arguments: first is list as a whole, second is list as an item so
157 * if it is /list it means list as whole, if it is /list/list - it
158 * is wildcarded and if it is /list/list[key] it is concrete item,
159 * all this variations are expressed in Binding Aware Instance
160 * Identifier as Item or IdentifiableItem
162 if (currentList != null) {
163 Preconditions.checkArgument(currentList == nextNode, "List should be referenced two times in YANG Instance Identifier %s", dom);
165 // We entered list, so now we have all information to emit
166 // list path using second list argument.
167 if (bindingArguments != null) {
168 bindingArguments.add(currentList.getBindingPathArgument(domArg));
171 currentNode = nextNode;
172 } else if (nextNode instanceof ListNodeCodecContext) {
173 // We enter list, we do not update current Node yet,
174 // since we need to verify
175 currentList = (ListNodeCodecContext<?>) nextNode;
176 } else if (nextNode instanceof ChoiceNodeCodecContext) {
177 // We do not add path argument for choice, since
178 // it is not supported by binding instance identifier.
179 currentNode = nextNode;
180 } else if (nextNode instanceof DataContainerCodecContext<?,?>) {
181 if (bindingArguments != null) {
182 bindingArguments.add(((DataContainerCodecContext<?,?>) nextNode).getBindingPathArgument(domArg));
184 currentNode = nextNode;
185 } else if (nextNode instanceof LeafNodeCodecContext) {
186 LOG.debug("Instance identifier referencing a leaf is not representable (%s)", dom);
191 // Algorithm ended in list as whole representation
192 // we sill need to emit identifier for list
193 if (currentNode instanceof ChoiceNodeCodecContext) {
194 LOG.debug("Instance identifier targeting a choice is not representable (%s)", dom);
197 if (currentNode instanceof CaseNodeCodecContext) {
198 LOG.debug("Instance identifier targeting a case is not representable (%s)", dom);
202 if (currentList != null) {
203 if (bindingArguments != null) {
204 bindingArguments.add(currentList.getBindingPathArgument(null));
211 NotificationCodecContext<?> getNotificationContext(final SchemaPath notification) {
212 return root.getNotification(notification);
215 ContainerNodeCodecContext<?> getRpcDataContext(final SchemaPath path) {
216 return root.getRpc(path);
220 public ImmutableMap<String, LeafNodeCodecContext<?>> getLeafNodes(final Class<?> parentClass,
221 final DataNodeContainer childSchema) {
222 final Map<String, DataSchemaNode> getterToLeafSchema = new HashMap<>();
223 for (final DataSchemaNode leaf : childSchema.getChildNodes()) {
224 final TypeDefinition<?> typeDef;
225 if (leaf instanceof LeafSchemaNode) {
226 typeDef = ((LeafSchemaNode) leaf).getType();
227 } else if (leaf instanceof LeafListSchemaNode) {
228 typeDef = ((LeafListSchemaNode) leaf).getType();
233 final String getterName = getGetterName(leaf.getQName(), typeDef);
234 getterToLeafSchema.put(getterName, leaf);
236 return getLeafNodesUsingReflection(parentClass, getterToLeafSchema);
239 private static String getGetterName(final QName qName, TypeDefinition<?> typeDef) {
240 final String suffix = BindingMapping.getGetterSuffix(qName);
241 while (typeDef.getBaseType() != null) {
242 typeDef = typeDef.getBaseType();
244 if (typeDef instanceof BooleanTypeDefinition || typeDef instanceof EmptyTypeDefinition) {
245 return "is" + suffix;
247 return "get" + suffix;
250 private ImmutableMap<String, LeafNodeCodecContext<?>> getLeafNodesUsingReflection(final Class<?> parentClass,
251 final Map<String, DataSchemaNode> getterToLeafSchema) {
252 final Map<String, LeafNodeCodecContext<?>> leaves = new HashMap<>();
253 for (final Method method : parentClass.getMethods()) {
254 if (method.getParameterTypes().length == 0) {
255 final DataSchemaNode schema = getterToLeafSchema.get(method.getName());
256 final Class<?> valueType;
257 if (schema instanceof LeafSchemaNode) {
258 valueType = method.getReturnType();
259 } else if (schema instanceof LeafListSchemaNode) {
260 final Type genericType = ClassLoaderUtils.getFirstGenericParameter(method.getGenericReturnType());
262 if (genericType instanceof Class<?>) {
263 valueType = (Class<?>) genericType;
264 } else if (genericType instanceof ParameterizedType) {
265 valueType = (Class<?>) ((ParameterizedType) genericType).getRawType();
267 throw new IllegalStateException("Unexpected return type " + genericType);
270 continue; // We do not have schema for leaf, so we will ignore it (eg. getClass, getImplementedInterface).
272 final Codec<Object, Object> codec = getCodec(valueType, schema);
273 final LeafNodeCodecContext<?> leafNode = new LeafNodeCodecContext<>(schema, codec, method,
274 context.getSchemaContext());
275 leaves.put(schema.getQName().getLocalName(), leafNode);
278 return ImmutableMap.copyOf(leaves);
281 private Codec<Object, Object> getCodec(final Class<?> valueType, final DataSchemaNode schema) {
282 final TypeDefinition<?> instantiatedType;
283 if (schema instanceof LeafSchemaNode) {
284 instantiatedType = ((LeafSchemaNode) schema).getType();
285 } else if (schema instanceof LeafListSchemaNode) {
286 instantiatedType = ((LeafListSchemaNode) schema).getType();
288 throw new IllegalArgumentException("Unsupported leaf node type " + schema.getClass());
290 return getCodec(valueType, instantiatedType);
293 Codec<Object, Object> getCodec(final Class<?> valueType, final TypeDefinition<?> instantiatedType) {
294 if (Class.class.equals(valueType)) {
295 @SuppressWarnings({ "unchecked", "rawtypes" })
296 final Codec<Object, Object> casted = (Codec) identityCodec;
298 } else if (InstanceIdentifier.class.equals(valueType)) {
299 @SuppressWarnings({ "unchecked", "rawtypes" })
300 final Codec<Object, Object> casted = (Codec) instanceIdentifierCodec;
302 } else if (Boolean.class.equals(valueType)) {
303 if (instantiatedType instanceof EmptyTypeDefinition) {
304 return ValueTypeCodec.EMPTY_CODEC;
306 } else if (BindingReflections.isBindingClass(valueType)) {
307 return getCodecForBindingClass(valueType, instantiatedType);
309 return ValueTypeCodec.NOOP_CODEC;
312 private Codec<Object, Object> getCodecForBindingClass(final Class<?> valueType, final TypeDefinition<?> instantiatedType) {
313 @SuppressWarnings("rawtypes")
314 TypeDefinition rootType = instantiatedType;
315 while (rootType.getBaseType() != null) {
316 rootType = rootType.getBaseType();
318 if (rootType instanceof IdentityrefTypeDefinition) {
319 return ValueTypeCodec.encapsulatedValueCodecFor(valueType, identityCodec);
320 } else if (rootType instanceof InstanceIdentifierTypeDefinition) {
321 return ValueTypeCodec.encapsulatedValueCodecFor(valueType, instanceIdentifierCodec);
322 } else if (rootType instanceof UnionTypeDefinition) {
323 final Callable<UnionTypeCodec> loader = UnionTypeCodec.loader(valueType, (UnionTypeDefinition) rootType, this);
325 return loader.call();
326 } catch (final Exception e) {
327 throw new IllegalStateException("Unable to load codec for " + valueType, e);
329 } else if (rootType instanceof LeafrefTypeDefinition) {
330 final Entry<GeneratedType, Object> typeWithSchema = context.getTypeWithSchema(valueType);
331 final Object schema = typeWithSchema.getValue();
332 Preconditions.checkState(schema instanceof TypeDefinition<?>);
333 return getCodec(valueType, (TypeDefinition<?>) schema);
335 return ValueTypeCodec.getCodecFor(valueType, instantiatedType);
339 public Codec<NodeIdentifierWithPredicates, IdentifiableItem<?, ?>> getPathArgumentCodec(final Class<?> listClz,
340 final ListSchemaNode schema) {
341 final Class<? extends Identifier<?>> identifier = ClassLoaderUtils.findFirstGenericArgument(listClz,
343 final Map<QName, ValueContext> valueCtx = new HashMap<>();
344 for (final LeafNodeCodecContext<?> leaf : getLeafNodes(identifier, schema).values()) {
345 final QName name = leaf.getDomPathArgument().getNodeType();
346 valueCtx.put(name, new ValueContext(identifier, leaf));
348 return new IdentifiableItemCodec(schema, identifier, listClz, valueCtx);
351 @SuppressWarnings("unchecked")
353 public <T extends DataObject> BindingCodecTreeNode<T> getSubtreeCodec(final InstanceIdentifier<T> path) {
354 // TODO Do we need defensive check here?
355 return (BindingCodecTreeNode<T>) getCodecContextNode(path, null);
359 public BindingCodecTreeNode<?> getSubtreeCodec(final YangInstanceIdentifier path) {
360 return getCodecContextNode(path, null);
364 public BindingCodecTreeNode<?> getSubtreeCodec(final SchemaPath path) {
365 throw new UnsupportedOperationException("Not implemented yet.");