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

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