]> source.dussan.org Git - sonarqube.git/commitdiff
SONAR-4923 Export profile for a given plugin key and backup now use Java facade
authorJulien Lancelot <julien.lancelot@sonarsource.com>
Fri, 17 Jan 2014 13:44:11 +0000 (14:44 +0100)
committerJulien Lancelot <julien.lancelot@sonarsource.com>
Fri, 17 Jan 2014 13:44:11 +0000 (14:44 +0100)
15 files changed:
sonar-plugin-api/src/main/java/org/sonar/api/profiles/RulesProfile.java
sonar-plugin-api/src/main/java/org/sonar/api/profiles/XMLProfileSerializer.java
sonar-server/src/main/java/org/sonar/server/platform/Platform.java
sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileBackup.java
sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileExporter.java [deleted file]
sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfileOperations.java
sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfilePluginExporter.java [new file with mode: 0644]
sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfiles.java
sonar-server/src/main/webapp/WEB-INF/app/controllers/profiles_controller.rb
sonar-server/src/main/webapp/WEB-INF/app/views/profiles/permalinks.html.erb
sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileBackupTest.java
sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileExporterTest.java [deleted file]
sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileOperationsTest.java
sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfilePluginExporterTest.java [new file with mode: 0644]
sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfilesTest.java

index 9bcc59f6f1676cad83f659646577dc5e84ed68c5..b7e23152096032b8cb875e860e7013c1c68026dc 100644 (file)
@@ -116,11 +116,6 @@ public class RulesProfile implements Cloneable {
     return id;
   }
 
-  public RulesProfile setId(Integer id) {
-    this.id = id;
-    return this;
-  }
-
   /**
    * @return the profile name, unique by language.
    */
index fad79c3d9e31c9cd89d628eecd20e11f30b317d2..c078881c3bd48788eb4ff9ee4b964a354eefdf79 100644 (file)
@@ -32,7 +32,7 @@ import java.io.Writer;
 /**
  * @since 2.3
  */
