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()) {
394 new ReferencedTypeImpl(identity.getValue().getPackageName(), identity.getValue().getName()),
397 captureCases(context.getCases(), schemaContext);
400 private void captureCases(Map<SchemaPath, GeneratedTypeBuilder> cases, SchemaContext module) {
401 for (Entry<SchemaPath, GeneratedTypeBuilder> caseNode : cases.entrySet()) {
402 ReferencedTypeImpl typeref = new ReferencedTypeImpl(caseNode.getValue().getPackageName(), caseNode
403 .getValue().getName());
405 pathToType.put(caseNode.getKey(), caseNode.getValue());
407 ChoiceCaseNode node = (ChoiceCaseNode) SchemaContextUtil.findDataSchemaNode(module, caseNode.getKey());
410 LOG.error("YANGTools Bug: SchemaNode for {}, with path {} was not found in context.",
411 typeref.getFullyQualifiedName(), caseNode.getKey());
412 @SuppressWarnings("rawtypes")
413 ChoiceCaseCodecImpl value = new ChoiceCaseCodecImpl();
414 typeToCaseCodecs.putIfAbsent(typeref, value);
417 @SuppressWarnings("rawtypes")
418 ChoiceCaseCodecImpl value = new ChoiceCaseCodecImpl(node);
419 typeToCaseCodecs.putIfAbsent(typeref, value);
424 public void onGlobalContextUpdated(SchemaContext context) {
425 currentSchema = context;
428 @SuppressWarnings({ "unchecked", "rawtypes" })
430 public void onChoiceCodecCreated(Class<?> choiceClass,
431 Class<? extends BindingCodec<Map<QName, Object>, Object>> choiceCodec, ChoiceNode schema) {
432 ChoiceCodec<?> oldCodec = choiceCodecs.get(choiceClass);
433 checkState(oldCodec == null);
434 BindingCodec<Map<QName, Object>, Object> delegate = newInstanceOf(choiceCodec);
435 ChoiceCodecImpl<?> newCodec = new ChoiceCodecImpl(delegate);
436 choiceCodecs.put(choiceClass, newCodec);
437 CodecMapping.setClassToCaseMap(choiceCodec, (Map<Class<?>, BindingCodec<?, ?>>) classToCaseRawCodec);
438 CodecMapping.setCompositeNodeToCaseMap(choiceCodec, newCodec.getCompositeToCase());
440 tryToCreateCasesCodecs(schema);
444 private void tryToCreateCasesCodecs(ChoiceNode schema) {
445 for (ChoiceCaseNode caseNode : schema.getCases()) {
446 SchemaPath path = caseNode.getPath();
447 GeneratedTypeBuilder type;
448 if (path != null && (type = pathToType.get(path)) != null) {
449 ReferencedTypeImpl typeref = new ReferencedTypeImpl(type.getPackageName(), type.getName());
450 ChoiceCaseCodecImpl partialCodec = typeToCaseCodecs.get(typeref);
451 if (partialCodec.getSchema() == null) {
452 partialCodec.setSchema(caseNode);
455 Class<?> caseClass = ClassLoaderUtils.tryToLoadClassWithTCCL(type.getFullyQualifiedName());
456 if (caseClass != null) {
457 getCaseCodecFor(caseClass);
465 public void onValueCodecCreated(Class<?> valueClass, Class<?> valueCodec) {
469 public void onCaseCodecCreated(Class<?> choiceClass,
470 Class<? extends BindingCodec<Map<QName, Object>, Object>> choiceCodec) {
474 public void onDataContainerCodecCreated(Class<?> dataClass, Class<? extends BindingCodec<?, ?>> dataCodec) {
475 if (Augmentable.class.isAssignableFrom(dataClass)) {
476 AugmentableCompositeCodec augmentableCodec = getAugmentableCodec(dataClass);
477 CodecMapping.setAugmentationCodec(dataCodec, augmentableCodec);
482 public AugmentableCompositeCodec getAugmentableCodec(Class<?> dataClass) {
483 AugmentableCompositeCodec ret = augmentableCodecs.get(dataClass);
487 ret = new AugmentableCompositeCodec(dataClass);
488 augmentableCodecs.put(dataClass, ret);
492 private static abstract class IntermediateCodec<T> implements //
493 DomCodec<T>, Delegator<BindingCodec<Map<QName, Object>, Object>> {
495 private final BindingCodec<Map<QName, Object>, Object> delegate;
498 public BindingCodec<Map<QName, Object>, Object> getDelegate() {
502 public IntermediateCodec(BindingCodec<Map<QName, Object>, Object> delegate) {
503 this.delegate = delegate;
507 public Node<?> serialize(ValueWithQName<T> input) {
508 Map<QName, Object> intermediateOutput = delegate.serialize(input);
509 return toNode(intermediateOutput);
513 private static class IdentifierCodecImpl<T extends Identifier<?>> //
514 extends IntermediateCodec<T> //
515 implements IdentifierCodec<T> {
517 public IdentifierCodecImpl(BindingCodec<Map<QName, Object>, Object> delegate) {
522 public ValueWithQName<T> deserialize(Node<?> input) {
523 QName qname = input.getNodeType();
524 @SuppressWarnings("unchecked")
525 T value = (T) getDelegate().deserialize((Map<QName, Object>) input);
526 return new ValueWithQName<T>(qname, value);
530 public CompositeNode serialize(ValueWithQName<T> input) {
531 return (CompositeNode) super.serialize(input);
535 private static class DataContainerCodecImpl<T extends DataContainer> //
536 extends IntermediateCodec<T> //
537 implements DataContainerCodec<T> {
539 public DataContainerCodecImpl(BindingCodec<Map<QName, Object>, Object> delegate) {
544 public ValueWithQName<T> deserialize(Node<?> input) {
548 QName qname = input.getNodeType();
549 @SuppressWarnings("unchecked")
550 T value = (T) getDelegate().deserialize((Map<QName, Object>) input);
551 return new ValueWithQName<T>(qname, value);
555 public CompositeNode serialize(ValueWithQName<T> input) {
556 return (CompositeNode) super.serialize(input);
560 @SuppressWarnings("rawtypes")
561 private static class ChoiceCaseCodecImpl<T extends DataContainer> implements ChoiceCaseCodec<T>, //
562 Delegator<BindingCodec> {
563 private boolean augmenting;
564 private BindingCodec delegate;
566 private Set<String> validNames;
567 private Set<QName> validQNames;
568 private ChoiceCaseNode schema;
570 public void setSchema(ChoiceCaseNode caseNode) {
571 this.schema = schema;
572 this.schema = caseNode;
573 validNames = new HashSet<>();
574 validQNames = new HashSet<>();
575 for (DataSchemaNode node : caseNode.getChildNodes()) {
576 QName qname = node.getQName();
577 validQNames.add(qname);
578 validNames.add(qname.getLocalName());
580 augmenting = caseNode.isAugmenting();
583 public ChoiceCaseCodecImpl() {
584 this.delegate = NOT_READY_CODEC;
587 public ChoiceCaseCodecImpl(ChoiceCaseNode caseNode) {
588 this.delegate = NOT_READY_CODEC;
593 public ValueWithQName<T> deserialize(Node<?> input) {
594 throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
598 public CompositeNode serialize(ValueWithQName<T> input) {
599 throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
602 public BindingCodec getDelegate() {
606 public void setDelegate(BindingCodec delegate) {
607 this.delegate = delegate;
610 public ChoiceCaseNode getSchema() {
615 public boolean isAcceptable(Node<?> input) {
616 if (input instanceof CompositeNode) {
618 return checkAugmenting((CompositeNode) input);
620 return checkLocal((CompositeNode) input);
626 private boolean checkLocal(CompositeNode input) {
627 QName parent = input.getNodeType();
628 for (Node<?> childNode : input.getChildren()) {
629 QName child = childNode.getNodeType();
630 if (!Objects.equals(parent.getNamespace(), child.getNamespace())
631 || !Objects.equals(parent.getRevision(), child.getRevision())) {
634 if (validNames.contains(child.getLocalName())) {
641 private boolean checkAugmenting(CompositeNode input) {
642 for (Node<?> child : input.getChildren()) {
643 if (validQNames.contains(child.getNodeType())) {
651 private static class ChoiceCodecImpl<T> implements ChoiceCodec<T> {
653 private final BindingCodec<Map<QName, Object>, Object> delegate;
655 @SuppressWarnings("rawtypes")
656 private final Map<Class, ChoiceCaseCodecImpl<?>> cases = new WeakHashMap<>();
658 private final CaseCompositeNodeMapFacade CompositeToCase;
660 public ChoiceCodecImpl(BindingCodec<Map<QName, Object>, Object> delegate) {
661 this.delegate = delegate;
662 this.CompositeToCase = new CaseCompositeNodeMapFacade(cases);
666 public ValueWithQName<T> deserialize(Node<?> input) {
667 throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
671 public Node<?> serialize(ValueWithQName<T> input) {
672 throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
675 public CaseCompositeNodeMapFacade getCompositeToCase() {
676 return CompositeToCase;
679 public Map<Class, ChoiceCaseCodecImpl<?>> getCases() {
683 public BindingCodec<Map<QName, Object>, Object> getDelegate() {
689 @SuppressWarnings("rawtypes")
690 private class CaseClassMapFacade extends MapFacadeBase {
693 public Set<java.util.Map.Entry<Class, BindingCodec<Object, Object>>> entrySet() {
694 return Collections.emptySet();
698 public BindingCodec get(Object key) {
699 if (key instanceof Class) {
700 Class cls = (Class) key;
701 // bindingClassEncountered(cls);
702 ChoiceCaseCodecImpl caseCodec = getCaseCodecFor(cls);
703 return caseCodec.getDelegate();
709 @SuppressWarnings("rawtypes")
710 private static class CaseCompositeNodeMapFacade extends MapFacadeBase<CompositeNode> {
712 final Map<Class, ChoiceCaseCodecImpl<?>> choiceCases;
714 public CaseCompositeNodeMapFacade(Map<Class, ChoiceCaseCodecImpl<?>> choiceCases) {
715 this.choiceCases = choiceCases;
719 public BindingCodec get(Object key) {
720 if (!(key instanceof CompositeNode)) {
723 for (java.util.Map.Entry<Class, ChoiceCaseCodecImpl<?>> entry : choiceCases.entrySet()) {
724 ChoiceCaseCodecImpl<?> codec = entry.getValue();
725 if (codec.isAcceptable((CompositeNode) key)) {
726 return codec.getDelegate();
735 * This map is used as only facade for {@link BindingCodec} in different
736 * classloaders to retrieve codec dynamicly based on provided key.
741 @SuppressWarnings("rawtypes")
742 private static abstract class MapFacadeBase<T> implements Map<T, BindingCodec<?, ?>> {
745 public boolean containsKey(Object key) {
746 return get(key) != null;
750 public void clear() {
751 throw notModifiable();
755 public boolean equals(Object obj) {
756 return super.equals(obj);
760 public BindingCodec remove(Object key) {
770 public Collection<BindingCodec<?, ?>> values() {
771 return Collections.emptySet();
774 private UnsupportedOperationException notModifiable() {
775 return new UnsupportedOperationException("Not externally modifiable.");
779 public BindingCodec<Map<QName, Object>, Object> put(T key, BindingCodec<?, ?> value) {
780 throw notModifiable();
784 public void putAll(Map<? extends T, ? extends BindingCodec<?, ?>> m) {
785 throw notModifiable();
789 public int hashCode() {
790 return super.hashCode();
794 public boolean isEmpty() {
799 public Set<T> keySet() {
800 return Collections.emptySet();
804 public Set<java.util.Map.Entry<T, BindingCodec<?, ?>>> entrySet() {
805 return Collections.emptySet();
809 public boolean containsValue(Object value) {
814 @SuppressWarnings({ "rawtypes", "unchecked" })
815 private class AugmentableCompositeCodec implements BindingCodec {
817 private final Class augmentableType;
819 Map<Class, AugmentationCodec<?>> localAugmentationCodecs = new WeakHashMap<>();
821 public AugmentableCompositeCodec(Class type) {
822 checkArgument(Augmentable.class.isAssignableFrom(type));
823 augmentableType = type;
827 public Object serialize(Object input) {
828 if (input instanceof Augmentable<?>) {
830 Map<Class, Augmentation> augmentations = getAugmentations(input);
831 return serializeImpl(augmentations);
836 private Map<Class, Augmentation> getAugmentations(Object input) {
837 Field augmentationField;
839 augmentationField = input.getClass().getDeclaredField("augmentation");
840 augmentationField.setAccessible(true);
841 Map<Class, Augmentation> augMap = (Map<Class, Augmentation>) augmentationField.get(input);
843 } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {
844 LOG.debug("Could not read augmentations for {}", input, e);
846 return Collections.emptyMap();
849 private List serializeImpl(Map<Class, Augmentation> input) {
850 List ret = new ArrayList<>();
851 for (Entry<Class, Augmentation> entry : input.entrySet()) {
852 AugmentationCodec codec = getCodecForAugmentation(entry.getKey());
853 CompositeNode node = codec.serialize(new ValueWithQName(null, entry.getValue()));
854 ret.addAll(node.getChildren());
859 public synchronized <T extends Augmentation<?>> void addAugmentationCodec(Class<T> augmentationClass,
860 AugmentationCodec<T> value) {
861 localAugmentationCodecs.put(augmentationClass, value);
865 public Map<Class, Augmentation> deserialize(Object input) {
866 Map<Class, Augmentation> ret = new HashMap<>();
867 if (input instanceof CompositeNode) {
868 List<Entry<Class, AugmentationCodec<?>>> codecs = new ArrayList<>(localAugmentationCodecs.entrySet());
869 for (Entry<Class, AugmentationCodec<?>> codec : codecs) {
870 ValueWithQName<?> value = codec.getValue().deserialize((CompositeNode) input);
871 if (value != null && value.getValue() != null) {
872 ret.put(codec.getKey(), (Augmentation) value.getValue());
879 public Class getAugmentableType() {
880 return augmentableType;
884 @SuppressWarnings({ "rawtypes", "unchecked" })
885 private static class LateMixinCodec implements BindingCodec, Delegator<BindingCodec> {
887 private BindingCodec delegate;
890 public BindingCodec getDelegate() {
891 if (delegate == null) {
892 throw new IllegalStateException("Codec not initialized yet.");
898 public Object deserialize(Object input) {
899 return getDelegate().deserialize(input);
903 public Object serialize(Object input) {
904 return getDelegate().serialize(input);
908 private static class AugmentationCodecWrapper<T extends Augmentation<?>> implements AugmentationCodec<T>,
909 Delegator<BindingCodec> {
911 private BindingCodec delegate;
913 public AugmentationCodecWrapper(BindingCodec<Map<QName, Object>, Object> rawCodec) {
914 this.delegate = rawCodec;
918 public BindingCodec getDelegate() {
923 public CompositeNode serialize(ValueWithQName<T> input) {
924 @SuppressWarnings("unchecked")
925 List<Map<QName, Object>> rawValues = (List<Map<QName, Object>>) getDelegate().serialize(input);
926 List<Node<?>> serialized = new ArrayList<>(rawValues.size());
927 for (Map<QName, Object> val : rawValues) {
928 serialized.add(toNode(val));
930 return new CompositeNodeTOImpl(input.getQname(), null, serialized);
934 @SuppressWarnings("unchecked")
935 public ValueWithQName<T> deserialize(Node<?> input) {
936 Object rawCodecValue = getDelegate().deserialize((Map<QName, Object>) input);
937 return new ValueWithQName<T>(input.getNodeType(), (T) rawCodecValue);
941 private class IdentityCompositeCodec implements IdentitityCodec {
944 public Object deserialize(Object input) {
945 checkArgument(input instanceof QName);
946 return deserialize((QName) input);
950 public Class<?> deserialize(QName input) {
951 Type type = qnamesToIdentityMap.get(input);
955 ReferencedTypeImpl typeref = new ReferencedTypeImpl(type.getPackageName(), type.getName());
956 WeakReference<Class> softref = typeToClass.get(typeref);
957 if (softref == null) {
960 return softref.get();
964 public QName serialize(Class input) {
965 checkArgument(BaseIdentity.class.isAssignableFrom(input));
966 bindingClassEncountered(input);
967 QName qname = identityQNames.get(input);
971 ConcreteType typeref = Types.typeForClass(input);
972 qname = typeToQname.get(typeref);
974 identityQNames.put(input, qname);
980 public Object serialize(Object input) {
981 checkArgument(input instanceof Class);
982 return serialize((Class) input);
986 public boolean isCodecAvailable(Class<? extends DataContainer> cls) {
987 if (containerCodecs.containsKey(cls)) {
990 if (identifierCodecs.containsKey(cls)) {
993 if (choiceCodecs.containsKey(cls)) {
996 if (caseCodecs.containsKey(cls)) {
999 if (augmentableCodecs.containsKey(cls)) {
1002 if (augmentationCodecs.containsKey(cls)) {