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.mdsal.binding.dom.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 org.eclipse.jdt.annotation.NonNull;
24 import org.eclipse.jdt.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.mdsal.binding.dom.codec.impl.NodeCodecContext.CodecContextFactory;
28 import org.opendaylight.mdsal.binding.generator.util.BindingRuntimeContext;
29 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
30 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
31 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
32 import org.opendaylight.yangtools.concepts.Codec;
33 import org.opendaylight.yangtools.concepts.Immutable;
34 import org.opendaylight.yangtools.util.ClassLoaderUtils;
35 import org.opendaylight.yangtools.yang.binding.Action;
36 import org.opendaylight.yangtools.yang.binding.BindingStreamEventWriter;
37 import org.opendaylight.yangtools.yang.binding.DataContainer;
38 import org.opendaylight.yangtools.yang.binding.DataObject;
39 import org.opendaylight.yangtools.yang.binding.DataObjectSerializer;
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.Notification;
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.DocumentedNode.WithStatus;
52 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
55 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
57 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
58 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
60 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
61 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
62 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
63 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
64 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
65 import org.slf4j.Logger;
66 import org.slf4j.LoggerFactory;
68 final class BindingCodecContext implements CodecContextFactory, BindingCodecTree, Immutable {
69 private static final Logger LOG = LoggerFactory.getLogger(BindingCodecContext.class);
71 private final Codec<YangInstanceIdentifier, InstanceIdentifier<?>> instanceIdentifierCodec;
72 private final Codec<QName, Class<?>> identityCodec;
73 private final BindingNormalizedNodeCodecRegistry registry;
74 private final BindingRuntimeContext context;
75 private final SchemaRootCodecContext<?> root;
77 BindingCodecContext(final BindingRuntimeContext context, final BindingNormalizedNodeCodecRegistry registry) {
78 this.context = Preconditions.checkNotNull(context, "Binding Runtime Context is required.");
79 this.root = SchemaRootCodecContext.create(this);
80 this.identityCodec = new IdentityCodec(context);
81 this.instanceIdentifierCodec = new InstanceIdentifierCodec(this);
82 this.registry = Preconditions.checkNotNull(registry);
86 public BindingRuntimeContext getRuntimeContext() {
90 Codec<YangInstanceIdentifier, InstanceIdentifier<?>> getInstanceIdentifierCodec() {
91 return instanceIdentifierCodec;
94 public Codec<QName, Class<?>> getIdentityCodec() {
98 @SuppressWarnings({"rawtypes", "unchecked"})
100 public DataObjectSerializer getEventStreamSerializer(final Class<?> type) {
101 return registry.getSerializer((Class) type);
104 public Entry<YangInstanceIdentifier, BindingStreamEventWriter> newWriter(final InstanceIdentifier<?> path,
105 final NormalizedNodeStreamWriter domWriter) {
106 final List<YangInstanceIdentifier.PathArgument> yangArgs = new LinkedList<>();
107 final DataContainerCodecContext<?,?> codecContext = getCodecContextNode(path, yangArgs);
108 return new SimpleEntry<>(YangInstanceIdentifier.create(yangArgs), codecContext.createWriter(domWriter));
111 public BindingStreamEventWriter newWriterWithoutIdentifier(final InstanceIdentifier<?> path,
112 final NormalizedNodeStreamWriter domWriter) {
113 return getCodecContextNode(path, null).createWriter(domWriter);
116 BindingStreamEventWriter newRpcWriter(final Class<? extends DataContainer> rpcInputOrOutput,
117 final NormalizedNodeStreamWriter domWriter) {
118 return root.getRpc(rpcInputOrOutput).createWriter(domWriter);
121 BindingStreamEventWriter newNotificationWriter(final Class<? extends Notification> notification,
122 final NormalizedNodeStreamWriter domWriter) {
123 return root.getNotification(notification).createWriter(domWriter);
126 public DataContainerCodecContext<?,?> getCodecContextNode(final InstanceIdentifier<?> binding,
127 final List<YangInstanceIdentifier.PathArgument> builder) {
128 DataContainerCodecContext<?,?> currentNode = root;
129 for (final InstanceIdentifier.PathArgument bindingArg : binding.getPathArguments()) {
130 currentNode = currentNode.bindingPathArgumentChild(bindingArg, builder);
131 Preconditions.checkArgument(currentNode != null, "Supplied Instance Identifier %s is not valid.", binding);
137 * Multi-purpose utility function. Traverse the codec tree, looking for
138 * the appropriate codec for the specified {@link YangInstanceIdentifier}.
139 * As a side-effect, gather all traversed binding {@link InstanceIdentifier.PathArgument}s
140 * into the supplied collection.
142 * @param dom {@link YangInstanceIdentifier} which is to be translated
143 * @param bindingArguments Collection for traversed path arguments
144 * @return Codec for target node, or @null if the node does not have a
145 * binding representation (choice, case, leaf).
148 @Nullable NodeCodecContext<?> getCodecContextNode(final @NonNull YangInstanceIdentifier dom,
149 final @Nullable Collection<InstanceIdentifier.PathArgument> bindingArguments) {
150 NodeCodecContext<?> currentNode = root;
151 ListNodeCodecContext<?> currentList = null;
153 for (final YangInstanceIdentifier.PathArgument domArg : dom.getPathArguments()) {
154 Preconditions.checkArgument(currentNode instanceof DataContainerCodecContext<?,?>,
155 "Unexpected child of non-container node %s", currentNode);
156 final DataContainerCodecContext<?,?> previous = (DataContainerCodecContext<?,?>) currentNode;
157 final NodeCodecContext<?> nextNode = previous.yangPathArgumentChild(domArg);
160 * List representation in YANG Instance Identifier consists of two
161 * arguments: first is list as a whole, second is list as an item so
162 * if it is /list it means list as whole, if it is /list/list - it
163 * is wildcarded and if it is /list/list[key] it is concrete item,
164 * all this variations are expressed in Binding Aware Instance
165 * Identifier as Item or IdentifiableItem
167 if (currentList != null) {
168 Preconditions.checkArgument(currentList == nextNode,
169 "List should be referenced two times in YANG Instance Identifier %s", dom);
171 // We entered list, so now we have all information to emit
172 // list path using second list argument.
173 if (bindingArguments != null) {
174 bindingArguments.add(currentList.getBindingPathArgument(domArg));
177 currentNode = nextNode;
178 } else if (nextNode instanceof ListNodeCodecContext) {
179 // We enter list, we do not update current Node yet,
180 // since we need to verify
181 currentList = (ListNodeCodecContext<?>) nextNode;
182 } else if (nextNode instanceof ChoiceNodeCodecContext) {
183 // We do not add path argument for choice, since
184 // it is not supported by binding instance identifier.
185 currentNode = nextNode;
186 } else if (nextNode instanceof DataContainerCodecContext<?,?>) {
187 if (bindingArguments != null) {
188 bindingArguments.add(((DataContainerCodecContext<?,?>) nextNode).getBindingPathArgument(domArg));
190 currentNode = nextNode;
191 } else if (nextNode instanceof LeafNodeCodecContext) {
192 LOG.debug("Instance identifier referencing a leaf is not representable (%s)", dom);
197 // Algorithm ended in list as whole representation
198 // we sill need to emit identifier for list
199 if (currentNode instanceof ChoiceNodeCodecContext) {
200 LOG.debug("Instance identifier targeting a choice is not representable (%s)", dom);
203 if (currentNode instanceof CaseNodeCodecContext) {
204 LOG.debug("Instance identifier targeting a case is not representable (%s)", dom);
208 if (currentList != null) {
209 if (bindingArguments != null) {
210 bindingArguments.add(currentList.getBindingPathArgument(null));
217 NotificationCodecContext<?> getNotificationContext(final SchemaPath notification) {
218 return root.getNotification(notification);
221 RpcInputCodec<?> getRpcInputCodec(final SchemaPath path) {
222 return root.getRpc(path);
225 ActionCodecContext getActionCodec(final Class<? extends Action<?, ?, ?>> action) {
226 return root.getAction(action);
230 public ImmutableMap<String, LeafNodeCodecContext<?>> getLeafNodes(final Class<?> parentClass,
231 final DataNodeContainer childSchema) {
232 final Map<String, DataSchemaNode> getterToLeafSchema = new HashMap<>();
233 for (final DataSchemaNode leaf : childSchema.getChildNodes()) {
234 if (leaf instanceof TypedDataSchemaNode) {
235 getterToLeafSchema.put(getGetterName(leaf, ((TypedDataSchemaNode) leaf).getType()), leaf);
238 return getLeafNodesUsingReflection(parentClass, getterToLeafSchema);
241 private static String getGetterName(final SchemaNode node, final TypeDefinition<?> typeDef) {
242 final String suffix = BindingMapping.getGetterSuffix(node.getQName());
243 // Bug 8903: If it is a derived type of boolean or empty, not an inner type, then the return type
244 // of method would be the generated type of typedef not build-in types, so here it should be 'get'.
245 if ((typeDef instanceof BooleanTypeDefinition || typeDef instanceof EmptyTypeDefinition)
246 && (typeDef.getPath().equals(node.getPath()) || typeDef.getBaseType() == null)) {
247 return "is" + suffix;
249 return "get" + suffix;
252 private ImmutableMap<String, LeafNodeCodecContext<?>> getLeafNodesUsingReflection(final Class<?> parentClass,
253 final Map<String, DataSchemaNode> getterToLeafSchema) {
254 final Map<String, LeafNodeCodecContext<?>> leaves = new HashMap<>();
255 for (final Method method : parentClass.getMethods()) {
256 if (method.getParameterTypes().length == 0) {
257 final DataSchemaNode schema = getterToLeafSchema.get(method.getName());
258 final Class<?> valueType;
259 if (schema instanceof LeafSchemaNode) {
260 valueType = method.getReturnType();
261 } else if (schema instanceof LeafListSchemaNode) {
262 final Type genericType = ClassLoaderUtils.getFirstGenericParameter(method.getGenericReturnType());
264 if (genericType instanceof Class<?>) {
265 valueType = (Class<?>) genericType;
266 } else if (genericType instanceof ParameterizedType) {
267 valueType = (Class<?>) ((ParameterizedType) genericType).getRawType();
269 throw new IllegalStateException("Unexpected return type " + genericType);
272 // We do not have schema for leaf, so we will ignore it (eg. getClass, getImplementedInterface).
275 final Codec<Object, Object> codec = getCodec(valueType, schema);
276 final LeafNodeCodecContext<?> leafNode = new LeafNodeCodecContext<>(schema, codec, method,
277 context.getSchemaContext());
278 leaves.put(schema.getQName().getLocalName(), leafNode);
281 return ImmutableMap.copyOf(leaves);
284 private Codec<Object, Object> getCodec(final Class<?> valueType, final DataSchemaNode schema) {
285 Preconditions.checkArgument(schema instanceof TypedDataSchemaNode, "Unsupported leaf node type %s", schema);
287 return getCodec(valueType, ((TypedDataSchemaNode)schema).getType());
290 Codec<Object, Object> getCodec(final Class<?> valueType, final TypeDefinition<?> instantiatedType) {
291 if (Class.class.equals(valueType)) {
292 @SuppressWarnings({ "unchecked", "rawtypes" })
293 final Codec<Object, Object> casted = (Codec) identityCodec;
295 } else if (InstanceIdentifier.class.equals(valueType)) {
296 @SuppressWarnings({ "unchecked", "rawtypes" })
297 final Codec<Object, Object> casted = (Codec) instanceIdentifierCodec;
299 } else if (Boolean.class.equals(valueType)) {
300 if (instantiatedType instanceof EmptyTypeDefinition) {
301 return ValueTypeCodec.EMPTY_CODEC;
303 } else if (BindingReflections.isBindingClass(valueType)) {
304 return getCodecForBindingClass(valueType, instantiatedType);
306 return ValueTypeCodec.NOOP_CODEC;
309 @SuppressWarnings("checkstyle:illegalCatch")
310 private Codec<Object, Object> getCodecForBindingClass(final Class<?> valueType, final TypeDefinition<?> typeDef) {
311 if (typeDef instanceof IdentityrefTypeDefinition) {
312 return ValueTypeCodec.encapsulatedValueCodecFor(valueType, typeDef, identityCodec);
313 } else if (typeDef instanceof InstanceIdentifierTypeDefinition) {
314 return ValueTypeCodec.encapsulatedValueCodecFor(valueType, typeDef, instanceIdentifierCodec);
315 } else if (typeDef instanceof UnionTypeDefinition) {
316 final Callable<UnionTypeCodec> loader = UnionTypeCodec.loader(valueType, (UnionTypeDefinition) typeDef,
319 return loader.call();
320 } catch (final Exception e) {
321 throw new IllegalStateException("Unable to load codec for " + valueType, e);
323 } else if (typeDef instanceof LeafrefTypeDefinition) {
324 final Entry<GeneratedType, WithStatus> typeWithSchema = context.getTypeWithSchema(valueType);
325 final WithStatus schema = typeWithSchema.getValue();
326 Preconditions.checkState(schema instanceof TypeDefinition<?>);
327 return getCodec(valueType, (TypeDefinition<?>) schema);
329 return ValueTypeCodec.getCodecFor(valueType, typeDef);
333 public Codec<NodeIdentifierWithPredicates, IdentifiableItem<?, ?>> getPathArgumentCodec(final Class<?> listClz,
334 final ListSchemaNode schema) {
335 final Class<? extends Identifier<?>> identifier = ClassLoaderUtils.findFirstGenericArgument(listClz,
337 final Map<QName, ValueContext> valueCtx = new HashMap<>();
338 for (final LeafNodeCodecContext<?> leaf : getLeafNodes(identifier, schema).values()) {
339 final QName name = leaf.getDomPathArgument().getNodeType();
340 valueCtx.put(name, new ValueContext(identifier, leaf));
342 return new IdentifiableItemCodec(schema, identifier, listClz, valueCtx);
345 @SuppressWarnings("unchecked")
347 public <T extends DataObject> BindingCodecTreeNode<T> getSubtreeCodec(final InstanceIdentifier<T> path) {
348 // TODO Do we need defensive check here?
349 return (BindingCodecTreeNode<T>) getCodecContextNode(path, null);
353 public BindingCodecTreeNode<?> getSubtreeCodec(final YangInstanceIdentifier path) {
354 return getCodecContextNode(path, null);
358 public BindingCodecTreeNode<?> getSubtreeCodec(final SchemaPath path) {
359 throw new UnsupportedOperationException("Not implemented yet.");