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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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.Arrays;
  17. import java.util.Collection;
  18. import java.util.Collections;
  19. import java.util.Comparator;
  20. import java.util.Enumeration;
  21. import java.util.Iterator;
  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.Assert;
  29. import org.junit.Test;
  30. import com.vaadin.ui.Component;
  31. public class ClassesSerializableTest {
  32. /**
  33. * JARs that will be scanned for classes to test, in addition to classpath
  34. * directories.
  35. */
  36. private static final String JAR_PATTERN = ".*vaadin.*\\.jar";
  37. private static final String[] BASE_PACKAGES = { "com.vaadin" };
  38. private static final String[] EXCLUDED_PATTERNS = {
  39. "com\\.vaadin\\.demo\\..*", //
  40. "com\\.vaadin\\.external\\.org\\.apache\\.commons\\.fileupload\\..*", //
  41. "com\\.vaadin\\.launcher\\..*", //
  42. "com\\.vaadin\\.client\\..*", //
  43. "com\\.vaadin\\.server\\.widgetsetutils\\..*", //
  44. "com\\.vaadin\\.server\\.themeutils\\..*", //
  45. "com\\.vaadin\\.tests\\..*", // exclude automated tests
  46. "com\\.vaadin\\.tools\\..*", //
  47. "com\\.vaadin\\.ui\\.themes\\..*", //
  48. // exact class level filtering
  49. "com\\.vaadin\\.event\\.FieldEvents", //
  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. // and its inner classes do not need to be serializable
  65. "com\\.vaadin\\.util\\.SerializerHelper", // fully static
  66. // class level filtering, also affecting nested classes and
  67. // interfaces
  68. "com\\.vaadin\\.server\\.LegacyCommunicationManager.*", //
  69. "com\\.vaadin\\.buildhelpers.*", //
  70. "com\\.vaadin\\.util\\.EncodeUtil.*", //
  71. "com\\.vaadin\\.util\\.ReflectTools.*", //
  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\\.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. };
  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. ArrayList<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 syntehtic 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. ArrayList<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. Assert.fail("Fields with functional types that are not serializable: "
  194. + nonSerializableString);
  195. }
  196. private void failSerializableClasses(
  197. ArrayList<Class<?>> nonSerializableClasses) {
  198. String nonSerializableString = "";
  199. Iterator<Class<?>> it = nonSerializableClasses.iterator();
  200. while (it.hasNext()) {
  201. Class<?> c = it.next();
  202. nonSerializableString += ", " + c.getName();
  203. if (c.isAnonymousClass()) {
  204. nonSerializableString += "(super: ";
  205. nonSerializableString += c.getSuperclass().getName();
  206. nonSerializableString += ", interfaces: ";
  207. for (Class<?> i : c.getInterfaces()) {
  208. nonSerializableString += i.getName();
  209. nonSerializableString += ",";
  210. }
  211. nonSerializableString += ")";
  212. }
  213. }
  214. Assert.fail(
  215. "Serializable not implemented by the following classes and interfaces: "
  216. + nonSerializableString);
  217. }
  218. private static boolean isFunctionalType(Type type) {
  219. return type.getTypeName().contains("java.util.function");
  220. }
  221. private boolean isTestClass(Class<?> cls) {
  222. if (cls.getEnclosingClass() != null
  223. && isTestClass(cls.getEnclosingClass())) {
  224. return true;
  225. }
  226. // Test classes with a @Test annotation on some method
  227. for (Method method : cls.getMethods()) {
  228. if (method.isAnnotationPresent(Test.class)) {
  229. return true;
  230. }
  231. }
  232. return false;
  233. }
  234. /**
  235. * Lists all class path entries by splitting the class path string.
  236. *
  237. * Adapted from ClassPathExplorer.getRawClasspathEntries(), but without
  238. * filtering.
  239. *
  240. * @return List of class path segment strings
  241. */
  242. private final static List<String> getRawClasspathEntries() {
  243. // try to keep the order of the classpath
  244. List<String> locations = new ArrayList<>();
  245. String pathSep = System.getProperty("path.separator");
  246. String classpath = System.getProperty("java.class.path");
  247. if (classpath.startsWith("\"")) {
  248. classpath = classpath.substring(1);
  249. }
  250. if (classpath.endsWith("\"")) {
  251. classpath = classpath.substring(0, classpath.length() - 1);
  252. }
  253. String[] split = classpath.split(pathSep);
  254. locations.addAll(Arrays.asList(split));
  255. return locations;
  256. }
  257. /**
  258. * Finds the server side classes/interfaces under a class path entry -
  259. * either a directory or a JAR that matches {@link #JAR_PATTERN}.
  260. *
  261. * Only classes under {@link #BASE_PACKAGES} are considered, and those
  262. * matching {@link #EXCLUDED_PATTERNS} are filtered out.
  263. *
  264. * @param classpathEntry
  265. * @return
  266. * @throws IOException
  267. */
  268. private List<String> findServerClasses(String classpathEntry)
  269. throws IOException {
  270. Collection<String> classes = new ArrayList<>();
  271. File file = new File(classpathEntry);
  272. if (file.isDirectory()) {
  273. classes = findClassesInDirectory(null, file);
  274. } else if (file.getName().matches(JAR_PATTERN)) {
  275. classes = findClassesInJar(file);
  276. } else {
  277. System.out.println("Ignoring " + classpathEntry);
  278. return Collections.emptyList();
  279. }
  280. List<String> filteredClasses = new ArrayList<>();
  281. for (String className : classes) {
  282. boolean ok = false;
  283. for (String basePackage : BASE_PACKAGES) {
  284. if (className.startsWith(basePackage + ".")) {
  285. ok = true;
  286. break;
  287. }
  288. }
  289. for (String excludedPrefix : EXCLUDED_PATTERNS) {
  290. if (className.matches(excludedPrefix)) {
  291. ok = false;
  292. break;
  293. }
  294. }
  295. // Don't add test classes
  296. if (className.contains("Test")) {
  297. ok = false;
  298. }
  299. if (ok) {
  300. filteredClasses.add(className);
  301. }
  302. }
  303. return filteredClasses;
  304. }
  305. /**
  306. * Lists class names (based on .class files) in a JAR file.
  307. *
  308. * @param file
  309. * a valid JAR file
  310. * @return collection of fully qualified class names in the JAR
  311. * @throws IOException
  312. */
  313. private Collection<String> findClassesInJar(File file) throws IOException {
  314. Collection<String> classes = new ArrayList<>();
  315. try (JarFile jar = new JarFile(file)) {
  316. Enumeration<JarEntry> e = jar.entries();
  317. while (e.hasMoreElements()) {
  318. JarEntry entry = e.nextElement();
  319. if (entry.getName().endsWith(".class")) {
  320. String nameWithoutExtension = entry.getName()
  321. .replaceAll("\\.class", "");
  322. String className = nameWithoutExtension.replace('/', '.');
  323. classes.add(className);
  324. }
  325. }
  326. }
  327. return classes;
  328. }
  329. /**
  330. * Lists class names (based on .class files) in a directory (a package path
  331. * root).
  332. *
  333. * @param parentPackage
  334. * parent package name or null at root of hierarchy, used by
  335. * recursion
  336. * @param parent
  337. * File representing the directory to scan
  338. * @return collection of fully qualified class names in the directory
  339. */
  340. private final static Collection<String> findClassesInDirectory(
  341. String parentPackage, File parent) {
  342. if (parent.isHidden()
  343. || parent.getPath().contains(File.separator + ".")) {
  344. return Collections.emptyList();
  345. }
  346. if (parentPackage == null) {
  347. parentPackage = "";
  348. } else {
  349. parentPackage += ".";
  350. }
  351. Collection<String> classNames = new ArrayList<>();
  352. // add all directories recursively
  353. File[] files = parent.listFiles();
  354. for (File child : files) {
  355. if (child.isDirectory()) {
  356. classNames.addAll(findClassesInDirectory(
  357. parentPackage + child.getName(), child));
  358. } else if (child.getName().endsWith(".class")) {
  359. classNames.add(parentPackage.replace(File.separatorChar, '.')
  360. + child.getName().replaceAll("\\.class", ""));
  361. }
  362. }
  363. return classNames;
  364. }
  365. }