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.

ComponentKeyUpdaterDao.java 8.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2018 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.component;
  21. import com.google.common.annotations.VisibleForTesting;
  22. import com.google.common.collect.ImmutableSet;
  23. import com.google.common.collect.Lists;
  24. import com.google.common.collect.Maps;
  25. import java.util.Collection;
  26. import java.util.HashMap;
  27. import java.util.HashSet;
  28. import java.util.List;
  29. import java.util.Map;
  30. import java.util.Set;
  31. import java.util.function.Function;
  32. import java.util.stream.Collectors;
  33. import org.apache.commons.lang.StringUtils;
  34. import org.sonar.api.resources.Qualifiers;
  35. import org.sonar.db.Dao;
  36. import org.sonar.db.DbSession;
  37. import static com.google.common.base.Preconditions.checkArgument;
  38. import static org.sonar.core.component.ComponentKeys.checkModuleKey;
  39. import static org.sonar.core.component.ComponentKeys.isValidModuleKey;
  40. /**
  41. * Class used to rename the key of a project and its resources.
  42. *
  43. * @since 3.2
  44. */
  45. public class ComponentKeyUpdaterDao implements Dao {
  46. private static final Set<String> PROJECT_OR_MODULE_QUALIFIERS = ImmutableSet.of(Qualifiers.PROJECT, Qualifiers.MODULE);
  47. public void updateKey(DbSession dbSession, String projectOrModuleUuid, String newKey) {
  48. ComponentKeyUpdaterMapper mapper = dbSession.getMapper(ComponentKeyUpdaterMapper.class);
  49. if (mapper.countResourceByKey(newKey) > 0) {
  50. throw new IllegalArgumentException("Impossible to update key: a component with key \"" + newKey + "\" already exists.");
  51. }
  52. // must SELECT first everything
  53. ResourceDto project = mapper.selectProject(projectOrModuleUuid);
  54. String projectOldKey = project.getKey();
  55. List<ResourceDto> resources = mapper.selectProjectResources(projectOrModuleUuid);
  56. resources.add(project);
  57. // add branch components
  58. dbSession.getMapper(BranchMapper.class).selectByProjectUuid(projectOrModuleUuid)
  59. .stream()
  60. .filter(branch -> !projectOrModuleUuid.equals(branch.getUuid()))
  61. .forEach(branch -> {
  62. resources.addAll(mapper.selectProjectResources(branch.getUuid()));
  63. resources.add(mapper.selectProject(branch.getUuid()));
  64. });
  65. // and then proceed with the batch UPDATE at once
  66. runBatchUpdateForAllResources(resources, projectOldKey, newKey, mapper);
  67. }
  68. public static void checkIsProjectOrModule(ComponentDto component) {
  69. checkArgument(PROJECT_OR_MODULE_QUALIFIERS.contains(component.qualifier()), "Component updated must be a module or a key");
  70. }
  71. /**
  72. *
  73. * @return a map with currentKey/newKey is a bulk update was executed
  74. */
  75. public Map<String, String> simulateBulkUpdateKey(DbSession dbSession, String projectUuid, String stringToReplace, String replacementString) {
  76. return collectAllModules(projectUuid, stringToReplace, mapper(dbSession))
  77. .stream()
  78. .collect(Collectors.toMap(
  79. ResourceDto::getKey,
  80. component -> {
  81. String newKey = computeNewKey(component.getKey(), stringToReplace, replacementString);
  82. checkModuleKey(newKey);
  83. return newKey;
  84. }));
  85. }
  86. /**
  87. * @return a map with the component key as key, and boolean as true if key already exists in db
  88. */
  89. public Map<String, Boolean> checkComponentKeys(DbSession dbSession, List<String> newComponentKeys) {
  90. return newComponentKeys.stream().collect(Collectors.toMap(Function.identity(), key -> mapper(dbSession).countResourceByKey(key) > 0));
  91. }
  92. @VisibleForTesting
  93. static String computeNewKey(String key, String stringToReplace, String replacementString) {
  94. return key.replace(stringToReplace, replacementString);
  95. }
  96. public void bulkUpdateKey(DbSession session, String projectUuid, String stringToReplace, String replacementString) {
  97. ComponentKeyUpdaterMapper mapper = session.getMapper(ComponentKeyUpdaterMapper.class);
  98. // must SELECT first everything
  99. Set<ResourceDto> modules = collectAllModules(projectUuid, stringToReplace, mapper);
  100. // add branches
  101. Map<String, String> branchBaseKeys = new HashMap<>();
  102. session.getMapper(BranchMapper.class).selectByProjectUuid(projectUuid)
  103. .stream()
  104. .filter(branch -> !projectUuid.equals(branch.getUuid()))
  105. .forEach(branch -> {
  106. Set<ResourceDto> branchModules = collectAllModules(branch.getUuid(), stringToReplace, mapper);
  107. modules.addAll(branchModules);
  108. branchModules.forEach(module -> branchBaseKeys.put(module.getKey(), branchBaseKey(module.getKey())));
  109. });
  110. checkNewNameOfAllModules(modules, stringToReplace, replacementString, mapper);
  111. Map<ResourceDto, List<ResourceDto>> allResourcesByModuleMap = Maps.newHashMap();
  112. for (ResourceDto module : modules) {
  113. allResourcesByModuleMap.put(module, mapper.selectProjectResources(module.getUuid()));
  114. }
  115. // and then proceed with the batch UPDATE at once
  116. for (ResourceDto module : modules) {
  117. String oldModuleKey = module.getKey();
  118. oldModuleKey = branchBaseKeys.getOrDefault(oldModuleKey, oldModuleKey);
  119. String newModuleKey = computeNewKey(oldModuleKey, stringToReplace, replacementString);
  120. Collection<ResourceDto> resources = Lists.newArrayList(module);
  121. resources.addAll(allResourcesByModuleMap.get(module));
  122. runBatchUpdateForAllResources(resources, oldModuleKey, newModuleKey, mapper);
  123. }
  124. }
  125. private static String branchBaseKey(String key) {
  126. int index = key.lastIndexOf(ComponentDto.BRANCH_KEY_SEPARATOR);
  127. if (index > -1) {
  128. return key.substring(0, index);
  129. }
  130. index = key.lastIndexOf(ComponentDto.PULL_REQUEST_SEPARATOR);
  131. if (index > -1) {
  132. return key.substring(0, index);
  133. }
  134. return key;
  135. }
  136. private static void runBatchUpdateForAllResources(Collection<ResourceDto> resources, String oldKey, String newKey, ComponentKeyUpdaterMapper mapper) {
  137. for (ResourceDto resource : resources) {
  138. String oldResourceKey = resource.getKey();
  139. String newResourceKey = newKey + oldResourceKey.substring(oldKey.length(), oldResourceKey.length());
  140. resource.setKey(newResourceKey);
  141. String oldResourceDeprecatedKey = resource.getDeprecatedKey();
  142. if (StringUtils.isNotBlank(oldResourceDeprecatedKey)) {
  143. String newResourceDeprecatedKey = newKey + oldResourceDeprecatedKey.substring(oldKey.length(), oldResourceDeprecatedKey.length());
  144. resource.setDeprecatedKey(newResourceDeprecatedKey);
  145. }
  146. mapper.update(resource);
  147. }
  148. }
  149. private static Set<ResourceDto> collectAllModules(String projectUuid, String stringToReplace, ComponentKeyUpdaterMapper mapper) {
  150. ResourceDto project = mapper.selectProject(projectUuid);
  151. Set<ResourceDto> modules = new HashSet<>();
  152. if (project.getKey().contains(stringToReplace)) {
  153. modules.add(project);
  154. }
  155. for (ResourceDto submodule : mapper.selectDescendantProjects(projectUuid)) {
  156. modules.addAll(collectAllModules(submodule.getUuid(), stringToReplace, mapper));
  157. }
  158. return modules;
  159. }
  160. private static void checkNewNameOfAllModules(Set<ResourceDto> modules, String stringToReplace, String replacementString, ComponentKeyUpdaterMapper mapper) {
  161. for (ResourceDto module : modules) {
  162. String newKey = computeNewKey(module.getKey(), stringToReplace, replacementString);
  163. checkArgument(isValidModuleKey(newKey), "Malformed key for '%s'. Allowed characters are alphanumeric, '-', '_', '.' and ':', with at least one non-digit.", newKey);
  164. if (mapper.countResourceByKey(newKey) > 0) {
  165. throw new IllegalArgumentException("Impossible to update key: a component with key \"" + newKey + "\" already exists.");
  166. }
  167. }
  168. }
  169. private static ComponentKeyUpdaterMapper mapper(DbSession dbSession) {
  170. return dbSession.getMapper(ComponentKeyUpdaterMapper.class);
  171. }
  172. }