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);
66 static final String GETTER_PREFIX = "get";
68 private final Codec<YangInstanceIdentifier, InstanceIdentifier<?>> instanceIdentifierCodec;
69 private final Codec<QName, Class<?>> identityCodec;
70 private final BindingNormalizedNodeCodecRegistry registry;
71 private final BindingRuntimeContext context;
72 private final SchemaRootCodecContext<?> root;
74 BindingCodecContext(final BindingRuntimeContext context, final BindingNormalizedNodeCodecRegistry registry) {
75 this.context = Preconditions.checkNotNull(context, "Binding Runtime Context is required.");
76 this.root = SchemaRootCodecContext.create(this);
77 this.identityCodec = new IdentityCodec(context);
78 this.instanceIdentifierCodec = new InstanceIdentifierCodec(this);
79 this.registry = Preconditions.checkNotNull(registry);
83 public BindingRuntimeContext getRuntimeContext() {
87 Codec<YangInstanceIdentifier, InstanceIdentifier<?>> getInstanceIdentifierCodec() {
88 return instanceIdentifierCodec;
91 public Codec<QName, Class<?>> getIdentityCodec() {
95 @SuppressWarnings({"rawtypes", "unchecked"})
97 public DataObjectSerializer getEventStreamSerializer(final Class<?> type) {
98 return registry.getSerializer((Class) type);
101 public Entry<YangInstanceIdentifier, BindingStreamEventWriter> newWriter(final InstanceIdentifier<?> path,
102 final NormalizedNodeStreamWriter domWriter) {
103 final List<YangInstanceIdentifier.PathArgument> yangArgs = new LinkedList<>();
104 final DataContainerCodecContext<?,?> codecContext = getCodecContextNode(path, yangArgs);
105 return new SimpleEntry<>(YangInstanceIdentifier.create(yangArgs), codecContext.createWriter(domWriter));
108 public BindingStreamEventWriter newWriterWithoutIdentifier(final InstanceIdentifier<?> path,
109 final NormalizedNodeStreamWriter domWriter) {
110 return getCodecContextNode(path, null).createWriter(domWriter);
113 BindingStreamEventWriter newRpcWriter(final Class<? extends DataContainer> rpcInputOrOutput,
114 final NormalizedNodeStreamWriter domWriter) {
115 return root.getRpc(rpcInputOrOutput).createWriter(domWriter);
118 BindingStreamEventWriter newNotificationWriter(final Class<? extends Notification> notification,
119 final NormalizedNodeStreamWriter domWriter) {
120 return root.getNotification(notification).createWriter(domWriter);
123 public DataContainerCodecContext<?,?> getCodecContextNode(final InstanceIdentifier<?> binding,
124 final List<YangInstanceIdentifier.PathArgument> builder) {
125 DataContainerCodecContext<?,?> currentNode = root;
126 for (final InstanceIdentifier.PathArgument bindingArg : binding.getPathArguments()) {
127 currentNode = currentNode.bindingPathArgumentChild(bindingArg, builder);
128 Preconditions.checkArgument(currentNode != null, "Supplied Instance Identifier %s is not valid.",binding);
134 * Multi-purpose utility function. Traverse the codec tree, looking for
135 * the appropriate codec for the specified {@link YangInstanceIdentifier}.
136 * As a side-effect, gather all traversed binding {@link InstanceIdentifier.PathArgument}s
137 * into the supplied collection.
139 * @param dom {@link YangInstanceIdentifier} which is to be translated
140 * @param bindingArguments Collection for traversed path arguments
141 * @return Codec for target node, or @null if the node does not have a
142 * binding representation (choice, case, leaf).
145 @Nullable NodeCodecContext<?> getCodecContextNode(final @Nonnull YangInstanceIdentifier dom,
146 final @Nullable Collection<InstanceIdentifier.PathArgument> bindingArguments) {
147 NodeCodecContext<?> currentNode = root;
148 ListNodeCodecContext<?> currentList = null;
150 for (final YangInstanceIdentifier.PathArgument domArg : dom.getPathArguments()) {
151 Preconditions.checkArgument(currentNode instanceof DataContainerCodecContext<?,?>, "Unexpected child of non-container node %s", currentNode);
152 final DataContainerCodecContext<?,?> previous = (DataContainerCodecContext<?,?>) currentNode;
153 final NodeCodecContext<?> nextNode = previous.yangPathArgumentChild(domArg);
156 * List representation in YANG Instance Identifier consists of two
157 * arguments: first is list as a whole, second is list as an item so
158 * if it is /list it means list as whole, if it is /list/list - it
159 * is wildcarded and if it is /list/list[key] it is concrete item,
160 * all this variations are expressed in Binding Aware Instance
161 * Identifier as Item or IdentifiableItem
163 if (currentList != null) {
164 Preconditions.checkArgument(currentList == nextNode, "List should be referenced two times in YANG Instance Identifier %s", dom);
166 // We entered list, so now we have all information to emit
167 // list path using second list argument.
168 if (bindingArguments != null) {
169 bindingArguments.add(currentList.getBindingPathArgument(domArg));
172 currentNode = nextNode;
173 } else if (nextNode instanceof ListNodeCodecContext) {
174 // We enter list, we do not update current Node yet,
175 // since we need to verify
176 currentList = (ListNodeCodecContext<?>) nextNode;
177 } else if (nextNode instanceof ChoiceNodeCodecContext) {
178 // We do not add path argument for choice, since
179 // it is not supported by binding instance identifier.
180 currentNode = nextNode;
181 } else if (nextNode instanceof DataContainerCodecContext<?,?>) {
182 if (bindingArguments != null) {
183 bindingArguments.add(((DataContainerCodecContext<?,?>) nextNode).getBindingPathArgument(domArg));
185 currentNode = nextNode;
186 } else if (nextNode instanceof LeafNodeCodecContext) {
187 LOG.debug("Instance identifier referencing a leaf is not representable (%s)", dom);
192 // Algorithm ended in list as whole representation
193 // we sill need to emit identifier for list
194 if (currentNode instanceof ChoiceNodeCodecContext) {
195 LOG.debug("Instance identifier targeting a choice is not representable (%s)", dom);
198 if (currentNode instanceof CaseNodeCodecContext) {
199 LOG.debug("Instance identifier targeting a case is not representable (%s)", dom);
203 if (currentList != null) {
204 if(bindingArguments != null) {
205 bindingArguments.add(currentList.getBindingPathArgument(null));
212 NotificationCodecContext<?> getNotificationContext(final SchemaPath notification) {
213 return root.getNotification(notification);
216 ContainerNodeCodecContext<?> getRpcDataContext(final SchemaPath path) {
217 return root.getRpc(path);
221 public ImmutableMap<String, LeafNodeCodecContext<?>> getLeafNodes(final Class<?> parentClass,
222 final DataNodeContainer childSchema) {
223 final Map<String, DataSchemaNode> getterToLeafSchema = new HashMap<>();
224 for (final DataSchemaNode leaf : childSchema.getChildNodes()) {
225 final TypeDefinition<?> typeDef;
226 if (leaf instanceof LeafSchemaNode) {
227 typeDef = ((LeafSchemaNode) leaf).getType();
228 } else if (leaf instanceof LeafListSchemaNode) {
229 typeDef = ((LeafListSchemaNode) leaf).getType();
234 final String getterName = getGetterName(leaf.getQName(), typeDef);
235 getterToLeafSchema.put(getterName, leaf);
237 return getLeafNodesUsingReflection(parentClass, getterToLeafSchema);
240 private String getGetterName(final QName qName, TypeDefinition<?> typeDef) {
241 final String suffix = BindingMapping.getClassName(qName);
243 while (typeDef.getBaseType() != null) {
244 typeDef = typeDef.getBaseType();
246 if (typeDef instanceof BooleanTypeDefinition || typeDef instanceof EmptyTypeDefinition) {
247 return "is" + suffix;
249 return GETTER_PREFIX + 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 continue; // We do not have schema for leaf, so we will ignore it (eg. getClass, getImplementedInterface).
274 final Codec<Object, Object> codec = getCodec(valueType, schema);
275 final LeafNodeCodecContext<?> leafNode = new LeafNodeCodecContext<>(schema, codec, method,
276 context.getSchemaContext());
277 leaves.put(schema.getQName().getLocalName(), leafNode);
280 return ImmutableMap.copyOf(leaves);
283 private Codec<Object, Object> getCodec(final Class<?> valueType, final DataSchemaNode schema) {
284 final TypeDefinition<?> instantiatedType;
285 if (schema instanceof LeafSchemaNode) {
286 instantiatedType = ((LeafSchemaNode) schema).getType();
287 } else if (schema instanceof LeafListSchemaNode) {
288 instantiatedType = ((LeafListSchemaNode) schema).getType();
290 throw new IllegalArgumentException("Unsupported leaf node type " + schema.getClass());
292 if (Class.class.equals(valueType)) {
293 @SuppressWarnings({ "unchecked", "rawtypes" })
294 final Codec<Object, Object> casted = (Codec) identityCodec;
296 } else if (InstanceIdentifier.class.equals(valueType)) {
297 @SuppressWarnings({ "unchecked", "rawtypes" })
298 final Codec<Object, Object> casted = (Codec) instanceIdentifierCodec;
300 } else if (Boolean.class.equals(valueType)) {
301 if(instantiatedType instanceof EmptyTypeDefinition) {
302 return ValueTypeCodec.EMPTY_CODEC;
304 } else if (BindingReflections.isBindingClass(valueType)) {
305 return getCodec(valueType, instantiatedType);
307 return ValueTypeCodec.NOOP_CODEC;
310 private Codec<Object, Object> getCodec(final Class<?> valueType, final TypeDefinition<?> instantiatedType) {
311 @SuppressWarnings("rawtypes")
312 TypeDefinition rootType = instantiatedType;
313 while (rootType.getBaseType() != null) {
314 rootType = rootType.getBaseType();
316 if (rootType instanceof IdentityrefTypeDefinition) {
317 return ValueTypeCodec.encapsulatedValueCodecFor(valueType, identityCodec);
318 } else if (rootType instanceof InstanceIdentifierTypeDefinition) {
319 return ValueTypeCodec.encapsulatedValueCodecFor(valueType, instanceIdentifierCodec);
320 } else if (rootType instanceof UnionTypeDefinition) {
321 final Callable<UnionTypeCodec> loader = UnionTypeCodec.loader(valueType, (UnionTypeDefinition) rootType);
323 return loader.call();
324 } catch (final Exception e) {
325 throw new IllegalStateException("Unable to load codec for " + valueType, e);
327 } else if(rootType instanceof LeafrefTypeDefinition) {
328 final Entry<GeneratedType, Object> typeWithSchema = context.getTypeWithSchema(valueType);
329 final Object schema = typeWithSchema.getValue();
330 Preconditions.checkState(schema instanceof TypeDefinition<?>);
331 return getCodec(valueType, (TypeDefinition<?>) schema);
333 return ValueTypeCodec.getCodecFor(valueType, instantiatedType);
337 public Codec<NodeIdentifierWithPredicates, IdentifiableItem<?, ?>> getPathArgumentCodec(final Class<?> listClz,
338 final ListSchemaNode schema) {
339 final Class<? extends Identifier<?>> identifier = ClassLoaderUtils.findFirstGenericArgument(listClz,
341 final Map<QName, ValueContext> valueCtx = new HashMap<>();
342 for (final LeafNodeCodecContext<?> leaf : getLeafNodes(identifier, schema).values()) {
343 final QName name = leaf.getDomPathArgument().getNodeType();
344 valueCtx.put(name, new ValueContext(identifier, leaf));
346 return new IdentifiableItemCodec(schema, identifier, listClz, valueCtx);
349 @SuppressWarnings("unchecked")
351 public <T extends DataObject> BindingCodecTreeNode<T> getSubtreeCodec(final InstanceIdentifier<T> path) {
352 // TODO Do we need defensive check here?
353 return (BindingCodecTreeNode<T>) getCodecContextNode(path, null);
357 public BindingCodecTreeNode<?> getSubtreeCodec(final YangInstanceIdentifier path) {
358 return getCodecContextNode(path, null);
362 public BindingCodecTreeNode<?> getSubtreeCodec(final SchemaPath path) {
363 throw new UnsupportedOperationException("Not implemented yet.");