3 * Copyright (C) 2009-2022 SonarSource SA
4 * mailto:info AT sonarsource DOT com
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.
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.
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.
20 package org.sonar.server.qualityprofile;
22 import java.io.Reader;
23 import java.io.Writer;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.Comparator;
28 import java.util.List;
31 import java.util.function.Function;
32 import java.util.stream.Collectors;
33 import javax.annotation.Nullable;
34 import org.apache.commons.lang.builder.CompareToBuilder;
35 import org.sonar.api.rule.RuleKey;
36 import org.sonar.api.rule.RuleStatus;
37 import org.sonar.api.rules.RuleType;
38 import org.sonar.api.server.ServerSide;
39 import org.sonar.db.DbClient;
40 import org.sonar.db.DbSession;
41 import org.sonar.db.qualityprofile.ExportRuleDto;
42 import org.sonar.db.qualityprofile.ExportRuleParamDto;
43 import org.sonar.db.qualityprofile.QProfileDto;
44 import org.sonar.db.rule.DeprecatedRuleKeyDto;
45 import org.sonar.db.rule.RuleDto;
46 import org.sonar.server.qualityprofile.builtin.QProfileName;
47 import org.sonar.server.rule.NewCustomRule;
48 import org.sonar.server.rule.NewRuleDescriptionSection;
49 import org.sonar.server.rule.RuleCreator;
51 import static com.google.common.base.Preconditions.checkArgument;
52 import static java.util.function.Function.identity;
53 import static java.util.stream.Collectors.toSet;
56 public class QProfileBackuperImpl implements QProfileBackuper {
58 private final DbClient db;
59 private final QProfileReset profileReset;
60 private final QProfileFactory profileFactory;
61 private final RuleCreator ruleCreator;
62 private final QProfileParser qProfileParser;
64 public QProfileBackuperImpl(DbClient db, QProfileReset profileReset, QProfileFactory profileFactory,
65 RuleCreator ruleCreator, QProfileParser qProfileParser) {
67 this.profileReset = profileReset;
68 this.profileFactory = profileFactory;
69 this.ruleCreator = ruleCreator;
70 this.qProfileParser = qProfileParser;
74 public void backup(DbSession dbSession, QProfileDto profile, Writer writer) {
75 List<ExportRuleDto> rulesToExport = db.qualityProfileExportDao().selectRulesByProfile(dbSession, profile);
76 rulesToExport.sort(BackupActiveRuleComparator.INSTANCE);
77 qProfileParser.writeXml(writer, profile, rulesToExport.iterator());
81 public QProfileRestoreSummary copy(DbSession dbSession, QProfileDto from, QProfileDto to) {
82 List<ExportRuleDto> rulesToExport = db.qualityProfileExportDao().selectRulesByProfile(dbSession, from);
83 rulesToExport.sort(BackupActiveRuleComparator.INSTANCE);
85 ImportedQProfile qProfile = toImportedQProfile(rulesToExport, to.getName(), to.getLanguage());
86 return restore(dbSession, qProfile, name -> to);
89 private static ImportedQProfile toImportedQProfile(List<ExportRuleDto> exportRules, String profileName, String profileLang) {
90 List<ImportedRule> importedRules = new ArrayList<>(exportRules.size());
92 for (ExportRuleDto exportRuleDto : exportRules) {
93 var ruleKey = exportRuleDto.getRuleKey();
94 ImportedRule importedRule = new ImportedRule();
95 importedRule.setName(exportRuleDto.getName());
96 importedRule.setRepository(ruleKey.repository());
97 importedRule.setKey(ruleKey.rule());
98 importedRule.setSeverity(exportRuleDto.getSeverityString());
99 if (importedRule.isCustomRule()) {
100 importedRule.setTemplate(exportRuleDto.getTemplateRuleKey().rule());
102 importedRule.setType(exportRuleDto.getRuleType().name());
103 exportRuleDto.getRuleDescriptionSections()
105 .map(r -> new NewRuleDescriptionSection(r.getKey(), r.getContent()))
106 .forEach(importedRule::addRuleDescriptionSection);
107 importedRule.setParameters(exportRuleDto.getParams().stream().collect(Collectors.toMap(ExportRuleParamDto::getKey, ExportRuleParamDto::getValue)));
108 importedRules.add(importedRule);
111 return new ImportedQProfile(profileName, profileLang, importedRules);
115 public QProfileRestoreSummary restore(DbSession dbSession, Reader backup, @Nullable String overriddenProfileName) {
116 return restore(dbSession, backup, nameInBackup -> {
117 QProfileName targetName = nameInBackup;
118 if (overriddenProfileName != null) {
119 targetName = new QProfileName(nameInBackup.getLanguage(), overriddenProfileName);
121 return profileFactory.getOrCreateCustom(dbSession, targetName);
126 public QProfileRestoreSummary restore(DbSession dbSession, Reader backup, QProfileDto profile) {
127 return restore(dbSession, backup, nameInBackup -> {
128 checkArgument(profile.getLanguage().equals(nameInBackup.getLanguage()),
129 "Can't restore %s backup on %s profile with key [%s]. Languages are different.", nameInBackup.getLanguage(), profile.getLanguage(), profile.getKee());
134 private QProfileRestoreSummary restore(DbSession dbSession, Reader backup, Function<QProfileName, QProfileDto> profileLoader) {
135 ImportedQProfile qProfile = qProfileParser.readXml(backup);
136 return restore(dbSession, qProfile, profileLoader);
139 private QProfileRestoreSummary restore(DbSession dbSession, ImportedQProfile qProfile, Function<QProfileName, QProfileDto> profileLoader) {
140 QProfileName targetName = new QProfileName(qProfile.getProfileLang(), qProfile.getProfileName());
141 QProfileDto targetProfile = profileLoader.apply(targetName);
143 List<ImportedRule> importedRules = qProfile.getRules();
145 Map<RuleKey, RuleDto> ruleDefinitionsByKey = getImportedRulesDefinitions(dbSession, importedRules);
146 checkIfRulesFromExternalEngines(ruleDefinitionsByKey.values());
148 Map<RuleKey, RuleDto> customRulesDefinitions = createCustomRulesIfNotExist(dbSession, importedRules, ruleDefinitionsByKey);
149 ruleDefinitionsByKey.putAll(customRulesDefinitions);
151 List<RuleActivation> ruleActivations = toRuleActivations(importedRules, ruleDefinitionsByKey);
153 BulkChangeResult changes = profileReset.reset(dbSession, targetProfile, ruleActivations);
154 return new QProfileRestoreSummary(targetProfile, changes);
158 * Returns map of rule definition for an imported rule key.
159 * The imported rule key may refer to a deprecated rule key, in which case the the RuleDto will correspond to a different key (the new key).
161 private Map<RuleKey, RuleDto> getImportedRulesDefinitions(DbSession dbSession, List<ImportedRule> rules) {
162 Set<RuleKey> ruleKeys = rules.stream()
163 .map(ImportedRule::getRuleKey)
165 Map<RuleKey, RuleDto> rulesDefinitions = db.ruleDao().selectByKeys(dbSession, ruleKeys).stream()
166 .collect(Collectors.toMap(RuleDto::getKey, identity()));
168 Set<RuleKey> unrecognizedRuleKeys = ruleKeys.stream()
169 .filter(r -> !rulesDefinitions.containsKey(r))
172 if (!unrecognizedRuleKeys.isEmpty()) {
173 Map<String, DeprecatedRuleKeyDto> deprecatedRuleKeysByUuid = db.ruleDao().selectAllDeprecatedRuleKeys(dbSession).stream()
174 .filter(r -> r.getNewRepositoryKey() != null && r.getNewRuleKey() != null)
175 .filter(r -> unrecognizedRuleKeys.contains(RuleKey.of(r.getOldRepositoryKey(), r.getOldRuleKey())))
176 // ignore deprecated rule if the new rule key was already found in the list of imported rules
177 .filter(r -> !ruleKeys.contains(RuleKey.of(r.getNewRepositoryKey(), r.getNewRuleKey())))
178 .collect(Collectors.toMap(DeprecatedRuleKeyDto::getRuleUuid, identity()));
180 List<RuleDto> rulesBasedOnDeprecatedKeys = db.ruleDao().selectByUuids(dbSession, deprecatedRuleKeysByUuid.keySet());
181 for (RuleDto rule : rulesBasedOnDeprecatedKeys) {
182 DeprecatedRuleKeyDto deprecatedRuleKey = deprecatedRuleKeysByUuid.get(rule.getUuid());
183 RuleKey oldRuleKey = RuleKey.of(deprecatedRuleKey.getOldRepositoryKey(), deprecatedRuleKey.getOldRuleKey());
184 rulesDefinitions.put(oldRuleKey, rule);
188 return rulesDefinitions;
191 private static void checkIfRulesFromExternalEngines(Collection<RuleDto> ruleDefinitions) {
192 List<RuleDto> externalRules = ruleDefinitions.stream()
193 .filter(RuleDto::isExternal)
194 .collect(Collectors.toList());
196 if (!externalRules.isEmpty()) {
197 throw new IllegalArgumentException("The quality profile cannot be restored as it contains rules from external rule engines: "
198 + externalRules.stream().map(r -> r.getKey().toString()).collect(Collectors.joining(", ")));
202 private Map<RuleKey, RuleDto> createCustomRulesIfNotExist(DbSession dbSession, List<ImportedRule> rules, Map<RuleKey, RuleDto> ruleDefinitionsByKey) {
203 List<NewCustomRule> customRulesToCreate = rules.stream()
204 .filter(r -> ruleDefinitionsByKey.get(r.getRuleKey()) == null && r.isCustomRule())
205 .map(QProfileBackuperImpl::importedRuleToNewCustomRule)
206 .collect(Collectors.toList());
208 if (!customRulesToCreate.isEmpty()) {
209 return db.ruleDao().selectByKeys(dbSession, ruleCreator.create(dbSession, customRulesToCreate))
211 .collect(Collectors.toMap(RuleDto::getKey, identity()));
213 return Collections.emptyMap();
216 private static NewCustomRule importedRuleToNewCustomRule(ImportedRule r) {
217 return NewCustomRule.createForCustomRule(r.getRuleKey().rule(), r.getTemplateKey())
218 .setName(r.getName())
219 .setSeverity(r.getSeverity())
220 .setStatus(RuleStatus.READY)
221 .setPreventReactivation(true)
222 .setType(RuleType.valueOf(r.getType()))
223 .setMarkdownDescription(r.getDescription())
224 .setRuleDescriptionSections(r.getRuleDescriptionSections())
225 .setParameters(r.getParameters());
228 private static List<RuleActivation> toRuleActivations(List<ImportedRule> rules, Map<RuleKey, RuleDto> ruleDefinitionsByKey) {
229 List<RuleActivation> activatedRule = new ArrayList<>();
231 for (ImportedRule r : rules) {
232 RuleDto ruleDto = ruleDefinitionsByKey.get(r.getRuleKey());
233 if (ruleDto == null) {
236 activatedRule.add(RuleActivation.create(ruleDto.getUuid(), r.getSeverity(), r.getParameters()));
238 return activatedRule;
241 private enum BackupActiveRuleComparator implements Comparator<ExportRuleDto> {
245 public int compare(ExportRuleDto o1, ExportRuleDto o2) {
246 RuleKey rk1 = o1.getRuleKey();
247 RuleKey rk2 = o2.getRuleKey();
248 return new CompareToBuilder()
249 .append(rk1.repository(), rk2.repository())
250 .append(rk1.rule(), rk2.rule())