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 15KB

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