Split out BindingRuntimeGenerator
[yangtools.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / codec / gen / impl / AbstractStreamWriterGenerator.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.gen.impl;
9
10 import com.google.common.base.Preconditions;
11 import com.google.common.base.Supplier;
12 import com.google.common.cache.CacheBuilder;
13 import com.google.common.cache.CacheLoader;
14 import com.google.common.cache.LoadingCache;
15 import java.lang.reflect.Field;
16 import java.lang.reflect.InvocationTargetException;
17 import java.util.Map.Entry;
18 import javassist.CannotCompileException;
19 import javassist.CtClass;
20 import javassist.CtField;
21 import javassist.CtMethod;
22 import javassist.Modifier;
23 import javassist.NotFoundException;
24 import org.opendaylight.mdsal.binding.dom.codec.gen.spi.StaticConstantDefinition;
25 import org.opendaylight.mdsal.binding.dom.codec.util.AugmentableDispatchSerializer;
26 import org.opendaylight.mdsal.binding.generator.util.BindingRuntimeContext;
27 import org.opendaylight.mdsal.binding.generator.util.JavassistUtils;
28 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
29 import org.opendaylight.mdsal.binding.model.util.Types;
30 import org.opendaylight.yangtools.util.ClassLoaderUtils;
31 import org.opendaylight.yangtools.yang.binding.BindingStreamEventWriter;
32 import org.opendaylight.yangtools.yang.binding.DataContainer;
33 import org.opendaylight.yangtools.yang.binding.DataObject;
34 import org.opendaylight.yangtools.yang.binding.DataObjectSerializerImplementation;
35 import org.opendaylight.yangtools.yang.binding.DataObjectSerializerRegistry;
36 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
37 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
41 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 abstract class AbstractStreamWriterGenerator extends AbstractGenerator implements DataObjectSerializerGenerator {
47     private static final Logger LOG = LoggerFactory.getLogger(AbstractStreamWriterGenerator.class);
48
49     protected static final String SERIALIZE_METHOD_NAME = "serialize";
50     protected static final AugmentableDispatchSerializer AUGMENTABLE = new AugmentableDispatchSerializer();
51     private static final Field FIELD_MODIFIERS;
52
53     private final LoadingCache<Class<?>, DataObjectSerializerImplementation> implementations;
54     private final CtClass[] serializeArguments;
55     private final JavassistUtils javassist;
56     private BindingRuntimeContext context;
57
58     static {
59         /*
60          * Cache reflection access to field modifiers field. We need this to set
61          * fix the static declared fields to final once we initialize them. If we
62          * cannot get access, that's fine, too.
63          */
64         Field field = null;
65         try {
66             field = Field.class.getDeclaredField("modifiers");
67             field.setAccessible(true);
68         } catch (NoSuchFieldException | SecurityException e) {
69             LOG.warn("Could not get Field modifiers field, serializers run at decreased efficiency", e);
70         }
71
72         FIELD_MODIFIERS = field;
73     }
74
75     protected AbstractStreamWriterGenerator(final JavassistUtils utils) {
76         this.javassist = Preconditions.checkNotNull(utils,"JavassistUtils instance is required.");
77         this.serializeArguments = new CtClass[] {
78                 javassist.asCtClass(DataObjectSerializerRegistry.class),
79                 javassist.asCtClass(DataObject.class),
80                 javassist.asCtClass(BindingStreamEventWriter.class),
81         };
82         javassist.appendClassLoaderIfMissing(DataObjectSerializerPrototype.class.getClassLoader());
83         this.implementations = CacheBuilder.newBuilder().weakKeys().build(new SerializerImplementationLoader());
84     }
85
86     @Override
87     public final DataObjectSerializerImplementation getSerializer(final Class<?> type) {
88         return implementations.getUnchecked(type);
89     }
90
91     @Override
92     public final void onBindingRuntimeContextUpdated(final BindingRuntimeContext runtime) {
93         this.context = runtime;
94     }
95
96     @Override
97     protected final String loadSerializerFor(final Class<?> cls) {
98         return implementations.getUnchecked(cls).getClass().getName();
99     }
100
101     private final class SerializerImplementationLoader
102             extends CacheLoader<Class<?>, DataObjectSerializerImplementation> {
103
104         private static final String GETINSTANCE_METHOD_NAME = "getInstance";
105         private static final String SERIALIZER_SUFFIX = "$StreamWriter";
106
107         private String getSerializerName(final Class<?> type) {
108             return type.getName() + SERIALIZER_SUFFIX;
109         }
110
111         @Override
112         @SuppressWarnings("unchecked")
113         public DataObjectSerializerImplementation load(final Class<?> type) throws Exception {
114             Preconditions.checkArgument(BindingReflections.isBindingClass(type));
115             Preconditions.checkArgument(DataContainer.class.isAssignableFrom(type),
116                 "DataContainer is not assingnable from %s from classloader %s.", type, type.getClassLoader());
117
118             final String serializerName = getSerializerName(type);
119
120             Class<? extends DataObjectSerializerImplementation> cls;
121             try {
122                 cls = (Class<? extends DataObjectSerializerImplementation>) ClassLoaderUtils
123                         .loadClass(type.getClassLoader(), serializerName);
124             } catch (final ClassNotFoundException e) {
125                 cls = generateSerializer(type, serializerName);
126             }
127
128             final DataObjectSerializerImplementation obj =
129                     (DataObjectSerializerImplementation) cls.getDeclaredMethod(GETINSTANCE_METHOD_NAME).invoke(null);
130             LOG.debug("Loaded serializer {} for class {}", obj, type);
131             return obj;
132         }
133
134         private Class<? extends DataObjectSerializerImplementation> generateSerializer(final Class<?> type,
135                 final String serializerName) throws CannotCompileException, IllegalAccessException,
136                 IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException,
137                 NoSuchFieldException {
138             final DataObjectSerializerSource source = generateEmitterSource(type, serializerName);
139             final CtClass poolClass = generateEmitter0(type, source, serializerName);
140             @SuppressWarnings("unchecked")
141             final Class<? extends DataObjectSerializerImplementation> cls = poolClass.toClass(type.getClassLoader(),
142                 type.getProtectionDomain());
143
144             /*
145              * Due to OSGi class loader rules we cannot initialize the fields during
146              * construction, as the initializer expressions do not see our implementation
147              * classes. This should be almost as good as that, as we are resetting the
148              * fields to final before ever leaking the class.
149              */
150             for (final StaticConstantDefinition constant : source.getStaticConstants()) {
151                 final Field field = cls.getDeclaredField(constant.getName());
152                 field.setAccessible(true);
153                 field.set(null, constant.getValue());
154
155                 if (FIELD_MODIFIERS != null) {
156                     FIELD_MODIFIERS.setInt(field, field.getModifiers() | Modifier.FINAL);
157                 }
158             }
159
160             return cls;
161         }
162     }
163
164     private DataObjectSerializerSource generateEmitterSource(final Class<?> type, final String serializerName) {
165         Types.typeForClass(type);
166         javassist.appendClassLoaderIfMissing(type.getClassLoader());
167         final Entry<GeneratedType, WithStatus> typeWithSchema = context.getTypeWithSchema(type);
168         final GeneratedType generatedType = typeWithSchema.getKey();
169         final WithStatus schema = typeWithSchema.getValue();
170
171         final DataObjectSerializerSource source;
172         if (schema instanceof ContainerSchemaNode) {
173             source = generateContainerSerializer(generatedType, (ContainerSchemaNode) schema);
174         } else if (schema instanceof ListSchemaNode) {
175             final ListSchemaNode casted = (ListSchemaNode) schema;
176             if (casted.getKeyDefinition().isEmpty()) {
177                 source = generateUnkeyedListEntrySerializer(generatedType, casted);
178             } else {
179                 source = generateMapEntrySerializer(generatedType, casted);
180             }
181         } else if (schema instanceof AugmentationSchemaNode) {
182             source = generateSerializer(generatedType,(AugmentationSchemaNode) schema);
183         } else if (schema instanceof CaseSchemaNode) {
184             source = generateCaseSerializer(generatedType,(CaseSchemaNode) schema);
185         } else if (schema instanceof NotificationDefinition) {
186             source = generateNotificationSerializer(generatedType,(NotificationDefinition) schema);
187         } else {
188             throw new UnsupportedOperationException("Schema type " + schema.getClass() + " is not supported");
189         }
190         return source;
191     }
192
193     private CtClass generateEmitter0(final Class<?> type, final DataObjectSerializerSource source,
194             final String serializerName) {
195         final CtClass product;
196
197         /*
198          * getSerializerBody() has side effects, such as loading classes and codecs, it should be run in model class
199          * loader in order to correctly reference load child classes.
200          *
201          * Furthermore the fact that getSerializedBody() can trigger other code generation to happen, we need to take
202          * care of this before calling instantiatePrototype(), as that will call our customizer with the lock held,
203          * hence any code generation will end up being blocked on the javassist lock.
204          */
205         final String body = ClassLoaderUtils.withClassLoader(type.getClassLoader(),
206             (Supplier<String>) () -> source.getSerializerBody().toString());
207
208         try {
209             product = javassist.instantiatePrototype(DataObjectSerializerPrototype.class.getName(), serializerName,
210                 cls -> {
211                     // Generate any static fields
212                     for (final StaticConstantDefinition def : source.getStaticConstants()) {
213                         final CtField field = new CtField(javassist.asCtClass(def.getType()), def.getName(), cls);
214                         field.setModifiers(Modifier.PRIVATE + Modifier.STATIC);
215                         cls.addField(field);
216                     }
217
218                     // Replace serialize() -- may reference static fields
219                     final CtMethod serializeTo = cls.getDeclaredMethod(SERIALIZE_METHOD_NAME, serializeArguments);
220                     serializeTo.setBody(body);
221
222                     // The prototype is not visible, so we need to take care of that
223                     cls.setModifiers(Modifier.setPublic(cls.getModifiers()));
224                 });
225         } catch (final NotFoundException e) {
226             LOG.error("Failed to instatiate serializer {}", source, e);
227             throw new LinkageError("Unexpected instantation problem: serializer prototype not found", e);
228         }
229         return product;
230     }
231
232     /**
233      * Generates serializer source code for supplied container node, which will read supplied binding type and invoke
234      * proper methods on supplied {@link BindingStreamEventWriter}.
235      *
236      * <p>
237      * Implementation is required to recursively invoke events for all reachable binding objects.
238      *
239      * @param type Binding type of container
240      * @param node Schema of container
241      * @return Source for container node writer
242      */
243     protected abstract DataObjectSerializerSource generateContainerSerializer(GeneratedType type,
244             ContainerSchemaNode node);
245
246     /**
247      * Generates serializer source for supplied case node, which will read supplied binding type and invoke proper
248      * methods on supplied {@link BindingStreamEventWriter}.
249      *
250      * <p>
251      * Implementation is required to recursively invoke events for all reachable binding objects.
252      *
253      * @param type Binding type of case
254      * @param node Schema of case
255      * @return Source for case node writer
256      */
257     protected abstract DataObjectSerializerSource generateCaseSerializer(GeneratedType type, CaseSchemaNode node);
258
259     /**
260      * Generates serializer source for supplied list node, which will read supplied binding type and invoke proper
261      * methods on supplied {@link BindingStreamEventWriter}.
262      *
263      * <p>
264      * Implementation is required to recursively invoke events for all reachable binding objects.
265      *
266      * @param type Binding type of list
267      * @param node Schema of list
268      * @return Source for list node writer
269      */
270     protected abstract DataObjectSerializerSource generateMapEntrySerializer(GeneratedType type, ListSchemaNode node);
271
272     /**
273      * Generates serializer source for supplied list node, which will read supplied binding type and invoke proper
274      * methods on supplied {@link BindingStreamEventWriter}.
275      *
276      * <p>
277      * Implementation is required to recursively invoke events for all reachable binding objects.
278      *
279      * @param type Binding type of list
280      * @param node Schema of list
281      * @return Source for list node writer
282      */
283     protected abstract DataObjectSerializerSource generateUnkeyedListEntrySerializer(GeneratedType type,
284             ListSchemaNode node);
285
286     /**
287      * Generates serializer source for supplied augmentation node, which will read supplied binding type and invoke
288      * proper methods on supplied {@link BindingStreamEventWriter}.
289      *
290      * <p>
291      * Implementation is required to recursively invoke events for all reachable binding objects.
292      *
293      * @param type Binding type of augmentation
294      * @param schema Schema of augmentation
295      * @return Source for augmentation node writer
296      */
297     protected abstract DataObjectSerializerSource generateSerializer(GeneratedType type, AugmentationSchemaNode schema);
298
299     /**
300      * Generates serializer source for notification node, which will read supplied binding type and invoke proper
301      * methods on supplied {@link BindingStreamEventWriter}.
302      *
303      * <p>
304      * Implementation is required to recursively invoke events for all reachable binding objects.
305      *
306      * @param type Binding type of notification
307      * @param node Schema of notification
308      * @return Source for notification node writer
309      */
310     protected abstract DataObjectSerializerSource generateNotificationSerializer(GeneratedType type,
311             NotificationDefinition node);
312 }