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 com.google.common.collect.ImmutableSortedMap;
14 import java.lang.reflect.Constructor;
15 import java.lang.reflect.InvocationTargetException;
16 import java.lang.reflect.Method;
17 import java.lang.reflect.ParameterizedType;
18 import java.lang.reflect.Type;
19 import java.util.AbstractMap.SimpleEntry;
20 import java.util.ArrayList;
21 import java.util.HashMap;
22 import java.util.LinkedList;
23 import java.util.List;
25 import java.util.Map.Entry;
26 import java.util.concurrent.Callable;
28 import org.opendaylight.yangtools.binding.data.codec.impl.NodeCodecContext.CodecContextFactory;
29 import org.opendaylight.yangtools.concepts.Codec;
30 import org.opendaylight.yangtools.concepts.Immutable;
31 import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
32 import org.opendaylight.yangtools.util.ClassLoaderUtils;
33 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
34 import org.opendaylight.yangtools.yang.binding.BindingMapping;
35 import org.opendaylight.yangtools.yang.binding.BindingStreamEventWriter;
36 import org.opendaylight.yangtools.yang.binding.Identifiable;
37 import org.opendaylight.yangtools.yang.binding.Identifier;
38 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
39 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.IdentifiableItem;
40 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
41 import org.opendaylight.yangtools.yang.common.QName;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
44 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
45 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
46 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
51 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
52 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
53 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
54 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
56 class BindingCodecContext implements CodecContextFactory, Immutable {
58 private static final String GETTER_PREFIX = "get";
59 private final SchemaRootCodecContext root;
60 private final BindingRuntimeContext context;
61 private final Codec<YangInstanceIdentifier, InstanceIdentifier<?>> instanceIdentifierCodec =
62 new InstanceIdentifierCodec();
63 private final Codec<QName, Class<?>> identityCodec = new IdentityCodec();
65 public BindingCodecContext(final BindingRuntimeContext context) {
66 this.context = Preconditions.checkNotNull(context, "Binding Runtime Context is required.");
67 this.root = SchemaRootCodecContext.create(this);
71 public BindingRuntimeContext getRuntimeContext() {
75 public Codec<YangInstanceIdentifier, InstanceIdentifier<?>> getInstanceIdentifierCodec() {
76 return instanceIdentifierCodec;
79 public Codec<QName, Class<?>> getIdentityCodec() {
83 public Entry<YangInstanceIdentifier, BindingStreamEventWriter> newWriter(final InstanceIdentifier<?> path,
84 final NormalizedNodeStreamWriter domWriter) {
85 LinkedList<YangInstanceIdentifier.PathArgument> yangArgs = new LinkedList<>();
86 DataContainerCodecContext<?> codecContext = getCodecContextNode(path, yangArgs);
87 BindingStreamEventWriter writer = new BindingToNormalizedStreamWriter(codecContext, domWriter);
88 return new SimpleEntry<>(YangInstanceIdentifier.create(yangArgs), writer);
91 public BindingStreamEventWriter newWriterWithoutIdentifier(final InstanceIdentifier<?> path,
92 final NormalizedNodeStreamWriter domWriter) {
93 return new BindingToNormalizedStreamWriter(getCodecContextNode(path, null), domWriter);
96 public DataContainerCodecContext<?> getCodecContextNode(final InstanceIdentifier<?> binding,
97 final List<YangInstanceIdentifier.PathArgument> builder) {
98 DataContainerCodecContext<?> currentNode = root;
99 for (InstanceIdentifier.PathArgument bindingArg : binding.getPathArguments()) {
100 currentNode = currentNode.getIdentifierChild(bindingArg, builder);
105 public NodeCodecContext getCodecContextNode(final YangInstanceIdentifier dom,
106 final List<InstanceIdentifier.PathArgument> builder) {
107 NodeCodecContext currentNode = root;
108 ListNodeCodecContext currentList = null;
109 for (YangInstanceIdentifier.PathArgument domArg : dom.getPathArguments()) {
110 Preconditions.checkArgument(currentNode instanceof DataContainerCodecContext<?>);
111 DataContainerCodecContext<?> previous = (DataContainerCodecContext<?>) currentNode;
112 NodeCodecContext nextNode = previous.getYangIdentifierChild(domArg);
114 * List representation in YANG Instance Identifier consists of two
115 * arguments: first is list as a whole, second is list as an item so
116 * if it is /list it means list as whole, if it is /list/list - it
117 * is wildcarded and if it is /list/list[key] it is concrete item,
118 * all this variations are expressed in Binding Aware Instance
119 * Identifier as Item or IdentifiableItem
121 if (currentList != null) {
123 if (currentList == nextNode) {
125 // We entered list, so now we have all information to emit
127 // path using second list argument.
128 builder.add(currentList.getBindingPathArgument(domArg));
130 currentNode = nextNode;
132 throw new IllegalArgumentException(
133 "List should be referenced two times in YANG Instance Identifier");
135 } else if (nextNode instanceof ListNodeCodecContext) {
136 // We enter list, we do not update current Node yet,
137 // since we need to verify
138 currentList = (ListNodeCodecContext) nextNode;
139 } else if (nextNode instanceof ChoiceNodeCodecContext) {
140 // We do not add path argument for choice, since
141 // it is not supported by binding instance identifier.
142 currentNode = nextNode;
143 } else if (nextNode instanceof DataContainerCodecContext<?>) {
144 builder.add(((DataContainerCodecContext<?>) nextNode).getBindingPathArgument(domArg));
145 currentNode = nextNode;
146 } else if (nextNode instanceof LeafNodeCodecContext) {
147 Preconditions.checkArgument(builder == null, "Instance Identifier for leaf is not representable.");
151 // Algorithm ended in list as whole representation
152 // we sill need to emit identifier for list
154 if (builder != null) {
155 Preconditions.checkArgument(!(currentNode instanceof ChoiceNodeCodecContext),
156 "Instance Identifier for choice is not representable.");
157 Preconditions.checkArgument(!(currentNode instanceof CaseNodeCodecContext),
158 "Instance Identifier for case is not representable.");
160 if (currentList != null) {
161 builder.add(currentList.getBindingPathArgument(null));
168 public ImmutableMap<String, LeafNodeCodecContext> getLeafNodes(final Class<?> parentClass,
169 final DataNodeContainer childSchema) {
170 HashMap<String, DataSchemaNode> getterToLeafSchema = new HashMap<>();
171 for (DataSchemaNode leaf : childSchema.getChildNodes()) {
172 final TypeDefinition<?> typeDef;
173 if (leaf instanceof LeafSchemaNode) {
174 typeDef = ((LeafSchemaNode) leaf).getType();
175 } else if (leaf instanceof LeafListSchemaNode) {
176 typeDef = ((LeafListSchemaNode) leaf).getType();
181 String getterName = getGetterName(leaf.getQName(), typeDef);
182 getterToLeafSchema.put(getterName, leaf);
184 return getLeafNodesUsingReflection(parentClass, getterToLeafSchema);
187 private String getGetterName(final QName qName, TypeDefinition<?> typeDef) {
188 String suffix = BindingMapping.getClassName(qName);
190 while (typeDef.getBaseType() != null) {
191 typeDef = typeDef.getBaseType();
193 if (typeDef instanceof BooleanTypeDefinition) {
194 return "is" + suffix;
196 return GETTER_PREFIX + suffix;
199 private ImmutableMap<String, LeafNodeCodecContext> getLeafNodesUsingReflection(final Class<?> parentClass,
200 final Map<String, DataSchemaNode> getterToLeafSchema) {
201 Map<String, LeafNodeCodecContext> leaves = new HashMap<>();
202 for (Method method : parentClass.getMethods()) {
203 if (method.getParameterTypes().length == 0) {
204 DataSchemaNode schema = getterToLeafSchema.get(method.getName());
205 final Class<?> valueType;
206 if (schema instanceof LeafSchemaNode) {
207 valueType = method.getReturnType();
208 } else if (schema instanceof LeafListSchemaNode) {
209 Type genericType = ClassLoaderUtils.getFirstGenericParameter(method.getGenericReturnType());
211 if (genericType instanceof Class<?>) {
212 valueType = (Class<?>) genericType;
213 } else if (genericType instanceof ParameterizedType) {
214 valueType = (Class<?>) ((ParameterizedType) genericType).getRawType();
216 throw new IllegalStateException("Unexpected return type " + genericType);
219 continue; // We do not have schema for leaf, so we will ignore it (eg. getClass, getImplementedInterface).
221 Codec<Object, Object> codec = getCodec(valueType, schema);
222 final LeafNodeCodecContext leafNode = new LeafNodeCodecContext(schema, codec, method);
223 leaves.put(schema.getQName().getLocalName(), leafNode);
226 return ImmutableMap.copyOf(leaves);
231 private Codec<Object, Object> getCodec(final Class<?> valueType, final DataSchemaNode schema) {
232 if (Class.class.equals(valueType)) {
233 @SuppressWarnings({ "unchecked", "rawtypes" })
234 final Codec<Object, Object> casted = (Codec) identityCodec;
236 } else if (InstanceIdentifier.class.equals(valueType)) {
237 @SuppressWarnings({ "unchecked", "rawtypes" })
238 final Codec<Object, Object> casted = (Codec) instanceIdentifierCodec;
240 } else if (BindingReflections.isBindingClass(valueType)) {
241 final TypeDefinition<?> instantiatedType;
242 if (schema instanceof LeafSchemaNode) {
243 instantiatedType = ((LeafSchemaNode) schema).getType();
244 } else if (schema instanceof LeafListSchemaNode) {
245 instantiatedType = ((LeafListSchemaNode) schema).getType();
247 instantiatedType = null;
249 if (instantiatedType != null) {
250 return getCodec(valueType, instantiatedType);
253 return ValueTypeCodec.NOOP_CODEC;
256 private Codec<Object, Object> getCodec(final Class<?> valueType, final TypeDefinition<?> instantiatedType) {
257 @SuppressWarnings("rawtypes")
258 TypeDefinition rootType = instantiatedType;
259 while (rootType.getBaseType() != null) {
260 rootType = rootType.getBaseType();
262 if (rootType instanceof IdentityrefTypeDefinition) {
263 return ValueTypeCodec.encapsulatedValueCodecFor(valueType, identityCodec);
264 } else if (rootType instanceof InstanceIdentifierTypeDefinition) {
265 return ValueTypeCodec.encapsulatedValueCodecFor(valueType, instanceIdentifierCodec);
266 } else if (rootType instanceof UnionTypeDefinition) {
267 Callable<UnionTypeCodec> loader = UnionTypeCodec.loader(valueType, (UnionTypeDefinition) rootType,
268 getInstanceIdentifierCodec(), getIdentityCodec());
270 return loader.call();
271 } catch (Exception e) {
272 throw new IllegalStateException("Unable to load codec for "+valueType,e);
275 return ValueTypeCodec.getCodecFor(valueType, instantiatedType);
278 private class InstanceIdentifierCodec implements Codec<YangInstanceIdentifier, InstanceIdentifier<?>> {
281 public YangInstanceIdentifier serialize(final InstanceIdentifier<?> input) {
282 List<YangInstanceIdentifier.PathArgument> domArgs = new LinkedList<>();
283 getCodecContextNode(input, domArgs);
284 return YangInstanceIdentifier.create(domArgs);
288 public InstanceIdentifier<?> deserialize(final YangInstanceIdentifier input) {
289 List<InstanceIdentifier.PathArgument> builder = new LinkedList<>();
290 getCodecContextNode(input, builder);
291 return InstanceIdentifier.create(builder);
295 private class IdentityCodec implements Codec<QName, Class<?>> {
298 public Class<?> deserialize(final QName input) {
299 Preconditions.checkArgument(input != null, "Input must not be null.");
300 return context.getIdentityClass(input);
304 public QName serialize(final Class<?> input) {
305 Preconditions.checkArgument(BaseIdentity.class.isAssignableFrom(input));
306 return BindingReflections.findQName(input);
310 private static class ValueContext {
313 Codec<Object, Object> codec;
315 public ValueContext(final Class<?> identifier, final LeafNodeCodecContext leaf) {
316 final String getterName = GETTER_PREFIX
317 + BindingMapping.getClassName(leaf.getDomPathArgument().getNodeType());
319 getter = identifier.getMethod(getterName);
320 } catch (NoSuchMethodException | SecurityException e) {
321 throw new IllegalStateException(e);
323 codec = leaf.getValueCodec();
326 public Object getAndSerialize(final Object obj) {
328 Object value = getter.invoke(obj);
329 Preconditions.checkArgument(value != null,
330 "All keys must be specified for %s. Missing key is %s. Supplied key is %s",
331 getter.getDeclaringClass(), getter.getName(), obj);
332 return codec.serialize(value);
333 } catch (IllegalAccessException | InvocationTargetException e) {
334 throw new IllegalArgumentException(e);
338 public Object deserialize(final Object obj) {
339 return codec.deserialize(obj);
344 private class IdentifiableItemCodec implements Codec<NodeIdentifierWithPredicates, IdentifiableItem<?, ?>> {
346 private final ImmutableSortedMap<QName, ValueContext> keyValueContexts;
347 private final ListSchemaNode schema;
348 private final Constructor<? extends Identifier<?>> constructor;
349 private final Class<?> identifiable;
351 public IdentifiableItemCodec(final ListSchemaNode schema, final Class<? extends Identifier<?>> keyClass,
352 final Class<?> identifiable, final Map<QName, ValueContext> keyValueContexts) {
353 this.schema = schema;
354 this.identifiable = identifiable;
355 this.keyValueContexts = ImmutableSortedMap.copyOf(keyValueContexts);
356 this.constructor = getConstructor(keyClass);
360 public IdentifiableItem<?, ?> deserialize(final NodeIdentifierWithPredicates input) {
361 ArrayList<Object> bindingValues = new ArrayList<>();
363 for(QName key: schema.getKeyDefinition()) {
364 Object yangValue = input.getKeyValues().get(key);
365 bindingValues.add(keyValueContexts.get(key).deserialize(yangValue));
368 final Identifier<?> identifier = constructor.newInstance(bindingValues.toArray());
369 @SuppressWarnings({ "rawtypes", "unchecked" })
370 final IdentifiableItem identifiableItem = new IdentifiableItem(identifiable, identifier);
371 return identifiableItem;
372 } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
373 throw new IllegalStateException(e);
378 public NodeIdentifierWithPredicates serialize(final IdentifiableItem<?, ?> input) {
379 Object value = input.getKey();
381 Map<QName, Object> values = new HashMap<>();
382 for (Entry<QName, ValueContext> valueCtx : keyValueContexts.entrySet()) {
383 values.put(valueCtx.getKey(), valueCtx.getValue().getAndSerialize(value));
385 return new NodeIdentifierWithPredicates(schema.getQName(), values);
390 @SuppressWarnings("unchecked")
391 private static Constructor<? extends Identifier<?>> getConstructor(final Class<? extends Identifier<?>> clazz) {
392 for (@SuppressWarnings("rawtypes") Constructor constr : clazz.getConstructors()) {
393 Class<?>[] parameters = constr.getParameterTypes();
394 if (!clazz.equals(parameters[0])) {
395 // It is not copy constructor;
399 throw new IllegalArgumentException("Supplied class " + clazz + "does not have required constructor.");
403 public Codec<NodeIdentifierWithPredicates, IdentifiableItem<?, ?>> getPathArgumentCodec(final Class<?> listClz,
404 final ListSchemaNode schema) {
405 Class<? extends Identifier<?>> identifier = ClassLoaderUtils.findFirstGenericArgument(listClz,
407 Map<QName, ValueContext> valueCtx = new HashMap<>();
408 for (LeafNodeCodecContext leaf : getLeafNodes(identifier, schema).values()) {
409 QName name = leaf.getDomPathArgument().getNodeType();
410 valueCtx.put(name, new ValueContext(identifier, leaf));
412 return new IdentifiableItemCodec(schema, identifier, listClz, valueCtx);