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.lang.ref.WeakReference;
19 import java.util.AbstractMap.SimpleEntry;
20 import java.util.ArrayList;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.HashMap;
24 import java.util.HashSet;
25 import java.util.Iterator;
26 import java.util.List;
28 import java.util.Map.Entry;
30 import java.util.WeakHashMap;
31 import java.util.concurrent.ConcurrentHashMap;
32 import java.util.concurrent.ConcurrentMap;
33 import org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl;
34 import org.opendaylight.yangtools.binding.generator.util.Types;
35 import org.opendaylight.yangtools.concepts.Delegator;
36 import org.opendaylight.yangtools.concepts.Identifiable;
37 import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
38 import org.opendaylight.yangtools.sal.binding.generator.util.CodeGenerationException;
39 import org.opendaylight.yangtools.sal.binding.model.api.ConcreteType;
40 import org.opendaylight.yangtools.sal.binding.model.api.Type;
41 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
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.binding.util.ClassLoaderUtils;
53 import org.opendaylight.yangtools.yang.common.QName;
54 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
55 import org.opendaylight.yangtools.yang.data.api.Node;
56 import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl;
57 import org.opendaylight.yangtools.yang.data.impl.codec.AugmentationCodec;
58 import org.opendaylight.yangtools.yang.data.impl.codec.ChoiceCaseCodec;
59 import org.opendaylight.yangtools.yang.data.impl.codec.ChoiceCodec;
60 import org.opendaylight.yangtools.yang.data.impl.codec.CodecRegistry;
61 import org.opendaylight.yangtools.yang.data.impl.codec.DataContainerCodec;
62 import org.opendaylight.yangtools.yang.data.impl.codec.DomCodec;
63 import org.opendaylight.yangtools.yang.data.impl.codec.IdentifierCodec;
64 import org.opendaylight.yangtools.yang.data.impl.codec.IdentityCodec;
65 import org.opendaylight.yangtools.yang.data.impl.codec.InstanceIdentifierCodec;
66 import org.opendaylight.yangtools.yang.data.impl.codec.ValueWithQName;
67 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
68 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
69 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
70 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
71 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
72 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
73 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
74 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
75 import org.opendaylight.yangtools.yang.model.api.Module;
76 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
77 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
78 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
79 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
80 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
81 import org.slf4j.Logger;
82 import org.slf4j.LoggerFactory;
84 class LazyGeneratedCodecRegistry implements CodecRegistry, SchemaContextListener, GeneratorListener {
86 private static final Logger LOG = LoggerFactory.getLogger(LazyGeneratedCodecRegistry.class);
88 // Concrete class to codecs
89 private static final Map<Class<?>, DataContainerCodec<?>> containerCodecs = Collections
90 .synchronizedMap(new WeakHashMap<Class<?>, DataContainerCodec<?>>());
91 private static final Map<Class<?>, IdentifierCodec<?>> identifierCodecs = Collections
92 .synchronizedMap(new WeakHashMap<Class<?>, IdentifierCodec<?>>());
93 private static final Map<Class<?>, PublicChoiceCodecImpl<?>> choiceCodecs = Collections
94 .synchronizedMap(new WeakHashMap<Class<?>, PublicChoiceCodecImpl<?>>());
95 private static final Map<Class<?>, ChoiceCaseCodecImpl<?>> caseCodecs = Collections
96 .synchronizedMap(new WeakHashMap<Class<?>, ChoiceCaseCodecImpl<?>>());
97 private static final Map<Class<?>, AugmentableDispatchCodec> augmentableCodecs = Collections
98 .synchronizedMap(new WeakHashMap<Class<?>, AugmentableDispatchCodec>());
99 private static final Map<Class<?>, AugmentationCodecWrapper<?>> augmentationCodecs = Collections
100 .synchronizedMap(new WeakHashMap<Class<?>, AugmentationCodecWrapper<?>>());
102 private static final Map<Class<?>, LocationAwareDispatchCodec<?>> dispatchCodecs = Collections
103 .synchronizedMap(new WeakHashMap<Class<?>, LocationAwareDispatchCodec<?>>());
105 private static final Map<Class<?>, QName> identityQNames = Collections
106 .synchronizedMap(new WeakHashMap<Class<?>, QName>());
107 private static final Map<QName, Type> qnamesToIdentityMap = new ConcurrentHashMap<>();
108 /** Binding type to encountered classes mapping **/
109 @SuppressWarnings("rawtypes")
110 private static final Map<Type, WeakReference<Class>> typeToClass = new ConcurrentHashMap<>();
112 private static final ConcurrentMap<Type, ChoiceCaseNode> caseTypeToCaseSchema = new ConcurrentHashMap<>();
114 private static final Map<SchemaPath, Type> pathToType = new ConcurrentHashMap<>();
115 private static final Map<List<QName>, Type> pathToInstantiatedType = new ConcurrentHashMap<>();
116 private static final Map<Type, QName> typeToQname = new ConcurrentHashMap<>();
117 private static final BiMap<Type, AugmentationSchema> typeToAugment = HashBiMap
118 .create(new ConcurrentHashMap<Type, AugmentationSchema>());
120 private static final Multimap<Type, Type> augmentableToAugmentations = Multimaps.synchronizedMultimap(HashMultimap
121 .<Type, Type> create());
122 private static final Multimap<Type, Type> choiceToCases = Multimaps.synchronizedMultimap(HashMultimap
123 .<Type, Type> create());
125 private final InstanceIdentifierCodec instanceIdentifierCodec = new InstanceIdentifierCodecImpl(this);
126 private final IdentityCompositeCodec identityRefCodec = new IdentityCompositeCodec();
127 private final ClassLoadingStrategy classLoadingStrategy;
128 private final AbstractTransformerGenerator generator;
129 private final SchemaLock lock;
133 // FIXME: how is this protected?
134 private SchemaContext currentSchema;
136 LazyGeneratedCodecRegistry(final SchemaLock lock, final AbstractTransformerGenerator generator,
137 final ClassLoadingStrategy classLoadingStrategy) {
138 this.lock = Preconditions.checkNotNull(lock);
139 this.classLoadingStrategy = Preconditions.checkNotNull(classLoadingStrategy);
140 this.generator = Preconditions.checkNotNull(generator);
143 public SchemaLock getLock() {
148 public InstanceIdentifierCodec getInstanceIdentifierCodec() {
149 return instanceIdentifierCodec;
152 @SuppressWarnings("unchecked")
154 public <T extends Augmentation<?>> AugmentationCodecWrapper<T> getCodecForAugmentation(final Class<T> augClass) {
155 AugmentationCodecWrapper<T> codec = null;
156 @SuppressWarnings("rawtypes")
157 AugmentationCodecWrapper potentialCodec = augmentationCodecs.get(augClass);
158 if (potentialCodec != null) {
159 codec = potentialCodec;
161 lock.waitForSchema(augClass);
162 Class<? extends BindingCodec<Map<QName, Object>, Object>> augmentRawCodec = generator
163 .augmentationTransformerFor(augClass);
165 BindingCodec<Map<QName, Object>, Object> rawCodec = newInstanceOf(augmentRawCodec);
166 codec = new AugmentationCodecWrapper<T>(rawCodec, augClass);
167 augmentationCodecs.put(augClass, codec);
170 final Class<? extends Augmentable<?>> objectSupertype;
172 objectSupertype = BindingReflections.findAugmentationTarget(augClass);
173 } catch (Exception e) {
174 LOG.warn("Failed to find target for augmentation {}, ignoring it", augClass, e);
178 if (objectSupertype == null) {
179 LOG.warn("Augmentation target for {} not found, ignoring it", augClass);
183 getAugmentableCodec(objectSupertype).addImplementation(codec);
187 @SuppressWarnings("unchecked")
189 public QName getQNameForAugmentation(final Class<?> cls) {
190 Preconditions.checkArgument(Augmentation.class.isAssignableFrom(cls));
191 return getCodecForAugmentation((Class<? extends Augmentation<?>>) cls).getAugmentationQName();
195 public Class<?> getClassForPath(final List<QName> names) {
196 DataSchemaNode node = getSchemaNode(names);
197 Preconditions.checkArgument(node != null, "Path %s points to invalid schema location",names);
198 SchemaNode originalDefinition = SchemaNodeUtils.getRootOriginalIfPossible(node);
199 if(originalDefinition instanceof DataSchemaNode) {
200 node =(DataSchemaNode) originalDefinition;
202 final SchemaPath path = node.getPath();
203 final Type t = pathToType.get(path);
207 type = new ReferencedTypeImpl(t.getPackageName(), t.getName());
209 type = pathToInstantiatedType.get(names);
210 Preconditions.checkState(type != null, "Failed to lookup instantiated type for path %s", path);
213 @SuppressWarnings("rawtypes")
214 final WeakReference<Class> weakRef = typeToClass.get(type);
215 if(weakRef != null) {
216 return weakRef.get();
219 return classLoadingStrategy.loadClass(type);
220 } catch (ClassNotFoundException e) {
221 throw new IllegalStateException(String.format("Could not find loaded class for path: %s and type: %s", path,type.getFullyQualifiedName()));
226 public void putPathToClass(final List<QName> names, final Class<?> cls) {
227 final Type reference = Types.typeForClass(cls);
228 pathToInstantiatedType.put(names, reference);
229 LOG.trace("Path {} attached to class {} reference {}", names, cls, reference);
230 bindingClassEncountered(cls);
234 public IdentifierCodec<?> getKeyCodecForPath(final List<QName> names) {
235 @SuppressWarnings("unchecked")
236 Class<? extends Identifiable<?>> cls = (Class<? extends Identifiable<?>>) getClassForPath(names);
237 return getIdentifierCodecForIdentifiable(cls);
241 public <T extends DataContainer> DataContainerCodec<T> getCodecForDataObject(final Class<T> type) {
242 @SuppressWarnings("unchecked")
243 DataContainerCodec<T> ret = (DataContainerCodec<T>) containerCodecs.get(type);
247 Class<? extends BindingCodec<Map<QName, Object>, Object>> newType = generator.transformerFor(type);
248 BindingCodec<Map<QName, Object>, Object> rawCodec = newInstanceOf(newType);
249 DataContainerCodecImpl<T> newWrapper = new DataContainerCodecImpl<>(rawCodec);
250 containerCodecs.put(type, newWrapper);
255 @SuppressWarnings("rawtypes")
256 public void bindingClassEncountered(final Class cls) {
258 ConcreteType typeRef = Types.typeForClass(cls);
259 if (typeToClass.containsKey(typeRef)) {
262 LOG.trace("Binding Class {} encountered.", cls);
263 WeakReference<Class> weakRef = new WeakReference<>(cls);
264 typeToClass.put(typeRef, weakRef);
265 if (Augmentation.class.isAssignableFrom(cls)) {
266 // Intentionally NOOP
267 } else if (DataObject.class.isAssignableFrom(cls)) {
268 getCodecForDataObject((Class<? extends DataObject>) cls);
273 public void onClassProcessed(final Class<?> cls) {
274 ConcreteType typeRef = Types.typeForClass(cls);
275 if (typeToClass.containsKey(typeRef)) {
278 LOG.trace("Binding Class {} encountered.", cls);
279 @SuppressWarnings("rawtypes")
280 WeakReference<Class> weakRef = new WeakReference<Class>(cls);
281 typeToClass.put(typeRef, weakRef);
284 private DataSchemaNode getSchemaNode(final List<QName> path) {
285 QName firstNode = path.get(0);
286 DataNodeContainer previous = currentSchema.findModuleByNamespaceAndRevision(firstNode.getNamespace(),
287 firstNode.getRevision());
288 Preconditions.checkArgument(previous != null, "Failed to find module %s for path %s", firstNode, path);
290 Iterator<QName> iterator = path.iterator();
291 while (iterator.hasNext()) {
292 QName arg = iterator.next();
293 DataSchemaNode currentNode = previous.getDataChildByName(arg);
294 if (currentNode == null && previous instanceof DataNodeContainer) {
295 currentNode = searchInChoices(previous, arg);
297 if (currentNode instanceof DataNodeContainer) {
298 previous = (DataNodeContainer) currentNode;
299 } else if (currentNode instanceof LeafSchemaNode || currentNode instanceof LeafListSchemaNode) {
300 Preconditions.checkState(!iterator.hasNext(), "Path tries to nest inside leaf node.");
304 return (DataSchemaNode) previous;
307 private DataSchemaNode searchInChoices(final DataNodeContainer node, final QName arg) {
308 for (DataSchemaNode child : node.getChildNodes()) {
309 if (child instanceof ChoiceNode) {
310 ChoiceNode choiceNode = (ChoiceNode) child;
311 DataSchemaNode potential = searchInCases(choiceNode, arg);
312 if (potential != null) {
320 private DataSchemaNode searchInCases(final ChoiceNode choiceNode, final QName arg) {
321 Set<ChoiceCaseNode> cases = choiceNode.getCases();
322 for (ChoiceCaseNode caseNode : cases) {
323 DataSchemaNode node = caseNode.getDataChildByName(arg);
331 private static <T> T newInstanceOf(final Class<?> cls) {
333 @SuppressWarnings("unchecked")
334 T ret = (T) cls.newInstance();
336 } catch (InstantiationException e) {
337 LOG.error("Failed to instantiate codec {}", cls.getSimpleName(), e);
338 throw new IllegalStateException(String.format("Failed to instantiate codec %s", cls), e);
339 } catch (IllegalAccessException e) {
341 "Run-time consistency issue: constructor for {} is not available. This indicates either a code generation bug or a misconfiguration of JVM.",
342 cls.getSimpleName(), e);
343 throw new IllegalStateException(String.format("Cannot access contructor of %s", cls), e);
347 @SuppressWarnings("unchecked")
349 public IdentifierCodec<?> getIdentifierCodecForIdentifiable(final Class identifiable) {
351 Class identifier= ClassLoaderUtils.findFirstGenericArgument(identifiable, org.opendaylight.yangtools.yang.binding.Identifiable.class);
352 IdentifierCodec<?> obj = identifierCodecs.get(identifier);
356 return createIdentifierCodec(identifier,identifiable);
360 public <T extends Identifier<?>> IdentifierCodec<T> getCodecForIdentifier(final Class<T> identifier) {
361 @SuppressWarnings("unchecked")
362 IdentifierCodec<T> obj = (IdentifierCodec<T>) identifierCodecs.get(identifier);
366 Class<? extends Identifiable<T>> identifiable = ClassLoaderUtils.findFirstGenericArgument(identifier, Identifier.class);
367 return createIdentifierCodec(identifier,identifiable);
370 private <T extends Identifier<?>> IdentifierCodec<T> createIdentifierCodec(final Class<T> identifier,final Class<? extends Identifiable<T>> identifiable){
371 Class<? extends BindingCodec<Map<QName, Object>, Object>> newCodec = generator
372 .keyTransformerForIdentifiable(identifiable);
373 BindingCodec<Map<QName, Object>, Object> newInstance;
374 newInstance = newInstanceOf(newCodec);
375 IdentifierCodecImpl<T> newWrapper = new IdentifierCodecImpl<>(newInstance);
376 identifierCodecs.put(identifier, newWrapper);
381 public IdentityCodec<?> getIdentityCodec() {
382 return identityRefCodec;
385 @SuppressWarnings("unchecked")
387 public <T extends BaseIdentity> IdentityCodec<T> getCodecForIdentity(final Class<T> codec) {
388 bindingClassEncountered(codec);
389 return identityRefCodec;
393 public void onCodecCreated(final Class<?> cls) {
394 CodecMapping.setIdentifierCodec(cls, instanceIdentifierCodec);
395 CodecMapping.setIdentityRefCodec(cls, identityRefCodec);
398 @SuppressWarnings("rawtypes")
399 public ChoiceCaseCodecImpl getCaseCodecFor(final Class caseClass) {
400 ChoiceCaseCodecImpl<?> potential = caseCodecs.get(caseClass);
401 if (potential != null) {
404 ConcreteType typeref = Types.typeForClass(caseClass);
405 ChoiceCaseNode caseSchema = caseTypeToCaseSchema.get(typeref);
407 Preconditions.checkState(caseSchema != null, "Case schema is not available for %s", caseClass.getName());
408 Class<? extends BindingCodec> newCodec = generator.caseCodecFor(caseClass, caseSchema);
409 BindingCodec newInstance = newInstanceOf(newCodec);
410 @SuppressWarnings("unchecked")
411 ChoiceCaseCodecImpl caseCodec = new ChoiceCaseCodecImpl(caseClass, caseSchema, newInstance);
412 caseCodecs.put(caseClass, caseCodec);
416 public void onModuleContextAdded(final SchemaContext schemaContext, final Module module, final ModuleContext context) {
417 pathToType.putAll(context.getChildNodes());
419 BiMap<Type, AugmentationSchema> bimap = context.getTypeToAugmentation();
420 for (Map.Entry<Type, AugmentationSchema> entry : bimap.entrySet()) {
421 Type key = entry.getKey();
422 AugmentationSchema value = entry.getValue();
423 Collection<DataSchemaNode> augmentedNodes = value.getChildNodes();
424 if (augmentedNodes != null && !augmentedNodes.isEmpty()) {
425 typeToAugment.put(key, value);
429 qnamesToIdentityMap.putAll(context.getIdentities());
430 for (Entry<QName, GeneratedTOBuilder> identity : context.getIdentities().entrySet()) {
432 new ReferencedTypeImpl(identity.getValue().getPackageName(), identity.getValue().getName()),
436 synchronized (augmentableToAugmentations) {
437 augmentableToAugmentations.putAll(context.getAugmentableToAugmentations());
439 synchronized (choiceToCases) {
440 choiceToCases.putAll(context.getChoiceToCases());
442 synchronized (caseTypeToCaseSchema) {
443 caseTypeToCaseSchema.putAll(context.getCaseTypeToSchemas());
448 public void onGlobalContextUpdated(final SchemaContext context) {
449 currentSchema = context;
450 resetDispatchCodecsAdaptation();
455 * Resets / clears adaptation for all schema context sensitive codecs in
456 * order for them to adapt to new schema context and maybe newly discovered
457 * augmentations This ensure correct behaviour for augmentations and
458 * augmented cases for preexisting codecs, which augmentations were
459 * introduced at later point in time.
461 * This also makes removed augmentations unavailable.
463 private void resetDispatchCodecsAdaptation() {
464 synchronized (dispatchCodecs) {
465 for (LocationAwareDispatchCodec<?> codec : dispatchCodecs.values()) {
466 codec.resetCodec(this);
471 @SuppressWarnings({ "unchecked", "rawtypes" })
473 public void onChoiceCodecCreated(final Class<?> choiceClass,
474 final Class<? extends BindingCodec<Map<QName, Object>, Object>> choiceCodec, final ChoiceNode schema) {
475 ChoiceCodec<?> oldCodec = choiceCodecs.get(choiceClass);
476 Preconditions.checkState(oldCodec == null);
477 BindingCodec<Map<QName, Object>, Object> delegate = newInstanceOf(choiceCodec);
478 PublicChoiceCodecImpl<?> newCodec = new PublicChoiceCodecImpl(delegate);
479 DispatchChoiceCodecImpl dispatchCodec = new DispatchChoiceCodecImpl(choiceClass,this);
480 choiceCodecs.put(choiceClass, newCodec);
481 synchronized (dispatchCodecs) {
482 dispatchCodecs.put(choiceClass, dispatchCodec);
484 CodecMapping.setDispatchCodec(choiceCodec, dispatchCodec);
488 public void onValueCodecCreated(final Class<?> valueClass, final Class<?> valueCodec) {
492 public void onCaseCodecCreated(final Class<?> choiceClass,
493 final Class<? extends BindingCodec<Map<QName, Object>, Object>> choiceCodec) {
497 public void onDataContainerCodecCreated(final Class<?> dataClass,
498 final Class<? extends BindingCodec<?, ?>> dataCodec) {
499 if (Augmentable.class.isAssignableFrom(dataClass)) {
500 AugmentableDispatchCodec augmentableCodec = getAugmentableCodec(dataClass);
501 CodecMapping.setAugmentationCodec(dataCodec, augmentableCodec);
505 public synchronized AugmentableDispatchCodec getAugmentableCodec(final Class<?> dataClass) {
506 AugmentableDispatchCodec ret = augmentableCodecs.get(dataClass);
510 ret = new AugmentableDispatchCodec(dataClass,this);
511 augmentableCodecs.put(dataClass, ret);
512 synchronized (dispatchCodecs) {
513 dispatchCodecs.put(dataClass, ret);
515 ret.tryToLoadImplementations();
521 private static abstract class IntermediateCodec<T> implements DomCodec<T>, Delegator<BindingCodec<Map<QName, Object>, Object>> {
523 private final BindingCodec<Map<QName, Object>, Object> delegate;
526 public BindingCodec<Map<QName, Object>, Object> getDelegate() {
530 public IntermediateCodec(final BindingCodec<Map<QName, Object>, Object> delegate) {
531 this.delegate = delegate;
535 public Node<?> serialize(final ValueWithQName<T> input) {
536 Map<QName, Object> intermediateOutput = delegate.serialize(input);
537 return IntermediateMapping.toNode(intermediateOutput);
542 private static class IdentifierCodecImpl<T extends Identifier<?>> extends IntermediateCodec<T> implements IdentifierCodec<T> {
544 public IdentifierCodecImpl(final BindingCodec<Map<QName, Object>, Object> delegate) {
549 public ValueWithQName<T> deserialize(final Node<?> input) {
550 QName qname = input.getNodeType();
551 @SuppressWarnings("unchecked")
552 T value = (T) getDelegate().deserialize((Map<QName, Object>) input);
553 return new ValueWithQName<T>(qname, value);
557 public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
558 QName qname = input.getNodeType();
559 @SuppressWarnings("unchecked")
560 T value = (T) getDelegate().deserialize((Map<QName, Object>) input, bindingIdentifier);
561 return new ValueWithQName<T>(qname, value);
565 public CompositeNode serialize(final ValueWithQName<T> input) {
566 return (CompositeNode) super.serialize(input);
570 private static class DataContainerCodecImpl<T extends DataContainer> extends IntermediateCodec<T> implements DataContainerCodec<T> {
572 public DataContainerCodecImpl(final BindingCodec<Map<QName, Object>, Object> delegate) {
577 public ValueWithQName<T> deserialize(final Node<?> input) {
581 QName qname = input.getNodeType();
582 @SuppressWarnings("unchecked")
583 T value = (T) getDelegate().deserialize((Map<QName, Object>) input);
584 return new ValueWithQName<T>(qname, value);
588 public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
592 QName qname = input.getNodeType();
593 @SuppressWarnings("unchecked")
594 T value = (T) getDelegate().deserialize((Map<QName, Object>) input, bindingIdentifier);
595 return new ValueWithQName<T>(qname, value);
599 public CompositeNode serialize(final ValueWithQName<T> input) {
600 return (CompositeNode) super.serialize(input);
604 private interface LocationAwareBindingCodec<P, I> extends BindingCodec<P, I> {
606 boolean isApplicable(InstanceIdentifier<?> parentPath, CompositeNode data);
608 public Class<?> getDataType();
612 @SuppressWarnings("rawtypes")
613 private static abstract class LocationAwareDispatchCodec<T extends LocationAwareBindingCodec> implements BindingCodec {
615 private final Map<Class, T> implementations = Collections.synchronizedMap(new WeakHashMap<Class, T>());
616 private final Set<InstanceIdentifier<?>> adaptedForPaths = new HashSet<>();
617 private LazyGeneratedCodecRegistry registry;
620 protected LocationAwareDispatchCodec(final LazyGeneratedCodecRegistry registry) {
621 this.registry = registry;
624 protected Map<Class, T> getImplementations() {
625 return implementations;
629 * Resets codec adaptation based on location and schema context.
631 * This is required if new cases / augmentations were introduced or
632 * removed and first use of codec is triggered by invocation from DOM to
633 * Java, so the implementations may change and this may require loading
634 * of new codecs and/or removal of existing ones.
637 public synchronized void resetCodec(final LazyGeneratedCodecRegistry currentRegistry) {
638 registry = currentRegistry;
639 adaptedForPaths.clear();
640 resetAdaptationImpl();
643 protected void resetAdaptationImpl() {
644 // Intentionally NOOP, subclasses may specify their custom
648 protected final LazyGeneratedCodecRegistry getRegistry() {
651 protected void addImplementation(final T implementation) {
652 implementations.put(implementation.getDataType(), implementation);
656 public final Object deserialize(final Object input) {
657 throw new UnsupportedOperationException("Invocation of deserialize without Tree location is unsupported");
661 public final Object deserialize(final Object parent, final InstanceIdentifier parentPath) {
662 adaptForPath(parentPath);
663 Preconditions.checkArgument(parent instanceof CompositeNode, "node must be of CompositeNode type.");
664 CompositeNode parentData = (CompositeNode) parent;
665 ArrayList<T> applicable = new ArrayList<>(implementations.size());
668 * Codecs are filtered to only ones, which
669 * are applicable in supplied parent context.
672 for (T impl : getImplementations().values()) {
673 @SuppressWarnings("unchecked")
674 boolean codecApplicable = impl.isApplicable(parentPath, parentData);
675 if (codecApplicable) {
676 applicable.add(impl);
679 LOG.trace("{}: Deserializing mixins from {}, Schema Location {}, Applicable Codecs: {}, All Codecs: {}",this,parent,parentPath,applicable,getImplementations().values());
681 /* In case of none is applicable, we return
682 * null. Since there is no mixin which
683 * is applicable in this location.
685 if(applicable.isEmpty()) {
688 return deserializeImpl(parentData, parentPath, applicable);
691 protected abstract Object deserializeImpl(final CompositeNode input, final InstanceIdentifier<?> parentPath,
692 Iterable<T> applicableCodecs);
695 public Object serialize(final Object input) {
696 Preconditions.checkArgument(input instanceof DataContainer);
697 Class<? extends DataContainer> inputType = ((DataContainer) input).getImplementedInterface();
698 T implementation = implementations.get(inputType);
699 if (implementation == null) {
700 implementation = tryToLoadImplementationImpl(inputType);
706 private T tryToLoadImplementationImpl(final Class<? extends DataContainer> inputType) {
707 T implementation = tryToLoadImplementation(inputType);
708 Preconditions.checkArgument(implementation != null, "Data type %s is not supported.", inputType);
709 addImplementation(implementation);
710 return implementation;
713 protected final synchronized void adaptForPath(final InstanceIdentifier<?> path) {
714 if (adaptedForPaths.contains(path)) {
717 LOG.debug("Adapting mixin codec {} for path {}",this,path);
719 * We search in schema context if the use of this location aware
720 * codec (augmentable codec, case codec) makes sense on provided
724 Optional<DataNodeContainer> contextNode = BindingSchemaContextUtils.findDataNodeContainer(getRegistry().currentSchema,
727 * If context node is present, this codec makes sense on provided
731 if (contextNode.isPresent()) {
732 synchronized (this) {
735 * We adapt (turn on / off) possible implementations of
736 * child codecs (augmentations, cases) based on this
742 adaptForPathImpl(path, contextNode.get());
745 * We trigger serialization of instance identifier, to
746 * make sure instance identifier codec is aware of
747 * combination of this path / augmentation / case
749 getRegistry().getInstanceIdentifierCodec().serialize(path);
750 } catch (Exception e) {
751 LOG.warn("Exception during preparation of instance identifier codec for path {}.", path, e);
753 adaptedForPaths.add(path);
756 LOG.debug("Context node (parent node) not found for {}", path);
760 protected abstract T tryToLoadImplementation(Class<? extends DataContainer> inputType);
762 protected abstract void tryToLoadImplementations();
764 protected abstract void adaptForPathImpl(InstanceIdentifier<?> path, DataNodeContainer ctx);
767 @SuppressWarnings("rawtypes")
768 private static class ChoiceCaseCodecImpl<T extends DataContainer> implements ChoiceCaseCodec<T>, //
769 Delegator<BindingCodec>, LocationAwareBindingCodec<Node<?>, ValueWithQName<T>> {
770 private final BindingCodec delegate;
771 private final ChoiceCaseNode schema;
772 private final Map<InstanceIdentifier<?>, ChoiceCaseNode> instantiatedLocations;
773 private final Class<?> dataType;
775 public ChoiceCaseCodecImpl(final Class<?> caseClass, final ChoiceCaseNode caseNode,
776 final BindingCodec newInstance) {
777 this.delegate = newInstance;
778 this.dataType = caseClass;
779 this.schema = caseNode;
780 instantiatedLocations = new HashMap<>();
784 public ValueWithQName<T> deserialize(final Node<?> input) {
785 throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
789 public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
793 QName qname = input.getNodeType();
794 synchronized (instantiatedLocations) {
795 ChoiceCaseNode instantiation = instantiatedLocations.get(bindingIdentifier);
796 if (instantiation != null) {
797 qname = instantiatedLocations.get(bindingIdentifier).getQName();
800 @SuppressWarnings("unchecked")
801 T value = (T) getDelegate().deserialize(new SimpleEntry(qname, input), bindingIdentifier);
802 return new ValueWithQName<T>(qname, value);
806 public CompositeNode serialize(final ValueWithQName<T> input) {
807 throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
811 public BindingCodec getDelegate() {
815 public ChoiceCaseNode getSchema() {
821 public boolean isAcceptable(final Node<?> input) {
822 return checkAgainstSchema(schema, input);
825 private static boolean checkAgainstSchema(final ChoiceCaseNode schema, final Node<?> node) {
826 if (node instanceof CompositeNode) {
827 CompositeNode input = (CompositeNode) node;
828 for (Node<?> childNode : input.getValue()) {
829 QName child = childNode.getNodeType();
830 if (schema.getDataChildByName(child) != null) {
839 public Class<?> getDataType() {
843 public void adaptForPath(final InstanceIdentifier<?> augTarget, final ChoiceCaseNode choiceCaseNode) {
844 synchronized (instantiatedLocations) {
845 instantiatedLocations.put(augTarget, choiceCaseNode);
850 public boolean isApplicable(final InstanceIdentifier path, final CompositeNode input) {
851 ChoiceCaseNode instantiatedSchema = null;
852 synchronized (instantiatedLocations) {
853 instantiatedSchema = instantiatedLocations.get(path);
855 if (instantiatedSchema == null) {
858 return checkAgainstSchema(instantiatedSchema, input);
861 protected boolean isAugmenting(final QName choiceName, final QName proposedQName) {
862 if (schema.isAugmenting()) {
866 QName parentQName = Iterables.get(schema.getPath().getPathTowardsRoot(), 1);
867 if (!parentQName.getNamespace().equals(schema.getQName().getNamespace())) {
870 if (!parentQName.equals(choiceName)) {
871 // This item is instantiation of choice via uses in other YANG
873 if (choiceName.getNamespace().equals(schema.getQName())) {
874 // Original definition of grouping is in same namespace
875 // as original definition of case
876 // so for sure case is introduced via instantiation of
880 // Since we are still here, that means case has same namespace
881 // as its parent, which is instantiation of grouping
882 // but case namespace is different from parent node
883 // so it is augmentation.
890 public String toString() {
891 return "ChoiceCaseCodec [case=" + dataType
892 + ", knownLocations=" + instantiatedLocations.keySet() + "]";
896 private static class PublicChoiceCodecImpl<T> implements ChoiceCodec<T>, Delegator<BindingCodec<Map<QName, Object>, Object>> {
898 private final BindingCodec<Map<QName, Object>, Object> delegate;
900 public PublicChoiceCodecImpl(final BindingCodec<Map<QName, Object>, Object> delegate) {
901 this.delegate = delegate;
905 public ValueWithQName<T> deserialize(final Node<?> input) {
906 throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
910 public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
911 throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
915 public Node<?> serialize(final ValueWithQName<T> input) {
916 throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
920 public BindingCodec<Map<QName, Object>, Object> getDelegate() {
926 class DispatchChoiceCodecImpl extends LocationAwareDispatchCodec<ChoiceCaseCodecImpl<?>> {
927 private final Class<?> choiceType;
928 private final QName choiceName;
930 private DispatchChoiceCodecImpl(final Class<?> type, final LazyGeneratedCodecRegistry registry) {
933 choiceName = BindingReflections.findQName(type);
937 public Object deserializeImpl(final CompositeNode input, final InstanceIdentifier<?> path,
938 final Iterable<ChoiceCaseCodecImpl<?>> codecs) {
939 ChoiceCaseCodecImpl<?> caseCodec = Iterables.getOnlyElement(codecs);
940 ValueWithQName<?> value = caseCodec.deserialize(input, path);
942 return value.getValue();
947 @SuppressWarnings("unchecked")
949 public Object serialize(final Object input) {
950 Preconditions.checkArgument(input instanceof Map.Entry<?, ?>, "Input must be QName, Value");
951 @SuppressWarnings("rawtypes")
952 QName derivedQName = (QName) ((Map.Entry) input).getKey();
953 @SuppressWarnings("rawtypes")
954 Object inputValue = ((Map.Entry) input).getValue();
955 Preconditions.checkArgument(inputValue instanceof DataObject);
956 Class<? extends DataContainer> inputType = ((DataObject) inputValue).getImplementedInterface();
957 ChoiceCaseCodecImpl<?> codec = tryToLoadImplementation(inputType);
958 Preconditions.checkState(codec != null, "Unable to get codec for %s", inputType);
959 if (codec.isAugmenting(choiceName, derivedQName)) {
960 // If choice is augmenting we use QName which defined this
962 return codec.getDelegate().serialize(new ValueWithQName<>(codec.getSchema().getQName(), inputValue));
964 return codec.getDelegate().serialize(input);
967 @SuppressWarnings("rawtypes")
968 protected Optional<ChoiceCaseCodecImpl> tryToLoadImplementation(final Type potential) {
970 @SuppressWarnings("unchecked")
971 Class<? extends DataContainer> clazz = (Class<? extends DataContainer>) classLoadingStrategy
972 .loadClass(potential);
973 ChoiceCaseCodecImpl codec = tryToLoadImplementation(clazz);
974 addImplementation(codec);
975 return Optional.of(codec);
976 } catch (ClassNotFoundException e) {
977 LOG.warn("Failed to find class for choice {}", potential, e);
979 return Optional.absent();
983 protected ChoiceCaseCodecImpl<?> tryToLoadImplementation(final Class<? extends DataContainer> inputType) {
984 ChoiceCaseCodecImpl<?> codec = getCaseCodecFor(inputType);
985 addImplementation(codec);
990 protected void tryToLoadImplementations() {
991 Type type = referencedType(choiceType);
992 Collection<Type> potentialCases;
993 synchronized (choiceToCases) {
994 potentialCases = choiceToCases.get(type);
996 for (Type potential : potentialCases) {
998 tryToLoadImplementation(potential);
999 } catch (CodeGenerationException e) {
1000 LOG.warn("Failed to proactively generate choice code for {}", type, e);
1006 protected void adaptForPathImpl(final InstanceIdentifier<?> augTarget, final DataNodeContainer ctxNode) {
1007 Optional<ChoiceNode> newChoice = BindingSchemaContextUtils.findInstantiatedChoice(ctxNode, choiceType);
1008 tryToLoadImplementations();
1009 Preconditions.checkState(newChoice.isPresent(), "BUG: Unable to find instantiated choice node in schema.");
1010 for (@SuppressWarnings("rawtypes")
1011 Entry<Class, ChoiceCaseCodecImpl<?>> codec : getImplementations().entrySet()) {
1012 ChoiceCaseCodecImpl<?> caseCodec = codec.getValue();
1013 Optional<ChoiceCaseNode> instantiatedSchema = BindingSchemaContextUtils.findInstantiatedCase(newChoice.get(),
1014 caseCodec.getSchema());
1015 if (instantiatedSchema.isPresent()) {
1016 caseCodec.adaptForPath(augTarget, instantiatedSchema.get());
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
1035 * during {@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.
1049 * @param type Class representing augmentation target
1050 * @param registry Registry with which this codec is associated.
1052 public AugmentableDispatchCodec(final Class type, final LazyGeneratedCodecRegistry registry) {
1054 Preconditions.checkArgument(Augmentable.class.isAssignableFrom(type));
1055 augmentableType = type;
1061 * Serializes object to list of values which needs to be injected
1062 * into resulting DOM Node. Injection of data to parent DOM Node
1063 * is handled by caller (in this case generated codec).
1065 * TODO: Deprecate use of augmentation codec without instance
1066 * instance identifier
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,augmentableType);
1074 if (input instanceof Augmentable<?>) {
1075 Map<Class<? extends Augmentation<?>>, Augmentation<?>> augmentations = BindingReflections.getAugmentations((Augmentable<?>) input);
1076 return serializeImpl(augmentations);
1085 * Serialization of augmentations, returns list of composite nodes,
1086 * which needs to be injected to parent node.
1088 * @param input Map of classes to augmentations
1089 * @return List of nodes, which should be added to parent node.
1091 private List serializeImpl(final Map<Class<? extends Augmentation<?>>, Augmentation<?>> input) {
1092 List ret = new ArrayList<>();
1093 for (Entry<Class<? extends Augmentation<?>>, Augmentation<?>> entry : input.entrySet()) {
1094 AugmentationCodec codec = getRegistry().getCodecForAugmentation(entry.getKey());
1095 CompositeNode node = codec.serialize(new ValueWithQName(null, entry.getValue()));
1096 ret.addAll(node.getValue());
1103 * Deserialization of augmentation which is location aware.
1105 * Note: In case of composite nodes as an input, each codec
1106 * is invoked since there is no augmentation identifier
1107 * and we need to look for concrete classes.
1108 * FIXME: Maybe faster variation will be by extending
1109 * {@link AugmentationCodecWrapper} to look for particular QNames,
1110 * which will filter incoming set of codecs.
1113 * @param input Input representation of data
1114 * @param path Wildcarded instance identifier representing location of augmentation parent
1115 * in conceptual schema tree
1116 * @param codecs Set of codecs which are applicable for supplied <code>path</code>,
1117 * selected by caller to be used by deserialization
1122 public Map<Class, Augmentation> deserializeImpl(final CompositeNode input, final InstanceIdentifier<?> path,
1123 final Iterable<AugmentationCodecWrapper> codecs) {
1124 LOG.trace("{}: Going to deserialize augmentations from {} in location {}. Available codecs {}",this,input,path,codecs);
1125 Map<Class, Augmentation> ret = new HashMap<>();
1126 for (AugmentationCodecWrapper codec : codecs) {
1127 // We add Augmentation Identifier to path, in order to
1128 // correctly identify children.
1129 Class type = codec.getDataType();
1130 final InstanceIdentifier augmentPath = path.augmentation(type);
1131 ValueWithQName<?> value = codec.deserialize(input, augmentPath);
1132 if (value != null && value.getValue() != null) {
1133 ret.put(type, (Augmentation) value.getValue());
1141 * Tries to load implementation of concrete augmentation codec for supplied type
1143 * Loading of codec may fail, because of supplied type may not be visible
1144 * by classloaders known by registry. If class was not found returns {@link Optional#absent()}.
1146 * @param potential Augmentation class identifier for which codecs should be loaded.
1147 * @return Optional with codec for supplied type
1150 protected Optional<AugmentationCodecWrapper> tryToLoadImplementation(final Type potential) {
1152 Class<? extends Augmentation<?>> clazz = (Class<? extends Augmentation<?>>) getRegistry().classLoadingStrategy
1153 .loadClass(potential);
1154 return Optional.of(tryToLoadImplementation(clazz));
1155 } catch (ClassNotFoundException e) {
1156 LOG.warn("Failed to find class for augmentation of {}", potential, e);
1158 return Optional.absent();
1162 protected AugmentationCodecWrapper tryToLoadImplementation(final Class inputType) {
1163 AugmentationCodecWrapper<? extends Augmentation<?>> potentialImpl = getRegistry().getCodecForAugmentation(inputType);
1164 addImplementation(potentialImpl);
1165 return potentialImpl;
1169 protected void tryToLoadImplementations() {
1170 Type type = referencedType(augmentableType);
1171 Collection<Type> potentialAugmentations;
1172 synchronized (augmentableToAugmentations) {
1173 potentialAugmentations = new ArrayList(augmentableToAugmentations.get(type));
1175 for (Type potential : potentialAugmentations) {
1177 tryToLoadImplementation(potential);
1178 } catch (CodeGenerationException e) {
1179 LOG.warn("Failed to proactively generate augment code for {}", type, e);
1185 protected void adaptForPathImpl(final InstanceIdentifier<?> augTarget, final DataNodeContainer ctxNode) {
1186 if (ctxNode instanceof AugmentationTarget) {
1187 Set<AugmentationSchema> availableAugmentations = ((AugmentationTarget) ctxNode)
1188 .getAvailableAugmentations();
1189 if (!availableAugmentations.isEmpty()) {
1190 updateAugmentationMapping(augTarget, availableAugmentations);
1197 * Adapts augmentation codec for specific provider location (target)
1199 * Since augmentation are not forward-referencing and may be discovered
1200 * during runtime, we need to adapt {@link AugmentableDispatchCodec},
1201 * {@link AugmentationCodecWrapper} and {@link InstanceIdentifierCodec}
1202 * for this newly discovered location where augmentation may be used.
1204 * Adaptation consists of:
1206 * <li>scan of available (valid) augmentations for current location
1207 * <li>lookup for Java classes derived from this augmentations
1208 * <li>generation of missing codecs
1209 * <li>updating Augmentation codecs to work with new location
1210 * <li>updating Instance Identifier to work with new location
1213 private void updateAugmentationMapping(final InstanceIdentifier<?> augTarget,
1214 final Set<AugmentationSchema> availableAugmentations) {
1215 for (AugmentationSchema aug : availableAugmentations) {
1217 Type potentialType = getTypeForAugmentation(aug);
1218 if (potentialType != null) {
1219 Optional<AugmentationCodecWrapper> potentialImpl = tryToLoadImplementation(potentialType);
1220 if (potentialImpl.isPresent()) {
1221 potentialImpl.get().addApplicableFor(augTarget, aug);
1222 Class augType = potentialImpl.get().getDataType();
1223 InstanceIdentifier augPath = augTarget.augmentation(augType);
1226 org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier domPath = getRegistry().getInstanceIdentifierCodec()
1227 .serialize(augPath);
1228 if (domPath == null) {
1229 LOG.error("Unable to serialize instance identifier for {}", augPath);
1231 } catch (Exception e) {
1232 LOG.error("Unable to serialize instance identifiers for {}", augPath, e);
1237 // Omits warning for empty augmentations since they are not
1238 // represented in data
1239 if (!aug.getChildNodes().isEmpty()) {
1240 LOG.warn("Could not find generated type for augmentation {} with children {}", aug,
1241 aug.getChildNodes());
1247 private Type getTypeForAugmentation(final AugmentationSchema aug) {
1248 Optional<AugmentationSchema> currentAug = Optional.of(aug);
1249 while (currentAug.isPresent()) {
1250 Type potentialType = typeToAugment.inverse().get(currentAug.get());
1251 if (potentialType != null) {
1252 return potentialType;
1254 currentAug = currentAug.get().getOriginalDefinition();
1260 public String toString() {
1261 return "AugmentableDispatchCodec [augmentable=" + augmentableType + "]";
1266 @SuppressWarnings("rawtypes")
1267 private static class AugmentationCodecWrapper<T extends Augmentation<?>> implements AugmentationCodec<T>, Delegator<BindingCodec>, LocationAwareBindingCodec<Node<?>, ValueWithQName<T>> {
1269 private final BindingCodec delegate;
1270 private final QName augmentationQName;
1271 private final Multimap<InstanceIdentifier<?>, QName> validAugmentationTargets;
1272 private final Class<?> augmentationType;
1274 public AugmentationCodecWrapper(final BindingCodec<Map<QName, Object>, Object> rawCodec, final Class<?> dataType) {
1275 this.delegate = rawCodec;
1276 this.augmentationType = dataType;
1277 this.augmentationQName = BindingReflections.findQName(rawCodec.getClass());
1278 this.validAugmentationTargets = Multimaps.synchronizedSetMultimap(HashMultimap
1279 .<InstanceIdentifier<?>, QName> create());
1282 public void addApplicableFor(final InstanceIdentifier<?> path, final AugmentationSchema aug) {
1283 for (DataSchemaNode child : aug.getChildNodes()) {
1284 validAugmentationTargets.put(path, child.getQName());
1289 public BindingCodec getDelegate() {
1294 public CompositeNode serialize(final ValueWithQName<T> input) {
1295 @SuppressWarnings("unchecked")
1296 List<Map<QName, Object>> rawValues = (List<Map<QName, Object>>) getDelegate().serialize(input);
1297 List<Node<?>> serialized = new ArrayList<>(rawValues.size());
1298 for (Map<QName, Object> val : rawValues) {
1299 serialized.add(IntermediateMapping.toNode(val));
1301 return new CompositeNodeTOImpl(input.getQname(), null, serialized);
1305 @SuppressWarnings("unchecked")
1306 public ValueWithQName<T> deserialize(final Node<?> input) {
1307 Object rawCodecValue = getDelegate().deserialize(input);
1308 return new ValueWithQName<T>(input.getNodeType(), (T) rawCodecValue);
1312 @SuppressWarnings("unchecked")
1313 public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
1314 Object rawCodecValue = getDelegate().deserialize(input, bindingIdentifier);
1315 return new ValueWithQName<T>(input.getNodeType(), (T) rawCodecValue);
1319 public QName getAugmentationQName() {
1320 return augmentationQName;
1324 public boolean isAcceptable(final InstanceIdentifier<?> path) {
1328 return validAugmentationTargets.containsKey(path);
1332 public boolean isApplicable(final InstanceIdentifier parentPath,final CompositeNode parentData) {
1333 return isAcceptable(parentPath);
1337 public Class<?> getDataType() {
1338 return augmentationType;
1342 public String toString() {
1343 return "AugmentationCodecWrapper [augmentation=" + augmentationType
1344 + ", knownLocations=" + validAugmentationTargets.keySet() + "]";
1348 @SuppressWarnings("rawtypes")
1349 private class IdentityCompositeCodec implements IdentityCodec {
1352 public Object deserialize(final Object input) {
1353 Preconditions.checkArgument(input instanceof QName);
1354 return deserialize((QName) input);
1358 public Class<?> deserialize(final QName input) {
1362 Type type = qnamesToIdentityMap.get(input);
1364 String packageName = BindingMapping.getRootPackageName(input);
1365 String className = BindingMapping.getClassName(input);
1366 type = new ReferencedTypeImpl(packageName, className);
1368 ReferencedTypeImpl typeref = new ReferencedTypeImpl(type.getPackageName(), type.getName());
1369 WeakReference<Class> softref = typeToClass.get(typeref);
1370 if (softref == null) {
1373 Class<?> cls = classLoadingStrategy.loadClass(typeref.getFullyQualifiedName());
1378 } catch (Exception e) {
1379 LOG.warn("Identity {} was not deserialized, because of missing class {}", input,
1380 typeref.getFullyQualifiedName());
1384 return softref.get();
1388 public Object deserialize(final Object input, final InstanceIdentifier bindingIdentifier) {
1389 Type type = qnamesToIdentityMap.get(input);
1391 throw new IllegalArgumentException( "Invalid for \"" + input + "\"." );
1393 ReferencedTypeImpl typeref = new ReferencedTypeImpl(type.getPackageName(), type.getName());
1394 WeakReference<Class> softref = typeToClass.get(typeref);
1395 if (softref == null) {
1398 Class<?> cls = classLoadingStrategy.loadClass(typeref.getFullyQualifiedName());
1403 } catch (Exception e) {
1404 LOG.warn("Identity {} was not deserialized, because of missing class {}", input,
1405 typeref.getFullyQualifiedName());
1409 return softref.get();
1413 public QName serialize(final Class input) {
1414 Preconditions.checkArgument(BaseIdentity.class.isAssignableFrom(input));
1415 bindingClassEncountered(input);
1416 QName qname = identityQNames.get(input);
1417 if (qname != null) {
1420 qname = BindingReflections.findQName(input);
1421 if (qname != null) {
1422 identityQNames.put(input, qname);
1428 public Object serialize(final Object input) {
1429 Preconditions.checkArgument(input instanceof Class);
1430 return serialize((Class) input);
1435 private static final Type referencedType(final Class<?> augmentableType) {
1436 return new ReferencedTypeImpl(augmentableType.getPackage().getName(), augmentableType.getSimpleName());