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.

Runner.java 9.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. /*
  2. * Sonar Runner
  3. * Copyright (C) 2011 SonarSource
  4. * dev@sonar.codehaus.org
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 3 of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with this program; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
  19. */
  20. package org.sonar.runner;
  21. import java.io.File;
  22. import java.lang.reflect.Constructor;
  23. import java.lang.reflect.InvocationTargetException;
  24. import java.lang.reflect.Method;
  25. import java.net.MalformedURLException;
  26. import java.net.URL;
  27. import java.util.ArrayList;
  28. import java.util.List;
  29. import java.util.Properties;
  30. /**
  31. * <p>
  32. * Sonar Runner class that can be used to launch Sonar analyses.
  33. * </p>
  34. * <p>
  35. * Configuration is all done through properties:
  36. * </p>
  37. * <ul>
  38. * <li>"sonar.projectDir": the base directory of the project to analyse (this can also be passed via the {@link #create(Properties, File)} constructor)</li>
  39. * <li>"sonar.working.directory": the working directory, which is "${sonar.projectDir}/.sonar" by default.</li>
  40. * <li>"sonar.verbose": if set to "true", more information is displayed in the log</li>
  41. * <li>"sonar.environment.information.key" and "sonar.environment.information.version": can be used to overwrite environment information (can also be
  42. * set via {@link #setEnvironmentInformation(String, String)} method)</li>
  43. * <li>... plus all the other Sonar and Sonar plugins properties.</li>
  44. * </ul>
  45. *
  46. * @since 1.1
  47. */
  48. public final class Runner {
  49. /**
  50. * Old property used to activate debug level for logging.
  51. *
  52. * @deprecated Replaced by sonar.verbose since 1.2
  53. */
  54. @Deprecated
  55. public static final String PROPERTY_OLD_DEBUG_MODE = "runner.debug";
  56. /**
  57. * Property used to increase logging information.
  58. *
  59. * @since 1.2
  60. */
  61. public static final String PROPERTY_VERBOSE = "sonar.verbose";
  62. /**
  63. * Property used to specify the working directory for the runner. May be a relative or absolute path.
  64. *
  65. * @since 1.4
  66. */
  67. public static final String PROPERTY_WORK_DIRECTORY = "sonar.working.directory";
  68. /**
  69. * Default value of the working directory.
  70. */
  71. public static final String DEF_VALUE_WORK_DIRECTORY = ".sonar";
  72. /**
  73. * Property used to specify the base directory of the project to analyse.
  74. *
  75. * @since 1.5
  76. */
  77. public static final String PROPERTY_SONAR_PROJECT_BASEDIR = "sonar.projectBaseDir";
  78. /**
  79. * Property used to specify the name of the tool that will run a Sonar analysis.
  80. *
  81. * @since 1.5
  82. */
  83. public static final String PROPERTY_ENVIRONMENT_INFORMATION_KEY = "sonar.environment.information.key";
  84. /**
  85. * Property used to specify the version of the tool that will run a Sonar analysis.
  86. *
  87. * @since 1.5
  88. */
  89. public static final String PROPERTY_ENVIRONMENT_INFORMATION_VERSION = "sonar.environment.information.version";
  90. /**
  91. * Array of prefixes of versions of Sonar without support of this runner.
  92. */
  93. private static final String[] UNSUPPORTED_VERSIONS = {"1", "2.0", "2.1", "2.2", "2.3", "2.4", "2.5", "2.6", "2.7", "2.8", "2.9", "2.10"};
  94. private File projectDir;
  95. private File workDir;
  96. private String[] unmaskedPackages;
  97. private List<Object> containerExtensions = new ArrayList<Object>();
  98. private Properties properties;
  99. private Runner(Properties props) {
  100. this.properties = props;
  101. this.unmaskedPackages = new String[0];
  102. // set the default values for the Sonar Runner - they can be overriden with #setEnvironmentInformation
  103. this.properties.put(PROPERTY_ENVIRONMENT_INFORMATION_KEY, "Runner");
  104. this.properties.put(PROPERTY_ENVIRONMENT_INFORMATION_VERSION, Version.getVersion());
  105. // and init the directories
  106. initDirs();
  107. }
  108. /**
  109. * Creates a Runner based only on the given properties.
  110. */
  111. public static Runner create(Properties props) {
  112. return new Runner(props);
  113. }
  114. /**
  115. * Creates a Runner based only on the properties and with the given base directory.
  116. */
  117. public static Runner create(Properties props, File basedir) {
  118. props.put(PROPERTY_SONAR_PROJECT_BASEDIR, basedir.getAbsolutePath());
  119. return new Runner(props);
  120. }
  121. /**
  122. * Runs a Sonar analysis.
  123. */
  124. public void execute() {
  125. Bootstrapper bootstrapper = new Bootstrapper("SonarRunner/" + Version.getVersion(), getSonarServerURL(), getWorkDir());
  126. checkSonarVersion(bootstrapper);
  127. delegateExecution(createClassLoader(bootstrapper));
  128. }
  129. public String getSonarServerURL() {
  130. return properties.getProperty("sonar.host.url", "http://localhost:9000");
  131. }
  132. private void initDirs() {
  133. String path = properties.getProperty(PROPERTY_SONAR_PROJECT_BASEDIR, ".");
  134. projectDir = new File(path);
  135. if (!projectDir.isDirectory()) {
  136. throw new RunnerException("Project home must be an existing directory: " + path);
  137. }
  138. // project home exists: add its absolute path as "sonar.runner.projectDir" property
  139. properties.put(PROPERTY_SONAR_PROJECT_BASEDIR, projectDir.getAbsolutePath());
  140. workDir = initWorkDir();
  141. }
  142. private File initWorkDir() {
  143. String customWorkDir = properties.getProperty(PROPERTY_WORK_DIRECTORY);
  144. if (customWorkDir == null || customWorkDir.trim().length() == 0) {
  145. return new File(getProjectDir(), DEF_VALUE_WORK_DIRECTORY);
  146. }
  147. return defineCustomizedWorkDir(new File(customWorkDir));
  148. }
  149. private File defineCustomizedWorkDir(File customWorkDir) {
  150. if (customWorkDir.isAbsolute()) {
  151. return customWorkDir;
  152. }
  153. return new File(getProjectDir(), customWorkDir.getPath());
  154. }
  155. /**
  156. * @return the project base directory
  157. */
  158. public File getProjectDir() {
  159. return projectDir;
  160. }
  161. /**
  162. * @return work directory, default is ".sonar" in project directory
  163. */
  164. public File getWorkDir() {
  165. return workDir;
  166. }
  167. /**
  168. * @return global properties, project properties and command-line properties
  169. */
  170. protected Properties getProperties() {
  171. return properties;
  172. }
  173. protected void checkSonarVersion(Bootstrapper bootstrapper) {
  174. String serverVersion = bootstrapper.getServerVersion();
  175. if (isUnsupportedVersion(serverVersion)) {
  176. throw new RunnerException("Sonar " + serverVersion
  177. + " is not supported. Please upgrade Sonar to version 2.11 or more.");
  178. }
  179. }
  180. private BootstrapClassLoader createClassLoader(Bootstrapper bootstrapper) {
  181. URL url = getJarPath();
  182. return bootstrapper.createClassLoader(
  183. new URL[]{url}, // Add JAR with Sonar Runner - it's a Jar which contains this class
  184. getClass().getClassLoader(),
  185. unmaskedPackages);
  186. }
  187. /**
  188. * For unknown reasons <code>getClass().getProtectionDomain().getCodeSource().getLocation()</code> doesn't work under Ant 1.7.0.
  189. * So this is a workaround.
  190. *
  191. * @return Jar which contains this class
  192. */
  193. public static URL getJarPath() {
  194. String pathToClass = "/" + Runner.class.getName().replace('.', '/') + ".class";
  195. URL url = Runner.class.getResource(pathToClass);
  196. if (url != null) {
  197. String path = url.toString();
  198. String uri = null;
  199. if (path.startsWith("jar:file:")) {
  200. int bang = path.indexOf('!');
  201. uri = path.substring(4, bang);
  202. } else if (path.startsWith("file:")) {
  203. int tail = path.indexOf(pathToClass);
  204. uri = path.substring(0, tail);
  205. }
  206. if (uri != null) {
  207. try {
  208. return new URL(uri);
  209. } catch (MalformedURLException e) { // NOSONAR
  210. }
  211. }
  212. }
  213. return null;
  214. }
  215. static boolean isUnsupportedVersion(String version) {
  216. for (String unsupportedVersion : UNSUPPORTED_VERSIONS) {
  217. if (isVersion(version, unsupportedVersion)) {
  218. return true;
  219. }
  220. }
  221. return false;
  222. }
  223. static boolean isVersion(String version, String prefix) {
  224. return version.startsWith(prefix + ".") || version.equals(prefix);
  225. }
  226. private void delegateExecution(BootstrapClassLoader sonarClassLoader) {
  227. ClassLoader oldContextClassLoader = Thread.currentThread().getContextClassLoader();
  228. try {
  229. Thread.currentThread().setContextClassLoader(sonarClassLoader);
  230. Class<?> launcherClass = sonarClassLoader.findClass("org.sonar.runner.internal.batch.Launcher");
  231. Constructor<?> constructor = launcherClass.getConstructor(Properties.class, List.class);
  232. Object launcher = constructor.newInstance(getProperties(), containerExtensions);
  233. Method method = launcherClass.getMethod("execute");
  234. method.invoke(launcher);
  235. } catch (InvocationTargetException e) {
  236. // Unwrap original exception
  237. throw new RunnerException(e.getTargetException());
  238. } catch (Exception e) {
  239. // Catch all other exceptions, which relates to reflection
  240. throw new RunnerException(e);
  241. } finally {
  242. Thread.currentThread().setContextClassLoader(oldContextClassLoader);
  243. }
  244. }
  245. /**
  246. * Allows to overwrite the environment information when Sonar Runner is embedded in a specific tool (for instance, with the Sonar Ant Task).
  247. *
  248. * @param key the key of the tool that embeds Sonar Runner
  249. * @param version the version of this tool
  250. */
  251. public void setEnvironmentInformation(String key, String version) {
  252. this.properties.put(PROPERTY_ENVIRONMENT_INFORMATION_KEY, key);
  253. this.properties.put(PROPERTY_ENVIRONMENT_INFORMATION_VERSION, version);
  254. }
  255. public void setUnmaskedPackages(String... unmaskedPackages) {
  256. this.unmaskedPackages = unmaskedPackages;
  257. }
  258. public void addContainerExtension(Object extension) {
  259. containerExtensions.add(extension);
  260. }
  261. }