Elffuss BraidHub

kikocis/java-driver public

d844cea208b1 · 6.6 KiBRawPermalink
1/*
2 * Copyright (C) 2012-2015 DataStax Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package com.datastax.driver.mapping;
17
18import com.datastax.driver.core.CCMTestsSupport;
19import com.datastax.driver.mapping.annotations.PartitionKey;
20import com.datastax.driver.mapping.annotations.Table;
21import com.google.common.io.Closeables;
22import org.objectweb.asm.*;
23import org.testng.annotations.Test;
24
25import java.io.IOException;
26import java.io.InputStream;
27import java.lang.reflect.Constructor;
28import java.util.Collection;
29import java.util.Collections;
30
31import static org.testng.Assert.assertEquals;
32
33@SuppressWarnings("unused")
34public class SyntheticFieldsMapperTest extends CCMTestsSupport {
35
36 @Override
37 public Collection<String> createTestFixtures() {
38 return Collections.singletonList("CREATE TABLE synthetic_fields (id int PRIMARY KEY)");
39 }
40
41 /**
42 * Test that synthetic fields are ignored by the {@code AnnotationParser} (JAVA-465).
43 * <p/>
44 * This test creates a modified version of this class where {@code futureSynthetic} is marked as synthetic, and
45 * therefore ignored by the {@code AnnotationParser}. If the test throws an error "Cannot find matching getter and
46 * setter for field 'futureSynthetic'", it means that the field is not ignored by the mapped. However,
47 * if it succeed, we know that the field was ignored and that the fix does the right job.
48 * <p/>
49 * If the class {@code ClassWithSyntheticField} was used as-is, the {@code Mapper} would complain that there are
50 * no getter and setter for the field {@code futureSynthetic}.
51 * <p/>
52 * Note that we could also have used not-static inner classes, but the {@code Mapper} is never able to instantiate
53 * those as they require a reference to their enclosing class that is not provided at instantiation time.
54 */
55 @Test(groups = "short")
56 public void should_ignore_synthetic_fields() {
57 Class<?> classWithSyntheticFields = makeTestClassWithSyntheticFields();
58 Object instance = instantiateNewClass(classWithSyntheticFields, 42);
59
60 // Here we cannot use ClassWithSyntheticField since it is not the one the source file was compiled against
61 // Instead, it is a different Class (identity + ClassLoader), a modified version of ClassWithSyntheticField
62 // Nice ClassCastException will be thrown if we try to cast it to ClassWithSyntheticField
63 @SuppressWarnings("unchecked")
64 Mapper<Object> m = (Mapper<Object>) new MappingManager(session).mapper(classWithSyntheticFields);
65 m.save(instance);
66
67 assertEquals(m.get(42), instance);
68 }
69
70 private Class<?> makeTestClassWithSyntheticFields() {
71 InputStream stream = null;
72 try {
73 // Get class bytes
74 Class<ClassWithSyntheticField> c = ClassWithSyntheticField.class;
75 String classAsPath = c.getName().replace('.', '/') + ".class";
76 stream = c.getClassLoader().getResourceAsStream(classAsPath);
77
78 // Make "futureSynthetic" field actually synthetic
79 ClassWriter cw = new ClassWriter(0);
80 ClassVisitor cv = new SyntheticFieldCreator(Opcodes.ASM5, cw);
81 ClassReader cr = new ClassReader(stream);
82 cr.accept(cv, 0);
83 byte[] updatedClassBytes = cw.toByteArray();
84
85 // Build the new class
86 return new InterceptingClassLoader().defineClass(
87 ClassWithSyntheticField.class.getName(),
88 updatedClassBytes);
89 } catch (IOException e) {
90 throw new RuntimeException("Could not read Class bytes", e);
91 } finally {
92 try {
93 Closeables.close(stream, true);
94 } catch (IOException ignored) {
95 }
96 }
97 }
98
99 private Object instantiateNewClass(Class<?> classWithSyntheticFields, int id) {
100 try {
101 Constructor<?> declaredConstructor = classWithSyntheticFields.getDeclaredConstructor(int.class);
102 return declaredConstructor.newInstance(id);
103 } catch (Exception e) {
104 throw new RuntimeException("Could not instantiate Class", e);
105 }
106 }
107
108 @Table(name = "synthetic_fields")
109 public static class ClassWithSyntheticField {
110 @PartitionKey
111 private int id;
112
113 // Intentionally broken class: there is no getter/setter for this field
114 private int futureSynthetic;
115
116 // This constructor will be used by the Mapper
117 @SuppressWarnings("unused")
118 public ClassWithSyntheticField() {
119 }
120
121 // This constructor is invoked using reflection
122 @SuppressWarnings("unused")
123 public ClassWithSyntheticField(int id) {
124 this.id = id;
125 }
126
127 // Getters & Setters used by the Mapper
128 @SuppressWarnings("unused")
129 public int getId() {
130 return id;
131 }
132
133 // Getters & Setters used by the Mapper
134 @SuppressWarnings("unused")
135 public void setId(int id) {
136 this.id = id;
137 }
138
139 @Override
140 public boolean equals(Object o) {
141 if (this == o) return true;
142 if (o == null || getClass() != o.getClass()) return false;
143
144 ClassWithSyntheticField that = (ClassWithSyntheticField) o;
145
146 return id == that.id;
147
148 }
149
150 @Override
151 public int hashCode() {
152 return id;
153 }
154 }
155
156 private static class SyntheticFieldCreator extends ClassVisitor {
157 public SyntheticFieldCreator(int api, ClassVisitor cv) {
158 super(api, cv);
159 }
160
161 @Override
162 public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) {
163 int newAccesses = access;
164 if ("futureSynthetic".equals(name)) {
165 newAccesses = access + Opcodes.ACC_SYNTHETIC;
166 }
167 return super.visitField(newAccesses, name, desc, signature, value);
168 }
169 }
170
171 private static class InterceptingClassLoader extends ClassLoader {
172 public Class defineClass(String name, byte[] b) {
173 return defineClass(name, b, 0, b.length);
174 }
175 }
176}