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.

CoreTestDb.java 6.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2019 SonarSource SA
  4. * mailto:info AT sonarsource DOT com
  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 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.db;
  21. import java.io.File;
  22. import java.io.InputStream;
  23. import java.net.HttpURLConnection;
  24. import java.net.URI;
  25. import java.sql.SQLException;
  26. import java.util.Map;
  27. import java.util.Properties;
  28. import java.util.function.BiConsumer;
  29. import javax.annotation.Nullable;
  30. import org.apache.commons.codec.digest.DigestUtils;
  31. import org.apache.commons.io.FileUtils;
  32. import org.apache.commons.io.IOUtils;
  33. import org.apache.commons.lang.StringUtils;
  34. import org.apache.commons.lang.text.StrSubstitutor;
  35. import org.dbunit.DataSourceDatabaseTester;
  36. import org.dbunit.IDatabaseTester;
  37. import org.dbunit.dataset.datatype.IDataTypeFactory;
  38. import org.junit.AssumptionViolatedException;
  39. import org.sonar.api.config.Settings;
  40. import org.sonar.api.impl.config.MapSettings;
  41. import org.sonar.api.utils.log.Logger;
  42. import org.sonar.api.utils.log.Loggers;
  43. import org.sonar.db.dialect.H2;
  44. import org.sonar.process.logging.LogbackHelper;
  45. import static org.apache.commons.lang.StringUtils.isNotEmpty;
  46. import static org.sonar.process.ProcessProperties.Property.JDBC_USERNAME;
  47. /**
  48. * This class should be call using @ClassRule in order to create the schema once (if @Rule is used
  49. * the schema will be recreated before each test).
  50. */
  51. class CoreTestDb {
  52. private static CoreTestDb DEFAULT;
  53. private static final Logger LOG = Loggers.get(CoreTestDb.class);
  54. private Database db;
  55. private DatabaseCommands commands;
  56. private IDatabaseTester tester;
  57. private boolean isDefault;
  58. protected CoreTestDb() {
  59. // use static factory method
  60. }
  61. protected CoreTestDb(CoreTestDb base) {
  62. this.db = base.db;
  63. this.isDefault = base.isDefault;
  64. this.commands = base.commands;
  65. this.tester = base.tester;
  66. }
  67. CoreTestDb init(@Nullable String schemaPath, BiConsumer<Database, Boolean> extendedStart) {
  68. if (db == null) {
  69. Settings settings = new MapSettings().addProperties(System.getProperties());
  70. if (isNotEmpty(settings.getString("orchestrator.configUrl"))) {
  71. loadOrchestratorSettings(settings);
  72. }
  73. String login = settings.getString(JDBC_USERNAME.getKey());
  74. for (String key : settings.getKeysStartingWith("sonar.jdbc")) {
  75. LOG.info(key + ": " + settings.getString(key));
  76. }
  77. String dialect = settings.getString("sonar.jdbc.dialect");
  78. if (dialect != null && !"h2".equals(dialect)) {
  79. db = new DefaultDatabase(new LogbackHelper(), settings);
  80. } else {
  81. db = new H2Database("h2Tests" + DigestUtils.md5Hex(StringUtils.defaultString(schemaPath)), schemaPath == null);
  82. }
  83. db.start();
  84. if (schemaPath != null) {
  85. // will fail if not H2
  86. if (db.getDialect().getId().equals("h2")) {
  87. ((H2Database) db).executeScript(schemaPath);
  88. } else {
  89. db.stop();
  90. }
  91. }
  92. isDefault = (schemaPath == null);
  93. LOG.debug("Test Database: " + db);
  94. commands = DatabaseCommands.forDialect(db.getDialect());
  95. tester = new DataSourceDatabaseTester(db.getDataSource(), commands.useLoginAsSchema() ? login : null);
  96. extendedStart.accept(db, true);
  97. } else {
  98. extendedStart.accept(db, false);
  99. }
  100. return this;
  101. }
  102. static CoreTestDb create(@Nullable String schemaPath) {
  103. if (schemaPath == null) {
  104. if (DEFAULT == null) {
  105. DEFAULT = new CoreTestDb().init(null, (db, created) -> {
  106. });
  107. }
  108. return DEFAULT;
  109. }
  110. return new CoreTestDb().init(schemaPath, (db, created) -> {
  111. });
  112. }
  113. public void start() {
  114. if (!isDefault && !H2.ID.equals(db.getDialect().getId())) {
  115. throw new AssumptionViolatedException("Test disabled because it supports only H2");
  116. }
  117. }
  118. void stop() {
  119. if (!isDefault) {
  120. db.stop();
  121. }
  122. }
  123. void truncateTables() {
  124. try {
  125. commands.truncateDatabase(db.getDataSource());
  126. } catch (SQLException e) {
  127. throw new IllegalStateException("Fail to truncate db tables", e);
  128. }
  129. }
  130. Database getDatabase() {
  131. return db;
  132. }
  133. DatabaseCommands getCommands() {
  134. return commands;
  135. }
  136. IDatabaseTester getDbUnitTester() {
  137. return tester;
  138. }
  139. IDataTypeFactory getDbUnitFactory() {
  140. return commands.getDbUnitFactory();
  141. }
  142. private void loadOrchestratorSettings(Settings settings) {
  143. String url = settings.getString("orchestrator.configUrl");
  144. InputStream input = null;
  145. try {
  146. URI uri = new URI(url);
  147. if (url.startsWith("file:")) {
  148. File file = new File(uri);
  149. input = FileUtils.openInputStream(file);
  150. } else {
  151. HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();
  152. int responseCode = connection.getResponseCode();
  153. if (responseCode >= 400) {
  154. throw new IllegalStateException("Fail to request: " + uri + ". Status code=" + responseCode);
  155. }
  156. input = connection.getInputStream();
  157. }
  158. Properties props = new Properties();
  159. props.load(input);
  160. settings.addProperties(props);
  161. for (Map.Entry<String, String> entry : settings.getProperties().entrySet()) {
  162. String interpolatedValue = StrSubstitutor.replace(entry.getValue(), System.getenv(), "${", "}");
  163. settings.setProperty(entry.getKey(), interpolatedValue);
  164. }
  165. } catch (Exception e) {
  166. throw new IllegalStateException("Cannot load Orchestrator properties from:" + url, e);
  167. } finally {
  168. IOUtils.closeQuietly(input);
  169. }
  170. }
  171. }