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 static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static java.util.Objects.requireNonNull;
14 import com.google.common.collect.ImmutableMap;
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.Collection;
20 import java.util.HashMap;
21 import java.util.LinkedList;
22 import java.util.List;
24 import java.util.Map.Entry;
25 import java.util.concurrent.Callable;
26 import org.eclipse.jdt.annotation.NonNull;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.opendaylight.mdsal.binding.dom.codec.api.BindingCodecTree;
29 import org.opendaylight.mdsal.binding.dom.codec.api.BindingCodecTreeNode;
30 import org.opendaylight.mdsal.binding.dom.codec.impl.NodeCodecContext.CodecContextFactory;
31 import org.opendaylight.mdsal.binding.dom.codec.util.BindingSchemaMapping;
32 import org.opendaylight.mdsal.binding.generator.util.BindingRuntimeContext;
33 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
34 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
35 import org.opendaylight.yangtools.concepts.Codec;
36 import org.opendaylight.yangtools.concepts.Immutable;
37 import org.opendaylight.yangtools.util.ClassLoaderUtils;
38 import org.opendaylight.yangtools.yang.binding.Action;
39 import org.opendaylight.yangtools.yang.binding.BindingStreamEventWriter;
40 import org.opendaylight.yangtools.yang.binding.DataContainer;
41 import org.opendaylight.yangtools.yang.binding.DataObject;
42 import org.opendaylight.yangtools.yang.binding.DataObjectSerializer;
43 import org.opendaylight.yangtools.yang.binding.Identifiable;
44 import org.opendaylight.yangtools.yang.binding.Identifier;
45 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
46 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.IdentifiableItem;
47 import org.opendaylight.yangtools.yang.binding.Notification;
48 import org.opendaylight.yangtools.yang.common.QName;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
50 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
51 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
52 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
53 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
55 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
59 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
60 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
62 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
63 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
64 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
65 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
69 final class BindingCodecContext implements CodecContextFactory, BindingCodecTree, Immutable {
70 private static final Logger LOG = LoggerFactory.getLogger(BindingCodecContext.class);
72 private final Codec<YangInstanceIdentifier, InstanceIdentifier<?>> instanceIdentifierCodec;
73 private final Codec<QName, Class<?>> identityCodec;
74 private final BindingNormalizedNodeCodecRegistry registry;
75 private final BindingRuntimeContext context;
76 private final SchemaRootCodecContext<?> root;
78 BindingCodecContext(final BindingRuntimeContext context, final BindingNormalizedNodeCodecRegistry registry) {
79 this.context = requireNonNull(context, "Binding Runtime Context is required.");
80 this.root = SchemaRootCodecContext.create(this);
81 this.identityCodec = new IdentityCodec(context);
82 this.instanceIdentifierCodec = new InstanceIdentifierCodec(this);
83 this.registry = requireNonNull(registry);
87 public BindingRuntimeContext getRuntimeContext() {
91 Codec<YangInstanceIdentifier, InstanceIdentifier<?>> getInstanceIdentifierCodec() {
92 return instanceIdentifierCodec;
95 public Codec<QName, Class<?>> getIdentityCodec() {
99 @SuppressWarnings({"rawtypes", "unchecked"})
101 public DataObjectSerializer getEventStreamSerializer(final Class<?> type) {
102 return registry.getSerializer((Class) type);
105 public Entry<YangInstanceIdentifier, BindingStreamEventWriter> newWriter(final InstanceIdentifier<?> path,
106 final NormalizedNodeStreamWriter domWriter) {
107 final List<YangInstanceIdentifier.PathArgument> yangArgs = new LinkedList<>();
108 final DataContainerCodecContext<?,?> codecContext = getCodecContextNode(path, yangArgs);
109 return new SimpleEntry<>(YangInstanceIdentifier.create(yangArgs), codecContext.createWriter(domWriter));
112 public BindingStreamEventWriter newWriterWithoutIdentifier(final InstanceIdentifier<?> path,
113 final NormalizedNodeStreamWriter domWriter) {
114 return getCodecContextNode(path, null).createWriter(domWriter);
117 BindingStreamEventWriter newRpcWriter(final Class<? extends DataContainer> rpcInputOrOutput,
118 final NormalizedNodeStreamWriter domWriter) {
119 return root.getRpc(rpcInputOrOutput).createWriter(domWriter);
122 BindingStreamEventWriter newNotificationWriter(final Class<? extends Notification> notification,
123 final NormalizedNodeStreamWriter domWriter) {
124 return root.getNotification(notification).createWriter(domWriter);
127 public DataContainerCodecContext<?,?> getCodecContextNode(final InstanceIdentifier<?> binding,
128 final List<YangInstanceIdentifier.PathArgument> builder) {
129 DataContainerCodecContext<?,?> currentNode = root;
130 for (final InstanceIdentifier.PathArgument bindingArg : binding.getPathArguments()) {
131 currentNode = currentNode.bindingPathArgumentChild(bindingArg, builder);
132 checkArgument(currentNode != null, "Supplied Instance Identifier %s is not valid.", binding);
138 * Multi-purpose utility function. Traverse the codec tree, looking for
139 * the appropriate codec for the specified {@link YangInstanceIdentifier}.
140 * As a side-effect, gather all traversed binding {@link InstanceIdentifier.PathArgument}s
141 * into the supplied collection.
143 * @param dom {@link YangInstanceIdentifier} which is to be translated
144 * @param bindingArguments Collection for traversed path arguments
145 * @return Codec for target node, or @null if the node does not have a
146 * binding representation (choice, case, leaf).
149 @Nullable NodeCodecContext<?> getCodecContextNode(final @NonNull YangInstanceIdentifier dom,
150 final @Nullable Collection<InstanceIdentifier.PathArgument> bindingArguments) {
151 NodeCodecContext<?> currentNode = root;
152 ListNodeCodecContext<?> currentList = null;
154 for (final YangInstanceIdentifier.PathArgument domArg : dom.getPathArguments()) {
155 checkArgument(currentNode instanceof DataContainerCodecContext,
156 "Unexpected child of non-container node %s", currentNode);
157 final DataContainerCodecContext<?,?> previous = (DataContainerCodecContext<?, ?>) currentNode;
158 final NodeCodecContext<?> nextNode = previous.yangPathArgumentChild(domArg);
161 * List representation in YANG Instance Identifier consists of two
162 * arguments: first is list as a whole, second is list as an item so
163 * if it is /list it means list as whole, if it is /list/list - it
164 * is wildcarded and if it is /list/list[key] it is concrete item,
165 * all this variations are expressed in Binding Aware Instance
166 * Identifier as Item or IdentifiableItem
168 if (currentList != null) {
169 checkArgument(currentList == nextNode,
170 "List should be referenced two times in YANG Instance Identifier %s", dom);
172 // We entered list, so now we have all information to emit
173 // list path using second list argument.
174 if (bindingArguments != null) {
175 bindingArguments.add(currentList.getBindingPathArgument(domArg));
178 currentNode = nextNode;
179 } else if (nextNode instanceof ListNodeCodecContext) {
180 // We enter list, we do not update current Node yet,
181 // since we need to verify
182 currentList = (ListNodeCodecContext<?>) nextNode;
183 } else if (nextNode instanceof ChoiceNodeCodecContext) {
184 // We do not add path argument for choice, since
185 // it is not supported by binding instance identifier.
186 currentNode = nextNode;
187 } else if (nextNode instanceof DataContainerCodecContext) {
188 if (bindingArguments != null) {
189 bindingArguments.add(((DataContainerCodecContext<?, ?>) nextNode).getBindingPathArgument(domArg));
191 currentNode = nextNode;
192 } else if (nextNode instanceof LeafNodeCodecContext) {
193 LOG.debug("Instance identifier referencing a leaf is not representable ({})", dom);
198 // Algorithm ended in list as whole representation
199 // we sill need to emit identifier for list
200 if (currentNode instanceof ChoiceNodeCodecContext) {
201 LOG.debug("Instance identifier targeting a choice is not representable ({})", dom);
204 if (currentNode instanceof CaseNodeCodecContext) {
205 LOG.debug("Instance identifier targeting a case is not representable ({})", dom);
209 if (currentList != null) {
210 if (bindingArguments != null) {
211 bindingArguments.add(currentList.getBindingPathArgument(null));
218 NotificationCodecContext<?> getNotificationContext(final SchemaPath notification) {
219 return root.getNotification(notification);
222 RpcInputCodec<?> getRpcInputCodec(final SchemaPath path) {
223 return root.getRpc(path);
226 ActionCodecContext getActionCodec(final Class<? extends Action<?, ?, ?>> action) {
227 return root.getAction(action);
231 public ImmutableMap<String, LeafNodeCodecContext<?>> getLeafNodes(final Class<?> parentClass,
232 final DataNodeContainer childSchema) {
233 final Map<String, DataSchemaNode> getterToLeafSchema = new HashMap<>();
234 for (final DataSchemaNode leaf : childSchema.getChildNodes()) {
235 if (leaf instanceof TypedDataSchemaNode) {
236 getterToLeafSchema.put(BindingSchemaMapping.getGetterMethodName((TypedDataSchemaNode) leaf), leaf);
239 return getLeafNodesUsingReflection(parentClass, getterToLeafSchema);
242 private ImmutableMap<String, LeafNodeCodecContext<?>> getLeafNodesUsingReflection(final Class<?> parentClass,
243 final Map<String, DataSchemaNode> getterToLeafSchema) {
244 final Map<String, LeafNodeCodecContext<?>> leaves = new HashMap<>();
245 for (final Method method : parentClass.getMethods()) {
246 if (method.getParameterTypes().length == 0) {
247 final DataSchemaNode schema = getterToLeafSchema.get(method.getName());
248 final Class<?> valueType;
249 if (schema instanceof LeafSchemaNode) {
250 valueType = method.getReturnType();
251 } else if (schema instanceof LeafListSchemaNode) {
252 final Type genericType = ClassLoaderUtils.getFirstGenericParameter(method.getGenericReturnType());
254 if (genericType instanceof Class<?>) {
255 valueType = (Class<?>) genericType;
256 } else if (genericType instanceof ParameterizedType) {
257 valueType = (Class<?>) ((ParameterizedType) genericType).getRawType();
259 throw new IllegalStateException("Unexpected return type " + genericType);
262 // We do not have schema for leaf, so we will ignore it (eg. getClass, getImplementedInterface).
265 final Codec<Object, Object> codec = getCodec(valueType, schema);
266 final LeafNodeCodecContext<?> leafNode = new LeafNodeCodecContext<>(schema, codec, method,
267 context.getSchemaContext());
268 leaves.put(schema.getQName().getLocalName(), leafNode);
271 return ImmutableMap.copyOf(leaves);
274 private Codec<Object, Object> getCodec(final Class<?> valueType, final DataSchemaNode schema) {
275 checkArgument(schema instanceof TypedDataSchemaNode, "Unsupported leaf node type %s", schema);
276 return getCodec(valueType, ((TypedDataSchemaNode)schema).getType());
279 Codec<Object, Object> getCodec(final Class<?> valueType, final TypeDefinition<?> instantiatedType) {
280 if (Class.class.equals(valueType)) {
281 @SuppressWarnings({ "unchecked", "rawtypes" })
282 final Codec<Object, Object> casted = (Codec) identityCodec;
284 } else if (InstanceIdentifier.class.equals(valueType)) {
285 @SuppressWarnings({ "unchecked", "rawtypes" })
286 final Codec<Object, Object> casted = (Codec) instanceIdentifierCodec;
288 } else if (Boolean.class.equals(valueType)) {
289 if (instantiatedType instanceof EmptyTypeDefinition) {
290 return ValueTypeCodec.EMPTY_CODEC;
292 } else if (BindingReflections.isBindingClass(valueType)) {
293 return getCodecForBindingClass(valueType, instantiatedType);
295 return ValueTypeCodec.NOOP_CODEC;
298 @SuppressWarnings("checkstyle:illegalCatch")
299 private Codec<Object, Object> getCodecForBindingClass(final Class<?> valueType, final TypeDefinition<?> typeDef) {
300 if (typeDef instanceof IdentityrefTypeDefinition) {
301 return ValueTypeCodec.encapsulatedValueCodecFor(valueType, typeDef, identityCodec);
302 } else if (typeDef instanceof InstanceIdentifierTypeDefinition) {
303 return ValueTypeCodec.encapsulatedValueCodecFor(valueType, typeDef, instanceIdentifierCodec);
304 } else if (typeDef instanceof UnionTypeDefinition) {
305 final Callable<UnionTypeCodec> loader = UnionTypeCodec.loader(valueType, (UnionTypeDefinition) typeDef,
308 return loader.call();
309 } catch (final Exception e) {
310 throw new IllegalStateException("Unable to load codec for " + valueType, e);
312 } else if (typeDef instanceof LeafrefTypeDefinition) {
313 final Entry<GeneratedType, WithStatus> typeWithSchema = context.getTypeWithSchema(valueType);
314 final WithStatus schema = typeWithSchema.getValue();
315 checkState(schema instanceof TypeDefinition);
316 return getCodec(valueType, (TypeDefinition<?>) schema);
318 return ValueTypeCodec.getCodecFor(valueType, typeDef);
322 public Codec<NodeIdentifierWithPredicates, IdentifiableItem<?, ?>> getPathArgumentCodec(final Class<?> listClz,
323 final ListSchemaNode schema) {
324 final Class<? extends Identifier<?>> identifier = ClassLoaderUtils.findFirstGenericArgument(listClz,
326 final Map<QName, ValueContext> valueCtx = new HashMap<>();
327 for (final LeafNodeCodecContext<?> leaf : getLeafNodes(identifier, schema).values()) {
328 final QName name = leaf.getDomPathArgument().getNodeType();
329 valueCtx.put(name, new ValueContext(identifier, leaf));
331 return new IdentifiableItemCodec(schema, identifier, listClz, valueCtx);
334 @SuppressWarnings("unchecked")
336 public <T extends DataObject> BindingCodecTreeNode<T> getSubtreeCodec(final InstanceIdentifier<T> path) {
337 // TODO Do we need defensive check here?
338 return (BindingCodecTreeNode<T>) getCodecContextNode(path, null);
342 public BindingCodecTreeNode<?> getSubtreeCodec(final YangInstanceIdentifier path) {
343 return getCodecContextNode(path, null);
347 public BindingCodecTreeNode<?> getSubtreeCodec(final SchemaPath path) {
348 throw new UnsupportedOperationException("Not implemented yet.");