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.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;
46 abstract class AbstractStreamWriterGenerator extends AbstractGenerator implements DataObjectSerializerGenerator {
47 private static final Logger LOG = LoggerFactory.getLogger(AbstractStreamWriterGenerator.class);
49 protected static final String SERIALIZE_METHOD_NAME = "serialize";
50 protected static final AugmentableDispatchSerializer AUGMENTABLE = new AugmentableDispatchSerializer();
51 private static final Field FIELD_MODIFIERS;
53 private final LoadingCache<Class<?>, DataObjectSerializerImplementation> implementations;
54 private final CtClass[] serializeArguments;
55 private final JavassistUtils javassist;
56 private BindingRuntimeContext context;
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.
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);
72 FIELD_MODIFIERS = field;
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),
82 javassist.appendClassLoaderIfMissing(DataObjectSerializerPrototype.class.getClassLoader());
83 this.implementations = CacheBuilder.newBuilder().weakKeys().build(new SerializerImplementationLoader());
87 public final DataObjectSerializerImplementation getSerializer(final Class<?> type) {
88 return implementations.getUnchecked(type);
92 public final void onBindingRuntimeContextUpdated(final BindingRuntimeContext runtime) {
93 this.context = runtime;
97 protected final String loadSerializerFor(final Class<?> cls) {
98 return implementations.getUnchecked(cls).getClass().getName();
101 private final class SerializerImplementationLoader
102 extends CacheLoader<Class<?>, DataObjectSerializerImplementation> {
104 private static final String GETINSTANCE_METHOD_NAME = "getInstance";
105 private static final String SERIALIZER_SUFFIX = "$StreamWriter";
107 private String getSerializerName(final Class<?> type) {
108 return type.getName() + SERIALIZER_SUFFIX;
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());
118 final String serializerName = getSerializerName(type);
120 Class<? extends DataObjectSerializerImplementation> cls;
122 cls = (Class<? extends DataObjectSerializerImplementation>) ClassLoaderUtils
123 .loadClass(type.getClassLoader(), serializerName);
124 } catch (final ClassNotFoundException e) {
125 cls = generateSerializer(type, serializerName);
128 final DataObjectSerializerImplementation obj =
129 (DataObjectSerializerImplementation) cls.getDeclaredMethod(GETINSTANCE_METHOD_NAME).invoke(null);
130 LOG.debug("Loaded serializer {} for class {}", obj, type);
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());
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.
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());
155 if (FIELD_MODIFIERS != null) {
156 FIELD_MODIFIERS.setInt(field, field.getModifiers() | Modifier.FINAL);
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();
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);
179 source = generateMapEntrySerializer(generatedType, casted);
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);
188 throw new UnsupportedOperationException("Schema type " + schema.getClass() + " is not supported");
193 private CtClass generateEmitter0(final Class<?> type, final DataObjectSerializerSource source,
194 final String serializerName) {
195 final CtClass product;
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.
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.
205 final String body = ClassLoaderUtils.withClassLoader(type.getClassLoader(),
206 (Supplier<String>) () -> source.getSerializerBody().toString());
209 product = javassist.instantiatePrototype(DataObjectSerializerPrototype.class.getName(), serializerName,
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);
218 // Replace serialize() -- may reference static fields
219 final CtMethod serializeTo = cls.getDeclaredMethod(SERIALIZE_METHOD_NAME, serializeArguments);
220 serializeTo.setBody(body);
222 // The prototype is not visible, so we need to take care of that
223 cls.setModifiers(Modifier.setPublic(cls.getModifiers()));
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);
233 * Generates serializer source code for supplied container node, which will read supplied binding type and invoke
234 * proper methods on supplied {@link BindingStreamEventWriter}.
237 * Implementation is required to recursively invoke events for all reachable binding objects.
239 * @param type Binding type of container
240 * @param node Schema of container
241 * @return Source for container node writer
243 protected abstract DataObjectSerializerSource generateContainerSerializer(GeneratedType type,
244 ContainerSchemaNode node);
247 * Generates serializer source for supplied case node, which will read supplied binding type and invoke proper
248 * methods on supplied {@link BindingStreamEventWriter}.
251 * Implementation is required to recursively invoke events for all reachable binding objects.
253 * @param type Binding type of case
254 * @param node Schema of case
255 * @return Source for case node writer
257 protected abstract DataObjectSerializerSource generateCaseSerializer(GeneratedType type, CaseSchemaNode node);
260 * Generates serializer source for supplied list node, which will read supplied binding type and invoke proper
261 * methods on supplied {@link BindingStreamEventWriter}.
264 * Implementation is required to recursively invoke events for all reachable binding objects.
266 * @param type Binding type of list
267 * @param node Schema of list
268 * @return Source for list node writer
270 protected abstract DataObjectSerializerSource generateMapEntrySerializer(GeneratedType type, ListSchemaNode node);
273 * Generates serializer source for supplied list node, which will read supplied binding type and invoke proper
274 * methods on supplied {@link BindingStreamEventWriter}.
277 * Implementation is required to recursively invoke events for all reachable binding objects.
279 * @param type Binding type of list
280 * @param node Schema of list
281 * @return Source for list node writer
283 protected abstract DataObjectSerializerSource generateUnkeyedListEntrySerializer(GeneratedType type,
284 ListSchemaNode node);
287 * Generates serializer source for supplied augmentation node, which will read supplied binding type and invoke
288 * proper methods on supplied {@link BindingStreamEventWriter}.
291 * Implementation is required to recursively invoke events for all reachable binding objects.
293 * @param type Binding type of augmentation
294 * @param schema Schema of augmentation
295 * @return Source for augmentation node writer
297 protected abstract DataObjectSerializerSource generateSerializer(GeneratedType type, AugmentationSchemaNode schema);
300 * Generates serializer source for notification node, which will read supplied binding type and invoke proper
301 * methods on supplied {@link BindingStreamEventWriter}.
304 * Implementation is required to recursively invoke events for all reachable binding objects.
306 * @param type Binding type of notification
307 * @param node Schema of notification
308 * @return Source for notification node writer
310 protected abstract DataObjectSerializerSource generateNotificationSerializer(GeneratedType type,
311 NotificationDefinition node);