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.

JRubyFacade.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. /*
  2. * SonarQube, open source software quality management tool.
  3. * Copyright (C) 2008-2014 SonarSource
  4. * mailto:contact AT sonarsource DOT com
  5. *
  6. * SonarQube 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. * SonarQube 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 License
  17. * along with this program; if not, write to the Free Software Foundation,
  18. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. */
  20. package org.sonar.server.ui;
  21. import java.net.InetAddress;
  22. import java.sql.Connection;
  23. import java.util.Collection;
  24. import java.util.Date;
  25. import java.util.List;
  26. import java.util.Map;
  27. import javax.annotation.CheckForNull;
  28. import javax.annotation.Nullable;
  29. import org.sonar.api.Plugin;
  30. import org.sonar.api.config.License;
  31. import org.sonar.api.config.PropertyDefinitions;
  32. import org.sonar.api.config.Settings;
  33. import org.sonar.api.platform.NewUserHandler;
  34. import org.sonar.api.resources.Language;
  35. import org.sonar.api.resources.ResourceType;
  36. import org.sonar.api.resources.ResourceTypes;
  37. import org.sonar.api.utils.log.Loggers;
  38. import org.sonar.api.web.Footer;
  39. import org.sonar.api.web.Page;
  40. import org.sonar.api.web.RubyRailsWebservice;
  41. import org.sonar.api.web.Widget;
  42. import org.sonar.core.persistence.Database;
  43. import org.sonar.core.persistence.DatabaseVersion;
  44. import org.sonar.core.platform.ComponentContainer;
  45. import org.sonar.core.platform.PluginInfo;
  46. import org.sonar.core.platform.PluginRepository;
  47. import org.sonar.core.resource.ResourceIndexerDao;
  48. import org.sonar.core.timemachine.Periods;
  49. import org.sonar.process.ProcessProperties;
  50. import org.sonar.server.component.ComponentCleanerService;
  51. import org.sonar.server.db.migrations.DatabaseMigration;
  52. import org.sonar.server.db.migrations.DatabaseMigrator;
  53. import org.sonar.server.measure.MeasureFilterEngine;
  54. import org.sonar.server.measure.MeasureFilterResult;
  55. import org.sonar.server.platform.Platform;
  56. import org.sonar.server.platform.ServerIdGenerator;
  57. import org.sonar.server.platform.ServerSettings;
  58. import org.sonar.server.platform.SettingsChangeNotifier;
  59. import org.sonar.server.plugins.InstalledPluginReferentialFactory;
  60. import org.sonar.server.plugins.PluginDownloader;
  61. import org.sonar.server.plugins.ServerPluginRepository;
  62. import org.sonar.server.plugins.UpdateCenterMatrixFactory;
  63. import org.sonar.server.rule.RuleRepositories;
  64. import org.sonar.server.user.NewUserNotifier;
  65. import org.sonar.updatecenter.common.PluginReferential;
  66. import org.sonar.updatecenter.common.UpdateCenter;
  67. import org.sonar.updatecenter.common.Version;
  68. import static com.google.common.collect.Lists.newArrayList;
  69. public final class JRubyFacade {
  70. private static final JRubyFacade SINGLETON = new JRubyFacade();
  71. public static JRubyFacade getInstance() {
  72. return SINGLETON;
  73. }
  74. <T> T get(Class<T> componentType) {
  75. return getContainer().getComponentByType(componentType);
  76. }
  77. public MeasureFilterResult executeMeasureFilter(Map<String, Object> map, @Nullable Long userId) {
  78. return get(MeasureFilterEngine.class).execute(map, userId);
  79. }
  80. public Collection<ResourceType> getResourceTypesForFilter() {
  81. return get(ResourceTypes.class).getAll(ResourceTypes.AVAILABLE_FOR_FILTERS);
  82. }
  83. public Collection<ResourceType> getResourceTypes() {
  84. return get(ResourceTypes.class).getAll();
  85. }
  86. public Collection<ResourceType> getResourceRootTypes() {
  87. return get(ResourceTypes.class).getRoots();
  88. }
  89. public ResourceType getResourceType(String qualifier) {
  90. return get(ResourceTypes.class).get(qualifier);
  91. }
  92. public String getResourceTypeStringProperty(String resourceTypeQualifier, String resourceTypeProperty) {
  93. ResourceType resourceType = getResourceType(resourceTypeQualifier);
  94. if (resourceType != null) {
  95. return resourceType.getStringProperty(resourceTypeProperty);
  96. }
  97. return null;
  98. }
  99. public List<String> getQualifiersWithProperty(final String propertyKey) {
  100. List<String> qualifiers = newArrayList();
  101. for (ResourceType type : getResourceTypes()) {
  102. if (type.getBooleanProperty(propertyKey) == Boolean.TRUE) {
  103. qualifiers.add(type.getQualifier());
  104. }
  105. }
  106. return qualifiers;
  107. }
  108. public Boolean getResourceTypeBooleanProperty(String resourceTypeQualifier, String resourceTypeProperty) {
  109. ResourceType resourceType = getResourceType(resourceTypeQualifier);
  110. if (resourceType != null) {
  111. return resourceType.getBooleanProperty(resourceTypeProperty);
  112. }
  113. return null;
  114. }
  115. public Collection<String> getResourceLeavesQualifiers(String qualifier) {
  116. return get(ResourceTypes.class).getLeavesQualifiers(qualifier);
  117. }
  118. public Collection<String> getResourceChildrenQualifiers(String qualifier) {
  119. return get(ResourceTypes.class).getChildrenQualifiers(qualifier);
  120. }
  121. // UPDATE CENTER ------------------------------------------------------------
  122. public void downloadPlugin(String pluginKey, String pluginVersion) {
  123. get(PluginDownloader.class).download(pluginKey, Version.create(pluginVersion));
  124. }
  125. public void cancelPluginDownloads() {
  126. get(PluginDownloader.class).cancelDownloads();
  127. }
  128. public List<String> getPluginDownloads() {
  129. return get(PluginDownloader.class).getDownloadedPluginFilenames();
  130. }
  131. public void uninstallPlugin(String pluginKey) {
  132. get(ServerPluginRepository.class).uninstall(pluginKey);
  133. }
  134. public void cancelPluginUninstalls() {
  135. get(ServerPluginRepository.class).cancelUninstalls();
  136. }
  137. public List<String> getPluginUninstalls() {
  138. return get(ServerPluginRepository.class).getUninstalledPluginFilenames();
  139. }
  140. public UpdateCenter getUpdatePluginCenter(boolean forceReload) {
  141. return get(UpdateCenterMatrixFactory.class).getUpdateCenter(forceReload);
  142. }
  143. public PluginReferential getInstalledPluginReferential() {
  144. return get(InstalledPluginReferentialFactory.class).getInstalledPluginReferential();
  145. }
  146. // PLUGINS ------------------------------------------------------------------
  147. public PropertyDefinitions getPropertyDefinitions() {
  148. return get(PropertyDefinitions.class);
  149. }
  150. /**
  151. * Used for WS api/updatecenter/installed_plugins, to be replaced by api/plugins/installed.
  152. */
  153. public Collection<PluginInfo> getPluginInfos() {
  154. return get(PluginRepository.class).getPluginInfos();
  155. }
  156. public List<ViewProxy<Widget>> getWidgets(String resourceScope, String resourceQualifier, String resourceLanguage, Object[] availableMeasures) {
  157. return get(Views.class).getWidgets(resourceScope, resourceQualifier, resourceLanguage, (String[]) availableMeasures);
  158. }
  159. public List<ViewProxy<Widget>> getWidgets() {
  160. return get(Views.class).getWidgets();
  161. }
  162. public ViewProxy<Widget> getWidget(String id) {
  163. return get(Views.class).getWidget(id);
  164. }
  165. public List<ViewProxy<Page>> getPages(String section, String resourceScope, String resourceQualifier, String resourceLanguage, Object[] availableMeasures) {
  166. return get(Views.class).getPages(section, resourceScope, resourceQualifier, resourceLanguage, (String[]) availableMeasures);
  167. }
  168. public ViewProxy<Page> getPage(String id) {
  169. return get(Views.class).getPage(id);
  170. }
  171. public Collection<RubyRailsWebservice> getRubyRailsWebservices() {
  172. return getContainer().getComponentsByType(RubyRailsWebservice.class);
  173. }
  174. public Collection<Language> getLanguages() {
  175. return getContainer().getComponentsByType(Language.class);
  176. }
  177. public Database getDatabase() {
  178. return get(Database.class);
  179. }
  180. // Only used by Java migration
  181. public DatabaseMigrator databaseMigrator() {
  182. return get(DatabaseMigrator.class);
  183. }
  184. /* PROFILES CONSOLE : RULES AND METRIC THRESHOLDS */
  185. /**
  186. * @deprecated in 4.2
  187. */
  188. @Deprecated
  189. @CheckForNull
  190. public RuleRepositories.Repository getRuleRepository(String repositoryKey) {
  191. return get(RuleRepositories.class).repository(repositoryKey);
  192. }
  193. public Collection<RuleRepositories.Repository> getRuleRepositories() {
  194. return get(RuleRepositories.class).repositories();
  195. }
  196. public Collection<RuleRepositories.Repository> getRuleRepositoriesByLanguage(String languageKey) {
  197. return get(RuleRepositories.class).repositoriesForLang(languageKey);
  198. }
  199. public List<Footer> getWebFooters() {
  200. return getContainer().getComponentsByType(Footer.class);
  201. }
  202. public void setGlobalProperty(String key, @Nullable String value) {
  203. get(ServerSettings.class).setProperty(key, value);
  204. get(SettingsChangeNotifier.class).onGlobalPropertyChange(key, value);
  205. }
  206. public Settings getSettings() {
  207. return get(Settings.class);
  208. }
  209. public String getConfigurationValue(String key) {
  210. return get(Settings.class).getString(key);
  211. }
  212. public List<InetAddress> getValidInetAddressesForServerId() {
  213. return get(ServerIdGenerator.class).getAvailableAddresses();
  214. }
  215. public String generateServerId(String organisation, String ipAddress) {
  216. return get(ServerIdGenerator.class).generate(organisation, ipAddress);
  217. }
  218. public Connection getConnection() {
  219. try {
  220. return get(Database.class).getDataSource().getConnection();
  221. } catch (Exception e) {
  222. /* activerecord does not correctly manage exceptions when connection can not be opened. */
  223. return null;
  224. }
  225. }
  226. public Object getCoreComponentByClassname(String className) {
  227. if (className == null) {
  228. return null;
  229. }
  230. try {
  231. return get(Class.forName(className));
  232. } catch (ClassNotFoundException e) {
  233. Loggers.get(getClass()).error("Component not found: " + className, e);
  234. return null;
  235. }
  236. }
  237. public Object getComponentByClassname(String pluginKey, String className) {
  238. Plugin plugin = get(PluginRepository.class).getPluginInstance(pluginKey);
  239. try {
  240. Class componentClass = plugin.getClass().getClassLoader().loadClass(className);
  241. return get(componentClass);
  242. } catch (ClassNotFoundException e) {
  243. throw new IllegalStateException(String.format("Class [%s] not found in plugin [%s]", className, pluginKey), e);
  244. }
  245. }
  246. private JRubyI18n getJRubyI18n() {
  247. return get(JRubyI18n.class);
  248. }
  249. public String getMessage(String rubyLocale, String key, String defaultValue, Object... parameters) {
  250. return getJRubyI18n().message(rubyLocale, key, defaultValue, parameters);
  251. }
  252. public void indexProjects() {
  253. get(ResourceIndexerDao.class).indexProjects();
  254. }
  255. public void indexResource(long resourceId) {
  256. get(ResourceIndexerDao.class).indexResource(resourceId);
  257. }
  258. /*
  259. * /!\ Used by Views
  260. */
  261. public void deleteResourceTree(String projectKey) {
  262. try {
  263. get(ComponentCleanerService.class).delete(projectKey);
  264. } catch (RuntimeException e) {
  265. Loggers.get(JRubyFacade.class).error("Fail to delete resource with key: " + projectKey, e);
  266. throw e;
  267. }
  268. }
  269. public void logError(String message) {
  270. Loggers.get(getClass()).error(message);
  271. }
  272. public boolean hasSecretKey() {
  273. return get(Settings.class).getEncryption().hasSecretKey();
  274. }
  275. public String encrypt(String clearText) {
  276. return get(Settings.class).getEncryption().encrypt(clearText);
  277. }
  278. public String generateRandomSecretKey() {
  279. return get(Settings.class).getEncryption().generateRandomSecretKey();
  280. }
  281. public License parseLicense(String base64) {
  282. return License.readBase64(base64);
  283. }
  284. public String getServerHome() {
  285. return get(Settings.class).getString(ProcessProperties.PATH_HOME);
  286. }
  287. public ComponentContainer getContainer() {
  288. return Platform.getInstance().getContainer();
  289. }
  290. // USERS
  291. public void onNewUser(Map<String, String> fields) {
  292. NewUserNotifier notifier = get(NewUserNotifier.class);
  293. // notifier is null when creating the administrator in the migration script 011.
  294. if (notifier != null) {
  295. notifier.onNewUser(NewUserHandler.Context.builder()
  296. .setLogin(fields.get("login"))
  297. .setName(fields.get("name"))
  298. .setEmail(fields.get("email"))
  299. .build());
  300. }
  301. }
  302. public String getPeriodLabel(int periodIndex) {
  303. return get(Periods.class).label(periodIndex);
  304. }
  305. public String getPeriodLabel(String mode, String param, Date date) {
  306. return get(Periods.class).label(mode, param, date);
  307. }
  308. public String getPeriodLabel(String mode, String param, String date) {
  309. return get(Periods.class).label(mode, param, date);
  310. }
  311. public String getPeriodAbbreviation(int periodIndex) {
  312. return get(Periods.class).abbreviation(periodIndex);
  313. }
  314. /**
  315. * Checks whether the SQ instance is up and running (ie. not in safemode and with an up-to-date database).
  316. * <p>
  317. * This method duplicates most of the logic code written in {@link org.sonar.server.platform.ws.UpgradesSystemWsAction}
  318. * class. There is no need to refactor code to avoid this duplication since this method is only used by RoR code
  319. * which will soon be replaced by pure JS code based on the {@link org.sonar.server.platform.ws.UpgradesSystemWsAction}
  320. * WebService.
  321. * </p>
  322. */
  323. public boolean isSonarAccessAllowed() {
  324. ComponentContainer container = Platform.getInstance().getContainer();
  325. DatabaseMigration databaseMigration = container.getComponentByType(DatabaseMigration.class);
  326. if (databaseMigration.status() == DatabaseMigration.Status.RUNNING
  327. || databaseMigration.status() == DatabaseMigration.Status.FAILED) {
  328. return false;
  329. }
  330. if (databaseMigration.status() == DatabaseMigration.Status.SUCCEEDED) {
  331. return true;
  332. }
  333. DatabaseVersion databaseVersion = container.getComponentByType(DatabaseVersion.class);
  334. Integer currentVersion = databaseVersion.getVersion();
  335. if (currentVersion == null) {
  336. throw new IllegalStateException("Version can not be retrieved from Database. Database is either blank or corrupted");
  337. }
  338. if (currentVersion >= DatabaseVersion.LAST_VERSION) {
  339. return true;
  340. }
  341. Database database = container.getComponentByType(Database.class);
  342. return !database.getDialect().supportsMigration();
  343. }
  344. }