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.yangtools.binding.data.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.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;
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 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);
75 protected AbstractStreamWriterGenerator(final JavassistUtils utils) {
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),
83 javassist.appendClassLoaderIfMissing(DataObjectSerializerPrototype.class.getClassLoader());
84 this.implementations = CacheBuilder.newBuilder().weakKeys().build(new SerializerImplementationLoader());
88 public final DataObjectSerializerImplementation getSerializer(final Class<?> type) {
89 return implementations.getUnchecked(type);
93 public final void onBindingRuntimeContextUpdated(final BindingRuntimeContext runtime) {
94 this.context = runtime;
98 protected final String loadSerializerFor(final Class<?> cls) {
99 return implementations.getUnchecked(cls).getClass().getName();
102 private final class SerializerImplementationLoader 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),"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, 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());
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.
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());
151 if (FIELD_MODIFIERS != null) {
152 FIELD_MODIFIERS.setInt(field, field.getModifiers() | Modifier.FINAL);
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();
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);
175 source = generateMapEntrySerializer(generatedType, casted);
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);
184 throw new UnsupportedOperationException("Schema type " + schema.getClass() + " is not supported");
189 private CtClass generateEmitter0(final Class<?> type, final DataObjectSerializerSource source, final String serializerName) {
190 final CtClass product;
192 product = javassist.instantiatePrototype(DataObjectSerializerPrototype.class.getName(), serializerName, new ClassCustomizer() {
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
199 final String body = ClassLoaderUtils.withClassLoader(type.getClassLoader(), new Supplier<String>() {
201 public String get() {
202 return source.getSerializerBody().toString();
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);
214 // Replace serialize() -- may reference static fields
215 final CtMethod serializeTo = cls.getDeclaredMethod(SERIALIZE_METHOD_NAME, serializeArguments);
216 serializeTo.setBody(body);
218 // The prototype is not visible, so we need to take care of that
219 cls.setModifiers(Modifier.setPublic(cls.getModifiers()));
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);
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}.
234 * Implementation is required to recursively invoke events
235 * for all reachable binding objects.
237 * @param type Binding type of container
238 * @param node Schema of container
239 * @return Source for container node writer
241 protected abstract DataObjectSerializerSource generateContainerSerializer(GeneratedType type, ContainerSchemaNode node);
244 * Generates serializer source for supplied case node,
245 * which will read supplied binding type and invoke proper methods
246 * on supplied {@link BindingStreamEventWriter}.
248 * Implementation is required to recursively invoke events
249 * for all reachable binding objects.
251 * @param type Binding type of case
252 * @param node Schema of case
253 * @return Source for case node writer
255 protected abstract DataObjectSerializerSource generateCaseSerializer(GeneratedType type, ChoiceCaseNode node);
258 * Generates serializer source for supplied list node,
259 * which will read supplied binding type and invoke proper methods
260 * on supplied {@link BindingStreamEventWriter}.
262 * Implementation is required to recursively invoke events
263 * 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,
273 * which will read supplied binding type and invoke proper methods
274 * on supplied {@link BindingStreamEventWriter}.
276 * Implementation is required to recursively invoke events
277 * 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, ListSchemaNode node);
286 * Generates serializer source for supplied augmentation node,
287 * which will read supplied binding type and invoke proper methods
288 * on supplied {@link BindingStreamEventWriter}.
290 * Implementation is required to recursively invoke events
291 * 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, AugmentationSchema schema);
300 * Generates serializer source for notification node,
301 * which will read supplied binding type and invoke proper methods
302 * on supplied {@link BindingStreamEventWriter}.
304 * Implementation is required to recursively invoke events
305 * for all reachable binding objects.
307 * @param type Binding type of notification
308 * @param node Schema of notification
309 * @return Source for notification node writer
311 protected abstract DataObjectSerializerSource generateNotificationSerializer(GeneratedType type, NotificationDefinition node);