-public final class XMLProfileSerializer implements ServerComponent {
+public class XMLProfileSerializer implements ServerComponent {
 
   public void write(RulesProfile profile, Writer writer) {
     try {
index b0f29bf52a2c5b97bf4e560254ee639a998fc0db..968182638266a978e06d4dc1cc09d77f7a545e7e 100644 (file)
@@ -279,7 +279,7 @@ public final class Platform {
     servicesContainer.addSingleton(QProfileProjectOperations.class);
     servicesContainer.addSingleton(QProfileProjectLookup.class);
     servicesContainer.addSingleton(QProfileBackup.class);
-    servicesContainer.addSingleton(QProfileExporter.class);
+    servicesContainer.addSingleton(QProfilePluginExporter.class);
 
     // users
     servicesContainer.addSingleton(HibernateUserFinder.class);
index c82b38889c5c905e11be68fb6be4f88fc9b49656..cc6a07f79b8e06006468cc94620252caa24e578e 100644 (file)
@@ -25,6 +25,7 @@ import org.sonar.api.ServerComponent;
 import org.sonar.api.database.DatabaseSession;
 import org.sonar.api.profiles.RulesProfile;
 import org.sonar.api.profiles.XMLProfileParser;
+import org.sonar.api.profiles.XMLProfileSerializer;
 import org.sonar.api.utils.ValidationMessages;
 import org.sonar.core.permission.GlobalPermissions;
 import org.sonar.core.persistence.MyBatis;
@@ -35,6 +36,8 @@ import org.sonar.server.rule.RuleRegistry;
 import org.sonar.server.user.UserSession;
 
 import java.io.StringReader;
+import java.io.StringWriter;
+import java.io.Writer;
 import java.util.List;
 
 import static com.google.common.collect.Lists.newArrayList;
@@ -43,26 +46,36 @@ public class QProfileBackup implements ServerComponent {
 
   private final DatabaseSessionFactory sessionFactory;
   private final XMLProfileParser xmlProfileParser;
+  private final XMLProfileSerializer xmlProfileSerializer;
 
   private final MyBatis myBatis;
   private final QProfileLookup qProfileLookup;
   private final RuleRegistry ruleRegistry;
   private final PreviewCache dryRunCache;
 
-  public QProfileBackup(DatabaseSessionFactory sessionFactory, XMLProfileParser xmlProfileParser, MyBatis myBatis,
+  public QProfileBackup(DatabaseSessionFactory sessionFactory, XMLProfileParser xmlProfileParser, XMLProfileSerializer xmlProfileSerializer, MyBatis myBatis,
                         QProfileLookup qProfileLookup, RuleRegistry ruleRegistry, PreviewCache dryRunCache) {
 
     this.sessionFactory = sessionFactory;
     this.xmlProfileParser = xmlProfileParser;
+    this.xmlProfileSerializer = xmlProfileSerializer;
     this.myBatis = myBatis;
     this.qProfileLookup = qProfileLookup;
     this.ruleRegistry = ruleRegistry;
     this.dryRunCache = dryRunCache;
   }
 
+  public String backupProfile(QProfile profile) {
+    DatabaseSession session = sessionFactory.getSession();
+    RulesProfile rulesProfile = session.getSingleResult(RulesProfile.class, "id", profile.id());
+    Writer writer = new StringWriter();
+    xmlProfileSerializer.write(rulesProfile, writer);
+    return writer.toString();
+  }
+
   /**
-   * deleteExisting is used to not fail if profile exist but to delete it first.
-   * It's only used by WS, and it should should be soon removed
+   * @param deleteExisting is used to not fail if profile exist but to delete it first.
+   *                       It's only used by WS, and it should should be soon removed
    */
   public QProfileResult restore(String xmlBackup, boolean deleteExisting, UserSession userSession) {
     checkPermission(userSession);
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
deleted file mode 100644 (file)
index 393d353..0000000
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- * 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.database.DatabaseSession;
-import org.sonar.api.profiles.ProfileExporter;
-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.jpa.session.DatabaseSessionFactory;
-import org.sonar.server.exceptions.BadRequestException;
-import org.sonar.server.exceptions.NotFoundException;
-import org.sonar.server.rule.RuleRegistry;
-
-import java.io.StringReader;
-import java.io.StringWriter;
-import java.io.Writer;
-import java.util.List;
-
-import static com.google.common.collect.Lists.newArrayList;
-
-public class QProfileExporter implements ServerComponent {
-
-  private final DatabaseSessionFactory sessionFactory;
-  private final ActiveRuleDao activeRuleDao;
-  private final RuleRegistry ruleRegistry;
-  private final List<ProfileExporter> exporters;
-  private final List<ProfileImporter> importers;
-
-  /**
-   * Used by pico when no plugin provide profile exporter / importer
-   */
-  public QProfileExporter(DatabaseSessionFactory sessionFactory, ActiveRuleDao activeRuleDao, RuleRegistry ruleRegistry) {
-    this(sessionFactory, activeRuleDao, ruleRegistry, Lists.<ProfileImporter>newArrayList(), Lists.<ProfileExporter>newArrayList());
-  }
-
-  public QProfileExporter(DatabaseSessionFactory sessionFactory, ActiveRuleDao activeRuleDao, RuleRegistry ruleRegistry,
-                          List<ProfileImporter> importers, List<ProfileExporter> exporters) {
-    this.sessionFactory = sessionFactory;
-    this.activeRuleDao = activeRuleDao;
-    this.ruleRegistry = ruleRegistry;
-    this.importers = importers;
-    this.exporters = exporters;
-  }
-
-  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;
-  }
-
-  public String exportToXml(QProfile profile, String pluginKey) {
-    DatabaseSession session = sessionFactory.getSession();
-    RulesProfile rulesProfile = session.getSingleResult(RulesProfile.class, "id", profile.id());
-    if (profile == null) {
-      throw new NotFoundException("This profile does not exists.");
-    }
-    ProfileExporter exporter = getProfileExporter(pluginKey);
-    Writer writer = new StringWriter();
-    exporter.exportProfile(rulesProfile, writer);
-    return writer.toString();
-  }
-
-  public String getProfileExporterMimeType(String pluginKey) {
-    return getProfileExporter(pluginKey).getMimeType();
-  }
-
-  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);
-  }
-
-  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());
-  }
-
-  private ProfileImporter getProfileImporter(String importerKey) {
-    for (ProfileImporter importer : importers) {
-      if (StringUtils.equals(importerKey, importer.getKey())) {
-        return importer;
-      }
-    }
-    throw BadRequestException.of("No such importer : " + importerKey);
-  }
-
-  private ProfileExporter getProfileExporter(String exporterKey) {
-    for (ProfileExporter exporter : exporters) {
-      if (StringUtils.equals(exporterKey, exporter.getKey())) {
-        return exporter;
-      }
-    }
-    throw BadRequestException.of("No such exporter : " + exporterKey);
-  }
-
-}
index bbe52de7f6bf318f6a201b19f70f6b564b3e6db9..b1298afc259e5334baa1f42ebfd9c6c744cd01fd 100644 (file)
@@ -50,14 +50,14 @@ public class QProfileOperations implements ServerComponent {
   private final QualityProfileDao dao;
   private final ActiveRuleDao activeRuleDao;
   private final PropertiesDao propertiesDao;
-  private final QProfileExporter exporter;
+  private final QProfilePluginExporter exporter;
   private final PreviewCache dryRunCache;
   private final RuleRegistry ruleRegistry;
   private final QProfileLookup profileLookup;
   private final ProfilesManager profilesManager;
 
   public QProfileOperations(MyBatis myBatis, QualityProfileDao dao, ActiveRuleDao activeRuleDao, PropertiesDao propertiesDao,
-                            QProfileExporter exporter, PreviewCache dryRunCache, RuleRegistry ruleRegistry, QProfileLookup profileLookup, ProfilesManager profilesManager) {
+                            QProfilePluginExporter exporter, PreviewCache dryRunCache, RuleRegistry ruleRegistry, QProfileLookup profileLookup, ProfilesManager profilesManager) {
     this.myBatis = myBatis;
     this.dao = dao;
     this.activeRuleDao = activeRuleDao;
diff --git a/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfilePluginExporter.java b/sonar-server/src/main/java/org/sonar/server/qualityprofile/QProfilePluginExporter.java
new file mode 100644 (file)
index 0000000..c468497
--- /dev/null
@@ -0,0 +1,167 @@
+/*
+ * 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.database.DatabaseSession;
+import org.sonar.api.profiles.ProfileExporter;
+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.jpa.session.DatabaseSessionFactory;
+import org.sonar.server.exceptions.BadRequestException;
+import org.sonar.server.exceptions.NotFoundException;
+import org.sonar.server.rule.RuleRegistry;
+
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.io.Writer;
+import java.util.List;
+
+import static com.google.common.collect.Lists.newArrayList;
+
+public class QProfilePluginExporter implements ServerComponent {
+
+  private final DatabaseSessionFactory sessionFactory;
+  private final ActiveRuleDao activeRuleDao;
+  private final RuleRegistry ruleRegistry;
+  private final List<ProfileExporter> exporters;
+  private final List<ProfileImporter> importers;
+
+  /**
+   * Used by pico when no plugin provide profile exporter / importer
+   */
+  public QProfilePluginExporter(DatabaseSessionFactory sessionFactory, ActiveRuleDao activeRuleDao, RuleRegistry ruleRegistry) {
+    this(sessionFactory, activeRuleDao, ruleRegistry, Lists.<ProfileImporter>newArrayList(), Lists.<ProfileExporter>newArrayList());
+  }
+
+  public QProfilePluginExporter(DatabaseSessionFactory sessionFactory, ActiveRuleDao activeRuleDao, RuleRegistry ruleRegistry,
+                                List<ProfileImporter> importers, List<ProfileExporter> exporters) {
+    this.sessionFactory = sessionFactory;
+    this.activeRuleDao = activeRuleDao;
+    this.ruleRegistry = ruleRegistry;
+    this.importers = importers;
+    this.exporters = exporters;
+  }
+
+  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;
+  }
+
+  public String exportToXml(QProfile profile, String pluginKey) {
+    DatabaseSession session = sessionFactory.getSession();
+    RulesProfile rulesProfile = session.getSingleResult(RulesProfile.class, "id", profile.id());
+    if (profile == null) {
+      throw new NotFoundException("This profile does not exists.");
+    }
+    ProfileExporter exporter = getProfileExporter(pluginKey);
+    Writer writer = new StringWriter();
+    exporter.exportProfile(rulesProfile, writer);
+    return writer.toString();
+  }
+
+  public String getProfileExporterMimeType(String pluginKey) {
+    return getProfileExporter(pluginKey).getMimeType();
+  }
+
+  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);
+  }
+
+  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());
+  }
+
+  private ProfileImporter getProfileImporter(String importerKey) {
+    for (ProfileImporter importer : importers) {
+      if (StringUtils.equals(importerKey, importer.getKey())) {
+        return importer;
+      }
+    }
+    throw BadRequestException.of("No such importer : " + importerKey);
+  }
+
+  private ProfileExporter getProfileExporter(String exporterKey) {
+    for (ProfileExporter exporter : exporters) {
+      if (StringUtils.equals(exporterKey, exporter.getKey())) {
+        return exporter;
+      }
+    }
+    throw BadRequestException.of("No such exporter : " + exporterKey);
+  }
+
+}
index 90fd5184618d3470e55e5a6be3a99805302a91b0..ae36c7a5ec40cf5e862fd3a1813f9f666dc3be0a 100644 (file)
@@ -61,7 +61,7 @@ public class QProfiles implements ServerComponent {
   private final QProfileProjectOperations projectOperations;
   private final QProfileProjectLookup projectLookup;
   private final QProfileBackup backup;
-  private final QProfileExporter exporter;
+  private final QProfilePluginExporter exporter;
   private final QProfileLookup profileLookup;
   private final QProfileOperations operations;
   private final QProfileActiveRuleOperations activeRuleOperations;
@@ -69,7 +69,7 @@ public class QProfiles implements ServerComponent {
   private final ProfileRules rules;
 
   public QProfiles(QualityProfileDao qualityProfileDao, ActiveRuleDao activeRuleDao, RuleDao ruleDao, ResourceDao resourceDao,
-                   QProfileProjectOperations projectOperations, QProfileProjectLookup projectLookup, QProfileBackup backup, QProfileExporter exporter, QProfileLookup profileLookup,
+                   QProfileProjectOperations projectOperations, QProfileProjectLookup projectLookup, QProfileBackup backup, QProfilePluginExporter exporter, QProfileLookup profileLookup,
                    QProfileOperations operations, QProfileActiveRuleOperations activeRuleOperations, QProfileRuleOperations ruleOperations, ProfileRules rules) {
     this.qualityProfileDao = qualityProfileDao;
     this.activeRuleDao = activeRuleDao;
@@ -151,6 +151,10 @@ public class QProfiles implements ServerComponent {
     return backup.restore(xmlBackup, deleteExisting, UserSession.get());
   }
 
+  public String backupProfile(QProfile profile) {
+    return backup.backupProfile(profile);
+  }
+
   public boolean isDeletable(QProfile profile) {
     return profileLookup.isDeletable(profile);
   }
index c5d6f369c1a6c43cc9ad9f701da793a9462eacdc..645b76f16bf28613bfb8b5857e02bedeb1c167ce 100644 (file)
@@ -120,15 +120,15 @@ class ProfilesController < ApplicationController
 
   # the backup action is allow to non-admin users : see http://jira.codehaus.org/browse/SONAR-2039
   # POST /profiles/backup?id=<profile id>
-  # TODO use QProfiles facade instead
   def backup
     verify_post_request
     require_parameters 'id'
 
-    profile = Profile.find(params[:id])
-    xml = java_facade.backupProfile(profile.id)
-    filename=profile.name.gsub(' ', '_')
-    send_data(xml, :type => 'text/xml', :disposition => "attachment; filename=#{filename}_#{profile.language}.xml")
+    profile = Internal.quality_profiles.profile(params[:id].to_i)
+    not_found('Profile not found') unless profile
+    xml = Internal.quality_profiles.backupProfile(profile)
+    filename = profile.name().gsub(' ', '_')
+    send_data(xml, :type => 'text/xml', :disposition => "attachment; filename=#{filename}_#{profile.language()}.xml")
   end
 
 
@@ -165,8 +165,7 @@ class ProfilesController < ApplicationController
 
     if (params[:format].blank?)
       # standard sonar format
-      # TODO
-      result = java_facade.backupProfile(profile.id)
+      result = Internal.quality_profiles.backupProfile(profile)
       send_data(result, :type => 'text/xml', :disposition => 'inline')
     else
       exporter_key = params[:format]
@@ -255,10 +254,10 @@ class ProfilesController < ApplicationController
   # GET /profiles/permalinks?id=<profile id>
   #
   #
-  # TODO use QProfiles facade instead
   def permalinks
     require_parameters 'id'
-    @profile = Profile.find(params[:id])
+    @profile = Internal.quality_profiles.profile(params[:id].to_i)
+    not_found('Profile not found') unless @profile
     set_profile_breadcrumbs
   end
 
index 760b2a0dd41c158aeae226d2b5b5628d14a76062..dc677c5188500d73f86d65ef3a2527dd39e8938a 100644 (file)
@@ -2,7 +2,7 @@
 <%= render :partial => 'profiles/tabs', :locals => {:selected_tab=>'Permalinks'} %>
 
 <div class="tabs-panel marginbottom10 ">
-       <% exporters=controller.java_facade.getProfileExportersForLanguage(@profile.language) %>
+       <% exporters = controller.java_facade.getProfileExportersForLanguage(@profile.language()) %>
        <br/>
        <table class="data without-header marginbottom10" id="permalinks-table">
          <tbody>
@@ -11,7 +11,7 @@
              <%= message('quality_profiles.export_all_rules') -%>
            </td>
            <td>
-             <% permalink = url_for :controller => 'profiles', :action => 'export', :language => @profile.language, :name => url_encode(@profile.name), :only_path => false %>
+             <% permalink = url_for :controller => 'profiles', :action => 'export', :language => @profile.language(), :name => url_encode(@profile.name()), :only_path => false %>
              <span class="small"><%= link_to permalink, permalink %></span>
            </td>
          </tr>
@@ -21,8 +21,8 @@
                <%= h exporter.getName() -%>
              </td>
              <td>
-               <% permalink=url_for :controller => 'profiles', :action => 'export', :language => @profile.language, :name => url_encode(@profile.name), :format => exporter.getKey(), :only_path => false %>
-               <span class="small"><%= link_to permalink, permalink, :id => "export_" + exporter.getKey().to_s + "_" + u(@profile.key) %></span>
+               <% permalink=url_for :controller => 'profiles', :action => 'export', :language => @profile.language(), :name => url_encode(@profile.name()), :format => exporter.getKey(), :only_path => false %>
+               <span class="small"><%= link_to permalink, permalink, :id => "export_" + exporter.getKey().to_s + "_" + profile_key(@profile) %></span>
              </td>
            </tr>
          <% end %>
index f565daaa11ebbd320ff5d084a431dcd8e6aa37cd..a137920d6647e9a97680458e27199dfe981ff53c 100644 (file)
@@ -31,6 +31,7 @@ import org.mockito.stubbing.Answer;
 import org.sonar.api.database.DatabaseSession;
 import org.sonar.api.profiles.RulesProfile;
 import org.sonar.api.profiles.XMLProfileParser;
+import org.sonar.api.profiles.XMLProfileSerializer;
 import org.sonar.api.utils.ValidationMessages;
 import org.sonar.core.permission.GlobalPermissions;
 import org.sonar.core.persistence.MyBatis;
@@ -43,6 +44,7 @@ import org.sonar.server.user.MockUserSession;
 import org.sonar.server.user.UserSession;
 
 import java.io.Reader;
+import java.io.Writer;
 
 import static org.fest.assertions.Assertions.assertThat;
 import static org.fest.assertions.Fail.fail;
@@ -69,6 +71,9 @@ public class QProfileBackupTest {
   @Mock
   XMLProfileParser xmlProfileParser;
 
+  @Mock
+  XMLProfileSerializer xmlProfileSerializer;;
+
   @Mock
   QProfileLookup qProfileLookup;
 
@@ -87,7 +92,18 @@ public class QProfileBackupTest {
     when(myBatis.openSession()).thenReturn(session);
     when(sessionFactory.getSession()).thenReturn(hibernateSession);
 
-    backup = new QProfileBackup(sessionFactory, xmlProfileParser, myBatis, qProfileLookup, ruleRegistry, dryRunCache);
+    backup = new QProfileBackup(sessionFactory, xmlProfileParser, xmlProfileSerializer, myBatis, qProfileLookup, ruleRegistry, dryRunCache);
+  }
+
+  @Test
+  public void backup() throws Exception {
+    RulesProfile profile = mock(RulesProfile.class);
+    when(profile.getId()).thenReturn(1);
+    when(hibernateSession.getSingleResult(any(Class.class), eq("id"), eq(1))).thenReturn(profile);
+
+    backup.backupProfile(new QProfile().setId(1));
+
+    verify(xmlProfileSerializer).write(eq(profile), any(Writer.class));
   }
 
   @Test
@@ -151,7 +167,8 @@ public class QProfileBackupTest {
     when(profile.getId()).thenReturn(1);
     when(xmlProfileParser.parse(any(Reader.class), any(ValidationMessages.class))).thenReturn(profile);
 
-    RulesProfile existingProfile = RulesProfile.create("Default", "java").setId(1);
+    RulesProfile existingProfile = mock(RulesProfile.class);
+    when(existingProfile.getId()).thenReturn(1);
     when(hibernateSession.getSingleResult(any(Class.class), eq("name"), eq("Default"), eq("language"), eq("java"))).thenReturn(existingProfile);
     when(qProfileLookup.profile(anyInt(), eq(session))).thenReturn(new QProfile().setId(1));
 
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
deleted file mode 100644 (file)
index 2fe7505..0000000
+++ /dev/null
@@ -1,267 +0,0 @@
-/*
- * 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.database.DatabaseSession;
-import org.sonar.api.profiles.ProfileExporter;
-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.jpa.session.DatabaseSessionFactory;
-import org.sonar.server.exceptions.BadRequestException;
-import org.sonar.server.rule.RuleRegistry;
-
-import java.io.Reader;
-import java.io.Writer;
-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
-  DatabaseSessionFactory sessionFactory;
-
-  @Mock
-  DatabaseSession hibernateSession;
-
-  @Mock
-  ActiveRuleDao activeRuleDao;
-
-  @Mock
-  RuleRegistry ruleRegistry;
-
-  List<ProfileImporter> importers = newArrayList();
-  List<ProfileExporter> exporters = newArrayList();
-
-  Integer currentId = 1;
-
-  QProfileExporter operations;
-
-  @Before
-  public void setUp() throws Exception {
-    when(sessionFactory.getSession()).thenReturn(hibernateSession);
-
-    // 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(sessionFactory, activeRuleDao, ruleRegistry, importers, exporters);
-  }
-
-  @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);
-
-    verify(importer).importProfile(any(Reader.class), any(ValidationMessages.class));
-
-    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 {
-    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));
-
-    try {
-      operations.importXml(new QProfile().setId(1), "pmd", "<xml/>", session);
-      fail();
-    } catch (Exception e) {
-      assertThat(e).isInstanceOf(BadRequestException.class);
-    }
-  }
-
-  @Test
-  public void fail_to_import_profile_when_missing_importer() 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");
-    importers.add(importer);
-
-    when(importer.importProfile(any(Reader.class), any(ValidationMessages.class))).thenReturn(profile);
-
-    try {
-      operations.importXml(new QProfile().setId(1), "unknown", "<xml/>", session);
-      fail();
-    } catch (Exception e) {
-      assertThat(e).isInstanceOf(BadRequestException.class).hasMessage("No such importer : unknown");
-    }
-    verify(importer, never()).importProfile(any(Reader.class), any(ValidationMessages.class));
-  }
-
-  @Test
-  public void export_to_plugin_xml() throws Exception {
-    RulesProfile profile = RulesProfile.create("Default", "java").setId(1);
-    Rule rule = Rule.create("pmd", "rule1");
-    rule.createParameter("max");
-    rule.setId(10);
-    ActiveRule activeRule = profile.activateRule(rule, RulePriority.BLOCKER);
-    activeRule.setParameter("max", "10");
-    when(hibernateSession.getSingleResult(any(Class.class), eq("id"), eq(1))).thenReturn(profile);
-
-    ProfileExporter exporter = mock(ProfileExporter.class);
-    when(exporter.getKey()).thenReturn("pmd");
-    exporters.add(exporter);
-
-    operations.exportToXml(new QProfile().setId(1), "pmd");
-
-    verify(exporter).exportProfile(eq(profile), any(Writer.class));
-  }
-
-  @Test
-  public void fail_to_export_profile_when_missing_exporter() throws Exception {
-    RulesProfile profile = RulesProfile.create("Default", "java").setId(1);
-    Rule rule = Rule.create("pmd", "rule1");
-    rule.createParameter("max");
-    rule.setId(10);
-    ActiveRule activeRule = profile.activateRule(rule, RulePriority.BLOCKER);
-    activeRule.setParameter("max", "10");
-    when(hibernateSession.getSingleResult(any(Class.class), eq("id"), eq(1))).thenReturn(profile);
-
-    ProfileExporter exporter = mock(ProfileExporter.class);
-    when(exporter.getKey()).thenReturn("pmd");
-    exporters.add(exporter);
-
-    try {
-      operations.exportToXml(new QProfile().setId(1), "unknown");
-      fail();
-    } catch (Exception e) {
-      assertThat(e).isInstanceOf(BadRequestException.class).hasMessage("No such exporter : unknown");
-    }
-
-    verify(exporter, never()).exportProfile(any(RulesProfile.class), any(Writer.class));
-  }
-
-  @Test
-  public void get_profile_exporter_mime_type() throws Exception {
-    ProfileExporter exporter = mock(ProfileExporter.class);
-    when(exporter.getKey()).thenReturn("pmd");
-    when(exporter.getMimeType()).thenReturn("mime");
-    exporters.add(exporter);
-
-    assertThat(operations.getProfileExporterMimeType("pmd")).isEqualTo("mime");
-  }
-
-}
index a4070be0b4b756db3590b900887b54ca4cdac668..80d848afd9738f703812e24725bf7c534810f578 100644 (file)
@@ -90,7 +90,7 @@ public class QProfileOperationsTest {
   ProfilesManager profilesManager;
 
   @Mock
-  QProfileExporter exporter;
+  QProfilePluginExporter exporter;
 
   Integer currentId = 1;
 
diff --git a/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfilePluginExporterTest.java b/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfilePluginExporterTest.java
new file mode 100644 (file)
index 0000000..e77a076
--- /dev/null
@@ -0,0 +1,259 @@
+/*
+ * 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.database.DatabaseSession;
+import org.sonar.api.profiles.ProfileExporter;
+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.jpa.session.DatabaseSessionFactory;
+import org.sonar.server.exceptions.BadRequestException;
+import org.sonar.server.rule.RuleRegistry;
+
+import java.io.Reader;
+import java.io.Writer;
+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 QProfilePluginExporterTest {
+
+  @Mock
+  SqlSession session;
+
+  @Mock
+  DatabaseSessionFactory sessionFactory;
+
+  @Mock
+  DatabaseSession hibernateSession;
+
+  @Mock
+  ActiveRuleDao activeRuleDao;
+
+  @Mock
+  RuleRegistry ruleRegistry;
+
+  List<ProfileImporter> importers = newArrayList();
+  List<ProfileExporter> exporters = newArrayList();
+
+  Integer currentId = 1;
+
+  QProfilePluginExporter operations;
+
+  @Before
+  public void setUp() throws Exception {
+    when(sessionFactory.getSession()).thenReturn(hibernateSession);
+
+    // 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 QProfilePluginExporter(sessionFactory, activeRuleDao, ruleRegistry, importers, exporters);
+  }
+
+  @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);
+
+    verify(importer).importProfile(any(Reader.class), any(ValidationMessages.class));
+
+    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 {
+    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));
+
+    try {
+      operations.importXml(new QProfile().setId(1), "pmd", "<xml/>", session);
+      fail();
+    } catch (Exception e) {
+      assertThat(e).isInstanceOf(BadRequestException.class);
+    }
+  }
+
+  @Test
+  public void fail_to_import_profile_when_missing_importer() 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");
+    importers.add(importer);
+
+    when(importer.importProfile(any(Reader.class), any(ValidationMessages.class))).thenReturn(profile);
+
+    try {
+      operations.importXml(new QProfile().setId(1), "unknown", "<xml/>", session);
+      fail();
+    } catch (Exception e) {
+      assertThat(e).isInstanceOf(BadRequestException.class).hasMessage("No such importer : unknown");
+    }
+    verify(importer, never()).importProfile(any(Reader.class), any(ValidationMessages.class));
+  }
+
+  @Test
+  public void export_to_plugin_xml() throws Exception {
+    RulesProfile profile = mock(RulesProfile.class);
+    when(profile.getId()).thenReturn(1);
+    when(hibernateSession.getSingleResult(any(Class.class), eq("id"), eq(1))).thenReturn(profile);
+
+    ProfileExporter exporter = mock(ProfileExporter.class);
+    when(exporter.getKey()).thenReturn("pmd");
+    exporters.add(exporter);
+
+    operations.exportToXml(new QProfile().setId(1), "pmd");
+
+    verify(exporter).exportProfile(eq(profile), any(Writer.class));
+  }
+
+  @Test
+  public void fail_to_export_profile_when_missing_exporter() throws Exception {
+    RulesProfile profile = mock(RulesProfile.class);
+    when(profile.getId()).thenReturn(1);
+    when(hibernateSession.getSingleResult(any(Class.class), eq("id"), eq(1))).thenReturn(profile);
+
+    ProfileExporter exporter = mock(ProfileExporter.class);
+    when(exporter.getKey()).thenReturn("pmd");
+    exporters.add(exporter);
+
+    try {
+      operations.exportToXml(new QProfile().setId(1), "unknown");
+      fail();
+    } catch (Exception e) {
+      assertThat(e).isInstanceOf(BadRequestException.class).hasMessage("No such exporter : unknown");
+    }
+
+    verify(exporter, never()).exportProfile(any(RulesProfile.class), any(Writer.class));
+  }
+
+  @Test
+  public void get_profile_exporter_mime_type() throws Exception {
+    ProfileExporter exporter = mock(ProfileExporter.class);
+    when(exporter.getKey()).thenReturn("pmd");
+    when(exporter.getMimeType()).thenReturn("mime");
+    exporters.add(exporter);
+
+    assertThat(operations.getProfileExporterMimeType("pmd")).isEqualTo("mime");
+  }
+
+}
index c23bdf27cf0942f95a0cfd195c8320b28ac153e5..da6f3c46cee4acdc9f1fb9d54afd81916d8578be 100644 (file)
@@ -91,7 +91,7 @@ public class QProfilesTest {
   QProfileBackup backup;
 
   @Mock
-  QProfileExporter exporter;
+  QProfilePluginExporter exporter;
 
   @Mock
   ProfileRules rules;
@@ -208,6 +208,19 @@ public class QProfilesTest {
     verify(profileOperations).deleteProfile(eq(1), any(UserSession.class));
   }
 
+  @Test
+  public void restore_profile() throws Exception {
+    qProfiles.restore("<xml/>", true);
+    verify(backup).restore(eq("<xml/>"), eq(true), any(UserSession.class));
+  }
+
+  @Test
+  public void backup_profile() throws Exception {
+    QProfile profile = new QProfile().setId(1);
+    qProfiles.backupProfile(profile);
+    verify(backup).backupProfile(profile);
+  }
+
   @Test
   public void update_default_profile() throws Exception {
     qProfiles.setDefaultProfile(1);