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.SchemaPath;
72 import org.slf4j.Logger;
73 import org.slf4j.LoggerFactory;
75 import com.google.common.base.Optional;
76 import com.google.common.base.Preconditions;
77 import com.google.common.collect.BiMap;
78 import com.google.common.collect.HashBiMap;
79 import com.google.common.collect.HashMultimap;
80 import com.google.common.collect.Iterables;
81 import com.google.common.collect.Multimap;
82 import com.google.common.collect.Multimaps;
84 class LazyGeneratedCodecRegistry implements //
86 SchemaContextListener, //
89 private static final Logger LOG = LoggerFactory.getLogger(LazyGeneratedCodecRegistry.class);
91 // Concrete class to codecs
92 private static final Map<Class<?>, DataContainerCodec<?>> containerCodecs = Collections
93 .synchronizedMap(new WeakHashMap<Class<?>, DataContainerCodec<?>>());
94 private static final Map<Class<?>, IdentifierCodec<?>> identifierCodecs = Collections
95 .synchronizedMap(new WeakHashMap<Class<?>, IdentifierCodec<?>>());
96 private static final Map<Class<?>, PublicChoiceCodecImpl<?>> choiceCodecs = Collections
97 .synchronizedMap(new WeakHashMap<Class<?>, PublicChoiceCodecImpl<?>>());
98 private static final Map<Class<?>, ChoiceCaseCodecImpl<?>> caseCodecs = Collections
99 .synchronizedMap(new WeakHashMap<Class<?>, ChoiceCaseCodecImpl<?>>());
100 private static final Map<Class<?>, AugmentableDispatchCodec> augmentableCodecs = Collections
101 .synchronizedMap(new WeakHashMap<Class<?>, AugmentableDispatchCodec>());
102 private static final Map<Class<?>, AugmentationCodecWrapper<?>> augmentationCodecs = Collections
103 .synchronizedMap(new WeakHashMap<Class<?>, AugmentationCodecWrapper<?>>());
105 private static final Map<Class<?>, LocationAwareDispatchCodec<?>> dispatchCodecs = Collections
106 .synchronizedMap(new WeakHashMap<Class<?>, LocationAwareDispatchCodec<?>>());
108 private static final Map<Class<?>, QName> identityQNames = Collections
109 .synchronizedMap(new WeakHashMap<Class<?>, QName>());
110 private static final Map<QName, Type> qnamesToIdentityMap = new ConcurrentHashMap<>();
111 /** Binding type to encountered classes mapping **/
112 @SuppressWarnings("rawtypes")
113 private static final Map<Type, WeakReference<Class>> typeToClass = new ConcurrentHashMap<>();
115 private static final ConcurrentMap<Type, ChoiceCaseNode> caseTypeToCaseSchema = new ConcurrentHashMap<>();
117 private static final Map<SchemaPath, Type> pathToType = new ConcurrentHashMap<>();
118 private static final Map<List<QName>, Type> pathToInstantiatedType = new ConcurrentHashMap<>();
119 private static final Map<Type, QName> typeToQname = new ConcurrentHashMap<>();
120 private static final BiMap<Type, AugmentationSchema> typeToAugment = HashBiMap
121 .create(new ConcurrentHashMap<Type, AugmentationSchema>());
123 private static final Multimap<Type, Type> augmentableToAugmentations = Multimaps.synchronizedMultimap(HashMultimap
124 .<Type, Type> create());
125 private static final Multimap<Type, Type> choiceToCases = Multimaps.synchronizedMultimap(HashMultimap
126 .<Type, Type> create());
128 private final InstanceIdentifierCodec instanceIdentifierCodec = new InstanceIdentifierCodecImpl(this);
129 private final IdentityCompositeCodec identityRefCodec = new IdentityCompositeCodec();
130 private final ClassLoadingStrategy classLoadingStrategy;
131 private final AbstractTransformerGenerator generator;
132 private final SchemaLock lock;
134 // FIXME: how is this protected?
135 private SchemaContext currentSchema;
137 LazyGeneratedCodecRegistry(final SchemaLock lock, final AbstractTransformerGenerator generator,
138 final ClassLoadingStrategy classLoadingStrategy) {
139 this.lock = Preconditions.checkNotNull(lock);
140 this.classLoadingStrategy = Preconditions.checkNotNull(classLoadingStrategy);
141 this.generator = Preconditions.checkNotNull(generator);
144 public SchemaLock getLock() {
149 public InstanceIdentifierCodec getInstanceIdentifierCodec() {
150 return instanceIdentifierCodec;
153 @SuppressWarnings("unchecked")
155 public <T extends Augmentation<?>> AugmentationCodecWrapper<T> getCodecForAugmentation(final Class<T> augClass) {
156 AugmentationCodecWrapper<T> codec = null;
157 @SuppressWarnings("rawtypes")
158 AugmentationCodecWrapper potentialCodec = augmentationCodecs.get(augClass);
159 if (potentialCodec != null) {
160 codec = potentialCodec;
162 lock.waitForSchema(augClass);
163 Class<? extends BindingCodec<Map<QName, Object>, Object>> augmentRawCodec = generator
164 .augmentationTransformerFor(augClass);
166 BindingCodec<Map<QName, Object>, Object> rawCodec = newInstanceOf(augmentRawCodec);
167 codec = new AugmentationCodecWrapper<T>(rawCodec, augClass);
168 augmentationCodecs.put(augClass, codec);
171 final Class<? extends Augmentable<?>> objectSupertype;
173 objectSupertype = BindingReflections.findAugmentationTarget(augClass);
174 } catch (Exception e) {
175 LOG.warn("Failed to find target for augmentation {}, ignoring it", augClass, e);
179 if (objectSupertype == null) {
180 LOG.warn("Augmentation target for {} not found, ignoring it", augClass);
184 getAugmentableCodec(objectSupertype).addImplementation(codec);
188 @SuppressWarnings("unchecked")
190 public QName getQNameForAugmentation(final Class<?> cls) {
191 Preconditions.checkArgument(Augmentation.class.isAssignableFrom(cls));
192 return getCodecForAugmentation((Class<? extends Augmentation<?>>) cls).getAugmentationQName();
196 public Class<?> getClassForPath(final List<QName> names) {
197 final DataSchemaNode node = getSchemaNode(names);
198 final SchemaPath path = node.getPath();
199 final Type t = pathToType.get(path);
203 type = new ReferencedTypeImpl(t.getPackageName(), t.getName());
205 type = pathToInstantiatedType.get(names);
206 Preconditions.checkState(type != null, "Failed to lookup instantiated type for path %s", path);
209 @SuppressWarnings("rawtypes")
210 final WeakReference<Class> weakRef = typeToClass.get(type);
211 Preconditions.checkState(weakRef != null, "Could not find loaded class for path: %s and type: %s", path,
212 type.getFullyQualifiedName());
213 return weakRef.get();
217 public void putPathToClass(final List<QName> names, final Class<?> cls) {
218 final Type reference = Types.typeForClass(cls);
219 pathToInstantiatedType.put(names, reference);
220 LOG.trace("Path {} attached to class {} reference {}", names, cls, reference);
221 bindingClassEncountered(cls);
225 public IdentifierCodec<?> getKeyCodecForPath(final List<QName> names) {
226 @SuppressWarnings("unchecked")
227 Class<? extends Identifiable<?>> cls = (Class<? extends Identifiable<?>>) getClassForPath(names);
228 return getIdentifierCodecForIdentifiable(cls);
232 public <T extends DataContainer> DataContainerCodec<T> getCodecForDataObject(final Class<T> type) {
233 @SuppressWarnings("unchecked")
234 DataContainerCodec<T> ret = (DataContainerCodec<T>) containerCodecs.get(type);
238 Class<? extends BindingCodec<Map<QName, Object>, Object>> newType = generator.transformerFor(type);
239 BindingCodec<Map<QName, Object>, Object> rawCodec = newInstanceOf(newType);
240 DataContainerCodecImpl<T> newWrapper = new DataContainerCodecImpl<>(rawCodec);
241 containerCodecs.put(type, newWrapper);
246 @SuppressWarnings("rawtypes")
247 public void bindingClassEncountered(final Class cls) {
249 ConcreteType typeRef = Types.typeForClass(cls);
250 if (typeToClass.containsKey(typeRef)) {
253 LOG.trace("Binding Class {} encountered.", cls);
254 WeakReference<Class> weakRef = new WeakReference<>(cls);
255 typeToClass.put(typeRef, weakRef);
256 if (Augmentation.class.isAssignableFrom(cls)) {
258 } else if (DataObject.class.isAssignableFrom(cls)) {
259 getCodecForDataObject((Class<? extends DataObject>) cls);
264 public void onClassProcessed(final Class<?> cls) {
265 ConcreteType typeRef = Types.typeForClass(cls);
266 if (typeToClass.containsKey(typeRef)) {
269 LOG.trace("Binding Class {} encountered.", cls);
270 @SuppressWarnings("rawtypes")
271 WeakReference<Class> weakRef = new WeakReference<Class>(cls);
272 typeToClass.put(typeRef, weakRef);
275 private DataSchemaNode getSchemaNode(final List<QName> path) {
276 QName firstNode = path.get(0);
277 DataNodeContainer previous = currentSchema.findModuleByNamespaceAndRevision(firstNode.getNamespace(),
278 firstNode.getRevision());
279 Preconditions.checkArgument(previous != null, "Failed to find module %s for path %s", firstNode, path);
281 Iterator<QName> iterator = path.iterator();
282 while (iterator.hasNext()) {
283 QName arg = iterator.next();
284 DataSchemaNode currentNode = previous.getDataChildByName(arg);
285 if (currentNode == null && previous instanceof DataNodeContainer) {
286 currentNode = searchInChoices(previous, arg);
288 if (currentNode instanceof DataNodeContainer) {
289 previous = (DataNodeContainer) currentNode;
290 } else if (currentNode instanceof LeafSchemaNode || currentNode instanceof LeafListSchemaNode) {
291 Preconditions.checkState(!iterator.hasNext(), "Path tries to nest inside leaf node.");
295 return (DataSchemaNode) previous;
298 private DataSchemaNode searchInChoices(final DataNodeContainer node, final QName arg) {
299 Set<DataSchemaNode> children = node.getChildNodes();
300 for (DataSchemaNode child : children) {
301 if (child instanceof ChoiceNode) {
302 ChoiceNode choiceNode = (ChoiceNode) child;
303 DataSchemaNode potential = searchInCases(choiceNode, arg);
304 if (potential != null) {
312 private DataSchemaNode searchInCases(final ChoiceNode choiceNode, final QName arg) {
313 Set<ChoiceCaseNode> cases = choiceNode.getCases();
314 for (ChoiceCaseNode caseNode : cases) {
315 DataSchemaNode node = caseNode.getDataChildByName(arg);
323 private static <T> T newInstanceOf(final Class<?> cls) {
325 @SuppressWarnings("unchecked")
326 T ret = (T) cls.newInstance();
328 } catch (InstantiationException e) {
329 LOG.error("Failed to instantiate codec {}", cls.getSimpleName(), e);
330 throw new IllegalStateException(String.format("Failed to instantiate codec %s", cls), e);
331 } catch (IllegalAccessException e) {
333 "Run-time consistency issue: constructor for {} is not available. This indicates either a code generation bug or a misconfiguration of JVM.",
334 cls.getSimpleName(), e);
335 throw new IllegalStateException(String.format("Cannot access contructor of %s", cls), e);
340 public <T extends Identifiable<?>> IdentifierCodec<?> getIdentifierCodecForIdentifiable(final Class<T> type) {
341 IdentifierCodec<?> obj = identifierCodecs.get(type);
345 Class<? extends BindingCodec<Map<QName, Object>, Object>> newCodec = generator
346 .keyTransformerForIdentifiable(type);
347 BindingCodec<Map<QName, Object>, Object> newInstance;
348 newInstance = newInstanceOf(newCodec);
349 IdentifierCodecImpl<?> newWrapper = new IdentifierCodecImpl<>(newInstance);
350 identifierCodecs.put(type, newWrapper);
355 public IdentityCodec<?> getIdentityCodec() {
356 return identityRefCodec;
359 @SuppressWarnings("unchecked")
361 public <T extends BaseIdentity> IdentityCodec<T> getCodecForIdentity(final Class<T> codec) {
362 bindingClassEncountered(codec);
363 return identityRefCodec;
367 public void onCodecCreated(final Class<?> cls) {
368 CodecMapping.setIdentifierCodec(cls, instanceIdentifierCodec);
369 CodecMapping.setIdentityRefCodec(cls, identityRefCodec);
373 public <T extends Identifier<?>> IdentifierCodec<T> getCodecForIdentifier(final Class<T> object) {
374 @SuppressWarnings("unchecked")
375 IdentifierCodec<T> obj = (IdentifierCodec<T>) identifierCodecs.get(object);
379 Class<? extends BindingCodec<Map<QName, Object>, Object>> newCodec = generator
380 .keyTransformerForIdentifier(object);
381 BindingCodec<Map<QName, Object>, Object> newInstance;
382 newInstance = newInstanceOf(newCodec);
383 IdentifierCodecImpl<T> newWrapper = new IdentifierCodecImpl<>(newInstance);
384 identifierCodecs.put(object, newWrapper);
388 @SuppressWarnings("rawtypes")
389 public ChoiceCaseCodecImpl getCaseCodecFor(final Class caseClass) {
390 ChoiceCaseCodecImpl<?> potential = caseCodecs.get(caseClass);
391 if (potential != null) {
394 ConcreteType typeref = Types.typeForClass(caseClass);
395 ChoiceCaseNode caseSchema = caseTypeToCaseSchema.get(typeref);
397 Preconditions.checkState(caseSchema != null, "Case schema is not available for %s", caseClass.getName());
398 Class<? extends BindingCodec> newCodec = generator.caseCodecFor(caseClass, caseSchema);
399 BindingCodec newInstance = newInstanceOf(newCodec);
400 @SuppressWarnings("unchecked")
401 ChoiceCaseCodecImpl caseCodec = new ChoiceCaseCodecImpl(caseClass, caseSchema, newInstance);
402 caseCodecs.put(caseClass, caseCodec);
406 public void onModuleContextAdded(final SchemaContext schemaContext, final Module module, final ModuleContext context) {
407 pathToType.putAll(context.getChildNodes());
409 BiMap<Type, AugmentationSchema> bimap = context.getTypeToAugmentation();
410 for (Map.Entry<Type, AugmentationSchema> entry : bimap.entrySet()) {
411 Type key = entry.getKey();
412 AugmentationSchema value = entry.getValue();
413 Set<DataSchemaNode> augmentedNodes = value.getChildNodes();
414 if (augmentedNodes != null && !(augmentedNodes.isEmpty())) {
415 typeToAugment.put(key, value);
419 qnamesToIdentityMap.putAll(context.getIdentities());
420 for (Entry<QName, GeneratedTOBuilder> identity : context.getIdentities().entrySet()) {
422 new ReferencedTypeImpl(identity.getValue().getPackageName(), identity.getValue().getName()),
426 synchronized (augmentableToAugmentations) {
427 augmentableToAugmentations.putAll(context.getAugmentableToAugmentations());
429 synchronized (choiceToCases) {
430 choiceToCases.putAll(context.getChoiceToCases());
432 synchronized (caseTypeToCaseSchema) {
433 caseTypeToCaseSchema.putAll(context.getCaseTypeToSchemas());
438 public void onGlobalContextUpdated(final SchemaContext context) {
439 currentSchema = context;
440 resetDispatchCodecsAdaptation();
445 * Resets / clears adaptation for all schema context sensitive codecs in
446 * order for them to adapt to new schema context and maybe newly discovered
447 * augmentations This ensure correct behaviour for augmentations and
448 * augmented cases for preexisting codecs, which augmentations were
449 * introduced at later point in time.
451 * This also makes removed augmentations unavailable.
453 private void resetDispatchCodecsAdaptation() {
454 synchronized (dispatchCodecs) {
455 for (LocationAwareDispatchCodec<?> codec : dispatchCodecs.values()) {
456 codec.resetCodec(this);
461 @SuppressWarnings({ "unchecked", "rawtypes" })
463 public void onChoiceCodecCreated(final Class<?> choiceClass,
464 final Class<? extends BindingCodec<Map<QName, Object>, Object>> choiceCodec, final ChoiceNode schema) {
465 ChoiceCodec<?> oldCodec = choiceCodecs.get(choiceClass);
466 Preconditions.checkState(oldCodec == null);
467 BindingCodec<Map<QName, Object>, Object> delegate = newInstanceOf(choiceCodec);
468 PublicChoiceCodecImpl<?> newCodec = new PublicChoiceCodecImpl(delegate);
469 DispatchChoiceCodecImpl dispatchCodec = new DispatchChoiceCodecImpl(choiceClass,this);
470 choiceCodecs.put(choiceClass, newCodec);
471 synchronized (dispatchCodecs) {
472 dispatchCodecs.put(choiceClass, dispatchCodec);
474 CodecMapping.setDispatchCodec(choiceCodec, dispatchCodec);
478 public void onValueCodecCreated(final Class<?> valueClass, final Class<?> valueCodec) {
482 public void onCaseCodecCreated(final Class<?> choiceClass,
483 final Class<? extends BindingCodec<Map<QName, Object>, Object>> choiceCodec) {
487 public void onDataContainerCodecCreated(final Class<?> dataClass,
488 final Class<? extends BindingCodec<?, ?>> dataCodec) {
489 if (Augmentable.class.isAssignableFrom(dataClass)) {
490 AugmentableDispatchCodec augmentableCodec = getAugmentableCodec(dataClass);
491 CodecMapping.setAugmentationCodec(dataCodec, augmentableCodec);
495 public synchronized AugmentableDispatchCodec getAugmentableCodec(final Class<?> dataClass) {
496 AugmentableDispatchCodec ret = augmentableCodecs.get(dataClass);
500 ret = new AugmentableDispatchCodec(dataClass,this);
501 augmentableCodecs.put(dataClass, ret);
502 synchronized (dispatchCodecs) {
503 dispatchCodecs.put(dataClass, ret);
505 ret.tryToLoadImplementations();
509 private static abstract class IntermediateCodec<T> implements //
510 DomCodec<T>, Delegator<BindingCodec<Map<QName, Object>, Object>> {
512 private final BindingCodec<Map<QName, Object>, Object> delegate;
515 public BindingCodec<Map<QName, Object>, Object> getDelegate() {
519 public IntermediateCodec(final BindingCodec<Map<QName, Object>, Object> delegate) {
520 this.delegate = delegate;
524 public Node<?> serialize(final ValueWithQName<T> input) {
525 Map<QName, Object> intermediateOutput = delegate.serialize(input);
526 return IntermediateMapping.toNode(intermediateOutput);
531 private static class IdentifierCodecImpl<T extends Identifier<?>> //
532 extends IntermediateCodec<T> //
533 implements IdentifierCodec<T> {
535 public IdentifierCodecImpl(final BindingCodec<Map<QName, Object>, Object> delegate) {
540 public ValueWithQName<T> deserialize(final Node<?> input) {
541 QName qname = input.getNodeType();
542 @SuppressWarnings("unchecked")
543 T value = (T) getDelegate().deserialize((Map<QName, Object>) input);
544 return new ValueWithQName<T>(qname, value);
548 public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
549 QName qname = input.getNodeType();
550 @SuppressWarnings("unchecked")
551 T value = (T) getDelegate().deserialize((Map<QName, Object>) input, bindingIdentifier);
552 return new ValueWithQName<T>(qname, value);
556 public CompositeNode serialize(final ValueWithQName<T> input) {
557 return (CompositeNode) super.serialize(input);
561 private static class DataContainerCodecImpl<T extends DataContainer> //
562 extends IntermediateCodec<T> //
563 implements DataContainerCodec<T> {
565 public DataContainerCodecImpl(final BindingCodec<Map<QName, Object>, Object> delegate) {
570 public ValueWithQName<T> deserialize(final Node<?> input) {
574 QName qname = input.getNodeType();
575 @SuppressWarnings("unchecked")
576 T value = (T) getDelegate().deserialize((Map<QName, Object>) input);
577 return new ValueWithQName<T>(qname, value);
581 public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
585 QName qname = input.getNodeType();
586 @SuppressWarnings("unchecked")
587 T value = (T) getDelegate().deserialize((Map<QName, Object>) input, bindingIdentifier);
588 return new ValueWithQName<T>(qname, value);
592 public CompositeNode serialize(final ValueWithQName<T> input) {
593 return (CompositeNode) super.serialize(input);
597 private interface LocationAwareBindingCodec<P, I> extends BindingCodec<P, I> {
599 boolean isApplicable(InstanceIdentifier<?> parentPath, CompositeNode data);
601 public Class<?> getDataType();
605 @SuppressWarnings("rawtypes")
606 private static abstract class LocationAwareDispatchCodec<T extends LocationAwareBindingCodec> implements BindingCodec {
608 private final Map<Class, T> implementations = Collections.synchronizedMap(new WeakHashMap<Class, T>());
609 private final Set<InstanceIdentifier<?>> adaptedForPaths = new HashSet<>();
610 private LazyGeneratedCodecRegistry registry;
613 protected LocationAwareDispatchCodec(final LazyGeneratedCodecRegistry registry) {
614 this.registry = registry;
617 protected Map<Class, T> getImplementations() {
618 return implementations;
622 * Resets codec adaptation based on location and schema context.
624 * This is required if new cases / augmentations were introduced or
625 * removed and first use of codec is triggered by invocation from DOM to
626 * Java, so the implementations may change and this may require loading
627 * of new codecs and/or removal of existing ones.
630 public synchronized void resetCodec(final LazyGeneratedCodecRegistry currentRegistry) {
631 registry = currentRegistry;
632 adaptedForPaths.clear();
633 resetAdaptationImpl();
636 protected void resetAdaptationImpl() {
637 // Intentionally NOOP, subclasses may specify their custom
641 protected final LazyGeneratedCodecRegistry getRegistry() {
644 protected void addImplementation(final T implementation) {
645 implementations.put(implementation.getDataType(), implementation);
649 public final Object deserialize(final Object input) {
650 throw new UnsupportedOperationException("Invocation of deserialize without Tree location is unsupported");
654 public final Object deserialize(final Object parent, final InstanceIdentifier parentPath) {
655 adaptForPath(parentPath);
656 Preconditions.checkArgument(parent instanceof CompositeNode, "node must be of CompositeNode type.");
657 CompositeNode parentData = (CompositeNode) parent;
658 ArrayList<T> applicable = new ArrayList<>(implementations.size());
661 * Codecs are filtered to only ones, which
662 * are applicable in supplied parent context.
665 for (T impl : getImplementations().values()) {
666 @SuppressWarnings("unchecked")
667 boolean codecApplicable = impl.isApplicable(parentPath, parentData);
668 if (codecApplicable) {
669 applicable.add(impl);
672 LOG.trace("{}: Deserializing mixins from {}, Schema Location {}, Applicable Codecs: {}, All Codecs: {}",this,parent,parentPath,applicable,getImplementations().values());
674 /* In case of none is applicable, we return
675 * null. Since there is no mixin which
676 * is applicable in this location.
678 if(applicable.isEmpty()) {
681 return deserializeImpl(parentData, parentPath, applicable);
684 protected abstract Object deserializeImpl(final CompositeNode input, final InstanceIdentifier<?> parentPath,
685 Iterable<T> applicableCodecs);
688 public Object serialize(final Object input) {
689 Preconditions.checkArgument(input instanceof DataContainer);
690 Class<? extends DataContainer> inputType = ((DataContainer) input).getImplementedInterface();
691 T implementation = implementations.get(inputType);
692 if (implementation == null) {
693 implementation = tryToLoadImplementationImpl(inputType);
699 private T tryToLoadImplementationImpl(final Class<? extends DataContainer> inputType) {
700 T implementation = tryToLoadImplementation(inputType);
701 Preconditions.checkArgument(implementation != null, "Data type %s is not supported.", inputType);
702 addImplementation(implementation);
703 return implementation;
706 protected final synchronized void adaptForPath(final InstanceIdentifier<?> path) {
707 if (adaptedForPaths.contains(path)) {
710 LOG.debug("Adapting mixin codec {} for path {}",this,path);
712 * We search in schema context if the use of this location aware
713 * codec (augmentable codec, case codec) makes sense on provided
717 Optional<DataNodeContainer> contextNode = BindingSchemaContextUtils.findDataNodeContainer(getRegistry().currentSchema,
720 * If context node is present, this codec makes sense on provided
724 if (contextNode.isPresent()) {
725 synchronized (this) {
728 * We adapt (turn on / off) possible implementations of
729 * child codecs (augmentations, cases) based on this
735 adaptForPathImpl(path, contextNode.get());
738 * We trigger serialization of instance identifier, to
739 * make sure instance identifier codec is aware of
740 * combination of this path / augmentation / case
742 getRegistry().getInstanceIdentifierCodec().serialize(path);
743 } catch (Exception e) {
744 LOG.warn("Exception during preparation of instance identifier codec for path {}.", path, e);
746 adaptedForPaths.add(path);
749 LOG.debug("Context node (parent node) not found for {}", path);
753 protected abstract T tryToLoadImplementation(Class<? extends DataContainer> inputType);
755 protected abstract void tryToLoadImplementations();
757 protected abstract void adaptForPathImpl(InstanceIdentifier<?> path, DataNodeContainer ctx);
760 @SuppressWarnings("rawtypes")
761 private static class ChoiceCaseCodecImpl<T extends DataContainer> implements ChoiceCaseCodec<T>, //
762 Delegator<BindingCodec>, LocationAwareBindingCodec<Node<?>, ValueWithQName<T>> {
763 private final BindingCodec delegate;
764 private final ChoiceCaseNode schema;
765 private final Map<InstanceIdentifier<?>, ChoiceCaseNode> instantiatedLocations;
766 private final Class<?> dataType;
768 public ChoiceCaseCodecImpl(final Class<?> caseClass, final ChoiceCaseNode caseNode,
769 final BindingCodec newInstance) {
770 this.delegate = newInstance;
771 this.dataType = caseClass;
772 this.schema = caseNode;
773 instantiatedLocations = new HashMap<>();
777 public ValueWithQName<T> deserialize(final Node<?> input) {
778 throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
782 public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
786 QName qname = input.getNodeType();
787 synchronized (instantiatedLocations) {
788 ChoiceCaseNode instantiation = instantiatedLocations.get(bindingIdentifier);
789 if (instantiation != null) {
790 qname = instantiatedLocations.get(bindingIdentifier).getQName();
793 @SuppressWarnings("unchecked")
794 T value = (T) getDelegate().deserialize(new SimpleEntry(qname, input), bindingIdentifier);
795 return new ValueWithQName<T>(qname, value);
799 public CompositeNode serialize(final ValueWithQName<T> input) {
800 throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
804 public BindingCodec getDelegate() {
808 public ChoiceCaseNode getSchema() {
814 public boolean isAcceptable(final Node<?> input) {
815 return checkAgainstSchema(schema, input);
818 private static boolean checkAgainstSchema(final ChoiceCaseNode schema, final Node<?> node) {
819 if (node instanceof CompositeNode) {
820 CompositeNode input = (CompositeNode) node;
821 for (Node<?> childNode : input.getValue()) {
822 QName child = childNode.getNodeType();
823 if (schema.getDataChildByName(child) != null) {
832 public Class<?> getDataType() {
836 public void adaptForPath(final InstanceIdentifier<?> augTarget, final ChoiceCaseNode choiceCaseNode) {
837 synchronized (instantiatedLocations) {
838 instantiatedLocations.put(augTarget, choiceCaseNode);
843 public boolean isApplicable(final InstanceIdentifier path, final CompositeNode input) {
844 ChoiceCaseNode instantiatedSchema = null;
845 synchronized (instantiatedLocations) {
846 instantiatedSchema = instantiatedLocations.get(path);
848 if (instantiatedSchema == null) {
851 return checkAgainstSchema(instantiatedSchema, input);
854 protected boolean isAugmenting(final QName choiceName, final QName proposedQName) {
855 if (schema.isAugmenting()) {
859 QName parentQName = Iterables.get(schema.getPath().getPathTowardsRoot(), 1);
860 if (!parentQName.getNamespace().equals(schema.getQName().getNamespace())) {
863 if (!parentQName.equals(choiceName)) {
864 // This item is instantiation of choice via uses in other YANG
866 if (choiceName.getNamespace().equals(schema.getQName())) {
867 // Original definition of grouping is in same namespace
868 // as original definition of case
869 // so for sure case is introduced via instantiation of
873 // Since we are still here, that means case has same namespace
874 // as its parent, which is instantiation of grouping
875 // but case namespace is different from parent node
876 // so it is augmentation.
883 public String toString() {
884 return "ChoiceCaseCodec [case=" + dataType
885 + ", knownLocations=" + instantiatedLocations.keySet() + "]";
889 private static class PublicChoiceCodecImpl<T> implements ChoiceCodec<T>,
890 Delegator<BindingCodec<Map<QName, Object>, Object>> {
892 private final BindingCodec<Map<QName, Object>, Object> delegate;
894 public PublicChoiceCodecImpl(final BindingCodec<Map<QName, Object>, Object> delegate) {
895 this.delegate = delegate;
899 public ValueWithQName<T> deserialize(final Node<?> input) {
900 throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
904 public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
905 throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
909 public Node<?> serialize(final ValueWithQName<T> input) {
910 throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
914 public BindingCodec<Map<QName, Object>, Object> getDelegate() {
920 class DispatchChoiceCodecImpl extends LocationAwareDispatchCodec<ChoiceCaseCodecImpl<?>> {
921 private final Class<?> choiceType;
922 private final QName choiceName;
924 private DispatchChoiceCodecImpl(final Class<?> type, final LazyGeneratedCodecRegistry registry) {
927 choiceName = BindingReflections.findQName(type);
931 public Object deserializeImpl(final CompositeNode input, final InstanceIdentifier<?> path,
932 final Iterable<ChoiceCaseCodecImpl<?>> codecs) {
933 ChoiceCaseCodecImpl<?> caseCodec = Iterables.getOnlyElement(codecs);
934 ValueWithQName<?> value = caseCodec.deserialize(input, path);
936 return value.getValue();
941 @SuppressWarnings("unchecked")
943 public Object serialize(final Object input) {
944 Preconditions.checkArgument(input instanceof Map.Entry<?, ?>, "Input must be QName, Value");
945 @SuppressWarnings("rawtypes")
946 QName derivedQName = (QName) ((Map.Entry) input).getKey();
947 @SuppressWarnings("rawtypes")
948 Object inputValue = ((Map.Entry) input).getValue();
949 Preconditions.checkArgument(inputValue instanceof DataObject);
950 Class<? extends DataContainer> inputType = ((DataObject) inputValue).getImplementedInterface();
951 ChoiceCaseCodecImpl<?> codec = tryToLoadImplementation(inputType);
952 Preconditions.checkState(codec != null, "Unable to get codec for %s", inputType);
953 if (codec.isAugmenting(choiceName, derivedQName)) {
954 // If choice is augmenting we use QName which defined this
956 return codec.getDelegate().serialize(new ValueWithQName<>(codec.getSchema().getQName(), inputValue));
958 return codec.getDelegate().serialize(input);
961 @SuppressWarnings("rawtypes")
962 protected Optional<ChoiceCaseCodecImpl> tryToLoadImplementation(final Type potential) {
964 @SuppressWarnings("unchecked")
965 Class<? extends DataContainer> clazz = (Class<? extends DataContainer>) classLoadingStrategy
966 .loadClass(potential);
967 ChoiceCaseCodecImpl codec = tryToLoadImplementation(clazz);
968 addImplementation(codec);
969 return Optional.of(codec);
970 } catch (ClassNotFoundException e) {
971 LOG.warn("Failed to find class for choice {}", potential, e);
973 return Optional.absent();
977 protected ChoiceCaseCodecImpl<?> tryToLoadImplementation(final Class<? extends DataContainer> inputType) {
978 ChoiceCaseCodecImpl<?> codec = getCaseCodecFor(inputType);
979 addImplementation(codec);
984 protected void tryToLoadImplementations() {
985 Type type = referencedType(choiceType);
986 Collection<Type> potentialCases;
987 synchronized (choiceToCases) {
988 potentialCases = choiceToCases.get(type);
990 for (Type potential : potentialCases) {
992 tryToLoadImplementation(potential);
993 } catch (CodeGenerationException e) {
994 LOG.warn("Failed to proactively generate choice code for {}", type, e);
1000 protected void adaptForPathImpl(final InstanceIdentifier<?> augTarget, final DataNodeContainer ctxNode) {
1001 Optional<ChoiceNode> newChoice = BindingSchemaContextUtils.findInstantiatedChoice(ctxNode, choiceType);
1002 tryToLoadImplementations();
1003 Preconditions.checkState(newChoice.isPresent(), "BUG: Unable to find instantiated choice node in schema.");
1004 for (@SuppressWarnings("rawtypes")
1005 Entry<Class, ChoiceCaseCodecImpl<?>> codec : getImplementations().entrySet()) {
1006 ChoiceCaseCodecImpl<?> caseCodec = codec.getValue();
1007 Optional<ChoiceCaseNode> instantiatedSchema = BindingSchemaContextUtils.findInstantiatedCase(newChoice.get(),
1008 caseCodec.getSchema());
1009 if (instantiatedSchema.isPresent()) {
1010 caseCodec.adaptForPath(augTarget, instantiatedSchema.get());
1018 public String toString() {
1019 return "DispatchChoiceCodecImpl [choiceType=" + choiceType + "]";
1023 @SuppressWarnings({ "rawtypes", "unchecked" })
1024 static class AugmentableDispatchCodec extends LocationAwareDispatchCodec<AugmentationCodecWrapper> {
1026 private final Class augmentableType;
1028 public AugmentableDispatchCodec(final Class type, final LazyGeneratedCodecRegistry registry) {
1030 Preconditions.checkArgument(Augmentable.class.isAssignableFrom(type));
1031 augmentableType = type;
1035 // TODO deprecate use without iid
1036 public Object serialize(final Object input) {
1037 if (input instanceof Augmentable<?>) {
1038 Map<Class, Augmentation> augmentations = getAugmentations(input);
1039 return serializeImpl(augmentations);
1044 private Map<Class, Augmentation> getAugmentations(final Object input) {
1045 Field augmentationField;
1047 augmentationField = input.getClass().getDeclaredField("augmentation");
1048 augmentationField.setAccessible(true);
1049 Map<Class, Augmentation> augMap = (Map<Class, Augmentation>) augmentationField.get(input);
1051 } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {
1052 LOG.debug("Could not read augmentations for {}", input, e);
1054 return Collections.emptyMap();
1057 @SuppressWarnings("deprecation")
1058 private List serializeImpl(final Map<Class, Augmentation> input) {
1059 List ret = new ArrayList<>();
1060 for (Entry<Class, Augmentation> entry : input.entrySet()) {
1061 AugmentationCodec codec = getRegistry().getCodecForAugmentation(entry.getKey());
1062 CompositeNode node = codec.serialize(new ValueWithQName(null, entry.getValue()));
1063 ret.addAll(node.getChildren());
1069 public Map<Class, Augmentation> deserializeImpl(final CompositeNode input, final InstanceIdentifier<?> path,
1070 final Iterable<AugmentationCodecWrapper> codecs) {
1071 LOG.trace("{}: Going to deserialize augmentations from {} in location {}. Available codecs {}",this,input,path,codecs);
1072 Map<Class, Augmentation> ret = new HashMap<>();
1073 for (AugmentationCodecWrapper codec : codecs) {
1074 // We add Augmentation Identifier to path, in order to
1075 // correctly identify children.
1076 Class type = codec.getDataType();
1077 final InstanceIdentifier augmentPath = path.augmentation(type);
1078 ValueWithQName<?> value = codec.deserialize(input, augmentPath);
1079 if (value != null && value.getValue() != null) {
1080 ret.put(type, (Augmentation) value.getValue());
1086 protected Optional<AugmentationCodecWrapper> tryToLoadImplementation(final Type potential) {
1088 Class<? extends Augmentation<?>> clazz = (Class<? extends Augmentation<?>>) getRegistry().classLoadingStrategy
1089 .loadClass(potential);
1090 return Optional.of(tryToLoadImplementation(clazz));
1091 } catch (ClassNotFoundException e) {
1092 LOG.warn("Failed to find class for augmentation of {}", potential, e);
1094 return Optional.absent();
1098 protected AugmentationCodecWrapper tryToLoadImplementation(final Class inputType) {
1099 AugmentationCodecWrapper<? extends Augmentation<?>> potentialImpl = getRegistry().getCodecForAugmentation(inputType);
1100 addImplementation(potentialImpl);
1101 return potentialImpl;
1105 protected void tryToLoadImplementations() {
1106 Type type = referencedType(augmentableType);
1107 Collection<Type> potentialAugmentations;
1108 synchronized (augmentableToAugmentations) {
1109 potentialAugmentations = new ArrayList(augmentableToAugmentations.get(type));
1111 for (Type potential : potentialAugmentations) {
1113 tryToLoadImplementation(potential);
1114 } catch (CodeGenerationException e) {
1115 LOG.warn("Failed to proactively generate augment code for {}", type, e);
1121 protected void adaptForPathImpl(final InstanceIdentifier<?> augTarget, final DataNodeContainer ctxNode) {
1122 if (ctxNode instanceof AugmentationTarget) {
1123 Set<AugmentationSchema> availableAugmentations = ((AugmentationTarget) ctxNode)
1124 .getAvailableAugmentations();
1125 if (!availableAugmentations.isEmpty()) {
1126 updateAugmentationMapping(augTarget, availableAugmentations);
1133 * Adapts augmentation codec for specific provider location (target)
1135 * Since augmentation are not forward-referencing and may be discovered
1136 * during runtime, we need to adapt {@link AugmentableDispatchCodec},
1137 * {@link AugmentationCodecWrapper} and {@link InstanceIdentifierCodec}
1138 * for this newly discovered location where augmentation may be used.
1140 * Adaptation consists of:
1142 * <li>scan of available (valid) augmentations for current location
1143 * <li>lookup for Java classes derived from this augmentations
1144 * <li>generation of missing codecs
1145 * <li>updating Augmentation codecs to work with new location
1146 * <li>updating Instance Identifier to work with new location
1149 private void updateAugmentationMapping(final InstanceIdentifier<?> augTarget,
1150 final Set<AugmentationSchema> availableAugmentations) {
1151 for (AugmentationSchema aug : availableAugmentations) {
1153 Type potentialType = getTypeForAugmentation(aug);
1154 if (potentialType != null) {
1155 Optional<AugmentationCodecWrapper> potentialImpl = tryToLoadImplementation(potentialType);
1156 if (potentialImpl.isPresent()) {
1157 potentialImpl.get().addApplicableFor(augTarget, aug);
1158 Class augType = potentialImpl.get().getDataType();
1159 InstanceIdentifier augPath = augTarget.augmentation(augType);
1162 org.opendaylight.yangtools.yang.data.api.InstanceIdentifier domPath = getRegistry().getInstanceIdentifierCodec()
1163 .serialize(augPath);
1164 if (domPath == null) {
1165 LOG.error("Unable to serialize instance identifier for {}", augPath);
1167 } catch (Exception e) {
1168 LOG.error("Unable to serialize instance identifiers for {}", augPath, e);
1173 // Omits warning for empty augmentations since they are not
1174 // represented in data
1175 if (!aug.getChildNodes().isEmpty()) {
1176 LOG.warn("Could not find generated type for augmentation {} with children {}", aug,
1177 aug.getChildNodes());
1183 private Type getTypeForAugmentation(final AugmentationSchema aug) {
1184 Optional<AugmentationSchema> currentAug = Optional.of(aug);
1185 while (currentAug.isPresent()) {
1186 Type potentialType = typeToAugment.inverse().get(currentAug.get());
1187 if (potentialType != null) {
1188 return potentialType;
1190 currentAug = currentAug.get().getOriginalDefinition();
1196 public String toString() {
1197 return "AugmentableDispatchCodec [augmentable=" + augmentableType + "]";
1202 @SuppressWarnings("rawtypes")
1203 private static class AugmentationCodecWrapper<T extends Augmentation<?>> implements AugmentationCodec<T>,
1204 Delegator<BindingCodec>, LocationAwareBindingCodec<Node<?>, ValueWithQName<T>> {
1206 private final BindingCodec delegate;
1207 private final QName augmentationQName;
1208 private final Multimap<InstanceIdentifier<?>, QName> validAugmentationTargets;
1209 private final Class<?> augmentationType;
1211 public AugmentationCodecWrapper(final BindingCodec<Map<QName, Object>, Object> rawCodec, final Class<?> dataType) {
1212 this.delegate = rawCodec;
1213 this.augmentationType = dataType;
1214 this.augmentationQName = BindingReflections.findQName(rawCodec.getClass());
1215 this.validAugmentationTargets = Multimaps.synchronizedSetMultimap(HashMultimap
1216 .<InstanceIdentifier<?>, QName> create());
1219 public void addApplicableFor(final InstanceIdentifier<?> path, final AugmentationSchema aug) {
1220 for (DataSchemaNode child : aug.getChildNodes()) {
1221 validAugmentationTargets.put(path, child.getQName());
1226 public BindingCodec getDelegate() {
1231 public CompositeNode serialize(final ValueWithQName<T> input) {
1232 @SuppressWarnings("unchecked")
1233 List<Map<QName, Object>> rawValues = (List<Map<QName, Object>>) getDelegate().serialize(input);
1234 List<Node<?>> serialized = new ArrayList<>(rawValues.size());
1235 for (Map<QName, Object> val : rawValues) {
1236 serialized.add(IntermediateMapping.toNode(val));
1238 return new CompositeNodeTOImpl(input.getQname(), null, serialized);
1242 @SuppressWarnings("unchecked")
1243 public ValueWithQName<T> deserialize(final Node<?> input) {
1244 Object rawCodecValue = getDelegate().deserialize(input);
1245 return new ValueWithQName<T>(input.getNodeType(), (T) rawCodecValue);
1249 @SuppressWarnings("unchecked")
1250 public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
1251 Object rawCodecValue = getDelegate().deserialize(input, bindingIdentifier);
1252 return new ValueWithQName<T>(input.getNodeType(), (T) rawCodecValue);
1256 public QName getAugmentationQName() {
1257 return augmentationQName;
1261 public boolean isAcceptable(final InstanceIdentifier<?> path) {
1265 return validAugmentationTargets.containsKey(path);
1269 public boolean isApplicable(final InstanceIdentifier parentPath,final CompositeNode parentData) {
1270 return isAcceptable(parentPath);
1274 public Class<?> getDataType() {
1275 return augmentationType;
1279 public String toString() {
1280 return "AugmentationCodecWrapper [augmentation=" + augmentationType
1281 + ", knownLocations=" + validAugmentationTargets.keySet() + "]";
1285 @SuppressWarnings("rawtypes")
1286 private class IdentityCompositeCodec implements IdentityCodec {
1289 public Object deserialize(final Object input) {
1290 Preconditions.checkArgument(input instanceof QName);
1291 return deserialize((QName) input);
1295 public Class<?> deserialize(final QName input) {
1299 Type type = qnamesToIdentityMap.get(input);
1301 String packageName = BindingMapping.getRootPackageName(input);
1302 String className = BindingMapping.getClassName(input);
1303 type = new ReferencedTypeImpl(packageName, className);
1305 ReferencedTypeImpl typeref = new ReferencedTypeImpl(type.getPackageName(), type.getName());
1306 WeakReference<Class> softref = typeToClass.get(typeref);
1307 if (softref == null) {
1310 Class<?> cls = classLoadingStrategy.loadClass(typeref.getFullyQualifiedName());
1315 } catch (Exception e) {
1316 LOG.warn("Identity {} was not deserialized, because of missing class {}", input,
1317 typeref.getFullyQualifiedName());
1321 return softref.get();
1325 public Object deserialize(final Object input, final InstanceIdentifier bindingIdentifier) {
1326 Type type = qnamesToIdentityMap.get(input);
1328 throw new IllegalArgumentException( "Invalid for \"" + input + "\"." );
1330 ReferencedTypeImpl typeref = new ReferencedTypeImpl(type.getPackageName(), type.getName());
1331 WeakReference<Class> softref = typeToClass.get(typeref);
1332 if (softref == null) {
1335 Class<?> cls = classLoadingStrategy.loadClass(typeref.getFullyQualifiedName());
1340 } catch (Exception e) {
1341 LOG.warn("Identity {} was not deserialized, because of missing class {}", input,
1342 typeref.getFullyQualifiedName());
1346 return softref.get();
1350 public QName serialize(final Class input) {
1351 Preconditions.checkArgument(BaseIdentity.class.isAssignableFrom(input));
1352 bindingClassEncountered(input);
1353 QName qname = identityQNames.get(input);
1354 if (qname != null) {
1357 qname = BindingReflections.findQName(input);
1358 if (qname != null) {
1359 identityQNames.put(input, qname);
1365 public Object serialize(final Object input) {
1366 Preconditions.checkArgument(input instanceof Class);
1367 return serialize((Class) input);
1372 private static final Type referencedType(final Class<?> augmentableType) {
1373 return new ReferencedTypeImpl(augmentableType.getPackage().getName(), augmentableType.getSimpleName());