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

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