]> source.dussan.org Git - sonarqube.git/commitdiff
SONAR-4923 Create QProfileExporter used to import / export active rules from plugin xml
authorJulien Lancelot <julien.lancelot@sonarsource.com>
Thu, 16 Jan 2014 18:19:12 +0000 (19:19 +0100)
committerJulien Lancelot <julien.lancelot@sonarsource.com>
Thu, 16 Jan 2014 18:19:23 +0000 (19:19 +0100)
sonar-server/src/main/java/org/sonar/server/platform/Platform.java
sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileExporter.java [new file with mode: 0644]
sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileOperations.java
sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileResult.java
sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileExporterTest.java [new file with mode: 0644]
sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileOperationsTest.java

index 97e0e29544c2e9e9b4786f29b57c725d257f0094..b0f29bf52a2c5b97bf4e560254ee639a998fc0db 100644 (file)
@@ -279,6 +279,7 @@ public final class Platform {
     servicesContainer.addSingleton(QProfileProjectOperations.class);
     servicesContainer.addSingleton(QProfileProjectLookup.class);
     servicesContainer.addSingleton(QProfileBackup.class);
+    servicesContainer.addSingleton(QProfileExporter.class);
 
     // users
     servicesContainer.addSingleton(HibernateUserFinder.class);
diff --git a/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileExporter.java b/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileExporter.java
new file mode 100644 (file)
index 0000000..27f9688
--- /dev/null
@@ -0,0 +1,134 @@
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2013 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ */
+
+package org.sonar.server.qualityprofile;
+
+import com.google.common.collect.ArrayListMultimap;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Multimap;
+import org.apache.commons.lang.StringUtils;
+import org.apache.ibatis.session.SqlSession;
+import org.sonar.api.ServerComponent;
+import org.sonar.api.profiles.ProfileImporter;
+import org.sonar.api.profiles.RulesProfile;
+import org.sonar.api.rules.ActiveRule;
+import org.sonar.api.rules.ActiveRuleParam;
+import org.sonar.api.rules.RulePriority;
+import org.sonar.api.utils.ValidationMessages;
+import org.sonar.core.qualityprofile.db.ActiveRuleDao;
+import org.sonar.core.qualityprofile.db.ActiveRuleDto;
+import org.sonar.core.qualityprofile.db.ActiveRuleParamDto;
+import org.sonar.server.exceptions.BadRequestException;
+import org.sonar.server.rule.RuleRegistry;
+
+import javax.annotation.CheckForNull;
+
+import java.io.StringReader;
+import java.util.List;
+
+import static com.google.common.collect.Lists.newArrayList;
+
+public class QProfileExporter implements ServerComponent {
+
+  private final ActiveRuleDao activeRuleDao;
+  private final List<ProfileImporter> importers;
+  private final RuleRegistry ruleRegistry;
+
+  /**
+   * Used by pico when no plugin provide profile exporter / importer
+   */
+  public QProfileExporter(ActiveRuleDao activeRuleDao, RuleRegistry ruleRegistry) {
+    this(activeRuleDao, Lists.<ProfileImporter>newArrayList(), ruleRegistry);
+  }
+
+  public QProfileExporter(ActiveRuleDao activeRuleDao, List<ProfileImporter> importers, RuleRegistry ruleRegistry) {
+    this.activeRuleDao = activeRuleDao;
+    this.importers = importers;
+    this.ruleRegistry = ruleRegistry;
+  }
+
+  public QProfileResult importXml(QProfile profile, String pluginKey, String xml, SqlSession session) {
+    QProfileResult result = new QProfileResult();
+    ValidationMessages messages = ValidationMessages.create();
+    ProfileImporter importer = getProfileImporter(pluginKey);
+    RulesProfile rulesProfile = importer.importProfile(new StringReader(xml), messages);
+    importProfile(profile.id(), rulesProfile, session);
+    processValidationMessages(messages, result);
+    return result;
+  }
+
+  private void importProfile(int profileId, RulesProfile rulesProfile, SqlSession sqlSession) {
+    List<ActiveRuleDto> activeRuleDtos = newArrayList();
+    Multimap<Integer, ActiveRuleParamDto> paramsByActiveRule = ArrayListMultimap.create();
+    for (ActiveRule activeRule : rulesProfile.getActiveRules()) {
+      ActiveRuleDto activeRuleDto = toActiveRuleDto(activeRule, profileId);
+      activeRuleDao.insert(activeRuleDto, sqlSession);
+      activeRuleDtos.add(activeRuleDto);
+      for (ActiveRuleParam activeRuleParam : activeRule.getActiveRuleParams()) {
+        ActiveRuleParamDto activeRuleParamDto = toActiveRuleParamDto(activeRuleParam, activeRuleDto);
+        activeRuleDao.insert(activeRuleParamDto, sqlSession);
+        paramsByActiveRule.put(activeRuleDto.getId(), activeRuleParamDto);
+      }
+    }
+    ruleRegistry.bulkIndexActiveRules(activeRuleDtos, paramsByActiveRule);
+  }
+
+  @CheckForNull
+  private ProfileImporter getProfileImporter(String exporterKey) {
+    for (ProfileImporter importer : importers) {
+      if (StringUtils.equals(exporterKey, importer.getKey())) {
+        return importer;
+      }
+    }
+    return null;
+  }
+
+  private void processValidationMessages(ValidationMessages messages, QProfileResult result) {
+    if (!messages.getErrors().isEmpty()) {
+      List<BadRequestException.Message> errors = newArrayList();
+      for (String error : messages.getErrors()) {
+        errors.add(BadRequestException.Message.of(error));
+      }
+      throw BadRequestException.of("Fail to import profile", errors);
+    }
+    result.setWarnings(messages.getWarnings());
+    result.setInfos(messages.getInfos());
+  }
+
+  private ActiveRuleDto toActiveRuleDto(ActiveRule activeRule, int profileId) {
+    return new ActiveRuleDto()
+      .setProfileId(profileId)
+      .setRuleId(activeRule.getRule().getId())
+      .setSeverity(toSeverityLevel(activeRule.getSeverity()));
+  }
+
+  private Integer toSeverityLevel(RulePriority rulePriority) {
+    return rulePriority.ordinal();
+  }
+
+  private ActiveRuleParamDto toActiveRuleParamDto(ActiveRuleParam activeRuleParam, ActiveRuleDto activeRuleDto) {
+    return new ActiveRuleParamDto()
+      .setActiveRuleId(activeRuleDto.getId())
+      .setRulesParameterId(activeRuleParam.getRuleParam().getId())
+      .setKey(activeRuleParam.getKey())
+      .setValue(activeRuleParam.getValue());
+  }
+
+}
index 56befc8555f0ac413bd04800ff1a66df0593304a..2443914547faa1663d413889eb3090f3f19f5322 100644 (file)
 package org.sonar.server.qualityprofile;
 
 import com.google.common.annotations.VisibleForTesting;
-import com.google.common.collect.ArrayListMultimap;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Multimap;
-import org.apache.commons.lang.StringUtils;
 import org.apache.ibatis.session.SqlSession;
 import org.sonar.api.ServerComponent;
-import org.sonar.api.profiles.ProfileImporter;
-import org.sonar.api.profiles.RulesProfile;
-import org.sonar.api.rules.ActiveRule;
-import org.sonar.api.rules.ActiveRuleParam;
-import org.sonar.api.rules.RulePriority;
-import org.sonar.api.utils.ValidationMessages;
 import org.sonar.core.permission.GlobalPermissions;
 import org.sonar.core.persistence.MyBatis;
 import org.sonar.core.preview.PreviewCache;
 import org.sonar.core.properties.PropertiesDao;
 import org.sonar.core.properties.PropertyDto;
-import org.sonar.core.qualityprofile.db.*;
+import org.sonar.core.qualityprofile.db.ActiveRuleDao;
+import org.sonar.core.qualityprofile.db.QualityProfileDao;
+import org.sonar.core.qualityprofile.db.QualityProfileDto;
 import org.sonar.server.configuration.ProfilesManager;
 import org.sonar.server.exceptions.BadRequestException;
 import org.sonar.server.rule.RuleRegistry;
@@ -47,12 +39,8 @@ import org.sonar.server.user.UserSession;
 import javax.annotation.CheckForNull;
 import javax.annotation.Nullable;
 
-import java.io.StringReader;
-import java.util.List;
 import java.util.Map;
 
-import static com.google.common.collect.Lists.newArrayList;
-
 public class QProfileOperations implements ServerComponent {
 
   public static final String PROFILE_PROPERTY_PREFIX = "sonar.profile.";
@@ -61,27 +49,19 @@ public class QProfileOperations implements ServerComponent {
   private final QualityProfileDao dao;
   private final ActiveRuleDao activeRuleDao;
   private final PropertiesDao propertiesDao;
-  private final List<ProfileImporter> importers;
+  private final QProfileExporter exporter;
   private final PreviewCache dryRunCache;
   private final RuleRegistry ruleRegistry;
   private final QProfileLookup profileLookup;
   private final ProfilesManager profilesManager;
 
-  /**
-   * Used by pico when no plugin provide profile exporter / importer
-   */
   public QProfileOperations(MyBatis myBatis, QualityProfileDao dao, ActiveRuleDao activeRuleDao, PropertiesDao propertiesDao,
-                            PreviewCache dryRunCache, RuleRegistry ruleRegistry, QProfileLookup profileLookup, ProfilesManager profilesManager) {
-    this(myBatis, dao, activeRuleDao, propertiesDao, Lists.<ProfileImporter>newArrayList(), dryRunCache, ruleRegistry, profileLookup, profilesManager);
-  }
-
-  public QProfileOperations(MyBatis myBatis, QualityProfileDao dao, ActiveRuleDao activeRuleDao, PropertiesDao propertiesDao,
-                            List<ProfileImporter> importers, PreviewCache dryRunCache, RuleRegistry ruleRegistry, QProfileLookup profileLookup, ProfilesManager profilesManager) {
+                            QProfileExporter exporter, PreviewCache dryRunCache, RuleRegistry ruleRegistry, QProfileLookup profileLookup, ProfilesManager profilesManager) {
     this.myBatis = myBatis;
     this.dao = dao;
     this.activeRuleDao = activeRuleDao;
     this.propertiesDao = propertiesDao;
-    this.importers = importers;
+    this.exporter = exporter;
     this.dryRunCache = dryRunCache;
     this.ruleRegistry = ruleRegistry;
     this.profileLookup = profileLookup;
@@ -94,11 +74,11 @@ public class QProfileOperations implements ServerComponent {
       QProfile profile = newProfile(name, language, userSession, session);
 
       QProfileResult result = new QProfileResult();
-      List<RulesProfile> importProfiles = readProfilesFromXml(result, xmlProfilesByPlugin);
-      for (RulesProfile rulesProfile : importProfiles) {
-        importProfile(profile.id(), rulesProfile, session);
-      }
       result.setProfile(profile);
+
+      for (Map.Entry<String, String> entry : xmlProfilesByPlugin.entrySet()) {
+        result.add(exporter.importXml(profile, entry.getKey(), entry.getValue(), session));
+      }
       session.commit();
       dryRunCache.reportGlobalModification();
       return result;
@@ -142,24 +122,28 @@ public class QProfileOperations implements ServerComponent {
     checkPermission(userSession);
     SqlSession session = myBatis.openSession();
     try {
-      QualityProfileDto profile = findNotNull(profileId, session);
-      if (!profileLookup.isDeletable(QProfile.from(profile), session)) {
-        throw new BadRequestException("This profile can not be deleted");
-      } else {
-        activeRuleDao.deleteParametersFromProfile(profile.getId(), session);
-        activeRuleDao.deleteFromProfile(profile.getId(), session);
-        dao.delete(profile.getId(), session);
-        propertiesDao.deleteProjectProperties(PROFILE_PROPERTY_PREFIX + profile.getLanguage(), profile.getName(), session);
-        ruleRegistry.deleteActiveRulesFromProfile(profile.getId());
-        session.commit();
-
-        dryRunCache.reportGlobalModification();
-      }
+      deleteProfile(profileId, userSession, session);
+      session.commit();
     } finally {
       MyBatis.closeQuietly(session);
     }
   }
 
+  public void deleteProfile(int profileId, UserSession userSession, SqlSession session) {
+    checkPermission(userSession);
+    QualityProfileDto profile = findNotNull(profileId, session);
+    if (!profileLookup.isDeletable(QProfile.from(profile), session)) {
+      throw new BadRequestException("This profile can not be deleted");
+    } else {
+      activeRuleDao.deleteParametersFromProfile(profile.getId(), session);
+      activeRuleDao.deleteFromProfile(profile.getId(), session);
+      dao.delete(profile.getId(), session);
+      propertiesDao.deleteProjectProperties(PROFILE_PROPERTY_PREFIX + profile.getLanguage(), profile.getName(), session);
+      ruleRegistry.deleteActiveRulesFromProfile(profile.getId());
+      dryRunCache.reportGlobalModification();
+    }
+  }
+
   public void setDefaultProfile(int profileId, UserSession userSession) {
     checkPermission(userSession);
     SqlSession session = myBatis.openSession();
@@ -217,77 +201,6 @@ public class QProfileOperations implements ServerComponent {
     return null;
   }
 
-  private List<RulesProfile> readProfilesFromXml(QProfileResult result, Map<String, String> xmlProfilesByPlugin) {
-    List<RulesProfile> profiles = newArrayList();
-    ValidationMessages messages = ValidationMessages.create();
-    for (Map.Entry<String, String> entry : xmlProfilesByPlugin.entrySet()) {
-      String pluginKey = entry.getKey();
-      String file = entry.getValue();
-      ProfileImporter importer = getProfileImporter(pluginKey);
-      RulesProfile profile = importer.importProfile(new StringReader(file), messages);
-      processValidationMessages(messages, result);
-      profiles.add(profile);
-    }
-    return profiles;
-  }
-
-  public void importProfile(int profileId, RulesProfile rulesProfile, SqlSession sqlSession) {
-    List<ActiveRuleDto> activeRuleDtos = newArrayList();
-    Multimap<Integer, ActiveRuleParamDto> paramsByActiveRule = ArrayListMultimap.create();
-    for (ActiveRule activeRule : rulesProfile.getActiveRules()) {
-      ActiveRuleDto activeRuleDto = toActiveRuleDto(activeRule, profileId);
-      activeRuleDao.insert(activeRuleDto, sqlSession);
-      activeRuleDtos.add(activeRuleDto);
-      for (ActiveRuleParam activeRuleParam : activeRule.getActiveRuleParams()) {
-        ActiveRuleParamDto activeRuleParamDto = toActiveRuleParamDto(activeRuleParam, activeRuleDto);
-        activeRuleDao.insert(activeRuleParamDto, sqlSession);
-        paramsByActiveRule.put(activeRuleDto.getId(), activeRuleParamDto);
-      }
-    }
-    ruleRegistry.bulkIndexActiveRules(activeRuleDtos, paramsByActiveRule);
-  }
-
-  @CheckForNull
-  private ProfileImporter getProfileImporter(String exporterKey) {
-    for (ProfileImporter importer : importers) {
-      if (StringUtils.equals(exporterKey, importer.getKey())) {
-        return importer;
-      }
-    }
-    return null;
-  }
-
-  private void processValidationMessages(ValidationMessages messages, QProfileResult result) {
-    if (!messages.getErrors().isEmpty()) {
-      List<BadRequestException.Message> errors = newArrayList();
-      for (String error : messages.getErrors()) {
-        errors.add(BadRequestException.Message.of(error));
-      }
-      throw BadRequestException.of("Fail to create profile", errors);
-    }
-    result.setWarnings(messages.getWarnings());
-    result.setInfos(messages.getInfos());
-  }
-
-  private ActiveRuleDto toActiveRuleDto(ActiveRule activeRule, int profileId) {
-    return new ActiveRuleDto()
-      .setProfileId(profileId)
-      .setRuleId(activeRule.getRule().getId())
-      .setSeverity(toSeverityLevel(activeRule.getSeverity()));
-  }
-
-  private Integer toSeverityLevel(RulePriority rulePriority) {
-    return rulePriority.ordinal();
-  }
-
-  private ActiveRuleParamDto toActiveRuleParamDto(ActiveRuleParam activeRuleParam, ActiveRuleDto activeRuleDto) {
-    return new ActiveRuleParamDto()
-      .setActiveRuleId(activeRuleDto.getId())
-      .setRulesParameterId(activeRuleParam.getRuleParam().getId())
-      .setKey(activeRuleParam.getKey())
-      .setValue(activeRuleParam.getValue());
-  }
-
   private void checkPermission(UserSession userSession) {
     userSession.checkLoggedIn();
     userSession.checkGlobalPermission(GlobalPermissions.QUALITY_PROFILE_ADMIN);
index 9f7315329f45d0d3fba8b979c0599994e7fb9986..ff56f33fe67c744f0f11bd73988d57b849113e68 100644 (file)
@@ -63,4 +63,10 @@ public class QProfileResult {
     return this;
   }
 
+  public QProfileResult add(QProfileResult result) {
+    warnings.addAll(result.warnings());
+    infos.addAll(result.infos());
+    return this;
+  }
+
 }
diff --git a/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileExporterTest.java b/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileExporterTest.java
new file mode 100644 (file)
index 0000000..68f73ad
--- /dev/null
@@ -0,0 +1,175 @@
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2013 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ */
+
+package org.sonar.server.qualityprofile;
+
+import com.google.common.collect.Multimap;
+import org.apache.ibatis.session.SqlSession;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.runners.MockitoJUnitRunner;
+import org.mockito.stubbing.Answer;
+import org.sonar.api.profiles.ProfileImporter;
+import org.sonar.api.profiles.RulesProfile;
+import org.sonar.api.rules.ActiveRule;
+import org.sonar.api.rules.Rule;
+import org.sonar.api.rules.RulePriority;
+import org.sonar.api.utils.ValidationMessages;
+import org.sonar.core.qualityprofile.db.ActiveRuleDao;
+import org.sonar.core.qualityprofile.db.ActiveRuleDto;
+import org.sonar.core.qualityprofile.db.ActiveRuleParamDto;
+import org.sonar.server.exceptions.BadRequestException;
+import org.sonar.server.rule.RuleRegistry;
+
+import java.io.Reader;
+import java.util.List;
+
+import static com.google.common.collect.Lists.newArrayList;
+import static org.fest.assertions.Assertions.assertThat;
+import static org.fest.assertions.Fail.fail;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyListOf;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.*;
+
+@RunWith(MockitoJUnitRunner.class)
+public class QProfileExporterTest {
+
+  @Mock
+  SqlSession session;
+
+  @Mock
+  ActiveRuleDao activeRuleDao;
+
+  @Mock
+  RuleRegistry ruleRegistry;
+
+  List<ProfileImporter> importers = newArrayList();
+
+  Integer currentId = 1;
+
+  QProfileExporter operations;
+
+  @Before
+  public void setUp() throws Exception {
+    // Associate an id when inserting an object to simulate the db id generator
+    doAnswer(new Answer() {
+      public Object answer(InvocationOnMock invocation) {
+        Object[] args = invocation.getArguments();
+        ActiveRuleDto dto = (ActiveRuleDto) args[0];
+        dto.setId(currentId++);
+        return null;
+      }
+    }).when(activeRuleDao).insert(any(ActiveRuleDto.class), any(SqlSession.class));
+
+    operations = new QProfileExporter(activeRuleDao, importers, ruleRegistry);
+  }
+
+  @Test
+  public void import_from_xml_plugin() throws Exception {
+    RulesProfile profile = RulesProfile.create("Default", "java");
+    Rule rule = Rule.create("pmd", "rule1");
+    rule.createParameter("max");
+    rule.setId(10);
+    ActiveRule activeRule = profile.activateRule(rule, RulePriority.BLOCKER);
+    activeRule.setParameter("max", "10");
+
+    ProfileImporter importer = mock(ProfileImporter.class);
+    when(importer.getKey()).thenReturn("pmd");
+    when(importer.importProfile(any(Reader.class), any(ValidationMessages.class))).thenReturn(profile);
+    importers.add(importer);
+
+    operations.importXml(new QProfile().setId(1), "pmd", "<xml/>", session);
+
+    ArgumentCaptor<ActiveRuleDto> activeRuleArgument = ArgumentCaptor.forClass(ActiveRuleDto.class);
+    verify(activeRuleDao).insert(activeRuleArgument.capture(), eq(session));
+    assertThat(activeRuleArgument.getValue().getRulId()).isEqualTo(10);
+    assertThat(activeRuleArgument.getValue().getSeverity()).isEqualTo(4);
+
+    ArgumentCaptor<ActiveRuleParamDto> activeRuleParamArgument = ArgumentCaptor.forClass(ActiveRuleParamDto.class);
+    verify(activeRuleDao).insert(activeRuleParamArgument.capture(), eq(session));
+    assertThat(activeRuleParamArgument.getValue().getKey()).isEqualTo("max");
+    assertThat(activeRuleParamArgument.getValue().getValue()).isEqualTo("10");
+
+    verify(ruleRegistry).bulkIndexActiveRules(anyListOf(ActiveRuleDto.class), any(Multimap.class));
+  }
+
+  @Test
+  public void import_from_xml_plugin_add_infos_and_warnings() throws Exception {
+    final RulesProfile profile = RulesProfile.create("Default", "java");
+    Rule rule = Rule.create("pmd", "rule1");
+    rule.createParameter("max");
+    rule.setId(10);
+    ActiveRule activeRule = profile.activateRule(rule, RulePriority.BLOCKER);
+    activeRule.setParameter("max", "10");
+
+    ProfileImporter importer = mock(ProfileImporter.class);
+    when(importer.getKey()).thenReturn("pmd");
+    doAnswer(new Answer() {
+      public Object answer(InvocationOnMock invocation) {
+        Object[] args = invocation.getArguments();
+        ValidationMessages validationMessages = (ValidationMessages) args[1];
+        validationMessages.addInfoText("an info message");
+        validationMessages.addWarningText("a warning message");
+        return profile;
+      }
+    }).when(importer).importProfile(any(Reader.class), any(ValidationMessages.class));
+    importers.add(importer);
+
+    QProfileResult result = operations.importXml(new QProfile().setId(1), "pmd", "<xml/>", session);;
+    assertThat(result.infos()).hasSize(1);
+    assertThat(result.warnings()).hasSize(1);
+  }
+
+  @Test
+  public void fail_to_import_profile_from_xml_plugin_if_error() throws Exception {
+    try {
+      final RulesProfile profile = RulesProfile.create("Default", "java");
+      Rule rule = Rule.create("pmd", "rule1");
+      rule.createParameter("max");
+      rule.setId(10);
+      ActiveRule activeRule = profile.activateRule(rule, RulePriority.BLOCKER);
+      activeRule.setParameter("max", "10");
+
+      ProfileImporter importer = mock(ProfileImporter.class);
+      when(importer.getKey()).thenReturn("pmd");
+      importers.add(importer);
+
+      doAnswer(new Answer() {
+        public Object answer(InvocationOnMock invocation) {
+          Object[] args = invocation.getArguments();
+          ValidationMessages validationMessages = (ValidationMessages) args[1];
+          validationMessages.addErrorText("error!");
+          return profile;
+        }
+      }).when(importer).importProfile(any(Reader.class), any(ValidationMessages.class));
+
+      operations.importXml(new QProfile().setId(1), "pmd", "<xml/>", session);
+      fail();
+    } catch (Exception e) {
+      assertThat(e).isInstanceOf(BadRequestException.class);
+    }
+  }
+
+}
index 537e8eddb66574e8977a2b84ea925fd8ad3ff068..ab92a8c4c6f01f32ee105b584df7d57d1355efb2 100644 (file)
@@ -21,7 +21,6 @@
 package org.sonar.server.qualityprofile;
 
 import com.google.common.collect.Maps;
-import com.google.common.collect.Multimap;
 import org.apache.ibatis.session.SqlSession;
 import org.junit.Before;
 import org.junit.Test;
@@ -31,18 +30,15 @@ import org.mockito.Mock;
 import org.mockito.invocation.InvocationOnMock;
 import org.mockito.runners.MockitoJUnitRunner;
 import org.mockito.stubbing.Answer;
-import org.sonar.api.profiles.ProfileImporter;
-import org.sonar.api.profiles.RulesProfile;
-import org.sonar.api.rules.ActiveRule;
-import org.sonar.api.rules.Rule;
-import org.sonar.api.rules.RulePriority;
-import org.sonar.api.utils.ValidationMessages;
 import org.sonar.core.permission.GlobalPermissions;
 import org.sonar.core.persistence.MyBatis;
 import org.sonar.core.preview.PreviewCache;
 import org.sonar.core.properties.PropertiesDao;
 import org.sonar.core.properties.PropertyDto;
-import org.sonar.core.qualityprofile.db.*;
+import org.sonar.core.qualityprofile.db.ActiveRuleDao;
+import org.sonar.core.qualityprofile.db.ActiveRuleDto;
+import org.sonar.core.qualityprofile.db.QualityProfileDao;
+import org.sonar.core.qualityprofile.db.QualityProfileDto;
 import org.sonar.server.configuration.ProfilesManager;
 import org.sonar.server.exceptions.BadRequestException;
 import org.sonar.server.exceptions.ForbiddenException;
@@ -51,12 +47,6 @@ import org.sonar.server.rule.RuleRegistry;
 import org.sonar.server.user.MockUserSession;
 import org.sonar.server.user.UserSession;
 
-import java.io.Reader;
-import java.util.List;
-import java.util.Map;
-
-import static com.google.common.collect.Lists.newArrayList;
-import static com.google.common.collect.Maps.newHashMap;
 import static org.fest.assertions.Assertions.assertThat;
 import static org.fest.assertions.Fail.fail;
 import static org.mockito.Matchers.any;
@@ -96,7 +86,8 @@ public class QProfileOperationsTest {
   @Mock
   ProfilesManager profilesManager;
 
-  List<ProfileImporter> importers = newArrayList();
+  @Mock
+  QProfileExporter exporter;
 
   Integer currentId = 1;
 
@@ -127,7 +118,7 @@ public class QProfileOperationsTest {
       }
     }).when(qualityProfileDao).insert(any(QualityProfileDto.class), any(SqlSession.class));
 
-    operations = new QProfileOperations(myBatis, qualityProfileDao, activeRuleDao, propertiesDao, importers, dryRunCache, ruleRegistry, profileLookup, profilesManager);
+    operations = new QProfileOperations(myBatis, qualityProfileDao, activeRuleDao, propertiesDao, exporter, dryRunCache, ruleRegistry, profileLookup, profilesManager);
   }
 
   @Test
@@ -171,98 +162,6 @@ public class QProfileOperationsTest {
     }
   }
 
-  @Test
-  public void create_profile_from_xml_plugin() throws Exception {
-    RulesProfile profile = RulesProfile.create("Default", "java");
-    Rule rule = Rule.create("pmd", "rule1");
-    rule.createParameter("max");
-    rule.setId(10);
-    ActiveRule activeRule = profile.activateRule(rule, RulePriority.BLOCKER);
-    activeRule.setParameter("max", "10");
-
-    Map<String, String> xmlProfilesByPlugin = newHashMap();
-    xmlProfilesByPlugin.put("pmd", "<xml/>");
-    ProfileImporter importer = mock(ProfileImporter.class);
-    when(importer.getKey()).thenReturn("pmd");
-    when(importer.importProfile(any(Reader.class), any(ValidationMessages.class))).thenReturn(profile);
-    importers.add(importer);
-
-    operations.newProfile("Default", "java", xmlProfilesByPlugin, authorizedUserSession);
-    verify(session).commit();
-
-    ArgumentCaptor<QualityProfileDto> profileArgument = ArgumentCaptor.forClass(QualityProfileDto.class);
-    verify(qualityProfileDao).insert(profileArgument.capture(), eq(session));
-    assertThat(profileArgument.getValue().getName()).isEqualTo("Default");
-    assertThat(profileArgument.getValue().getLanguage()).isEqualTo("java");
-
-    ArgumentCaptor<ActiveRuleDto> activeRuleArgument = ArgumentCaptor.forClass(ActiveRuleDto.class);
-    verify(activeRuleDao).insert(activeRuleArgument.capture(), eq(session));
-    assertThat(activeRuleArgument.getValue().getRulId()).isEqualTo(10);
-    assertThat(activeRuleArgument.getValue().getSeverity()).isEqualTo(4);
-
-    ArgumentCaptor<ActiveRuleParamDto> activeRuleParamArgument = ArgumentCaptor.forClass(ActiveRuleParamDto.class);
-    verify(activeRuleDao).insert(activeRuleParamArgument.capture(), eq(session));
-    assertThat(activeRuleParamArgument.getValue().getKey()).isEqualTo("max");
-    assertThat(activeRuleParamArgument.getValue().getValue()).isEqualTo("10");
-
-    verify(ruleRegistry).bulkIndexActiveRules(anyListOf(ActiveRuleDto.class), any(Multimap.class));
-  }
-
-  @Test
-  public void create_profile_from_xml_plugin_add_infos_and_warnings() throws Exception {
-    final RulesProfile profile = RulesProfile.create("Default", "java");
-    Rule rule = Rule.create("pmd", "rule1");
-    rule.createParameter("max");
-    rule.setId(10);
-    ActiveRule activeRule = profile.activateRule(rule, RulePriority.BLOCKER);
-    activeRule.setParameter("max", "10");
-
-    Map<String, String> xmlProfilesByPlugin = newHashMap();
-    xmlProfilesByPlugin.put("pmd", "<xml/>");
-    ProfileImporter importer = mock(ProfileImporter.class);
-    when(importer.getKey()).thenReturn("pmd");
-    doAnswer(new Answer() {
-      public Object answer(InvocationOnMock invocation) {
-        Object[] args = invocation.getArguments();
-        ValidationMessages validationMessages = (ValidationMessages) args[1];
-        validationMessages.addInfoText("an info message");
-        validationMessages.addWarningText("a warning message");
-        return profile;
-      }
-    }).when(importer).importProfile(any(Reader.class), any(ValidationMessages.class));
-    importers.add(importer);
-
-    QProfileResult result = operations.newProfile("Default", "java", xmlProfilesByPlugin, authorizedUserSession);
-    assertThat(result.infos()).hasSize(1);
-    assertThat(result.warnings()).hasSize(1);
-  }
-
-  @Test
-  public void fail_to_create_profile_from_xml_plugin_if_error() throws Exception {
-    try {
-      Map<String, String> xmlProfilesByPlugin = newHashMap();
-      xmlProfilesByPlugin.put("pmd", "<xml/>");
-      ProfileImporter importer = mock(ProfileImporter.class);
-      when(importer.getKey()).thenReturn("pmd");
-      importers.add(importer);
-
-      doAnswer(new Answer() {
-        public Object answer(InvocationOnMock invocation) {
-          Object[] args = invocation.getArguments();
-          ValidationMessages validationMessages = (ValidationMessages) args[1];
-          validationMessages.addErrorText("error!");
-          return null;
-        }
-      }).when(importer).importProfile(any(Reader.class), any(ValidationMessages.class));
-
-      operations.newProfile("Default", "java", xmlProfilesByPlugin, authorizedUserSession);
-      fail();
-    } catch (Exception e) {
-      assertThat(e).isInstanceOf(BadRequestException.class);
-    }
-    verify(session, never()).commit();
-  }
-
   @Test
   public void rename_profile() throws Exception {
     when(qualityProfileDao.selectById(1, session)).thenReturn(new QualityProfileDto().setId(1).setName("Default").setLanguage("java"));