return id;
}
- public RulesProfile setId(Integer id) {
- this.id = id;
- return this;
- }
-
/**
* @return the profile name, unique by language.
*/
/**
* @since 2.3
*/
-public final class XMLProfileSerializer implements ServerComponent {
+public class XMLProfileSerializer implements ServerComponent {
public void write(RulesProfile profile, Writer writer) {
try {
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);
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;
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;
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);
+++ /dev/null
-/*
- * 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);
- }
-
-}
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;
--- /dev/null
+/*
+ * 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);
+ }
+
+}
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;
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;
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);
}
# 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
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]
# 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
<%= 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>
<%= 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>
<%= 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 %>
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;
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;
@Mock
XMLProfileParser xmlProfileParser;
+ @Mock
+ XMLProfileSerializer xmlProfileSerializer;;
+
@Mock
QProfileLookup qProfileLookup;
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
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));
+++ /dev/null
-/*
- * 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");
- }
-
-}
ProfilesManager profilesManager;
@Mock
- QProfileExporter exporter;
+ QProfilePluginExporter exporter;
Integer currentId = 1;
--- /dev/null
+/*
+ * 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");
+ }
+
+}
QProfileBackup backup;
@Mock
- QProfileExporter exporter;
+ QProfilePluginExporter exporter;
@Mock
ProfileRules rules;
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);