7cc9f60495205c709c36186e46ce8b2f1e5c33dc
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / codec / impl / DataContainerCodecPrototype.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.mdsal.binding.dom.codec.impl;
9
10 import com.google.common.collect.Iterables;
11 import java.lang.invoke.MethodHandles;
12 import java.lang.invoke.VarHandle;
13 import org.checkerframework.checker.lock.qual.Holding;
14 import org.eclipse.jdt.annotation.NonNull;
15 import org.opendaylight.mdsal.binding.dom.codec.api.BindingDataObjectCodecTreeNode.ChildAddressabilitySummary;
16 import org.opendaylight.mdsal.binding.dom.codec.impl.NodeCodecContext.CodecContextFactory;
17 import org.opendaylight.yangtools.yang.binding.DataObject;
18 import org.opendaylight.yangtools.yang.binding.DataRoot;
19 import org.opendaylight.yangtools.yang.binding.Identifiable;
20 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.Item;
21 import org.opendaylight.yangtools.yang.common.QNameModule;
22 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
23 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
24 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
25 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
26 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
27 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
28 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
29 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
30 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
32 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
33 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
34 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
36 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
37 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 final class DataContainerCodecPrototype<T extends WithStatus> implements NodeContextSupplier {
42     private static final Logger LOG = LoggerFactory.getLogger(DataContainerCodecPrototype.class);
43
44     private static final VarHandle INSTANCE;
45
46     static {
47         try {
48             INSTANCE = MethodHandles.lookup().findVarHandle(DataContainerCodecPrototype.class,
49                 "instance", DataContainerCodecContext.class);
50         } catch (NoSuchFieldException | IllegalAccessException e) {
51             throw new ExceptionInInitializerError(e);
52         }
53     }
54
55     private final T schema;
56     private final QNameModule namespace;
57     private final CodecContextFactory factory;
58     private final Item<?> bindingArg;
59     private final PathArgument yangArg;
60     private final ChildAddressabilitySummary childAddressabilitySummary;
61
62     /*
63      * This field is now utterly in the hot path of CodecDataObject's instantiation of data. It is a volatile support
64      * double-checked locking, as detailed in https://en.wikipedia.org/wiki/Double-checked_locking#Usage_in_Java
65      *
66      * We are opting for the document Java 9 equivalent, forsaking our usual CAS-based approach, where we'd re-assert
67      * concurrent loads. This improves safety a bit (by forcing a synchronized() block), as we expect prototypes to be
68      * long-lived.
69      *
70      * FIXME: MDSAL-579: all we need is safe publish semantics here, we can most probably tolerate concurrent value
71      *                   loads -- and everything seems to be ready. This means loadInstance() should not be
72      *                   synchronized, createInstance() should not have @Holding.
73      */
74     @SuppressWarnings("unused")
75     private volatile DataContainerCodecContext<?, T> instance;
76
77     @SuppressWarnings("unchecked")
78     private DataContainerCodecPrototype(final Class<?> cls, final PathArgument arg, final T nodeSchema,
79             final CodecContextFactory factory) {
80         this(Item.of((Class<? extends DataObject>) cls), arg, nodeSchema, factory);
81     }
82
83     private DataContainerCodecPrototype(final Item<?> bindingArg, final PathArgument arg, final T nodeSchema,
84             final CodecContextFactory factory) {
85         this.bindingArg = bindingArg;
86         this.yangArg = arg;
87         this.schema = nodeSchema;
88         this.factory = factory;
89
90         if (arg instanceof AugmentationIdentifier) {
91             this.namespace = Iterables.getFirst(((AugmentationIdentifier) arg).getPossibleChildNames(), null)
92                     .getModule();
93         } else {
94             this.namespace = arg.getNodeType().getModule();
95         }
96
97         this.childAddressabilitySummary = computeChildAddressabilitySummary(nodeSchema);
98     }
99
100     private static ChildAddressabilitySummary computeChildAddressabilitySummary(final WithStatus nodeSchema) {
101         if (nodeSchema instanceof DataNodeContainer) {
102             boolean haveAddressable = false;
103             boolean haveUnaddressable = false;
104             for (DataSchemaNode child : ((DataNodeContainer) nodeSchema).getChildNodes()) {
105                 if (child instanceof ContainerSchemaNode || child instanceof AugmentationSchemaNode) {
106                     haveAddressable = true;
107                 } else if (child instanceof ListSchemaNode) {
108                     if (((ListSchemaNode) child).getKeyDefinition().isEmpty()) {
109                         haveUnaddressable = true;
110                     } else {
111                         haveAddressable = true;
112                     }
113                 } else if (child instanceof AnydataSchemaNode || child instanceof AnyxmlSchemaNode
114                         || child instanceof TypedDataSchemaNode) {
115                     haveUnaddressable = true;
116                 } else if (child instanceof ChoiceSchemaNode) {
117                     switch (computeChildAddressabilitySummary(child)) {
118                         case ADDRESSABLE:
119                             haveAddressable = true;
120                             break;
121                         case MIXED:
122                             haveAddressable = true;
123                             haveUnaddressable = true;
124                             break;
125                         case UNADDRESSABLE:
126                             haveUnaddressable = true;
127                             break;
128                         default:
129                             throw new IllegalStateException("Unhandled accessibility summary for " + child);
130                     }
131                 } else {
132                     LOG.warn("Unhandled child node {}", child);
133                 }
134             }
135
136             if (!haveAddressable) {
137                 // Empty or all are unaddressable
138                 return ChildAddressabilitySummary.UNADDRESSABLE;
139             }
140
141             return haveUnaddressable ? ChildAddressabilitySummary.MIXED : ChildAddressabilitySummary.ADDRESSABLE;
142         } else if (nodeSchema instanceof ChoiceSchemaNode) {
143             boolean haveAddressable = false;
144             boolean haveUnaddressable = false;
145             for (CaseSchemaNode child : ((ChoiceSchemaNode) nodeSchema).getCases()) {
146                 switch (computeChildAddressabilitySummary(child)) {
147                     case ADDRESSABLE:
148                         haveAddressable = true;
149                         break;
150                     case UNADDRESSABLE:
151                         haveUnaddressable = true;
152                         break;
153                     case MIXED:
154                         // A child is mixed, which means we are mixed, too
155                         return ChildAddressabilitySummary.MIXED;
156                     default:
157                         throw new IllegalStateException("Unhandled accessibility summary for " + child);
158                 }
159             }
160
161             if (!haveAddressable) {
162                 // Empty or all are unaddressable
163                 return ChildAddressabilitySummary.UNADDRESSABLE;
164             }
165
166             return haveUnaddressable ? ChildAddressabilitySummary.MIXED : ChildAddressabilitySummary.ADDRESSABLE;
167         }
168
169         // No child nodes possible: return unaddressable
170         return ChildAddressabilitySummary.UNADDRESSABLE;
171     }
172
173     static DataContainerCodecPrototype<SchemaContext> rootPrototype(final CodecContextFactory factory) {
174         final SchemaContext schema = factory.getRuntimeContext().getEffectiveModelContext();
175         final NodeIdentifier arg = NodeIdentifier.create(schema.getQName());
176         return new DataContainerCodecPrototype<>(DataRoot.class, arg, schema, factory);
177     }
178
179     @SuppressWarnings({ "unchecked", "rawtypes" })
180     static <T extends DataSchemaNode> DataContainerCodecPrototype<T> from(final Class<?> cls, final T schema,
181             final CodecContextFactory factory) {
182         return new DataContainerCodecPrototype(cls, NodeIdentifier.create(schema.getQName()), schema, factory);
183     }
184
185     @SuppressWarnings({ "unchecked", "rawtypes" })
186     static <T extends DataSchemaNode> DataContainerCodecPrototype<T> from(final Item<?> bindingArg, final T schema,
187             final CodecContextFactory factory) {
188         return new DataContainerCodecPrototype(bindingArg, NodeIdentifier.create(schema.getQName()), schema, factory);
189     }
190
191     @SuppressWarnings({ "rawtypes", "unchecked" })
192     static DataContainerCodecPrototype<?> from(final Class<?> augClass, final AugmentationIdentifier arg,
193             final AugmentationSchemaNode schema, final CodecContextFactory factory) {
194         return new DataContainerCodecPrototype(augClass, arg, schema, factory);
195     }
196
197     static DataContainerCodecPrototype<NotificationDefinition> from(final Class<?> augClass,
198             final NotificationDefinition schema, final CodecContextFactory factory) {
199         final PathArgument arg = NodeIdentifier.create(schema.getQName());
200         return new DataContainerCodecPrototype<>(augClass,arg, schema, factory);
201     }
202
203     protected T getSchema() {
204         return schema;
205     }
206
207     ChildAddressabilitySummary getChildAddressabilitySummary() {
208         return childAddressabilitySummary;
209     }
210
211     protected QNameModule getNamespace() {
212         return namespace;
213     }
214
215     protected CodecContextFactory getFactory() {
216         return factory;
217     }
218
219     protected Class<?> getBindingClass() {
220         return bindingArg.getType();
221     }
222
223     protected Item<?> getBindingArg() {
224         return bindingArg;
225     }
226
227     protected PathArgument getYangArg() {
228         return yangArg;
229     }
230
231     @Override
232     public DataContainerCodecContext<?, T> get() {
233         final DataContainerCodecContext<?, T> existing = getInstance();
234         return existing != null ? existing : loadInstance();
235     }
236
237     private synchronized @NonNull DataContainerCodecContext<?, T> loadInstance() {
238         // re-acquire under lock
239         DataContainerCodecContext<?, T> tmp = getInstance();
240         if (tmp == null) {
241             tmp = createInstance();
242             INSTANCE.setRelease(this, tmp);
243         }
244         return tmp;
245     }
246
247     // Helper for getAcquire access to instance
248     private DataContainerCodecContext<?, T> getInstance() {
249         return (DataContainerCodecContext<?, T>) INSTANCE.getAcquire(this);
250     }
251
252     @Holding("this")
253     @SuppressWarnings({ "rawtypes", "unchecked" })
254     private @NonNull DataContainerCodecContext<?, T> createInstance() {
255         // FIXME: make protected abstract
256         if (schema instanceof ContainerSchemaNode) {
257             return new ContainerNodeCodecContext(this);
258         } else if (schema instanceof ListSchemaNode) {
259             return Identifiable.class.isAssignableFrom(getBindingClass())
260                     ? KeyedListNodeCodecContext.create((DataContainerCodecPrototype<ListSchemaNode>) this)
261                             : new ListNodeCodecContext(this);
262         } else if (schema instanceof ChoiceSchemaNode) {
263             return new ChoiceNodeCodecContext(this);
264         } else if (schema instanceof AugmentationSchemaNode) {
265             return new AugmentationNodeContext(this);
266         } else if (schema instanceof CaseSchemaNode) {
267             return new CaseNodeCodecContext(this);
268         }
269         throw new IllegalArgumentException("Unsupported type " + getBindingClass() + " " + schema);
270     }
271
272     boolean isChoice() {
273         return schema instanceof ChoiceSchemaNode;
274     }
275 }