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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. /*
  2. * Copyright 2000-2014 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.server.widgetsetutils;
  17. import java.io.File;
  18. import java.io.FileFilter;
  19. import java.io.IOException;
  20. import java.net.JarURLConnection;
  21. import java.net.MalformedURLException;
  22. import java.net.URL;
  23. import java.net.URLConnection;
  24. import java.util.ArrayList;
  25. import java.util.HashMap;
  26. import java.util.Iterator;
  27. import java.util.LinkedHashMap;
  28. import java.util.List;
  29. import java.util.Map;
  30. import java.util.Set;
  31. import java.util.jar.Attributes;
  32. import java.util.jar.JarFile;
  33. import java.util.jar.Manifest;
  34. /**
  35. * Utility class to collect widgetset related information from classpath.
  36. * Utility will seek all directories from classpaths, and jar files having
  37. * "Vaadin-Widgetsets" key in their manifest file.
  38. * <p>
  39. * Used by WidgetMapGenerator and ide tools to implement some monkey coding for
  40. * you.
  41. * <p>
  42. * Developer notice: If you end up reading this comment, I guess you have faced
  43. * a sluggish performance of widget compilation or unreliable detection of
  44. * components in your classpaths. The thing you might be able to do is to use
  45. * annotation processing tool like apt to generate the needed information. Then
  46. * either use that information in {@link WidgetMapGenerator} or create the
  47. * appropriate monkey code for gwt directly in annotation processor and get rid
  48. * of {@link WidgetMapGenerator}. Using annotation processor might be a good
  49. * idea when dropping Java 1.5 support (integrated to javac in 6).
  50. *
  51. */
  52. public class ClassPathExplorer {
  53. private static final String VAADIN_ADDON_VERSION_ATTRIBUTE = "Vaadin-Package-Version";
  54. /**
  55. * File filter that only accepts directories.
  56. */
  57. private final static FileFilter DIRECTORIES_ONLY = new FileFilter() {
  58. @Override
  59. public boolean accept(File f) {
  60. if (f.exists() && f.isDirectory()) {
  61. return true;
  62. } else {
  63. return false;
  64. }
  65. }
  66. };
  67. /**
  68. * Contains information about widgetsets and themes found on the classpath
  69. *
  70. * @since 7.1
  71. */
  72. public static class LocationInfo {
  73. private final Map<String, URL> widgetsets;
  74. private final Map<String, URL> addonStyles;
  75. public LocationInfo(Map<String, URL> widgetsets, Map<String, URL> themes) {
  76. this.widgetsets = widgetsets;
  77. addonStyles = themes;
  78. }
  79. public Map<String, URL> getWidgetsets() {
  80. return widgetsets;
  81. }
  82. public Map<String, URL> getAddonStyles() {
  83. return addonStyles;
  84. }
  85. }
  86. /**
  87. * Raw class path entries as given in the java class path string. Only
  88. * entries that could include widgets/widgetsets are listed (primarily
  89. * directories, Vaadin JARs and add-on JARs).
  90. */
  91. private static List<String> rawClasspathEntries = getRawClasspathEntries();
  92. /**
  93. * Map from identifiers (either a package name preceded by the path and a
  94. * slash, or a URL for a JAR file) to the corresponding URLs. This is
  95. * constructed from the class path.
  96. */
  97. private static Map<String, URL> classpathLocations = getClasspathLocations(rawClasspathEntries);
  98. private static boolean debug = false;
  99. static {
  100. String debugProperty = System.getProperty("debug");
  101. if (debugProperty != null && !debugProperty.equals("")) {
  102. debug = true;
  103. }
  104. }
  105. /**
  106. * No instantiation from outside, callable methods are static.
  107. */
  108. private ClassPathExplorer() {
  109. }
  110. /**
  111. * Finds the names and locations of widgetsets available on the class path.
  112. *
  113. * @return map from widgetset classname to widgetset location URL
  114. * @deprecated Use {@link #getAvailableWidgetSetsAndStylesheets()} instead
  115. */
  116. @Deprecated
  117. public static Map<String, URL> getAvailableWidgetSets() {
  118. return getAvailableWidgetSetsAndStylesheets().getWidgetsets();
  119. }
  120. /**
  121. * Finds the names and locations of widgetsets and themes available on the
  122. * class path.
  123. *
  124. * @return
  125. */
  126. public static LocationInfo getAvailableWidgetSetsAndStylesheets() {
  127. long start = System.currentTimeMillis();
  128. Map<String, URL> widgetsets = new HashMap<String, URL>();
  129. Map<String, URL> themes = new HashMap<String, URL>();
  130. Set<String> keySet = classpathLocations.keySet();
  131. for (String location : keySet) {
  132. searchForWidgetSetsAndAddonStyles(location, widgetsets, themes);
  133. }
  134. long end = System.currentTimeMillis();
  135. StringBuilder sb = new StringBuilder();
  136. sb.append("Widgetsets found from classpath:\n");
  137. for (String ws : widgetsets.keySet()) {
  138. sb.append("\t");
  139. sb.append(ws);
  140. sb.append(" in ");
  141. sb.append(widgetsets.get(ws));
  142. sb.append("\n");
  143. }
  144. sb.append("Addon styles found from classpath:\n");
  145. for (String theme : themes.keySet()) {
  146. sb.append("\t");
  147. sb.append(theme);
  148. sb.append(" in ");
  149. sb.append(themes.get(theme));
  150. sb.append("\n");
  151. }
  152. log(sb.toString());
  153. log("Search took " + (end - start) + "ms");
  154. return new LocationInfo(widgetsets, themes);
  155. }
  156. /**
  157. * Finds all GWT modules / Vaadin widgetsets and Addon styles in a valid
  158. * location.
  159. *
  160. * If the location is a directory, all GWT modules (files with the
  161. * ".gwt.xml" extension) are added to widgetsets.
  162. *
  163. * If the location is a JAR file, the comma-separated values of the
  164. * "Vaadin-Widgetsets" attribute in its manifest are added to widgetsets.
  165. *
  166. * @param locationString
  167. * an entry in {@link #classpathLocations}
  168. * @param widgetsets
  169. * a map from widgetset name (including package, with dots as
  170. * separators) to a URL (see {@link #classpathLocations}) - new
  171. * entries are added to this map
  172. */
  173. private static void searchForWidgetSetsAndAddonStyles(
  174. String locationString, Map<String, URL> widgetsets,
  175. Map<String, URL> addonStyles) {
  176. URL location = classpathLocations.get(locationString);
  177. File directory = new File(location.getFile());
  178. if (directory.exists() && !directory.isHidden()) {
  179. // Get the list of the files contained in the directory
  180. String[] files = directory.list();
  181. for (int i = 0; i < files.length; i++) {
  182. // we are only interested in .gwt.xml files
  183. if (!files[i].endsWith(".gwt.xml")) {
  184. continue;
  185. }
  186. // remove the .gwt.xml extension
  187. String classname = files[i].substring(0, files[i].length() - 8);
  188. String packageName = locationString.substring(locationString
  189. .lastIndexOf("/") + 1);
  190. classname = packageName + "." + classname;
  191. if (!WidgetSetBuilder.isWidgetset(classname)) {
  192. // Only return widgetsets and not GWT modules to avoid
  193. // comparing modules and widgetsets
  194. continue;
  195. }
  196. if (!widgetsets.containsKey(classname)) {
  197. String packagePath = packageName.replaceAll("\\.", "/");
  198. String basePath = location.getFile().replaceAll(
  199. "/" + packagePath + "$", "");
  200. try {
  201. URL url = new URL(location.getProtocol(),
  202. location.getHost(), location.getPort(),
  203. basePath);
  204. widgetsets.put(classname, url);
  205. } catch (MalformedURLException e) {
  206. // should never happen as based on an existing URL,
  207. // only changing end of file name/path part
  208. error("Error locating the widgetset " + classname, e);
  209. }
  210. }
  211. }
  212. } else {
  213. try {
  214. // check files in jar file, entries will list all directories
  215. // and files in jar
  216. URLConnection openConnection = location.openConnection();
  217. if (openConnection instanceof JarURLConnection) {
  218. JarURLConnection conn = (JarURLConnection) openConnection;
  219. JarFile jarFile = conn.getJarFile();
  220. Manifest manifest = jarFile.getManifest();
  221. if (manifest == null) {
  222. // No manifest so this is not a Vaadin Add-on
  223. return;
  224. }
  225. // Check for widgetset attribute
  226. String value = manifest.getMainAttributes().getValue(
  227. "Vaadin-Widgetsets");
  228. if (value != null) {
  229. String[] widgetsetNames = value.split(",");
  230. for (int i = 0; i < widgetsetNames.length; i++) {
  231. String widgetsetname = widgetsetNames[i].trim();
  232. if (!widgetsetname.equals("")) {
  233. widgetsets.put(widgetsetname, location);
  234. }
  235. }
  236. }
  237. // Check for theme attribute
  238. value = manifest.getMainAttributes().getValue(
  239. "Vaadin-Stylesheets");
  240. if (value != null) {
  241. String[] stylesheets = value.split(",");
  242. for (int i = 0; i < stylesheets.length; i++) {
  243. String stylesheet = stylesheets[i].trim();
  244. if (!stylesheet.equals("")) {
  245. addonStyles.put(stylesheet, location);
  246. }
  247. }
  248. }
  249. }
  250. } catch (IOException e) {
  251. error("Error parsing jar file", e);
  252. }
  253. }
  254. }
  255. /**
  256. * Splits the current class path into entries, and filters them accepting
  257. * directories, Vaadin add-on JARs with widgetsets and Vaadin JARs.
  258. *
  259. * Some other non-JAR entries may also be included in the result.
  260. *
  261. * @return filtered list of class path entries
  262. */
  263. private final static List<String> getRawClasspathEntries() {
  264. // try to keep the order of the classpath
  265. List<String> locations = new ArrayList<String>();
  266. String pathSep = System.getProperty("path.separator");
  267. String classpath = System.getProperty("java.class.path");
  268. if (classpath.startsWith("\"")) {
  269. classpath = classpath.substring(1);
  270. }
  271. if (classpath.endsWith("\"")) {
  272. classpath = classpath.substring(0, classpath.length() - 1);
  273. }
  274. debug("Classpath: " + classpath);
  275. String[] split = classpath.split(pathSep);
  276. for (int i = 0; i < split.length; i++) {
  277. String classpathEntry = split[i];
  278. if (acceptClassPathEntry(classpathEntry)) {
  279. locations.add(classpathEntry);
  280. }
  281. }
  282. return locations;
  283. }
  284. /**
  285. * Determine every URL location defined by the current classpath, and it's
  286. * associated package name.
  287. *
  288. * See {@link #classpathLocations} for information on output format.
  289. *
  290. * @param rawClasspathEntries
  291. * raw class path entries as split from the Java class path
  292. * string
  293. * @return map of classpath locations, see {@link #classpathLocations}
  294. */
  295. private final static Map<String, URL> getClasspathLocations(
  296. List<String> rawClasspathEntries) {
  297. long start = System.currentTimeMillis();
  298. // try to keep the order of the classpath
  299. Map<String, URL> locations = new LinkedHashMap<String, URL>();
  300. for (String classpathEntry : rawClasspathEntries) {
  301. File file = new File(classpathEntry);
  302. include(null, file, locations);
  303. }
  304. long end = System.currentTimeMillis();
  305. if (debug) {
  306. debug("getClassPathLocations took " + (end - start) + "ms");
  307. }
  308. return locations;
  309. }
  310. /**
  311. * Checks a class path entry to see whether it can contain widgets and
  312. * widgetsets.
  313. *
  314. * All directories are automatically accepted. JARs are accepted if they
  315. * have the "Vaadin-Widgetsets" attribute in their manifest or the JAR file
  316. * name contains "vaadin-" or ".vaadin.".
  317. *
  318. * Also other non-JAR entries may be accepted, the caller should be prepared
  319. * to handle them.
  320. *
  321. * @param classpathEntry
  322. * class path entry string as given in the Java class path
  323. * @return true if the entry should be considered when looking for widgets
  324. * or widgetsets
  325. */
  326. private static boolean acceptClassPathEntry(String classpathEntry) {
  327. if (!classpathEntry.endsWith(".jar")) {
  328. // accept all non jars (practically directories)
  329. return true;
  330. } else {
  331. // accepts jars that comply with vaadin-component packaging
  332. // convention (.vaadin. or vaadin- as distribution packages),
  333. if (classpathEntry.contains("vaadin-")
  334. || classpathEntry.contains(".vaadin.")) {
  335. return true;
  336. } else {
  337. URL url;
  338. try {
  339. url = new URL("file:"
  340. + new File(classpathEntry).getCanonicalPath());
  341. url = new URL("jar:" + url.toExternalForm() + "!/");
  342. JarURLConnection conn = (JarURLConnection) url
  343. .openConnection();
  344. debug(url.toString());
  345. JarFile jarFile = conn.getJarFile();
  346. Manifest manifest = jarFile.getManifest();
  347. if (manifest != null) {
  348. Attributes mainAttributes = manifest
  349. .getMainAttributes();
  350. if (mainAttributes.getValue("Vaadin-Widgetsets") != null) {
  351. return true;
  352. }
  353. if (mainAttributes.getValue("Vaadin-Stylesheets") != null) {
  354. return true;
  355. }
  356. }
  357. } catch (MalformedURLException e) {
  358. if (debug) {
  359. error("Failed to inspect JAR file", e);
  360. }
  361. } catch (IOException e) {
  362. if (debug) {
  363. error("Failed to inspect JAR file", e);
  364. }
  365. }
  366. return false;
  367. }
  368. }
  369. }
  370. /**
  371. * Recursively add subdirectories and jar files to locations - see
  372. * {@link #classpathLocations}.
  373. *
  374. * @param name
  375. * @param file
  376. * @param locations
  377. */
  378. private final static void include(String name, File file,
  379. Map<String, URL> locations) {
  380. if (!file.exists()) {
  381. return;
  382. }
  383. if (!file.isDirectory()) {
  384. // could be a JAR file
  385. includeJar(file, locations);
  386. return;
  387. }
  388. if (file.isHidden() || file.getPath().contains(File.separator + ".")) {
  389. return;
  390. }
  391. if (name == null) {
  392. name = "";
  393. } else {
  394. name += ".";
  395. }
  396. // add all directories recursively
  397. File[] dirs = file.listFiles(DIRECTORIES_ONLY);
  398. for (int i = 0; i < dirs.length; i++) {
  399. try {
  400. // add the present directory
  401. if (!dirs[i].isHidden()
  402. && !dirs[i].getPath().contains(File.separator + ".")) {
  403. String key = dirs[i].getCanonicalPath() + "/" + name
  404. + dirs[i].getName();
  405. locations.put(key,
  406. new URL("file://" + dirs[i].getCanonicalPath()));
  407. }
  408. } catch (Exception ioe) {
  409. return;
  410. }
  411. include(name + dirs[i].getName(), dirs[i], locations);
  412. }
  413. }
  414. /**
  415. * Add a jar file to locations - see {@link #classpathLocations}.
  416. *
  417. * @param name
  418. * @param locations
  419. */
  420. private static void includeJar(File file, Map<String, URL> locations) {
  421. try {
  422. URL url = new URL("file:" + file.getCanonicalPath());
  423. url = new URL("jar:" + url.toExternalForm() + "!/");
  424. JarURLConnection conn = (JarURLConnection) url.openConnection();
  425. JarFile jarFile = conn.getJarFile();
  426. if (jarFile != null) {
  427. // the key does not matter here as long as it is unique
  428. locations.put(url.toString(), url);
  429. }
  430. } catch (Exception e) {
  431. // e.printStackTrace();
  432. return;
  433. }
  434. }
  435. /**
  436. * Find and return the default source directory where to create new
  437. * widgetsets.
  438. *
  439. * Return the first directory (not a JAR file etc.) on the classpath by
  440. * default.
  441. *
  442. * TODO this could be done better...
  443. *
  444. * @return URL
  445. */
  446. public static URL getDefaultSourceDirectory() {
  447. return getWidgetsetSourceDirectory(null);
  448. }
  449. /**
  450. * Find and return the source directory which contains the given widgetset
  451. * file.
  452. *
  453. * If not applicable or widgetsetFileName is null, return the first
  454. * directory (not a JAR file etc.) on the classpath.
  455. *
  456. * TODO this could be done better...
  457. *
  458. * @since 7.6.5
  459. *
  460. * @param widgetsetFileName
  461. * relative path for the widgetset
  462. *
  463. * @return URL
  464. */
  465. public static URL getWidgetsetSourceDirectory(String widgetsetFileName) {
  466. if (debug) {
  467. debug("classpathLocations values:");
  468. ArrayList<String> locations = new ArrayList<String>(
  469. classpathLocations.keySet());
  470. for (String location : locations) {
  471. debug(String.valueOf(classpathLocations.get(location)));
  472. }
  473. }
  474. URL firstDirectory = null;
  475. Iterator<String> it = rawClasspathEntries.iterator();
  476. while (it.hasNext()) {
  477. String entry = it.next();
  478. File directory = new File(entry);
  479. if (directory.exists() && !directory.isHidden()
  480. && directory.isDirectory()) {
  481. try {
  482. URL directoryUrl = directory.toURI().toURL();
  483. // Store the first directory encountered.
  484. if (firstDirectory == null) {
  485. firstDirectory = directoryUrl;
  486. }
  487. if (widgetsetFileName == null
  488. || new File(directory, widgetsetFileName).exists()) {
  489. return directoryUrl;
  490. }
  491. } catch (MalformedURLException e) {
  492. // ignore: continue to the next classpath entry
  493. if (debug) {
  494. e.printStackTrace();
  495. }
  496. }
  497. }
  498. }
  499. return firstDirectory;
  500. }
  501. /**
  502. * Test method for helper tool
  503. */
  504. public static void main(String[] args) {
  505. log("Searching for available widgetsets and stylesheets...");
  506. ClassPathExplorer.getAvailableWidgetSetsAndStylesheets();
  507. }
  508. private static void log(String message) {
  509. System.out.println(message);
  510. }
  511. private static void error(String message, Exception e) {
  512. System.err.println(message);
  513. e.printStackTrace();
  514. }
  515. private static void debug(String message) {
  516. if (debug) {
  517. System.out.println(message);
  518. }
  519. }
  520. }