XooProjectBuilder.class,
XooPostJob.class);
}
+
}
repo.createRule(CustomMessageSensor.RULE_KEY).setName("Issue With Custom Message")
.setHtmlDescription("Generate an issue on each file with a custom message");
+
+ repo.createRule(RandomAccessSensor.RULE_KEY).setName("One Issue Per File with Random Access")
+ .setHtmlDescription("This issue is generated on each file");
+ repo.createRule(DeprecatedResourceApiSensor.RULE_KEY).setName("Issue created using deprecated API")
+ .setHtmlDescription("Issue created using deprecated API");
+
repo.done();
}
assertThat(repo).isNotNull();
assertThat(repo.name()).isEqualTo("Xoo");
assertThat(repo.language()).isEqualTo("xoo");
- assertThat(repo.rules()).hasSize(8);
+ assertThat(repo.rules()).hasSize(10);
RulesDefinition.Rule rule = repo.rule(OneIssuePerLineSensor.RULE_KEY);
assertThat(rule.name()).isNotEmpty();
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 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.batch.protocol.input;
+
+import javax.annotation.CheckForNull;
+import javax.annotation.Nullable;
+
+public class Rule {
+ private final String key;
+ private final String repo;
+ private final String internalKey;
+ private final String name;
+ private final String severity;
+ private final String lang;
+
+ public Rule(String ruleKey, String repositoryKey, String internalKey, String name, @Nullable String severity, @Nullable String language) {
+ this.key = ruleKey;
+ this.repo = repositoryKey;
+ this.internalKey = internalKey;
+ this.name = name;
+ this.severity = severity;
+ this.lang = language;
+ }
+
+ public String ruleKey() {
+ return key;
+ }
+
+ public String repositoryKey() {
+ return repo;
+ }
+
+ public String internalKey() {
+ return internalKey;
+ }
+
+ public String name() {
+ return name;
+ }
+
+ /**
+ * Is null on manual rules
+ */
+ @CheckForNull
+ public String severity() {
+ return severity;
+ }
+
+ /**
+ * Is null on manual rules
+ */
+ @CheckForNull
+ public String language() {
+ return lang;
+ }
+
+}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 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.batch.protocol.input;
+
+import java.util.List;
+
+import org.sonar.batch.protocol.GsonHelper;
+
+public class RulesSearchResult {
+ List<Rule> rules;
+
+ public List<Rule> getRules() {
+ return rules;
+ }
+
+ public void setRules(List<Rule> rules) {
+ this.rules = rules;
+ }
+
+ public String toJson() {
+ return GsonHelper.create().toJson(this);
+ }
+
+ public static RulesSearchResult fromJson(String json) {
+ return GsonHelper.create().fromJson(json, RulesSearchResult.class);
+ }
+
+}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 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.batch.protocol.input;
+
+import org.apache.commons.io.IOUtils;
+
+import java.io.IOException;
+import java.net.URL;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.sonar.test.JsonAssert;
+import org.assertj.core.util.Lists;
+import org.junit.Test;
+
+public class RulesSearchResultTest {
+ @Test
+ public void testJsonParsing() {
+ Rule rule1 = new Rule("squid:S1194", "squid", "S1194", "\"java.lang.Error\" should not be extended", "MAJOR", "java");
+ Rule rule2 = new Rule("squid:ObjectFinalizeOverridenCallsSuperFinalizeCheck", "squid", "ObjectFinalizeOverridenCallsSuperFinalizeCheck",
+ "super.finalize() should be called at the end of Object.finalize() implementations", "BLOCKER", "java");
+
+ RulesSearchResult rules = new RulesSearchResult();
+ rules.setRules(Lists.newArrayList(rule1, rule2));
+
+ JsonAssert
+ .assertJson(getClass().getResource("RulesSearchTest/expected.json"))
+ .isSimilarTo(rules.toJson());
+ }
+
+ @Test
+ public void testJsonParsingEmpty() throws IOException {
+ URL resource = getClass().getResource("RulesSearchTest/empty.json");
+ String json = IOUtils.toString(resource);
+ RulesSearchResult result = RulesSearchResult.fromJson(json);
+
+ assertThat(result.getRules()).isEmpty();
+ }
+}
--- /dev/null
+{"total":3225,"p":30,"ps":500,"rules":[]}
\ No newline at end of file
--- /dev/null
+{"total":290,"p":1,"ps":2,"rules":[{"key":"squid:S1194","internalKey":"S1194","repo":"squid","name":"\"java.lang.Error\" should not be extended","severity":"MAJOR","lang":"java"},{"key":"squid:ObjectFinalizeOverridenCallsSuperFinalizeCheck","internalKey":"ObjectFinalizeOverridenCallsSuperFinalizeCheck","repo":"squid","name":"super.finalize() should be called at the end of Object.finalize() implementations","severity":"BLOCKER","lang":"java"}]}
\ No newline at end of file
// only static stuff
}
- public static Collection all(GlobalMode analysisMode) {
- List components = Lists.newArrayList(
+ public static Collection<Object> all(GlobalMode analysisMode) {
+ List<Object> components = Lists.newArrayList(
DefaultResourceTypes.get(),
// SCM
ScmConfiguration.class,
*/
package org.sonar.batch.bootstrap;
+import org.sonar.batch.rule.RulesLoader;
+
+import org.sonar.batch.rule.DefaultRulesLoader;
+import org.sonar.batch.rule.RulesProvider;
+
import java.util.List;
import java.util.Map;
import org.sonar.api.CoreProperties;
CachesManager.class,
GlobalMode.class,
GlobalSettings.class,
+ new RulesProvider(),
ServerClient.class,
Logback.class,
DefaultServer.class,
new GlobalRepositoriesProvider(),
UserRepository.class);
addIfMissing(BatchPluginInstaller.class, PluginInstaller.class);
+ addIfMissing(DefaultRulesLoader.class, RulesLoader.class);
addIfMissing(DefaultGlobalRepositoriesLoader.class, GlobalRepositoriesLoader.class);
addIfMissing(DefaultProjectRepositoriesLoader.class, ProjectRepositoriesLoader.class);
addIfMissing(DefaultServerIssuesLoader.class, ServerIssuesLoader.class);
}
public URI getURI(String pathStartingWithSlash) {
- Preconditions.checkArgument(pathStartingWithSlash.startsWith("/"), "Path must start with slash /");
+ Preconditions.checkArgument(pathStartingWithSlash.startsWith("/"), "Path must start with slash /: " + pathStartingWithSlash);
String path = StringEscapeUtils.escapeHtml(pathStartingWithSlash);
return URI.create(getURL() + path);
}
package org.sonar.batch.cpd;
import com.google.common.collect.ImmutableList;
+
import java.util.List;
+
import org.sonar.batch.cpd.index.IndexFactory;
public final class CpdComponents {
private CpdComponents() {
}
- public static List all() {
+ public static List<? extends Object> all() {
return ImmutableList.of(
CpdSensor.class,
CpdMappings.class,
import org.sonar.api.batch.rule.ActiveRules;
import org.sonar.api.batch.rule.Rule;
import org.sonar.api.batch.rule.Rules;
-import org.sonar.api.batch.rule.internal.DefaultActiveRule;
import org.sonar.api.resources.Project;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.utils.MessageException;
private final Project project;
private final IssueFilters filters;
- public ModuleIssues(ActiveRules activeRules, @Nullable Rules rules, IssueCache cache, Project project, IssueFilters filters) {
+ public ModuleIssues(ActiveRules activeRules, Rules rules, IssueCache cache, Project project, IssueFilters filters) {
this.activeRules = activeRules;
this.rules = rules;
this.cache = cache;
this.filters = filters;
}
- public ModuleIssues(ActiveRules activeRules, IssueCache cache, Project project, IssueFilters filters) {
- this(activeRules, null, cache, project, filters);
- }
-
public boolean initAndAddIssue(DefaultIssue issue) {
RuleKey ruleKey = issue.ruleKey();
- Rule rule = null;
- if (rules != null) {
- rule = rules.find(ruleKey);
- validateRule(issue, rule);
- }
+ Rule rule = rules.find(ruleKey);
+ validateRule(issue, rule);
ActiveRule activeRule = activeRules.find(ruleKey);
if (activeRule == null) {
// rule does not exist or is not enabled -> ignore the issue
private void updateIssue(DefaultIssue issue, @Nullable Rule rule, ActiveRule activeRule) {
if (Strings.isNullOrEmpty(issue.message())) {
- issue.setMessage(((DefaultActiveRule) activeRule).name());
+ issue.setMessage(rule.name());
}
if (project != null) {
issue.setCreationDate(project.getAnalysisDate());
*/
package org.sonar.batch.mediumtest;
+import org.sonar.api.server.rule.RulesDefinition.Repository;
+
+import org.sonar.api.server.rule.RulesDefinition;
+import org.sonar.batch.protocol.input.RulesSearchResult;
+import org.sonar.batch.rule.RulesLoader;
+import org.sonar.batch.protocol.input.Rule;
import com.google.common.base.Function;
import com.google.common.io.Files;
+
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
+import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
+
import org.sonar.api.CoreProperties;
import org.sonar.api.SonarPlugin;
import org.sonar.api.batch.bootstrap.ProjectReactor;
private final FakeServerIssuesLoader serverIssues = new FakeServerIssuesLoader();
private final FakeServerLineHashesLoader serverLineHashes = new FakeServerLineHashesLoader();
private final Map<String, String> bootstrapProperties = new HashMap<>();
+ private final FakeRulesLoader rulesLoader = new FakeRulesLoader();
private LogOutput logOutput = null;
public BatchMediumTester build() {
return this;
}
+ public BatchMediumTesterBuilder addRule(Rule rule) {
+ rulesLoader.addRule(rule);
+ return this;
+ }
+
+ public BatchMediumTesterBuilder addRules(List<Rule> rules) {
+ for (Rule r : rules) {
+ rulesLoader.addRule(r);
+ }
+ return this;
+ }
+
+ public BatchMediumTesterBuilder addRules(RulesDefinition rulesDefinition) {
+ RulesDefinition.Context context = new RulesDefinition.Context();
+ rulesDefinition.define(context);
+ List<Repository> repositories = context.repositories();
+ for (Repository repo : repositories) {
+ for (RulesDefinition.Rule rule : repo.rules()) {
+ this.addRule(new Rule(rule.repository().key() + ":" + rule.key(), rule.repository().key(), rule.internalKey(), rule.name(), rule.severity(), repo.language()));
+ }
+ }
+ return this;
+ }
+
public BatchMediumTesterBuilder addDefaultQProfile(String language, String name) {
addQProfile(language, name);
globalRefProvider.globalSettings().put("sonar.profile." + language, name);
builder.projectRefProvider,
builder.serverIssues,
builder.serverLineHashes,
+ builder.rulesLoader,
new DefaultDebtModel())
.setBootstrapProperties(builder.bootstrapProperties)
.setLogOutput(builder.logOutput)
}
}
+ private static class FakeRulesLoader implements RulesLoader {
+ private List<Rule> rules = new LinkedList<>();
+
+ public FakeRulesLoader addRule(Rule rule) {
+ rules.add(rule);
+ return this;
+ }
+
+ @Override
+ public RulesSearchResult load() {
+ RulesSearchResult r = new RulesSearchResult();
+ r.setRules(rules);
+ return r;
+ }
+
+ }
+
private static class FakeGlobalRepositoriesLoader implements GlobalRepositoriesLoader {
private int metricId = 1;
throw MessageException.of("No quality profiles has been found this project, you probably don't have any language plugin suitable for this analysis.");
}
}
-
}
return singleton;
}
- private ActiveRules load(ProjectRepositories ref) {
+ private static ActiveRules load(ProjectRepositories ref) {
ActiveRulesBuilder builder = new ActiveRulesBuilder();
for (ActiveRule activeRule : ref.activeRules()) {
NewActiveRule newActiveRule = builder.create(RuleKey.of(activeRule.repositoryKey(), activeRule.ruleKey()));
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 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.batch.rule;
+
+import org.sonar.batch.protocol.input.Rule;
+
+import org.sonar.batch.protocol.input.RulesSearchResult;
+import org.sonar.batch.bootstrap.WSLoader;
+
+public class DefaultRulesLoader implements RulesLoader {
+ private static final String RULES_SEARCH_URL = "/api/rules/search?ps=500&f=repo,name,internalKey,severity,lang";
+
+ private final WSLoader wsLoader;
+
+ public DefaultRulesLoader(WSLoader wsLoader) {
+ this.wsLoader = wsLoader;
+ }
+
+ @Override
+ public RulesSearchResult load() {
+
+ RulesSearchResult rules = RulesSearchResult.fromJson(wsLoader.loadString(getUrl(1)));
+
+ for (int i = 2; i < 100; i++) {
+ RulesSearchResult moreRules = RulesSearchResult.fromJson(wsLoader.loadString(getUrl(i)));
+ if (moreRules.getRules().isEmpty()) {
+ break;
+ }
+ rules.getRules().addAll(moreRules.getRules());
+ }
+ return rules;
+ }
+
+ private String getUrl(int page) {
+ return RULES_SEARCH_URL + "&p=" + page;
+ }
+}
*/
package org.sonar.batch.rule;
+import org.sonar.api.batch.rule.Rules;
+
import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
-import org.sonar.api.batch.rule.ActiveRule;
-import org.sonar.api.batch.rule.ActiveRules;
-import org.sonar.api.batch.rule.internal.DefaultActiveRule;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rules.Rule;
import org.sonar.api.rules.RuleFinder;
*/
public class RuleFinderCompatibility implements RuleFinder {
- private final ActiveRules activeRules;
+ private final Rules rules;
- public RuleFinderCompatibility(ActiveRules activeRules) {
- this.activeRules = activeRules;
+ public RuleFinderCompatibility(Rules rules) {
+ this.rules = rules;
}
@Override
@Override
public Rule findByKey(RuleKey key) {
- return toRule(activeRules.find(key));
+ return toRule(rules.find(key));
}
@Override
}
private Collection<Rule> byRepository(RuleQuery query) {
- return Collections2.transform(activeRules.findByRepository(query.getRepositoryKey()), new Function<ActiveRule, Rule>() {
+ return Collections2.transform(rules.findByRepository(query.getRepositoryKey()), new Function<org.sonar.api.batch.rule.Rule, Rule>() {
@Override
- public Rule apply(@Nonnull ActiveRule input) {
+ public Rule apply(@Nonnull org.sonar.api.batch.rule.Rule input) {
return toRule(input);
}
});
}
private Collection<Rule> byKey(RuleQuery query) {
- Rule rule = toRule(activeRules.find(RuleKey.of(query.getRepositoryKey(), query.getKey())));
+ Rule rule = toRule(rules.find(RuleKey.of(query.getRepositoryKey(), query.getKey())));
return rule != null ? Arrays.asList(rule) : Collections.<Rule>emptyList();
}
private Collection<Rule> byInternalKey(RuleQuery query) {
- Rule rule = toRule(activeRules.findByInternalKey(query.getRepositoryKey(), query.getConfigKey()));
+ Rule rule = toRule(rules.findByInternalKey(query.getRepositoryKey(), query.getConfigKey()));
return rule != null ? Arrays.asList(rule) : Collections.<Rule>emptyList();
}
@CheckForNull
- private Rule toRule(@Nullable ActiveRule rule) {
- DefaultActiveRule ar = (DefaultActiveRule) rule;
- return ar == null ? null : Rule.create(ar.ruleKey().repository(), ar.ruleKey().rule()).setName(ar.name()).setConfigKey(ar.internalKey()).setLanguage(ar.language());
+ private static Rule toRule(@Nullable org.sonar.api.batch.rule.Rule ar) {
+ return ar == null ? null : Rule.create(ar.key().repository(), ar.key().rule()).setName(ar.name()).setConfigKey(ar.internalKey());
}
}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 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.batch.rule;
+
+import org.sonar.batch.protocol.input.RulesSearchResult;
+
+public interface RulesLoader {
+ RulesSearchResult load();
+}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 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.batch.rule;
+
+import org.picocontainer.injectors.ProviderAdapter;
+
+import org.sonar.api.rule.RuleKey;
+import org.sonar.api.batch.rule.internal.RulesBuilder;
+import org.sonar.api.batch.rule.internal.NewRule;
+import org.sonar.batch.protocol.input.Rule;
+import org.sonar.api.batch.rule.Rules;
+
+public class RulesProvider extends ProviderAdapter {
+ private Rules singleton = null;
+
+ public Rules provide(RulesLoader ref) {
+ if (singleton == null) {
+ singleton = load(ref);
+ }
+ return singleton;
+ }
+
+ private static Rules load(RulesLoader ref) {
+ RulesBuilder builder = new RulesBuilder();
+
+ for (Rule inputRule : ref.load().getRules()) {
+ NewRule newRule = builder.add(RuleKey.parse(inputRule.ruleKey()));
+ newRule.setName(inputRule.name());
+ newRule.setSeverity(inputRule.severity());
+ newRule.setInternalKey(inputRule.internalKey());
+ }
+
+ return builder.build();
+ }
+
+}
ProjectExclusions.class,
ProjectReactorValidator.class,
new ProjectRepositoriesProvider(),
- new WSLoaderProjectProvider(),
+ new ProjectWSLoaderProvider(),
DefaultResourceCreationLock.class,
CodeColorizers.class,
MetricProvider.class,
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 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.batch.scan;
+
+import org.picocontainer.injectors.ProviderAdapter;
+
+import java.util.Map;
+
+import org.sonar.batch.bootstrap.AnalysisProperties;
+import org.sonar.batch.bootstrap.ServerClient;
+import org.sonar.batch.bootstrap.WSLoader;
+import org.sonar.home.cache.PersistentCache;
+import org.sonar.api.batch.AnalysisMode;
+import org.sonar.batch.bootstrap.WSLoader.LoadStrategy;
+
+public class ProjectWSLoaderProvider extends ProviderAdapter {
+ private WSLoader wsLoader;
+
+ public WSLoader provide(AnalysisProperties props, AnalysisMode mode, PersistentCache cache, ServerClient client) {
+ if (wsLoader == null) {
+ // recreate cache directory if needed for this analysis
+ cache.reconfigure();
+ wsLoader = new WSLoader(isCacheEnabled(props.properties(), mode.isPreview()), cache, client);
+ wsLoader.setStrategy(getStrategy(mode));
+ }
+ return wsLoader;
+ }
+
+ private static LoadStrategy getStrategy(AnalysisMode mode) {
+ if (mode.isQuick()) {
+ return LoadStrategy.CACHE_FIRST;
+ }
+
+ return LoadStrategy.SERVER_FIRST;
+ }
+
+ private static boolean isCacheEnabled(Map<String, String> props, boolean isPreview) {
+ String enableOffline = props.get("sonar.enableOffline");
+ return isPreview && "true".equals(enableOffline);
+ }
+}
*/
package org.sonar.batch.scan.report;
+import org.sonar.api.batch.rule.Rule;
+
import com.google.common.collect.Maps;
import org.sonar.api.issue.Issue;
-import org.sonar.api.rules.Rule;
import org.sonar.api.rules.RulePriority;
import org.sonar.batch.index.BatchComponent;
*/
package org.sonar.batch.scan.report;
+import org.sonar.api.batch.rule.Rule;
+
+import org.sonar.api.batch.rule.Rules;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.batch.BatchSide;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.api.resources.Project;
import org.sonar.api.rule.RuleKey;
-import org.sonar.api.rules.Rule;
-import org.sonar.api.rules.RuleFinder;
import org.sonar.api.rules.RulePriority;
import org.sonar.batch.DefaultProjectTree;
import org.sonar.batch.index.BatchComponent;
private static final Logger LOG = LoggerFactory.getLogger(IssuesReportBuilder.class);
private final IssueCache issueCache;
- private final RuleFinder ruleFinder;
+ private final Rules rules;
private final BatchComponentCache resourceCache;
private final DefaultProjectTree projectTree;
private final InputPathCache inputPathCache;
- public IssuesReportBuilder(IssueCache issueCache, RuleFinder ruleFinder, BatchComponentCache resourceCache, DefaultProjectTree projectTree, InputPathCache inputPathCache) {
+ public IssuesReportBuilder(IssueCache issueCache, Rules rules, BatchComponentCache resourceCache, DefaultProjectTree projectTree, InputPathCache inputPathCache) {
this.issueCache = issueCache;
- this.ruleFinder = ruleFinder;
+ this.rules = rules;
this.resourceCache = resourceCache;
this.projectTree = projectTree;
this.inputPathCache = inputPathCache;
@CheckForNull
private Rule findRule(Issue issue) {
- RuleKey ruleKey = issue.ruleKey();
- return ruleFinder.findByKey(ruleKey);
+ return rules.find(issue.ruleKey());
}
}
*/
package org.sonar.batch.scan.report;
+import org.sonar.api.batch.rule.Rule;
+
+import org.sonar.api.batch.rule.Rules;
import com.google.common.annotations.VisibleForTesting;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.DefaultInputDir;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
-import org.sonar.api.batch.rule.ActiveRules;
-import org.sonar.api.batch.rule.internal.DefaultActiveRule;
import org.sonar.api.config.Settings;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.api.platform.Server;
private final Settings settings;
private final FileSystem fileSystem;
private final Server server;
- private final ActiveRules activeRules;
+ private final Rules rules;
private final IssueCache issueCache;
private final InputPathCache fileCache;
private final Project rootModule;
private final UserRepository userRepository;
- public JSONReport(Settings settings, FileSystem fileSystem, Server server, ActiveRules activeRules, IssueCache issueCache,
+ public JSONReport(Settings settings, FileSystem fileSystem, Server server, Rules rules, IssueCache issueCache,
Project rootModule, InputPathCache fileCache, UserRepository userRepository) {
this.settings = settings;
this.fileSystem = fileSystem;
this.server = server;
- this.activeRules = activeRules;
+ this.rules = rules;
this.issueCache = issueCache;
this.rootModule = rootModule;
this.fileCache = fileCache;
json.endArray();
}
- private void writeUsers(JsonWriter json, Collection<BatchInput.User> users) throws IOException {
+ private static void writeUsers(JsonWriter json, Collection<BatchInput.User> users) throws IOException {
json.name("users").beginArray();
for (BatchInput.User user : users) {
json
}
private String getRuleName(RuleKey ruleKey) {
- DefaultActiveRule rule = (DefaultActiveRule) activeRules.find(ruleKey);
+ Rule rule = rules.find(ruleKey);
return rule != null ? rule.name() : null;
}
*/
package org.sonar.batch.scan.report;
+import org.sonar.api.batch.rule.Rule;
+
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
-import org.sonar.api.rules.Rule;
import org.sonar.api.rules.RulePriority;
/**
@Override
public int compareTo(ReportRuleKey o) {
if (severity == o.getSeverity()) {
- return getRule().ruleKey().toString().compareTo(o.getRule().ruleKey().toString());
+ return getRule().key().toString().compareTo(o.getRule().key().toString());
}
return o.getSeverity().compareTo(severity);
}
*/
package org.sonar.batch.scan.report;
+import org.sonar.api.batch.rule.Rule;
+
import com.google.common.collect.Maps;
import org.sonar.api.issue.Issue;
-import org.sonar.api.rules.Rule;
import org.sonar.api.rules.RulePriority;
import java.util.ArrayList;
initMaps(reportRuleKey);
ruleReportByRuleKey.get(reportRuleKey).getTotal().incrementCountInCurrentAnalysis();
total.incrementCountInCurrentAnalysis();
- totalByRuleKey.get(rule.ruleKey().toString()).incrementCountInCurrentAnalysis();
+ totalByRuleKey.get(rule.key().toString()).incrementCountInCurrentAnalysis();
totalBySeverity.get(severity.toString()).incrementCountInCurrentAnalysis();
if (issue.isNew()) {
total.incrementNewIssuesCount();
ruleReportByRuleKey.get(reportRuleKey).getTotal().incrementNewIssuesCount();
- totalByRuleKey.get(rule.ruleKey().toString()).incrementNewIssuesCount();
+ totalByRuleKey.get(rule.key().toString()).incrementNewIssuesCount();
totalBySeverity.get(severity.toString()).incrementNewIssuesCount();
}
}
initMaps(reportRuleKey);
total.incrementResolvedIssuesCount();
ruleReportByRuleKey.get(reportRuleKey).getTotal().incrementResolvedIssuesCount();
- totalByRuleKey.get(rule.ruleKey().toString()).incrementResolvedIssuesCount();
+ totalByRuleKey.get(rule.key().toString()).incrementResolvedIssuesCount();
totalBySeverity.get(severity.toString()).incrementResolvedIssuesCount();
}
if (!ruleReportByRuleKey.containsKey(reportRuleKey)) {
ruleReportByRuleKey.put(reportRuleKey, new RuleReport(reportRuleKey));
}
- if (!totalByRuleKey.containsKey(reportRuleKey.getRule().ruleKey().toString())) {
- totalByRuleKey.put(reportRuleKey.getRule().ruleKey().toString(), new IssueVariation());
+ if (!totalByRuleKey.containsKey(reportRuleKey.getRule().key().toString())) {
+ totalByRuleKey.put(reportRuleKey.getRule().key().toString(), new IssueVariation());
}
if (!totalBySeverity.containsKey(reportRuleKey.getSeverity().toString())) {
totalBySeverity.put(reportRuleKey.getSeverity().toString(), new IssueVariation());
*/
package org.sonar.batch.scan.report;
+import org.sonar.api.batch.rule.Rule;
+
import com.google.common.collect.Maps;
import org.sonar.api.issue.Issue;
-import org.sonar.api.rules.Rule;
import org.sonar.api.rules.RulePriority;
import org.sonar.batch.index.BatchComponent;
*/
package org.sonar.batch.scan.report;
+import org.sonar.api.batch.rule.Rule;
+
+import org.sonar.api.batch.rule.Rules;
import org.apache.commons.lang.StringEscapeUtils;
import org.sonar.api.batch.BatchSide;
import org.sonar.api.rule.RuleKey;
-import org.sonar.api.rules.Rule;
-import org.sonar.api.rules.RuleFinder;
import javax.annotation.CheckForNull;
@BatchSide
public class RuleNameProvider {
- private RuleFinder ruleFinder;
+ private Rules rules;
- public RuleNameProvider(RuleFinder ruleFinder) {
- this.ruleFinder = ruleFinder;
+ public RuleNameProvider(Rules rules) {
+ this.rules = rules;
}
@CheckForNull
private String nameFromDB(RuleKey ruleKey) {
- Rule r = ruleFinder.findByKey(ruleKey);
- return r != null ? r.getName() : null;
+ Rule r = rules.find(ruleKey);
+ return r != null ? r.name() : null;
}
public String nameForHTML(RuleKey ruleKey) {
}
public String nameForHTML(Rule rule) {
- String name = nameFromDB(RuleKey.of(rule.getRepositoryKey(), rule.getKey()));
- return StringEscapeUtils.escapeHtml(name != null ? name : rule.getName());
+ return StringEscapeUtils.escapeHtml(rule.name());
}
}
*/
package org.sonar.batch.scan.report;
+import org.sonar.api.batch.rule.Rule;
+
import org.apache.commons.lang.builder.ToStringBuilder;
-import org.sonar.api.rules.Rule;
public final class RuleReport {
private final ReportRuleKey reportRuleKey;
@Test
public void fail_if_rule_has_no_name_and_issue_has_no_message() {
- ruleBuilder.add(RuleKey.of("squid", "AvoidCycle"));
+ ruleBuilder.add(SQUID_RULE_KEY).setInternalKey(SQUID_RULE_KEY.rule());
initModuleIssues();
DefaultIssue issue = new DefaultIssue().setRuleKey(SQUID_RULE_KEY).setMessage("");
*/
package org.sonar.batch.mediumtest.deprecated;
+import org.sonar.xoo.rule.XooRulesDefinition;
+
import com.google.common.collect.ImmutableMap;
import java.io.File;
import java.io.IOException;
public BatchMediumTester tester = BatchMediumTester.builder()
.registerPlugin("xoo", new XooPlugin())
+ .addRules(new XooRulesDefinition())
.addDefaultQProfile("xoo", "Sonar Way")
.activateRule(new ActiveRule("xoo", "DeprecatedResourceApi", null, "One issue per line", "MAJOR", null, "xoo"))
.build();
.start();
assertThat(result.issues()).extracting("componentKey", "message", "line").containsOnly(
- tuple("com.foo.project:src/sample.xoo", "One issue per line", null),
+ tuple("com.foo.project:src/sample.xoo", "Issue created using deprecated API", null),
tuple("com.foo.project:src/sample.xoo", "Issue created using deprecated API", 1),
- tuple("com.foo.project:src/package/sample.xoo", "One issue per line", null),
+ tuple("com.foo.project:src/package/sample.xoo", "Issue created using deprecated API", null),
tuple("com.foo.project:src/package/sample.xoo", "Issue created using deprecated API", 1),
tuple("com.foo.project:src", "Issue created using deprecated API", null),
tuple("com.foo.project:src/package", "Issue created using deprecated API", null));
*/
package org.sonar.batch.mediumtest.fs;
+import org.sonar.xoo.rule.XooRulesDefinition;
+
import com.google.common.collect.ImmutableMap;
import org.apache.commons.io.FileUtils;
import org.junit.After;
public BatchMediumTester tester = BatchMediumTester.builder()
.registerPlugin("xoo", new XooPlugin())
+ .addRules(new XooRulesDefinition())
.addDefaultQProfile("xoo", "Sonar Way")
.bootstrapProperties(ImmutableMap.of(CoreProperties.ANALYSIS_MODE, CoreProperties.ANALYSIS_MODE_PREVIEW))
.setPreviousAnalysisDate(new Date())
*/
package org.sonar.batch.mediumtest.fs;
+import org.sonar.xoo.rule.XooRulesDefinition;
+
import com.google.common.collect.ImmutableMap;
import org.apache.commons.io.FileUtils;
import org.junit.After;
public BatchMediumTester tester = BatchMediumTester.builder()
.registerPlugin("xoo", new XooPlugin())
.addDefaultQProfile("xoo", "Sonar Way")
+ .addRules(new XooRulesDefinition())
.activateRule(new ActiveRule("xoo", "RandomAccessIssue", null, "One issue per line", "MAJOR", null, "xoo"))
.build();
*/
package org.sonar.batch.mediumtest.issues;
+import org.sonar.batch.protocol.input.Rule;
+
+import org.sonar.xoo.rule.XooRulesDefinition;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.io.FileUtils;
import org.junit.After;
public BatchMediumTester tester = BatchMediumTester.builder()
.registerPlugin("xoo", new XooPlugin())
+ .addRules(new XooRulesDefinition())
.addDefaultQProfile("xoo", "Sonar Way")
+ .addRule(new Rule("xoo:TemplateRule_1234", "xoo", "TemplateRule_1234", "A template rule", "MAJOR", "xoo"))
+ .addRule(new Rule("xoo:TemplateRule_1235", "xoo", "TemplateRule_1235", "Another template rule", "MAJOR", "xoo"))
.activateRule(new ActiveRule("xoo", "TemplateRule_1234", "TemplateRule", "A template rule", "MAJOR", null, "xoo").addParam("line", "1"))
.activateRule(new ActiveRule("xoo", "TemplateRule_1235", "TemplateRule", "Another template rule", "MAJOR", null, "xoo").addParam("line", "2"))
.build();
*/
package org.sonar.batch.mediumtest.issues;
+import org.sonar.xoo.rule.XooRulesDefinition;
+
import com.google.common.collect.ImmutableMap;
import org.apache.commons.io.FileUtils;
import org.junit.After;
public BatchMediumTester tester = BatchMediumTester.builder()
.registerPlugin("xoo", new XooPlugin())
.addDefaultQProfile("xoo", "Sonar Way")
+ .addRules(new XooRulesDefinition())
.activateRule(new ActiveRule("xoo", "OneIssuePerLine", null, "One issue per line", "MAJOR", "OneIssuePerLine.internal", "xoo"))
.build();
*/
package org.sonar.batch.mediumtest.issues;
+import org.sonar.xoo.rule.XooRulesDefinition;
+
import com.google.common.collect.ImmutableMap;
import org.apache.commons.io.FileUtils;
import org.junit.After;
public BatchMediumTester tester = BatchMediumTester.builder()
.registerPlugin("xoo", new XooPlugin())
.addDefaultQProfile("xoo", "Sonar Way")
+ .addRules(new XooRulesDefinition())
.activateRule(new ActiveRule("xoo", "OneIssueOnDirPerFile", null, "One issue per line", "MINOR", "xoo", "xoo"))
.build();
*/
package org.sonar.batch.mediumtest.issues;
+import org.sonar.xoo.rule.XooRulesDefinition;
+
+import org.sonar.batch.protocol.input.Rule;
+
import java.io.File;
+
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.sonar.batch.mediumtest.TaskResult;
import org.sonar.batch.protocol.input.ActiveRule;
import org.sonar.xoo.XooPlugin;
-
import static org.assertj.core.api.Assertions.assertThat;
public class MultilineIssuesMediumTest {
public BatchMediumTester tester = BatchMediumTester.builder()
.registerPlugin("xoo", new XooPlugin())
+ .addRules(new XooRulesDefinition())
+ .addRule(new Rule("xoo:MultilineIssue", "xoo", null, "Multinile Issue", "MAJOR", "xoo"))
.addDefaultQProfile("xoo", "Sonar Way")
.activateRule(new ActiveRule("xoo", "MultilineIssue", null, "Multinile Issue", "MAJOR", null, "xoo"))
.build();
*/
package org.sonar.batch.mediumtest.preview;
+import org.sonar.xoo.rule.XooRulesDefinition;
+
import com.google.common.collect.ImmutableMap;
import org.junit.After;
import org.junit.Before;
public BatchMediumTester tester = BatchMediumTester.builder()
.bootstrapProperties(ImmutableMap.of(CoreProperties.ANALYSIS_MODE, CoreProperties.ANALYSIS_MODE_PREVIEW))
.registerPlugin("xoo", new XooPlugin())
+ .addRules(new XooRulesDefinition())
.addDefaultQProfile("xoo", "Sonar Way")
.activateRule(new ActiveRule("xoo", "OneIssuePerLine", null, "One issue per line", "MAJOR", "my/internal/key", "xoo"))
.setPreviousAnalysisDate(new Date())
*/
package org.sonar.batch.mediumtest.preview;
+import org.sonar.xoo.rule.XooRulesDefinition;
+
import com.google.common.collect.ImmutableMap;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
.builder()
.bootstrapProperties(ImmutableMap.of(CoreProperties.ANALYSIS_MODE, CoreProperties.ANALYSIS_MODE_INCREMENTAL))
.registerPlugin("xoo", new XooPlugin())
+ .addRules(new XooRulesDefinition())
.addDefaultQProfile("xoo", "Sonar Way")
.activateRule(new ActiveRule("xoo", "OneIssuePerLine", null, "One issue per line", "MAJOR", null, "xoo"))
.activateRule(new ActiveRule("manual", "MyManualIssue", null, "My manual issue", "MAJOR", null, null))
*/
package org.sonar.batch.mediumtest.preview;
+import org.sonar.batch.protocol.input.Rule;
+
+import org.sonar.xoo.rule.XooRulesDefinition;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
-import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.CoreProperties;
public class PreviewAndReportsMediumTest {
- @Rule
+ @org.junit.Rule
public TemporaryFolder temp = new TemporaryFolder();
- @Rule
+ @org.junit.Rule
public LogTester logTester = new LogTester();
private static SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
.bootstrapProperties(ImmutableMap.of(CoreProperties.ANALYSIS_MODE, CoreProperties.ANALYSIS_MODE_PREVIEW))
.registerPlugin("xoo", new XooPlugin())
.addDefaultQProfile("xoo", "Sonar Way")
+ .addRules(new XooRulesDefinition())
+ .addRule(new Rule("manual:MyManualIssue", "manual", "MyManualIssue", "My manual issue", "MAJOR", null))
.activateRule(new ActiveRule("xoo", "OneIssuePerLine", null, "One issue per line", "MAJOR", null, "xoo"))
.activateRule(new ActiveRule("manual", "MyManualIssue", null, "My manual issue", "MAJOR", null, null))
.setPreviousAnalysisDate(new Date())
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 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.batch.rule;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.LinkedList;
+
+import static org.mockito.Matchers.contains;
+import static org.assertj.core.api.Assertions.assertThat;
+import org.sonar.batch.bootstrap.WSLoader;
+import org.junit.Test;
+import org.sonar.batch.protocol.input.Rule;
+import org.sonar.batch.protocol.input.RulesSearchResult;
+
+public class DefaultRulesLoaderTest {
+ @Test
+ public void testLoadingJson() throws IOException {
+ Rule rule1 = new Rule("squid:S1194", "squid", "S1194", "\"java.lang.Error\" should not be extended", "MAJOR", "java");
+ Rule rule2 = new Rule("squid:ObjectFinalizeOverridenCallsSuperFinalizeCheck", "squid", "ObjectFinalizeOverridenCallsSuperFinalizeCheck",
+ "super.finalize() should be called at the end of Object.finalize() implementations", "BLOCKER", "java");
+
+ // generate json
+ RulesSearchResult rulesSearch = new RulesSearchResult();
+ rulesSearch.setRules(Arrays.asList(rule1, rule2));
+ String json = rulesSearch.toJson();
+
+ RulesSearchResult empty = new RulesSearchResult();
+ empty.setRules(new LinkedList<Rule>());
+ String emptyJson = empty.toJson();
+
+ WSLoader wsLoader = mock(WSLoader.class);
+ when(wsLoader.loadString(contains("p=1"))).thenReturn(json);
+ when(wsLoader.loadString(contains("p=2"))).thenReturn(emptyJson);
+
+ // load
+ RulesLoader loader = new DefaultRulesLoader(wsLoader);
+ RulesSearchResult rules = loader.load();
+
+ assertThat(rules.toJson()).isEqualTo(json);
+ }
+}
*/
package org.sonar.batch.rule;
+import org.sonar.api.batch.rule.internal.RulesBuilder;
+
+import org.sonar.api.batch.rule.Rules;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
-import org.sonar.api.batch.rule.ActiveRules;
-import org.sonar.api.batch.rule.internal.ActiveRulesBuilder;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rules.RuleQuery;
-
import static org.assertj.core.api.Assertions.assertThat;
public class RuleFinderCompatibilityTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
- private ActiveRules activeRules = new ActiveRulesBuilder()
- .create(RuleKey.of("repo1", "rule1"))
- .activate()
- .create(RuleKey.of("repo1", "rule2"))
- .setInternalKey("rule2_internal")
- .activate()
- .create(RuleKey.of("repo2", "rule1"))
- .activate()
- .build();
+ private Rules rules;
private RuleFinderCompatibility ruleFinder;
@Before
public void prepare() {
- ruleFinder = new RuleFinderCompatibility(activeRules);
+ RulesBuilder builder = new RulesBuilder();
+ builder.add(RuleKey.of("repo1", "rule1"));
+ builder.add(RuleKey.of("repo1", "rule2")).setInternalKey("rule2_internal");
+ builder.add(RuleKey.of("repo2", "rule1"));
+ rules = builder.build();
+
+ ruleFinder = new RuleFinderCompatibility(rules);
}
@Test
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 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.batch.rule;
+
+import org.assertj.core.api.Condition;
+
+import org.sonar.api.batch.rule.Rules;
+
+import java.util.Arrays;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.when;
+import static org.mockito.Mockito.mock;
+import org.sonar.batch.protocol.input.Rule;
+import org.sonar.batch.protocol.input.RulesSearchResult;
+import org.junit.Test;
+
+public class RulesProviderTest {
+ @Test
+ public void testRuleTranslation() {
+ final Rule testRule = new Rule("repo1:key1", "repo1", "key1", "name", "severity", "language");
+
+ RulesSearchResult loadResult = new RulesSearchResult();
+ loadResult.setRules(Arrays.asList(testRule));
+ RulesLoader loader = mock(RulesLoader.class);
+ when(loader.load()).thenReturn(loadResult);
+
+ RulesProvider provider = new RulesProvider();
+ Rules rules = provider.provide(loader);
+
+ assertThat(rules.findAll()).hasSize(1);
+ assertThat(rules.findAll()).are(new Condition<org.sonar.api.batch.rule.Rule>() {
+
+ @Override
+ public boolean matches(org.sonar.api.batch.rule.Rule value) {
+ return value.key().rule().equals(testRule.internalKey()) &&
+ value.internalKey().equals(testRule.internalKey()) &&
+ value.name().equals(testRule.name()) &&
+ value.severity().equals(testRule.severity()) &&
+ value.key().repository().equals(testRule.repositoryKey());
+ }
+ });
+ }
+}
*/
package org.sonar.batch.scan.report;
+import org.sonar.api.batch.rule.internal.RulesBuilder;
+
+import org.sonar.api.batch.rule.Rules;
import com.google.common.collect.Lists;
import com.google.common.io.Resources;
import org.junit.Before;
import org.sonar.api.batch.fs.internal.DefaultFileSystem;
import org.sonar.api.batch.fs.internal.DefaultInputDir;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
-import org.sonar.api.batch.rule.ActiveRules;
-import org.sonar.api.batch.rule.internal.ActiveRulesBuilder;
import org.sonar.api.config.Settings;
import org.sonar.api.issue.Issue;
import org.sonar.core.issue.DefaultIssue;
Resource resource = mock(Resource.class);
DefaultFileSystem fs;
Server server = mock(Server.class);
- ActiveRules activeRules = mock(ActiveRules.class);
+ Rules rules = mock(Rules.class);
Settings settings = new Settings();
IssueCache issueCache = mock(IssueCache.class);
private UserRepository userRepository;
moduleA.setParent(rootModule).setPath("core");
Project moduleB = new Project("struts-ui");
moduleB.setParent(rootModule).setPath("ui");
- activeRules = new ActiveRulesBuilder()
- .create(RuleKey.of("squid", "AvoidCycles")).setName("Avoid Cycles").activate()
- .build();
- jsonReport = new JSONReport(settings, fs, server, activeRules, issueCache, rootModule, fileCache, userRepository);
+
+ RulesBuilder builder = new RulesBuilder();
+ builder.add(RuleKey.of("squid", "AvoidCycles")).setName("Avoid Cycles");
+ rules = builder.build();
+ jsonReport = new JSONReport(settings, fs, server, rules, issueCache, rootModule, fileCache, userRepository);
}
@Test
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 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.batch.scan.report;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import static org.mockito.Matchers.any;
+
+import org.sonar.api.rule.RuleKey;
+import org.sonar.api.batch.rule.Rule;
+import org.junit.Test;
+import org.junit.Before;
+import org.sonar.api.batch.rule.Rules;
+
+public class RuleNameProviderTest {
+ RuleNameProvider provider;
+ Rules rules;
+ Rule rule;
+ RuleKey ruleKey;
+
+ @Before
+ public void setUp() {
+ ruleKey = mock(RuleKey.class);
+ rule = mock(Rule.class);
+ rules = mock(Rules.class);
+ provider = new RuleNameProvider(rules);
+
+ when(ruleKey.rule()).thenReturn("ruleKey");
+ when(ruleKey.repository()).thenReturn("repoKey");
+
+ when(rule.name()).thenReturn("name");
+ when(rule.key()).thenReturn(ruleKey);
+
+ when(rules.find(any(RuleKey.class))).thenReturn(rule);
+ }
+
+ @Test
+ public void testNameForHTML() {
+ assertThat(provider.nameForHTML(rule)).isEqualTo(rule.name());
+ assertThat(provider.nameForHTML(ruleKey)).isEqualTo(rule.name());
+ }
+
+ @Test
+ public void testNameForJS() {
+ assertThat(provider.nameForJS("repoKey:ruleKey")).isEqualTo(rule.name());
+ }
+
+}
*/
Collection<Rule> findByRepository(String repository);
+ Rule findByInternalKey(String repository, String internalKey);
+
}
@Immutable
public class DefaultActiveRule implements ActiveRule {
private final RuleKey ruleKey;
- private final String name;
private final String severity;
private final String internalKey;
private final String language;
DefaultActiveRule(NewActiveRule newActiveRule) {
this.severity = newActiveRule.severity;
- this.name = newActiveRule.name;
this.internalKey = newActiveRule.internalKey;
this.templateRuleKey = newActiveRule.templateRuleKey;
this.ruleKey = newActiveRule.ruleKey;
return ruleKey;
}
- public String name() {
- return name;
- }
-
@Override
public String severity() {
return severity;
*/
package org.sonar.api.batch.rule.internal;
+import org.sonar.api.batch.rule.Rule;
+import com.google.common.collect.ImmutableTable;
+import com.google.common.collect.Table;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ListMultimap;
import org.apache.commons.lang.StringUtils;
-import org.sonar.api.batch.rule.Rule;
import org.sonar.api.batch.rule.Rules;
import org.sonar.api.rule.RuleKey;
// TODO use disk-backed cache (persistit) instead of full in-memory cache ?
private final ListMultimap<String, Rule> rulesByRepository;
+ private final Table<String, String, Rule> rulesByRepositoryAndInternalKey;
DefaultRules(Collection<NewRule> newRules) {
ImmutableListMultimap.Builder<String, Rule> builder = ImmutableListMultimap.builder();
+ ImmutableTable.Builder<String, String, Rule> tableBuilder = ImmutableTable.builder();
+
for (NewRule newRule : newRules) {
DefaultRule r = new DefaultRule(newRule);
builder.put(r.key().repository(), r);
+ if (r.internalKey() != null) {
+ tableBuilder.put(r.key().repository(), r.internalKey(), r);
+ }
}
+
rulesByRepository = builder.build();
+ rulesByRepositoryAndInternalKey = tableBuilder.build();
}
@Override
public Collection<Rule> findByRepository(String repository) {
return rulesByRepository.get(repository);
}
+
+ @Override
+ public Rule findByInternalKey(String repository, String internalKey) {
+ return rulesByRepositoryAndInternalKey.get(repository, internalKey);
+ }
}
ActiveRule squid1 = activeRules.find(RuleKey.of("squid", "S0001"));
assertThat(squid1.ruleKey().repository()).isEqualTo("squid");
assertThat(squid1.ruleKey().rule()).isEqualTo("S0001");
- assertThat(((DefaultActiveRule) squid1).name()).isEqualTo("My Rule");
assertThat(squid1.severity()).isEqualTo(Severity.CRITICAL);
assertThat(squid1.internalKey()).isEqualTo("__S0001__");
assertThat(squid1.params()).hasSize(1);