1 package org.opendaylight.controller.sal.binding.dom.serializer.impl;
3 import java.awt.CompositeContext;
4 import java.lang.ref.WeakReference;
5 import java.lang.reflect.Field;
6 import java.lang.reflect.ParameterizedType;
7 import java.util.ArrayList;
8 import java.util.Collection;
9 import java.util.Collections;
10 import java.util.HashMap;
11 import java.util.HashSet;
12 import java.util.Iterator;
13 import java.util.List;
15 import java.util.Map.Entry;
16 import java.util.Objects;
17 import java.util.concurrent.Callable;
18 import java.util.concurrent.ConcurrentHashMap;
19 import java.util.concurrent.ConcurrentMap;
21 import java.util.WeakHashMap;
23 import org.apache.commons.lang3.text.translate.AggregateTranslator;
24 import org.opendaylight.controller.sal.binding.dom.serializer.api.AugmentationCodec;
25 import org.opendaylight.controller.sal.binding.dom.serializer.api.ChoiceCaseCodec;
26 import org.opendaylight.controller.sal.binding.dom.serializer.api.ChoiceCodec;
27 import org.opendaylight.controller.sal.binding.dom.serializer.api.CodecRegistry;
28 import org.opendaylight.controller.sal.binding.dom.serializer.api.DataContainerCodec;
29 import org.opendaylight.controller.sal.binding.dom.serializer.api.DomCodec;
30 import org.opendaylight.controller.sal.binding.dom.serializer.api.IdentifierCodec;
31 import org.opendaylight.controller.sal.binding.dom.serializer.api.IdentitityCodec;
32 import org.opendaylight.controller.sal.binding.dom.serializer.api.InstanceIdentifierCodec;
33 import org.opendaylight.controller.sal.binding.dom.serializer.api.ValueWithQName;
34 import org.opendaylight.controller.sal.binding.impl.util.ClassLoaderUtils;
35 import org.opendaylight.controller.sal.core.api.model.SchemaServiceListener;
36 import org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl;
37 import org.opendaylight.yangtools.binding.generator.util.Types;
38 import org.opendaylight.yangtools.concepts.Delegator;
39 import org.opendaylight.yangtools.concepts.Identifiable;
40 import org.opendaylight.yangtools.yang.binding.Augmentable;
41 import org.opendaylight.yangtools.yang.binding.Augmentation;
42 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
43 import org.opendaylight.yangtools.yang.binding.BindingCodec;
44 import org.opendaylight.yangtools.yang.binding.DataContainer;
45 import org.opendaylight.yangtools.yang.binding.DataObject;
46 import org.opendaylight.yangtools.yang.binding.Identifier;
47 import org.opendaylight.yangtools.yang.common.QName;
48 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
49 import org.opendaylight.yangtools.yang.data.api.Node;
50 import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl;
51 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
52 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
53 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
54 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
55 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
56 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
60 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
61 import org.opendaylight.yangtools.yang.model.api.UsesNode;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
65 import static com.google.common.base.Preconditions.*;
66 import static org.opendaylight.controller.sal.binding.dom.serializer.impl.IntermediateMapping.*;
68 import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleContext;
69 import org.opendaylight.yangtools.sal.binding.model.api.ConcreteType;
70 import org.opendaylight.yangtools.sal.binding.model.api.Type;
71 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
72 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
73 import org.opendaylight.yangtools.yang.model.api.Module;
74 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
76 import com.google.common.collect.FluentIterable;
77 import com.google.common.util.concurrent.CycleDetectingLockFactory.WithExplicitOrdering;
79 public class LazyGeneratedCodecRegistry implements //
81 SchemaServiceListener, //
84 private final static Logger LOG = LoggerFactory.getLogger(LazyGeneratedCodecRegistry.class);
85 private final static LateMixinCodec NOT_READY_CODEC = new LateMixinCodec();
87 private final InstanceIdentifierCodec instanceIdentifierCodec = new InstanceIdentifierCodecImpl(this);
88 private final IdentityCompositeCodec identityRefCodec = new IdentityCompositeCodec();
90 private TransformerGenerator generator;
92 // Concrete class to codecs
93 private static final Map<Class<?>, DataContainerCodec<?>> containerCodecs = new WeakHashMap<>();
94 private static final Map<Class<?>, IdentifierCodec<?>> identifierCodecs = new WeakHashMap<>();
95 private static final Map<Class<?>, ChoiceCodecImpl<?>> choiceCodecs = new WeakHashMap<>();
96 private static final Map<Class<?>, ChoiceCaseCodecImpl<?>> caseCodecs = new WeakHashMap<>();
97 private static final Map<Class<?>, AugmentableCompositeCodec> augmentableCodecs = new WeakHashMap<>();
98 private static final Map<Class<?>, AugmentationCodec<?>> augmentationCodecs = new WeakHashMap<>();
99 private static final Map<Class<?>, QName> identityQNames = new WeakHashMap<>();
100 private static final Map<QName, Type> qnamesToIdentityMap = new ConcurrentHashMap<>();
101 /** Binding type to encountered classes mapping **/
102 @SuppressWarnings("rawtypes")
103 private static final Map<Type, WeakReference<Class>> typeToClass = new ConcurrentHashMap<>();
105 @SuppressWarnings("rawtypes")
106 private static final ConcurrentMap<Type, ChoiceCaseCodecImpl> typeToCaseCodecs = new ConcurrentHashMap<>();
108 private CaseClassMapFacade classToCaseRawCodec = new CaseClassMapFacade();
110 private static final Map<SchemaPath, GeneratedTypeBuilder> pathToType = new ConcurrentHashMap<>();
111 private static final Map<List<QName>, Type> pathToInstantiatedType = new ConcurrentHashMap<>();
112 private static final Map<Type, QName> typeToQname = new ConcurrentHashMap<>();
114 private SchemaContext currentSchema;
116 public TransformerGenerator getGenerator() {
120 public void setGenerator(TransformerGenerator generator) {
121 this.generator = generator;
125 public InstanceIdentifierCodec getInstanceIdentifierCodec() {
126 return instanceIdentifierCodec;
130 public <T extends Augmentation<?>> AugmentationCodec<T> getCodecForAugmentation(Class<T> object) {
131 AugmentationCodec<T> codec = null;
132 @SuppressWarnings("rawtypes")
133 AugmentationCodec potentialCodec = augmentationCodecs.get(object);
134 if (potentialCodec != null) {
135 codec = potentialCodec;
138 Class<? extends BindingCodec<Map<QName, Object>, Object>> augmentRawCodec = generator
139 .augmentationTransformerFor(object);
140 BindingCodec<Map<QName, Object>, Object> rawCodec = augmentRawCodec.newInstance();
141 codec = new AugmentationCodecWrapper<T>(rawCodec);
142 augmentationCodecs.put(augmentRawCodec, codec);
143 } catch (InstantiationException e) {
144 LOG.error("Can not instantiate raw augmentation codec {}", object.getSimpleName(), e);
145 } catch (IllegalAccessException e) {
146 LOG.debug("BUG: Constructor for {} is not accessible.", object.getSimpleName(), e);
148 Class<? extends Augmentable<?>> objectSupertype = getAugmentableArgumentFrom(object);
149 if (objectSupertype != null) {
150 getAugmentableCodec(objectSupertype).addAugmentationCodec(object, codec);
152 LOG.warn("Could not find augmentation target for augmentation {}", object);
157 private static Class<? extends Augmentable<?>> getAugmentableArgumentFrom(
158 final Class<? extends Augmentation<?>> augmentation) {
160 Class<? extends Augmentable<?>> ret = ClassLoaderUtils.withClassLoader(augmentation.getClassLoader(),
161 new Callable<Class<? extends Augmentable<?>>>() {
163 @SuppressWarnings("unchecked")
164 public Class<? extends Augmentable<?>> call() throws Exception {
165 for (java.lang.reflect.Type supertype : augmentation.getGenericInterfaces()) {
166 if (supertype instanceof ParameterizedType
167 && Augmentation.class.equals(((ParameterizedType) supertype).getRawType())) {
168 ParameterizedType augmentationGeneric = (ParameterizedType) supertype;
169 return (Class<? extends Augmentable<?>>) augmentationGeneric
170 .getActualTypeArguments()[0];
177 } catch (Exception e) {
178 LOG.error("Could not find augmentable for {}", augmentation, e);
184 public Class<?> getClassForPath(List<QName> names) {
185 DataSchemaNode node = getSchemaNode(names);
186 SchemaPath path = node.getPath();
187 Type type = pathToType.get(path);
189 type = new ReferencedTypeImpl(type.getPackageName(), type.getName());
191 type = pathToInstantiatedType.get(names);
193 @SuppressWarnings("rawtypes")
194 WeakReference<Class> weakRef = typeToClass.get(type);
195 if (weakRef == null) {
196 LOG.error("Could not find loaded class for path: {} and type: {}", path, type.getFullyQualifiedName());
198 return weakRef.get();
202 public void putPathToClass(List<QName> names, Class<?> cls) {
203 Type reference = Types.typeForClass(cls);
204 pathToInstantiatedType.put(names, reference);
205 bindingClassEncountered(cls);
209 public IdentifierCodec<?> getKeyCodecForPath(List<QName> names) {
210 @SuppressWarnings("unchecked")
211 Class<? extends Identifiable<?>> cls = (Class<? extends Identifiable<?>>) getClassForPath(names);
212 return getIdentifierCodecForIdentifiable(cls);
216 public <T extends DataContainer> DataContainerCodec<T> getCodecForDataObject(Class<T> type) {
217 @SuppressWarnings("unchecked")
218 DataContainerCodec<T> ret = (DataContainerCodec<T>) containerCodecs.get(type);
222 Class<? extends BindingCodec<Map<QName, Object>, Object>> newType = generator.transformerFor(type);
223 BindingCodec<Map<QName, Object>, Object> rawCodec = newInstanceOf(newType);
224 DataContainerCodecImpl<T> newWrapper = new DataContainerCodecImpl<>(rawCodec);
225 containerCodecs.put(type, newWrapper);
229 @SuppressWarnings("rawtypes")
230 public void bindingClassEncountered(Class cls) {
232 ConcreteType typeRef = Types.typeForClass(cls);
233 if (typeToClass.containsKey(typeRef)) {
236 LOG.info("Binding Class {} encountered.", cls);
237 WeakReference<Class> weakRef = new WeakReference<>(cls);
238 typeToClass.put(typeRef, weakRef);
239 if (Augmentation.class.isAssignableFrom(cls)) {
241 } else if (DataObject.class.isAssignableFrom(cls)) {
242 @SuppressWarnings({ "unchecked", "unused" })
243 Object cdc = getCodecForDataObject((Class<? extends DataObject>) cls);
248 public void onClassProcessed(Class<?> cls) {
249 ConcreteType typeRef = Types.typeForClass(cls);
250 if (typeToClass.containsKey(typeRef)) {
253 LOG.info("Binding Class {} encountered.", cls);
254 WeakReference<Class> weakRef = new WeakReference<>((Class) cls);
255 typeToClass.put(typeRef, weakRef);
258 private DataSchemaNode getSchemaNode(List<QName> path) {
259 QName firstNode = path.get(0);
260 DataNodeContainer previous = currentSchema.findModuleByNamespaceAndRevision(firstNode.getNamespace(),
261 firstNode.getRevision());
262 Iterator<QName> iterator = path.iterator();
263 while (iterator.hasNext()) {
264 QName arg = iterator.next();
265 DataSchemaNode currentNode = previous.getDataChildByName(arg);
266 if (currentNode == null && previous instanceof DataNodeContainer) {
267 currentNode = searchInChoices(previous, arg);
269 if (currentNode instanceof DataNodeContainer) {
270 previous = (DataNodeContainer) currentNode;
271 } else if (currentNode instanceof LeafSchemaNode || currentNode instanceof LeafListSchemaNode) {
272 checkState(!iterator.hasNext(), "Path tries to nest inside leaf node.");
276 return (DataSchemaNode) previous;
279 private DataSchemaNode searchInChoices(DataNodeContainer node, QName arg) {
280 Set<DataSchemaNode> children = node.getChildNodes();
281 for (DataSchemaNode child : children) {
282 if (child instanceof ChoiceNode) {
283 ChoiceNode choiceNode = (ChoiceNode) child;
284 DataSchemaNode potential = searchInCases(choiceNode, arg);
285 if (potential != null) {
293 private DataSchemaNode searchInCases(ChoiceNode choiceNode, QName arg) {
294 Set<ChoiceCaseNode> cases = choiceNode.getCases();
295 for (ChoiceCaseNode caseNode : cases) {
296 DataSchemaNode node = caseNode.getDataChildByName(arg);
304 private <T> T newInstanceOf(Class<?> newType) {
306 @SuppressWarnings("unchecked")
307 T ret = (T) newType.newInstance();
309 } catch (InstantiationException e) {
310 throw new IllegalStateException(e);
311 } catch (IllegalAccessException e) {
312 throw new IllegalStateException(e);
317 public <T extends Identifiable<?>> IdentifierCodec<?> getIdentifierCodecForIdentifiable(Class<T> type) {
318 IdentifierCodec<?> obj = identifierCodecs.get(type);
322 Class<? extends BindingCodec<Map<QName, Object>, Object>> newCodec = generator
323 .keyTransformerForIdentifiable(type);
324 BindingCodec<Map<QName, Object>, Object> newInstance;
325 newInstance = newInstanceOf(newCodec);
326 IdentifierCodecImpl<?> newWrapper = new IdentifierCodecImpl<>(newInstance);
327 identifierCodecs.put(type, newWrapper);
332 public IdentitityCodec<?> getIdentityCodec() {
333 return identityRefCodec;
337 public <T extends BaseIdentity> IdentitityCodec<T> getCodecForIdentity(Class<T> codec) {
338 bindingClassEncountered(codec);
339 return identityRefCodec;
343 public void onCodecCreated(Class<?> cls) {
344 CodecMapping.setIdentifierCodec(cls, instanceIdentifierCodec);
345 CodecMapping.setIdentityRefCodec(cls, identityRefCodec);
349 public <T extends Identifier<?>> IdentifierCodec<T> getCodecForIdentifier(Class<T> object) {
350 @SuppressWarnings("unchecked")
351 IdentifierCodec<T> obj = (IdentifierCodec<T>) identifierCodecs.get(object);
355 Class<? extends BindingCodec<Map<QName, Object>, Object>> newCodec = generator
356 .keyTransformerForIdentifier(object);
357 BindingCodec<Map<QName, Object>, Object> newInstance;
358 newInstance = newInstanceOf(newCodec);
359 IdentifierCodecImpl<T> newWrapper = new IdentifierCodecImpl<>(newInstance);
360 identifierCodecs.put(object, newWrapper);
364 @SuppressWarnings("rawtypes")
365 public ChoiceCaseCodecImpl getCaseCodecFor(Class caseClass) {
366 ChoiceCaseCodecImpl<?> potential = caseCodecs.get(caseClass);
367 if (potential != null) {
370 ConcreteType typeref = Types.typeForClass(caseClass);
371 ChoiceCaseCodecImpl caseCodec = typeToCaseCodecs.get(typeref);
373 checkState(caseCodec != null, "Case Codec was not created proactivelly for %s", caseClass.getName());
374 checkState(caseCodec.getSchema() != null, "Case schema is not available for %s", caseClass.getName());
375 @SuppressWarnings("unchecked")
376 Class<? extends BindingCodec> newCodec = generator.caseCodecFor(caseClass, caseCodec.getSchema());
377 BindingCodec newInstance = newInstanceOf(newCodec);
378 caseCodec.setDelegate(newInstance);
379 caseCodecs.put(caseClass, caseCodec);
381 for (Entry<Class<?>, ChoiceCodecImpl<?>> choice : choiceCodecs.entrySet()) {
382 if (choice.getKey().isAssignableFrom(caseClass)) {
383 choice.getValue().cases.put(caseClass, caseCodec);
389 public void onModuleContextAdded(SchemaContext schemaContext, Module module, ModuleContext context) {
390 pathToType.putAll(context.getChildNodes());
391 qnamesToIdentityMap.putAll(context.getIdentities());
392 for(Entry<QName, GeneratedTOBuilder> identity : context.getIdentities().entrySet()) {
393 typeToQname.put(new ReferencedTypeImpl(identity.getValue().getPackageName(), identity.getValue().getName()),identity.getKey());
395 captureCases(context.getCases(), schemaContext);
398 private void captureCases(Map<SchemaPath, GeneratedTypeBuilder> cases, SchemaContext module) {
399 for (Entry<SchemaPath, GeneratedTypeBuilder> caseNode : cases.entrySet()) {
400 ReferencedTypeImpl typeref = new ReferencedTypeImpl(caseNode.getValue().getPackageName(), caseNode
401 .getValue().getName());
403 pathToType.put(caseNode.getKey(), caseNode.getValue());
405 ChoiceCaseNode node = (ChoiceCaseNode) SchemaContextUtil.findDataSchemaNode(module, caseNode.getKey());
408 LOG.error("YANGTools Bug: SchemaNode for {}, with path {} was not found in context.",
409 typeref.getFullyQualifiedName(), caseNode.getKey());
410 @SuppressWarnings("rawtypes")
411 ChoiceCaseCodecImpl value = new ChoiceCaseCodecImpl();
412 typeToCaseCodecs.putIfAbsent(typeref, value);
415 @SuppressWarnings("rawtypes")
416 ChoiceCaseCodecImpl value = new ChoiceCaseCodecImpl(node);
417 typeToCaseCodecs.putIfAbsent(typeref, value);
422 public void onGlobalContextUpdated(SchemaContext context) {
423 currentSchema = context;
426 @SuppressWarnings({ "unchecked", "rawtypes" })
428 public void onChoiceCodecCreated(Class<?> choiceClass,
429 Class<? extends BindingCodec<Map<QName, Object>, Object>> choiceCodec, ChoiceNode schema) {
430 ChoiceCodec<?> oldCodec = choiceCodecs.get(choiceClass);
431 checkState(oldCodec == null);
432 BindingCodec<Map<QName, Object>, Object> delegate = newInstanceOf(choiceCodec);
433 ChoiceCodecImpl<?> newCodec = new ChoiceCodecImpl(delegate);
434 choiceCodecs.put(choiceClass, newCodec);
435 CodecMapping.setClassToCaseMap(choiceCodec, (Map<Class<?>, BindingCodec<?, ?>>) classToCaseRawCodec);
436 CodecMapping.setCompositeNodeToCaseMap(choiceCodec, newCodec.getCompositeToCase());
438 tryToCreateCasesCodecs(schema);
442 private void tryToCreateCasesCodecs(ChoiceNode schema) {
443 for (ChoiceCaseNode caseNode : schema.getCases()) {
444 SchemaPath path = caseNode.getPath();
445 GeneratedTypeBuilder type;
446 if (path != null && (type = pathToType.get(path)) != null) {
447 ReferencedTypeImpl typeref = new ReferencedTypeImpl(type.getPackageName(), type.getName());
448 ChoiceCaseCodecImpl partialCodec = typeToCaseCodecs.get(typeref);
449 if (partialCodec.getSchema() == null) {
450 partialCodec.setSchema(caseNode);
453 Class<?> caseClass = ClassLoaderUtils.tryToLoadClassWithTCCL(type.getFullyQualifiedName());
454 if (caseClass != null) {
455 getCaseCodecFor(caseClass);
463 public void onValueCodecCreated(Class<?> valueClass, Class<?> valueCodec) {
467 public void onCaseCodecCreated(Class<?> choiceClass,
468 Class<? extends BindingCodec<Map<QName, Object>, Object>> choiceCodec) {
472 public void onDataContainerCodecCreated(Class<?> dataClass, Class<? extends BindingCodec<?, ?>> dataCodec) {
473 if (Augmentable.class.isAssignableFrom(dataClass)) {
474 AugmentableCompositeCodec augmentableCodec = getAugmentableCodec(dataClass);
475 CodecMapping.setAugmentationCodec(dataCodec, augmentableCodec);
480 public AugmentableCompositeCodec getAugmentableCodec(Class<?> dataClass) {
481 AugmentableCompositeCodec ret = augmentableCodecs.get(dataClass);
485 ret = new AugmentableCompositeCodec(dataClass);
486 augmentableCodecs.put(dataClass, ret);
490 private static abstract class IntermediateCodec<T> implements //
491 DomCodec<T>, Delegator<BindingCodec<Map<QName, Object>, Object>> {
493 private final BindingCodec<Map<QName, Object>, Object> delegate;
496 public BindingCodec<Map<QName, Object>, Object> getDelegate() {
500 public IntermediateCodec(BindingCodec<Map<QName, Object>, Object> delegate) {
501 this.delegate = delegate;
505 public Node<?> serialize(ValueWithQName<T> input) {
506 Map<QName, Object> intermediateOutput = delegate.serialize(input);
507 return toNode(intermediateOutput);
511 private static class IdentifierCodecImpl<T extends Identifier<?>> //
512 extends IntermediateCodec<T> //
513 implements IdentifierCodec<T> {
515 public IdentifierCodecImpl(BindingCodec<Map<QName, Object>, Object> delegate) {
520 public ValueWithQName<T> deserialize(Node<?> input) {
521 QName qname = input.getNodeType();
522 @SuppressWarnings("unchecked")
523 T value = (T) getDelegate().deserialize((Map<QName, Object>) input);
524 return new ValueWithQName<T>(qname, value);
528 public CompositeNode serialize(ValueWithQName<T> input) {
529 return (CompositeNode) super.serialize(input);
533 private static class DataContainerCodecImpl<T extends DataContainer> //
534 extends IntermediateCodec<T> //
535 implements DataContainerCodec<T> {
537 public DataContainerCodecImpl(BindingCodec<Map<QName, Object>, Object> delegate) {
542 public ValueWithQName<T> deserialize(Node<?> input) {
546 QName qname = input.getNodeType();
547 @SuppressWarnings("unchecked")
548 T value = (T) getDelegate().deserialize((Map<QName, Object>) input);
549 return new ValueWithQName<T>(qname, value);
553 public CompositeNode serialize(ValueWithQName<T> input) {
554 return (CompositeNode) super.serialize(input);
558 @SuppressWarnings("rawtypes")
559 private static class ChoiceCaseCodecImpl<T extends DataContainer> implements ChoiceCaseCodec<T>, //
560 Delegator<BindingCodec> {
561 private boolean augmenting;
562 private BindingCodec delegate;
564 private Set<String> validNames;
565 private Set<QName> validQNames;
566 private ChoiceCaseNode schema;
568 public void setSchema(ChoiceCaseNode caseNode) {
569 this.schema = schema;
570 this.schema = caseNode;
571 validNames = new HashSet<>();
572 validQNames = new HashSet<>();
573 for (DataSchemaNode node : caseNode.getChildNodes()) {
574 QName qname = node.getQName();
575 validQNames.add(qname);
576 validNames.add(qname.getLocalName());
578 augmenting = caseNode.isAugmenting();
581 public ChoiceCaseCodecImpl() {
582 this.delegate = NOT_READY_CODEC;
585 public ChoiceCaseCodecImpl(ChoiceCaseNode caseNode) {
586 this.delegate = NOT_READY_CODEC;
591 public ValueWithQName<T> deserialize(Node<?> input) {
592 throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
596 public CompositeNode serialize(ValueWithQName<T> input) {
597 throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
600 public BindingCodec getDelegate() {
604 public void setDelegate(BindingCodec delegate) {
605 this.delegate = delegate;
608 public ChoiceCaseNode getSchema() {
613 public boolean isAcceptable(Node<?> input) {
614 if (input instanceof CompositeNode) {
616 return checkAugmenting((CompositeNode) input);
618 return checkLocal((CompositeNode) input);
624 private boolean checkLocal(CompositeNode input) {
625 QName parent = input.getNodeType();
626 for (Node<?> childNode : input.getChildren()) {
627 QName child = childNode.getNodeType();
628 if (!Objects.equals(parent.getNamespace(), child.getNamespace())
629 || !Objects.equals(parent.getRevision(), child.getRevision())) {
632 if (validNames.contains(child.getLocalName())) {
639 private boolean checkAugmenting(CompositeNode input) {
640 for (Node<?> child : input.getChildren()) {
641 if (validQNames.contains(child.getNodeType())) {
649 private static class ChoiceCodecImpl<T> implements ChoiceCodec<T> {
651 private final BindingCodec<Map<QName, Object>, Object> delegate;
653 @SuppressWarnings("rawtypes")
654 private final Map<Class, ChoiceCaseCodecImpl<?>> cases = new WeakHashMap<>();
656 private final CaseCompositeNodeMapFacade CompositeToCase;
658 public ChoiceCodecImpl(BindingCodec<Map<QName, Object>, Object> delegate) {
659 this.delegate = delegate;
660 this.CompositeToCase = new CaseCompositeNodeMapFacade(cases);
664 public ValueWithQName<T> deserialize(Node<?> input) {
665 throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
669 public Node<?> serialize(ValueWithQName<T> input) {
670 throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
673 public CaseCompositeNodeMapFacade getCompositeToCase() {
674 return CompositeToCase;
677 public Map<Class, ChoiceCaseCodecImpl<?>> getCases() {
681 public BindingCodec<Map<QName, Object>, Object> getDelegate() {
687 @SuppressWarnings("rawtypes")
688 private class CaseClassMapFacade extends MapFacadeBase {
691 public Set<java.util.Map.Entry<Class, BindingCodec<Object, Object>>> entrySet() {
692 return Collections.emptySet();
696 public BindingCodec get(Object key) {
697 if (key instanceof Class) {
698 Class cls = (Class) key;
699 // bindingClassEncountered(cls);
700 ChoiceCaseCodecImpl caseCodec = getCaseCodecFor(cls);
701 return caseCodec.getDelegate();
707 @SuppressWarnings("rawtypes")
708 private static class CaseCompositeNodeMapFacade extends MapFacadeBase<CompositeNode> {
710 final Map<Class, ChoiceCaseCodecImpl<?>> choiceCases;
712 public CaseCompositeNodeMapFacade(Map<Class, ChoiceCaseCodecImpl<?>> choiceCases) {
713 this.choiceCases = choiceCases;
717 public BindingCodec get(Object key) {
718 if (!(key instanceof CompositeNode)) {
721 for (java.util.Map.Entry<Class, ChoiceCaseCodecImpl<?>> entry : choiceCases.entrySet()) {
722 ChoiceCaseCodecImpl<?> codec = entry.getValue();
723 if (codec.isAcceptable((CompositeNode) key)) {
724 return codec.getDelegate();
733 * This map is used as only facade for {@link BindingCodec} in different
734 * classloaders to retrieve codec dynamicly based on provided key.
739 @SuppressWarnings("rawtypes")
740 private static abstract class MapFacadeBase<T> implements Map<T, BindingCodec<?, ?>> {
743 public boolean containsKey(Object key) {
744 return get(key) != null;
748 public void clear() {
749 throw notModifiable();
753 public boolean equals(Object obj) {
754 return super.equals(obj);
758 public BindingCodec remove(Object key) {
768 public Collection<BindingCodec<?, ?>> values() {
769 return Collections.emptySet();
772 private UnsupportedOperationException notModifiable() {
773 return new UnsupportedOperationException("Not externally modifiable.");
777 public BindingCodec<Map<QName, Object>, Object> put(T key, BindingCodec<?, ?> value) {
778 throw notModifiable();
782 public void putAll(Map<? extends T, ? extends BindingCodec<?, ?>> m) {
783 throw notModifiable();
787 public int hashCode() {
788 return super.hashCode();
792 public boolean isEmpty() {
797 public Set<T> keySet() {
798 return Collections.emptySet();
802 public Set<java.util.Map.Entry<T, BindingCodec<?, ?>>> entrySet() {
803 return Collections.emptySet();
807 public boolean containsValue(Object value) {
812 @SuppressWarnings({ "rawtypes", "unchecked" })
813 private class AugmentableCompositeCodec implements BindingCodec {
815 private final Class augmentableType;
817 Map<Class, AugmentationCodec<?>> localAugmentationCodecs = new WeakHashMap<>();
819 public AugmentableCompositeCodec(Class type) {
820 checkArgument(Augmentable.class.isAssignableFrom(type));
821 augmentableType = type;
825 public Object serialize(Object input) {
826 if (input instanceof Augmentable<?>) {
828 Map<Class, Augmentation> augmentations = getAugmentations(input);
829 return serializeImpl(augmentations);
834 private Map<Class, Augmentation> getAugmentations(Object input) {
835 Field augmentationField;
837 augmentationField = input.getClass().getDeclaredField("augmentation");
838 augmentationField.setAccessible(true);
839 Map<Class, Augmentation> augMap = (Map<Class, Augmentation>) augmentationField.get(input);
841 } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {
842 LOG.debug("Could not read augmentations for {}", input, e);
844 return Collections.emptyMap();
847 private List serializeImpl(Map<Class, Augmentation> input) {
848 List ret = new ArrayList<>();
849 for (Entry<Class, Augmentation> entry : input.entrySet()) {
850 AugmentationCodec codec = getCodecForAugmentation(entry.getKey());
851 CompositeNode node = codec.serialize(new ValueWithQName(null, entry.getValue()));
852 ret.addAll(node.getChildren());
857 public synchronized <T extends Augmentation<?>> void addAugmentationCodec(Class<T> augmentationClass,
858 AugmentationCodec<T> value) {
859 localAugmentationCodecs.put(augmentationClass, value);
863 public Map<Class, Augmentation> deserialize(Object input) {
864 Map<Class, Augmentation> ret = new HashMap<>();
865 if (input instanceof CompositeNode) {
866 List<Entry<Class, AugmentationCodec<?>>> codecs = new ArrayList<>(localAugmentationCodecs.entrySet());
867 for (Entry<Class, AugmentationCodec<?>> codec : codecs) {
868 ValueWithQName<?> value = codec.getValue().deserialize((CompositeNode) input);
869 if (value != null && value.getValue() != null) {
870 ret.put(codec.getKey(), (Augmentation) value.getValue());
877 public Class getAugmentableType() {
878 return augmentableType;
882 @SuppressWarnings({ "rawtypes", "unchecked" })
883 private static class LateMixinCodec implements BindingCodec, Delegator<BindingCodec> {
885 private BindingCodec delegate;
888 public BindingCodec getDelegate() {
889 if (delegate == null) {
890 throw new IllegalStateException("Codec not initialized yet.");
896 public Object deserialize(Object input) {
897 return getDelegate().deserialize(input);
901 public Object serialize(Object input) {
902 return getDelegate().serialize(input);
906 private static class AugmentationCodecWrapper<T extends Augmentation<?>> implements AugmentationCodec<T>,
907 Delegator<BindingCodec> {
909 private BindingCodec delegate;
911 public AugmentationCodecWrapper(BindingCodec<Map<QName, Object>, Object> rawCodec) {
912 this.delegate = rawCodec;
916 public BindingCodec getDelegate() {
921 public CompositeNode serialize(ValueWithQName<T> input) {
922 @SuppressWarnings("unchecked")
923 List<Map<QName, Object>> rawValues = (List<Map<QName, Object>>) getDelegate().serialize(input);
924 List<Node<?>> serialized = new ArrayList<>(rawValues.size());
925 for (Map<QName, Object> val : rawValues) {
926 serialized.add(toNode(val));
928 return new CompositeNodeTOImpl(input.getQname(), null, serialized);
932 @SuppressWarnings("unchecked")
933 public ValueWithQName<T> deserialize(Node<?> input) {
934 Object rawCodecValue = getDelegate().deserialize((Map<QName, Object>) input);
935 return new ValueWithQName<T>(input.getNodeType(), (T) rawCodecValue);
939 private class IdentityCompositeCodec implements IdentitityCodec {
942 public Object deserialize(Object input) {
943 checkArgument(input instanceof QName);
944 return deserialize((QName) input);
948 public Class<?> deserialize(QName input) {
949 Type type = qnamesToIdentityMap.get(input);
953 ReferencedTypeImpl typeref = new ReferencedTypeImpl(type.getPackageName(), type.getName());
954 WeakReference<Class> softref = typeToClass.get(typeref);
955 if(softref == null) {
958 return softref.get();
962 public QName serialize(Class input) {
963 checkArgument(BaseIdentity.class.isAssignableFrom(input));
964 bindingClassEncountered(input);
965 QName qname = identityQNames.get(input);
969 ConcreteType typeref = Types.typeForClass(input);
970 qname = typeToQname.get(typeref);
972 identityQNames.put(input, qname);
978 public Object serialize(Object input) {
979 checkArgument(input instanceof Class);
980 return serialize((Class) input);