Introduce top-level pom file.
[mdsal.git] / code-generator / binding-data-codec / src / main / java / org / opendaylight / yangtools / binding / data / 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.yangtools.binding.data.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.yangtools.binding.data.codec.gen.spi.StaticConstantDefinition;
25 import org.opendaylight.yangtools.binding.data.codec.util.AugmentableDispatchSerializer;
26 import org.opendaylight.yangtools.binding.generator.util.Types;
27 import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
28 import org.opendaylight.yangtools.sal.binding.generator.util.ClassCustomizer;
29 import org.opendaylight.yangtools.sal.binding.generator.util.JavassistUtils;
30 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType;
31 import org.opendaylight.yangtools.util.ClassLoaderUtils;
32 import org.opendaylight.yangtools.yang.binding.BindingStreamEventWriter;
33 import org.opendaylight.yangtools.yang.binding.DataContainer;
34 import org.opendaylight.yangtools.yang.binding.DataObject;
35 import org.opendaylight.yangtools.yang.binding.DataObjectSerializerImplementation;
36 import org.opendaylight.yangtools.yang.binding.DataObjectSerializerRegistry;
37 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
38 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
39 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
40 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
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 f = null;
65         try {
66             f = Field.class.getDeclaredField("modifiers");
67             f.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 = f;
73     }
74
75     protected AbstractStreamWriterGenerator(final JavassistUtils utils) {
76         super();
77         this.javassist = Preconditions.checkNotNull(utils,"JavassistUtils instance is required.");
78         this.serializeArguments = new CtClass[] {
79                 javassist.asCtClass(DataObjectSerializerRegistry.class),
80                 javassist.asCtClass(DataObject.class),
81                 javassist.asCtClass(BindingStreamEventWriter.class),
82         };
83         javassist.appendClassLoaderIfMissing(DataObjectSerializerPrototype.class.getClassLoader());
84         this.implementations = CacheBuilder.newBuilder().weakKeys().build(new SerializerImplementationLoader());
85     }
86
87     @Override
88     public final DataObjectSerializerImplementation getSerializer(final Class<?> type) {
89         return implementations.getUnchecked(type);
90     }
91
92     @Override
93     public final void onBindingRuntimeContextUpdated(final BindingRuntimeContext runtime) {
94         this.context = runtime;
95     }
96
97     @Override
98     protected final String loadSerializerFor(final Class<?> cls) {
99         return implementations.getUnchecked(cls).getClass().getName();
100     }
101
102     private final class SerializerImplementationLoader 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),"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, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, NoSuchFieldException {
135             final DataObjectSerializerSource source = generateEmitterSource(type, serializerName);
136             final CtClass poolClass = generateEmitter0(type, source, serializerName);
137             @SuppressWarnings("unchecked")
138             final Class<? extends DataObjectSerializerImplementation> cls = poolClass.toClass(type.getClassLoader(), type.getProtectionDomain());
139
140             /*
141              * Due to OSGi class loader rules we cannot initialize the fields during
142              * construction, as the initializer expressions do not see our implementation
143              * classes. This should be almost as good as that, as we are resetting the
144              * fields to final before ever leaking the class.
145              */
146             for (final StaticConstantDefinition constant : source.getStaticConstants()) {
147                 final Field field = cls.getDeclaredField(constant.getName());
148                 field.setAccessible(true);
149                 field.set(null, constant.getValue());
150
151                 if (FIELD_MODIFIERS != null) {
152                     FIELD_MODIFIERS.setInt(field, field.getModifiers() | Modifier.FINAL);
153                 }
154             }
155
156             return cls;
157         }
158     }
159
160     private DataObjectSerializerSource generateEmitterSource(final Class<?> type, final String serializerName) {
161         Types.typeForClass(type);
162         javassist.appendClassLoaderIfMissing(type.getClassLoader());
163         final Entry<GeneratedType, Object> typeWithSchema = context.getTypeWithSchema(type);
164         final GeneratedType generatedType = typeWithSchema.getKey();
165         final Object schema = typeWithSchema.getValue();
166
167         final DataObjectSerializerSource source;
168         if (schema instanceof ContainerSchemaNode) {
169             source = generateContainerSerializer(generatedType, (ContainerSchemaNode) schema);
170         } else if (schema instanceof ListSchemaNode){
171             final ListSchemaNode casted = (ListSchemaNode) schema;
172             if (casted.getKeyDefinition().isEmpty()) {
173                 source = generateUnkeyedListEntrySerializer(generatedType, casted);
174             } else {
175                 source = generateMapEntrySerializer(generatedType, casted);
176             }
177         } else if(schema instanceof AugmentationSchema) {
178             source = generateSerializer(generatedType,(AugmentationSchema) schema);
179         } else if(schema instanceof ChoiceCaseNode) {
180             source = generateCaseSerializer(generatedType,(ChoiceCaseNode) schema);
181         } else if(schema instanceof NotificationDefinition) {
182             source = generateNotificationSerializer(generatedType,(NotificationDefinition) schema);
183         } else {
184             throw new UnsupportedOperationException("Schema type " + schema.getClass() + " is not supported");
185         }
186         return source;
187     }
188
189     private CtClass generateEmitter0(final Class<?> type, final DataObjectSerializerSource source, final String serializerName) {
190         final CtClass product;
191         try {
192             product = javassist.instantiatePrototype(DataObjectSerializerPrototype.class.getName(), serializerName, new ClassCustomizer() {
193                 @Override
194                 public void customizeClass(final CtClass cls) throws CannotCompileException, NotFoundException {
195                     /* getSerializerBody() has side effects, such as loading classes
196                      * and codecs, it should be run in model class loader in order to
197                      * correctly reference load child classes
198                      */
199                     final String body = ClassLoaderUtils.withClassLoader(type.getClassLoader(), new Supplier<String>() {
200                             @Override
201                             public String get() {
202                                 return source.getSerializerBody().toString();
203                             }
204                         }
205                     );
206
207                     // Generate any static fields
208                     for (final StaticConstantDefinition def : source.getStaticConstants()) {
209                         final CtField field = new CtField(javassist.asCtClass(def.getType()), def.getName(), cls);
210                         field.setModifiers(Modifier.PRIVATE + Modifier.STATIC);
211                         cls.addField(field);
212                     }
213
214                     // Replace serialize() -- may reference static fields
215                     final CtMethod serializeTo = cls.getDeclaredMethod(SERIALIZE_METHOD_NAME, serializeArguments);
216                     serializeTo.setBody(body);
217
218                     // The prototype is not visible, so we need to take care of that
219                     cls.setModifiers(Modifier.setPublic(cls.getModifiers()));
220                 }
221             });
222         } catch (final NotFoundException e) {
223             LOG.error("Failed to instatiate serializer {}", source, e);
224             throw new LinkageError("Unexpected instantation problem: serializer prototype not found", e);
225         }
226         return product;
227     }
228
229     /**
230      * Generates serializer source code for supplied container node,
231      * which will read supplied binding type and invoke proper methods
232      * on supplied {@link BindingStreamEventWriter}.
233      * <p>
234      * Implementation is required to recursively invoke events
235      * for all reachable binding objects.
236      *
237      * @param type Binding type of container
238      * @param node Schema of container
239      * @return Source for container node writer
240      */
241     protected abstract DataObjectSerializerSource generateContainerSerializer(GeneratedType type, ContainerSchemaNode node);
242
243     /**
244      * Generates serializer source for supplied case node,
245      * which will read supplied binding type and invoke proper methods
246      * on supplied {@link BindingStreamEventWriter}.
247      * <p>
248      * Implementation is required to recursively invoke events
249      * for all reachable binding objects.
250      *
251      * @param type Binding type of case
252      * @param node Schema of case
253      * @return Source for case node writer
254      */
255     protected abstract DataObjectSerializerSource generateCaseSerializer(GeneratedType type, ChoiceCaseNode node);
256
257     /**
258      * Generates serializer source for supplied list node,
259      * which will read supplied binding type and invoke proper methods
260      * on supplied {@link BindingStreamEventWriter}.
261      * <p>
262      * Implementation is required to recursively invoke events
263      * 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,
273      * which will read supplied binding type and invoke proper methods
274      * on supplied {@link BindingStreamEventWriter}.
275      * <p>
276      * Implementation is required to recursively invoke events
277      * 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, ListSchemaNode node);
284
285     /**
286      * Generates serializer source for supplied augmentation node,
287      * which will read supplied binding type and invoke proper methods
288      * on supplied {@link BindingStreamEventWriter}.
289      * <p>
290      * Implementation is required to recursively invoke events
291      * 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, AugmentationSchema schema);
298
299     /**
300      * Generates serializer source for notification node,
301      * which will read supplied binding type and invoke proper methods
302      * on supplied {@link BindingStreamEventWriter}.
303      * <p>
304      * Implementation is required to recursively invoke events
305      * for all reachable binding objects.
306      *
307      * @param type Binding type of notification
308      * @param node Schema of notification
309      * @return Source for notification node writer
310      */
311     protected abstract DataObjectSerializerSource generateNotificationSerializer(GeneratedType type, NotificationDefinition node);
312
313 }