You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ClassesSerializableTest.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. package com.vaadin.tests.server;
  2. import static org.junit.Assert.fail;
  3. import java.io.ByteArrayInputStream;
  4. import java.io.ByteArrayOutputStream;
  5. import java.io.File;
  6. import java.io.IOException;
  7. import java.io.ObjectInputStream;
  8. import java.io.ObjectOutputStream;
  9. import java.io.Serializable;
  10. import java.lang.reflect.Constructor;
  11. import java.lang.reflect.Field;
  12. import java.lang.reflect.InvocationTargetException;
  13. import java.lang.reflect.Method;
  14. import java.lang.reflect.Modifier;
  15. import java.lang.reflect.Type;
  16. import java.util.ArrayList;
  17. import java.util.Arrays;
  18. import java.util.Collection;
  19. import java.util.Collections;
  20. import java.util.Comparator;
  21. import java.util.Enumeration;
  22. import java.util.List;
  23. import java.util.Optional;
  24. import java.util.jar.JarEntry;
  25. import java.util.jar.JarFile;
  26. import java.util.stream.Collectors;
  27. import java.util.stream.Stream;
  28. import org.junit.Test;
  29. import com.vaadin.ui.Component;
  30. public class ClassesSerializableTest {
  31. /**
  32. * JARs that will be scanned for classes to test, in addition to classpath
  33. * directories.
  34. */
  35. private static final String JAR_PATTERN = ".*vaadin.*\\.jar";
  36. private static final String[] BASE_PACKAGES = { "com.vaadin" };
  37. private static final String[] EXCLUDED_PATTERNS = {
  38. "com\\.vaadin\\.demo\\..*", //
  39. "com\\.vaadin\\.external\\.org\\.apache\\.commons\\.fileupload\\..*", //
  40. "com\\.vaadin\\.launcher\\..*", //
  41. "com\\.vaadin\\.client\\..*", //
  42. "com\\.vaadin\\.server\\.widgetsetutils\\..*", //
  43. "com\\.vaadin\\.server\\.themeutils\\..*", //
  44. "com\\.vaadin\\.tests\\..*", // exclude automated tests
  45. "com\\.vaadin\\.tools\\..*", //
  46. "com\\.vaadin\\.ui\\.themes\\..*", //
  47. // exact class level filtering
  48. "com\\.vaadin\\.event\\.FieldEvents", //
  49. "com\\.vaadin\\.util\\.FileTypeResolver",
  50. "com\\.vaadin\\.event\\.LayoutEvents", //
  51. "com\\.vaadin\\.event\\.MouseEvents", //
  52. "com\\.vaadin\\.event\\.UIEvents", //
  53. "com\\.vaadin\\.server\\.VaadinPortlet", //
  54. "com\\.vaadin\\.server\\.MockServletConfig", //
  55. "com\\.vaadin\\.server\\.MockServletContext", //
  56. "com\\.vaadin\\.server\\.MockVaadinServletService", //
  57. "com\\.vaadin\\.server\\.Constants", //
  58. "com\\.vaadin\\.server\\.VaadinServiceClassLoaderUtil", //
  59. "com\\.vaadin\\.server\\.VaadinServiceClassLoaderUtil\\$GetClassLoaderPrivilegedAction", //
  60. "com\\.vaadin\\.server\\.communication\\.FileUploadHandler\\$SimpleMultiPartInputStream", //
  61. "com\\.vaadin\\.server\\.communication\\.PushRequestHandler.*",
  62. "com\\.vaadin\\.server\\.communication\\.PushHandler.*", // PushHandler
  63. "com\\.vaadin\\.server\\.communication\\.DateSerializer", //
  64. "com\\.vaadin\\.server\\.communication\\.JSONSerializer", //
  65. "com\\.vaadin\\.ui\\.declarative\\.DesignContext", //
  66. // and its inner classes do not need to be serializable
  67. "com\\.vaadin\\.v7\\.util\\.SerializerHelper", // fully static
  68. // class level filtering, also affecting nested classes and
  69. // interfaces
  70. "com\\.vaadin\\.server\\.LegacyCommunicationManager.*", //
  71. "com\\.vaadin\\.buildhelpers.*", //
  72. "com\\.vaadin\\.util\\.EncodeUtil.*", //
  73. "com\\.vaadin\\.util\\.ReflectTools.*", //
  74. "com\\.vaadin\\.data\\.provider\\.InMemoryDataProviderHelpers",
  75. "com\\.vaadin\\.data\\.provider\\.HierarchyMapper\\$TreeLevelQuery",
  76. "com\\.vaadin\\.data\\.util\\.ReflectTools.*", //
  77. "com\\.vaadin\\.data\\.util\\.JsonUtil.*", //
  78. "com\\.vaadin\\.data\\.util\\.BeanUtil.*",
  79. // the JSR-303 constraint interpolation context
  80. "com\\.vaadin\\.data\\.validator\\.BeanValidator\\$1", //
  81. "com\\.vaadin\\.sass.*", //
  82. "com\\.vaadin\\.testbench.*", //
  83. "com\\.vaadin\\.util\\.CurrentInstance\\$1", //
  84. "com\\.vaadin\\.server\\.AbstractClientConnector\\$1", //
  85. "com\\.vaadin\\.server\\.AbstractClientConnector\\$1\\$1", //
  86. "com\\.vaadin\\.server\\.JsonCodec\\$1", //
  87. "com\\.vaadin\\.server\\.communication\\.PushConnection", //
  88. "com\\.vaadin\\.server\\.communication\\.AtmospherePushConnection.*", //
  89. "com\\.vaadin\\.ui\\.components\\.colorpicker\\.ColorUtil", //
  90. "com\\.vaadin\\.util\\.ConnectorHelper", //
  91. "com\\.vaadin\\.server\\.VaadinSession\\$FutureAccess", //
  92. "com\\.vaadin\\.external\\..*", //
  93. "com\\.vaadin\\.util\\.WeakValueMap.*", //
  94. "com\\.vaadin\\.themes\\.valoutil\\.BodyStyleName", //
  95. "com\\.vaadin\\.server\\.communication\\.JSR356WebsocketInitializer.*", //
  96. "com\\.vaadin\\.screenshotbrowser\\.ScreenshotBrowser.*", //
  97. "com\\.vaadin\\.osgi.*", //
  98. "com\\.vaadin\\.server\\.osgi.*",
  99. // V7
  100. "com\\.vaadin\\.v7\\.ui\\.themes\\.BaseTheme",
  101. "com\\.vaadin\\.v7\\.ui\\.themes\\.ChameleonTheme",
  102. "com\\.vaadin\\.v7\\.ui\\.themes\\.Reindeer",
  103. "com\\.vaadin\\.v7\\.ui\\.themes\\.Runo",
  104. "com\\.vaadin\\.v7\\.tests\\.VaadinClasses",
  105. "com\\.vaadin\\.v7\\.event\\.FieldEvents", //
  106. "com\\.vaadin\\.v7\\.data\\.util.BeanItemContainerGenerator.*",
  107. "com\\.vaadin\\.v7\\.data\\.util\\.sqlcontainer\\.connection\\.MockInitialContextFactory",
  108. "com\\.vaadin\\.v7\\.data\\.util\\.sqlcontainer\\.DataGenerator",
  109. "com\\.vaadin\\.v7\\.data\\.util\\.sqlcontainer\\.FreeformQueryUtil", };
  110. /**
  111. * Tests that all the relevant classes and interfaces under
  112. * {@link #BASE_PACKAGES} implement Serializable.
  113. *
  114. * @throws Exception
  115. */
  116. @Test
  117. public void testClassesSerializable() throws Exception {
  118. List<String> rawClasspathEntries = getRawClasspathEntries();
  119. List<String> classes = new ArrayList<>();
  120. for (String location : rawClasspathEntries) {
  121. classes.addAll(findServerClasses(location));
  122. }
  123. ArrayList<Field> nonSerializableFunctionFields = new ArrayList<>();
  124. List<Class<?>> nonSerializableClasses = new ArrayList<>();
  125. for (String className : classes) {
  126. Class<?> cls = Class.forName(className);
  127. // Don't add classes that have a @Ignore annotation on the class
  128. if (isTestClass(cls)) {
  129. continue;
  130. }
  131. // report fields that use lambda types that won't be serializable
  132. // (also in synthetic classes)
  133. Stream.of(cls.getDeclaredFields())
  134. .filter(field -> isFunctionalType(field.getGenericType()))
  135. .forEach(nonSerializableFunctionFields::add);
  136. // skip annotations and synthetic classes
  137. if (cls.isAnnotation() || cls.isSynthetic()) {
  138. continue;
  139. }
  140. if (!cls.isInterface()
  141. && !Modifier.isAbstract(cls.getModifiers())) {
  142. serializeAndDeserialize(cls);
  143. }
  144. // report non-serializable classes and interfaces
  145. if (!Serializable.class.isAssignableFrom(cls)) {
  146. if (cls.getSuperclass() == Object.class
  147. && cls.getInterfaces().length == 1) {
  148. // Single interface implementors
  149. Class<?> iface = cls.getInterfaces()[0];
  150. if (iface == Runnable.class) {
  151. // Ignore Runnables used with access()
  152. continue;
  153. } else if (iface == Comparator.class) {
  154. // Ignore inline comparators
  155. continue;
  156. }
  157. }
  158. nonSerializableClasses.add(cls);
  159. // TODO easier to read when testing
  160. // System.err.println(cls);
  161. }
  162. }
  163. // useful failure message including all non-serializable classes and
  164. // interfaces
  165. if (!nonSerializableClasses.isEmpty()) {
  166. failSerializableClasses(nonSerializableClasses);
  167. }
  168. if (!nonSerializableFunctionFields.isEmpty()) {
  169. failSerializableFields(nonSerializableFunctionFields);
  170. }
  171. }
  172. private void serializeAndDeserialize(Class<?> clazz)
  173. throws IOException, ClassNotFoundException, InstantiationException,
  174. IllegalAccessException, IllegalArgumentException,
  175. InvocationTargetException {
  176. Optional<Constructor<?>> defaultCtor = Stream
  177. .of(clazz.getDeclaredConstructors())
  178. .filter(ctor -> ctor.getParameterCount() == 0).findFirst();
  179. if (!defaultCtor.isPresent()) {
  180. return;
  181. }
  182. defaultCtor.get().setAccessible(true);
  183. Object instance = defaultCtor.get().newInstance();
  184. serializeAndDeserialize(instance);
  185. }
  186. public static <T> T serializeAndDeserialize(T instance)
  187. throws IOException, ClassNotFoundException {
  188. ByteArrayOutputStream bs = new ByteArrayOutputStream();
  189. ObjectOutputStream out = new ObjectOutputStream(bs);
  190. out.writeObject(instance);
  191. byte[] data = bs.toByteArray();
  192. ObjectInputStream in = new ObjectInputStream(
  193. new ByteArrayInputStream(data));
  194. @SuppressWarnings("unchecked")
  195. T readObject = (T) in.readObject();
  196. return readObject;
  197. }
  198. private void failSerializableFields(
  199. List<Field> nonSerializableFunctionFields) {
  200. String nonSerializableString = nonSerializableFunctionFields.stream()
  201. .map(field -> String.format("%s.%s",
  202. field.getDeclaringClass().getName(), field.getName()))
  203. .collect(Collectors.joining(", "));
  204. fail("Fields with functional types that are not serializable: "
  205. + nonSerializableString);
  206. }
  207. private void failSerializableClasses(
  208. List<Class<?>> nonSerializableClasses) {
  209. String nonSerializableString = "";
  210. for (Class<?> c : nonSerializableClasses) {
  211. nonSerializableString += ", " + c.getName();
  212. if (c.isAnonymousClass()) {
  213. nonSerializableString += "(super: ";
  214. nonSerializableString += c.getSuperclass().getName();
  215. nonSerializableString += ", interfaces: ";
  216. for (Class<?> i : c.getInterfaces()) {
  217. nonSerializableString += i.getName();
  218. nonSerializableString += ",";
  219. }
  220. nonSerializableString += ")";
  221. }
  222. }
  223. fail("Serializable not implemented by the following classes and interfaces: "
  224. + nonSerializableString);
  225. }
  226. private static boolean isFunctionalType(Type type) {
  227. return type.getTypeName().contains("java.util.function");
  228. }
  229. private boolean isTestClass(Class<?> cls) {
  230. if (cls.getEnclosingClass() != null
  231. && isTestClass(cls.getEnclosingClass())) {
  232. return true;
  233. }
  234. // Test classes with a @Test annotation on some method
  235. for (Method method : cls.getMethods()) {
  236. if (method.isAnnotationPresent(Test.class)) {
  237. return true;
  238. }
  239. }
  240. return false;
  241. }
  242. /**
  243. * Lists all class path entries by splitting the class path string.
  244. *
  245. * Adapted from ClassPathExplorer.getRawClasspathEntries(), but without
  246. * filtering.
  247. *
  248. * @return List of class path segment strings
  249. */
  250. private static final List<String> getRawClasspathEntries() {
  251. // try to keep the order of the classpath
  252. List<String> locations = new ArrayList<>();
  253. String pathSep = System.getProperty("path.separator");
  254. String classpath = System.getProperty("java.class.path");
  255. if (classpath.startsWith("\"")) {
  256. classpath = classpath.substring(1);
  257. }
  258. if (classpath.endsWith("\"")) {
  259. classpath = classpath.substring(0, classpath.length() - 1);
  260. }
  261. String[] split = classpath.split(pathSep);
  262. locations.addAll(Arrays.asList(split));
  263. return locations;
  264. }
  265. /**
  266. * Finds the server side classes/interfaces under a class path entry -
  267. * either a directory or a JAR that matches {@link #JAR_PATTERN}.
  268. *
  269. * Only classes under {@link #BASE_PACKAGES} are considered, and those
  270. * matching {@link #EXCLUDED_PATTERNS} are filtered out.
  271. *
  272. * @param classpathEntry
  273. * @return
  274. * @throws IOException
  275. */
  276. private List<String> findServerClasses(String classpathEntry)
  277. throws IOException {
  278. Collection<String> classes = new ArrayList<>();
  279. File file = new File(classpathEntry);
  280. if (file.isDirectory()) {
  281. classes = findClassesInDirectory(null, file);
  282. } else if (file.getName().matches(JAR_PATTERN)) {
  283. classes = findClassesInJar(file);
  284. } else {
  285. System.out.println("Ignoring " + classpathEntry);
  286. return Collections.emptyList();
  287. }
  288. List<String> filteredClasses = new ArrayList<>();
  289. for (String className : classes) {
  290. boolean ok = false;
  291. for (String basePackage : BASE_PACKAGES) {
  292. if (className.startsWith(basePackage + ".")) {
  293. ok = true;
  294. break;
  295. }
  296. }
  297. for (String excludedPrefix : EXCLUDED_PATTERNS) {
  298. if (className.matches(excludedPrefix)) {
  299. ok = false;
  300. break;
  301. }
  302. }
  303. // Don't add test classes
  304. if (className.contains("Test")) {
  305. ok = false;
  306. }
  307. if (ok) {
  308. filteredClasses.add(className);
  309. }
  310. }
  311. return filteredClasses;
  312. }
  313. /**
  314. * Lists class names (based on .class files) in a JAR file.
  315. *
  316. * @param file
  317. * a valid JAR file
  318. * @return collection of fully qualified class names in the JAR
  319. * @throws IOException
  320. */
  321. private Collection<String> findClassesInJar(File file) throws IOException {
  322. Collection<String> classes = new ArrayList<>();
  323. try (JarFile jar = new JarFile(file)) {
  324. Enumeration<JarEntry> e = jar.entries();
  325. while (e.hasMoreElements()) {
  326. JarEntry entry = e.nextElement();
  327. if (entry.getName().endsWith(".class")) {
  328. String nameWithoutExtension = entry.getName()
  329. .replaceAll("\\.class", "");
  330. String className = nameWithoutExtension.replace('/', '.');
  331. classes.add(className);
  332. }
  333. }
  334. }
  335. return classes;
  336. }
  337. /**
  338. * Lists class names (based on .class files) in a directory (a package path
  339. * root).
  340. *
  341. * @param parentPackage
  342. * parent package name or null at root of hierarchy, used by
  343. * recursion
  344. * @param parent
  345. * File representing the directory to scan
  346. * @return collection of fully qualified class names in the directory
  347. */
  348. private static final Collection<String> findClassesInDirectory(
  349. String parentPackage, File parent) {
  350. if (parent.isHidden()
  351. || parent.getPath().contains(File.separator + ".")) {
  352. return Collections.emptyList();
  353. }
  354. if (parentPackage == null) {
  355. parentPackage = "";
  356. } else {
  357. parentPackage += ".";
  358. }
  359. Collection<String> classNames = new ArrayList<>();
  360. // add all directories recursively
  361. File[] files = parent.listFiles();
  362. for (File child : files) {
  363. if (child.isDirectory()) {
  364. classNames.addAll(findClassesInDirectory(
  365. parentPackage + child.getName(), child));
  366. } else if (child.getName().endsWith(".class")) {
  367. classNames.add(parentPackage.replace(File.separatorChar, '.')
  368. + child.getName().replaceAll("\\.class", ""));
  369. }
  370. }
  371. return classNames;
  372. }
  373. }