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.

ClassPathExplorer.java 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. /*
  2. @VaadinApache2LicenseForJavaFiles@
  3. */
  4. package com.vaadin.terminal.gwt.widgetsetutils;
  5. import java.io.File;
  6. import java.io.FileFilter;
  7. import java.io.IOException;
  8. import java.net.JarURLConnection;
  9. import java.net.MalformedURLException;
  10. import java.net.URL;
  11. import java.net.URLConnection;
  12. import java.util.ArrayList;
  13. import java.util.HashMap;
  14. import java.util.Iterator;
  15. import java.util.LinkedHashMap;
  16. import java.util.List;
  17. import java.util.Map;
  18. import java.util.Set;
  19. import java.util.jar.Attributes;
  20. import java.util.jar.JarFile;
  21. import java.util.jar.Manifest;
  22. import java.util.logging.Level;
  23. import java.util.logging.Logger;
  24. /**
  25. * Utility class to collect widgetset related information from classpath.
  26. * Utility will seek all directories from classpaths, and jar files having
  27. * "Vaadin-Widgetsets" key in their manifest file.
  28. * <p>
  29. * Used by WidgetMapGenerator and ide tools to implement some monkey coding for
  30. * you.
  31. * <p>
  32. * Developer notice: If you end up reading this comment, I guess you have faced
  33. * a sluggish performance of widget compilation or unreliable detection of
  34. * components in your classpaths. The thing you might be able to do is to use
  35. * annotation processing tool like apt to generate the needed information. Then
  36. * either use that information in {@link WidgetMapGenerator} or create the
  37. * appropriate monkey code for gwt directly in annotation processor and get rid
  38. * of {@link WidgetMapGenerator}. Using annotation processor might be a good
  39. * idea when dropping Java 1.5 support (integrated to javac in 6).
  40. *
  41. */
  42. public class ClassPathExplorer {
  43. private static final String VAADIN_ADDON_VERSION_ATTRIBUTE = "Vaadin-Package-Version";
  44. /**
  45. * File filter that only accepts directories.
  46. */
  47. private final static FileFilter DIRECTORIES_ONLY = new FileFilter() {
  48. public boolean accept(File f) {
  49. if (f.exists() && f.isDirectory()) {
  50. return true;
  51. } else {
  52. return false;
  53. }
  54. }
  55. };
  56. /**
  57. * Raw class path entries as given in the java class path string. Only
  58. * entries that could include widgets/widgetsets are listed (primarily
  59. * directories, Vaadin JARs and add-on JARs).
  60. */
  61. private static List<String> rawClasspathEntries = getRawClasspathEntries();
  62. /**
  63. * Map from identifiers (either a package name preceded by the path and a
  64. * slash, or a URL for a JAR file) to the corresponding URLs. This is
  65. * constructed from the class path.
  66. */
  67. private static Map<String, URL> classpathLocations = getClasspathLocations(rawClasspathEntries);
  68. /**
  69. * No instantiation from outside, callable methods are static.
  70. */
  71. private ClassPathExplorer() {
  72. }
  73. /**
  74. * Finds the names and locations of widgetsets available on the class path.
  75. *
  76. * @return map from widgetset classname to widgetset location URL
  77. */
  78. public static Map<String, URL> getAvailableWidgetSets() {
  79. long start = System.currentTimeMillis();
  80. Map<String, URL> widgetsets = new HashMap<String, URL>();
  81. Set<String> keySet = classpathLocations.keySet();
  82. for (String location : keySet) {
  83. searchForWidgetSets(location, widgetsets);
  84. }
  85. long end = System.currentTimeMillis();
  86. StringBuilder sb = new StringBuilder();
  87. sb.append("Widgetsets found from classpath:\n");
  88. for (String ws : widgetsets.keySet()) {
  89. sb.append("\t");
  90. sb.append(ws);
  91. sb.append(" in ");
  92. sb.append(widgetsets.get(ws));
  93. sb.append("\n");
  94. }
  95. final Logger logger = getLogger();
  96. logger.info(sb.toString());
  97. logger.info("Search took " + (end - start) + "ms");
  98. return widgetsets;
  99. }
  100. /**
  101. * Finds all GWT modules / Vaadin widgetsets in a valid location.
  102. *
  103. * If the location is a directory, all GWT modules (files with the
  104. * ".gwt.xml" extension) are added to widgetsets.
  105. *
  106. * If the location is a JAR file, the comma-separated values of the
  107. * "Vaadin-Widgetsets" attribute in its manifest are added to widgetsets.
  108. *
  109. * @param locationString
  110. * an entry in {@link #classpathLocations}
  111. * @param widgetsets
  112. * a map from widgetset name (including package, with dots as
  113. * separators) to a URL (see {@link #classpathLocations}) - new
  114. * entries are added to this map
  115. */
  116. private static void searchForWidgetSets(String locationString,
  117. Map<String, URL> widgetsets) {
  118. URL location = classpathLocations.get(locationString);
  119. File directory = new File(location.getFile());
  120. if (directory.exists() && !directory.isHidden()) {
  121. // Get the list of the files contained in the directory
  122. String[] files = directory.list();
  123. for (int i = 0; i < files.length; i++) {
  124. // we are only interested in .gwt.xml files
  125. if (!files[i].endsWith(".gwt.xml")) {
  126. continue;
  127. }
  128. // remove the .gwt.xml extension
  129. String classname = files[i].substring(0, files[i].length() - 8);
  130. String packageName = locationString.substring(locationString
  131. .lastIndexOf("/") + 1);
  132. classname = packageName + "." + classname;
  133. if (!WidgetSetBuilder.isWidgetset(classname)) {
  134. // Only return widgetsets and not GWT modules to avoid
  135. // comparing modules and widgetsets
  136. continue;
  137. }
  138. if (!widgetsets.containsKey(classname)) {
  139. String packagePath = packageName.replaceAll("\\.", "/");
  140. String basePath = location.getFile().replaceAll(
  141. "/" + packagePath + "$", "");
  142. try {
  143. URL url = new URL(location.getProtocol(),
  144. location.getHost(), location.getPort(),
  145. basePath);
  146. widgetsets.put(classname, url);
  147. } catch (MalformedURLException e) {
  148. // should never happen as based on an existing URL,
  149. // only changing end of file name/path part
  150. getLogger().log(Level.SEVERE,
  151. "Error locating the widgetset " + classname, e);
  152. }
  153. }
  154. }
  155. } else {
  156. try {
  157. // check files in jar file, entries will list all directories
  158. // and files in jar
  159. URLConnection openConnection = location.openConnection();
  160. if (openConnection instanceof JarURLConnection) {
  161. JarURLConnection conn = (JarURLConnection) openConnection;
  162. JarFile jarFile = conn.getJarFile();
  163. Manifest manifest = jarFile.getManifest();
  164. if (manifest == null) {
  165. // No manifest so this is not a Vaadin Add-on
  166. return;
  167. }
  168. String value = manifest.getMainAttributes().getValue(
  169. "Vaadin-Widgetsets");
  170. if (value != null) {
  171. String[] widgetsetNames = value.split(",");
  172. for (int i = 0; i < widgetsetNames.length; i++) {
  173. String widgetsetname = widgetsetNames[i].trim()
  174. .intern();
  175. if (!widgetsetname.equals("")) {
  176. widgetsets.put(widgetsetname, location);
  177. }
  178. }
  179. }
  180. }
  181. } catch (IOException e) {
  182. getLogger().log(Level.WARNING, "Error parsing jar file", e);
  183. }
  184. }
  185. }
  186. /**
  187. * Splits the current class path into entries, and filters them accepting
  188. * directories, Vaadin add-on JARs with widgetsets and Vaadin JARs.
  189. *
  190. * Some other non-JAR entries may also be included in the result.
  191. *
  192. * @return filtered list of class path entries
  193. */
  194. private final static List<String> getRawClasspathEntries() {
  195. // try to keep the order of the classpath
  196. List<String> locations = new ArrayList<String>();
  197. String pathSep = System.getProperty("path.separator");
  198. String classpath = System.getProperty("java.class.path");
  199. if (classpath.startsWith("\"")) {
  200. classpath = classpath.substring(1);
  201. }
  202. if (classpath.endsWith("\"")) {
  203. classpath = classpath.substring(0, classpath.length() - 1);
  204. }
  205. getLogger().fine("Classpath: " + classpath);
  206. String[] split = classpath.split(pathSep);
  207. for (int i = 0; i < split.length; i++) {
  208. String classpathEntry = split[i];
  209. if (acceptClassPathEntry(classpathEntry)) {
  210. locations.add(classpathEntry);
  211. }
  212. }
  213. return locations;
  214. }
  215. /**
  216. * Determine every URL location defined by the current classpath, and it's
  217. * associated package name.
  218. *
  219. * See {@link #classpathLocations} for information on output format.
  220. *
  221. * @param rawClasspathEntries
  222. * raw class path entries as split from the Java class path
  223. * string
  224. * @return map of classpath locations, see {@link #classpathLocations}
  225. */
  226. private final static Map<String, URL> getClasspathLocations(
  227. List<String> rawClasspathEntries) {
  228. long start = System.currentTimeMillis();
  229. // try to keep the order of the classpath
  230. Map<String, URL> locations = new LinkedHashMap<String, URL>();
  231. for (String classpathEntry : rawClasspathEntries) {
  232. File file = new File(classpathEntry);
  233. include(null, file, locations);
  234. }
  235. long end = System.currentTimeMillis();
  236. Logger logger = getLogger();
  237. if (logger.isLoggable(Level.FINE)) {
  238. logger.fine("getClassPathLocations took " + (end - start) + "ms");
  239. }
  240. return locations;
  241. }
  242. /**
  243. * Checks a class path entry to see whether it can contain widgets and
  244. * widgetsets.
  245. *
  246. * All directories are automatically accepted. JARs are accepted if they
  247. * have the "Vaadin-Widgetsets" attribute in their manifest or the JAR file
  248. * name contains "vaadin-" or ".vaadin.".
  249. *
  250. * Also other non-JAR entries may be accepted, the caller should be prepared
  251. * to handle them.
  252. *
  253. * @param classpathEntry
  254. * class path entry string as given in the Java class path
  255. * @return true if the entry should be considered when looking for widgets
  256. * or widgetsets
  257. */
  258. private static boolean acceptClassPathEntry(String classpathEntry) {
  259. if (!classpathEntry.endsWith(".jar")) {
  260. // accept all non jars (practically directories)
  261. return true;
  262. } else {
  263. // accepts jars that comply with vaadin-component packaging
  264. // convention (.vaadin. or vaadin- as distribution packages),
  265. if (classpathEntry.contains("vaadin-")
  266. || classpathEntry.contains(".vaadin.")) {
  267. return true;
  268. } else {
  269. URL url;
  270. try {
  271. url = new URL("file:"
  272. + new File(classpathEntry).getCanonicalPath());
  273. url = new URL("jar:" + url.toExternalForm() + "!/");
  274. JarURLConnection conn = (JarURLConnection) url
  275. .openConnection();
  276. getLogger().fine(url.toString());
  277. JarFile jarFile = conn.getJarFile();
  278. Manifest manifest = jarFile.getManifest();
  279. if (manifest != null) {
  280. Attributes mainAttributes = manifest
  281. .getMainAttributes();
  282. if (mainAttributes.getValue("Vaadin-Widgetsets") != null) {
  283. return true;
  284. }
  285. }
  286. } catch (MalformedURLException e) {
  287. getLogger().log(Level.FINEST, "Failed to inspect JAR file",
  288. e);
  289. } catch (IOException e) {
  290. getLogger().log(Level.FINEST, "Failed to inspect JAR file",
  291. e);
  292. }
  293. return false;
  294. }
  295. }
  296. }
  297. /**
  298. * Recursively add subdirectories and jar files to locations - see
  299. * {@link #classpathLocations}.
  300. *
  301. * @param name
  302. * @param file
  303. * @param locations
  304. */
  305. private final static void include(String name, File file,
  306. Map<String, URL> locations) {
  307. if (!file.exists()) {
  308. return;
  309. }
  310. if (!file.isDirectory()) {
  311. // could be a JAR file
  312. includeJar(file, locations);
  313. return;
  314. }
  315. if (file.isHidden() || file.getPath().contains(File.separator + ".")) {
  316. return;
  317. }
  318. if (name == null) {
  319. name = "";
  320. } else {
  321. name += ".";
  322. }
  323. // add all directories recursively
  324. File[] dirs = file.listFiles(DIRECTORIES_ONLY);
  325. for (int i = 0; i < dirs.length; i++) {
  326. try {
  327. // add the present directory
  328. if (!dirs[i].isHidden()
  329. && !dirs[i].getPath().contains(File.separator + ".")) {
  330. String key = dirs[i].getCanonicalPath() + "/" + name
  331. + dirs[i].getName();
  332. locations.put(key,
  333. new URL("file://" + dirs[i].getCanonicalPath()));
  334. }
  335. } catch (Exception ioe) {
  336. return;
  337. }
  338. include(name + dirs[i].getName(), dirs[i], locations);
  339. }
  340. }
  341. /**
  342. * Add a jar file to locations - see {@link #classpathLocations}.
  343. *
  344. * @param name
  345. * @param locations
  346. */
  347. private static void includeJar(File file, Map<String, URL> locations) {
  348. try {
  349. URL url = new URL("file:" + file.getCanonicalPath());
  350. url = new URL("jar:" + url.toExternalForm() + "!/");
  351. JarURLConnection conn = (JarURLConnection) url.openConnection();
  352. JarFile jarFile = conn.getJarFile();
  353. if (jarFile != null) {
  354. // the key does not matter here as long as it is unique
  355. locations.put(url.toString(), url);
  356. }
  357. } catch (Exception e) {
  358. // e.printStackTrace();
  359. return;
  360. }
  361. }
  362. /**
  363. * Find and return the default source directory where to create new
  364. * widgetsets.
  365. *
  366. * Return the first directory (not a JAR file etc.) on the classpath by
  367. * default.
  368. *
  369. * TODO this could be done better...
  370. *
  371. * @return URL
  372. */
  373. public static URL getDefaultSourceDirectory() {
  374. final Logger logger = getLogger();
  375. if (logger.isLoggable(Level.FINE)) {
  376. logger.fine("classpathLocations values:");
  377. ArrayList<String> locations = new ArrayList<String>(
  378. classpathLocations.keySet());
  379. for (String location : locations) {
  380. logger.fine(String.valueOf(classpathLocations.get(location)));
  381. }
  382. }
  383. Iterator<String> it = rawClasspathEntries.iterator();
  384. while (it.hasNext()) {
  385. String entry = it.next();
  386. File directory = new File(entry);
  387. if (directory.exists() && !directory.isHidden()
  388. && directory.isDirectory()) {
  389. try {
  390. return new URL("file://" + directory.getCanonicalPath());
  391. } catch (MalformedURLException e) {
  392. logger.log(Level.FINEST, "Ignoring exception", e);
  393. // ignore: continue to the next classpath entry
  394. } catch (IOException e) {
  395. logger.log(Level.FINEST, "Ignoring exception", e);
  396. // ignore: continue to the next classpath entry
  397. }
  398. }
  399. }
  400. return null;
  401. }
  402. /**
  403. * Test method for helper tool
  404. */
  405. public static void main(String[] args) {
  406. getLogger().info("Searching available widgetsets...");
  407. Map<String, URL> availableWidgetSets = ClassPathExplorer
  408. .getAvailableWidgetSets();
  409. for (String string : availableWidgetSets.keySet()) {
  410. getLogger().info(string + " in " + availableWidgetSets.get(string));
  411. }
  412. }
  413. private static final Logger getLogger() {
  414. return Logger.getLogger(ClassPathExplorer.class.getName());
  415. }
  416. }