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