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 java.lang.ref.WeakReference;
11 import java.lang.reflect.Field;
12 import java.util.AbstractMap.SimpleEntry;
13 import java.util.ArrayList;
14 import java.util.Collection;
15 import java.util.Collections;
16 import java.util.HashMap;
17 import java.util.HashSet;
18 import java.util.Iterator;
19 import java.util.List;
21 import java.util.Map.Entry;
23 import java.util.WeakHashMap;
24 import java.util.concurrent.ConcurrentHashMap;
25 import java.util.concurrent.ConcurrentMap;
27 import org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl;
28 import org.opendaylight.yangtools.binding.generator.util.Types;
29 import org.opendaylight.yangtools.concepts.Delegator;
30 import org.opendaylight.yangtools.concepts.Identifiable;
31 import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
32 import org.opendaylight.yangtools.sal.binding.generator.util.CodeGenerationException;
33 import org.opendaylight.yangtools.sal.binding.model.api.ConcreteType;
34 import org.opendaylight.yangtools.sal.binding.model.api.Type;
35 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
36 import org.opendaylight.yangtools.yang.binding.Augmentable;
37 import org.opendaylight.yangtools.yang.binding.Augmentation;
38 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
39 import org.opendaylight.yangtools.yang.binding.BindingCodec;
40 import org.opendaylight.yangtools.yang.binding.BindingMapping;
41 import org.opendaylight.yangtools.yang.binding.DataContainer;
42 import org.opendaylight.yangtools.yang.binding.DataObject;
43 import org.opendaylight.yangtools.yang.binding.Identifier;
44 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
45 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
46 import org.opendaylight.yangtools.yang.common.QName;
47 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
48 import org.opendaylight.yangtools.yang.data.api.Node;
49 import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl;
50 import org.opendaylight.yangtools.yang.data.impl.codec.AugmentationCodec;
51 import org.opendaylight.yangtools.yang.data.impl.codec.ChoiceCaseCodec;
52 import org.opendaylight.yangtools.yang.data.impl.codec.ChoiceCodec;
53 import org.opendaylight.yangtools.yang.data.impl.codec.CodecRegistry;
54 import org.opendaylight.yangtools.yang.data.impl.codec.DataContainerCodec;
55 import org.opendaylight.yangtools.yang.data.impl.codec.DomCodec;
56 import org.opendaylight.yangtools.yang.data.impl.codec.IdentifierCodec;
57 import org.opendaylight.yangtools.yang.data.impl.codec.IdentityCodec;
58 import org.opendaylight.yangtools.yang.data.impl.codec.InstanceIdentifierCodec;
59 import org.opendaylight.yangtools.yang.data.impl.codec.ValueWithQName;
60 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
61 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
62 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
63 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
64 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
65 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
66 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
67 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
68 import org.opendaylight.yangtools.yang.model.api.Module;
69 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
70 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
71 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
72 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
73 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
74 import org.slf4j.Logger;
75 import org.slf4j.LoggerFactory;
77 import com.google.common.base.Optional;
78 import com.google.common.base.Preconditions;
79 import com.google.common.collect.BiMap;
80 import com.google.common.collect.HashBiMap;
81 import com.google.common.collect.HashMultimap;
82 import com.google.common.collect.Iterables;
83 import com.google.common.collect.Multimap;
84 import com.google.common.collect.Multimaps;
86 class LazyGeneratedCodecRegistry implements //
88 SchemaContextListener, //
91 private static final Logger LOG = LoggerFactory.getLogger(LazyGeneratedCodecRegistry.class);
93 // Concrete class to codecs
94 private static final Map<Class<?>, DataContainerCodec<?>> containerCodecs = Collections
95 .synchronizedMap(new WeakHashMap<Class<?>, DataContainerCodec<?>>());
96 private static final Map<Class<?>, IdentifierCodec<?>> identifierCodecs = Collections
97 .synchronizedMap(new WeakHashMap<Class<?>, IdentifierCodec<?>>());
98 private static final Map<Class<?>, PublicChoiceCodecImpl<?>> choiceCodecs = Collections
99 .synchronizedMap(new WeakHashMap<Class<?>, PublicChoiceCodecImpl<?>>());
100 private static final Map<Class<?>, ChoiceCaseCodecImpl<?>> caseCodecs = Collections
101 .synchronizedMap(new WeakHashMap<Class<?>, ChoiceCaseCodecImpl<?>>());
102 private static final Map<Class<?>, AugmentableDispatchCodec> augmentableCodecs = Collections
103 .synchronizedMap(new WeakHashMap<Class<?>, AugmentableDispatchCodec>());
104 private static final Map<Class<?>, AugmentationCodecWrapper<?>> augmentationCodecs = Collections
105 .synchronizedMap(new WeakHashMap<Class<?>, AugmentationCodecWrapper<?>>());
107 private static final Map<Class<?>, LocationAwareDispatchCodec<?>> dispatchCodecs = Collections
108 .synchronizedMap(new WeakHashMap<Class<?>, LocationAwareDispatchCodec<?>>());
110 private static final Map<Class<?>, QName> identityQNames = Collections
111 .synchronizedMap(new WeakHashMap<Class<?>, QName>());
112 private static final Map<QName, Type> qnamesToIdentityMap = new ConcurrentHashMap<>();
113 /** Binding type to encountered classes mapping **/
114 @SuppressWarnings("rawtypes")
115 private static final Map<Type, WeakReference<Class>> typeToClass = new ConcurrentHashMap<>();
117 private static final ConcurrentMap<Type, ChoiceCaseNode> caseTypeToCaseSchema = new ConcurrentHashMap<>();
119 private static final Map<SchemaPath, Type> pathToType = new ConcurrentHashMap<>();
120 private static final Map<List<QName>, Type> pathToInstantiatedType = new ConcurrentHashMap<>();
121 private static final Map<Type, QName> typeToQname = new ConcurrentHashMap<>();
122 private static final BiMap<Type, AugmentationSchema> typeToAugment = HashBiMap
123 .create(new ConcurrentHashMap<Type, AugmentationSchema>());
125 private static final Multimap<Type, Type> augmentableToAugmentations = Multimaps.synchronizedMultimap(HashMultimap
126 .<Type, Type> create());
127 private static final Multimap<Type, Type> choiceToCases = Multimaps.synchronizedMultimap(HashMultimap
128 .<Type, Type> create());
130 private final InstanceIdentifierCodec instanceIdentifierCodec = new InstanceIdentifierCodecImpl(this);
131 private final IdentityCompositeCodec identityRefCodec = new IdentityCompositeCodec();
132 private final ClassLoadingStrategy classLoadingStrategy;
133 private final AbstractTransformerGenerator generator;
134 private final SchemaLock lock;
136 // FIXME: how is this protected?
137 private SchemaContext currentSchema;
139 LazyGeneratedCodecRegistry(final SchemaLock lock, final AbstractTransformerGenerator generator,
140 final ClassLoadingStrategy classLoadingStrategy) {
141 this.lock = Preconditions.checkNotNull(lock);
142 this.classLoadingStrategy = Preconditions.checkNotNull(classLoadingStrategy);
143 this.generator = Preconditions.checkNotNull(generator);
146 public SchemaLock getLock() {
151 public InstanceIdentifierCodec getInstanceIdentifierCodec() {
152 return instanceIdentifierCodec;
155 @SuppressWarnings("unchecked")
157 public <T extends Augmentation<?>> AugmentationCodecWrapper<T> getCodecForAugmentation(final Class<T> augClass) {
158 AugmentationCodecWrapper<T> codec = null;
159 @SuppressWarnings("rawtypes")
160 AugmentationCodecWrapper potentialCodec = augmentationCodecs.get(augClass);
161 if (potentialCodec != null) {
162 codec = potentialCodec;
164 lock.waitForSchema(augClass);
165 Class<? extends BindingCodec<Map<QName, Object>, Object>> augmentRawCodec = generator
166 .augmentationTransformerFor(augClass);
168 BindingCodec<Map<QName, Object>, Object> rawCodec = newInstanceOf(augmentRawCodec);
169 codec = new AugmentationCodecWrapper<T>(rawCodec, augClass);
170 augmentationCodecs.put(augClass, codec);
173 final Class<? extends Augmentable<?>> objectSupertype;
175 objectSupertype = BindingReflections.findAugmentationTarget(augClass);
176 } catch (Exception e) {
177 LOG.warn("Failed to find target for augmentation {}, ignoring it", augClass, e);
181 if (objectSupertype == null) {
182 LOG.warn("Augmentation target for {} not found, ignoring it", augClass);
186 getAugmentableCodec(objectSupertype).addImplementation(codec);
190 @SuppressWarnings("unchecked")
192 public QName getQNameForAugmentation(final Class<?> cls) {
193 Preconditions.checkArgument(Augmentation.class.isAssignableFrom(cls));
194 return getCodecForAugmentation((Class<? extends Augmentation<?>>) cls).getAugmentationQName();
198 public Class<?> getClassForPath(final List<QName> names) {
199 DataSchemaNode node = getSchemaNode(names);
200 Preconditions.checkArgument(node != null, "Path %s points to invalid schema location",names);
201 SchemaNode originalDefinition = SchemaNodeUtils.getRootOriginalIfPossible(node);
202 if(originalDefinition instanceof DataSchemaNode) {
203 node =(DataSchemaNode) originalDefinition;
205 final SchemaPath path = node.getPath();
206 final Type t = pathToType.get(path);
210 type = new ReferencedTypeImpl(t.getPackageName(), t.getName());
212 type = pathToInstantiatedType.get(names);
213 Preconditions.checkState(type != null, "Failed to lookup instantiated type for path %s", path);
216 @SuppressWarnings("rawtypes")
217 final WeakReference<Class> weakRef = typeToClass.get(type);
218 if(weakRef != null) {
219 return weakRef.get();
222 return classLoadingStrategy.loadClass(type);
223 } catch (ClassNotFoundException e) {
224 throw new IllegalStateException(String.format("Could not find loaded class for path: %s and type: %s", path,type.getFullyQualifiedName()));
229 public void putPathToClass(final List<QName> names, final Class<?> cls) {
230 final Type reference = Types.typeForClass(cls);
231 pathToInstantiatedType.put(names, reference);
232 LOG.trace("Path {} attached to class {} reference {}", names, cls, reference);
233 bindingClassEncountered(cls);
237 public IdentifierCodec<?> getKeyCodecForPath(final List<QName> names) {
238 @SuppressWarnings("unchecked")
239 Class<? extends Identifiable<?>> cls = (Class<? extends Identifiable<?>>) getClassForPath(names);
240 return getIdentifierCodecForIdentifiable(cls);
244 public <T extends DataContainer> DataContainerCodec<T> getCodecForDataObject(final Class<T> type) {
245 @SuppressWarnings("unchecked")
246 DataContainerCodec<T> ret = (DataContainerCodec<T>) containerCodecs.get(type);
250 Class<? extends BindingCodec<Map<QName, Object>, Object>> newType = generator.transformerFor(type);
251 BindingCodec<Map<QName, Object>, Object> rawCodec = newInstanceOf(newType);
252 DataContainerCodecImpl<T> newWrapper = new DataContainerCodecImpl<>(rawCodec);
253 containerCodecs.put(type, newWrapper);
258 @SuppressWarnings("rawtypes")
259 public void bindingClassEncountered(final Class cls) {
261 ConcreteType typeRef = Types.typeForClass(cls);
262 if (typeToClass.containsKey(typeRef)) {
265 LOG.trace("Binding Class {} encountered.", cls);
266 WeakReference<Class> weakRef = new WeakReference<>(cls);
267 typeToClass.put(typeRef, weakRef);
268 if (Augmentation.class.isAssignableFrom(cls)) {
269 // Intentionally NOOP
270 } else if (DataObject.class.isAssignableFrom(cls)) {
271 getCodecForDataObject((Class<? extends DataObject>) cls);
276 public void onClassProcessed(final Class<?> cls) {
277 ConcreteType typeRef = Types.typeForClass(cls);
278 if (typeToClass.containsKey(typeRef)) {
281 LOG.trace("Binding Class {} encountered.", cls);
282 @SuppressWarnings("rawtypes")
283 WeakReference<Class> weakRef = new WeakReference<Class>(cls);
284 typeToClass.put(typeRef, weakRef);
287 private DataSchemaNode getSchemaNode(final List<QName> path) {
288 QName firstNode = path.get(0);
289 DataNodeContainer previous = currentSchema.findModuleByNamespaceAndRevision(firstNode.getNamespace(),
290 firstNode.getRevision());
291 Preconditions.checkArgument(previous != null, "Failed to find module %s for path %s", firstNode, path);
293 Iterator<QName> iterator = path.iterator();
294 while (iterator.hasNext()) {
295 QName arg = iterator.next();
296 DataSchemaNode currentNode = previous.getDataChildByName(arg);
297 if (currentNode == null && previous instanceof DataNodeContainer) {
298 currentNode = searchInChoices(previous, arg);
300 if (currentNode instanceof DataNodeContainer) {
301 previous = (DataNodeContainer) currentNode;
302 } else if (currentNode instanceof LeafSchemaNode || currentNode instanceof LeafListSchemaNode) {
303 Preconditions.checkState(!iterator.hasNext(), "Path tries to nest inside leaf node.");
307 return (DataSchemaNode) previous;
310 private DataSchemaNode searchInChoices(final DataNodeContainer node, final QName arg) {
311 Set<DataSchemaNode> children = node.getChildNodes();
312 for (DataSchemaNode child : children) {
313 if (child instanceof ChoiceNode) {
314 ChoiceNode choiceNode = (ChoiceNode) child;
315 DataSchemaNode potential = searchInCases(choiceNode, arg);
316 if (potential != null) {
324 private DataSchemaNode searchInCases(final ChoiceNode choiceNode, final QName arg) {
325 Set<ChoiceCaseNode> cases = choiceNode.getCases();
326 for (ChoiceCaseNode caseNode : cases) {
327 DataSchemaNode node = caseNode.getDataChildByName(arg);
335 private static <T> T newInstanceOf(final Class<?> cls) {
337 @SuppressWarnings("unchecked")
338 T ret = (T) cls.newInstance();
340 } catch (InstantiationException e) {
341 LOG.error("Failed to instantiate codec {}", cls.getSimpleName(), e);
342 throw new IllegalStateException(String.format("Failed to instantiate codec %s", cls), e);
343 } catch (IllegalAccessException e) {
345 "Run-time consistency issue: constructor for {} is not available. This indicates either a code generation bug or a misconfiguration of JVM.",
346 cls.getSimpleName(), e);
347 throw new IllegalStateException(String.format("Cannot access contructor of %s", cls), e);
352 public <T extends Identifiable<?>> IdentifierCodec<?> getIdentifierCodecForIdentifiable(final Class<T> type) {
353 IdentifierCodec<?> obj = identifierCodecs.get(type);
357 Class<? extends BindingCodec<Map<QName, Object>, Object>> newCodec = generator
358 .keyTransformerForIdentifiable(type);
359 BindingCodec<Map<QName, Object>, Object> newInstance;
360 newInstance = newInstanceOf(newCodec);
361 IdentifierCodecImpl<?> newWrapper = new IdentifierCodecImpl<>(newInstance);
362 identifierCodecs.put(type, newWrapper);
367 public IdentityCodec<?> getIdentityCodec() {
368 return identityRefCodec;
371 @SuppressWarnings("unchecked")
373 public <T extends BaseIdentity> IdentityCodec<T> getCodecForIdentity(final Class<T> codec) {
374 bindingClassEncountered(codec);
375 return identityRefCodec;
379 public void onCodecCreated(final Class<?> cls) {
380 CodecMapping.setIdentifierCodec(cls, instanceIdentifierCodec);
381 CodecMapping.setIdentityRefCodec(cls, identityRefCodec);
385 public <T extends Identifier<?>> IdentifierCodec<T> getCodecForIdentifier(final Class<T> object) {
386 @SuppressWarnings("unchecked")
387 IdentifierCodec<T> obj = (IdentifierCodec<T>) identifierCodecs.get(object);
391 Class<? extends BindingCodec<Map<QName, Object>, Object>> newCodec = generator
392 .keyTransformerForIdentifier(object);
393 BindingCodec<Map<QName, Object>, Object> newInstance;
394 newInstance = newInstanceOf(newCodec);
395 IdentifierCodecImpl<T> newWrapper = new IdentifierCodecImpl<>(newInstance);
396 identifierCodecs.put(object, newWrapper);
400 @SuppressWarnings("rawtypes")
401 public ChoiceCaseCodecImpl getCaseCodecFor(final Class caseClass) {
402 ChoiceCaseCodecImpl<?> potential = caseCodecs.get(caseClass);
403 if (potential != null) {
406 ConcreteType typeref = Types.typeForClass(caseClass);
407 ChoiceCaseNode caseSchema = caseTypeToCaseSchema.get(typeref);
409 Preconditions.checkState(caseSchema != null, "Case schema is not available for %s", caseClass.getName());
410 Class<? extends BindingCodec> newCodec = generator.caseCodecFor(caseClass, caseSchema);
411 BindingCodec newInstance = newInstanceOf(newCodec);
412 @SuppressWarnings("unchecked")
413 ChoiceCaseCodecImpl caseCodec = new ChoiceCaseCodecImpl(caseClass, caseSchema, newInstance);
414 caseCodecs.put(caseClass, caseCodec);
418 public void onModuleContextAdded(final SchemaContext schemaContext, final Module module, final ModuleContext context) {
419 pathToType.putAll(context.getChildNodes());
421 BiMap<Type, AugmentationSchema> bimap = context.getTypeToAugmentation();
422 for (Map.Entry<Type, AugmentationSchema> entry : bimap.entrySet()) {
423 Type key = entry.getKey();
424 AugmentationSchema value = entry.getValue();
425 Set<DataSchemaNode> augmentedNodes = value.getChildNodes();
426 if (augmentedNodes != null && !(augmentedNodes.isEmpty())) {
427 typeToAugment.put(key, value);
431 qnamesToIdentityMap.putAll(context.getIdentities());
432 for (Entry<QName, GeneratedTOBuilder> identity : context.getIdentities().entrySet()) {
434 new ReferencedTypeImpl(identity.getValue().getPackageName(), identity.getValue().getName()),
438 synchronized (augmentableToAugmentations) {
439 augmentableToAugmentations.putAll(context.getAugmentableToAugmentations());
441 synchronized (choiceToCases) {
442 choiceToCases.putAll(context.getChoiceToCases());
444 synchronized (caseTypeToCaseSchema) {
445 caseTypeToCaseSchema.putAll(context.getCaseTypeToSchemas());
450 public void onGlobalContextUpdated(final SchemaContext context) {
451 currentSchema = context;
452 resetDispatchCodecsAdaptation();
457 * Resets / clears adaptation for all schema context sensitive codecs in
458 * order for them to adapt to new schema context and maybe newly discovered
459 * augmentations This ensure correct behaviour for augmentations and
460 * augmented cases for preexisting codecs, which augmentations were
461 * introduced at later point in time.
463 * This also makes removed augmentations unavailable.
465 private void resetDispatchCodecsAdaptation() {
466 synchronized (dispatchCodecs) {
467 for (LocationAwareDispatchCodec<?> codec : dispatchCodecs.values()) {
468 codec.resetCodec(this);
473 @SuppressWarnings({ "unchecked", "rawtypes" })
475 public void onChoiceCodecCreated(final Class<?> choiceClass,
476 final Class<? extends BindingCodec<Map<QName, Object>, Object>> choiceCodec, final ChoiceNode schema) {
477 ChoiceCodec<?> oldCodec = choiceCodecs.get(choiceClass);
478 Preconditions.checkState(oldCodec == null);
479 BindingCodec<Map<QName, Object>, Object> delegate = newInstanceOf(choiceCodec);
480 PublicChoiceCodecImpl<?> newCodec = new PublicChoiceCodecImpl(delegate);
481 DispatchChoiceCodecImpl dispatchCodec = new DispatchChoiceCodecImpl(choiceClass,this);
482 choiceCodecs.put(choiceClass, newCodec);
483 synchronized (dispatchCodecs) {
484 dispatchCodecs.put(choiceClass, dispatchCodec);
486 CodecMapping.setDispatchCodec(choiceCodec, dispatchCodec);
490 public void onValueCodecCreated(final Class<?> valueClass, final Class<?> valueCodec) {
494 public void onCaseCodecCreated(final Class<?> choiceClass,
495 final Class<? extends BindingCodec<Map<QName, Object>, Object>> choiceCodec) {
499 public void onDataContainerCodecCreated(final Class<?> dataClass,
500 final Class<? extends BindingCodec<?, ?>> dataCodec) {
501 if (Augmentable.class.isAssignableFrom(dataClass)) {
502 AugmentableDispatchCodec augmentableCodec = getAugmentableCodec(dataClass);
503 CodecMapping.setAugmentationCodec(dataCodec, augmentableCodec);
507 public synchronized AugmentableDispatchCodec getAugmentableCodec(final Class<?> dataClass) {
508 AugmentableDispatchCodec ret = augmentableCodecs.get(dataClass);
512 ret = new AugmentableDispatchCodec(dataClass,this);
513 augmentableCodecs.put(dataClass, ret);
514 synchronized (dispatchCodecs) {
515 dispatchCodecs.put(dataClass, ret);
517 ret.tryToLoadImplementations();
521 private static abstract class IntermediateCodec<T> implements //
522 DomCodec<T>, Delegator<BindingCodec<Map<QName, Object>, Object>> {
524 private final BindingCodec<Map<QName, Object>, Object> delegate;
527 public BindingCodec<Map<QName, Object>, Object> getDelegate() {
531 public IntermediateCodec(final BindingCodec<Map<QName, Object>, Object> delegate) {
532 this.delegate = delegate;
536 public Node<?> serialize(final ValueWithQName<T> input) {
537 Map<QName, Object> intermediateOutput = delegate.serialize(input);
538 return IntermediateMapping.toNode(intermediateOutput);
543 private static class IdentifierCodecImpl<T extends Identifier<?>> //
544 extends IntermediateCodec<T> //
545 implements IdentifierCodec<T> {
547 public IdentifierCodecImpl(final BindingCodec<Map<QName, Object>, Object> delegate) {
552 public ValueWithQName<T> deserialize(final Node<?> input) {
553 QName qname = input.getNodeType();
554 @SuppressWarnings("unchecked")
555 T value = (T) getDelegate().deserialize((Map<QName, Object>) input);
556 return new ValueWithQName<T>(qname, value);
560 public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
561 QName qname = input.getNodeType();
562 @SuppressWarnings("unchecked")
563 T value = (T) getDelegate().deserialize((Map<QName, Object>) input, bindingIdentifier);
564 return new ValueWithQName<T>(qname, value);
568 public CompositeNode serialize(final ValueWithQName<T> input) {
569 return (CompositeNode) super.serialize(input);
573 private static class DataContainerCodecImpl<T extends DataContainer> //
574 extends IntermediateCodec<T> //
575 implements DataContainerCodec<T> {
577 public DataContainerCodecImpl(final BindingCodec<Map<QName, Object>, Object> delegate) {
582 public ValueWithQName<T> deserialize(final Node<?> input) {
586 QName qname = input.getNodeType();
587 @SuppressWarnings("unchecked")
588 T value = (T) getDelegate().deserialize((Map<QName, Object>) input);
589 return new ValueWithQName<T>(qname, value);
593 public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
597 QName qname = input.getNodeType();
598 @SuppressWarnings("unchecked")
599 T value = (T) getDelegate().deserialize((Map<QName, Object>) input, bindingIdentifier);
600 return new ValueWithQName<T>(qname, value);
604 public CompositeNode serialize(final ValueWithQName<T> input) {
605 return (CompositeNode) super.serialize(input);
609 private interface LocationAwareBindingCodec<P, I> extends BindingCodec<P, I> {
611 boolean isApplicable(InstanceIdentifier<?> parentPath, CompositeNode data);
613 public Class<?> getDataType();
617 @SuppressWarnings("rawtypes")
618 private static abstract class LocationAwareDispatchCodec<T extends LocationAwareBindingCodec> implements BindingCodec {
620 private final Map<Class, T> implementations = Collections.synchronizedMap(new WeakHashMap<Class, T>());
621 private final Set<InstanceIdentifier<?>> adaptedForPaths = new HashSet<>();
622 private LazyGeneratedCodecRegistry registry;
625 protected LocationAwareDispatchCodec(final LazyGeneratedCodecRegistry registry) {
626 this.registry = registry;
629 protected Map<Class, T> getImplementations() {
630 return implementations;
634 * Resets codec adaptation based on location and schema context.
636 * This is required if new cases / augmentations were introduced or
637 * removed and first use of codec is triggered by invocation from DOM to
638 * Java, so the implementations may change and this may require loading
639 * of new codecs and/or removal of existing ones.
642 public synchronized void resetCodec(final LazyGeneratedCodecRegistry currentRegistry) {
643 registry = currentRegistry;
644 adaptedForPaths.clear();
645 resetAdaptationImpl();
648 protected void resetAdaptationImpl() {
649 // Intentionally NOOP, subclasses may specify their custom
653 protected final LazyGeneratedCodecRegistry getRegistry() {
656 protected void addImplementation(final T implementation) {
657 implementations.put(implementation.getDataType(), implementation);
661 public final Object deserialize(final Object input) {
662 throw new UnsupportedOperationException("Invocation of deserialize without Tree location is unsupported");
666 public final Object deserialize(final Object parent, final InstanceIdentifier parentPath) {
667 adaptForPath(parentPath);
668 Preconditions.checkArgument(parent instanceof CompositeNode, "node must be of CompositeNode type.");
669 CompositeNode parentData = (CompositeNode) parent;
670 ArrayList<T> applicable = new ArrayList<>(implementations.size());
673 * Codecs are filtered to only ones, which
674 * are applicable in supplied parent context.
677 for (T impl : getImplementations().values()) {
678 @SuppressWarnings("unchecked")
679 boolean codecApplicable = impl.isApplicable(parentPath, parentData);
680 if (codecApplicable) {
681 applicable.add(impl);
684 LOG.trace("{}: Deserializing mixins from {}, Schema Location {}, Applicable Codecs: {}, All Codecs: {}",this,parent,parentPath,applicable,getImplementations().values());
686 /* In case of none is applicable, we return
687 * null. Since there is no mixin which
688 * is applicable in this location.
690 if(applicable.isEmpty()) {
693 return deserializeImpl(parentData, parentPath, applicable);
696 protected abstract Object deserializeImpl(final CompositeNode input, final InstanceIdentifier<?> parentPath,
697 Iterable<T> applicableCodecs);
700 public Object serialize(final Object input) {
701 Preconditions.checkArgument(input instanceof DataContainer);
702 Class<? extends DataContainer> inputType = ((DataContainer) input).getImplementedInterface();
703 T implementation = implementations.get(inputType);
704 if (implementation == null) {
705 implementation = tryToLoadImplementationImpl(inputType);
711 private T tryToLoadImplementationImpl(final Class<? extends DataContainer> inputType) {
712 T implementation = tryToLoadImplementation(inputType);
713 Preconditions.checkArgument(implementation != null, "Data type %s is not supported.", inputType);
714 addImplementation(implementation);
715 return implementation;
718 protected final synchronized void adaptForPath(final InstanceIdentifier<?> path) {
719 if (adaptedForPaths.contains(path)) {
722 LOG.debug("Adapting mixin codec {} for path {}",this,path);
724 * We search in schema context if the use of this location aware
725 * codec (augmentable codec, case codec) makes sense on provided
729 Optional<DataNodeContainer> contextNode = BindingSchemaContextUtils.findDataNodeContainer(getRegistry().currentSchema,
732 * If context node is present, this codec makes sense on provided
736 if (contextNode.isPresent()) {
737 synchronized (this) {
740 * We adapt (turn on / off) possible implementations of
741 * child codecs (augmentations, cases) based on this
747 adaptForPathImpl(path, contextNode.get());
750 * We trigger serialization of instance identifier, to
751 * make sure instance identifier codec is aware of
752 * combination of this path / augmentation / case
754 getRegistry().getInstanceIdentifierCodec().serialize(path);
755 } catch (Exception e) {
756 LOG.warn("Exception during preparation of instance identifier codec for path {}.", path, e);
758 adaptedForPaths.add(path);
761 LOG.debug("Context node (parent node) not found for {}", path);
765 protected abstract T tryToLoadImplementation(Class<? extends DataContainer> inputType);
767 protected abstract void tryToLoadImplementations();
769 protected abstract void adaptForPathImpl(InstanceIdentifier<?> path, DataNodeContainer ctx);
772 @SuppressWarnings("rawtypes")
773 private static class ChoiceCaseCodecImpl<T extends DataContainer> implements ChoiceCaseCodec<T>, //
774 Delegator<BindingCodec>, LocationAwareBindingCodec<Node<?>, ValueWithQName<T>> {
775 private final BindingCodec delegate;
776 private final ChoiceCaseNode schema;
777 private final Map<InstanceIdentifier<?>, ChoiceCaseNode> instantiatedLocations;
778 private final Class<?> dataType;
780 public ChoiceCaseCodecImpl(final Class<?> caseClass, final ChoiceCaseNode caseNode,
781 final BindingCodec newInstance) {
782 this.delegate = newInstance;
783 this.dataType = caseClass;
784 this.schema = caseNode;
785 instantiatedLocations = new HashMap<>();
789 public ValueWithQName<T> deserialize(final Node<?> input) {
790 throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
794 public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
798 QName qname = input.getNodeType();
799 synchronized (instantiatedLocations) {
800 ChoiceCaseNode instantiation = instantiatedLocations.get(bindingIdentifier);
801 if (instantiation != null) {
802 qname = instantiatedLocations.get(bindingIdentifier).getQName();
805 @SuppressWarnings("unchecked")
806 T value = (T) getDelegate().deserialize(new SimpleEntry(qname, input), bindingIdentifier);
807 return new ValueWithQName<T>(qname, value);
811 public CompositeNode serialize(final ValueWithQName<T> input) {
812 throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
816 public BindingCodec getDelegate() {
820 public ChoiceCaseNode getSchema() {
826 public boolean isAcceptable(final Node<?> input) {
827 return checkAgainstSchema(schema, input);
830 private static boolean checkAgainstSchema(final ChoiceCaseNode schema, final Node<?> node) {
831 if (node instanceof CompositeNode) {
832 CompositeNode input = (CompositeNode) node;
833 for (Node<?> childNode : input.getValue()) {
834 QName child = childNode.getNodeType();
835 if (schema.getDataChildByName(child) != null) {
844 public Class<?> getDataType() {
848 public void adaptForPath(final InstanceIdentifier<?> augTarget, final ChoiceCaseNode choiceCaseNode) {
849 synchronized (instantiatedLocations) {
850 instantiatedLocations.put(augTarget, choiceCaseNode);
855 public boolean isApplicable(final InstanceIdentifier path, final CompositeNode input) {
856 ChoiceCaseNode instantiatedSchema = null;
857 synchronized (instantiatedLocations) {
858 instantiatedSchema = instantiatedLocations.get(path);
860 if (instantiatedSchema == null) {
863 return checkAgainstSchema(instantiatedSchema, input);
866 protected boolean isAugmenting(final QName choiceName, final QName proposedQName) {
867 if (schema.isAugmenting()) {
871 QName parentQName = Iterables.get(schema.getPath().getPathTowardsRoot(), 1);
872 if (!parentQName.getNamespace().equals(schema.getQName().getNamespace())) {
875 if (!parentQName.equals(choiceName)) {
876 // This item is instantiation of choice via uses in other YANG
878 if (choiceName.getNamespace().equals(schema.getQName())) {
879 // Original definition of grouping is in same namespace
880 // as original definition of case
881 // so for sure case is introduced via instantiation of
885 // Since we are still here, that means case has same namespace
886 // as its parent, which is instantiation of grouping
887 // but case namespace is different from parent node
888 // so it is augmentation.
895 public String toString() {
896 return "ChoiceCaseCodec [case=" + dataType
897 + ", knownLocations=" + instantiatedLocations.keySet() + "]";
901 private static class PublicChoiceCodecImpl<T> implements ChoiceCodec<T>,
902 Delegator<BindingCodec<Map<QName, Object>, Object>> {
904 private final BindingCodec<Map<QName, Object>, Object> delegate;
906 public PublicChoiceCodecImpl(final BindingCodec<Map<QName, Object>, Object> delegate) {
907 this.delegate = delegate;
911 public ValueWithQName<T> deserialize(final Node<?> input) {
912 throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
916 public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
917 throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
921 public Node<?> serialize(final ValueWithQName<T> input) {
922 throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
926 public BindingCodec<Map<QName, Object>, Object> getDelegate() {
932 class DispatchChoiceCodecImpl extends LocationAwareDispatchCodec<ChoiceCaseCodecImpl<?>> {
933 private final Class<?> choiceType;
934 private final QName choiceName;
936 private DispatchChoiceCodecImpl(final Class<?> type, final LazyGeneratedCodecRegistry registry) {
939 choiceName = BindingReflections.findQName(type);
943 public Object deserializeImpl(final CompositeNode input, final InstanceIdentifier<?> path,
944 final Iterable<ChoiceCaseCodecImpl<?>> codecs) {
945 ChoiceCaseCodecImpl<?> caseCodec = Iterables.getOnlyElement(codecs);
946 ValueWithQName<?> value = caseCodec.deserialize(input, path);
948 return value.getValue();
953 @SuppressWarnings("unchecked")
955 public Object serialize(final Object input) {
956 Preconditions.checkArgument(input instanceof Map.Entry<?, ?>, "Input must be QName, Value");
957 @SuppressWarnings("rawtypes")
958 QName derivedQName = (QName) ((Map.Entry) input).getKey();
959 @SuppressWarnings("rawtypes")
960 Object inputValue = ((Map.Entry) input).getValue();
961 Preconditions.checkArgument(inputValue instanceof DataObject);
962 Class<? extends DataContainer> inputType = ((DataObject) inputValue).getImplementedInterface();
963 ChoiceCaseCodecImpl<?> codec = tryToLoadImplementation(inputType);
964 Preconditions.checkState(codec != null, "Unable to get codec for %s", inputType);
965 if (codec.isAugmenting(choiceName, derivedQName)) {
966 // If choice is augmenting we use QName which defined this
968 return codec.getDelegate().serialize(new ValueWithQName<>(codec.getSchema().getQName(), inputValue));
970 return codec.getDelegate().serialize(input);
973 @SuppressWarnings("rawtypes")
974 protected Optional<ChoiceCaseCodecImpl> tryToLoadImplementation(final Type potential) {
976 @SuppressWarnings("unchecked")
977 Class<? extends DataContainer> clazz = (Class<? extends DataContainer>) classLoadingStrategy
978 .loadClass(potential);
979 ChoiceCaseCodecImpl codec = tryToLoadImplementation(clazz);
980 addImplementation(codec);
981 return Optional.of(codec);
982 } catch (ClassNotFoundException e) {
983 LOG.warn("Failed to find class for choice {}", potential, e);
985 return Optional.absent();
989 protected ChoiceCaseCodecImpl<?> tryToLoadImplementation(final Class<? extends DataContainer> inputType) {
990 ChoiceCaseCodecImpl<?> codec = getCaseCodecFor(inputType);
991 addImplementation(codec);
996 protected void tryToLoadImplementations() {
997 Type type = referencedType(choiceType);
998 Collection<Type> potentialCases;
999 synchronized (choiceToCases) {
1000 potentialCases = choiceToCases.get(type);
1002 for (Type potential : potentialCases) {
1004 tryToLoadImplementation(potential);
1005 } catch (CodeGenerationException e) {
1006 LOG.warn("Failed to proactively generate choice code for {}", type, e);
1012 protected void adaptForPathImpl(final InstanceIdentifier<?> augTarget, final DataNodeContainer ctxNode) {
1013 Optional<ChoiceNode> newChoice = BindingSchemaContextUtils.findInstantiatedChoice(ctxNode, choiceType);
1014 tryToLoadImplementations();
1015 Preconditions.checkState(newChoice.isPresent(), "BUG: Unable to find instantiated choice node in schema.");
1016 for (@SuppressWarnings("rawtypes")
1017 Entry<Class, ChoiceCaseCodecImpl<?>> codec : getImplementations().entrySet()) {
1018 ChoiceCaseCodecImpl<?> caseCodec = codec.getValue();
1019 Optional<ChoiceCaseNode> instantiatedSchema = BindingSchemaContextUtils.findInstantiatedCase(newChoice.get(),
1020 caseCodec.getSchema());
1021 if (instantiatedSchema.isPresent()) {
1022 caseCodec.adaptForPath(augTarget, instantiatedSchema.get());
1030 public String toString() {
1031 return "DispatchChoiceCodecImpl [choiceType=" + choiceType + "]";
1035 @SuppressWarnings({ "rawtypes", "unchecked" })
1036 static class AugmentableDispatchCodec extends LocationAwareDispatchCodec<AugmentationCodecWrapper> {
1038 private final Class augmentableType;
1040 public AugmentableDispatchCodec(final Class type, final LazyGeneratedCodecRegistry registry) {
1042 Preconditions.checkArgument(Augmentable.class.isAssignableFrom(type));
1043 augmentableType = type;
1047 // TODO deprecate use without iid
1048 public Object serialize(final Object input) {
1049 if (input instanceof Augmentable<?>) {
1050 Map<Class, Augmentation> augmentations = getAugmentations(input);
1051 return serializeImpl(augmentations);
1056 private Map<Class, Augmentation> getAugmentations(final Object input) {
1057 Field augmentationField;
1059 augmentationField = input.getClass().getDeclaredField("augmentation");
1060 augmentationField.setAccessible(true);
1061 Map<Class, Augmentation> augMap = (Map<Class, Augmentation>) augmentationField.get(input);
1063 } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {
1064 LOG.debug("Could not read augmentations for {}", input, e);
1066 return Collections.emptyMap();
1069 @SuppressWarnings("deprecation")
1070 private List serializeImpl(final Map<Class, Augmentation> input) {
1071 List ret = new ArrayList<>();
1072 for (Entry<Class, Augmentation> entry : input.entrySet()) {
1073 AugmentationCodec codec = getRegistry().getCodecForAugmentation(entry.getKey());
1074 CompositeNode node = codec.serialize(new ValueWithQName(null, entry.getValue()));
1075 ret.addAll(node.getChildren());
1081 public Map<Class, Augmentation> deserializeImpl(final CompositeNode input, final InstanceIdentifier<?> path,
1082 final Iterable<AugmentationCodecWrapper> codecs) {
1083 LOG.trace("{}: Going to deserialize augmentations from {} in location {}. Available codecs {}",this,input,path,codecs);
1084 Map<Class, Augmentation> ret = new HashMap<>();
1085 for (AugmentationCodecWrapper codec : codecs) {
1086 // We add Augmentation Identifier to path, in order to
1087 // correctly identify children.
1088 Class type = codec.getDataType();
1089 final InstanceIdentifier augmentPath = path.augmentation(type);
1090 ValueWithQName<?> value = codec.deserialize(input, augmentPath);
1091 if (value != null && value.getValue() != null) {
1092 ret.put(type, (Augmentation) value.getValue());
1098 protected Optional<AugmentationCodecWrapper> tryToLoadImplementation(final Type potential) {
1100 Class<? extends Augmentation<?>> clazz = (Class<? extends Augmentation<?>>) getRegistry().classLoadingStrategy
1101 .loadClass(potential);
1102 return Optional.of(tryToLoadImplementation(clazz));
1103 } catch (ClassNotFoundException e) {
1104 LOG.warn("Failed to find class for augmentation of {}", potential, e);
1106 return Optional.absent();
1110 protected AugmentationCodecWrapper tryToLoadImplementation(final Class inputType) {
1111 AugmentationCodecWrapper<? extends Augmentation<?>> potentialImpl = getRegistry().getCodecForAugmentation(inputType);
1112 addImplementation(potentialImpl);
1113 return potentialImpl;
1117 protected void tryToLoadImplementations() {
1118 Type type = referencedType(augmentableType);
1119 Collection<Type> potentialAugmentations;
1120 synchronized (augmentableToAugmentations) {
1121 potentialAugmentations = new ArrayList(augmentableToAugmentations.get(type));
1123 for (Type potential : potentialAugmentations) {
1125 tryToLoadImplementation(potential);
1126 } catch (CodeGenerationException e) {
1127 LOG.warn("Failed to proactively generate augment code for {}", type, e);
1133 protected void adaptForPathImpl(final InstanceIdentifier<?> augTarget, final DataNodeContainer ctxNode) {
1134 if (ctxNode instanceof AugmentationTarget) {
1135 Set<AugmentationSchema> availableAugmentations = ((AugmentationTarget) ctxNode)
1136 .getAvailableAugmentations();
1137 if (!availableAugmentations.isEmpty()) {
1138 updateAugmentationMapping(augTarget, availableAugmentations);
1145 * Adapts augmentation codec for specific provider location (target)
1147 * Since augmentation are not forward-referencing and may be discovered
1148 * during runtime, we need to adapt {@link AugmentableDispatchCodec},
1149 * {@link AugmentationCodecWrapper} and {@link InstanceIdentifierCodec}
1150 * for this newly discovered location where augmentation may be used.
1152 * Adaptation consists of:
1154 * <li>scan of available (valid) augmentations for current location
1155 * <li>lookup for Java classes derived from this augmentations
1156 * <li>generation of missing codecs
1157 * <li>updating Augmentation codecs to work with new location
1158 * <li>updating Instance Identifier to work with new location
1161 private void updateAugmentationMapping(final InstanceIdentifier<?> augTarget,
1162 final Set<AugmentationSchema> availableAugmentations) {
1163 for (AugmentationSchema aug : availableAugmentations) {
1165 Type potentialType = getTypeForAugmentation(aug);
1166 if (potentialType != null) {
1167 Optional<AugmentationCodecWrapper> potentialImpl = tryToLoadImplementation(potentialType);
1168 if (potentialImpl.isPresent()) {
1169 potentialImpl.get().addApplicableFor(augTarget, aug);
1170 Class augType = potentialImpl.get().getDataType();
1171 InstanceIdentifier augPath = augTarget.augmentation(augType);
1174 org.opendaylight.yangtools.yang.data.api.InstanceIdentifier domPath = getRegistry().getInstanceIdentifierCodec()
1175 .serialize(augPath);
1176 if (domPath == null) {
1177 LOG.error("Unable to serialize instance identifier for {}", augPath);
1179 } catch (Exception e) {
1180 LOG.error("Unable to serialize instance identifiers for {}", augPath, e);
1185 // Omits warning for empty augmentations since they are not
1186 // represented in data
1187 if (!aug.getChildNodes().isEmpty()) {
1188 LOG.warn("Could not find generated type for augmentation {} with children {}", aug,
1189 aug.getChildNodes());
1195 private Type getTypeForAugmentation(final AugmentationSchema aug) {
1196 Optional<AugmentationSchema> currentAug = Optional.of(aug);
1197 while (currentAug.isPresent()) {
1198 Type potentialType = typeToAugment.inverse().get(currentAug.get());
1199 if (potentialType != null) {
1200 return potentialType;
1202 currentAug = currentAug.get().getOriginalDefinition();
1208 public String toString() {
1209 return "AugmentableDispatchCodec [augmentable=" + augmentableType + "]";
1214 @SuppressWarnings("rawtypes")
1215 private static class AugmentationCodecWrapper<T extends Augmentation<?>> implements AugmentationCodec<T>,
1216 Delegator<BindingCodec>, LocationAwareBindingCodec<Node<?>, ValueWithQName<T>> {
1218 private final BindingCodec delegate;
1219 private final QName augmentationQName;
1220 private final Multimap<InstanceIdentifier<?>, QName> validAugmentationTargets;
1221 private final Class<?> augmentationType;
1223 public AugmentationCodecWrapper(final BindingCodec<Map<QName, Object>, Object> rawCodec, final Class<?> dataType) {
1224 this.delegate = rawCodec;
1225 this.augmentationType = dataType;
1226 this.augmentationQName = BindingReflections.findQName(rawCodec.getClass());
1227 this.validAugmentationTargets = Multimaps.synchronizedSetMultimap(HashMultimap
1228 .<InstanceIdentifier<?>, QName> create());
1231 public void addApplicableFor(final InstanceIdentifier<?> path, final AugmentationSchema aug) {
1232 for (DataSchemaNode child : aug.getChildNodes()) {
1233 validAugmentationTargets.put(path, child.getQName());
1238 public BindingCodec getDelegate() {
1243 public CompositeNode serialize(final ValueWithQName<T> input) {
1244 @SuppressWarnings("unchecked")
1245 List<Map<QName, Object>> rawValues = (List<Map<QName, Object>>) getDelegate().serialize(input);
1246 List<Node<?>> serialized = new ArrayList<>(rawValues.size());
1247 for (Map<QName, Object> val : rawValues) {
1248 serialized.add(IntermediateMapping.toNode(val));
1250 return new CompositeNodeTOImpl(input.getQname(), null, serialized);
1254 @SuppressWarnings("unchecked")
1255 public ValueWithQName<T> deserialize(final Node<?> input) {
1256 Object rawCodecValue = getDelegate().deserialize(input);
1257 return new ValueWithQName<T>(input.getNodeType(), (T) rawCodecValue);
1261 @SuppressWarnings("unchecked")
1262 public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
1263 Object rawCodecValue = getDelegate().deserialize(input, bindingIdentifier);
1264 return new ValueWithQName<T>(input.getNodeType(), (T) rawCodecValue);
1268 public QName getAugmentationQName() {
1269 return augmentationQName;
1273 public boolean isAcceptable(final InstanceIdentifier<?> path) {
1277 return validAugmentationTargets.containsKey(path);
1281 public boolean isApplicable(final InstanceIdentifier parentPath,final CompositeNode parentData) {
1282 return isAcceptable(parentPath);
1286 public Class<?> getDataType() {
1287 return augmentationType;
1291 public String toString() {
1292 return "AugmentationCodecWrapper [augmentation=" + augmentationType
1293 + ", knownLocations=" + validAugmentationTargets.keySet() + "]";
1297 @SuppressWarnings("rawtypes")
1298 private class IdentityCompositeCodec implements IdentityCodec {
1301 public Object deserialize(final Object input) {
1302 Preconditions.checkArgument(input instanceof QName);
1303 return deserialize((QName) input);
1307 public Class<?> deserialize(final QName input) {
1311 Type type = qnamesToIdentityMap.get(input);
1313 String packageName = BindingMapping.getRootPackageName(input);
1314 String className = BindingMapping.getClassName(input);
1315 type = new ReferencedTypeImpl(packageName, className);
1317 ReferencedTypeImpl typeref = new ReferencedTypeImpl(type.getPackageName(), type.getName());
1318 WeakReference<Class> softref = typeToClass.get(typeref);
1319 if (softref == null) {
1322 Class<?> cls = classLoadingStrategy.loadClass(typeref.getFullyQualifiedName());
1327 } catch (Exception e) {
1328 LOG.warn("Identity {} was not deserialized, because of missing class {}", input,
1329 typeref.getFullyQualifiedName());
1333 return softref.get();
1337 public Object deserialize(final Object input, final InstanceIdentifier bindingIdentifier) {
1338 Type type = qnamesToIdentityMap.get(input);
1340 throw new IllegalArgumentException( "Invalid for \"" + input + "\"." );
1342 ReferencedTypeImpl typeref = new ReferencedTypeImpl(type.getPackageName(), type.getName());
1343 WeakReference<Class> softref = typeToClass.get(typeref);
1344 if (softref == null) {
1347 Class<?> cls = classLoadingStrategy.loadClass(typeref.getFullyQualifiedName());
1352 } catch (Exception e) {
1353 LOG.warn("Identity {} was not deserialized, because of missing class {}", input,
1354 typeref.getFullyQualifiedName());
1358 return softref.get();
1362 public QName serialize(final Class input) {
1363 Preconditions.checkArgument(BaseIdentity.class.isAssignableFrom(input));
1364 bindingClassEncountered(input);
1365 QName qname = identityQNames.get(input);
1366 if (qname != null) {
1369 qname = BindingReflections.findQName(input);
1370 if (qname != null) {
1371 identityQNames.put(input, qname);
1377 public Object serialize(final Object input) {
1378 Preconditions.checkArgument(input instanceof Class);
1379 return serialize((Class) input);
1384 private static final Type referencedType(final Class<?> augmentableType) {
1385 return new ReferencedTypeImpl(augmentableType.getPackage().getName(), augmentableType.getSimpleName());