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.sal.binding.generator.impl;
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.BiMap;
13 import com.google.common.collect.HashBiMap;
14 import com.google.common.collect.HashMultimap;
15 import com.google.common.collect.Iterables;
16 import com.google.common.collect.Multimap;
17 import com.google.common.collect.Multimaps;
18 import java.util.AbstractMap.SimpleEntry;
19 import java.util.ArrayList;
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.HashMap;
23 import java.util.HashSet;
24 import java.util.Iterator;
25 import java.util.List;
27 import java.util.Map.Entry;
29 import java.util.WeakHashMap;
30 import java.util.concurrent.ConcurrentHashMap;
31 import java.util.concurrent.ConcurrentMap;
32 import org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl;
33 import org.opendaylight.yangtools.binding.generator.util.Types;
34 import org.opendaylight.yangtools.concepts.Delegator;
35 import org.opendaylight.yangtools.concepts.Identifiable;
36 import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
37 import org.opendaylight.yangtools.sal.binding.generator.util.CodeGenerationException;
38 import org.opendaylight.yangtools.sal.binding.model.api.ConcreteType;
39 import org.opendaylight.yangtools.sal.binding.model.api.Type;
40 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
41 import org.opendaylight.yangtools.util.ClassLoaderUtils;
42 import org.opendaylight.yangtools.yang.binding.Augmentable;
43 import org.opendaylight.yangtools.yang.binding.Augmentation;
44 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
45 import org.opendaylight.yangtools.yang.binding.BindingCodec;
46 import org.opendaylight.yangtools.yang.binding.BindingMapping;
47 import org.opendaylight.yangtools.yang.binding.DataContainer;
48 import org.opendaylight.yangtools.yang.binding.DataObject;
49 import org.opendaylight.yangtools.yang.binding.Identifier;
50 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
51 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
52 import org.opendaylight.yangtools.yang.common.QName;
53 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
54 import org.opendaylight.yangtools.yang.data.api.Node;
55 import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl;
56 import org.opendaylight.yangtools.yang.data.impl.codec.AugmentationCodec;
57 import org.opendaylight.yangtools.yang.data.impl.codec.ChoiceCaseCodec;
58 import org.opendaylight.yangtools.yang.data.impl.codec.ChoiceCodec;
59 import org.opendaylight.yangtools.yang.data.impl.codec.CodecRegistry;
60 import org.opendaylight.yangtools.yang.data.impl.codec.DataContainerCodec;
61 import org.opendaylight.yangtools.yang.data.impl.codec.DomCodec;
62 import org.opendaylight.yangtools.yang.data.impl.codec.IdentifierCodec;
63 import org.opendaylight.yangtools.yang.data.impl.codec.IdentityCodec;
64 import org.opendaylight.yangtools.yang.data.impl.codec.InstanceIdentifierCodec;
65 import org.opendaylight.yangtools.yang.data.impl.codec.ValueWithQName;
66 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
67 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
68 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
69 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
70 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
71 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
72 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
73 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
74 import org.opendaylight.yangtools.yang.model.api.Module;
75 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
76 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
77 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
78 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
79 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
80 import org.slf4j.Logger;
81 import org.slf4j.LoggerFactory;
83 class LazyGeneratedCodecRegistry implements CodecRegistry, SchemaContextListener, GeneratorListener {
85 private static final Logger LOG = LoggerFactory.getLogger(LazyGeneratedCodecRegistry.class);
87 // Concrete class to codecs
88 private static final Map<Class<?>, DataContainerCodec<?>> containerCodecs = Collections
89 .synchronizedMap(new WeakHashMap<Class<?>, DataContainerCodec<?>>());
90 private static final Map<Class<?>, IdentifierCodec<?>> identifierCodecs = Collections
91 .synchronizedMap(new WeakHashMap<Class<?>, IdentifierCodec<?>>());
92 private static final Map<Class<?>, PublicChoiceCodecImpl<?>> choiceCodecs = Collections
93 .synchronizedMap(new WeakHashMap<Class<?>, PublicChoiceCodecImpl<?>>());
94 private static final Map<Class<?>, ChoiceCaseCodecImpl<?>> caseCodecs = Collections
95 .synchronizedMap(new WeakHashMap<Class<?>, ChoiceCaseCodecImpl<?>>());
96 private static final Map<Class<?>, AugmentableDispatchCodec> augmentableCodecs = Collections
97 .synchronizedMap(new WeakHashMap<Class<?>, AugmentableDispatchCodec>());
98 private static final Map<Class<?>, AugmentationCodecWrapper<?>> augmentationCodecs = Collections
99 .synchronizedMap(new WeakHashMap<Class<?>, AugmentationCodecWrapper<?>>());
101 private static final Map<Class<?>, LocationAwareDispatchCodec<?>> dispatchCodecs = Collections
102 .synchronizedMap(new WeakHashMap<Class<?>, LocationAwareDispatchCodec<?>>());
104 private static final Map<Class<?>, QName> identityQNames = Collections
105 .synchronizedMap(new WeakHashMap<Class<?>, QName>());
106 private static final Map<QName, Type> qnamesToIdentityMap = new ConcurrentHashMap<>();
108 private static final ConcurrentMap<Type, ChoiceCaseNode> caseTypeToCaseSchema = new ConcurrentHashMap<>();
110 private static final Map<SchemaPath, Type> pathToType = new ConcurrentHashMap<>();
111 private static final Map<List<QName>, Type> pathToInstantiatedType = new ConcurrentHashMap<>();
112 private static final Map<Type, QName> typeToQname = new ConcurrentHashMap<>();
113 private static final BiMap<Type, AugmentationSchema> typeToAugment = HashBiMap
114 .create(new ConcurrentHashMap<Type, AugmentationSchema>());
116 private static final Multimap<Type, Type> augmentableToAugmentations = Multimaps.synchronizedMultimap(HashMultimap
117 .<Type, Type> create());
118 private static final Multimap<Type, Type> choiceToCases = Multimaps.synchronizedMultimap(HashMultimap
119 .<Type, Type> create());
121 private final InstanceIdentifierCodec instanceIdentifierCodec = new InstanceIdentifierCodecImpl(this);
122 private final IdentityCompositeCodec identityRefCodec = new IdentityCompositeCodec();
123 private final ClassLoadingStrategy classLoadingStrategy;
124 private final AbstractTransformerGenerator generator;
125 private final SchemaLock lock;
127 // FIXME: how is this protected?
128 private SchemaContext currentSchema;
130 LazyGeneratedCodecRegistry(final SchemaLock lock, final AbstractTransformerGenerator generator,
131 final ClassLoadingStrategy classLoadingStrategy) {
132 this.lock = Preconditions.checkNotNull(lock);
133 this.classLoadingStrategy = Preconditions.checkNotNull(classLoadingStrategy);
134 this.generator = Preconditions.checkNotNull(generator);
137 public SchemaLock getLock() {
142 public InstanceIdentifierCodec getInstanceIdentifierCodec() {
143 return instanceIdentifierCodec;
146 @SuppressWarnings("unchecked")
148 public <T extends Augmentation<?>> AugmentationCodecWrapper<T> getCodecForAugmentation(final Class<T> augClass) {
149 AugmentationCodecWrapper<T> codec = null;
150 @SuppressWarnings("rawtypes")
151 AugmentationCodecWrapper potentialCodec = augmentationCodecs.get(augClass);
152 if (potentialCodec != null) {
153 codec = potentialCodec;
155 lock.waitForSchema(augClass);
156 Class<? extends BindingCodec<Map<QName, Object>, Object>> augmentRawCodec = generator
157 .augmentationTransformerFor(augClass);
159 BindingCodec<Map<QName, Object>, Object> rawCodec = newInstanceOf(augmentRawCodec);
160 codec = new AugmentationCodecWrapper<T>(rawCodec, augClass);
161 augmentationCodecs.put(augClass, codec);
164 final Class<? extends Augmentable<?>> objectSupertype;
166 objectSupertype = BindingReflections.findAugmentationTarget(augClass);
167 } catch (Exception e) {
168 LOG.warn("Failed to find target for augmentation {}, ignoring it", augClass, e);
172 if (objectSupertype == null) {
173 LOG.warn("Augmentation target for {} not found, ignoring it", augClass);
177 getAugmentableCodec(objectSupertype).addImplementation(codec);
181 @SuppressWarnings("unchecked")
183 public QName getQNameForAugmentation(final Class<?> cls) {
184 Preconditions.checkArgument(Augmentation.class.isAssignableFrom(cls));
185 return getCodecForAugmentation((Class<? extends Augmentation<?>>) cls).getAugmentationQName();
189 public Class<?> getClassForPath(final List<QName> names) {
190 DataSchemaNode node = getSchemaNode(names);
191 Preconditions.checkArgument(node != null, "Path %s points to invalid schema location", names);
192 SchemaNode originalDefinition = SchemaNodeUtils.getRootOriginalIfPossible(node);
193 if (originalDefinition instanceof DataSchemaNode) {
194 node = (DataSchemaNode) originalDefinition;
196 final SchemaPath path = node.getPath();
197 final Type t = pathToType.get(path);
201 type = new ReferencedTypeImpl(t.getPackageName(), t.getName());
203 type = pathToInstantiatedType.get(names);
204 Preconditions.checkState(type != null, "Failed to lookup instantiated type for path %s", path);
208 return classLoadingStrategy.loadClass(type);
209 } catch (ClassNotFoundException e) {
210 throw new IllegalStateException(String.format("Could not find loaded class for path: %s and type: %s",
211 path, type.getFullyQualifiedName()));
216 public void putPathToClass(final List<QName> names, final Class<?> cls) {
217 final Type reference = Types.typeForClass(cls);
218 pathToInstantiatedType.put(names, reference);
219 LOG.trace("Path {} attached to class {} reference {}", names, cls, reference);
220 bindingClassEncountered(cls);
224 public IdentifierCodec<?> getKeyCodecForPath(final List<QName> names) {
225 @SuppressWarnings("unchecked")
226 Class<? extends Identifiable<?>> cls = (Class<? extends Identifiable<?>>) getClassForPath(names);
227 return getIdentifierCodecForIdentifiable(cls);
231 public <T extends DataContainer> DataContainerCodec<T> getCodecForDataObject(final Class<T> type) {
232 @SuppressWarnings("unchecked")
233 DataContainerCodec<T> ret = (DataContainerCodec<T>) containerCodecs.get(type);
237 Class<? extends BindingCodec<Map<QName, Object>, Object>> newType = generator.transformerFor(type);
238 BindingCodec<Map<QName, Object>, Object> rawCodec = newInstanceOf(newType);
239 DataContainerCodecImpl<T> newWrapper = new DataContainerCodecImpl<>(rawCodec);
240 containerCodecs.put(type, newWrapper);
245 @SuppressWarnings("rawtypes")
246 public void bindingClassEncountered(final Class cls) {
247 if (Augmentation.class.isAssignableFrom(cls)) {
248 // Intentionally NOOP
249 } else if (DataObject.class.isAssignableFrom(cls)) {
250 getCodecForDataObject((Class<? extends DataObject>) cls);
255 public void onClassProcessed(final Class<?> cls) {
259 private DataSchemaNode getSchemaNode(final List<QName> path) {
260 QName firstNode = path.get(0);
261 DataNodeContainer previous = currentSchema.findModuleByNamespaceAndRevision(firstNode.getNamespace(),
262 firstNode.getRevision());
263 Preconditions.checkArgument(previous != null, "Failed to find module %s for path %s", firstNode, path);
265 Iterator<QName> iterator = path.iterator();
266 while (iterator.hasNext()) {
267 QName arg = iterator.next();
268 DataSchemaNode currentNode = previous.getDataChildByName(arg);
269 if (currentNode == null) {
270 currentNode = searchInChoices(previous, arg);
272 if (currentNode instanceof DataNodeContainer) {
273 previous = (DataNodeContainer) currentNode;
274 } else if (currentNode instanceof LeafSchemaNode || currentNode instanceof LeafListSchemaNode) {
275 Preconditions.checkState(!iterator.hasNext(), "Path tries to nest inside leaf node.");
279 return (DataSchemaNode) previous;
282 private DataSchemaNode searchInChoices(final DataNodeContainer node, final QName arg) {
283 for (DataSchemaNode child : node.getChildNodes()) {
284 if (child instanceof ChoiceSchemaNode) {
285 ChoiceSchemaNode choiceNode = (ChoiceSchemaNode) child;
286 DataSchemaNode potential = searchInCases(choiceNode, arg);
287 if (potential != null) {
295 private DataSchemaNode searchInCases(final ChoiceSchemaNode choiceNode, final QName arg) {
296 Set<ChoiceCaseNode> cases = choiceNode.getCases();
297 for (ChoiceCaseNode caseNode : cases) {
298 DataSchemaNode node = caseNode.getDataChildByName(arg);
306 private static <T> T newInstanceOf(final Class<?> cls) {
308 @SuppressWarnings("unchecked")
309 T ret = (T) cls.newInstance();
311 } catch (InstantiationException e) {
312 LOG.error("Failed to instantiate codec {}", cls.getSimpleName(), e);
313 throw new IllegalStateException(String.format("Failed to instantiate codec %s", cls), e);
314 } catch (IllegalAccessException e) {
316 "Run-time consistency issue: constructor for {} is not available. This indicates either a code generation bug or a misconfiguration of JVM.",
317 cls.getSimpleName(), e);
318 throw new IllegalStateException(String.format("Cannot access contructor of %s", cls), e);
322 @SuppressWarnings("unchecked")
324 public IdentifierCodec<?> getIdentifierCodecForIdentifiable(final Class identifiable) {
326 Class identifier = ClassLoaderUtils.findFirstGenericArgument(identifiable,
327 org.opendaylight.yangtools.yang.binding.Identifiable.class);
328 IdentifierCodec<?> obj = identifierCodecs.get(identifier);
332 return createIdentifierCodec(identifier, identifiable);
336 public <T extends Identifier<?>> IdentifierCodec<T> getCodecForIdentifier(final Class<T> identifier) {
337 @SuppressWarnings("unchecked")
338 IdentifierCodec<T> obj = (IdentifierCodec<T>) identifierCodecs.get(identifier);
342 Class<? extends Identifiable<T>> identifiable = ClassLoaderUtils.findFirstGenericArgument(identifier,
344 return createIdentifierCodec(identifier, identifiable);
347 private <T extends Identifier<?>> IdentifierCodec<T> createIdentifierCodec(final Class<T> identifier,
348 final Class<? extends Identifiable<T>> identifiable) {
349 Class<? extends BindingCodec<Map<QName, Object>, Object>> newCodec = generator
350 .keyTransformerForIdentifiable(identifiable);
351 BindingCodec<Map<QName, Object>, Object> newInstance;
352 newInstance = newInstanceOf(newCodec);
353 IdentifierCodecImpl<T> newWrapper = new IdentifierCodecImpl<>(newInstance);
354 identifierCodecs.put(identifier, newWrapper);
359 public IdentityCodec<?> getIdentityCodec() {
360 return identityRefCodec;
363 @SuppressWarnings("unchecked")
365 public <T extends BaseIdentity> IdentityCodec<T> getCodecForIdentity(final Class<T> codec) {
366 bindingClassEncountered(codec);
367 return identityRefCodec;
371 public void onCodecCreated(final Class<?> cls) {
372 CodecMapping.setIdentifierCodec(cls, instanceIdentifierCodec);
373 CodecMapping.setIdentityRefCodec(cls, identityRefCodec);
376 @SuppressWarnings("rawtypes")
377 public ChoiceCaseCodecImpl getCaseCodecFor(final Class caseClass) {
378 ChoiceCaseCodecImpl<?> potential = caseCodecs.get(caseClass);
379 if (potential != null) {
382 ConcreteType typeref = Types.typeForClass(caseClass);
383 ChoiceCaseNode caseSchema = caseTypeToCaseSchema.get(typeref);
385 Preconditions.checkState(caseSchema != null, "Case schema is not available for %s", caseClass.getName());
386 Class<? extends BindingCodec> newCodec = generator.caseCodecFor(caseClass, caseSchema);
387 BindingCodec newInstance = newInstanceOf(newCodec);
388 @SuppressWarnings("unchecked")
389 ChoiceCaseCodecImpl caseCodec = new ChoiceCaseCodecImpl(caseClass, caseSchema, newInstance);
390 caseCodecs.put(caseClass, caseCodec);
394 public void onModuleContextAdded(final SchemaContext schemaContext, final Module module, final ModuleContext context) {
395 pathToType.putAll(context.getChildNodes());
397 BiMap<Type, AugmentationSchema> bimap = context.getTypeToAugmentation();
398 for (Map.Entry<Type, AugmentationSchema> entry : bimap.entrySet()) {
399 Type key = entry.getKey();
400 AugmentationSchema value = entry.getValue();
401 Collection<DataSchemaNode> augmentedNodes = value.getChildNodes();
402 if (augmentedNodes != null && !augmentedNodes.isEmpty()) {
403 typeToAugment.put(key, value);
407 qnamesToIdentityMap.putAll(context.getIdentities());
408 for (Entry<QName, GeneratedTOBuilder> identity : context.getIdentities().entrySet()) {
410 new ReferencedTypeImpl(identity.getValue().getPackageName(), identity.getValue().getName()),
414 synchronized (augmentableToAugmentations) {
415 augmentableToAugmentations.putAll(context.getAugmentableToAugmentations());
417 synchronized (choiceToCases) {
418 choiceToCases.putAll(context.getChoiceToCases());
420 synchronized (caseTypeToCaseSchema) {
421 caseTypeToCaseSchema.putAll(context.getCaseTypeToSchemas());
426 public void onGlobalContextUpdated(final SchemaContext context) {
427 currentSchema = context;
428 resetDispatchCodecsAdaptation();
433 * Resets / clears adaptation for all schema context sensitive codecs in
434 * order for them to adapt to new schema context and maybe newly discovered
435 * augmentations This ensure correct behaviour for augmentations and
436 * augmented cases for preexisting codecs, which augmentations were
437 * introduced at later point in time.
439 * This also makes removed augmentations unavailable.
441 private void resetDispatchCodecsAdaptation() {
442 synchronized (dispatchCodecs) {
443 for (LocationAwareDispatchCodec<?> codec : dispatchCodecs.values()) {
444 codec.resetCodec(this);
449 @SuppressWarnings({ "unchecked", "rawtypes" })
451 public void onChoiceCodecCreated(final Class<?> choiceClass,
452 final Class<? extends BindingCodec<Map<QName, Object>, Object>> choiceCodec, final ChoiceSchemaNode schema) {
453 ChoiceCodec<?> oldCodec = choiceCodecs.get(choiceClass);
454 Preconditions.checkState(oldCodec == null);
455 BindingCodec<Map<QName, Object>, Object> delegate = newInstanceOf(choiceCodec);
456 PublicChoiceCodecImpl<?> newCodec = new PublicChoiceCodecImpl(delegate);
457 DispatchChoiceCodecImpl dispatchCodec = new DispatchChoiceCodecImpl(choiceClass, this);
458 choiceCodecs.put(choiceClass, newCodec);
459 synchronized (dispatchCodecs) {
460 dispatchCodecs.put(choiceClass, dispatchCodec);
462 CodecMapping.setDispatchCodec(choiceCodec, dispatchCodec);
466 public void onValueCodecCreated(final Class<?> valueClass, final Class<?> valueCodec) {
470 public void onCaseCodecCreated(final Class<?> choiceClass,
471 final Class<? extends BindingCodec<Map<QName, Object>, Object>> choiceCodec) {
475 public void onDataContainerCodecCreated(final Class<?> dataClass,
476 final Class<? extends BindingCodec<?, ?>> dataCodec) {
477 if (Augmentable.class.isAssignableFrom(dataClass)) {
478 AugmentableDispatchCodec augmentableCodec = getAugmentableCodec(dataClass);
479 CodecMapping.setAugmentationCodec(dataCodec, augmentableCodec);
483 public synchronized AugmentableDispatchCodec getAugmentableCodec(final Class<?> dataClass) {
484 AugmentableDispatchCodec ret = augmentableCodecs.get(dataClass);
488 ret = new AugmentableDispatchCodec(dataClass, this);
489 augmentableCodecs.put(dataClass, ret);
490 synchronized (dispatchCodecs) {
491 dispatchCodecs.put(dataClass, ret);
493 ret.tryToLoadImplementations();
497 private static abstract class IntermediateCodec<T> implements DomCodec<T>,
498 Delegator<BindingCodec<Map<QName, Object>, Object>> {
500 private final BindingCodec<Map<QName, Object>, Object> delegate;
503 public BindingCodec<Map<QName, Object>, Object> getDelegate() {
507 public IntermediateCodec(final BindingCodec<Map<QName, Object>, Object> delegate) {
508 this.delegate = delegate;
512 public Node<?> serialize(final ValueWithQName<T> input) {
513 Map<QName, Object> intermediateOutput = delegate.serialize(input);
514 return IntermediateMapping.toNode(intermediateOutput);
519 private static class IdentifierCodecImpl<T extends Identifier<?>> extends IntermediateCodec<T> implements
522 public IdentifierCodecImpl(final BindingCodec<Map<QName, Object>, Object> delegate) {
527 public ValueWithQName<T> deserialize(final Node<?> input) {
528 QName qname = input.getNodeType();
529 @SuppressWarnings("unchecked")
530 T value = (T) getDelegate().deserialize((Map<QName, Object>) input);
531 return new ValueWithQName<T>(qname, value);
535 public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
536 QName qname = input.getNodeType();
537 @SuppressWarnings("unchecked")
538 T value = (T) getDelegate().deserialize((Map<QName, Object>) input, bindingIdentifier);
539 return new ValueWithQName<T>(qname, value);
543 public CompositeNode serialize(final ValueWithQName<T> input) {
544 return (CompositeNode) super.serialize(input);
548 private static class DataContainerCodecImpl<T extends DataContainer> extends IntermediateCodec<T> implements
549 DataContainerCodec<T> {
551 public DataContainerCodecImpl(final BindingCodec<Map<QName, Object>, Object> delegate) {
556 public ValueWithQName<T> deserialize(final Node<?> input) {
560 QName qname = input.getNodeType();
561 @SuppressWarnings("unchecked")
562 T value = (T) getDelegate().deserialize((Map<QName, Object>) input);
563 return new ValueWithQName<T>(qname, value);
567 public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
571 QName qname = input.getNodeType();
572 @SuppressWarnings("unchecked")
573 T value = (T) getDelegate().deserialize((Map<QName, Object>) input, bindingIdentifier);
574 return new ValueWithQName<T>(qname, value);
578 public CompositeNode serialize(final ValueWithQName<T> input) {
579 return (CompositeNode) super.serialize(input);
583 private interface LocationAwareBindingCodec<P, I> extends BindingCodec<P, I> {
585 boolean isApplicable(InstanceIdentifier<?> parentPath, CompositeNode data);
587 public Class<?> getDataType();
591 @SuppressWarnings("rawtypes")
592 private static abstract class LocationAwareDispatchCodec<T extends LocationAwareBindingCodec> implements
595 private final Map<Class, T> implementations = Collections.synchronizedMap(new WeakHashMap<Class, T>());
596 private final Set<InstanceIdentifier<?>> adaptedForPaths = new HashSet<>();
597 private LazyGeneratedCodecRegistry registry;
599 protected LocationAwareDispatchCodec(final LazyGeneratedCodecRegistry registry) {
600 this.registry = registry;
603 protected Map<Class, T> getImplementations() {
604 return implementations;
608 * Resets codec adaptation based on location and schema context.
610 * This is required if new cases / augmentations were introduced or
611 * removed and first use of codec is triggered by invocation from DOM to
612 * Java, so the implementations may change and this may require loading
613 * of new codecs and/or removal of existing ones.
616 public synchronized void resetCodec(final LazyGeneratedCodecRegistry currentRegistry) {
617 registry = currentRegistry;
618 adaptedForPaths.clear();
619 resetAdaptationImpl();
622 protected void resetAdaptationImpl() {
623 // Intentionally NOOP, subclasses may specify their custom
627 protected final LazyGeneratedCodecRegistry getRegistry() {
631 protected void addImplementation(final T implementation) {
632 implementations.put(implementation.getDataType(), implementation);
636 public final Object deserialize(final Object input) {
637 throw new UnsupportedOperationException("Invocation of deserialize without Tree location is unsupported");
641 public final Object deserialize(final Object parent, final InstanceIdentifier parentPath) {
642 adaptForPath(parentPath);
643 Preconditions.checkArgument(parent instanceof CompositeNode, "node must be of CompositeNode type.");
644 CompositeNode parentData = (CompositeNode) parent;
645 ArrayList<T> applicable = new ArrayList<>(implementations.size());
648 * Codecs are filtered to only ones, which are applicable in
649 * supplied parent context.
651 for (T impl : getImplementations().values()) {
652 @SuppressWarnings("unchecked")
653 boolean codecApplicable = impl.isApplicable(parentPath, parentData);
654 if (codecApplicable) {
655 applicable.add(impl);
658 LOG.trace("{}: Deserializing mixins from {}, Schema Location {}, Applicable Codecs: {}, All Codecs: {}",
659 this, parent, parentPath, applicable, getImplementations().values());
662 * In case of none is applicable, we return null. Since there is no
663 * mixin which is applicable in this location.
665 if (applicable.isEmpty()) {
668 return deserializeImpl(parentData, parentPath, applicable);
671 protected abstract Object deserializeImpl(final CompositeNode input, final InstanceIdentifier<?> parentPath,
672 Iterable<T> applicableCodecs);
675 public Object serialize(final Object input) {
676 Preconditions.checkArgument(input instanceof DataContainer);
677 Class<? extends DataContainer> inputType = ((DataContainer) input).getImplementedInterface();
678 T implementation = implementations.get(inputType);
679 if (implementation == null) {
680 implementation = tryToLoadImplementationImpl(inputType);
682 return implementation;
685 private T tryToLoadImplementationImpl(final Class<? extends DataContainer> inputType) {
686 T implementation = tryToLoadImplementation(inputType);
687 Preconditions.checkArgument(implementation != null, "Data type %s is not supported.", inputType);
688 addImplementation(implementation);
689 return implementation;
692 protected final synchronized void adaptForPath(final InstanceIdentifier<?> path) {
693 if (adaptedForPaths.contains(path)) {
696 LOG.debug("Adapting mixin codec {} for path {}", this, path);
698 * We search in schema context if the use of this location aware
699 * codec (augmentable codec, case codec) makes sense on provided
703 Optional<DataNodeContainer> contextNode = BindingSchemaContextUtils.findDataNodeContainer(
704 getRegistry().currentSchema, path);
706 * If context node is present, this codec makes sense on provided
710 if (contextNode.isPresent()) {
711 synchronized (this) {
714 * We adapt (turn on / off) possible implementations of
715 * child codecs (augmentations, cases) based on this
721 adaptForPathImpl(path, contextNode.get());
724 * We trigger serialization of instance identifier, to
725 * make sure instance identifier codec is aware of
726 * combination of this path / augmentation / case
728 getRegistry().getInstanceIdentifierCodec().serialize(path);
729 } catch (Exception e) {
730 LOG.warn("Exception during preparation of instance identifier codec for path {}.", path, e);
732 adaptedForPaths.add(path);
735 LOG.debug("Context node (parent node) not found for {}", path);
739 protected abstract T tryToLoadImplementation(Class<? extends DataContainer> inputType);
741 protected abstract void tryToLoadImplementations();
743 protected abstract void adaptForPathImpl(InstanceIdentifier<?> path, DataNodeContainer ctx);
746 @SuppressWarnings("rawtypes")
747 private static class ChoiceCaseCodecImpl<T extends DataContainer> implements ChoiceCaseCodec<T>, //
748 Delegator<BindingCodec>, LocationAwareBindingCodec<Node<?>, ValueWithQName<T>> {
749 private final BindingCodec delegate;
750 private final ChoiceCaseNode schema;
751 private final Map<InstanceIdentifier<?>, ChoiceCaseNode> instantiatedLocations;
752 private final Class<?> dataType;
754 public ChoiceCaseCodecImpl(final Class<?> caseClass, final ChoiceCaseNode caseNode,
755 final BindingCodec newInstance) {
756 this.delegate = newInstance;
757 this.dataType = caseClass;
758 this.schema = caseNode;
759 instantiatedLocations = new HashMap<>();
763 public ValueWithQName<T> deserialize(final Node<?> input) {
764 throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
768 public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
772 QName qname = input.getNodeType();
773 synchronized (instantiatedLocations) {
774 ChoiceCaseNode instantiation = instantiatedLocations.get(bindingIdentifier);
775 if (instantiation != null) {
776 qname = instantiatedLocations.get(bindingIdentifier).getQName();
779 @SuppressWarnings("unchecked")
780 T value = (T) getDelegate().deserialize(new SimpleEntry(qname, input), bindingIdentifier);
781 return new ValueWithQName<T>(qname, value);
785 public CompositeNode serialize(final ValueWithQName<T> input) {
786 throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
790 public BindingCodec getDelegate() {
794 public ChoiceCaseNode getSchema() {
800 public boolean isAcceptable(final Node<?> input) {
801 return checkAgainstSchema(schema, input);
804 private static boolean checkAgainstSchema(final ChoiceCaseNode schema, final Node<?> node) {
805 if (node instanceof CompositeNode) {
806 CompositeNode input = (CompositeNode) node;
807 for (Node<?> childNode : input.getValue()) {
808 QName child = childNode.getNodeType();
809 if (schema.getDataChildByName(child) != null) {
818 public Class<?> getDataType() {
822 public void adaptForPath(final InstanceIdentifier<?> augTarget, final ChoiceCaseNode choiceCaseNode) {
823 synchronized (instantiatedLocations) {
824 instantiatedLocations.put(augTarget, choiceCaseNode);
829 public boolean isApplicable(final InstanceIdentifier path, final CompositeNode input) {
830 ChoiceCaseNode instantiatedSchema = null;
831 synchronized (instantiatedLocations) {
832 instantiatedSchema = instantiatedLocations.get(path);
834 if (instantiatedSchema == null) {
837 return checkAgainstSchema(instantiatedSchema, input);
840 protected boolean isAugmenting(final QName choiceName, final QName proposedQName) {
841 if (schema.isAugmenting()) {
845 QName parentQName = Iterables.get(schema.getPath().getPathTowardsRoot(), 1);
846 if (!parentQName.getNamespace().equals(schema.getQName().getNamespace())) {
849 if (!parentQName.equals(choiceName)) {
850 // This item is instantiation of choice via uses in other YANG
852 if (choiceName.getNamespace().equals(schema.getQName().getNamespace())) {
853 // Original definition of grouping is in same namespace
854 // as original definition of case
855 // so for sure case is introduced via instantiation of
859 // Since we are still here, that means case has same namespace
860 // as its parent, which is instantiation of grouping
861 // but case namespace is different from parent node
862 // so it is augmentation.
869 public String toString() {
870 return "ChoiceCaseCodec [case=" + dataType + ", knownLocations=" + instantiatedLocations.keySet() + "]";
874 private static class PublicChoiceCodecImpl<T> implements ChoiceCodec<T>,
875 Delegator<BindingCodec<Map<QName, Object>, Object>> {
877 private final BindingCodec<Map<QName, Object>, Object> delegate;
879 public PublicChoiceCodecImpl(final BindingCodec<Map<QName, Object>, Object> delegate) {
880 this.delegate = delegate;
884 public ValueWithQName<T> deserialize(final Node<?> input) {
885 throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
889 public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
890 throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
894 public Node<?> serialize(final ValueWithQName<T> input) {
895 throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
899 public BindingCodec<Map<QName, Object>, Object> getDelegate() {
905 class DispatchChoiceCodecImpl extends LocationAwareDispatchCodec<ChoiceCaseCodecImpl<?>> {
906 private final Class<?> choiceType;
907 private final QName choiceName;
909 private DispatchChoiceCodecImpl(final Class<?> type, final LazyGeneratedCodecRegistry registry) {
912 choiceName = BindingReflections.findQName(type);
916 public Object deserializeImpl(final CompositeNode input, final InstanceIdentifier<?> path,
917 final Iterable<ChoiceCaseCodecImpl<?>> codecs) {
918 ChoiceCaseCodecImpl<?> caseCodec = Iterables.getOnlyElement(codecs);
919 ValueWithQName<?> value = caseCodec.deserialize(input, path);
921 return value.getValue();
926 @SuppressWarnings("unchecked")
928 public Object serialize(final Object input) {
929 Preconditions.checkArgument(input instanceof Map.Entry<?, ?>, "Input must be QName, Value");
930 @SuppressWarnings("rawtypes")
931 QName derivedQName = (QName) ((Map.Entry) input).getKey();
932 @SuppressWarnings("rawtypes")
933 Object inputValue = ((Map.Entry) input).getValue();
934 Preconditions.checkArgument(inputValue instanceof DataObject);
935 Class<? extends DataContainer> inputType = ((DataObject) inputValue).getImplementedInterface();
936 ChoiceCaseCodecImpl<?> codec = tryToLoadImplementation(inputType);
937 Preconditions.checkState(codec != null, "Unable to get codec for %s", inputType);
938 if (codec.isAugmenting(choiceName, derivedQName)) {
939 // If choice is augmenting we use QName which defined this
941 return codec.getDelegate().serialize(new ValueWithQName<>(codec.getSchema().getQName(), inputValue));
943 return codec.getDelegate().serialize(input);
946 @SuppressWarnings("rawtypes")
947 protected Optional<ChoiceCaseCodecImpl> tryToLoadImplementation(final Type potential) {
949 @SuppressWarnings("unchecked")
950 Class<? extends DataContainer> clazz = (Class<? extends DataContainer>) classLoadingStrategy
951 .loadClass(potential);
952 ChoiceCaseCodecImpl codec = tryToLoadImplementation(clazz);
953 addImplementation(codec);
954 return Optional.of(codec);
955 } catch (ClassNotFoundException e) {
956 LOG.warn("Failed to find class for choice {}", potential, e);
958 return Optional.absent();
962 protected ChoiceCaseCodecImpl<?> tryToLoadImplementation(final Class<? extends DataContainer> inputType) {
963 ChoiceCaseCodecImpl<?> codec = getCaseCodecFor(inputType);
964 addImplementation(codec);
969 protected void tryToLoadImplementations() {
970 Type type = referencedType(choiceType);
971 Collection<Type> potentialCases;
972 synchronized (choiceToCases) {
973 potentialCases = choiceToCases.get(type);
975 for (Type potential : potentialCases) {
977 tryToLoadImplementation(potential);
978 } catch (CodeGenerationException e) {
979 LOG.warn("Failed to proactively generate choice code for {}", type, e);
985 protected void adaptForPathImpl(final InstanceIdentifier<?> augTarget, final DataNodeContainer ctxNode) {
986 tryToLoadImplementations();
987 Optional<ChoiceSchemaNode> newChoice = BindingSchemaContextUtils.findInstantiatedChoice(ctxNode, choiceType);
988 if(!newChoice.isPresent()) {
989 // Choice is nested inside other choice, so we need to look two levels deep.
990 in_choices: for(DataSchemaNode child : ctxNode.getChildNodes()) {
991 if (child instanceof ChoiceSchemaNode) {
992 Optional<ChoiceSchemaNode> potential = findChoiceInChoiceCases((ChoiceSchemaNode) child, choiceType);
993 if(potential.isPresent()) {
994 newChoice = potential;
1001 Preconditions.checkState(newChoice.isPresent(), "BUG: Unable to find instantiated choice node in schema.");
1002 for (@SuppressWarnings("rawtypes")
1003 Entry<Class, ChoiceCaseCodecImpl<?>> codec : getImplementations().entrySet()) {
1004 ChoiceCaseCodecImpl<?> caseCodec = codec.getValue();
1005 Optional<ChoiceCaseNode> instantiatedSchema = BindingSchemaContextUtils.findInstantiatedCase(
1006 newChoice.get(), caseCodec.getSchema());
1007 if (instantiatedSchema.isPresent()) {
1008 caseCodec.adaptForPath(augTarget, instantiatedSchema.get());
1013 private Optional<ChoiceSchemaNode> findChoiceInChoiceCases(final ChoiceSchemaNode choice, final Class<?> choiceType) {
1014 for(ChoiceCaseNode caze : choice.getCases()) {
1015 Optional<ChoiceSchemaNode> potential = BindingSchemaContextUtils.findInstantiatedChoice(caze, choiceType);
1016 if(potential.isPresent()) {
1020 return Optional.absent();
1024 public String toString() {
1025 return "DispatchChoiceCodecImpl [choiceType=" + choiceType + "]";
1031 * Dispatch codec for augmented object, which processes augmentations
1033 * This codec is used from DataObject codec generated using
1034 * {@link TransformerGenerator#transformerFor(Class)} and is wired during
1035 * {@link LazyGeneratedCodecRegistry#onDataContainerCodecCreated(Class, Class)}.
1037 * Instance of this codec is associated with class of Binding DTO which
1038 * represents target for augmentations.
1041 @SuppressWarnings({ "rawtypes", "unchecked" })
1042 static class AugmentableDispatchCodec extends LocationAwareDispatchCodec<AugmentationCodecWrapper> {
1044 private final Class augmentableType;
1047 * Construct augmetable dispatch codec.
1050 * Class representing augmentation target
1052 * Registry with which this codec is associated.
1054 public AugmentableDispatchCodec(final Class type, final LazyGeneratedCodecRegistry registry) {
1056 Preconditions.checkArgument(Augmentable.class.isAssignableFrom(type));
1057 augmentableType = type;
1061 * Serializes object to list of values which needs to be injected into
1062 * resulting DOM Node. Injection of data to parent DOM Node is handled
1063 * by caller (in this case generated codec).
1065 * TODO: Deprecate use of augmentation codec without instance instance
1068 * @return list of nodes, which needs to be added to parent node.
1072 public Object serialize(final Object input) {
1073 Preconditions.checkArgument(augmentableType.isInstance(input), "Object %s is not instance of %s ", input,
1075 if (input instanceof Augmentable<?>) {
1076 Map<Class<? extends Augmentation<?>>, Augmentation<?>> augmentations = BindingReflections
1077 .getAugmentations((Augmentable<?>) input);
1078 return serializeImpl(augmentations);
1085 * Serialization of augmentations, returns list of composite nodes,
1086 * which needs to be injected to parent node.
1089 * Map of classes to augmentations
1090 * @return List of nodes, which should be added to parent node.
1092 private List serializeImpl(final Map<Class<? extends Augmentation<?>>, Augmentation<?>> input) {
1093 List ret = new ArrayList<>();
1094 for (Entry<Class<? extends Augmentation<?>>, Augmentation<?>> entry : input.entrySet()) {
1095 AugmentationCodec codec = getRegistry().getCodecForAugmentation(entry.getKey());
1096 CompositeNode node = codec.serialize(new ValueWithQName(null, entry.getValue()));
1097 ret.addAll(node.getValue());
1104 * Deserialization of augmentation which is location aware.
1106 * Note: In case of composite nodes as an input, each codec is invoked
1107 * since there is no augmentation identifier and we need to look for
1108 * concrete classes. FIXME: Maybe faster variation will be by extending
1109 * {@link AugmentationCodecWrapper} to look for particular QNames, which
1110 * will filter incoming set of codecs.
1114 * Input representation of data
1116 * Wildcarded instance identifier representing location of
1117 * augmentation parent in conceptual schema tree
1119 * Set of codecs which are applicable for supplied
1120 * <code>path</code>, selected by caller to be used by
1126 public Map<Class, Augmentation> deserializeImpl(final CompositeNode input, final InstanceIdentifier<?> path,
1127 final Iterable<AugmentationCodecWrapper> codecs) {
1128 LOG.trace("{}: Going to deserialize augmentations from {} in location {}. Available codecs {}", this,
1129 input, path, codecs);
1130 Map<Class, Augmentation> ret = new HashMap<>();
1131 for (AugmentationCodecWrapper codec : codecs) {
1132 // We add Augmentation Identifier to path, in order to
1133 // correctly identify children.
1134 Class type = codec.getDataType();
1135 final InstanceIdentifier augmentPath = path.augmentation(type);
1136 ValueWithQName<?> value = codec.deserialize(input, augmentPath);
1137 if (value != null && value.getValue() != null) {
1138 ret.put(type, (Augmentation) value.getValue());
1146 * Tries to load implementation of concrete augmentation codec for
1149 * Loading of codec may fail, because of supplied type may not be
1150 * visible by classloaders known by registry. If class was not found
1151 * returns {@link Optional#absent()}.
1154 * Augmentation class identifier for which codecs should be
1156 * @return Optional with codec for supplied type
1159 protected Optional<AugmentationCodecWrapper> tryToLoadImplementation(final Type potential) {
1161 Class<? extends Augmentation<?>> clazz = (Class<? extends Augmentation<?>>) getRegistry().classLoadingStrategy
1162 .loadClass(potential);
1163 return Optional.of(tryToLoadImplementation(clazz));
1164 } catch (ClassNotFoundException e) {
1165 LOG.warn("Failed to find class for augmentation of {}", potential, e);
1167 return Optional.absent();
1171 protected AugmentationCodecWrapper tryToLoadImplementation(final Class inputType) {
1172 AugmentationCodecWrapper<? extends Augmentation<?>> potentialImpl = getRegistry().getCodecForAugmentation(
1174 addImplementation(potentialImpl);
1175 return potentialImpl;
1179 protected void tryToLoadImplementations() {
1180 Type type = referencedType(augmentableType);
1181 Collection<Type> potentialAugmentations;
1182 synchronized (augmentableToAugmentations) {
1183 potentialAugmentations = new ArrayList(augmentableToAugmentations.get(type));
1185 for (Type potential : potentialAugmentations) {
1187 tryToLoadImplementation(potential);
1188 } catch (CodeGenerationException e) {
1189 LOG.warn("Failed to proactively generate augment code for {}", type, e);
1195 protected void adaptForPathImpl(final InstanceIdentifier<?> augTarget, final DataNodeContainer ctxNode) {
1196 if (ctxNode instanceof AugmentationTarget) {
1197 Set<AugmentationSchema> availableAugmentations = ((AugmentationTarget) ctxNode)
1198 .getAvailableAugmentations();
1199 if (!availableAugmentations.isEmpty()) {
1200 updateAugmentationMapping(augTarget, availableAugmentations);
1207 * Adapts augmentation codec for specific provider location (target)
1209 * Since augmentation are not forward-referencing and may be discovered
1210 * during runtime, we need to adapt {@link AugmentableDispatchCodec},
1211 * {@link AugmentationCodecWrapper} and {@link InstanceIdentifierCodec}
1212 * for this newly discovered location where augmentation may be used.
1214 * Adaptation consists of:
1216 * <li>scan of available (valid) augmentations for current location
1217 * <li>lookup for Java classes derived from this augmentations
1218 * <li>generation of missing codecs
1219 * <li>updating Augmentation codecs to work with new location
1220 * <li>updating Instance Identifier to work with new location
1223 private void updateAugmentationMapping(final InstanceIdentifier<?> augTarget,
1224 final Set<AugmentationSchema> availableAugmentations) {
1225 for (AugmentationSchema aug : availableAugmentations) {
1227 Type potentialType = getTypeForAugmentation(aug);
1228 if (potentialType != null) {
1229 Optional<AugmentationCodecWrapper> potentialImpl = tryToLoadImplementation(potentialType);
1230 if (potentialImpl.isPresent()) {
1231 potentialImpl.get().addApplicableFor(augTarget, aug);
1232 Class augType = potentialImpl.get().getDataType();
1233 InstanceIdentifier augPath = augTarget.augmentation(augType);
1236 org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier domPath = getRegistry()
1237 .getInstanceIdentifierCodec().serialize(augPath);
1238 if (domPath == null) {
1239 LOG.error("Unable to serialize instance identifier for {}", augPath);
1241 } catch (Exception e) {
1242 LOG.error("Unable to serialize instance identifiers for {}", augPath, e);
1247 // Omits warning for empty augmentations since they are not
1248 // represented in data
1249 if (!aug.getChildNodes().isEmpty()) {
1250 LOG.warn("Could not find generated type for augmentation {} with children {}", aug,
1251 aug.getChildNodes());
1257 private Type getTypeForAugmentation(final AugmentationSchema aug) {
1258 Optional<AugmentationSchema> currentAug = Optional.of(aug);
1259 while (currentAug.isPresent()) {
1260 Type potentialType = typeToAugment.inverse().get(currentAug.get());
1261 if (potentialType != null) {
1262 return potentialType;
1264 currentAug = currentAug.get().getOriginalDefinition();
1270 public String toString() {
1271 return "AugmentableDispatchCodec [augmentable=" + augmentableType + "]";
1276 @SuppressWarnings("rawtypes")
1277 private static class AugmentationCodecWrapper<T extends Augmentation<?>> implements AugmentationCodec<T>,
1278 Delegator<BindingCodec>, LocationAwareBindingCodec<Node<?>, ValueWithQName<T>> {
1280 private final BindingCodec delegate;
1281 private final QName augmentationQName;
1282 private final Multimap<InstanceIdentifier<?>, QName> validAugmentationTargets;
1283 private final Class<?> augmentationType;
1285 public AugmentationCodecWrapper(final BindingCodec<Map<QName, Object>, Object> rawCodec, final Class<?> dataType) {
1286 this.delegate = rawCodec;
1287 this.augmentationType = dataType;
1288 this.augmentationQName = BindingReflections.findQName(rawCodec.getClass());
1289 this.validAugmentationTargets = Multimaps.synchronizedSetMultimap(HashMultimap
1290 .<InstanceIdentifier<?>, QName> create());
1293 public void addApplicableFor(final InstanceIdentifier<?> path, final AugmentationSchema aug) {
1294 for (DataSchemaNode child : aug.getChildNodes()) {
1295 validAugmentationTargets.put(path, child.getQName());
1300 public BindingCodec getDelegate() {
1305 public CompositeNode serialize(final ValueWithQName<T> input) {
1306 @SuppressWarnings("unchecked")
1307 List<Map<QName, Object>> rawValues = (List<Map<QName, Object>>) getDelegate().serialize(input);
1308 List<Node<?>> serialized = new ArrayList<>(rawValues.size());
1309 for (Map<QName, Object> val : rawValues) {
1310 serialized.add(IntermediateMapping.toNode(val));
1312 return new CompositeNodeTOImpl(input.getQname(), null, serialized);
1316 @SuppressWarnings("unchecked")
1317 public ValueWithQName<T> deserialize(final Node<?> input) {
1318 Object rawCodecValue = getDelegate().deserialize(input);
1319 return new ValueWithQName<T>(input.getNodeType(), (T) rawCodecValue);
1323 @SuppressWarnings("unchecked")
1324 public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
1325 Object rawCodecValue = getDelegate().deserialize(input, bindingIdentifier);
1326 return new ValueWithQName<T>(input.getNodeType(), (T) rawCodecValue);
1330 public QName getAugmentationQName() {
1331 return augmentationQName;
1335 public boolean isAcceptable(final InstanceIdentifier<?> path) {
1339 return validAugmentationTargets.containsKey(path);
1343 public boolean isApplicable(final InstanceIdentifier parentPath, final CompositeNode parentData) {
1344 return isAcceptable(parentPath);
1348 public Class<?> getDataType() {
1349 return augmentationType;
1353 public String toString() {
1354 return "AugmentationCodecWrapper [augmentation=" + augmentationType + ", knownLocations="
1355 + validAugmentationTargets.keySet() + "]";
1359 @SuppressWarnings("rawtypes")
1360 private class IdentityCompositeCodec implements IdentityCodec {
1363 public Object deserialize(final Object input) {
1364 Preconditions.checkArgument(input instanceof QName);
1365 return deserialize((QName) input);
1369 public Class<?> deserialize(final QName input) {
1370 if (input == null) {
1373 Type type = qnamesToIdentityMap.get(input);
1375 String packageName = BindingMapping.getRootPackageName(input);
1376 String className = BindingMapping.getClassName(input);
1377 type = new ReferencedTypeImpl(packageName, className);
1380 final Class<?> cls = classLoadingStrategy.loadClass(type);
1385 } catch (Exception e) {
1386 LOG.warn("Identity {} was not deserialized, because of missing class {}", input,
1387 type.getFullyQualifiedName(), e);
1394 public Object deserialize(final Object input, final InstanceIdentifier bindingIdentifier) {
1395 return deserialize(input);
1399 public QName serialize(final Class input) {
1400 Preconditions.checkArgument(BaseIdentity.class.isAssignableFrom(input));
1401 bindingClassEncountered(input);
1402 QName qname = identityQNames.get(input);
1403 if (qname != null) {
1406 qname = BindingReflections.findQName(input);
1407 if (qname != null) {
1408 identityQNames.put(input, qname);
1414 public Object serialize(final Object input) {
1415 Preconditions.checkArgument(input instanceof Class);
1416 return serialize((Class) input);
1421 private static final Type referencedType(final Class<?> augmentableType) {
1422 return new ReferencedTypeImpl(augmentableType.getPackage().getName(), augmentableType.getSimpleName());