diff options
author | Julien Lancelot <julien.lancelot@sonarsource.com> | 2014-01-17 17:17:33 +0100 |
---|---|---|
committer | Julien Lancelot <julien.lancelot@sonarsource.com> | 2014-01-17 17:17:33 +0100 |
commit | b6e72bfa81fc4a763349b701242893ad669066c5 (patch) | |
tree | 6bf93360bd5659bf15fc43fb9f766a1b6861d076 /sonar-server | |
parent | 2b45b3195551da785dd7619c8d84fee099e67ef1 (diff) | |
download | sonarqube-b6e72bfa81fc4a763349b701242893ad669066c5.tar.gz sonarqube-b6e72bfa81fc4a763349b701242893ad669066c5.zip |
SONAR-4887 Remove backup code
Diffstat (limited to 'sonar-server')
13 files changed, 6 insertions, 1509 deletions
diff --git a/sonar-server/src/main/java/org/sonar/server/configuration/Backup.java b/sonar-server/src/main/java/org/sonar/server/configuration/Backup.java deleted file mode 100644 index d2f86058b0f..00000000000 --- a/sonar-server/src/main/java/org/sonar/server/configuration/Backup.java +++ /dev/null @@ -1,200 +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.configuration; - -import org.sonar.core.preview.PreviewCache; - -import com.thoughtworks.xstream.XStream; -import com.thoughtworks.xstream.converters.basic.DateConverter; -import com.thoughtworks.xstream.core.util.QuickWriter; -import com.thoughtworks.xstream.io.HierarchicalStreamWriter; -import com.thoughtworks.xstream.io.xml.PrettyPrintWriter; -import com.thoughtworks.xstream.io.xml.XppDriver; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang.CharEncoding; -import org.apache.commons.lang.StringUtils; -import org.slf4j.LoggerFactory; -import org.sonar.api.database.DatabaseSession; -import org.sonar.core.persistence.DatabaseVersion; -import org.sonar.server.platform.PersistentSettings; - -import javax.annotation.Nullable; - -import java.io.IOException; -import java.io.InputStream; -import java.io.Writer; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.List; - -public class Backup { - - private List<Backupable> backupables; - private DatabaseSession session; - - protected static final String DATE_FORMAT = "yyyy-MM-dd"; - - protected Backup() { - backupables = new ArrayList<Backupable>(); - } - - public Backup(DatabaseSession session, PersistentSettings persistentSettings, PreviewCache dryRunCache) { - this(); - this.session = session; - - backupables.add(new MetricsBackup(session)); - backupables.add(new PropertiesBackup(persistentSettings)); - // Note that order is important, because profile can have reference to rule - backupables.add(new RulesBackup(session)); - backupables.add(new ProfilesBackup(session, dryRunCache)); - } - - /** - * For unit tests - */ - Backup(List<Backupable> backupables) { - this(); - this.backupables = backupables; - } - - /* - * Export methods - */ - - public String exportXml() { - try { - startDb(); - SonarConfig sonarConfig = new SonarConfig(getVersion(), getCurrentDate()); - return exportXml(sonarConfig); - } finally { - stopDb(); - } - } - - protected String exportXml(SonarConfig sonarConfig) { - for (Backupable backupable : backupables) { - backupable.exportXml(sonarConfig); - } - String xml = getXmlFromSonarConfig(sonarConfig); - return addXmlHeader(xml); - } - - protected String getXmlFromSonarConfig(SonarConfig sonarConfig) { - XStream xStream = getConfiguredXstream(); - return xStream.toXML(sonarConfig); - } - - private String addXmlHeader(String xml) { - return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".concat(xml); - } - - /* - * Import methods - */ - public void importXml(String xml) { - try { - startDb(); - doImportXml(xml); - LoggerFactory.getLogger(getClass()).info("Backup restored"); - } finally { - stopDb(); - } - } - - void doImportXml(String xml) { - SonarConfig sonarConfig = getSonarConfigFromXml(xml); - importBackupablesXml(sonarConfig); - } - - protected void importBackupablesXml(SonarConfig sonarConfig) { - for (Backupable backupable : backupables) { - backupable.importXml(sonarConfig); - } - } - - protected SonarConfig getSonarConfigFromXml(String xml) { - try { - XStream xStream = getConfiguredXstream(); - // Backward compatibility with old levels - xml = xml.replace("<level><![CDATA[ERROR]]></level>", "<level><![CDATA[MAJOR]]></level>"); - xml = xml.replace("<level><![CDATA[WARNING]]></level>", "<level><![CDATA[INFO]]></level>"); - InputStream inputStream = IOUtils.toInputStream(xml, CharEncoding.UTF_8); - - return (SonarConfig) xStream.fromXML(inputStream); - } catch (IOException e) { - throw new IllegalStateException("Can't read xml", e); - } - } - - /* - * Utils methods - */ - protected int getVersion() { - return DatabaseVersion.LAST_VERSION; - } - - protected Date getCurrentDate() { - return new Date(); - } - - private XStream getConfiguredXstream() { - XStream xStream = new XStream( - new XppDriver() { - @Override - public HierarchicalStreamWriter createWriter(Writer out) { - return new PrettyPrintWriter(out) { - @Override - protected void writeText(QuickWriter writer, @Nullable String text) { - if (text != null) { - writer.write("<![CDATA["); - /* - * See http://jira.codehaus.org/browse/SONAR-1605 According to XML specification ( - * http://www.w3.org/TR/REC-xml/#sec-cdata-sect ) CData section may contain everything except of sequence ']]>' so we will - * split all occurrences of this sequence into two CDATA first one would contain ']]' and second '>' - */ - text = StringUtils.replace(text, "]]>", "]]]]><![CDATA[>"); - writer.write(text); - writer.write("]]>"); - } - } - }; - } - }); - - xStream.processAnnotations(SonarConfig.class); - xStream.addDefaultImplementation(ArrayList.class, Collection.class); - xStream.registerConverter(new DateConverter(DATE_FORMAT, new String[] {})); - - for (Backupable backupable : backupables) { - backupable.configure(xStream); - } - return xStream; - } - - private void startDb() { - session.start(); - } - - private void stopDb() { - session.stop(); - } - -} diff --git a/sonar-server/src/main/java/org/sonar/server/configuration/Backupable.java b/sonar-server/src/main/java/org/sonar/server/configuration/Backupable.java deleted file mode 100644 index 95d33117e4d..00000000000 --- a/sonar-server/src/main/java/org/sonar/server/configuration/Backupable.java +++ /dev/null @@ -1,31 +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.configuration; - -import com.thoughtworks.xstream.XStream; - -public interface Backupable { - - void exportXml(SonarConfig sonarConfig); - - void importXml(SonarConfig sonarConfig); - - void configure(XStream xStream); -} diff --git a/sonar-server/src/main/java/org/sonar/server/configuration/MetricsBackup.java b/sonar-server/src/main/java/org/sonar/server/configuration/MetricsBackup.java deleted file mode 100644 index 922915cbcb9..00000000000 --- a/sonar-server/src/main/java/org/sonar/server/configuration/MetricsBackup.java +++ /dev/null @@ -1,99 +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.configuration; - -import com.thoughtworks.xstream.XStream; -import com.thoughtworks.xstream.converters.Converter; -import com.thoughtworks.xstream.converters.MarshallingContext; -import com.thoughtworks.xstream.converters.UnmarshallingContext; -import com.thoughtworks.xstream.io.HierarchicalStreamReader; -import com.thoughtworks.xstream.io.HierarchicalStreamWriter; -import org.slf4j.LoggerFactory; -import org.sonar.api.database.DatabaseSession; -import org.sonar.api.measures.Metric; -import org.sonar.jpa.dao.MeasuresDao; - -import java.util.Collection; - -public class MetricsBackup implements Backupable { - - private MeasuresDao measuresDao; - - public MetricsBackup(DatabaseSession session) { - measuresDao = new MeasuresDao(session); - } - - protected MetricsBackup() { - } - - public void exportXml(SonarConfig sonarConfig) { - Collection<Metric> metrics = measuresDao.getUserDefinedMetrics(); - exportXml(sonarConfig, metrics); - } - - protected void exportXml(SonarConfig sonarConfig, Collection<Metric> metrics) { - sonarConfig.setMetrics(metrics); - } - - public void importXml(SonarConfig sonarConfig) { - disableUserDefinedMetrics(); - registerMetrics(sonarConfig); - } - - protected void disableUserDefinedMetrics() { - LoggerFactory.getLogger(getClass()).info("Disable user-defined metrics"); - Collection<Metric> dbMetrics = measuresDao.getUserDefinedMetrics(); - measuresDao.disabledMetrics(dbMetrics); - } - - protected void registerMetrics(SonarConfig sonarConfig) { - LoggerFactory.getLogger(getClass()).info("Restore metrics"); - Collection<Metric> newMetrics = sonarConfig.getMetrics(); - measuresDao.registerMetrics(newMetrics); - } - - public void configure(XStream xStream) { - xStream.alias("metric", Metric.class); - xStream.omitField(Metric.class, "id"); - xStream.omitField(Metric.class, "userManaged"); - xStream.omitField(Metric.class, "comparable"); - xStream.omitField(Metric.class, "enabled"); - final Converter builtIn = xStream.getConverterLookup().lookupConverterForType(Metric.class); - xStream.registerConverter(new Converter() { - public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { - builtIn.marshal(source, writer, context); - } - - public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { - Metric unmarshalled = (Metric) builtIn.unmarshal(reader, context); - // See http://jira.codehaus.org/browse/SONAR-1819 - unmarshalled.setId(null); - unmarshalled.setUserManaged(true); - unmarshalled.setEnabled(true); - return unmarshalled; - } - - public boolean canConvert(Class type) { - return Metric.class.equals(type); - } - }); - } - -} diff --git a/sonar-server/src/main/java/org/sonar/server/configuration/ProfilesBackup.java b/sonar-server/src/main/java/org/sonar/server/configuration/ProfilesBackup.java index db5c6770c4b..ffd9a248f9c 100644 --- a/sonar-server/src/main/java/org/sonar/server/configuration/ProfilesBackup.java +++ b/sonar-server/src/main/java/org/sonar/server/configuration/ProfilesBackup.java @@ -37,7 +37,7 @@ import org.sonar.jpa.dao.RulesDao; import java.util.*; -public class ProfilesBackup implements Backupable { +public class ProfilesBackup { private static final String OPERATOR = "operator"; private static final String VALUE_ERROR = "value-error"; diff --git a/sonar-server/src/main/java/org/sonar/server/configuration/PropertiesBackup.java b/sonar-server/src/main/java/org/sonar/server/configuration/PropertiesBackup.java deleted file mode 100644 index bd489b190e4..00000000000 --- a/sonar-server/src/main/java/org/sonar/server/configuration/PropertiesBackup.java +++ /dev/null @@ -1,97 +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.configuration; - -import org.sonar.core.preview.PreviewCache; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.thoughtworks.xstream.XStream; -import org.slf4j.LoggerFactory; -import org.sonar.api.CoreProperties; -import org.sonar.api.database.configuration.Property; -import org.sonar.core.properties.PropertyDto; -import org.sonar.server.platform.PersistentSettings; - -import java.util.List; -import java.util.Map; - -public class PropertiesBackup implements Backupable { - - private static final String PERMISSION_PROPERTIES_PREFIX = "sonar.permission.template"; - - private final PersistentSettings persistentSettings; - - public PropertiesBackup(PersistentSettings persistentSettings) { - this.persistentSettings = persistentSettings; - } - - public void exportXml(SonarConfig sonarConfig) { - List<Property> xmlProperties = Lists.newArrayList(); - - for (PropertyDto property : persistentSettings.getGlobalProperties()) { - if (shouldBeExported(property.getKey())) { - xmlProperties.add(new Property(property.getKey(), property.getValue())); - } - } - sonarConfig.setProperties(xmlProperties); - } - - public void importXml(SonarConfig sonarConfig) { - LoggerFactory.getLogger(getClass()).info("Restore properties"); - - Map<String, String> properties = Maps.newHashMap(); - - if (sonarConfig.getProperties() != null && !sonarConfig.getProperties().isEmpty()) { - for (Property xmlProperty : sonarConfig.getProperties()) { - properties.put(xmlProperty.getKey(), xmlProperty.getValue()); - } - } - - for (PropertyDto property : persistentSettings.getGlobalProperties()) { - if (shouldNotBeErased(property.getKey())) { - properties.put(property.getKey(), property.getValue()); - } - } - - persistentSettings.deleteProperties(); - persistentSettings.saveProperties(properties); - } - - public void configure(XStream xStream) { - xStream.alias("property", Property.class); - } - - private boolean shouldBeExported(String propertyKey) { - // "sonar.core.id" must never be restored, it is unique for a server and it created once at the 1rst server startup - // default permissions properties should not be exported as they reference permission_templates entries in the DB - return !CoreProperties.SERVER_ID.equals(propertyKey) - && !propertyKey.startsWith(PERMISSION_PROPERTIES_PREFIX) - && !PreviewCache.SONAR_PREVIEW_CACHE_LAST_UPDATE_KEY.equals(propertyKey); - } - - private boolean shouldNotBeErased(String propertyKey) { - // "sonar.core.id" property should not be cleared, because it is the unique key used to identify the server - // and it is used by the batch to verify that it connects to the same DB as the remote server (see SONAR-3126). - // default permissions properties should not be erased as they reference permission_templates entries in the DB - return CoreProperties.SERVER_ID.equals(propertyKey) || CoreProperties.SERVER_STARTTIME.equals(propertyKey) - || propertyKey.startsWith(PERMISSION_PROPERTIES_PREFIX); - } -} diff --git a/sonar-server/src/main/java/org/sonar/server/configuration/RulesBackup.java b/sonar-server/src/main/java/org/sonar/server/configuration/RulesBackup.java deleted file mode 100644 index f2cc6061024..00000000000 --- a/sonar-server/src/main/java/org/sonar/server/configuration/RulesBackup.java +++ /dev/null @@ -1,223 +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.configuration; - -import com.google.common.collect.Lists; -import com.thoughtworks.xstream.XStream; -import com.thoughtworks.xstream.converters.Converter; -import com.thoughtworks.xstream.converters.MarshallingContext; -import com.thoughtworks.xstream.converters.UnmarshallingContext; -import com.thoughtworks.xstream.io.HierarchicalStreamReader; -import com.thoughtworks.xstream.io.HierarchicalStreamWriter; -import org.slf4j.LoggerFactory; -import org.sonar.api.database.DatabaseSession; -import org.sonar.api.rules.Rule; -import org.sonar.api.rules.RuleParam; -import org.sonar.api.rules.RulePriority; -import org.sonar.jpa.dao.RulesDao; - -import java.util.*; - -public class RulesBackup implements Backupable { - - private static final String PARENT_REPOSITORY_KEY = "parentRepositoryKey"; - private static final String PARENT_KEY = "parentKey"; - private static final String REPOSITORY_KEY = "repositoryKey"; - private static final String KEY = "key"; - private static final String CONFIG_KEY = "configKey"; - private static final String LEVEL = "level"; - private static final String NAME = "name"; - private static final String DESCRIPTION = "description"; - private static final String PARAMS = "params"; - private static final String VALUE = "value"; - - private Collection<Rule> rules; - private RulesDao rulesDao; - private DatabaseSession session; - - public RulesBackup(DatabaseSession session) { - this.rulesDao = new RulesDao(session); - this.session = session; - } - - /** - * For tests. - */ - RulesBackup(Collection<Rule> rules) { - this.rules = rules; - } - - public void exportXml(SonarConfig sonarConfig) { - if (rules == null) { - rules = getUserRules(); - } - sonarConfig.setRules(rules); - } - - public void importXml(SonarConfig sonarConfig) { - disableUserRules(); - if (sonarConfig.getRules() != null && !sonarConfig.getRules().isEmpty()) { - registerUserRules(sonarConfig.getRules()); - } - } - - private List<Rule> getUserRules() { - List<Rule> userRules = Lists.newArrayList(); - for (Rule rule : rulesDao.getRules()) { - if (rule.getParent() != null) { - userRules.add(rule); - } - } - return userRules; - } - - private void disableUserRules() { - LoggerFactory.getLogger(getClass()).info("Disable rules created by user"); - for (Rule rule : getUserRules()) { - rule.setStatus(Rule.STATUS_REMOVED); - session.save(rule); - } - } - - private void registerUserRules(Collection<Rule> rules) { - LoggerFactory.getLogger(getClass()).info("Restore rules"); - for (Rule rule : rules) { - Rule parent = rule.getParent(); - Rule matchingParentRuleInDb = rulesDao.getRuleByKey(parent.getRepositoryKey(), parent.getKey()); - if (matchingParentRuleInDb == null) { - LoggerFactory.getLogger(getClass()).error("Unable to find parent rule " + parent.getRepositoryKey() + ":" + parent.getKey()); - continue; - } - - for (Iterator<RuleParam> irp = rule.getParams().iterator(); irp.hasNext(); ) { - RuleParam param = irp.next(); - RuleParam matchingRPInDb = rulesDao.getRuleParam(matchingParentRuleInDb, param.getKey()); - if (matchingRPInDb == null) { - LoggerFactory.getLogger(getClass()).error("Unable to find rule parameter in parent " + param.getKey()); - irp.remove(); - } - } - - rule.setParent(matchingParentRuleInDb); - rule.setLanguage(matchingParentRuleInDb.getLanguage()); - Rule matchingRuleInDb = session.getSingleResult(Rule.class, - "pluginName", rule.getRepositoryKey(), - KEY, rule.getKey()); - if (matchingRuleInDb != null) { - // merge - matchingRuleInDb.setParent(matchingParentRuleInDb); - matchingRuleInDb.setConfigKey(rule.getConfigKey()); - matchingRuleInDb.setName(rule.getName()); - matchingRuleInDb.setDescription(rule.getDescription()); - matchingRuleInDb.setSeverity(rule.getSeverity()); - matchingRuleInDb.setParams(rule.getParams()); - matchingRuleInDb.setStatus(Rule.STATUS_READY); - matchingRuleInDb.setLanguage(rule.getLanguage()); - matchingRuleInDb.setUpdatedAt(new Date()); - session.save(matchingRuleInDb); - } else { - rule.setStatus(Rule.STATUS_READY); - rule.setCreatedAt(new Date()); - session.save(rule); - } - } - } - - public void configure(XStream xStream) { - xStream.alias("rule", Rule.class); - xStream.registerConverter(new Converter() { - public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { - Rule rule = (Rule) source; - writeNode(writer, PARENT_REPOSITORY_KEY, rule.getParent().getRepositoryKey()); - writeNode(writer, PARENT_KEY, rule.getParent().getKey()); - writeNode(writer, REPOSITORY_KEY, rule.getRepositoryKey()); - writeNode(writer, KEY, rule.getKey()); - writeNode(writer, CONFIG_KEY, rule.getConfigKey()); - writeNode(writer, LEVEL, rule.getSeverity().name()); - writeNode(writer, NAME, rule.getName()); - writeNode(writer, DESCRIPTION, rule.getDescription()); - - if (!rule.getParams().isEmpty()) { - writer.startNode(PARAMS); - for (RuleParam ruleParam : rule.getParams()) { - writer.startNode("param"); - writeNode(writer, KEY, ruleParam.getKey()); - writeNode(writer, VALUE, ruleParam.getDefaultValue()); - writer.endNode(); - } - writer.endNode(); - } - } - - public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { - Rule rule = Rule.create(); - - Map<String, String> valuesRule = new HashMap<String, String>(); - while (reader.hasMoreChildren()) { - reader.moveDown(); - valuesRule.put(reader.getNodeName(), reader.getValue()); - if (PARAMS.equals(reader.getNodeName())) { - while (reader.hasMoreChildren()) { - reader.moveDown(); - Map<String, String> valuesParam = readNode(reader); - rule.createParameter() - .setKey(valuesParam.get(KEY)) - .setDefaultValue(valuesParam.get(VALUE)); - reader.moveUp(); - } - } - reader.moveUp(); - } - - Rule parent = Rule.create() - .setRepositoryKey(valuesRule.get(PARENT_REPOSITORY_KEY)) - .setKey(valuesRule.get(PARENT_KEY)); - rule.setParent(parent) - .setRepositoryKey(valuesRule.get(REPOSITORY_KEY)) - .setKey(valuesRule.get(KEY)) - .setConfigKey(valuesRule.get(CONFIG_KEY)) - .setName(valuesRule.get(NAME)) - .setDescription(valuesRule.get(DESCRIPTION)) - .setSeverity(RulePriority.valueOf(valuesRule.get(LEVEL))); - return rule; - } - - public boolean canConvert(Class type) { - return Rule.class.equals(type); - } - }); - } - - private void writeNode(HierarchicalStreamWriter writer, String name, String value) { - writer.startNode(name); - writer.setValue(value); - writer.endNode(); - } - - private Map<String, String> readNode(HierarchicalStreamReader reader) { - Map<String, String> values = new HashMap<String, String>(); - while (reader.hasMoreChildren()) { - reader.moveDown(); - values.put(reader.getNodeName(), reader.getValue()); - reader.moveUp(); - } - return values; - } -} diff --git a/sonar-server/src/main/java/org/sonar/server/platform/Platform.java b/sonar-server/src/main/java/org/sonar/server/platform/Platform.java index abb7edcd9c4..1520c4868c7 100644 --- a/sonar-server/src/main/java/org/sonar/server/platform/Platform.java +++ b/sonar-server/src/main/java/org/sonar/server/platform/Platform.java @@ -75,7 +75,6 @@ import org.sonar.jpa.session.ThreadLocalDatabaseSessionFactory; import org.sonar.server.charts.ChartFactory; import org.sonar.server.component.DefaultComponentFinder; import org.sonar.server.component.DefaultRubyComponentService; -import org.sonar.server.configuration.Backup; import org.sonar.server.configuration.ProfilesManager; import org.sonar.server.db.EmbeddedDatabaseFactory; import org.sonar.server.db.migrations.DatabaseMigration; @@ -247,7 +246,6 @@ public final class Platform { servicesContainer.addComponent(org.sonar.api.database.daos.MeasuresDao.class, false); servicesContainer.addComponent(ProfilesDao.class, false); servicesContainer.addComponent(ProfilesManager.class, false); - servicesContainer.addComponent(Backup.class, false); servicesContainer.addSingleton(SecurityRealmFactory.class); servicesContainer.addSingleton(ServerLifecycleNotifier.class); servicesContainer.addSingleton(AnnotationProfileParser.class); diff --git a/sonar-server/src/main/java/org/sonar/server/ui/JRubyFacade.java b/sonar-server/src/main/java/org/sonar/server/ui/JRubyFacade.java index 2cdfabebe5d..307e7b61f58 100644 --- a/sonar-server/src/main/java/org/sonar/server/ui/JRubyFacade.java +++ b/sonar-server/src/main/java/org/sonar/server/ui/JRubyFacade.java @@ -46,7 +46,6 @@ import org.sonar.core.purge.PurgeDao; import org.sonar.core.resource.ResourceIndexerDao; import org.sonar.core.resource.ResourceKeyUpdaterDao; import org.sonar.core.timemachine.Periods; -import org.sonar.server.configuration.Backup; import org.sonar.server.configuration.ProfilesManager; import org.sonar.server.db.migrations.DatabaseMigrator; import org.sonar.server.platform.Platform; @@ -265,7 +264,7 @@ public final class JRubyFacade { public void ruleSeverityChanged(int parentProfileId, int activeRuleId, int oldSeverityId, int newSeverityId, String userName) { getProfilesManager().ruleSeverityChanged(parentProfileId, activeRuleId, RulePriority.values()[oldSeverityId], - RulePriority.values()[newSeverityId], userName); + RulePriority.values()[newSeverityId], userName); } public void ruleDeactivated(int parentProfileId, int deactivatedRuleId, String userName) { @@ -280,10 +279,6 @@ public final class JRubyFacade { return getContainer().getComponentsByType(Footer.class); } - public Backup getBackup() { - return get(Backup.class); - } - private ProfilesManager getProfilesManager() { return get(ProfilesManager.class); } @@ -419,10 +414,10 @@ public final class JRubyFacade { // notifier is null when creating the administrator in the migration script 011. if (notifier != null) { notifier.onNewUser(NewUserHandler.Context.builder() - .setLogin(fields.get("login")) - .setName(fields.get("name")) - .setEmail(fields.get("email")) - .build()); + .setLogin(fields.get("login")) + .setName(fields.get("name")) + .setEmail(fields.get("email")) + .build()); } } diff --git a/sonar-server/src/main/webapp/WEB-INF/app/controllers/backup_controller.rb b/sonar-server/src/main/webapp/WEB-INF/app/controllers/backup_controller.rb deleted file mode 100644 index 315ce75ad88..00000000000 --- a/sonar-server/src/main/webapp/WEB-INF/app/controllers/backup_controller.rb +++ /dev/null @@ -1,60 +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. -# -class BackupController < ApplicationController - - SECTION=Navigation::SECTION_CONFIGURATION - - before_filter :admin_required - - def index - end - - def export - filename="sonar_backup_#{Date.today}.xml" - xml=java_facade.getBackup().exportXml() - send_data xml, :type => "application/xml", :filename => filename, :disposition => 'attachment' - end - - def import - verify_post_request - file=params[:file] - xml=read_file(file) - if xml && !xml.empty? - java_facade.getBackup().importXml(xml) - Metric.clear_cache - flash[:notice] = "Backup restore succeed" - else - flash[:error] = "File is empty or invalid" - end - redirect_to :action => 'index' - end - - private - - def read_file(file) - # file is a StringIO - if file.respond_to?(:read) - return file.read - end - # file is not a readable object - nil - end - -end diff --git a/sonar-server/src/test/java/org/sonar/server/configuration/BackupTest.java b/sonar-server/src/test/java/org/sonar/server/configuration/BackupTest.java deleted file mode 100644 index b795678cbdc..00000000000 --- a/sonar-server/src/test/java/org/sonar/server/configuration/BackupTest.java +++ /dev/null @@ -1,387 +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.configuration; - -import org.sonar.core.preview.PreviewCache; - -import com.google.common.collect.Lists; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang.CharEncoding; -import org.custommonkey.xmlunit.Diff; -import org.custommonkey.xmlunit.XMLUnit; -import org.junit.Before; -import org.junit.Test; -import org.sonar.api.database.DatabaseSession; -import org.sonar.api.database.configuration.Property; -import org.sonar.api.measures.Metric; -import org.sonar.api.profiles.Alert; -import org.sonar.api.profiles.RulesProfile; -import org.sonar.api.rules.ActiveRule; -import org.sonar.api.rules.ActiveRuleParam; -import org.sonar.api.rules.Rule; -import org.sonar.api.rules.RuleParam; -import org.sonar.api.rules.RulePriority; - -import java.io.IOException; -import java.io.InputStream; -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Date; -import java.util.Iterator; -import java.util.List; - -import static org.fest.assertions.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -public class BackupTest { - - private PreviewCache dryRunCache; - - @Before - public void prepare() { - this.dryRunCache = mock(PreviewCache.class); - } - - @Test - public void shouldExportXml() throws Exception { - SonarConfig sonarConfig = getSonarConfig(); - Backupable backupable = mock(Backupable.class); - Backup backup = new Backup(Arrays.asList(backupable)); - - String xml = backup.exportXml(sonarConfig); - verify(backupable).exportXml(sonarConfig); - assertXmlAreSimilar(xml, "backup-empty.xml"); - } - - @Test - public void shouldReturnAValidXml() throws Exception { - Backup backup = new Backup(Arrays.asList(new MetricsBackup(null), new PropertiesBackup(null), - new RulesBackup((DatabaseSession) null), new ProfilesBackup((DatabaseSession) null, dryRunCache))); - SonarConfig sonarConfig = getSonarConfig(); - sonarConfig.setMetrics(getMetrics()); - sonarConfig.setProperties(getProperties()); - sonarConfig.setProfiles(getProfiles()); - sonarConfig.setRules(getUserRules()); - - String xml = backup.getXmlFromSonarConfig(sonarConfig); - assertXmlAreSimilar(xml, "backup-valid.xml"); - } - - @Test - public void shouldExportXmlInCdata() throws Exception { - SonarConfig sonarConfig = getSonarConfig(); - sonarConfig.setProperties(getPropertiesWithXmlIlliciteCharacters()); - Backup backup = new Backup(Arrays.asList(new MetricsBackup(null), new PropertiesBackup(null))); - - String xml = backup.getXmlFromSonarConfig(sonarConfig); - assertXmlAreSimilar(xml, "backup-with-cdata.xml"); - } - - @Test - public void shouldExportXmlWithUtf8Characters() throws Exception { - SonarConfig sonarConfig = getSonarConfig(); - sonarConfig.setProperties(getPropertiesWithUtf8Characters()); - Backup backup = new Backup(Arrays.asList(new MetricsBackup(null), new PropertiesBackup(null))); - - String xml = backup.getXmlFromSonarConfig(sonarConfig); - assertXmlAreSimilar(xml, "backup-with-utf8-char.xml"); - } - - @Test - public void shouldImportXml() { - Backup backup = new Backup(Arrays.asList(new MetricsBackup(null), new PropertiesBackup(null), - new RulesBackup((DatabaseSession) null), new ProfilesBackup((DatabaseSession) null, dryRunCache))); - - String xml = getFileFromClasspath("backup-restore-valid.xml"); - SonarConfig sonarConfig = backup.getSonarConfigFromXml(xml); - - assertThat(sonarConfig.getMetrics()).isEqualTo(getMetrics()); - assertThat(sonarConfig.getProperties()).isEqualTo(getProperties()); - for (Metric metric : sonarConfig.getMetrics()) { - assertThat(metric.getEnabled()).isNotNull(); - assertThat(metric.getEnabled()).isTrue(); - assertThat(metric.getUserManaged()).isNotNull(); - assertThat(metric.getUserManaged()).isTrue(); - } - - Collection<RulesProfile> profiles = sonarConfig.getProfiles(); - assertThat(profiles).hasSize(2); - - Iterator<RulesProfile> profilesIter = profiles.iterator(); - RulesProfile testProfile = profilesIter.next(); - assertThat("test name").isEqualTo(testProfile.getName()); - assertThat(testProfile.getDefaultProfile()).isTrue(); - assertThat("test language").isEqualTo(testProfile.getLanguage()); - assertThat(testProfile.getActiveRules()).hasSize(1); - - ActiveRule testActiveRule = testProfile.getActiveRules().get(0); - assertThat(RulePriority.MAJOR).isEqualTo(testActiveRule.getSeverity()); - assertThat(testActiveRule.getRule()).isNotNull(); - assertThat("test key").isEqualTo(testActiveRule.getRule().getKey()); - assertThat("test plugin").isEqualTo(testActiveRule.getRule().getRepositoryKey()); - assertThat(testActiveRule.getInheritance()).isNull(); - assertThat(testActiveRule.getActiveRuleParams()).hasSize(1); - - ActiveRuleParam testActiveRuleParam = testActiveRule.getActiveRuleParams().get(0); - assertThat("test value").isEqualTo(testActiveRuleParam.getValue()); - assertThat(testActiveRuleParam.getRuleParam()).isNotNull(); - assertThat("test param key").isEqualTo(testActiveRuleParam.getRuleParam().getKey()); - - assertThat(testProfile.getAlerts()).hasSize(2); - Alert testAlert = testProfile.getAlerts().get(0); - assertThat(Alert.OPERATOR_GREATER).isEqualTo(testAlert.getOperator()); - assertThat("testError").isEqualTo(testAlert.getValueError()); - assertThat("testWarn").isEqualTo(testAlert.getValueWarning()); - assertThat(testAlert.getPeriod()).isNull(); - assertThat(testAlert.getMetric()).isNotNull(); - assertThat("test key").isEqualTo(testAlert.getMetric().getKey()); - - Alert testAlert2 = testProfile.getAlerts().get(1); - assertThat(Alert.OPERATOR_SMALLER).isEqualTo(testAlert2.getOperator()); - assertThat("testError2").isEqualTo(testAlert2.getValueError()); - assertThat("testWarn2").isEqualTo(testAlert2.getValueWarning()); - assertThat(testAlert2.getPeriod()).isEqualTo(1); - assertThat(testAlert2.getMetric()).isNotNull(); - assertThat("test key2").isEqualTo(testAlert2.getMetric().getKey()); - - // Child profile - testProfile = profilesIter.next(); - assertThat("test2 name").isEqualTo(testProfile.getName()); - assertThat("test name").isEqualTo(testProfile.getParentName()); - testActiveRule = testProfile.getActiveRules().get(0); - assertThat(testActiveRule.getInheritance()).isEqualTo(ActiveRule.OVERRIDES); - - Collection<Rule> rules = sonarConfig.getRules(); - assertThat(rules).hasSize(1); - - Rule rule = rules.iterator().next(); - assertThat(rule.getParent().getRepositoryKey()).isEqualTo("test plugin"); - assertThat(rule.getParent().getKey()).isEqualTo("test key"); - assertThat(rule.getRepositoryKey()).isEqualTo("test plugin"); - assertThat(rule.getKey()).isEqualTo("test key2"); - assertThat(rule.getConfigKey()).isEqualTo("test config key"); - assertThat(rule.getName()).isEqualTo("test name"); - assertThat(rule.getDescription()).isEqualTo("test description"); - assertThat(rule.getSeverity()).isEqualTo(RulePriority.INFO); - assertThat(rule.getParams()).hasSize(1); - - RuleParam param = rule.getParams().get(0); - assertThat(param.getKey()).isEqualTo("test param key"); - assertThat(param.getDefaultValue()).isEqualTo("test param value"); - } - - @Test - public void shouldImportXmlWithoutInheritanceInformation() { - Backup backup = new Backup(Arrays.asList(new MetricsBackup(null), new PropertiesBackup(null), - new RulesBackup((DatabaseSession) null), new ProfilesBackup((DatabaseSession) null, dryRunCache))); - - String xml = getFileFromClasspath("backup-restore-without-inheritance.xml"); - SonarConfig sonarConfig = backup.getSonarConfigFromXml(xml); - - Collection<RulesProfile> profiles = sonarConfig.getProfiles(); - assertThat(profiles).hasSize(1); - RulesProfile testProfile = profiles.iterator().next(); - assertThat(testProfile.getActiveRules()).hasSize(1); - ActiveRule activeRule = testProfile.getActiveRules().get(0); - assertThat(activeRule.getInheritance()).isNull(); - } - - @Test - public void shouldImportXmlWithXmlIlliciteCharacters() { - Backup backup = new Backup(Arrays.asList(new MetricsBackup(null), new PropertiesBackup(null))); - - String xml = getFileFromClasspath("backup-with-cdata.xml"); - SonarConfig sonarConfig = backup.getSonarConfigFromXml(xml); - - assertThat(sonarConfig.getProperties()).isEqualTo(getPropertiesWithXmlIlliciteCharacters()); - } - - @Test - public void shouldImportOneDotFiveFormat() { - Backup backup = new Backup(Arrays.asList(new MetricsBackup(null), new PropertiesBackup(null))); - - String xml = getFileFromClasspath("shouldImportOneDotFiveFormat.xml"); - SonarConfig sonarConfig = backup.getSonarConfigFromXml(xml); - - assertThat(sonarConfig.getMetrics()).hasSize(1); - assertThat(sonarConfig.getProfiles()).isNull(); - assertThat(sonarConfig.getProperties()).hasSize(2); - } - - @Test - public void shouldImportXmlWithUtf8Character() { - Backup backup = new Backup(Arrays.asList(new MetricsBackup(null), new PropertiesBackup(null))); - - String xml = getFileFromClasspath("backup-with-utf8-char.xml"); - SonarConfig sonarConfig = backup.getSonarConfigFromXml(xml); - - assertThat(sonarConfig.getProperties()).isEqualTo(getPropertiesWithUtf8Characters()); - } - - @Test - public void shouldNotImportMetricIds() { - Backup backup = new Backup(Arrays.asList(new MetricsBackup(null), new PropertiesBackup(null))); - - String xml = getFileFromClasspath("backup-with-id-for-metrics.xml"); - SonarConfig sonarConfig = backup.getSonarConfigFromXml(xml); - - Metric metric = sonarConfig.getMetrics().iterator().next(); - assertThat(metric.getId()).isNull(); - } - - @Test - public void shouldExportAndImportInnerCDATA() throws Exception { - SonarConfig sonarConfig = getSonarConfig(); - sonarConfig.setProperties(getPropertiesWithCDATA()); - - Backup backup = new Backup(Arrays.asList(new MetricsBackup(null), new PropertiesBackup(null))); - String xml = backup.getXmlFromSonarConfig(sonarConfig); - assertXmlAreSimilar(xml, "backup-with-splitted-cdata.xml"); - - sonarConfig = backup.getSonarConfigFromXml(xml); - assertThat(sonarConfig.getProperties()).isEqualTo(getPropertiesWithCDATA()); - } - - private SonarConfig getSonarConfig() throws ParseException { - DateFormat dateFormat = new SimpleDateFormat(Backup.DATE_FORMAT); - Date date = dateFormat.parse("2008-11-18"); - return new SonarConfig(54, date); - } - - private List<Metric> getMetrics() { - List<Metric> metrics = new ArrayList<Metric>(); - - Metric m1 = new Metric("metric1"); - m1.setEnabled(true); - m1.setOrigin(Metric.Origin.GUI); - - Metric m2 = new Metric("metric2"); - m2.setEnabled(true); - m2.setOrigin(Metric.Origin.WS); - - metrics.add(m1); - metrics.add(m2); - - return metrics; - } - - private List<RulesProfile> getProfiles() { - List<RulesProfile> profiles = new ArrayList<RulesProfile>(); - - Rule rule = Rule.create("test plugin", "test key", null); - rule.createParameter("test param key"); - - RulesProfile profile1 = RulesProfile.create("test name", "test language"); - profile1.setDefaultProfile(true); - profile1.setProvided(true); - profiles.add(profile1); - - ActiveRule activeRule = profile1.activateRule(rule, RulePriority.MAJOR); - activeRule.setParameter("test param key", "test value"); - - RulesProfile profile2 = RulesProfile.create("test2 name", "test language"); - profile2.setParentName(profile1.getName()); - profiles.add(profile2); - - ActiveRule activeRule2 = profile2.activateRule(rule, RulePriority.MINOR); - activeRule2.setParameter("test param key", "test value"); - activeRule2.setInheritance(ActiveRule.OVERRIDES); - - Alert alert1 = new Alert(null, new Metric("test key"), Alert.OPERATOR_GREATER, "testError", "testWarn"); - Alert alert2 = new Alert(null, new Metric("test key2"), Alert.OPERATOR_SMALLER, "testError2", "testWarn2", 1); - - List<Alert> alerts = profiles.get(0).getAlerts(); - alerts.add(alert1); - alerts.add(alert2); - - return profiles; - } - - private List<Rule> getUserRules() { - List<Rule> rules = Lists.newArrayList(); - Rule parentRule = Rule.create("test plugin", "test key", null); - Rule rule = Rule.create("test plugin", "test key2", "test name") - .setDescription("test description") - .setConfigKey("test config key") - .setSeverity(RulePriority.INFO) - .setParent(parentRule); - rule.createParameter().setKey("test param key").setDefaultValue("test param value"); - rules.add(rule); - return rules; - } - - private List<Property> getProperties() { - List<Property> properties = new ArrayList<Property>(); - properties.add(new Property("key1", "value1")); - properties.add(new Property("key2", "value2")); - return properties; - } - - private List<Property> getPropertiesWithCDATA() { - List<Property> properties = new ArrayList<Property>(); - properties.add(new Property("key1", "<![CDATA[value1]]>")); - properties.add(new Property("key2", "]]>value2")); - properties.add(new Property("key3", "prefix]]>value3")); - properties.add(new Property("key4", "<name><![CDATA[Forges]]></name>")); - return properties; - } - - private List<Property> getPropertiesWithXmlIlliciteCharacters() { - List<Property> properties = new ArrayList<Property>(); - properties.add(new Property("key", "<value>")); - return properties; - } - - private List<Property> getPropertiesWithUtf8Characters() { - List<Property> properties = new ArrayList<Property>(); - properties.add(new Property("key", "\u00E9")); - return properties; - } - - private void assertXmlAreSimilar(String xml, String xmlExpected) { - try { - XMLUnit.setIgnoreWhitespace(true); - Diff diff = XMLUnit.compareXML(getFileFromClasspath(xmlExpected), xml); - assertThat(diff.similar()).as(diff.toString()).isTrue(); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - private String getFileFromClasspath(String file) { - InputStream input = null; - try { - input = getClass().getClassLoader().getResourceAsStream("org/sonar/server/configuration/BackupTest/" + file); - return IOUtils.toString(input, CharEncoding.UTF_8); - - } catch (IOException e) { - throw new RuntimeException(e); - - } finally { - IOUtils.closeQuietly(input); - } - } - -} diff --git a/sonar-server/src/test/java/org/sonar/server/configuration/MetricsBackupTest.java b/sonar-server/src/test/java/org/sonar/server/configuration/MetricsBackupTest.java deleted file mode 100644 index 0036c857720..00000000000 --- a/sonar-server/src/test/java/org/sonar/server/configuration/MetricsBackupTest.java +++ /dev/null @@ -1,98 +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.configuration; - -import org.junit.Test; -import org.sonar.jpa.dao.MeasuresDao; -import org.sonar.jpa.test.AbstractDbUnitTestCase; -import org.sonar.api.measures.Metric; - -import java.util.Arrays; -import java.util.Collection; - -import static org.fest.assertions.Assertions.assertThat; - -public class MetricsBackupTest extends AbstractDbUnitTestCase { - - @Test - public void shouldExportMetrics() { - MetricsBackup metricsBackup = new MetricsBackup(); - SonarConfig sonarConfig = new SonarConfig(); - Collection<Metric> metrics = createMetrics(); - metricsBackup.exportXml(sonarConfig, metrics); - - assertThat(sonarConfig.getMetrics()).isEqualTo(metrics); - } - - @Test - public void shouldImportMetrics() { - MeasuresDao measuresDao = new MeasuresDao(getSession()); - Collection<Metric> oldMetrics = createMetrics(); - measuresDao.registerMetrics(oldMetrics); - - MetricsBackup metricsBackup = new MetricsBackup(getSession()); - SonarConfig sonarConfig = new SonarConfig(); - - Collection<Metric> importedMetrics = createNewMetrics(); - sonarConfig.setMetrics(importedMetrics); - metricsBackup.importXml(sonarConfig); - - Collection<Metric> allMetrics = measuresDao.getMetrics(); - assertThat(allMetrics).hasSize(4); - - Collection<Metric> enabledMetrics = measuresDao.getEnabledMetrics(); - assertThat(enabledMetrics).hasSize(3); - - } - - private Collection<Metric> createMetrics() { - Metric m1 = new Metric("metric1"); - m1.setDescription("old desc metric1"); - m1.setEnabled(true); - m1.setOrigin(Metric.Origin.GUI); - - Metric m2 = new Metric("metric2"); - m2.setDescription("old desc metric2"); - m2.setEnabled(true); - m2.setOrigin(Metric.Origin.WS); - - Metric m3 = new Metric("metric3"); - m3.setDescription("desc metric3"); - m3.setEnabled(true); - m3.setOrigin(Metric.Origin.WS); - - return Arrays.asList(m1, m2, m3); - } - - private Collection<Metric> createNewMetrics() { - Metric m1 = new Metric("metric1"); - m1.setDescription("new desc metric1"); - m1.setOrigin(Metric.Origin.WS); - - Metric m2 = new Metric("metric2"); - m2.setDescription("new desc metric2"); - m2.setOrigin(Metric.Origin.WS); - - Metric m3 = new Metric("new metric"); - m3.setOrigin(Metric.Origin.WS); - - return Arrays.asList(m1, m2, m3); - } -} diff --git a/sonar-server/src/test/java/org/sonar/server/configuration/PropertiesBackupTest.java b/sonar-server/src/test/java/org/sonar/server/configuration/PropertiesBackupTest.java deleted file mode 100644 index 51173e6262f..00000000000 --- a/sonar-server/src/test/java/org/sonar/server/configuration/PropertiesBackupTest.java +++ /dev/null @@ -1,173 +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.configuration; - -import com.google.common.collect.Lists; -import org.hamcrest.Description; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentMatcher; -import org.sonar.api.CoreProperties; -import org.sonar.api.database.configuration.Property; -import org.sonar.core.properties.PropertyDto; -import org.sonar.server.platform.PersistentSettings; - -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -import static org.fest.assertions.Assertions.assertThat; -import static org.mockito.Matchers.argThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class PropertiesBackupTest { - - private PersistentSettings persistentSettings; - private PropertiesBackup backup; - - @Before - public void setup() { - persistentSettings = mock(PersistentSettings.class); - backup = new PropertiesBackup(persistentSettings); - } - - @Test - public void shouldExportProperties() { - when(persistentSettings.getGlobalProperties()) - .thenReturn(Lists.newArrayList(new PropertyDto().setKey("key1").setValue("value1"), new PropertyDto().setKey("key2").setValue("value2"))); - - SonarConfig config = new SonarConfig(); - backup.exportXml(config); - - assertThat(config.getProperties()).containsOnly(new Property("key1", "value1"), new Property("key2", "value2")); - } - - @Test - public void shouldNotExportServerId() { - when(persistentSettings.getGlobalProperties()) - .thenReturn(Lists.newArrayList(new PropertyDto().setKey(CoreProperties.SERVER_ID).setValue("111"), new PropertyDto().setKey("key").setValue("value"))); - - SonarConfig config = new SonarConfig(); - backup.exportXml(config); - - assertThat(config.getProperties()).containsOnly(new Property("key", "value")); - } - - @Test - public void shouldImportBackupOfProperties() { - SonarConfig config = new SonarConfig(); - config.setProperties(Arrays.asList(new Property("key1", "value1"))); - - backup.importXml(config); - - Map<String, String> expectedProperties = new HashMap<String, String>(); - expectedProperties.put("key1", "value1"); - verify(persistentSettings).saveProperties(argThat(IsMap.containing(expectedProperties))); - } - - @Test - public void shouldNotImportServerId() { - // initial server id - when(persistentSettings.getGlobalProperties()).thenReturn(Lists.newArrayList( - new PropertyDto().setKey(CoreProperties.SERVER_ID).setValue("111"))); - - Collection<Property> newProperties = Arrays.asList(new Property(CoreProperties.SERVER_ID, "999")); - SonarConfig config = new SonarConfig(); - config.setProperties(newProperties); - backup.importXml(config); - - Map<String, String> expectedProperties = new HashMap<String, String>(); - expectedProperties.put(CoreProperties.SERVER_ID, "111"); - verify(persistentSettings).saveProperties(argThat(IsMap.containing(expectedProperties))); - } - - @Test - public void shouldNotImportPermissionProperties() throws Exception { - when(persistentSettings.getGlobalProperties()).thenReturn(Lists.newArrayList( - new PropertyDto().setKey("sonar.permission.template.default").setValue("default_template"), - new PropertyDto().setKey("sonar.permission.template.TRK.default").setValue("default_template_for_projects"), - new PropertyDto().setKey("erasable_key").setValue("erasable_value"))); - - Collection<Property> newProperties = Arrays.asList( - new Property("sonar.permission.template.default", "another_default"), - new Property("key_to_import", "value_to_import"), - new Property("erasable_key", "new_value")); - SonarConfig config = new SonarConfig(); - config.setProperties(newProperties); - backup.importXml(config); - - Map<String, String> expectedProperties = new HashMap<String, String>(); - expectedProperties.put("key_to_import", "value_to_import"); - expectedProperties.put("erasable_key", "new_value"); - expectedProperties.put("sonar.permission.template.default", "default_template"); - expectedProperties.put("sonar.permission.template.TRK.default", "default_template_for_projects"); - verify(persistentSettings).saveProperties(argThat(IsMap.containing(expectedProperties))); - } - - @Test - public void shouldNotExportPermissionProperties() throws Exception { - when(persistentSettings.getGlobalProperties()).thenReturn(Lists.newArrayList( - new PropertyDto().setKey("sonar.permission.template.default").setValue("default_template"), - new PropertyDto().setKey("sonar.permission.template.TRK.default").setValue("default_template_for_projects"), - new PropertyDto().setKey("key").setValue("value"))); - - SonarConfig config = new SonarConfig(); - backup.exportXml(config); - - assertThat(config.getProperties()).containsOnly(new Property("key", "value")); - } - - private static class IsMap extends ArgumentMatcher<Map<String, String>> { - - private final Map<String, String> referenceMap; - - private IsMap(Map<String, String> referenceMap) { - this.referenceMap = referenceMap; - } - - static IsMap containing(Map<String, String> keyValuePairs) { - return new IsMap(keyValuePairs); - } - - @Override - public boolean matches(Object argument) { - if (argument != null && argument instanceof Map) { - Map<String, String> argAsMap = (Map<String, String>) argument; - for (String key : argAsMap.keySet()) { - if (!referenceMap.containsKey(key) || !referenceMap.get(key).equals(argAsMap.get(key))) { - return false; - } - } - return true; - } - return false; - } - - @Override - public void describeTo(Description description) { - if (referenceMap != null) { - description.appendText(referenceMap.toString()); - } - } - } -} diff --git a/sonar-server/src/test/java/org/sonar/server/configuration/RulesBackupTest.java b/sonar-server/src/test/java/org/sonar/server/configuration/RulesBackupTest.java deleted file mode 100644 index b01b270b1ba..00000000000 --- a/sonar-server/src/test/java/org/sonar/server/configuration/RulesBackupTest.java +++ /dev/null @@ -1,128 +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.configuration; - -import org.junit.Before; -import org.junit.Test; -import org.sonar.api.rules.Rule; -import org.sonar.api.rules.RuleParam; -import org.sonar.api.rules.RulePriority; -import org.sonar.jpa.dao.RulesDao; -import org.sonar.jpa.test.AbstractDbUnitTestCase; - -import java.util.Arrays; - -import static org.fest.assertions.Assertions.assertThat; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; - -public class RulesBackupTest extends AbstractDbUnitTestCase { - - private RulesBackup rulesBackup; - private SonarConfig sonarConfig; - - private Rule rule; - - @Before - public void setUp() { - rulesBackup = new RulesBackup(getSession()); - sonarConfig = new SonarConfig(); - - rule = Rule.create("repo", "key", "name").setDescription("description").setLanguage("language"); - rule.createParameter("param").setDefaultValue("value"); - } - - @Test - public void shouldExportRules() { - Rule userRule = createUserRule(); - RulesBackup rulesBackup = new RulesBackup(Arrays.asList(userRule)); - rulesBackup.exportXml(sonarConfig); - - assertThat(sonarConfig.getRules()).containsOnly(userRule); - } - - @Test - public void shouldImportRules() { - getSession().save(rule); - - sonarConfig.setRules(Arrays.asList(createUserRule())); - rulesBackup.importXml(sonarConfig); - - verify(); - } - - @Test - public void shouldUpdateRules() { - getSession().save(rule); - getSession().save(Rule.create("repo", "key2", "")); - - sonarConfig.setRules(Arrays.asList(createUserRule())); - rulesBackup.importXml(sonarConfig); - - verify(); - } - - @Test - public void shouldIgnoreIncorrectRule() { - sonarConfig.setRules(Arrays.asList(createUserRule())); - rulesBackup.importXml(sonarConfig); - - assertThat(getSession().getResults(Rule.class).size(), is(0)); - } - - @Test - public void shouldIgnoreIncorrectParam() { - Rule rule = Rule.create("repo", "key", "name").setDescription("description"); - getSession().save(rule); - sonarConfig.setRules(Arrays.asList(createUserRule())); - rulesBackup.importXml(sonarConfig); - - assertThat(getSession().getResults(Rule.class).size(), is(2)); - RulesDao rulesDao = new RulesDao(getSession()); - Rule importedRule = rulesDao.getRuleByKey("repo", "key2"); - assertThat(importedRule, notNullValue()); - assertThat(rulesDao.getRuleParam(importedRule, "param"), nullValue()); - } - - private Rule createUserRule() { - Rule userRule = Rule.create("repo", "key2", "name2").setDescription("description2"); - userRule.setParent(rule); - userRule.setSeverity(RulePriority.INFO); - userRule.createParameter("param").setDefaultValue("value"); - return userRule; - } - - private void verify() { - assertThat(getSession().getResults(Rule.class).size(), is(2)); - Rule importedRule = new RulesDao(getSession()).getRuleByKey("repo", "key2"); - assertThat(importedRule.getParent(), is(rule)); - assertThat(importedRule.isEnabled(), is(true)); - assertThat(importedRule.getName(), is("name2")); - assertThat(importedRule.getDescription(), is("description2")); - assertThat(importedRule.getSeverity(), is(RulePriority.INFO)); - assertThat(importedRule.getParams().size(), is(1)); - assertThat(importedRule.getLanguage(), is("language")); - RuleParam param = importedRule.getParams().get(0); - assertThat(param.getKey(), is("param")); - assertThat(param.getDefaultValue(), is("value")); - } -} |