2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.mdsal.binding.dom.codec.gen.impl;
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;
45 abstract class AbstractStreamWriterGenerator extends AbstractGenerator implements DataObjectSerializerGenerator {
46 private static final Logger LOG = LoggerFactory.getLogger(AbstractStreamWriterGenerator.class);
48 protected static final String SERIALIZE_METHOD_NAME = "serialize";
49 protected static final AugmentableDispatchSerializer AUGMENTABLE = new AugmentableDispatchSerializer();
50 private static final Field FIELD_MODIFIERS;
52 private final LoadingCache<Class<?>, DataObjectSerializerImplementation> implementations;
53 private final CtClass[] serializeArguments;
54 private final JavassistUtils javassist;
55 private BindingRuntimeContext context;
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.
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);
71 FIELD_MODIFIERS = field;
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),
81 javassist.appendClassLoaderIfMissing(DataObjectSerializerPrototype.class.getClassLoader());
82 this.implementations = CacheBuilder.newBuilder().weakKeys().build(new SerializerImplementationLoader());
86 public final DataObjectSerializerImplementation getSerializer(final Class<?> type) {
87 return implementations.getUnchecked(type);
91 public final void onBindingRuntimeContextUpdated(final BindingRuntimeContext runtime) {
92 this.context = runtime;
96 protected final String loadSerializerFor(final Class<?> cls) {
97 return implementations.getUnchecked(cls).getClass().getName();
100 private final class SerializerImplementationLoader
101 extends CacheLoader<Class<?>, DataObjectSerializerImplementation> {
103 private static final String GETINSTANCE_METHOD_NAME = "getInstance";
104 private static final String SERIALIZER_SUFFIX = "$StreamWriter";
106 private String getSerializerName(final Class<?> type) {
107 return type.getName() + SERIALIZER_SUFFIX;
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());
117 final String serializerName = getSerializerName(type);
119 Class<? extends DataObjectSerializerImplementation> cls;
121 cls = (Class<? extends DataObjectSerializerImplementation>) ClassLoaderUtils
122 .loadClass(type.getClassLoader(), serializerName);
123 } catch (final ClassNotFoundException e) {
124 cls = generateSerializer(type, serializerName);
127 final DataObjectSerializerImplementation obj =
128 (DataObjectSerializerImplementation) cls.getDeclaredMethod(GETINSTANCE_METHOD_NAME).invoke(null);
129 LOG.debug("Loaded serializer {} for class {}", obj, type);
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());
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.
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());
154 if (FIELD_MODIFIERS != null) {
155 FIELD_MODIFIERS.setInt(field, field.getModifiers() | Modifier.FINAL);
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();
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);
178 source = generateMapEntrySerializer(generatedType, casted);
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);
187 throw new UnsupportedOperationException("Schema type " + schema.getClass() + " is not supported");
192 private CtClass generateEmitter0(final Class<?> type, final DataObjectSerializerSource source,
193 final String serializerName) {
194 final CtClass product;
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.
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.
204 final String body = ClassLoaderUtils.withClassLoader(type.getClassLoader(),
205 (Supplier<String>) () -> source.getSerializerBody().toString());
208 product = javassist.instantiatePrototype(DataObjectSerializerPrototype.class.getName(), serializerName,
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);
217 // Replace serialize() -- may reference static fields
218 final CtMethod serializeTo = cls.getDeclaredMethod(SERIALIZE_METHOD_NAME, serializeArguments);
219 serializeTo.setBody(body);
221 // The prototype is not visible, so we need to take care of that
222 cls.setModifiers(Modifier.setPublic(cls.getModifiers()));
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);
232 * Generates serializer source code for supplied container node, which will read supplied binding type and invoke
233 * proper methods on supplied {@link BindingStreamEventWriter}.
236 * Implementation is required to recursively invoke events for all reachable binding objects.
238 * @param type Binding type of container
239 * @param node Schema of container
240 * @return Source for container node writer
242 protected abstract DataObjectSerializerSource generateContainerSerializer(GeneratedType type,
243 ContainerSchemaNode node);
246 * Generates serializer source for supplied case node, which will read supplied binding type and invoke proper
247 * methods on supplied {@link BindingStreamEventWriter}.
250 * Implementation is required to recursively invoke events for all reachable binding objects.
252 * @param type Binding type of case
253 * @param node Schema of case
254 * @return Source for case node writer
256 protected abstract DataObjectSerializerSource generateCaseSerializer(GeneratedType type, ChoiceCaseNode node);
259 * Generates serializer source for supplied list node, which will read supplied binding type and invoke proper
260 * methods on supplied {@link BindingStreamEventWriter}.
263 * Implementation is required to recursively invoke events for all reachable binding objects.
265 * @param type Binding type of list
266 * @param node Schema of list
267 * @return Source for list node writer
269 protected abstract DataObjectSerializerSource generateMapEntrySerializer(GeneratedType type, ListSchemaNode node);
272 * Generates serializer source for supplied list node, which will read supplied binding type and invoke proper
273 * methods on supplied {@link BindingStreamEventWriter}.
276 * Implementation is required to recursively invoke events for all reachable binding objects.
278 * @param type Binding type of list
279 * @param node Schema of list
280 * @return Source for list node writer
282 protected abstract DataObjectSerializerSource generateUnkeyedListEntrySerializer(GeneratedType type,
283 ListSchemaNode node);
286 * Generates serializer source for supplied augmentation node, which will read supplied binding type and invoke
287 * proper methods on supplied {@link BindingStreamEventWriter}.
290 * Implementation is required to recursively invoke events for all reachable binding objects.
292 * @param type Binding type of augmentation
293 * @param schema Schema of augmentation
294 * @return Source for augmentation node writer
296 protected abstract DataObjectSerializerSource generateSerializer(GeneratedType type, AugmentationSchema schema);
299 * Generates serializer source for notification node, which will read supplied binding type and invoke proper
300 * methods on supplied {@link BindingStreamEventWriter}.
303 * Implementation is required to recursively invoke events for all reachable binding objects.
305 * @param type Binding type of notification
306 * @param node Schema of notification
307 * @return Source for notification node writer
309 protected abstract DataObjectSerializerSource generateNotificationSerializer(GeneratedType type,
310 NotificationDefinition node);