repo stringlengths 1 191 ⌀ | file stringlengths 23 351 | code stringlengths 0 5.32M | file_length int64 0 5.32M | avg_line_length float64 0 2.9k | max_line_length int64 0 288k | extension_type stringclasses 1 value |
|---|---|---|---|---|---|---|
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/ChecksSensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import org.sonar.api.batch.fs.FilePredicates;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.InputFile.Type;
import org.sonar.api.batch.rule.CheckFactory;
import org.sonar.api.batch.rule.Checks;
import org.sonar.api.batch.sensor.Sensor;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.xoo.Xoo;
import org.sonar.xoo.checks.Check;
public class ChecksSensor implements Sensor {
private final CheckFactory checkFactory;
public ChecksSensor(CheckFactory checkFactory) {
this.checkFactory = checkFactory;
}
@Override
public void describe(SensorDescriptor descriptor) {
descriptor
.name("ChecksSensor")
.onlyOnLanguage(Xoo.KEY)
.createIssuesForRuleRepositories(XooRulesDefinition.XOO_REPOSITORY)
.onlyOnFileType(InputFile.Type.MAIN);
}
@Override
public void execute(SensorContext context) {
Checks<Check> checks = checkFactory.create(XooRulesDefinition.XOO_REPOSITORY);
checks.addAnnotatedChecks((Object[]) Check.ALL);
FilePredicates p = context.fileSystem().predicates();
for (InputFile file : context.fileSystem().inputFiles(p.and(p.hasLanguages(Xoo.KEY), p.hasType(Type.MAIN)))) {
for (Check check : checks.all()) {
check.execute(context, file, checks.ruleKey(check));
}
}
}
}
| 2,235 | 34.492063 | 114 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/CreateIssueByInternalKeySensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import org.sonar.api.batch.fs.FilePredicates;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.InputFile.Type;
import org.sonar.api.batch.rule.ActiveRule;
import org.sonar.api.batch.sensor.Sensor;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.api.batch.sensor.issue.NewIssue;
import org.sonar.xoo.Xoo;
public class CreateIssueByInternalKeySensor implements Sensor {
private static final String INTERNAL_KEY_PROPERTY = "sonar.xoo.internalKey";
@Override
public void describe(SensorDescriptor descriptor) {
descriptor
.name("CreateIssueByInternalKeySensor")
.onlyOnLanguages(Xoo.KEY)
.createIssuesForRuleRepositories(XooRulesDefinition.XOO_REPOSITORY);
}
@Override
public void execute(SensorContext context) {
FileSystem fs = context.fileSystem();
FilePredicates p = fs.predicates();
for (InputFile file : fs.inputFiles(p.and(p.hasLanguages(Xoo.KEY), p.hasType(Type.MAIN)))) {
createIssues(file, context);
}
}
private static void createIssues(InputFile file, SensorContext context) {
ActiveRule rule = context.activeRules().findByInternalKey(XooRulesDefinition.XOO_REPOSITORY,
context.config().get(INTERNAL_KEY_PROPERTY).orElse(null));
if (rule != null) {
NewIssue newIssue = context.newIssue();
newIssue
.forRule(rule.ruleKey())
.at(newIssue.newLocation()
.on(file)
.message("This issue is generated on each file"))
.save();
}
}
}
| 2,479 | 35.470588 | 96 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/CustomMessageSensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.rule.ActiveRules;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.issue.NewIssue;
import org.sonar.api.batch.sensor.issue.NewIssueLocation;
import org.sonar.api.config.Configuration;
import org.sonar.api.rule.RuleKey;
public class CustomMessageSensor extends AbstractXooRuleSensor {
public static final String RULE_KEY = "CustomMessage";
private static final String MESSAGE_PROPERTY = "sonar.customMessage.message";
private final Configuration settings;
public CustomMessageSensor(Configuration settings, FileSystem fs, ActiveRules activeRules) {
super(fs, activeRules);
this.settings = settings;
}
@Override
protected String getRuleKey() {
return RULE_KEY;
}
@Override protected void processFile(InputFile inputFile, SensorContext context, RuleKey ruleKey, String languageKey) {
NewIssue newIssue = context.newIssue()
.forRule(ruleKey);
NewIssueLocation location = newIssue.newLocation().on(inputFile);
settings.get(MESSAGE_PROPERTY).ifPresent(location::message);
newIssue
.at(location)
.save();
}
}
| 2,093 | 33.327869 | 121 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/HasTagSensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.rule.ActiveRules;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.issue.NewIssue;
import org.sonar.api.rule.RuleKey;
/**
* Generate issues on all the occurrences of a given tag in xoo sources.
*/
public class HasTagSensor extends AbstractXooRuleSensor {
public static final String RULE_KEY = "HasTag";
private static final String EFFORT_TO_FIX_PROPERTY = "sonar.hasTag.effortToFix";
private final ActiveRules activeRules;
public HasTagSensor(FileSystem fs, ActiveRules activeRules) {
super(fs, activeRules);
this.activeRules = activeRules;
}
@Override
protected String getRuleKey() {
return RULE_KEY;
}
@Override
protected void processFile(InputFile inputFile, SensorContext context, RuleKey ruleKey, String languageKey) {
org.sonar.api.batch.rule.ActiveRule activeRule = activeRules.find(ruleKey);
String tag = activeRule.param("tag");
if (tag == null) {
throw new IllegalStateException("Rule is badly configured. The parameter 'tag' is missing.");
}
try {
int[] lineCounter = {1};
try (InputStreamReader isr = new InputStreamReader(inputFile.inputStream(), inputFile.charset());
BufferedReader reader = new BufferedReader(isr)) {
reader.lines().forEachOrdered(lineStr -> {
int startIndex = -1;
while ((startIndex = lineStr.indexOf(tag, startIndex + 1)) != -1) {
NewIssue newIssue = context.newIssue();
newIssue
.forRule(ruleKey)
.gap(context.config().getDouble(EFFORT_TO_FIX_PROPERTY).orElse(null))
.at(newIssue.newLocation()
.on(inputFile)
.at(inputFile.newRange(lineCounter[0], startIndex, lineCounter[0], startIndex + tag.length())))
.save();
}
lineCounter[0]++;
});
}
} catch (IOException e) {
throw new IllegalStateException("Fail to process " + inputFile, e);
}
}
}
| 3,061 | 35.452381 | 111 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/MarkAsUnchangedSensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import org.sonar.api.batch.fs.FilePredicates;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.sensor.Sensor;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.xoo.Xoo;
import org.sonar.xoo.Xoo2;
public class MarkAsUnchangedSensor implements Sensor {
public static final String ACTIVATE_MARK_AS_UNCHANGED = "sonar.markAsUnchanged";
@Override
public void describe(SensorDescriptor descriptor) {
descriptor.name("Mark As Unchanged Sensor")
.onlyOnLanguages(Xoo.KEY, Xoo2.KEY)
.onlyWhenConfiguration(c -> c.getBoolean(ACTIVATE_MARK_AS_UNCHANGED).orElse(false))
.processesFilesIndependently();
}
@Override
public void execute(SensorContext context) {
FileSystem fs = context.fileSystem();
FilePredicates p = fs.predicates();
for (InputFile f : fs.inputFiles(p.all())) {
context.markAsUnchanged(f);
}
}
}
| 1,862 | 35.529412 | 89 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/MultilineHotspotSensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
public class MultilineHotspotSensor extends MultilineIssuesSensor {
public static final String RULE_KEY = "MultilineHotspot";
@Override
public String getRuleKey() {
return RULE_KEY;
}
}
| 1,072 | 33.612903 | 75 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/MultilineIssuesSensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.api.batch.fs.FilePredicates;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.InputFile.Type;
import org.sonar.api.batch.fs.TextPointer;
import org.sonar.api.batch.sensor.Sensor;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.api.batch.sensor.issue.MessageFormatting;
import org.sonar.api.batch.sensor.issue.NewIssue;
import org.sonar.api.batch.sensor.issue.NewIssue.FlowType;
import org.sonar.api.batch.sensor.issue.NewIssueLocation;
import org.sonar.api.batch.sensor.issue.NewMessageFormatting;
import org.sonar.api.rule.RuleKey;
import org.sonar.xoo.Xoo;
import static org.sonar.api.batch.sensor.issue.NewIssue.FlowType.DATA;
import static org.sonar.api.batch.sensor.issue.NewIssue.FlowType.EXECUTION;
import static org.sonar.api.utils.Preconditions.checkState;
public class MultilineIssuesSensor implements Sensor {
public static final String RULE_KEY = "MultilineIssue";
private static final Pattern START_ISSUE_PATTERN = Pattern.compile("\\{xoo-start-issue:([0-9]+)\\}");
private static final Pattern END_ISSUE_PATTERN = Pattern.compile("\\{xoo-end-issue:([0-9]+)\\}");
private static final Pattern START_FLOW_PATTERN = Pattern.compile("\\{xoo-start-flow:([0-9]+):([0-9]+):([0-9]+)\\}");
private static final Pattern END_FLOW_PATTERN = Pattern.compile("\\{xoo-end-flow:([0-9]+):([0-9]+):([0-9]+)\\}");
private static final Pattern START_DATA_FLOW_PATTERN = Pattern.compile("\\{xoo-start-data-flow:([0-9]+):([0-9]+):([0-9]+)\\}");
private static final Pattern END_DATA_FLOW_PATTERN = Pattern.compile("\\{xoo-end-data-flow:([0-9]+):([0-9]+):([0-9]+)\\}");
private static final Pattern START_EXECUTION_FLOW_PATTERN = Pattern.compile("\\{xoo-start-execution-flow:([0-9]+):([0-9]+):([0-9]+)\\}");
private static final Pattern END_EXECUTION_FLOW_PATTERN = Pattern.compile("\\{xoo-end-execution-flow:([0-9]+):([0-9]+):([0-9]+)\\}");
@Override
public void describe(SensorDescriptor descriptor) {
descriptor.name("Multiline Issues").onlyOnLanguages(Xoo.KEY).createIssuesForRuleRepositories(XooRulesDefinition.XOO_REPOSITORY);
}
@Override
public void execute(SensorContext context) {
FileSystem fs = context.fileSystem();
FilePredicates p = fs.predicates();
for (InputFile file : fs.inputFiles(p.and(p.hasLanguages(Xoo.KEY), p.hasType(Type.MAIN)))) {
createIssues(file, context);
}
}
public String getRuleKey() {
return RULE_KEY;
}
private void createIssues(InputFile file, SensorContext context) {
Collection<ParsedIssue> issues = parseIssues(file);
FlowIndex flowIndex = new FlowIndex();
parseFlows(flowIndex, file, START_FLOW_PATTERN, END_FLOW_PATTERN, null);
parseFlows(flowIndex, file, START_DATA_FLOW_PATTERN, END_DATA_FLOW_PATTERN, DATA);
parseFlows(flowIndex, file, START_EXECUTION_FLOW_PATTERN, END_EXECUTION_FLOW_PATTERN, EXECUTION);
createIssues(file, context, issues, flowIndex);
}
private void createIssues(InputFile file, SensorContext context, Collection<ParsedIssue> parsedIssues, FlowIndex flowIndex) {
RuleKey ruleKey = RuleKey.of(XooRulesDefinition.XOO_REPOSITORY, getRuleKey());
for (ParsedIssue parsedIssue : parsedIssues) {
NewIssue newIssue = context.newIssue().forRule(ruleKey);
NewIssueLocation primaryLocation = newIssue.newLocation();
String message = "Primary location of the issue in xoo code";
List<NewMessageFormatting> newMessageFormattings = formatIssueMessage(message, primaryLocation.newMessageFormatting());
newIssue.at(primaryLocation.on(file)
.at(file.newRange(parsedIssue.start, parsedIssue.end))
.message(message, newMessageFormattings));
for (ParsedFlow flow : flowIndex.getFlows(parsedIssue.issueId)) {
List<NewIssueLocation> flowLocations = new LinkedList<>();
for (ParsedFlowLocation flowLocation : flow.getLocations()) {
String locationMessage = "Xoo code, flow step #" + flowLocation.flowLocationId;
NewIssueLocation newIssueLocation = newIssue.newLocation();
List<NewMessageFormatting> locationMessageFormattings = formatIssueMessage(locationMessage, newIssueLocation.newMessageFormatting());
newIssueLocation
.on(file)
.at(file.newRange(flowLocation.start, flowLocation.end))
.message(locationMessage, locationMessageFormattings);
flowLocations.add(newIssueLocation);
}
if (flow.getType() != null) {
newIssue.addFlow(flowLocations, flow.getType(), "flow #" + flow.getFlowId());
} else {
newIssue.addFlow(flowLocations);
}
}
newIssue.save();
}
}
private static List<NewMessageFormatting> formatIssueMessage(String message, NewMessageFormatting newMessageFormatting) {
int startIndex = message.toLowerCase().indexOf("xoo");
if(startIndex == -1) {
return List.of();
}
int endIndex = startIndex + "xoo".length();
return List.of(newMessageFormatting.start(startIndex).end(endIndex).type(MessageFormatting.Type.CODE));
}
private static Collection<ParsedIssue> parseIssues(InputFile file) {
Map<Integer, ParsedIssue> issuesById = new HashMap<>();
int currentLine = 0;
try {
for (String lineStr : file.contents().split("\\r?\\n")) {
currentLine++;
Matcher m = START_ISSUE_PATTERN.matcher(lineStr);
while (m.find()) {
Integer issueId = Integer.parseInt(m.group(1));
issuesById.computeIfAbsent(issueId, ParsedIssue::new).start = file.newPointer(currentLine, m.end());
}
m = END_ISSUE_PATTERN.matcher(lineStr);
while (m.find()) {
Integer issueId = Integer.parseInt(m.group(1));
issuesById.computeIfAbsent(issueId, ParsedIssue::new).end = file.newPointer(currentLine, m.start());
}
}
} catch (IOException e) {
throw new IllegalStateException("Unable to read file", e);
}
return issuesById.values();
}
private void parseFlows(FlowIndex flowIndex, InputFile file, Pattern flowStartPattern, Pattern flowEndPattern, @Nullable FlowType flowType) {
int currentLine = 0;
try {
for (String lineStr : file.contents().split("\\r?\\n")) {
currentLine++;
Matcher m = flowStartPattern.matcher(lineStr);
while (m.find()) {
ParsedFlowLocation flowLocation = new ParsedFlowLocation(Integer.parseInt(m.group(1)), Integer.parseInt(m.group(2)), Integer.parseInt(m.group(3)));
flowLocation.start = file.newPointer(currentLine, m.end());
flowIndex.addLocation(flowLocation, flowType);
}
m = flowEndPattern.matcher(lineStr);
while (m.find()) {
ParsedFlowLocation flowLocation = new ParsedFlowLocation(Integer.parseInt(m.group(1)), Integer.parseInt(m.group(2)), Integer.parseInt(m.group(3)));
flowLocation.end = file.newPointer(currentLine, m.start());
flowIndex.addLocation(flowLocation, flowType);
}
}
} catch (IOException e) {
throw new IllegalStateException("Unable to read file", e);
}
}
private static class ParsedIssue {
private final int issueId;
private TextPointer start;
private TextPointer end;
private ParsedIssue(int issueId) {
this.issueId = issueId;
}
}
private static class FlowIndex {
private final Map<Integer, IssueFlows> flowsByIssueId = new HashMap<>();
public void addLocation(ParsedFlowLocation flowLocation, @Nullable FlowType type) {
flowsByIssueId.computeIfAbsent(flowLocation.issueId, issueId -> new IssueFlows()).addLocation(flowLocation, type);
}
public Collection<ParsedFlow> getFlows(int issueId) {
return Optional.ofNullable(flowsByIssueId.get(issueId)).map(IssueFlows::getFlows).orElse(Collections.emptyList());
}
}
private static class IssueFlows {
private final Map<Integer, ParsedFlow> flowById = new TreeMap<>();
private void addLocation(ParsedFlowLocation flowLocation, @Nullable FlowType type) {
flowById.computeIfAbsent(flowLocation.flowId, flowId -> new ParsedFlow(flowId, type)).addLocation(flowLocation);
}
Collection<ParsedFlow> getFlows() {
return flowById.values();
}
}
private static class ParsedFlow {
private final int id;
private final FlowType type;
private final Map<Integer, ParsedFlowLocation> locationsById = new TreeMap<>();
private String description;
private ParsedFlow(int id, @Nullable FlowType type) {
this.id = id;
this.type = type;
}
private void addLocation(ParsedFlowLocation flowLocation) {
if (locationsById.containsKey(flowLocation.flowLocationId)) {
checkState(flowLocation.end != null, "Existing flow should be the end");
locationsById.get(flowLocation.flowLocationId).end = flowLocation.end;
} else {
checkState(flowLocation.start != null, "New flow should be the start");
locationsById.put(flowLocation.flowLocationId, flowLocation);
}
}
public Collection<ParsedFlowLocation> getLocations() {
return locationsById.values();
}
public void setDescription(@Nullable String description) {
this.description = description;
}
@CheckForNull
public String getDescription() {
return description;
}
@CheckForNull
FlowType getType() {
return type;
}
int getFlowId() {
return id;
}
}
private static class ParsedFlowLocation {
private final int issueId;
private final int flowId;
private final int flowLocationId;
private TextPointer start;
private TextPointer end;
public ParsedFlowLocation(int issueId, int flowId, int flowLocationId) {
this.issueId = issueId;
this.flowId = flowId;
this.flowLocationId = flowLocationId;
}
}
}
| 11,222 | 37.83391 | 157 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/NoSonarSensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import java.io.IOException;
import java.nio.file.Files;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Stream;
import org.sonar.api.batch.Phase;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.sensor.Sensor;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.api.issue.NoSonarFilter;
import org.sonar.xoo.Xoo;
@Phase(name = Phase.Name.PRE)
public class NoSonarSensor implements Sensor {
private static final String NO_SONAR_SENSOR_ACTIVATE = "sonar.nosonarsensor.activate";
private final NoSonarFilter noSonarFilter;
public NoSonarSensor(NoSonarFilter noSonarFilter) {
this.noSonarFilter = noSonarFilter;
}
@Override
public void describe(SensorDescriptor descriptor) {
descriptor
.onlyOnLanguage(Xoo.KEY)
.onlyWhenConfiguration(c -> c.getBoolean(NO_SONAR_SENSOR_ACTIVATE).orElse(false));
}
@Override
public void execute(SensorContext context) {
for (InputFile inputFile : context.fileSystem().inputFiles(context.fileSystem().predicates().hasLanguage(Xoo.KEY))) {
processFile(inputFile);
}
}
private void processFile(InputFile inputFile) {
try {
Set<Integer> noSonarLines = new HashSet<>();
int[] lineCounter = {1};
try (Stream<String> stream = Files.lines(inputFile.path(), inputFile.charset())) {
stream.forEachOrdered(lineStr -> {
if (lineStr.contains("//NOSONAR")) {
noSonarLines.add(lineCounter[0]);
}
lineCounter[0]++;
});
}
noSonarFilter.noSonarInFile(inputFile, noSonarLines);
} catch (IOException e) {
throw new IllegalStateException("Fail to process " + inputFile, e);
}
}
}
| 2,637 | 33.710526 | 121 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/OneBlockerIssuePerFileSensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.rule.ActiveRules;
import org.sonar.api.batch.rule.Severity;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.issue.NewIssue;
import org.sonar.api.rule.RuleKey;
public class OneBlockerIssuePerFileSensor extends AbstractXooRuleSensor {
public static final String RULE_KEY = "OneBlockerIssuePerFile";
public OneBlockerIssuePerFileSensor(FileSystem fs, ActiveRules activeRules) {
super(fs, activeRules);
}
@Override
protected String getRuleKey() {
return RULE_KEY;
}
@Override protected void processFile(InputFile inputFile, SensorContext context, RuleKey ruleKey, String languageKey) {
NewIssue newIssue = context.newIssue()
.overrideSeverity(Severity.BLOCKER)
.forRule(ruleKey);
newIssue.at(newIssue.newLocation()
.on(inputFile)
.message("This issue is generated on each file. Severity is blocker, whatever quality profile"))
.save();
}
}
| 1,920 | 35.245283 | 121 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/OneBugIssuePerLineSensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import org.sonar.api.batch.fs.FilePredicates;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.InputFile.Type;
import org.sonar.api.batch.fs.TextRange;
import org.sonar.api.batch.sensor.Sensor;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.api.batch.sensor.issue.NewIssue;
import org.sonar.api.rule.RuleKey;
import org.sonar.xoo.Xoo;
import org.sonar.xoo.Xoo2;
public class OneBugIssuePerLineSensor implements Sensor {
public static final String RULE_KEY = "OneBugIssuePerLine";
@Override
public void describe(SensorDescriptor descriptor) {
descriptor
.name("One Bug Issue Per Line")
.onlyOnLanguages(Xoo.KEY, Xoo2.KEY)
.createIssuesForRuleRepositories(XooRulesDefinition.XOO_REPOSITORY, XooRulesDefinition.XOO2_REPOSITORY);
}
@Override
public void execute(SensorContext context) {
analyse(context, Xoo.KEY, XooRulesDefinition.XOO_REPOSITORY);
}
private void analyse(SensorContext context, String language, String repo) {
FileSystem fs = context.fileSystem();
FilePredicates p = fs.predicates();
for (InputFile file : fs.inputFiles(p.and(p.hasLanguages(language), p.hasType(Type.MAIN)))) {
createIssues(file, context, repo);
}
}
private static void createIssues(InputFile file, SensorContext context, String repo) {
RuleKey ruleKey = RuleKey.of(repo, RULE_KEY);
for (int line = 1; line <= file.lines(); line++) {
TextRange text = file.selectLine(line);
// do not count empty lines, which can be a pain with end-of-file return
if (text.end().lineOffset() == 0) {
continue;
}
NewIssue newIssue = context.newIssue();
newIssue
.forRule(ruleKey)
.at(newIssue.newLocation()
.on(file)
.at(text)
.message("This bug issue is generated on each line"))
.save();
}
}
}
| 2,852 | 34.6625 | 110 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/OneBugIssuePerTestLineSensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import org.sonar.api.batch.fs.FilePredicates;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.InputFile.Type;
import org.sonar.api.batch.fs.TextRange;
import org.sonar.api.batch.sensor.Sensor;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.api.batch.sensor.issue.NewIssue;
import org.sonar.api.rule.RuleKey;
import org.sonar.xoo.Xoo;
import org.sonar.xoo.Xoo2;
public class OneBugIssuePerTestLineSensor implements Sensor {
public static final String RULE_KEY = "OneBugIssuePerTestLine";
@Override
public void describe(SensorDescriptor descriptor) {
descriptor
.name("One Bug Issue Per Line of Test File")
.onlyOnFileType(Type.TEST)
.onlyOnLanguages(Xoo.KEY, Xoo2.KEY)
.createIssuesForRuleRepositories(XooRulesDefinition.XOO_REPOSITORY, XooRulesDefinition.XOO2_REPOSITORY);
}
@Override
public void execute(SensorContext context) {
analyse(context, Xoo.KEY, XooRulesDefinition.XOO_REPOSITORY);
}
private void analyse(SensorContext context, String language, String repo) {
FileSystem fs = context.fileSystem();
FilePredicates p = fs.predicates();
for (InputFile file : fs.inputFiles(p.and(p.hasLanguages(language), p.hasType(Type.TEST)))) {
createIssues(file, context, repo);
}
}
private static void createIssues(InputFile file, SensorContext context, String repo) {
RuleKey ruleKey = RuleKey.of(repo, RULE_KEY);
for (int line = 1; line <= file.lines(); line++) {
TextRange text = file.selectLine(line);
// do not count empty lines, which can be a pain with end-of-file return
if (text.end().lineOffset() == 0) {
continue;
}
NewIssue newIssue = context.newIssue();
newIssue
.forRule(ruleKey)
.at(newIssue.newLocation()
.on(file)
.at(text)
.message("This bug issue is generated on each line of a test file"))
.save();
}
}
}
| 2,921 | 35.074074 | 110 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/OneCodeSmellIssuePerLineSensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import org.sonar.api.batch.fs.FilePredicates;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.InputFile.Type;
import org.sonar.api.batch.fs.TextRange;
import org.sonar.api.batch.sensor.Sensor;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.api.batch.sensor.issue.NewIssue;
import org.sonar.api.rule.RuleKey;
import org.sonar.xoo.Xoo;
import org.sonar.xoo.Xoo2;
public class OneCodeSmellIssuePerLineSensor implements Sensor {
public static final String RULE_KEY = "OneCodeSmellIssuePerLine";
@Override
public void describe(SensorDescriptor descriptor) {
descriptor
.name("One Code Smell Issue Per Line")
.onlyOnLanguages(Xoo.KEY, Xoo2.KEY)
.createIssuesForRuleRepositories(XooRulesDefinition.XOO_REPOSITORY, XooRulesDefinition.XOO2_REPOSITORY);
}
@Override
public void execute(SensorContext context) {
analyse(context, Xoo.KEY, XooRulesDefinition.XOO_REPOSITORY);
}
private void analyse(SensorContext context, String language, String repo) {
FileSystem fs = context.fileSystem();
FilePredicates p = fs.predicates();
for (InputFile file : fs.inputFiles(p.and(p.hasLanguages(language), p.hasType(Type.MAIN)))) {
createIssues(file, context, repo);
}
}
private static void createIssues(InputFile file, SensorContext context, String repo) {
RuleKey ruleKey = RuleKey.of(repo, RULE_KEY);
for (int line = 1; line <= file.lines(); line++) {
TextRange text = file.selectLine(line);
// do not count empty lines, which can be a pain with end-of-file return
if (text.end().lineOffset() == 0) {
continue;
}
NewIssue newIssue = context.newIssue();
newIssue
.forRule(ruleKey)
.at(newIssue.newLocation()
.on(file)
.at(text)
.message("This code smell issue is generated on each line"))
.save();
}
}
}
| 2,878 | 34.9875 | 110 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/OneCodeSmellIssuePerTestLineSensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import org.sonar.api.batch.fs.FilePredicates;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.InputFile.Type;
import org.sonar.api.batch.fs.TextRange;
import org.sonar.api.batch.sensor.Sensor;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.api.batch.sensor.issue.NewIssue;
import org.sonar.api.rule.RuleKey;
import org.sonar.xoo.Xoo;
import org.sonar.xoo.Xoo2;
public class OneCodeSmellIssuePerTestLineSensor implements Sensor {
public static final String RULE_KEY = "OneCodeSmellIssuePerTestLine";
@Override
public void describe(SensorDescriptor descriptor) {
descriptor
.name("One Code Smell Issue Per Line of Test File")
.onlyOnFileType(Type.TEST)
.onlyOnLanguages(Xoo.KEY, Xoo2.KEY)
.createIssuesForRuleRepositories(XooRulesDefinition.XOO_REPOSITORY, XooRulesDefinition.XOO2_REPOSITORY);
}
@Override
public void execute(SensorContext context) {
analyse(context, Xoo.KEY, XooRulesDefinition.XOO_REPOSITORY);
}
private void analyse(SensorContext context, String language, String repo) {
FileSystem fs = context.fileSystem();
FilePredicates p = fs.predicates();
for (InputFile file : fs.inputFiles(p.and(p.hasLanguages(language), p.hasType(Type.TEST)))) {
createIssues(file, context, repo);
}
}
private static void createIssues(InputFile file, SensorContext context, String repo) {
RuleKey ruleKey = RuleKey.of(repo, RULE_KEY);
for (int line = 1; line <= file.lines(); line++) {
TextRange text = file.selectLine(line);
// do not count empty lines, which can be a pain with end-of-file return
if (text.end().lineOffset() == 0) {
continue;
}
NewIssue newIssue = context.newIssue();
newIssue
.forRule(ruleKey)
.at(newIssue.newLocation()
.on(file)
.at(text)
.message("This code smell issue is generated on each line of a test file"))
.save();
}
}
}
| 2,947 | 35.395062 | 110 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/OneDayDebtPerFileSensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.rule.ActiveRules;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.issue.NewIssue;
import org.sonar.api.rule.RuleKey;
public class OneDayDebtPerFileSensor extends AbstractXooRuleSensor {
public static final String RULE_KEY = "OneDayDebtPerFile";
public OneDayDebtPerFileSensor(FileSystem fs, ActiveRules activeRules) {
super(fs, activeRules);
}
@Override
protected String getRuleKey() {
return RULE_KEY;
}
@Override protected void processFile(InputFile inputFile, SensorContext context, RuleKey ruleKey, String languageKey) {
NewIssue newIssue = context.newIssue()
.forRule(ruleKey);
newIssue.at(newIssue.newLocation()
.on(inputFile)
.message("This issue is generated on each file with a debt of one day"))
.save();
}
}
| 1,798 | 33.596154 | 121 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/OneExternalIssueOnProjectSensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import org.sonar.api.batch.rule.Severity;
import org.sonar.api.batch.sensor.Sensor;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.api.batch.sensor.issue.NewExternalIssue;
import org.sonar.api.rules.RuleType;
import org.sonar.xoo.Xoo;
public class OneExternalIssueOnProjectSensor implements Sensor {
public static final String ENGINE_ID = "XooEngine";
public static final String SEVERITY = "MAJOR";
public static final RuleType TYPE = RuleType.BUG;
public static final String ACTIVATE = "sonar.oneExternalIssueOnProject.activate";
public static final String RULE_ID = "OneExternalIssueOnProject";
@Override
public void describe(SensorDescriptor descriptor) {
descriptor
.name("One External Issue At Project Level")
.onlyOnLanguages(Xoo.KEY)
.onlyWhenConfiguration(c -> c.getBoolean(ACTIVATE).orElse(false));
}
@Override
public void execute(SensorContext context) {
analyse(context);
}
private static void analyse(SensorContext context) {
NewExternalIssue newIssue = context.newExternalIssue();
newIssue
.engineId(ENGINE_ID)
.ruleId(RULE_ID)
.at(newIssue.newLocation()
.on(context.project())
.message("This issue is generated at project level"))
.severity(Severity.valueOf(SEVERITY))
.type(TYPE)
.save();
}
}
| 2,267 | 35 | 83 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/OneExternalIssuePerLineSensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import org.sonar.api.batch.fs.FilePredicates;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.rule.Severity;
import org.sonar.api.batch.sensor.Sensor;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.api.batch.sensor.issue.NewExternalIssue;
import org.sonar.api.rules.RuleType;
import org.sonar.xoo.Xoo;
public class OneExternalIssuePerLineSensor implements Sensor {
public static final String RULE_ID = "OneExternalIssuePerLine";
public static final String ENGINE_ID = "XooEngine";
public static final String SEVERITY = "MAJOR";
public static final Long EFFORT = 10L;
public static final RuleType TYPE = RuleType.BUG;
public static final String ACTIVATE = "sonar.oneExternalIssuePerLine.activate";
public static final String REGISTER_AD_HOC_RULE = "sonar.oneExternalIssuePerLine.adhocRule";
private static final String NAME = "One External Issue Per Line";
@Override
public void describe(SensorDescriptor descriptor) {
descriptor
.name(NAME)
.onlyOnLanguages(Xoo.KEY)
.onlyWhenConfiguration(c -> c.getBoolean(ACTIVATE).orElse(false));
}
@Override
public void execute(SensorContext context) {
FileSystem fs = context.fileSystem();
FilePredicates p = fs.predicates();
for (InputFile file : fs.inputFiles(p.and(p.hasLanguages(Xoo.KEY), p.hasType(InputFile.Type.MAIN)))) {
createIssues(file, context);
}
if (context.config().getBoolean(REGISTER_AD_HOC_RULE).orElse(false)) {
context.newAdHocRule()
.engineId(ENGINE_ID)
.ruleId(RULE_ID)
.name("An ad hoc rule")
.description("blah blah")
.severity(Severity.BLOCKER)
.type(RuleType.BUG)
.save();
}
}
private static void createIssues(InputFile file, SensorContext context) {
for (int line = 1; line <= file.lines(); line++) {
NewExternalIssue newIssue = context.newExternalIssue();
newIssue
.engineId(ENGINE_ID)
.ruleId(RULE_ID)
.at(newIssue.newLocation()
.on(file)
.at(file.selectLine(line))
.message("This issue is generated on each line"))
.severity(Severity.valueOf(SEVERITY))
.remediationEffortMinutes(EFFORT)
.type(TYPE)
.save();
}
}
}
| 3,244 | 36.298851 | 106 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/OneExternalIssuePerLineWithoutMessageSensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import org.sonar.api.batch.fs.FilePredicates;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.rule.Severity;
import org.sonar.api.batch.sensor.Sensor;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.api.batch.sensor.issue.NewExternalIssue;
import org.sonar.api.rules.RuleType;
import org.sonar.xoo.Xoo;
public class OneExternalIssuePerLineWithoutMessageSensor implements Sensor {
public static final String RULE_ID = "oneExternalIssuePerLineWithoutMessage";
public static final String ENGINE_ID = "XooEngine";
public static final String SEVERITY = "MAJOR";
public static final Long EFFORT = 10L;
public static final RuleType TYPE = RuleType.BUG;
public static final String ACTIVATE = "sonar.oneExternalIssuePerLineWithoutMessage.activate";
public static final String REGISTER_AD_HOC_RULE = "sonar.oneExternalIssuePerLineWithoutMessage.adhocRule";
private static final String NAME = "One External Issue Per Line Without Message";
@Override
public void describe(SensorDescriptor descriptor) {
descriptor
.name(NAME)
.onlyOnLanguages(Xoo.KEY)
.onlyWhenConfiguration(c -> c.getBoolean(ACTIVATE).orElse(false));
}
@Override
public void execute(SensorContext context) {
FileSystem fs = context.fileSystem();
FilePredicates p = fs.predicates();
for (InputFile file : fs.inputFiles(p.and(p.hasLanguages(Xoo.KEY), p.hasType(InputFile.Type.MAIN)))) {
createIssues(file, context);
}
if (context.config().getBoolean(REGISTER_AD_HOC_RULE).orElse(false)) {
context.newAdHocRule()
.engineId(ENGINE_ID)
.ruleId(RULE_ID)
.name("An ad hoc rule")
.description("blah blah")
.severity(Severity.BLOCKER)
.type(RuleType.BUG)
.save();
}
}
private static void createIssues(InputFile file, SensorContext context) {
for (int line = 1; line <= file.lines(); line++) {
NewExternalIssue newIssue = context.newExternalIssue();
newIssue
.engineId(ENGINE_ID)
.ruleId(RULE_ID)
.at(newIssue.newLocation()
.on(file)
.at(file.selectLine(line))
.message(""))
.severity(Severity.valueOf(SEVERITY))
.remediationEffortMinutes(EFFORT)
.type(TYPE)
.save();
}
}
}
| 3,280 | 36.712644 | 108 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/OneIssueOnDirPerFileSensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import org.sonar.api.batch.fs.InputDir;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.sensor.Sensor;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.api.batch.sensor.issue.NewIssue;
import org.sonar.api.rule.RuleKey;
import org.sonar.xoo.Xoo;
public class OneIssueOnDirPerFileSensor implements Sensor {
public static final String RULE_KEY = "OneIssueOnDirPerFile";
@Override
public void describe(SensorDescriptor descriptor) {
descriptor
.name("One Issue On Dir Per File")
.onlyOnLanguages(Xoo.KEY)
.createIssuesForRuleRepositories(XooRulesDefinition.XOO_REPOSITORY);
}
@Override
public void execute(SensorContext context) {
for (InputFile file : context.fileSystem().inputFiles(context.fileSystem().predicates().hasLanguages(Xoo.KEY))) {
createIssues(file, context);
}
}
private static void createIssues(InputFile file, SensorContext context) {
RuleKey ruleKey = RuleKey.of(XooRulesDefinition.XOO_REPOSITORY, RULE_KEY);
InputDir inputDir = context.fileSystem().inputDir(file.file().getParentFile());
if (inputDir != null) {
NewIssue newIssue = context.newIssue();
newIssue
.forRule(ruleKey)
.at(newIssue.newLocation()
.on(inputDir)
.message("This issue is generated for file " + file.relativePath()))
.save();
}
}
}
| 2,312 | 35.140625 | 117 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/OneIssuePerDirectorySensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import java.util.Objects;
import java.util.stream.StreamSupport;
import org.sonar.api.batch.fs.FilePredicates;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile.Type;
import org.sonar.api.batch.sensor.Sensor;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.api.batch.sensor.issue.NewIssue;
import org.sonar.api.rule.RuleKey;
public class OneIssuePerDirectorySensor implements Sensor {
public static final String RULE_KEY = "OneIssuePerDirectory";
@Override
public void describe(SensorDescriptor descriptor) {
descriptor
.name("One Issue Per Directory")
.createIssuesForRuleRepositories(XooRulesDefinition.XOO_REPOSITORY);
}
@Override
public void execute(SensorContext context) {
analyse(context);
}
private static void analyse(SensorContext context) {
FileSystem fs = context.fileSystem();
FilePredicates p = fs.predicates();
RuleKey ruleKey = RuleKey.of(XooRulesDefinition.XOO_REPOSITORY, RULE_KEY);
StreamSupport.stream(fs.inputFiles(p.hasType(Type.MAIN)).spliterator(), false)
.map(file -> fs.inputDir(file.file().getParentFile()))
.filter(Objects::nonNull)
.distinct()
.forEach(inputDir -> {
NewIssue newIssue = context.newIssue();
newIssue
.forRule(ruleKey)
.at(newIssue.newLocation()
.on(inputDir)
.message("This issue is generated for any non-empty directory"))
.save();
});
}
}
| 2,419 | 34.588235 | 82 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/OneIssuePerFileSensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.rule.ActiveRules;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.issue.NewIssue;
import org.sonar.api.config.Configuration;
import org.sonar.api.rule.RuleKey;
public class OneIssuePerFileSensor extends AbstractXooRuleSensor {
public static final String RULE_KEY = "OneIssuePerFile";
private static final String EFFORT_TO_FIX_PROPERTY = "sonar.oneIssuePerFile.effortToFix";
private final Configuration settings;
public OneIssuePerFileSensor(Configuration settings, FileSystem fs, ActiveRules activeRules) {
super(fs, activeRules);
this.settings = settings;
}
@Override
protected String getRuleKey() {
return RULE_KEY;
}
@Override protected void processFile(InputFile inputFile, SensorContext context, RuleKey ruleKey, String languageKey) {
NewIssue newIssue = context.newIssue()
.forRule(ruleKey)
.gap(settings.getDouble(EFFORT_TO_FIX_PROPERTY).orElse(0.0));
newIssue.at(newIssue.newLocation()
.on(inputFile)
.message("This issue is generated on each file"))
.save();
}
}
| 2,066 | 34.637931 | 121 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/OneIssuePerLineSensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import org.sonar.api.batch.fs.FilePredicates;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.InputFile.Type;
import org.sonar.api.batch.rule.Severity;
import org.sonar.api.batch.sensor.Sensor;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.api.batch.sensor.issue.NewIssue;
import org.sonar.api.rule.RuleKey;
import org.sonar.xoo.Xoo;
import org.sonar.xoo.Xoo2;
import static org.sonar.xoo.rule.XooRulesDefinition.AVAILABLE_CONTEXTS;
public class OneIssuePerLineSensor implements Sensor {
public static final String RULE_KEY = "OneIssuePerLine";
public static final String EFFORT_TO_FIX_PROPERTY = "sonar.oneIssuePerLine.effortToFix";
public static final String FORCE_SEVERITY_PROPERTY = "sonar.oneIssuePerLine.forceSeverity";
@Override
public void describe(SensorDescriptor descriptor) {
descriptor
.name("One Issue Per Line")
.onlyOnLanguages(Xoo.KEY, Xoo2.KEY)
.createIssuesForRuleRepositories(XooRulesDefinition.XOO_REPOSITORY, XooRulesDefinition.XOO2_REPOSITORY)
.processesFilesIndependently();
}
@Override
public void execute(SensorContext context) {
analyse(context, Xoo.KEY, XooRulesDefinition.XOO_REPOSITORY);
analyse(context, Xoo2.KEY, XooRulesDefinition.XOO2_REPOSITORY);
}
private void analyse(SensorContext context, String language, String repo) {
FileSystem fs = context.fileSystem();
FilePredicates p = fs.predicates();
for (InputFile file : fs.inputFiles(p.and(p.hasLanguages(language), p.hasType(Type.MAIN)))) {
createIssues(file, context, repo);
}
}
private void createIssues(InputFile file, SensorContext context, String repo) {
RuleKey ruleKey = RuleKey.of(repo, RULE_KEY);
String severity = context.config().get(FORCE_SEVERITY_PROPERTY).orElse(null);
for (int line = 1; line <= file.lines(); line++) {
NewIssue newIssue = context.newIssue();
newIssue
.forRule(ruleKey)
.at(newIssue.newLocation()
.on(file)
.at(file.selectLine(line))
.message("This issue is generated on each line"))
.overrideSeverity(severity != null ? Severity.valueOf(severity) : null)
.setRuleDescriptionContextKey(AVAILABLE_CONTEXTS[0])
.gap(context.config().getDouble(EFFORT_TO_FIX_PROPERTY).orElse(null));
newIssue.save();
}
}
}
| 3,327 | 38.152941 | 109 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/OneIssuePerModuleSensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import org.sonar.api.batch.sensor.Sensor;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.api.batch.sensor.issue.NewIssue;
import org.sonar.api.rule.RuleKey;
import org.sonar.xoo.Xoo;
public class OneIssuePerModuleSensor implements Sensor {
public static final String RULE_KEY = "OneIssuePerModule";
@Override
public void describe(SensorDescriptor descriptor) {
descriptor
.name("One Issue Per Module")
.onlyOnLanguages(Xoo.KEY)
.createIssuesForRuleRepositories(XooRulesDefinition.XOO_REPOSITORY);
}
@Override
public void execute(SensorContext context) {
analyse(context, Xoo.KEY, XooRulesDefinition.XOO_REPOSITORY);
}
private void analyse(SensorContext context, String language, String repo) {
RuleKey ruleKey = RuleKey.of(repo, RULE_KEY);
NewIssue newIssue = context.newIssue();
newIssue
.forRule(ruleKey)
.at(newIssue.newLocation()
.on(context.module())
.message("This issue is generated on each module"))
.save();
}
}
| 1,960 | 32.810345 | 77 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/OneIssuePerTestFileSensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import org.sonar.api.batch.fs.FilePredicates;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.InputFile.Type;
import org.sonar.api.batch.rule.ActiveRules;
import org.sonar.api.batch.sensor.Sensor;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.api.batch.sensor.issue.NewIssue;
import org.sonar.api.rule.RuleKey;
import org.sonar.xoo.Xoo;
public class OneIssuePerTestFileSensor implements Sensor {
public static final String RULE_KEY = "OneIssuePerTestFile";
private final FileSystem fs;
private final ActiveRules activeRules;
public OneIssuePerTestFileSensor(FileSystem fs, ActiveRules activeRules) {
this.fs = fs;
this.activeRules = activeRules;
}
@Override
public void describe(SensorDescriptor descriptor) {
descriptor
.onlyOnLanguage(Xoo.KEY)
.onlyOnFileType(Type.TEST)
.createIssuesForRuleRepository(XooRulesDefinition.XOO_REPOSITORY);
}
@Override
public void execute(SensorContext context) {
RuleKey ruleKey = RuleKey.of(XooRulesDefinition.XOO_REPOSITORY, RULE_KEY);
if (activeRules.find(ruleKey) == null) {
return;
}
FilePredicates p = fs.predicates();
for (InputFile inputFile : fs.inputFiles(p.and(p.hasLanguages(Xoo.KEY), p.hasType(Type.TEST)))) {
processFile(inputFile, context, ruleKey);
}
}
private void processFile(InputFile inputFile, SensorContext context, RuleKey ruleKey) {
NewIssue newIssue = context.newIssue();
newIssue
.forRule(ruleKey)
.at(newIssue.newLocation().message("This issue is generated on each test file")
.on(inputFile))
.save();
}
}
| 2,610 | 33.355263 | 101 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/OneIssuePerUnknownFileSensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import org.sonar.api.batch.fs.FilePredicate;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.sensor.Sensor;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.api.batch.sensor.issue.NewIssue;
import org.sonar.api.rule.RuleKey;
public class OneIssuePerUnknownFileSensor implements Sensor {
public static final String RULE_KEY = "OneIssuePerUnknownFile";
@Override
public void describe(SensorDescriptor descriptor) {
descriptor.name("One Issue Per Unknown File");
}
@Override
public void execute(SensorContext context) {
RuleKey ruleKey = RuleKey.of(XooRulesDefinition.XOO_REPOSITORY, RULE_KEY);
FilePredicate unknownFilesPredicate = context.fileSystem().predicates().matchesPathPattern("**/*.unknown");
Iterable<InputFile> unknownFiles = context.fileSystem().inputFiles(unknownFilesPredicate);
unknownFiles.forEach(inputFile -> {
NewIssue newIssue = context.newIssue();
newIssue
.forRule(ruleKey)
.at(newIssue.newLocation()
.on(inputFile)
.message("This issue is generated on each file with extension 'unknown'"))
.save();
});
}
}
| 2,089 | 35.666667 | 111 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/OnePredefinedAndAdHocRuleExternalIssuePerLineSensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import org.sonar.api.batch.fs.FilePredicates;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.InputFile.Type;
import org.sonar.api.batch.rule.Severity;
import org.sonar.api.batch.sensor.Sensor;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.api.batch.sensor.issue.NewExternalIssue;
import org.sonar.api.rules.RuleType;
import org.sonar.xoo.Xoo;
public class OnePredefinedAndAdHocRuleExternalIssuePerLineSensor implements Sensor {
public static final String ACTIVATE = "sonar.onePredefinedAndAdHocRuleExternalIssuePerLine.activate";
private static final String NAME = "One External Issue Per Line With A Predefined And An AdHoc Rule";
@Override
public void describe(SensorDescriptor descriptor) {
descriptor
.name(NAME)
.onlyOnLanguages(Xoo.KEY)
.onlyWhenConfiguration(c -> c.getBoolean(ACTIVATE).orElse(false));
}
@Override
public void execute(SensorContext context) {
FileSystem fs = context.fileSystem();
FilePredicates p = fs.predicates();
for (InputFile file : fs.inputFiles(p.and(p.hasLanguages(Xoo.KEY), p.hasType(Type.MAIN)))) {
createIssues(file, context);
}
}
private static void createIssues(InputFile file, SensorContext context) {
for (int line = 1; line <= file.lines(); line++) {
NewExternalIssue newIssue = context.newExternalIssue();
newIssue
.engineId(OnePredefinedRuleExternalIssuePerLineSensor.ENGINE_ID)
.ruleId(OnePredefinedRuleExternalIssuePerLineSensor.RULE_ID)
.at(newIssue.newLocation()
.on(file)
.at(file.selectLine(line))
.message("This issue is generated on each line and the rule is predefined"))
.severity(Severity.valueOf(OnePredefinedRuleExternalIssuePerLineSensor.SEVERITY))
.remediationEffortMinutes(OnePredefinedRuleExternalIssuePerLineSensor.EFFORT)
.type(OnePredefinedRuleExternalIssuePerLineSensor.TYPE)
.save();
// Even if the issue is on a predefined rule, the sensor is declaring an adHoc rule => this info should be ignored
context.newAdHocRule()
.engineId(OnePredefinedRuleExternalIssuePerLineSensor.ENGINE_ID)
.ruleId(OnePredefinedRuleExternalIssuePerLineSensor.RULE_ID)
.name("An ad hoc rule")
.description("blah blah")
.severity(Severity.BLOCKER)
.type(RuleType.BUG)
.save();
}
}
}
| 3,380 | 39.73494 | 120 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/OnePredefinedRuleExternalIssuePerLineSensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import org.sonar.api.batch.fs.FilePredicates;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.InputFile.Type;
import org.sonar.api.batch.rule.Severity;
import org.sonar.api.batch.sensor.Sensor;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.api.batch.sensor.issue.NewExternalIssue;
import org.sonar.api.rules.RuleType;
import org.sonar.xoo.Xoo;
public class OnePredefinedRuleExternalIssuePerLineSensor implements Sensor {
public static final String RULE_ID = "OnePredefinedRuleExternalIssuePerLine";
public static final String ENGINE_ID = "XooEngine";
public static final String SEVERITY = "MAJOR";
public static final Long EFFORT = 10L;
public static final RuleType TYPE = RuleType.BUG;
public static final String ACTIVATE = "sonar.onePredefinedRuleExternalIssuePerLine.activate";
private static final String NAME = "One External Issue Per Line With A Predefined Rule";
@Override
public void describe(SensorDescriptor descriptor) {
descriptor
.name(NAME)
.onlyOnLanguages(Xoo.KEY)
.onlyWhenConfiguration(c -> c.getBoolean(ACTIVATE).orElse(false));
}
@Override
public void execute(SensorContext context) {
FileSystem fs = context.fileSystem();
FilePredicates p = fs.predicates();
for (InputFile file : fs.inputFiles(p.and(p.hasLanguages(Xoo.KEY), p.hasType(Type.MAIN)))) {
createIssues(file, context);
}
}
private static void createIssues(InputFile file, SensorContext context) {
for (int line = 1; line <= file.lines(); line++) {
NewExternalIssue newIssue = context.newExternalIssue();
newIssue
.engineId(ENGINE_ID)
.ruleId(RULE_ID)
.at(newIssue.newLocation()
.on(file)
.at(file.selectLine(line))
.message("This issue is generated on each line and the rule is predefined"))
.severity(Severity.valueOf(SEVERITY))
.remediationEffortMinutes(EFFORT)
.type(TYPE)
.save();
}
}
}
| 2,966 | 37.532468 | 96 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/OneQuickFixPerLineSensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import org.sonar.api.batch.fs.FilePredicates;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.InputFile.Type;
import org.sonar.api.batch.sensor.Sensor;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.api.batch.sensor.issue.NewIssue;
import org.sonar.api.rule.RuleKey;
import org.sonar.xoo.Xoo;
import org.sonar.xoo.Xoo2;
public class OneQuickFixPerLineSensor implements Sensor {
public static final String RULE_KEY = "OneQuickFixPerLine";
@Override
public void describe(SensorDescriptor descriptor) {
descriptor
.name("One Quick Fix Per Line")
.onlyOnLanguages(Xoo.KEY, Xoo2.KEY)
.createIssuesForRuleRepositories(XooRulesDefinition.XOO_REPOSITORY, XooRulesDefinition.XOO2_REPOSITORY);
}
@Override
public void execute(SensorContext context) {
analyse(context, Xoo.KEY, XooRulesDefinition.XOO_REPOSITORY);
analyse(context, Xoo2.KEY, XooRulesDefinition.XOO2_REPOSITORY);
}
private void analyse(SensorContext context, String language, String repo) {
FileSystem fs = context.fileSystem();
FilePredicates p = fs.predicates();
for (InputFile file : fs.inputFiles(p.and(p.hasLanguages(language), p.hasType(Type.MAIN)))) {
createIssues(file, context, repo);
}
}
private void createIssues(InputFile file, SensorContext context, String repo) {
RuleKey ruleKey = RuleKey.of(repo, RULE_KEY);
for (int line = 1; line <= file.lines(); line++) {
NewIssue newIssue = context.newIssue();
newIssue
.setQuickFixAvailable(true)
.forRule(ruleKey)
.at(newIssue.newLocation()
.on(file)
.at(file.selectLine(line))
.message("This quick fix issue is generated on each line"))
.save();
}
}
}
| 2,738 | 35.039474 | 110 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/OneVulnerabilityIssuePerModuleSensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import org.sonar.api.batch.sensor.Sensor;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.api.batch.sensor.issue.NewIssue;
import org.sonar.api.rule.RuleKey;
import org.sonar.xoo.Xoo;
public class OneVulnerabilityIssuePerModuleSensor implements Sensor {
public static final String RULE_KEY = "OneVulnerabilityIssuePerModule";
@Override
public void describe(SensorDescriptor descriptor) {
descriptor
.name("One Issue Per Module")
.onlyOnLanguages(Xoo.KEY)
.createIssuesForRuleRepositories(XooRulesDefinition.XOO_REPOSITORY);
}
@Override
public void execute(SensorContext context) {
analyse(context, XooRulesDefinition.XOO_REPOSITORY);
}
private void analyse(SensorContext context, String repo) {
RuleKey ruleKey = RuleKey.of(repo, RULE_KEY);
NewIssue newIssue = context.newIssue();
newIssue
.forRule(ruleKey)
.at(newIssue.newLocation()
.on(context.module())
.message("This issue is generated on each module"))
.save();
}
}
| 1,960 | 32.810345 | 75 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/RandomAccessSensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.sonar.api.batch.fs.FilePredicates;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.InputFile.Type;
import org.sonar.api.batch.sensor.Sensor;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.api.batch.sensor.issue.NewIssue;
import org.sonar.api.rule.RuleKey;
import org.sonar.xoo.Xoo;
public class RandomAccessSensor implements Sensor {
private static final String SONAR_XOO_RANDOM_ACCESS_ISSUE_PATHS = "sonar.xoo.randomAccessIssue.paths";
public static final String RULE_KEY = "RandomAccessIssue";
@Override
public void describe(SensorDescriptor descriptor) {
descriptor
.name("One Issue Per File with Random Access")
.onlyOnLanguages(Xoo.KEY)
.createIssuesForRuleRepositories(XooRulesDefinition.XOO_REPOSITORY)
.onlyWhenConfiguration(c -> c.get(SONAR_XOO_RANDOM_ACCESS_ISSUE_PATHS).isPresent());
}
@Override
public void execute(SensorContext context) {
File f = new File(context.config().get(SONAR_XOO_RANDOM_ACCESS_ISSUE_PATHS).orElseThrow(() -> new IllegalStateException("Required property")));
FileSystem fs = context.fileSystem();
FilePredicates p = fs.predicates();
try {
for (String path : FileUtils.readLines(f)) {
createIssues(fs.inputFile(p.and(p.hasPath(path), p.hasType(Type.MAIN), p.hasLanguage(Xoo.KEY))), context);
}
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
private static void createIssues(InputFile file, SensorContext context) {
RuleKey ruleKey = RuleKey.of(XooRulesDefinition.XOO_REPOSITORY, RULE_KEY);
NewIssue newIssue = context.newIssue();
newIssue
.forRule(ruleKey)
.at(newIssue.newLocation()
.on(file)
.at(file.selectLine(1))
.message("This issue is generated on each file"))
.save();
}
}
| 2,901 | 37.184211 | 147 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/SaveDataTwiceSensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import java.util.Iterator;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.sensor.Sensor;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.api.batch.sensor.highlighting.TypeOfText;
/**
* This sensor will create and save highlighting twice on the first file that it finds in the index.
* It requires the property sonar.it.savedatatwice
*/
public class SaveDataTwiceSensor implements Sensor {
@Override
public void describe(SensorDescriptor descriptor) {
descriptor.name("SaveDataTwice IT Sensor ")
.onlyWhenConfiguration(c -> c.getBoolean("sonar.it.savedatatwice").orElse(false));
}
@Override
public void execute(SensorContext context) {
Iterator<InputFile> inputFiles = context.fileSystem().inputFiles(context.fileSystem().predicates().all()).iterator();
if (!inputFiles.hasNext()) {
throw new IllegalStateException("No files indexed");
}
InputFile file = inputFiles.next();
context.newHighlighting()
.onFile(file)
.highlight(file.selectLine(1), TypeOfText.CONSTANT)
.save();
context.newHighlighting()
.onFile(file)
.highlight(file.selectLine(file.lines()), TypeOfText.COMMENT)
.save();
}
}
| 2,150 | 33.693548 | 121 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/Xoo2BasicProfile.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition;
import org.sonar.xoo.Xoo2;
public class Xoo2BasicProfile implements BuiltInQualityProfilesDefinition {
@Override
public void define(Context context) {
NewBuiltInQualityProfile qProfile = context.createBuiltInQualityProfile("Basic", Xoo2.KEY);
qProfile.setDefault(true);
qProfile.activateRule(XooRulesDefinition.XOO2_REPOSITORY, HasTagSensor.RULE_KEY);
qProfile.done();
}
}
| 1,338 | 38.382353 | 95 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/Xoo2SonarWayProfile.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition;
import org.sonar.xoo.Xoo2;
public class Xoo2SonarWayProfile implements BuiltInQualityProfilesDefinition {
@Override
public void define(Context context) {
NewBuiltInQualityProfile qProfile = context.createBuiltInQualityProfile("Sonar way", Xoo2.KEY);
qProfile.activateRule(XooRulesDefinition.XOO2_REPOSITORY, HasTagSensor.RULE_KEY);
qProfile.activateRule(XooRulesDefinition.XOO2_REPOSITORY, OneIssuePerLineSensor.RULE_KEY);
qProfile.done();
}
}
| 1,409 | 40.470588 | 99 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/XooBasicProfile.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition;
import org.sonar.xoo.Xoo;
public class XooBasicProfile implements BuiltInQualityProfilesDefinition {
@Override
public void define(Context context) {
NewBuiltInQualityProfile qProfile = context.createBuiltInQualityProfile("Basic", Xoo.KEY);
qProfile.setDefault(true);
qProfile.activateRule(XooRulesDefinition.XOO_REPOSITORY, HasTagSensor.RULE_KEY);
qProfile.done();
}
}
| 1,334 | 38.264706 | 94 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/XooBuiltInQualityProfilesDefinition.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition;
import org.sonar.xoo.Xoo;
import static org.sonar.xoo.rule.XooRulesDefinition.XOO_REPOSITORY;
public class XooBuiltInQualityProfilesDefinition implements BuiltInQualityProfilesDefinition {
@Override
public void define(Context context) {
NewBuiltInQualityProfile profile = context.createBuiltInQualityProfile("test BuiltInQualityProfilesDefinition", Xoo.KEY);
profile.setDefault(false);
NewBuiltInActiveRule rule = profile.activateRule(XOO_REPOSITORY, HasTagSensor.RULE_KEY);
rule.overrideSeverity("BLOCKER");
rule.overrideParam("tag", "TODO");
profile.done();
}
}
| 1,538 | 39.5 | 125 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/XooEmptyProfile.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition;
import org.sonar.xoo.Xoo;
public class XooEmptyProfile implements BuiltInQualityProfilesDefinition {
@Override
public void define(Context context) {
context.createBuiltInQualityProfile("empty", Xoo.KEY)
.done();
}
}
| 1,173 | 35.6875 | 75 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/XooFakeExporter.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import org.sonar.api.profiles.ProfileExporter;
import org.sonar.api.profiles.RulesProfile;
import org.sonar.xoo.Xoo;
import java.io.IOException;
import java.io.Writer;
/**
* Fake exporter just for test
*/
public class XooFakeExporter extends ProfileExporter {
public XooFakeExporter() {
super("XooFakeExporter", "Xoo Fake Exporter");
}
@Override
public String[] getSupportedLanguages() {
return new String[]{Xoo.KEY};
}
@Override
public String getMimeType() {
return "plain/custom";
}
@Override
public void exportProfile(RulesProfile profile, Writer writer) {
try {
writer.write("xoo -> " + profile.getName() + " -> " + profile.getActiveRules().size());
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
| 1,659 | 28.642857 | 93 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/XooFakeImporter.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import org.sonar.api.profiles.ProfileImporter;
import org.sonar.api.profiles.RulesProfile;
import org.sonar.api.rules.Rule;
import org.sonar.api.rules.RulePriority;
import org.sonar.api.utils.ValidationMessages;
import org.sonar.xoo.Xoo;
import java.io.Reader;
/**
* Fake importer just for test, it will NOT take into account the given file but will create some hard-coded rules
*/
public class XooFakeImporter extends ProfileImporter {
public XooFakeImporter() {
super("XooProfileImporter", "Xoo Profile Importer");
}
@Override
public String[] getSupportedLanguages() {
return new String[] {Xoo.KEY};
}
@Override
public RulesProfile importProfile(Reader reader, ValidationMessages messages) {
RulesProfile rulesProfile = RulesProfile.create();
rulesProfile.activateRule(Rule.create(XooRulesDefinition.XOO_REPOSITORY, "x1"), RulePriority.CRITICAL);
return rulesProfile;
}
}
| 1,788 | 34.078431 | 114 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/XooFakeImporterWithMessages.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import org.sonar.api.profiles.ProfileImporter;
import org.sonar.api.profiles.RulesProfile;
import org.sonar.api.utils.ValidationMessages;
import java.io.Reader;
/**
* Fake importer just for test, it will NOT take into account the given file but will display some info and warning messages
*/
public class XooFakeImporterWithMessages extends ProfileImporter {
public XooFakeImporterWithMessages() {
super("XooFakeImporterWithMessages", "Xoo Profile Importer With Messages");
}
@Override
public String[] getSupportedLanguages() {
return new String[] {};
}
@Override
public RulesProfile importProfile(Reader reader, ValidationMessages messages) {
messages.addWarningText("a warning");
messages.addInfoText("an info");
return RulesProfile.create();
}
}
| 1,663 | 33.666667 | 124 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/XooRulesDefinition.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import javax.annotation.Nullable;
import org.sonar.api.SonarRuntime;
import org.sonar.api.rule.RuleScope;
import org.sonar.api.rules.RuleType;
import org.sonar.api.server.rule.RuleDescriptionSection;
import org.sonar.api.server.rule.RuleParamType;
import org.sonar.api.server.rule.RulesDefinition;
import org.sonar.api.server.rule.RulesDefinitionAnnotationLoader;
import org.sonar.api.utils.Version;
import org.sonar.xoo.Xoo;
import org.sonar.xoo.Xoo2;
import org.sonar.xoo.checks.Check;
import org.sonar.xoo.rule.variant.HotspotWithCodeVariantsSensor;
import org.sonar.xoo.rule.hotspot.HotspotWithContextsSensor;
import org.sonar.xoo.rule.hotspot.HotspotWithSingleContextSensor;
import org.sonar.xoo.rule.hotspot.HotspotWithoutContextSensor;
import org.sonar.xoo.rule.variant.IssueWithCodeVariantsSensor;
import static org.sonar.api.server.rule.RuleDescriptionSection.RuleDescriptionSectionKeys.ASSESS_THE_PROBLEM_SECTION_KEY;
import static org.sonar.api.server.rule.RuleDescriptionSection.RuleDescriptionSectionKeys.HOW_TO_FIX_SECTION_KEY;
import static org.sonar.api.server.rule.RuleDescriptionSection.RuleDescriptionSectionKeys.INTRODUCTION_SECTION_KEY;
import static org.sonar.api.server.rule.RuleDescriptionSection.RuleDescriptionSectionKeys.RESOURCES_SECTION_KEY;
import static org.sonar.api.server.rule.RuleDescriptionSection.RuleDescriptionSectionKeys.ROOT_CAUSE_SECTION_KEY;
import static org.sonar.api.server.rule.RulesDefinition.OwaspTop10Version.Y2017;
import static org.sonar.api.server.rule.RulesDefinition.OwaspTop10Version.Y2021;
/**
* Define all the coding rules that are supported on the repositories named "xoo" and "xoo2"
*/
public class XooRulesDefinition implements RulesDefinition {
public static final String[] AVAILABLE_CONTEXTS = {"javascript", "jquery", "express_js", "react", "axios"};
public static final String XOO_REPOSITORY = "xoo";
public static final String XOO2_REPOSITORY = "xoo2";
private static final String TEN_MIN = "10min";
@Nullable
private final Version version;
public XooRulesDefinition() {
this(null);
}
public XooRulesDefinition(@Nullable SonarRuntime sonarRuntime) {
this.version = sonarRuntime != null ? sonarRuntime.getApiVersion() : null;
}
@Override
public void define(Context context) {
defineRulesXoo(context);
defineRulesXoo2(context);
defineRulesXooExternal(context);
}
private static void defineRulesXoo2(Context context) {
NewRepository repo = context.createRepository(XOO2_REPOSITORY, Xoo2.KEY).setName("Xoo2");
NewRule hasTag = repo.createRule(HasTagSensor.RULE_KEY).setName("Has Tag");
addAllDescriptionSections(hasTag, "Search for a given tag in Xoo files");
NewRule oneIssuePerLine = repo.createRule(OneIssuePerLineSensor.RULE_KEY).setName("One Issue Per Line");
addAllDescriptionSections(oneIssuePerLine, "Generate an issue on each line of a file. It requires the metric \"lines\".");
oneIssuePerLine
.setDebtRemediationFunction(hasTag.debtRemediationFunctions().linear("1min"))
.setGapDescription("It takes about 1 minute to an experienced software craftsman to remove a line of code");
repo.done();
}
private void defineRulesXoo(Context context) {
NewRepository repo = context.createRepository(XOO_REPOSITORY, Xoo.KEY).setName("Xoo");
new RulesDefinitionAnnotationLoader().load(repo, Check.ALL);
NewRule hasTag = repo.createRule(HasTagSensor.RULE_KEY).setName("Has Tag")
.setActivatedByDefault(true)
.addDescriptionSection(howToFixSectionWithContext("single_context"));
addDescriptionSectionsWithoutContexts(hasTag, "Search for a given tag in Xoo files");
hasTag
.setDebtRemediationFunction(hasTag.debtRemediationFunctions().constantPerIssue("2min"));
hasTag.createParam("tag")
.setDefaultValue("xoo")
.setDescription("The tag to search for");
NewRule ruleWithParameters = repo.createRule("RuleWithParameters").setName("Rule with parameters");
addAllDescriptionSections(ruleWithParameters,
"Rule containing parameter of different types : boolean, integer, etc. For information, no issue will be linked to this rule.");
ruleWithParameters.createParam("string").setType(RuleParamType.STRING);
ruleWithParameters.createParam("text").setType(RuleParamType.TEXT);
ruleWithParameters.createParam("boolean").setType(RuleParamType.BOOLEAN);
ruleWithParameters.createParam("integer").setType(RuleParamType.INTEGER);
ruleWithParameters.createParam("float").setType(RuleParamType.FLOAT);
NewRule oneIssuePerLine = repo.createRule(OneIssuePerLineSensor.RULE_KEY).setName("One Issue Per Line")
.setTags("line");
addDescriptionSectionsWithoutContexts(oneIssuePerLine, "Generate an issue on each line of a file. It requires the metric \"lines\".");
addHowToFixSectionsWithContexts(oneIssuePerLine);
oneIssuePerLine
.setDebtRemediationFunction(oneIssuePerLine.debtRemediationFunctions().linear("1min"))
.setGapDescription("It takes about 1 minute to an experienced software craftsman to remove a line of code")
.addEducationPrincipleKeys("defense_in_depth", "never_trust_user_input");
NewRule oneQuickFixPerLine = repo.createRule(OneQuickFixPerLineSensor.RULE_KEY).setName("One Quick Fix Per Line")
.setTags("line");
addAllDescriptionSections(oneQuickFixPerLine,
"Generate an issue with quick fix available on each line of a file. It requires the metric \"lines\".");
oneQuickFixPerLine
.setDebtRemediationFunction(oneQuickFixPerLine.debtRemediationFunctions().linear("1min"))
.setGapDescription("It takes about 1 minute to an experienced software craftsman to remove a line of code");
NewRule oneIssueOnDirPerFile = repo.createRule(OneIssueOnDirPerFileSensor.RULE_KEY).setName("One Issue On Dir Per File");
addAllDescriptionSections(oneIssueOnDirPerFile,
"Generate issues on directories");
NewRule oneIssuePerFile = repo.createRule(OneIssuePerFileSensor.RULE_KEY).setName("One Issue Per File");
oneIssuePerFile.setDebtRemediationFunction(oneIssuePerFile.debtRemediationFunctions().linear(TEN_MIN));
addAllDescriptionSections(oneIssuePerFile, "Generate an issue on each file");
NewRule oneIssuePerTestFile = repo.createRule(OneIssuePerTestFileSensor.RULE_KEY).setName("One Issue Per Test File")
.setScope(RuleScope.TEST);
oneIssuePerTestFile.setDebtRemediationFunction(oneIssuePerTestFile.debtRemediationFunctions().linear("8min"));
addAllDescriptionSections(oneIssuePerTestFile, "Generate an issue on each test file");
NewRule oneBugIssuePerTestLine = repo.createRule(OneBugIssuePerTestLineSensor.RULE_KEY).setName("One Bug Issue Per Test Line")
.setScope(RuleScope.TEST)
.setType(RuleType.BUG);
addAllDescriptionSections(oneBugIssuePerTestLine, "Generate a bug issue on each line of a test file. It requires the metric \"lines\".");
oneBugIssuePerTestLine
.setDebtRemediationFunction(oneBugIssuePerTestLine.debtRemediationFunctions().linear("4min"));
NewRule oneCodeSmellIssuePerTestLine = repo.createRule(OneCodeSmellIssuePerTestLineSensor.RULE_KEY).setName("One Code Smell Issue Per Test Line")
.setScope(RuleScope.TEST)
.setType(RuleType.CODE_SMELL);
addAllDescriptionSections(oneCodeSmellIssuePerTestLine, "Generate a code smell issue on each line of a test file. It requires the metric \"lines\".");
oneCodeSmellIssuePerTestLine
.setDebtRemediationFunction(oneCodeSmellIssuePerTestLine.debtRemediationFunctions().linear("3min"));
NewRule oneIssuePerDirectory = repo.createRule(OneIssuePerDirectorySensor.RULE_KEY).setName("One Issue Per Directory");
oneIssuePerDirectory.setDebtRemediationFunction(oneIssuePerDirectory.debtRemediationFunctions().linear(TEN_MIN));
addAllDescriptionSections(oneIssuePerDirectory, "Generate an issue on each non-empty directory");
NewRule oneDayDebtPerFile = repo.createRule(OneDayDebtPerFileSensor.RULE_KEY).setName("One Day Debt Per File");
oneDayDebtPerFile.setDebtRemediationFunction(oneDayDebtPerFile.debtRemediationFunctions().linear("1d"));
addAllDescriptionSections(oneDayDebtPerFile, "Generate an issue on each file with a debt of one day");
NewRule oneIssuePerModule = repo.createRule(OneIssuePerModuleSensor.RULE_KEY).setName("One Issue Per Module");
oneIssuePerModule
.setDebtRemediationFunction(oneIssuePerModule.debtRemediationFunctions().linearWithOffset("25min", "1h"))
.setGapDescription("A certified architect will need roughly half an hour to start working on removal of modules, " +
"then it's about one hour per module.");
addAllDescriptionSections(oneIssuePerModule, "Generate an issue on each module");
NewRule oneBlockerIssuePerFile = repo.createRule(OneBlockerIssuePerFileSensor.RULE_KEY).setName("One Blocker Issue Per File");
addAllDescriptionSections(oneBlockerIssuePerFile, "Generate a blocker issue on each file, whatever the severity declared in the Quality profile");
NewRule issueWithCustomMessage = repo.createRule(CustomMessageSensor.RULE_KEY).setName("Issue With Custom Message");
addAllDescriptionSections(issueWithCustomMessage, "Generate an issue on each file with a custom message");
NewRule oneIssuePerFileWithRandomAccess = repo.createRule(RandomAccessSensor.RULE_KEY).setName("One Issue Per File with Random Access");
addAllDescriptionSections(oneIssuePerFileWithRandomAccess, "This issue is generated on each file");
NewRule issueWithRangeAndMultipleLocations = repo.createRule(MultilineIssuesSensor.RULE_KEY).setName("Creates issues with ranges/multiple locations");
addAllDescriptionSections(issueWithRangeAndMultipleLocations, "Issue with range and multiple locations");
NewRule hotspotWithRangeAndMultipleLocations = repo.createRule(MultilineHotspotSensor.RULE_KEY)
.setName("Creates hotspots with ranges/multiple locations")
.setType(RuleType.SECURITY_HOTSPOT);
addAllDescriptionSections(hotspotWithRangeAndMultipleLocations, "Hotspot with range and multiple locations");
NewRule issueOnEachFileWithExtUnknown = repo.createRule(OneIssuePerUnknownFileSensor.RULE_KEY).setName("Creates issues on each file with extension 'unknown'");
addAllDescriptionSections(issueOnEachFileWithExtUnknown, "This issue is generated on each file with extenstion 'unknown'");
NewRule oneBugIssuePerLine = repo.createRule(OneBugIssuePerLineSensor.RULE_KEY).setName("One Bug Issue Per Line")
.setType(RuleType.BUG);
oneBugIssuePerLine
.setDebtRemediationFunction(oneBugIssuePerLine.debtRemediationFunctions().linear("5min"));
addAllDescriptionSections(oneBugIssuePerLine, "Generate a bug issue on each line of a file. It requires the metric \"lines\".");
NewRule oneCodeSmellIssuePerLine = repo.createRule(OneCodeSmellIssuePerLineSensor.RULE_KEY).setName("One Code Smell Issue Per Line")
.setType(RuleType.CODE_SMELL);
oneCodeSmellIssuePerLine
.setDebtRemediationFunction(oneCodeSmellIssuePerLine.debtRemediationFunctions().linear("9min"));
addAllDescriptionSections(oneCodeSmellIssuePerLine, "Generate a code smell issue on each line of a file. It requires the metric \"lines\".");
NewRule oneVulnerabilityIssuePerModule = repo.createRule(OneVulnerabilityIssuePerModuleSensor.RULE_KEY).setName("One Vulnerability Issue Per Module")
.setType(RuleType.VULNERABILITY);
addAllDescriptionSections(oneVulnerabilityIssuePerModule, "Generate an issue on each module");
oneVulnerabilityIssuePerModule
.setDebtRemediationFunction(oneVulnerabilityIssuePerModule.debtRemediationFunctions().linearWithOffset("25min", "1h"))
.setGapDescription("A certified architect will need roughly half an hour to start working on removal of modules, " +
"then it's about one hour per module.");
NewRule templateofRule = repo
.createRule("xoo-template")
.setTemplate(true)
.setName("Template of rule");
addAllDescriptionSections(templateofRule, "Template to be overridden by custom rules");
NewRule hotspot = repo.createRule(HotspotWithoutContextSensor.RULE_KEY)
.setName("Find security hotspots")
.setType(RuleType.SECURITY_HOTSPOT)
.setActivatedByDefault(false);
addAllDescriptionSections(hotspot, "Search for Security Hotspots in Xoo files");
hotspot
.setDebtRemediationFunction(hotspot.debtRemediationFunctions().constantPerIssue("2min"));
NewRule variants = repo.createRule(IssueWithCodeVariantsSensor.RULE_KEY).setName("Find issues with code variants");
addAllDescriptionSections(variants, "Search for a given variant in Xoo files");
if (version != null && version.isGreaterThanOrEqual(Version.create(9, 3))) {
hotspot
.addOwaspTop10(OwaspTop10.A1, OwaspTop10.A3)
.addOwaspTop10(Y2021, OwaspTop10.A3, OwaspTop10.A2)
.addCwe(1, 89, 123, 863);
oneVulnerabilityIssuePerModule
.addOwaspTop10(Y2017, OwaspTop10.A9, OwaspTop10.A10)
.addOwaspTop10(Y2021, OwaspTop10.A6, OwaspTop10.A9)
.addCwe(250, 564, 546, 943);
}
if (version != null && version.isGreaterThanOrEqual(Version.create(9, 5))) {
hotspot
.addPciDss(PciDssVersion.V4_0, "6.5.1", "4.1")
.addPciDss(PciDssVersion.V3_2, "6.5.1", "4.2")
.addPciDss(PciDssVersion.V4_0, "6.5a.1", "4.2c")
.addPciDss(PciDssVersion.V3_2, "6.5a.1b", "4.2b");
oneVulnerabilityIssuePerModule
.addPciDss(PciDssVersion.V4_0, "10.1")
.addPciDss(PciDssVersion.V3_2, "10.2")
.addPciDss(PciDssVersion.V4_0, "10.1a.2b")
.addPciDss(PciDssVersion.V3_2, "10.1a.2c");
}
if (version != null && version.isGreaterThanOrEqual(Version.create(9, 6))) {
hotspot
.addOwaspAsvs(OwaspAsvsVersion.V4_0, "2.8.7", "3.1.1", "4.2.2");
oneVulnerabilityIssuePerModule
.addOwaspAsvs(OwaspAsvsVersion.V4_0, "11.1.2", "14.5.1", "14.5.4");
}
NewRule hotspotWithContexts = repo.createRule(HotspotWithContextsSensor.RULE_KEY)
.setName("Find security hotspots with contexts")
.setType(RuleType.SECURITY_HOTSPOT)
.setActivatedByDefault(false);
addDescriptionSectionsWithoutContexts(hotspotWithContexts, "Search for Security Hotspots with contexts in Xoo files");
addHowToFixSectionsWithContexts(hotspotWithContexts);
NewRule hotspotWithSingleContext = repo.createRule(HotspotWithSingleContextSensor.RULE_KEY)
.setName("Find security hotspots, how_to_fix with single context")
.setType(RuleType.SECURITY_HOTSPOT)
.setActivatedByDefault(false)
.addDescriptionSection(howToFixSectionWithContext("single_context"));
addDescriptionSectionsWithoutContexts(hotspotWithSingleContext, "Search for Security Hotspots with single context in Xoo files");
NewRule hotspotWithCodeVariants = repo.createRule(HotspotWithCodeVariantsSensor.RULE_KEY)
.setName("Find security hotspots with code variants")
.setType(RuleType.SECURITY_HOTSPOT)
.setActivatedByDefault(false);
addAllDescriptionSections(hotspotWithCodeVariants, "Search for a given variant in Xoo files");
repo.done();
}
private static void defineRulesXooExternal(Context context) {
NewRepository repo = context.createExternalRepository(OneExternalIssuePerLineSensor.ENGINE_ID, Xoo.KEY).setName(OneExternalIssuePerLineSensor.ENGINE_ID);
repo.createRule(OnePredefinedRuleExternalIssuePerLineSensor.RULE_ID)
.setSeverity(OnePredefinedRuleExternalIssuePerLineSensor.SEVERITY)
.setType(OnePredefinedRuleExternalIssuePerLineSensor.TYPE)
.setScope(RuleScope.ALL)
.setHtmlDescription("Generates one external issue in each line")
.addDescriptionSection(descriptionSection(INTRODUCTION_SECTION_KEY, "Generates one external issue in each line"))
.setName("One external issue per line")
.setTags("riri", "fifi", "loulou");
repo.done();
}
private static void addAllDescriptionSections(NewRule rule, String description) {
addDescriptionSectionsWithoutContexts(rule, description);
rule.addDescriptionSection(descriptionSection(HOW_TO_FIX_SECTION_KEY, "How to fix: " + description));
}
private static void addDescriptionSectionsWithoutContexts(NewRule rule, String description) {
rule
.setHtmlDescription(description)
.addDescriptionSection(descriptionSection(INTRODUCTION_SECTION_KEY, "Introduction: " + description))
.addDescriptionSection(descriptionSection(ROOT_CAUSE_SECTION_KEY, "Root cause: " + description))
.addDescriptionSection(descriptionSection(ASSESS_THE_PROBLEM_SECTION_KEY, "Assess the problem: " + description))
.addDescriptionSection(descriptionSection(RESOURCES_SECTION_KEY,
"<a href=\"www.google.fr\"> Google </a><br><a href=\"https://stackoverflow.com/\"> StackOverflow</a>"))
.addDescriptionSection(descriptionSection("fake_section_to_be_ignored",
"fake_section_to_be_ignored"));
}
private static void addHowToFixSectionsWithContexts(NewRule rule) {
for (String contextName : AVAILABLE_CONTEXTS) {
rule.addDescriptionSection(howToFixSectionWithContext(contextName));
}
}
private static RuleDescriptionSection descriptionSection(String sectionKey, String htmlDescription) {
return RuleDescriptionSection.builder()
.sectionKey(sectionKey)
.htmlContent(htmlDescription)
.build();
}
private static RuleDescriptionSection howToFixSectionWithContext(String contextName) {
return RuleDescriptionSection.builder()
.sectionKey(HOW_TO_FIX_SECTION_KEY)
.htmlContent(String.format("This is 'How to fix?' description section for the <a href=\"https://stackoverflow.com/\"> %s</a>. " +
"This text can be very long.", contextName))
.context(new org.sonar.api.server.rule.Context(contextName, contextName))
.build();
}
}
| 18,805 | 52.885387 | 163 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/XooSonarWayProfile.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import org.sonar.api.rule.Severity;
import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition;
import org.sonar.xoo.Xoo;
import org.sonar.xoo.rule.hotspot.HotspotWithContextsSensor;
import org.sonar.xoo.rule.hotspot.HotspotWithSingleContextSensor;
import org.sonar.xoo.rule.hotspot.HotspotWithoutContextSensor;
public class XooSonarWayProfile implements BuiltInQualityProfilesDefinition {
@Override
public void define(Context context) {
NewBuiltInQualityProfile qProfile = context.createBuiltInQualityProfile("Sonar way", Xoo.KEY);
qProfile.activateRule(XooRulesDefinition.XOO_REPOSITORY, HasTagSensor.RULE_KEY).overrideSeverity(Severity.MAJOR);
qProfile.activateRule(XooRulesDefinition.XOO_REPOSITORY, OneIssuePerLineSensor.RULE_KEY).overrideSeverity(Severity.INFO);
qProfile.activateRule(XooRulesDefinition.XOO_REPOSITORY, OneIssuePerFileSensor.RULE_KEY).overrideSeverity(Severity.CRITICAL);
qProfile.activateRule(XooRulesDefinition.XOO_REPOSITORY, HotspotWithoutContextSensor.RULE_KEY).overrideSeverity(Severity.CRITICAL);
qProfile.activateRule(XooRulesDefinition.XOO_REPOSITORY, HotspotWithContextsSensor.RULE_KEY).overrideSeverity(Severity.CRITICAL);
qProfile.activateRule(XooRulesDefinition.XOO_REPOSITORY, HotspotWithSingleContextSensor.RULE_KEY).overrideSeverity(Severity.CRITICAL);
qProfile.done();
}
}
| 2,234 | 52.214286 | 138 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.
*/
@ParametersAreNonnullByDefault
package org.sonar.xoo.rule;
import javax.annotation.ParametersAreNonnullByDefault;
| 958 | 38.958333 | 75 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/hotspot/HotspotSensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule.hotspot;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.rule.ActiveRules;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.issue.NewIssue;
import org.sonar.api.rule.RuleKey;
import org.sonar.xoo.rule.AbstractXooRuleSensor;
/**
* Raise security hotspots all the occurrences of tag defined by getTag() in xoo sources.
*/
public abstract class HotspotSensor extends AbstractXooRuleSensor {
protected HotspotSensor(FileSystem fs, ActiveRules activeRules) {
super(fs, activeRules);
}
protected abstract String getTag();
@Override
protected void processFile(InputFile inputFile, SensorContext context, RuleKey ruleKey, String languageKey) {
try {
int[] lineCounter = {1};
try (InputStreamReader isr = new InputStreamReader(inputFile.inputStream(), inputFile.charset());
BufferedReader reader = new BufferedReader(isr)) {
reader.lines().forEachOrdered(lineStr -> {
int startIndex = -1;
while ((startIndex = lineStr.indexOf(getTag(), startIndex + 1)) != -1) {
NewIssue newIssue = context.newIssue();
newIssue
.forRule(ruleKey)
.at(newIssue.newLocation()
.on(inputFile)
.at(inputFile.newRange(lineCounter[0], startIndex, lineCounter[0], startIndex + getTag().length())))
.save();
}
lineCounter[0]++;
});
}
} catch (IOException e) {
throw new IllegalStateException("Fail to process " + inputFile, e);
}
}
}
| 2,581 | 36.42029 | 116 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/hotspot/HotspotWithContextsSensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule.hotspot;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.rule.ActiveRules;
/**
* Generates security hotspots with contexts on all the occurrences of tag HOTSPOT_WITH_CONTEXTS in xoo sources.
*/
public class HotspotWithContextsSensor extends HotspotSensor {
public static final String RULE_KEY = "HotspotWithContexts";
public static final String TAG = "HOTSPOT_WITH_CONTEXTS";
public HotspotWithContextsSensor(FileSystem fs, ActiveRules activeRules) {
super(fs, activeRules);
}
@Override
protected String getRuleKey() {
return RULE_KEY;
}
@Override
public String getTag() {
return TAG;
}
}
| 1,521 | 30.708333 | 112 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/hotspot/HotspotWithSingleContextSensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule.hotspot;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.rule.ActiveRules;
/**
* Generates security hotspots with contexts on all the occurrences of tag HOTSPOT_WITH_CONTEXTS in xoo sources.
*/
public class HotspotWithSingleContextSensor extends HotspotSensor {
public static final String RULE_KEY = "HotspotWithSingleContext";
public static final String TAG = "HOTSPOT_WITH_SINGLE_CONTEXT";
public HotspotWithSingleContextSensor(FileSystem fs, ActiveRules activeRules) {
super(fs, activeRules);
}
@Override
protected String getRuleKey() {
return RULE_KEY;
}
@Override
public String getTag() {
return TAG;
}
}
| 1,542 | 31.145833 | 112 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/hotspot/HotspotWithoutContextSensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule.hotspot;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.rule.ActiveRules;
/**
* Generates security hotspots on all the occurrences of tag HOTSPOT in xoo sources.
*/
public class HotspotWithoutContextSensor extends HotspotSensor {
public static final String RULE_KEY = "Hotspot";
public static final String TAG = "HOTSPOT_WITHOUT_CONTEXT";
public HotspotWithoutContextSensor(FileSystem fs, ActiveRules activeRules) {
super(fs, activeRules);
}
@Override
protected String getRuleKey() {
return RULE_KEY;
}
@Override
public String getTag() {
return TAG;
}
}
| 1,487 | 30 | 84 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/variant/CodeVariantSensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule.variant;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.rule.ActiveRules;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.issue.NewIssue;
import org.sonar.api.config.Configuration;
import org.sonar.api.rule.RuleKey;
import org.sonar.xoo.rule.AbstractXooRuleSensor;
/**
* Raise issue for multiple code variants.
* Use the property "sonar.variants" to define the variants.
* If variant names are found on the file content, an issue is raised with all the corresponding variants.
* Extend this abstract class to define the rule key.
*/
public abstract class CodeVariantSensor extends AbstractXooRuleSensor {
private static final String VARIANTS_PROPERTY = "sonar.variants";
private final Configuration settings;
public CodeVariantSensor(Configuration settings, FileSystem fs, ActiveRules activeRules) {
super(fs, activeRules);
this.settings = settings;
}
@Override
protected void processFile(InputFile inputFile, SensorContext context, RuleKey ruleKey, String languageKey) {
Optional<String> variantsValue = settings.get(VARIANTS_PROPERTY);
if (variantsValue.isEmpty()) {
return;
}
List<String> variants = Arrays.asList(variantsValue.get().split(","));
try {
String contents = inputFile.contents();
List<String> identifiedVariants = variants.stream()
.filter(contents::contains)
.collect(Collectors.toList());
if (!identifiedVariants.isEmpty()) {
NewIssue newIssue = context.newIssue()
.forRule(ruleKey)
.setCodeVariants(identifiedVariants);
newIssue.at(newIssue.newLocation()
.on(inputFile)
.message("This is generated for variants"))
.save();
}
} catch (IOException e) {
throw new IllegalStateException("Fail to get content of file " + inputFile, e);
}
}
}
| 2,950 | 34.554217 | 111 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/variant/HotspotWithCodeVariantsSensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule.variant;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.rule.ActiveRules;
import org.sonar.api.config.Configuration;
/**
* Raises security hotspots with code variants.
*/
public class HotspotWithCodeVariantsSensor extends CodeVariantSensor {
public static final String RULE_KEY = "HotspotWithCodeVariants";
public HotspotWithCodeVariantsSensor(Configuration settings, FileSystem fs, ActiveRules activeRules) {
super(settings, fs, activeRules);
}
@Override
protected String getRuleKey() {
return RULE_KEY;
}
}
| 1,428 | 33.02381 | 104 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/variant/IssueWithCodeVariantsSensor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule.variant;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.rule.ActiveRules;
import org.sonar.api.config.Configuration;
/**
* Raises issues with code variants.
*/
public class IssueWithCodeVariantsSensor extends CodeVariantSensor {
public static final String RULE_KEY = "IssueWithCodeVariants";
public IssueWithCodeVariantsSensor(Configuration settings, FileSystem fs, ActiveRules activeRules) {
super(settings, fs, activeRules);
}
@Override
protected String getRuleKey() {
return RULE_KEY;
}
}
| 1,411 | 32.619048 | 102 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/scm/XooBlameCommand.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.scm;
import com.google.common.annotations.VisibleForTesting;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.scm.BlameCommand;
import org.sonar.api.batch.scm.BlameLine;
import org.sonar.api.utils.DateUtils;
import static com.google.common.base.Preconditions.checkState;
import static java.util.stream.Collectors.toList;
import static org.apache.commons.lang.StringUtils.trimToNull;
public class XooBlameCommand extends BlameCommand {
private static final String SCM_EXTENSION = ".scm";
@Override
public void blame(BlameInput input, BlameOutput result) {
for (InputFile inputFile : input.filesToBlame()) {
processFile(inputFile, result);
}
}
@VisibleForTesting
protected void processFile(InputFile inputFile, BlameOutput result) {
File ioFile = inputFile.file();
File scmDataFile = new File(ioFile.getParentFile(), ioFile.getName() + SCM_EXTENSION);
if (!scmDataFile.exists()) {
return;
}
try {
List<BlameLine> blame = readFile(scmDataFile);
result.blameResult(inputFile, blame);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
private static List<BlameLine> readFile(File inputStream) throws IOException {
Date now = new Date();
try (CSVParser csvParser = CSVFormat.RFC4180
.withIgnoreEmptyLines()
.withIgnoreSurroundingSpaces()
.parse(new FileReader(inputStream))) {
List<CSVRecord> records = csvParser.getRecords();
return records.stream()
.map(r -> convertToBlameLine(now, r))
.collect(toList());
}
}
private static BlameLine convertToBlameLine(Date now, CSVRecord csvRecord) {
checkState(csvRecord.size() >= 3, "Not enough fields on line %s", csvRecord);
String revision = trimToNull(csvRecord.get(0));
String author = trimToNull(csvRecord.get(1));
BlameLine blameLine = new BlameLine().revision(revision).author(author);
String dateStr = trimToNull(csvRecord.get(2));
if (dateStr != null) {
// try to load a relative number of days
try {
int days = Integer.parseInt(dateStr);
blameLine.date(DateUtils.addDays(now, days));
} catch (NumberFormatException e) {
Date dateTime = DateUtils.parseDateTimeQuietly(dateStr);
if (dateTime != null) {
blameLine.date(dateTime);
} else {
// Will throw an exception, when date is not in format "yyyy-MM-dd"
blameLine.date(DateUtils.parseDate(dateStr));
}
}
}
return blameLine;
}
}
| 3,658 | 34.182692 | 90 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/scm/XooIgnoreCommand.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.scm;
import java.io.File;
import java.nio.file.Path;
import org.apache.commons.io.FilenameUtils;
import org.sonar.api.batch.scm.IgnoreCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* To ignore a file simply add an empty file with the same name as the file to ignore with a .ignore suffix.
* E.g. to ignore src/foo.xoo create the file src/foo.xoo.ignore
*/
public class XooIgnoreCommand implements IgnoreCommand {
static final String IGNORE_FILE_EXTENSION = ".ignore";
private static final Logger LOG = LoggerFactory.getLogger(XooIgnoreCommand.class);
private boolean isInit;
@Override
public boolean isIgnored(Path path) {
if (!isInit) {
throw new IllegalStateException("Called init() first");
}
String fullPath = FilenameUtils.getFullPath(path.toAbsolutePath().toString());
File scmIgnoreFile = new File(fullPath, path.getFileName() + IGNORE_FILE_EXTENSION);
return scmIgnoreFile.exists();
}
@Override
public void init(Path baseDir) {
isInit = true;
LOG.debug("Init IgnoreCommand on dir '{}'");
}
@Override
public void clean() {
LOG.debug("Clean IgnoreCommand");
}
}
| 2,027 | 32.8 | 108 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/scm/XooScmProvider.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.scm;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.CheckForNull;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.batch.scm.BlameCommand;
import org.sonar.api.batch.scm.IgnoreCommand;
import org.sonar.api.batch.scm.ScmProvider;
public class XooScmProvider extends ScmProvider {
private static final Logger LOG = LoggerFactory.getLogger(XooScmProvider.class);
private static final String SCM_EXTENSION = ".scm";
private final XooBlameCommand blame;
private XooIgnoreCommand ignore;
public XooScmProvider(XooBlameCommand blame, XooIgnoreCommand ignore) {
this.blame = blame;
this.ignore = ignore;
}
@Override
public boolean supports(File baseDir) {
return new File(baseDir, ".xoo").exists();
}
@Override
public String key() {
return "xoo";
}
@Override
public BlameCommand blameCommand() {
return blame;
}
@Override
public IgnoreCommand ignoreCommand() {
return ignore;
}
@Override
public String revisionId(Path path) {
return "fakeSha1FromXoo";
}
@CheckForNull
public Set<Path> branchChangedFiles(String targetBranchName, Path rootBaseDir) {
Set<Path> changedFiles = new HashSet<>();
Set<Path> scmFiles = new HashSet<>();
try {
Files.walkFileTree(rootBaseDir, new SimpleFileVisitor<Path>() {
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
if (file.getFileName().toString().endsWith(".scm")) {
scmFiles.add(file);
}
return FileVisitResult.CONTINUE;
}
});
if (scmFiles.isEmpty()) {
return null;
}
for (Path scmFilePath : scmFiles) {
String fileName = scmFilePath.getFileName().toString();
Path filePath = scmFilePath.resolveSibling(fileName.substring(0, fileName.length() - 4));
if (!Files.exists(filePath)) {
continue;
}
Set<Integer> newLines = loadNewLines(scmFilePath);
if (newLines == null) {
return null;
}
if (!newLines.isEmpty()) {
changedFiles.add(filePath);
}
}
} catch (IOException e) {
throw new IllegalStateException("Failed to find scm files", e);
}
return changedFiles;
}
@CheckForNull
public Map<Path, Set<Integer>> branchChangedLines(String targetBranchName, Path rootBaseDir, Set<Path> files) {
Map<Path, Set<Integer>> map = new HashMap<>();
for (Path filePath : files) {
Path scmFilePath = filePath.resolveSibling(filePath.getFileName() + SCM_EXTENSION);
try {
Set<Integer> newLines = loadNewLines(scmFilePath);
if (newLines != null && !newLines.isEmpty()) {
map.put(filePath, newLines);
}
} catch (IOException e) {
throw new IllegalStateException("Failed to parse scm file", e);
}
}
return map.isEmpty() ? null : map;
}
// return null when any of the scm files lack the is-new flag (column 4)
@CheckForNull
private Set<Integer> loadNewLines(Path filePath) throws IOException {
if (!Files.isRegularFile(filePath)) {
return Collections.emptySet();
}
LOG.debug("Processing " + filePath.toAbsolutePath());
Set<Integer> newLines = new HashSet<>();
List<String> lines = Files.readAllLines(filePath, StandardCharsets.UTF_8);
int lineNum = 0;
boolean foundNewLineFlag = false;
for (String line : lines) {
lineNum++;
String[] fields = StringUtils.splitPreserveAllTokens(line, ',');
if (fields.length < 4) {
continue;
}
foundNewLineFlag = true;
if (Boolean.parseBoolean(fields[3])) {
newLines.add(lineNum);
}
}
return foundNewLineFlag ? newLines : null;
}
}
| 5,060 | 29.487952 | 113 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/scm/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.
*/
@ParametersAreNonnullByDefault
package org.sonar.xoo.scm;
import javax.annotation.ParametersAreNonnullByDefault;
| 957 | 38.916667 | 75 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/XooPluginTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo;
import java.util.List;
import org.junit.Test;
import org.sonar.api.Plugin;
import org.sonar.api.SonarEdition;
import org.sonar.api.SonarQubeSide;
import org.sonar.api.SonarRuntime;
import org.sonar.api.internal.PluginContextImpl;
import org.sonar.api.internal.SonarRuntimeImpl;
import org.sonar.api.utils.Version;
import org.sonar.xoo.global.GlobalProjectSensor;
import org.sonar.xoo.lang.MeasureSensor;
import org.sonar.xoo.scm.XooIgnoreCommand;
import static org.assertj.core.api.Assertions.assertThat;
public class XooPluginTest {
@Test
public void provide_extensions_for_sonar_lint() {
SonarRuntime runtime = SonarRuntimeImpl.forSonarLint(Version.parse("5.4"));
Plugin.Context context = new PluginContextImpl.Builder().setSonarRuntime(runtime).build();
new XooPlugin().define(context);
assertThat(getExtensions(context))
.isNotEmpty()
.doesNotContain(MeasureSensor.class);
}
@Test
public void provide_extensions_for_sonar_qube() {
SonarRuntime runtime = SonarRuntimeImpl.forSonarQube(Version.parse("8.4"), SonarQubeSide.SCANNER, SonarEdition.COMMUNITY);
Plugin.Context context = new PluginContextImpl.Builder().setSonarRuntime(runtime).build();
new XooPlugin().define(context);
assertThat(getExtensions(context))
.isNotEmpty()
.contains(MeasureSensor.class)
.contains(GlobalProjectSensor.class)
.contains(XooIgnoreCommand.class);
}
@SuppressWarnings("unchecked")
private static List<Object> getExtensions(Plugin.Context context) {
return (List<Object>) context.getExtensions();
}
}
| 2,450 | 35.044118 | 126 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/coverage/ItCoverageSensorTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.coverage;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.sensor.internal.DefaultSensorDescriptor;
import org.sonar.api.batch.sensor.internal.SensorContextTester;
import static org.assertj.core.api.Assertions.assertThat;
public class ItCoverageSensorTest {
private ItCoverageSensor sensor;
private SensorContextTester context;
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private File baseDir;
@Before
public void prepare() throws IOException {
baseDir = temp.newFolder();
sensor = new ItCoverageSensor();
context = SensorContextTester.create(baseDir);
}
@Test
public void testDescriptor() {
sensor.describe(new DefaultSensorDescriptor());
}
@Test
public void testNoExecutionIfNoCoverageFile() {
InputFile inputFile = new TestInputFileBuilder("foo", "src/foo.xoo").setLanguage("xoo").build();
context.fileSystem().add(inputFile);
sensor.execute(context);
}
@Test
public void testLineHitNoConditions() throws IOException {
File coverage = new File(baseDir, "src/foo.xoo.itcoverage");
FileUtils.write(coverage, "1:3\n\n#comment");
InputFile inputFile = new TestInputFileBuilder("foo", "src/foo.xoo").setModuleBaseDir(baseDir.toPath()).setLanguage("xoo").setLines(10).build();
context.fileSystem().add(inputFile);
sensor.execute(context);
assertThat(context.lineHits("foo:src/foo.xoo", 1)).isEqualTo(3);
}
@Test
public void testLineHitAndConditions() throws IOException {
File coverage = new File(baseDir, "src/foo.xoo.itcoverage");
FileUtils.write(coverage, "1:3:4:2");
InputFile inputFile = new TestInputFileBuilder("foo", "src/foo.xoo").setModuleBaseDir(baseDir.toPath()).setLanguage("xoo").setLines(10).build();
context.fileSystem().add(inputFile);
sensor.execute(context);
assertThat(context.lineHits("foo:src/foo.xoo", 1)).isEqualTo(3);
assertThat(context.conditions("foo:src/foo.xoo", 1)).isEqualTo(4);
assertThat(context.coveredConditions("foo:src/foo.xoo", 1)).isEqualTo(2);
}
}
| 3,184 | 34 | 148 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/coverage/OverallCoverageSensorTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.coverage;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.sensor.internal.DefaultSensorDescriptor;
import org.sonar.api.batch.sensor.internal.SensorContextTester;
import static org.assertj.core.api.Assertions.assertThat;
public class OverallCoverageSensorTest {
private OverallCoverageSensor sensor;
private SensorContextTester context;
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private File baseDir;
@Before
public void prepare() throws IOException {
baseDir = temp.newFolder();
sensor = new OverallCoverageSensor();
context = SensorContextTester.create(baseDir);
}
@Test
public void testDescriptor() {
sensor.describe(new DefaultSensorDescriptor());
}
@Test
public void testNoExecutionIfNoCoverageFile() {
InputFile inputFile = new TestInputFileBuilder("foo", "src/foo.xoo").setLanguage("xoo").setModuleBaseDir(baseDir.toPath()).build();
context.fileSystem().add(inputFile);
sensor.execute(context);
}
@Test
public void testLineHitNoConditions() throws IOException {
File coverage = new File(baseDir, "src/foo.xoo.overallcoverage");
FileUtils.write(coverage, "1:3\n\n#comment");
InputFile inputFile = new TestInputFileBuilder("foo", "src/foo.xoo").setLanguage("xoo").setModuleBaseDir(baseDir.toPath()).setLines(10).build();
context.fileSystem().add(inputFile);
sensor.execute(context);
assertThat(context.lineHits("foo:src/foo.xoo", 1)).isEqualTo(3);
}
@Test
public void testLineHitAndConditions() throws IOException {
File coverage = new File(baseDir, "src/foo.xoo.overallcoverage");
FileUtils.write(coverage, "1:3:4:2");
InputFile inputFile = new TestInputFileBuilder("foo", "src/foo.xoo").setLanguage("xoo").setModuleBaseDir(baseDir.toPath()).setLines(10).build();
context.fileSystem().add(inputFile);
sensor.execute(context);
assertThat(context.lineHits("foo:src/foo.xoo", 1)).isEqualTo(3);
assertThat(context.conditions("foo:src/foo.xoo", 1)).isEqualTo(4);
assertThat(context.coveredConditions("foo:src/foo.xoo", 1)).isEqualTo(2);
}
}
| 3,244 | 34.659341 | 148 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/coverage/UtCoverageSensorTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.coverage;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.sensor.internal.DefaultSensorDescriptor;
import org.sonar.api.batch.sensor.internal.SensorContextTester;
import static org.assertj.core.api.Assertions.assertThat;
public class UtCoverageSensorTest {
private UtCoverageSensor sensor;
private SensorContextTester context;
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private File baseDir;
@Before
public void prepare() throws IOException {
baseDir = temp.newFolder();
sensor = new UtCoverageSensor();
context = SensorContextTester.create(baseDir);
}
@Test
public void testDescriptor() {
sensor.describe(new DefaultSensorDescriptor());
}
@Test
public void testNoExecutionIfNoCoverageFile() {
InputFile inputFile = new TestInputFileBuilder("foo", "src/foo.xoo").setLanguage("xoo").setModuleBaseDir(baseDir.toPath()).build();
context.fileSystem().add(inputFile);
sensor.execute(context);
}
@Test
public void testLineHitNoConditions() throws IOException {
File coverage = new File(baseDir, "src/foo.xoo.coverage");
FileUtils.write(coverage, "1:3\n\n#comment");
InputFile inputFile = new TestInputFileBuilder("foo", "src/foo.xoo").setLanguage("xoo").setModuleBaseDir(baseDir.toPath()).setLines(10).build();
context.fileSystem().add(inputFile);
sensor.execute(context);
assertThat(context.lineHits("foo:src/foo.xoo", 1)).isEqualTo(3);
}
@Test
public void testLineHitAndConditions() throws IOException {
File coverage = new File(baseDir, "src/foo.xoo.coverage");
FileUtils.write(coverage, "1:3:4:2");
InputFile inputFile = new TestInputFileBuilder("foo", "src/foo.xoo").setLanguage("xoo").setModuleBaseDir(baseDir.toPath()).setLines(10).build();
context.fileSystem().add(inputFile);
sensor.execute(context);
assertThat(context.lineHits("foo:src/foo.xoo", 1)).isEqualTo(3);
assertThat(context.conditions("foo:src/foo.xoo", 1)).isEqualTo(4);
assertThat(context.coveredConditions("foo:src/foo.xoo", 1)).isEqualTo(2);
}
}
| 3,215 | 34.340659 | 148 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/extensions/XooPostJobTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.extensions;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.batch.postjob.PostJobContext;
import org.sonar.api.batch.postjob.internal.DefaultPostJobDescriptor;
import org.sonar.api.testfixtures.log.LogTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
public class XooPostJobTest {
@Rule
public LogTester logTester = new LogTester();
@Test
public void increaseCoverage() {
new XooPostJob().describe(new DefaultPostJobDescriptor());
PostJobContext context = mock(PostJobContext.class);
new XooPostJob().execute(context);
assertThat(logTester.logs()).contains("Running Xoo PostJob");
}
}
| 1,556 | 34.386364 | 75 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/lang/CpdTokenizerSensorTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.lang;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.sensor.internal.DefaultSensorDescriptor;
import org.sonar.api.batch.sensor.internal.SensorContextTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
public class CpdTokenizerSensorTest {
private CpdTokenizerSensor sensor;
private SensorContextTester context;
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private File baseDir;
@Before
public void prepare() throws IOException {
baseDir = temp.newFolder();
sensor = new CpdTokenizerSensor();
context = SensorContextTester.create(baseDir);
}
@Test
public void testDescriptor() {
sensor.describe(new DefaultSensorDescriptor());
}
@Test
public void testExecution() throws IOException {
String content = "public class Foo {\n\n}";
createSourceFile(content);
sensor.execute(context);
assertThat(context.cpdTokens("foo:src/foo.xoo")).extracting("value", "startLine", "startUnit", "endUnit")
.containsExactly(
tuple("publicclassFoo{", 1, 1, 4),
tuple("}", 3, 5, 5));
}
private void createSourceFile(String content) throws IOException {
File sourceFile = new File(baseDir, "src/foo.xoo");
FileUtils.write(sourceFile, content);
InputFile inputFile = new TestInputFileBuilder("foo", "src/foo.xoo")
.setLanguage("xoo")
.initMetadata(content)
.setCharset(Charset.defaultCharset())
.setModuleBaseDir(baseDir.toPath())
.build();
context.fileSystem().add(inputFile);
}
}
| 2,764 | 30.781609 | 109 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/lang/MeasureSensorTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.lang;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.measure.MetricFinder;
import org.sonar.api.batch.sensor.internal.DefaultSensorDescriptor;
import org.sonar.api.batch.sensor.internal.SensorContextTester;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.measures.Metric;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class MeasureSensorTest {
private MeasureSensor sensor;
private SensorContextTester context;
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private File baseDir;
private MetricFinder metricFinder;
@Before
public void prepare() throws IOException {
baseDir = temp.newFolder();
metricFinder = mock(MetricFinder.class);
sensor = new MeasureSensor(metricFinder);
context = SensorContextTester.create(baseDir);
}
@Test
public void testDescriptor() {
sensor.describe(new DefaultSensorDescriptor());
}
@Test
public void testNoExecutionIfNoMeasureFile() {
InputFile inputFile = new TestInputFileBuilder("foo", "src/foo.xoo").setLanguage("xoo").build();
context.fileSystem().add(inputFile);
sensor.execute(context);
}
@Test
public void testExecution() throws IOException {
File measures = new File(baseDir, "src/foo.xoo.measures");
FileUtils.write(measures, "ncloc:12\nbranch_coverage:5.3\nsqale_index:300\nbool:true\n\n#comment", StandardCharsets.UTF_8);
InputFile inputFile = new TestInputFileBuilder("foo", "src/foo.xoo").setLanguage("xoo").setModuleBaseDir(baseDir.toPath()).build();
context.fileSystem().add(inputFile);
Metric<Boolean> booleanMetric = new Metric.Builder("bool", "Bool", Metric.ValueType.BOOL)
.create();
when(metricFinder.<Integer>findByKey("ncloc")).thenReturn(CoreMetrics.NCLOC);
when(metricFinder.<Double>findByKey("branch_coverage")).thenReturn(CoreMetrics.BRANCH_COVERAGE);
when(metricFinder.<Long>findByKey("sqale_index")).thenReturn(CoreMetrics.TECHNICAL_DEBT);
when(metricFinder.<Boolean>findByKey("bool")).thenReturn(booleanMetric);
sensor.execute(context);
assertThat(context.measure("foo:src/foo.xoo", CoreMetrics.NCLOC).value()).isEqualTo(12);
assertThat(context.measure("foo:src/foo.xoo", CoreMetrics.BRANCH_COVERAGE).value()).isEqualTo(5.3);
assertThat(context.measure("foo:src/foo.xoo", CoreMetrics.TECHNICAL_DEBT).value()).isEqualTo(300L);
assertThat(context.measure("foo:src/foo.xoo", booleanMetric).value()).isTrue();
}
@Test
public void testExecutionForFoldersMeasures_no_measures() throws IOException {
File measures = new File(baseDir, "src/folder.measures");
FileUtils.write(measures, "ncloc:12\nbranch_coverage:5.3\nsqale_index:300\nbool:true\n\n#comment", StandardCharsets.UTF_8);
InputFile inputFile = new TestInputFileBuilder("foo", "src/foo.xoo").setLanguage("xoo").setModuleBaseDir(baseDir.toPath()).build();
context.fileSystem().add(inputFile);
Metric<Boolean> booleanMetric = new Metric.Builder("bool", "Bool", Metric.ValueType.BOOL)
.create();
when(metricFinder.<Integer>findByKey("ncloc")).thenReturn(CoreMetrics.NCLOC);
when(metricFinder.<Double>findByKey("branch_coverage")).thenReturn(CoreMetrics.BRANCH_COVERAGE);
when(metricFinder.<Long>findByKey("sqale_index")).thenReturn(CoreMetrics.TECHNICAL_DEBT);
when(metricFinder.<Boolean>findByKey("bool")).thenReturn(booleanMetric);
sensor.execute(context);
assertThat(context.measure("foo:src", CoreMetrics.NCLOC)).isNull();
}
@Test
public void failIfMetricNotFound() throws IOException {
File measures = new File(baseDir, "src/foo.xoo.measures");
FileUtils.write(measures, "unknow:12\n\n#comment");
InputFile inputFile = new TestInputFileBuilder("foo", "src/foo.xoo").setLanguage("xoo").setModuleBaseDir(baseDir.toPath()).build();
context.fileSystem().add(inputFile);
assertThatThrownBy(() -> sensor.execute(context))
.isInstanceOf(IllegalStateException.class);
}
}
| 5,300 | 40.414063 | 135 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/lang/SignificantCodeSensorTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.lang;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.TextRange;
import org.sonar.api.batch.fs.internal.DefaultTextPointer;
import org.sonar.api.batch.fs.internal.DefaultTextRange;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.sensor.internal.DefaultSensorDescriptor;
import org.sonar.api.batch.sensor.internal.SensorContextTester;
import static org.assertj.core.api.Assertions.assertThat;
public class SignificantCodeSensorTest {
private SignificantCodeSensor sensor;
private SensorContextTester context;
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private File baseDir;
private InputFile inputFile;
@Before
public void prepare() throws IOException {
baseDir = temp.newFolder();
sensor = new SignificantCodeSensor();
context = SensorContextTester.create(baseDir);
inputFile = new TestInputFileBuilder("foo", baseDir, new File(baseDir, "src/foo.xoo"))
.setLanguage("xoo")
.setContents("some lines\nof code\nyet another line")
.build();
}
@Test
public void testDescriptor() {
sensor.describe(new DefaultSensorDescriptor());
}
@Test
public void testNoExceptionIfNoFileWithOffsets() {
context.fileSystem().add(inputFile);
sensor.execute(context);
}
@Test
public void testExecution() throws IOException {
File significantCode = new File(baseDir, "src/foo.xoo.significantCode");
FileUtils.write(significantCode, "1,1,4\n2,2,5");
context.fileSystem().add(inputFile);
sensor.execute(context);
assertThat(context.significantCodeTextRange("foo:src/foo.xoo", 1)).isEqualTo(range(1, 1, 4));
assertThat(context.significantCodeTextRange("foo:src/foo.xoo", 2)).isEqualTo(range(2, 2, 5));
}
private static TextRange range(int line, int startOffset, int endOffset) {
return new DefaultTextRange(new DefaultTextPointer(line, startOffset), new DefaultTextPointer(line, endOffset));
}
}
| 3,040 | 33.556818 | 116 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/lang/SymbolReferencesSensorTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.lang;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.DefaultTextPointer;
import org.sonar.api.batch.fs.internal.DefaultTextRange;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.sensor.internal.DefaultSensorDescriptor;
import org.sonar.api.batch.sensor.internal.SensorContextTester;
import org.sonar.xoo.Xoo;
import static org.assertj.core.api.Assertions.assertThat;
public class SymbolReferencesSensorTest {
private SymbolReferencesSensor sensor = new SymbolReferencesSensor();
private SensorContextTester context;
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private File baseDir;
@Before
public void prepare() throws IOException {
baseDir = temp.newFolder();
context = SensorContextTester.create(baseDir);
}
@Test
public void testDescriptor() {
sensor.describe(new DefaultSensorDescriptor());
}
@Test
public void testNoExecutionIfNoSymbolFile() {
InputFile inputFile = new TestInputFileBuilder("foo", "src/foo.xoo").setLanguage("xoo").setModuleBaseDir(baseDir.toPath()).build();
context.fileSystem().add(inputFile);
sensor.execute(context);
}
@Test
public void testExecution() throws IOException {
File symbol = new File(baseDir, "src/foo.xoo.symbol");
FileUtils.write(symbol, "1:1:1:4,1:7:1:10\n1:11:1:13,1:14:1:33\n\n#comment");
InputFile inputFile = new TestInputFileBuilder("foo", "src/foo.xoo")
.initMetadata("xoo file with some source code and length over 33")
.setLanguage(Xoo.KEY)
.setModuleBaseDir(baseDir.toPath())
.build();
context.fileSystem().add(inputFile);
sensor.execute(context);
assertThat(context.referencesForSymbolAt("foo:src/foo.xoo", 1, 2))
.containsOnly(new DefaultTextRange(new DefaultTextPointer(1, 7), new DefaultTextPointer(1, 10)));
assertThat(context.referencesForSymbolAt("foo:src/foo.xoo", 1, 12))
.containsOnly(new DefaultTextRange(new DefaultTextPointer(1, 14), new DefaultTextPointer(1, 33)));
}
}
| 3,122 | 35.313953 | 135 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/lang/SyntaxHighlightingSensorTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.lang;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.sensor.highlighting.TypeOfText;
import org.sonar.api.batch.sensor.internal.DefaultSensorDescriptor;
import org.sonar.api.batch.sensor.internal.SensorContextTester;
import static org.assertj.core.api.Assertions.assertThat;
public class SyntaxHighlightingSensorTest {
private SyntaxHighlightingSensor sensor;
private SensorContextTester context;
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private File baseDir;
@Before
public void prepare() throws IOException {
baseDir = temp.newFolder();
sensor = new SyntaxHighlightingSensor();
context = SensorContextTester.create(baseDir);
}
@Test
public void testDescriptor() {
sensor.describe(new DefaultSensorDescriptor());
}
@Test
public void testNoExecutionIfNoSyntaxFile() {
DefaultInputFile inputFile = new TestInputFileBuilder("foo", "src/foo.xoo")
.setLanguage("xoo")
.setModuleBaseDir(baseDir.toPath())
.build();
context.fileSystem().add(inputFile);
sensor.execute(context);
}
@Test
public void testExecution() throws IOException {
File symbol = new File(baseDir, "src/foo.xoo.highlighting");
FileUtils.write(symbol, "1:1:1:4:k\n2:7:2:10:cd\n\n#comment");
DefaultInputFile inputFile = new TestInputFileBuilder("foo", "src/foo.xoo")
.setLanguage("xoo")
.setModuleBaseDir(baseDir.toPath())
.initMetadata(" xoo\nazertyazer\nfoo")
.build();
context.fileSystem().add(inputFile);
sensor.execute(context);
assertThat(context.highlightingTypeAt("foo:src/foo.xoo", 1, 2)).containsOnly(TypeOfText.KEYWORD);
assertThat(context.highlightingTypeAt("foo:src/foo.xoo", 2, 8)).containsOnly(TypeOfText.COMMENT);
}
}
| 2,920 | 33.364706 | 101 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/rule/AnalysisErrorSensorTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.sensor.error.AnalysisError;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.DefaultTextPointer;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.sensor.internal.SensorContextTester;
import static org.assertj.core.api.Assertions.assertThat;
public class AnalysisErrorSensorTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private AnalysisErrorSensor sensor;
@Before
public void setUp() {
sensor = new AnalysisErrorSensor();
}
private void createErrorFile(Path baseDir) throws IOException {
Path srcDir = baseDir.resolve("src");
Files.createDirectories(srcDir);
Path errorFile = srcDir.resolve("foo.xoo.error");
List<String> errors = new ArrayList<>();
errors.add("1,4,my error");
Files.write(errorFile, errors, StandardCharsets.UTF_8);
}
@Test
public void test() throws IOException {
Path baseDir = temp.newFolder().toPath().toAbsolutePath();
createErrorFile(baseDir);
int[] startOffsets = {10, 20, 30, 40};
int[] endOffsets = {19, 29, 39, 49};
DefaultInputFile inputFile = new TestInputFileBuilder("foo", "src/foo.xoo")
.setLanguage("xoo")
.setOriginalLineStartOffsets(startOffsets)
.setOriginalLineEndOffsets(endOffsets)
.setModuleBaseDir(baseDir)
.setLines(4)
.build();
SensorContextTester context = SensorContextTester.create(baseDir);
context.fileSystem().add(inputFile);
sensor.execute(context);
assertThat(context.allAnalysisErrors()).hasSize(1);
AnalysisError error = context.allAnalysisErrors().iterator().next();
assertThat(error.inputFile()).isEqualTo(inputFile);
assertThat(error.location()).isEqualTo(new DefaultTextPointer(1, 4));
assertThat(error.message()).isEqualTo("my error");
}
}
| 3,038 | 33.534091 | 79 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/rule/HotspotWithContextsSensorTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import java.io.IOException;
import java.nio.charset.Charset;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.internal.DefaultFileSystem;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.rule.ActiveRule;
import org.sonar.api.batch.rule.ActiveRules;
import org.sonar.api.batch.sensor.internal.SensorContextTester;
import org.sonar.xoo.Xoo;
import org.sonar.xoo.rule.hotspot.HotspotWithContextsSensor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class HotspotWithContextsSensorTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private final ActiveRules activeRules = mock(ActiveRules.class);
@Before
public void before() {
when(activeRules.find(any())).thenReturn(mock(ActiveRule.class));
}
@Test
public void processFile_givenCorrectTagPassed_oneSecurityHotspotWithContextsIsRaised() throws IOException {
DefaultInputFile inputFile = newTestFile(HotspotWithContextsSensor.TAG + "/n some text /n");
DefaultFileSystem fs = new DefaultFileSystem(temp.newFolder());
fs.add(inputFile);
SensorContextTester sensorContextTester = SensorContextTester.create(temp.newFolder().toPath());
HotspotWithContextsSensor sensor = new HotspotWithContextsSensor(fs, activeRules);
sensor.execute(sensorContextTester);
assertThat(sensorContextTester.allIssues()).hasSize(1);
}
@Test
public void processFile_givenJustHotspotTagPassed_noSecurityHotspotWithContextAreRaised() throws IOException {
DefaultInputFile inputFile = newTestFile("HOTSPOT/n hotspot hotspot some text /n hotspot /n text");
DefaultFileSystem fs = new DefaultFileSystem(temp.newFolder());
fs.add(inputFile);
SensorContextTester sensorContextTester = SensorContextTester.create(temp.newFolder().toPath());
HotspotWithContextsSensor sensor = new HotspotWithContextsSensor(fs, activeRules);
sensor.execute(sensorContextTester);
assertThat(sensorContextTester.allIssues()).isEmpty();
}
private DefaultInputFile newTestFile(String content) {
return new TestInputFileBuilder("foo", "hotspot.xoo")
.setLanguage(Xoo.KEY)
.setContents(content)
.setCharset(Charset.defaultCharset())
.build();
}
}
| 3,390 | 35.858696 | 112 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/rule/MarkAsUnchangedSensorTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import java.io.IOException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.sensor.internal.DefaultSensorDescriptor;
import org.sonar.api.batch.sensor.internal.SensorContextTester;
import org.sonar.api.config.Configuration;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.xoo.Xoo;
import static org.assertj.core.api.Assertions.assertThat;
public class MarkAsUnchangedSensorTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private final MarkAsUnchangedSensor sensor = new MarkAsUnchangedSensor();
@Test
public void mark_as_unchanged_for_all_files() throws IOException {
SensorContextTester context = SensorContextTester.create(temp.newFolder());
DefaultInputFile inputFile1 = createFile("file1");
DefaultInputFile inputFile2 = createFile("file2");
context.fileSystem()
.add(inputFile1)
.add(inputFile2);
sensor.execute(context);
assertThat(inputFile1.isMarkedAsUnchanged()).isTrue();
assertThat(inputFile2.isMarkedAsUnchanged()).isTrue();
}
@Test
public void only_runs_if_property_is_set() {
DefaultSensorDescriptor descriptor = new DefaultSensorDescriptor();
sensor.describe(descriptor);
Configuration configWithProperty = new MapSettings().setProperty("sonar.markAsUnchanged", "true").asConfig();
Configuration configWithoutProperty = new MapSettings().asConfig();
assertThat(descriptor.configurationPredicate().test(configWithoutProperty)).isFalse();
assertThat(descriptor.configurationPredicate().test(configWithProperty)).isTrue();
}
private DefaultInputFile createFile(String name) {
return new TestInputFileBuilder("foo", "src/" + name)
.setLanguage(Xoo.KEY)
.initMetadata("a\nb\nc\nd\ne\nf\ng\nh\ni\n")
.build();
}
}
| 2,832 | 36.773333 | 113 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/rule/MultilineHotspotSensorTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class MultilineHotspotSensorTest {
@Test
public void getRuleKey_returnsTheKey() {
assertThat(new MultilineHotspotSensor().getRuleKey()).isEqualTo(MultilineHotspotSensor.RULE_KEY);
}
} | 1,156 | 35.15625 | 101 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/rule/MultilineIssuesSensorTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.DefaultFileSystem;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.rule.ActiveRule;
import org.sonar.api.batch.rule.ActiveRules;
import org.sonar.api.batch.sensor.internal.SensorContextTester;
import org.sonar.api.batch.sensor.issue.Issue;
import org.sonar.api.batch.sensor.issue.IssueLocation;
import org.sonar.api.batch.sensor.issue.NewIssue.FlowType;
import org.sonar.api.batch.sensor.issue.internal.DefaultIssueFlow;
import org.sonar.api.internal.apachecommons.io.IOUtils;
import org.sonar.xoo.Xoo;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class MultilineIssuesSensorTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private final ActiveRules activeRules = mock(ActiveRules.class);
private final MultilineIssuesSensor sensor = new MultilineIssuesSensor();
@Before
public void before() {
when(activeRules.find(any())).thenReturn(mock(ActiveRule.class));
}
@Test
public void execute_dataAndExecutionFlowsAreDetectedAndMessageIsFormatted() throws IOException {
DefaultInputFile inputFile = newTestFile(IOUtils.toString(getClass().getResource("dataflow.xoo"), StandardCharsets.UTF_8));
DefaultFileSystem fs = new DefaultFileSystem(temp.newFolder());
fs.add(inputFile);
SensorContextTester sensorContextTester = SensorContextTester.create(fs.baseDir());
sensorContextTester.setFileSystem(fs);
sensor.execute(sensorContextTester);
assertThat(sensorContextTester.allIssues()).hasSize(1);
Issue issue = sensorContextTester.allIssues().iterator().next();
assertThat(issue.primaryLocation().messageFormattings()).isNotEmpty();
List<Issue.Flow> flows = issue.flows();
assertThat(flows).hasSize(2);
List<DefaultIssueFlow> defaultIssueFlows = flows.stream().map(DefaultIssueFlow.class::cast).collect(Collectors.toList());
assertThat(defaultIssueFlows).extracting(DefaultIssueFlow::type).containsExactlyInAnyOrder(FlowType.DATA, FlowType.EXECUTION);
assertThat(flows.get(0).locations()).extracting(IssueLocation::messageFormattings).isNotEmpty();
assertThat(flows.get(1).locations()).extracting(IssueLocation::messageFormattings).isNotEmpty();
}
private DefaultInputFile newTestFile(String content) {
return new TestInputFileBuilder("foo", "src/Foo.xoo")
.setLanguage(Xoo.KEY)
.setType(InputFile.Type.MAIN)
.setContents(content)
.build();
}
}
| 3,821 | 38.402062 | 130 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/rule/OneIssuePerLineSensorTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import java.io.IOException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.SonarEdition;
import org.sonar.api.SonarQubeSide;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.rule.Severity;
import org.sonar.api.batch.sensor.internal.DefaultSensorDescriptor;
import org.sonar.api.batch.sensor.internal.SensorContextTester;
import org.sonar.api.batch.sensor.issue.Issue;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.internal.SonarRuntimeImpl;
import org.sonar.api.utils.Version;
import org.sonar.xoo.Xoo;
import static org.assertj.core.api.Assertions.assertThat;
public class OneIssuePerLineSensorTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private OneIssuePerLineSensor sensor = new OneIssuePerLineSensor();
@Test
public void testDescriptor() {
DefaultSensorDescriptor descriptor = new DefaultSensorDescriptor();
sensor.describe(descriptor);
assertThat(descriptor.ruleRepositories()).containsOnly(XooRulesDefinition.XOO_REPOSITORY, XooRulesDefinition.XOO2_REPOSITORY);
}
@Test
public void testRule() throws IOException {
DefaultInputFile inputFile = new TestInputFileBuilder("foo", "src/Foo.xoo")
.setLanguage(Xoo.KEY)
.initMetadata("a\nb\nc\nd\ne\nf\ng\nh\ni\n")
.build();
SensorContextTester context = SensorContextTester.create(temp.newFolder());
context.fileSystem().add(inputFile);
sensor.execute(context);
assertThat(context.allIssues()).hasSize(10); // One issue per line
for (Issue issue : context.allIssues()) {
assertThat(issue.gap()).isNull();
}
}
@Test
public void testForceSeverity() throws IOException {
DefaultInputFile inputFile = new TestInputFileBuilder("foo", "src/Foo.xoo")
.setLanguage(Xoo.KEY)
.initMetadata("a\nb\nc\nd\ne\nf\ng\nh\ni\n")
.build();
SensorContextTester context = SensorContextTester.create(temp.newFolder());
context.fileSystem().add(inputFile);
context.setSettings(new MapSettings().setProperty(OneIssuePerLineSensor.FORCE_SEVERITY_PROPERTY, "MINOR"));
sensor.execute(context);
assertThat(context.allIssues()).hasSize(10); // One issue per line
for (Issue issue : context.allIssues()) {
assertThat(issue.overriddenSeverity()).isEqualTo(Severity.MINOR);
assertThat(issue.ruleDescriptionContextKey()).contains(XooRulesDefinition.AVAILABLE_CONTEXTS[0]);
}
}
@Test
public void testProvideGap() throws IOException {
DefaultInputFile inputFile = new TestInputFileBuilder("foo", "src/Foo.xoo")
.setLanguage(Xoo.KEY)
.initMetadata("a\nb\nc\nd\ne\nf\ng\nh\ni\n")
.build();
SensorContextTester context = SensorContextTester.create(temp.newFolder());
context.fileSystem().add(inputFile);
context.setSettings(new MapSettings().setProperty(OneIssuePerLineSensor.EFFORT_TO_FIX_PROPERTY, "1.2"));
sensor.execute(context);
assertThat(context.allIssues()).hasSize(10); // One issue per line
for (Issue issue : context.allIssues()) {
assertThat(issue.gap()).isEqualTo(1.2d);
}
}
@Test
public void testProvideGap_before_5_5() throws IOException {
DefaultInputFile inputFile = new TestInputFileBuilder("foo", "src/Foo.xoo")
.setLanguage(Xoo.KEY)
.initMetadata("a\nb\nc\nd\ne\nf\ng\nh\ni\n")
.build();
SensorContextTester context = SensorContextTester.create(temp.newFolder());
context.fileSystem().add(inputFile);
context.setSettings(new MapSettings().setProperty(OneIssuePerLineSensor.EFFORT_TO_FIX_PROPERTY, "1.2"));
context.setRuntime(SonarRuntimeImpl.forSonarQube(Version.parse("5.4"), SonarQubeSide.SCANNER, SonarEdition.COMMUNITY));
sensor.execute(context);
assertThat(context.allIssues()).hasSize(10); // One issue per line
for (Issue issue : context.allIssues()) {
assertThat(issue.gap()).isEqualTo(1.2d);
}
}
}
| 4,912 | 36.219697 | 130 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/rule/OneQuickFixPerLineSensorTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.sensor.internal.DefaultSensorDescriptor;
import org.sonar.api.batch.sensor.internal.SensorContextTester;
import org.sonar.api.batch.sensor.issue.Issue;
import org.sonar.xoo.Xoo;
import java.io.IOException;
import static org.assertj.core.api.Assertions.assertThat;
public class OneQuickFixPerLineSensorTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private OneQuickFixPerLineSensor sensor = new OneQuickFixPerLineSensor();
@Test
public void testDescriptor() {
DefaultSensorDescriptor descriptor = new DefaultSensorDescriptor();
sensor.describe(descriptor);
assertThat(descriptor.ruleRepositories()).containsOnly(XooRulesDefinition.XOO_REPOSITORY, XooRulesDefinition.XOO2_REPOSITORY);
}
@Test
public void testRule() throws IOException {
DefaultInputFile inputFile = new TestInputFileBuilder("foo", "src/Foo.xoo")
.setLanguage(Xoo.KEY)
.initMetadata("a\nb\nc\nd\ne\nf\ng\nh\ni\n")
.build();
SensorContextTester context = SensorContextTester.create(temp.newFolder());
context.fileSystem().add(inputFile);
sensor.execute(context);
assertThat(context.allIssues()).hasSize(10); // One issue per line
for (Issue issue : context.allIssues()) {
assertThat(issue.isQuickFixAvailable()).isTrue();
}
}
}
| 2,405 | 34.382353 | 130 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/rule/XooBuiltInQualityProfilesDefinitionTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import org.junit.Test;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition;
import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition.BuiltInQualityProfile;
import static org.assertj.core.api.Assertions.assertThat;
public class XooBuiltInQualityProfilesDefinitionTest {
private XooBuiltInQualityProfilesDefinition underTest = new XooBuiltInQualityProfilesDefinition();
@Test
public void test_built_in_quality_profile() {
BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context();
underTest.define(context);
BuiltInQualityProfile profile = context.profile("xoo", "test BuiltInQualityProfilesDefinition");
assertThat(profile.isDefault()).isFalse();
assertThat(profile.name()).isEqualTo("test BuiltInQualityProfilesDefinition");
assertThat(profile.language()).isEqualTo("xoo");
assertThat(profile.rules()).hasSize(1);
BuiltInQualityProfilesDefinition.BuiltInActiveRule activeRule = profile.rule(RuleKey.of("xoo", "HasTag"));
assertThat(activeRule.overriddenSeverity()).isEqualTo("BLOCKER");
assertThat(activeRule.overriddenParams()).hasSize(1);
assertThat(activeRule.overriddenParam("tag").overriddenValue()).isEqualTo("TODO");
}
}
| 2,162 | 42.26 | 110 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/rule/XooRulesDefinitionTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.rule;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.SonarEdition;
import org.sonar.api.SonarQubeSide;
import org.sonar.api.impl.server.RulesDefinitionContext;
import org.sonar.api.internal.SonarRuntimeImpl;
import org.sonar.api.server.debt.DebtRemediationFunction;
import org.sonar.api.server.rule.RulesDefinition;
import org.sonar.api.utils.Version;
import org.sonar.xoo.rule.hotspot.HotspotWithContextsSensor;
import org.sonar.xoo.rule.hotspot.HotspotWithoutContextSensor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.api.server.rule.RuleDescriptionSection.RuleDescriptionSectionKeys.HOW_TO_FIX_SECTION_KEY;
public class XooRulesDefinitionTest {
private XooRulesDefinition def = new XooRulesDefinition(SonarRuntimeImpl.forSonarQube(Version.create(9, 3), SonarQubeSide.SCANNER, SonarEdition.COMMUNITY));
private RulesDefinition.Context context = new RulesDefinitionContext();
@Before
public void setUp() {
def.define(context);
}
@Test
public void define_xoo_rules() {
RulesDefinition.Repository repo = getRepository();
RulesDefinition.Rule rule = repo.rule(OneIssuePerLineSensor.RULE_KEY);
assertThat(rule.name()).isNotEmpty();
assertThat(rule.debtRemediationFunction().type()).isEqualTo(DebtRemediationFunction.Type.LINEAR);
assertThat(rule.debtRemediationFunction().gapMultiplier()).isEqualTo("1min");
assertThat(rule.debtRemediationFunction().baseEffort()).isNull();
assertThat(rule.gapDescription()).isNotEmpty();
assertThat(rule.ruleDescriptionSections()).isNotEmpty();
assertThat(rule.ruleDescriptionSections().stream().anyMatch(rds -> rds.getContext().isPresent())).isTrue();
}
@Test
public void define_xoo_hotspot_rule() {
RulesDefinition.Repository repo = getRepository();
RulesDefinition.Rule rule = repo.rule(HotspotWithoutContextSensor.RULE_KEY);
assertThat(rule.name()).isNotEmpty();
assertThat(rule.securityStandards())
.isNotEmpty()
.containsExactlyInAnyOrder("cwe:1", "cwe:89", "cwe:123", "cwe:863", "owaspTop10:a1", "owaspTop10:a3",
"owaspTop10-2021:a3", "owaspTop10-2021:a2");
}
@Test
public void define_xoo_hotspot_rule_with_contexts() {
RulesDefinition.Repository repo = getRepository();
RulesDefinition.Rule rule = repo.rule(HotspotWithContextsSensor.RULE_KEY);
assertThat(rule.name()).isNotEmpty();
assertThat(rule.securityStandards()).isEmpty();
assertThat(rule.ruleDescriptionSections()).isNotEmpty();
assertThat(rule.ruleDescriptionSections().stream()
.filter(rds -> rds.getKey().equals(HOW_TO_FIX_SECTION_KEY)))
.allMatch(rds -> rds.getContext().isPresent());
}
@Test
public void define_xoo_vulnerability_rule() {
RulesDefinition.Repository repo = getRepository();
RulesDefinition.Rule rule = repo.rule(OneVulnerabilityIssuePerModuleSensor.RULE_KEY);
assertThat(rule.name()).isNotEmpty();
assertThat(rule.securityStandards())
.isNotEmpty()
.containsExactlyInAnyOrder("cwe:250", "cwe:546", "cwe:564", "cwe:943", "owaspTop10-2021:a6", "owaspTop10-2021:a9",
"owaspTop10:a10", "owaspTop10:a9");
}
@Test
public void define_xooExternal_rules() {
RulesDefinition.Repository repo = context.repository("external_XooEngine");
assertThat(repo).isNotNull();
assertThat(repo.name()).isEqualTo("XooEngine");
assertThat(repo.language()).isEqualTo("xoo");
assertThat(repo.rules()).hasSize(1);
}
@Test
public void define_xoo2_rules() {
RulesDefinition.Repository repo = context.repository("xoo2");
assertThat(repo).isNotNull();
assertThat(repo.name()).isEqualTo("Xoo2");
assertThat(repo.language()).isEqualTo("xoo2");
assertThat(repo.rules()).hasSize(2);
}
private RulesDefinition.Repository getRepository() {
RulesDefinition.Repository repo = context.repository("xoo");
assertThat(repo).isNotNull();
assertThat(repo.name()).isEqualTo("Xoo");
assertThat(repo.language()).isEqualTo("xoo");
assertThat(repo.rules()).hasSize(28);
return repo;
}
}
| 4,958 | 38.357143 | 158 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/scm/XooBlameCommandTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.scm;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.function.Predicate;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.mockito.ArgumentCaptor;
import org.sonar.api.batch.fs.internal.DefaultFileSystem;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.scm.BlameCommand.BlameInput;
import org.sonar.api.batch.scm.BlameCommand.BlameOutput;
import org.sonar.api.batch.scm.BlameLine;
import org.sonar.api.utils.DateUtils;
import org.sonar.xoo.Xoo;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class XooBlameCommandTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private DefaultFileSystem fs;
private File baseDir;
private BlameInput input;
@Before
public void prepare() throws IOException {
baseDir = temp.newFolder();
fs = new DefaultFileSystem(baseDir.toPath());
input = mock(BlameInput.class);
when(input.fileSystem()).thenReturn(fs);
}
@Test
public void testBlame() throws IOException {
File source = new File(baseDir, "src/foo.xoo");
FileUtils.write(source, "sample content");
File scm = new File(baseDir, "src/foo.xoo.scm");
FileUtils.write(scm, "123,julien,2014-12-12\n234,julien,2014-12-24");
DefaultInputFile inputFile = new TestInputFileBuilder("foo", "src/foo.xoo")
.setLanguage(Xoo.KEY)
.setModuleBaseDir(baseDir.toPath())
.build();
fs.add(inputFile);
BlameOutput result = mock(BlameOutput.class);
when(input.filesToBlame()).thenReturn(Arrays.asList(inputFile));
new XooBlameCommand().blame(input, result);
verify(result).blameResult(inputFile, Arrays.asList(
new BlameLine().revision("123").author("julien").date(DateUtils.parseDate("2014-12-12")),
new BlameLine().revision("234").author("julien").date(DateUtils.parseDate("2014-12-24"))));
}
@Test
public void testBlameWithRelativeDate() throws IOException {
File source = new File(baseDir, "src/foo.xoo");
FileUtils.write(source, "sample content");
File scm = new File(baseDir, "src/foo.xoo.scm");
FileUtils.write(scm, "123,julien,-10\n234,julien,-10");
DefaultInputFile inputFile = new TestInputFileBuilder("foo", "src/foo.xoo")
.setLanguage(Xoo.KEY)
.setModuleBaseDir(baseDir.toPath())
.build();
fs.add(inputFile);
BlameOutput result = mock(BlameOutput.class);
when(input.filesToBlame()).thenReturn(Arrays.asList(inputFile));
new XooBlameCommand().blame(input, result);
Predicate<Date> datePredicate = argument -> {
Date approximate = DateUtils.addDays(new Date(), -10);
return argument.getTime() > approximate.getTime() - 5000 && argument.getTime() < approximate.getTime() + 5000;
};
ArgumentCaptor<List<BlameLine>> blameLinesCaptor = ArgumentCaptor.forClass(List.class);
verify(result).blameResult(eq(inputFile), blameLinesCaptor.capture());
assertThat(blameLinesCaptor.getValue())
.extracting(BlameLine::date)
.allMatch(datePredicate);
}
@Test
public void blame_containing_author_with_comma() throws IOException {
File source = new File(baseDir, "src/foo.xoo");
FileUtils.write(source, "sample content");
File scm = new File(baseDir, "src/foo.xoo.scm");
FileUtils.write(scm, "\"123\",\"john,doe\",\"2019-01-22\"");
DefaultInputFile inputFile = new TestInputFileBuilder("foo", "src/foo.xoo")
.setLanguage(Xoo.KEY)
.setModuleBaseDir(baseDir.toPath())
.build();
fs.add(inputFile);
BlameOutput result = mock(BlameOutput.class);
when(input.filesToBlame()).thenReturn(Arrays.asList(inputFile));
new XooBlameCommand().blame(input, result);
verify(result).blameResult(inputFile, singletonList(
new BlameLine().revision("123").author("john,doe").date(DateUtils.parseDate("2019-01-22"))));
}
}
| 5,169 | 37.296296 | 116 | java |
sonarqube | sonarqube-master/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/scm/XooIgnoreCommandTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.xoo.scm;
import java.io.File;
import java.io.IOException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.xoo.scm.XooIgnoreCommand.IGNORE_FILE_EXTENSION;
public class XooIgnoreCommandTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private File baseDir;
@Before
public void prepare() throws IOException {
baseDir = temp.newFolder();
}
@Test
public void testBlame() throws IOException {
File source = newFile("foo.xoo", false);
File source1 = newFile("foo2.xoo", true);
XooIgnoreCommand ignoreCommand = new XooIgnoreCommand();
ignoreCommand.init(baseDir.toPath());
assertThat(ignoreCommand.isIgnored(source.toPath())).isFalse();
assertThat(ignoreCommand.isIgnored(source1.toPath())).isTrue();
}
private File newFile(String name, boolean isIgnored) throws IOException {
File source = new File(baseDir, name);
source.createNewFile();
if (isIgnored) {
File ignoredMetaFile = new File(baseDir, name + IGNORE_FILE_EXTENSION);
ignoredMetaFile.createNewFile();
}
return source;
}
}
| 2,090 | 30.208955 | 77 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/TimeoutConfiguration.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.alm.client;
import org.sonar.api.ce.ComputeEngineSide;
import org.sonar.api.server.ServerSide;
/**
* Holds the configuration of timeouts when connecting to ALMs.
*/
@ServerSide
@ComputeEngineSide
public interface TimeoutConfiguration {
/**
* @return connect timeout in milliseconds
*/
long getConnectTimeout();
/**
* @return read timeout in milliseconds
*/
long getReadTimeout();
}
| 1,268 | 29.95122 | 75 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/TimeoutConfigurationImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.alm.client;
import com.google.common.annotations.VisibleForTesting;
import java.util.OptionalLong;
import org.sonar.api.config.Configuration;
import org.slf4j.LoggerFactory;
/**
* Implementation of {@link TimeoutConfiguration} reading values from configuration properties.
*/
public class TimeoutConfigurationImpl implements TimeoutConfiguration {
@VisibleForTesting
public static final String CONNECT_TIMEOUT_PROPERTY = "sonar.alm.timeout.connect";
@VisibleForTesting
public static final String READ_TIMEOUT_PROPERTY = "sonar.alm.timeout.read";
private static final long DEFAULT_TIMEOUT = 30_000;
private final Configuration configuration;
public TimeoutConfigurationImpl(Configuration configuration) {
this.configuration = configuration;
}
@Override
public long getConnectTimeout() {
return safelyParseLongValue(CONNECT_TIMEOUT_PROPERTY).orElse(DEFAULT_TIMEOUT);
}
private OptionalLong safelyParseLongValue(String property) {
return configuration.get(property)
.map(value -> {
try {
return OptionalLong.of(Long.parseLong(value));
} catch (NumberFormatException e) {
LoggerFactory.getLogger(TimeoutConfigurationImpl.class)
.warn("Value of property {} can not be parsed to a long: {}", property, value);
return OptionalLong.empty();
}
})
.orElse(OptionalLong.empty());
}
@Override
public long getReadTimeout() {
return safelyParseLongValue(READ_TIMEOUT_PROPERTY).orElse(DEFAULT_TIMEOUT);
}
}
| 2,396 | 33.73913 | 95 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.
*/
@ParametersAreNonnullByDefault
package org.sonar.alm.client;
import javax.annotation.ParametersAreNonnullByDefault;
| 961 | 37.48 | 75 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/azure/AzureDevOpsHttpClient.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.alm.client.azure;
import com.google.common.base.Strings;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.nio.charset.StandardCharsets;
import java.util.function.Function;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.sonar.alm.client.TimeoutConfiguration;
import org.sonar.api.server.ServerSide;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonarqube.ws.client.OkHttpClientBuilder;
import static java.util.stream.Collectors.joining;
import static org.sonar.api.internal.apachecommons.lang.StringUtils.isBlank;
import static org.sonar.api.internal.apachecommons.lang.StringUtils.substringBeforeLast;
@ServerSide
public class AzureDevOpsHttpClient {
private static final Logger LOG = LoggerFactory.getLogger(AzureDevOpsHttpClient.class);
public static final String API_VERSION_3 = "api-version=3.0";
protected static final String GET = "GET";
protected static final String UNABLE_TO_CONTACT_AZURE_SERVER = "Unable to contact Azure DevOps server";
protected final OkHttpClient client;
public AzureDevOpsHttpClient(TimeoutConfiguration timeoutConfiguration) {
client = new OkHttpClientBuilder()
.setConnectTimeoutMs(timeoutConfiguration.getConnectTimeout())
.setReadTimeoutMs(timeoutConfiguration.getReadTimeout())
.setFollowRedirects(false)
.build();
}
public void checkPAT(String serverUrl, String token) {
String url = String.format("%s/_apis/projects?%s", getTrimmedUrl(serverUrl), API_VERSION_3);
LOG.debug(String.format("check pat : [%s]", url));
doGet(token, url);
}
public GsonAzureProjectList getProjects(String serverUrl, String token) {
String url = String.format("%s/_apis/projects?%s", getTrimmedUrl(serverUrl), API_VERSION_3);
LOG.debug(String.format("get projects : [%s]", url));
return doGet(token, url, r -> buildGson().fromJson(r.body().charStream(), GsonAzureProjectList.class));
}
public GsonAzureProject getProject(String serverUrl, String token, String projectName) {
String url = String.format("%s/_apis/projects/%s?%s", getTrimmedUrl(serverUrl), projectName, API_VERSION_3);
LOG.debug(String.format("get project : [%s]", url));
return doGet(token, url, r -> buildGson().fromJson(r.body().charStream(), GsonAzureProject.class));
}
public GsonAzureRepoList getRepos(String serverUrl, String token, @Nullable String projectName) {
String url = Stream.of(getTrimmedUrl(serverUrl), projectName, "_apis/git/repositories?" + API_VERSION_3)
.filter(StringUtils::isNotBlank)
.collect(joining("/"));
LOG.debug(String.format("get repos : [%s]", url));
return doGet(token, url, r -> buildGson().fromJson(r.body().charStream(), GsonAzureRepoList.class));
}
public GsonAzureRepo getRepo(String serverUrl, String token, String projectName, String repositoryName) {
String url = Stream.of(getTrimmedUrl(serverUrl), projectName, "_apis/git/repositories", repositoryName + "?" + API_VERSION_3)
.filter(StringUtils::isNotBlank)
.collect(joining("/"));
LOG.debug(String.format("get repo : [%s]", url));
return doGet(token, url, r -> buildGson().fromJson(r.body().charStream(), GsonAzureRepo.class));
}
private void doGet(String token, String url) {
Request request = prepareRequestWithToken(token, GET, url, null);
doCall(request);
}
protected void doCall(Request request) {
try (Response response = client.newCall(request).execute()) {
checkResponseIsSuccessful(response);
} catch (IOException e) {
LOG.error(String.format(UNABLE_TO_CONTACT_AZURE_SERVER + " for request [%s]: [%s]", request.url(), e.getMessage()));
throw new IllegalArgumentException(UNABLE_TO_CONTACT_AZURE_SERVER, e);
}
}
protected <G> G doGet(String token, String url, Function<Response, G> handler) {
Request request = prepareRequestWithToken(token, GET, url, null);
return doCall(request, handler);
}
protected <G> G doCall(Request request, Function<Response, G> handler) {
try (Response response = client.newCall(request).execute()) {
checkResponseIsSuccessful(response);
return handler.apply(response);
} catch (JsonSyntaxException e) {
LOG.error(String.format("Response from Azure for request [%s] could not be parsed: [%s]",
request.url(),
e.getMessage()));
throw new IllegalArgumentException(UNABLE_TO_CONTACT_AZURE_SERVER + ", got an unexpected response", e);
} catch (IOException e) {
LOG.error(String.format(UNABLE_TO_CONTACT_AZURE_SERVER + " for request [%s]: [%s]", request.url(), e.getMessage()));
throw new IllegalArgumentException(UNABLE_TO_CONTACT_AZURE_SERVER, e);
}
}
protected static Request prepareRequestWithToken(String token, String method, String url, @Nullable RequestBody body) {
return new Request.Builder()
.method(method, body)
.url(url)
.addHeader("Authorization", encodeToken("accessToken:" + token))
.build();
}
protected static void checkResponseIsSuccessful(Response response) throws IOException {
if (!response.isSuccessful()) {
if (response.code() == HttpURLConnection.HTTP_UNAUTHORIZED) {
LOG.error(String.format(UNABLE_TO_CONTACT_AZURE_SERVER + " for request [%s]: Invalid personal access token",
response.request().url()));
throw new AzureDevopsServerException(response.code(), "Invalid personal access token");
}
if (response.code() == HttpURLConnection.HTTP_NOT_FOUND) {
LOG.error(String.format(UNABLE_TO_CONTACT_AZURE_SERVER + " for request [%s]: URL Not Found",
response.request().url()));
throw new AzureDevopsServerException(response.code(), "Invalid Azure URL");
}
ResponseBody responseBody = response.body();
String body = responseBody == null ? "" : responseBody.string();
String errorMessage = generateErrorMessage(body, UNABLE_TO_CONTACT_AZURE_SERVER);
LOG.error(String.format("Azure API call to [%s] failed with %s http code. Azure response content : [%s]", response.request().url(), response.code(), body));
throw new AzureDevopsServerException(response.code(), errorMessage);
}
}
protected static String generateErrorMessage(String body, String defaultMessage) {
GsonAzureError gsonAzureError = null;
try {
gsonAzureError = buildGson().fromJson(body, GsonAzureError.class);
} catch (JsonSyntaxException e) {
// not a json payload, ignore the error
}
if (gsonAzureError != null && !Strings.isNullOrEmpty(gsonAzureError.message())) {
return defaultMessage + " : " + gsonAzureError.message();
} else {
return defaultMessage;
}
}
protected static String getTrimmedUrl(String rawUrl) {
if (isBlank(rawUrl)) {
return rawUrl;
}
if (rawUrl.endsWith("/")) {
return substringBeforeLast(rawUrl, "/");
}
return rawUrl;
}
protected static String encodeToken(String token) {
return String.format("BASIC %s", Base64.encodeBase64String(token.getBytes(StandardCharsets.UTF_8)));
}
protected static Gson buildGson() {
return new GsonBuilder()
.create();
}
}
| 8,408 | 40.835821 | 162 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/azure/AzureDevOpsValidator.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.alm.client.azure;
import org.sonar.api.server.ServerSide;
import org.sonar.db.alm.setting.AlmSettingDto;
import org.sonar.api.config.internal.Settings;
import static java.util.Objects.requireNonNull;
@ServerSide
public class AzureDevOpsValidator {
private final AzureDevOpsHttpClient azureDevOpsHttpClient;
private final Settings settings;
public AzureDevOpsValidator(AzureDevOpsHttpClient azureDevOpsHttpClient, Settings settings) {
this.azureDevOpsHttpClient = azureDevOpsHttpClient;
this.settings = settings;
}
public void validate(AlmSettingDto dto) {
try {
azureDevOpsHttpClient.checkPAT(requireNonNull(dto.getUrl()),
requireNonNull(dto.getDecryptedPersonalAccessToken(settings.getEncryption())));
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Invalid Azure URL or Personal Access Token", e);
}
}
}
| 1,752 | 35.520833 | 95 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/azure/AzureDevopsServerException.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.alm.client.azure;
public class AzureDevopsServerException extends IllegalArgumentException {
private final int httpCode;
public AzureDevopsServerException(int httpCode, String clientErrorMessage) {
super(clientErrorMessage);
this.httpCode = httpCode;
}
public int getHttpCode() {
return httpCode;
}
}
| 1,187 | 33.941176 | 78 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/azure/GsonAzureError.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.alm.client.azure;
import com.google.gson.annotations.SerializedName;
import javax.annotation.Nullable;
public class GsonAzureError {
@SerializedName("message")
private final String message;
public GsonAzureError(@Nullable String message) {
this.message = message;
}
public GsonAzureError() {
// http://stackoverflow.com/a/18645370/229031
this(null);
}
public String message() {
return message;
}
}
| 1,296 | 29.880952 | 75 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/azure/GsonAzureProject.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.alm.client.azure;
import com.google.gson.annotations.SerializedName;
public class GsonAzureProject {
@SerializedName("name")
private String name;
@SerializedName("description")
private String description;
public GsonAzureProject() {
// http://stackoverflow.com/a/18645370/229031
}
public GsonAzureProject(String name, String description) {
this.name = name;
this.description = description;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
}
| 1,403 | 27.653061 | 75 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/azure/GsonAzureProjectList.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.alm.client.azure;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
public class GsonAzureProjectList {
@SerializedName("value")
private List<GsonAzureProject> values;
public GsonAzureProjectList() {
// http://stackoverflow.com/a/18645370/229031
this(new ArrayList<>());
}
public GsonAzureProjectList(List<GsonAzureProject> values) {
this.values = values;
}
public List<GsonAzureProject> getValues() {
return values;
}
public GsonAzureProjectList setValues(List<GsonAzureProject> values) {
this.values = values;
return this;
}
@Override
public String toString() {
return "{" +
"values=" + values +
'}';
}
}
| 1,595 | 27 | 75 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/azure/GsonAzureRepo.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.alm.client.azure;
import com.google.gson.annotations.SerializedName;
import java.util.regex.Pattern;
public class GsonAzureRepo {
private static final String BRANCH_FULL_NAME_PREFIX = "refs/heads/";
@SerializedName("id")
private String id;
@SerializedName("name")
private String name;
@SerializedName("url")
private String url;
@SerializedName("project")
private GsonAzureProject project;
@SerializedName("defaultBranch")
private String defaultBranchFullName;
public GsonAzureRepo() {
// http://stackoverflow.com/a/18645370/229031
}
public GsonAzureRepo(String id, String name, String url, GsonAzureProject project, String defaultBranchFullName) {
this.id = id;
this.name = name;
this.url = url;
this.project = project;
this.defaultBranchFullName = defaultBranchFullName;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getUrl() {
return url;
}
public GsonAzureProject getProject() {
return project;
}
public String getDefaultBranchName() {
if (defaultBranchFullName == null || defaultBranchFullName.equals("")) {
return null;
}
return Pattern
.compile(Pattern.quote(BRANCH_FULL_NAME_PREFIX), Pattern.CASE_INSENSITIVE)
.matcher(defaultBranchFullName)
.replaceAll("");
}
}
| 2,220 | 26.085366 | 116 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/azure/GsonAzureRepoList.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.alm.client.azure;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
public class GsonAzureRepoList {
@SerializedName("value")
private List<GsonAzureRepo> values;
public GsonAzureRepoList() {
// http://stackoverflow.com/a/18645370/229031
this(new ArrayList<>());
}
public GsonAzureRepoList(List<GsonAzureRepo> values) {
this.values = values;
}
static GsonAzureRepoList parse(String json) {
return new Gson().fromJson(json, GsonAzureRepoList.class);
}
public List<GsonAzureRepo> getValues() {
return values;
}
}
| 1,500 | 29.02 | 75 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/azure/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.
*/
@ParametersAreNonnullByDefault
package org.sonar.alm.client.azure;
import javax.annotation.ParametersAreNonnullByDefault;
| 967 | 37.72 | 75 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/bitbucket/bitbucketcloud/BitbucketCloudRestClient.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.alm.client.bitbucket.bitbucketcloud;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import java.io.IOException;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.UnaryOperator;
import javax.annotation.Nullable;
import javax.inject.Inject;
import okhttp3.Credentials;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.sonar.api.server.ServerSide;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.server.exceptions.NotFoundException;
import static org.sonar.api.internal.apachecommons.lang.StringUtils.removeEnd;
@ServerSide
public class BitbucketCloudRestClient {
private static final Logger LOG = LoggerFactory.getLogger(BitbucketCloudRestClient.class);
private static final String AUTHORIZATION = "Authorization";
private static final String GET = "GET";
private static final String ENDPOINT = "https://api.bitbucket.org";
private static final String ACCESS_TOKEN_ENDPOINT = "https://bitbucket.org/site/oauth2/access_token";
private static final String VERSION = "2.0";
protected static final String ERROR_BBC_SERVERS = "Error returned by Bitbucket Cloud";
protected static final String UNABLE_TO_CONTACT_BBC_SERVERS = "Unable to contact Bitbucket Cloud servers";
protected static final String MISSING_PULL_REQUEST_READ_PERMISSION = "The OAuth consumer in the Bitbucket workspace is not configured with the permission to read pull requests.";
protected static final String SCOPE = "Scope is: %s";
protected static final String UNAUTHORIZED_CLIENT = "Check your credentials";
protected static final String OAUTH_CONSUMER_NOT_PRIVATE = "Configure the OAuth consumer in the Bitbucket workspace to be a private consumer";
protected static final String BBC_FAIL_WITH_RESPONSE = "Bitbucket Cloud API call to [%s] failed with %s http code. Bitbucket Cloud response content : [%s]";
protected static final String BBC_FAIL_WITH_ERROR = "Bitbucket Cloud API call to [%s] failed with error: %s";
protected static final MediaType JSON_MEDIA_TYPE = MediaType.parse("application/json; charset=utf-8");
private final OkHttpClient client;
private final String bitbucketCloudEndpoint;
private final String accessTokenEndpoint;
@Inject
public BitbucketCloudRestClient(OkHttpClient bitBucketCloudHttpClient) {
this(bitBucketCloudHttpClient, ENDPOINT, ACCESS_TOKEN_ENDPOINT);
}
protected BitbucketCloudRestClient(OkHttpClient bitBucketCloudHttpClient, String bitbucketCloudEndpoint, String accessTokenEndpoint) {
this.client = bitBucketCloudHttpClient;
this.bitbucketCloudEndpoint = bitbucketCloudEndpoint;
this.accessTokenEndpoint = accessTokenEndpoint;
}
/**
* Validate parameters provided.
*/
public void validate(String clientId, String clientSecret, String workspace) {
Token token = validateAccessToken(clientId, clientSecret);
if (token.getScopes() == null || !token.getScopes().contains("pullrequest")) {
LOG.info(MISSING_PULL_REQUEST_READ_PERMISSION + String.format(SCOPE, token.getScopes()));
throw new IllegalArgumentException(ERROR_BBC_SERVERS + ": " + MISSING_PULL_REQUEST_READ_PERMISSION);
}
try {
doGet(token.getAccessToken(), buildUrl("/repositories/" + workspace), r -> null);
} catch (NotFoundException | IllegalStateException e) {
throw new IllegalArgumentException(e.getMessage());
}
}
/**
* Validate parameters provided.
*/
public void validateAppPassword(String encodedCredentials, String workspace) {
try {
doGetWithBasicAuth(encodedCredentials, buildUrl("/repositories/" + workspace), r -> null);
} catch (NotFoundException | IllegalStateException e) {
throw new IllegalArgumentException(e.getMessage());
}
}
private Token validateAccessToken(String clientId, String clientSecret) {
Request request = createAccessTokenRequest(clientId, clientSecret);
try (Response response = client.newCall(request).execute()) {
if (response.isSuccessful()) {
return buildGson().fromJson(response.body().charStream(), Token.class);
}
ErrorDetails errorMsg = getTokenError(response.body());
if (errorMsg.body != null) {
LOG.info(String.format(BBC_FAIL_WITH_RESPONSE, response.request().url(), response.code(), errorMsg.body));
switch (errorMsg.body) {
case "invalid_grant":
throw new IllegalArgumentException(UNABLE_TO_CONTACT_BBC_SERVERS + ": " + OAUTH_CONSUMER_NOT_PRIVATE);
case "unauthorized_client":
throw new IllegalArgumentException(UNABLE_TO_CONTACT_BBC_SERVERS + ": " + UNAUTHORIZED_CLIENT);
default:
if (errorMsg.parsedErrorMsg != null) {
throw new IllegalArgumentException(ERROR_BBC_SERVERS + ": " + errorMsg.parsedErrorMsg);
} else {
throw new IllegalArgumentException(UNABLE_TO_CONTACT_BBC_SERVERS);
}
}
} else {
LOG.info(String.format(BBC_FAIL_WITH_RESPONSE, response.request().url(), response.code(), response.message()));
}
throw new IllegalArgumentException(UNABLE_TO_CONTACT_BBC_SERVERS);
} catch (IOException e) {
LOG.info(String.format(BBC_FAIL_WITH_ERROR, request.url(), e.getMessage()));
throw new IllegalArgumentException(UNABLE_TO_CONTACT_BBC_SERVERS, e);
}
}
public RepositoryList searchRepos(String encodedCredentials, String workspace, @Nullable String repoName, Integer page, Integer pageSize) {
String filterQuery = String.format("q=name~\"%s\"", repoName != null ? repoName : "");
HttpUrl url = buildUrl(String.format("/repositories/%s?%s&page=%s&pagelen=%s", workspace, filterQuery, page, pageSize));
return doGetWithBasicAuth(encodedCredentials, url, r -> buildGson().fromJson(r.body().charStream(), RepositoryList.class));
}
public Repository getRepo(String encodedCredentials, String workspace, String slug) {
HttpUrl url = buildUrl(String.format("/repositories/%s/%s", workspace, slug));
return doGetWithBasicAuth(encodedCredentials, url, r -> buildGson().fromJson(r.body().charStream(), Repository.class));
}
public String createAccessToken(String clientId, String clientSecret) {
Request request = createAccessTokenRequest(clientId, clientSecret);
return doCall(request, r -> buildGson().fromJson(r.body().charStream(), Token.class)).getAccessToken();
}
private Request createAccessTokenRequest(String clientId, String clientSecret) {
RequestBody body = new FormBody.Builder()
.add("grant_type", "client_credentials")
.build();
HttpUrl url = HttpUrl.parse(accessTokenEndpoint);
String credential = Credentials.basic(clientId, clientSecret);
return prepareRequestWithBasicAuthCredentials(credential, "POST", url, body);
}
protected HttpUrl buildUrl(String relativeUrl) {
return HttpUrl.parse(removeEnd(bitbucketCloudEndpoint, "/") + "/" + VERSION + relativeUrl);
}
protected <G> G doGet(String accessToken, HttpUrl url, Function<Response, G> handler) {
Request request = prepareRequestWithAccessToken(accessToken, GET, url, null);
return doCall(request, handler);
}
protected <G> G doGetWithBasicAuth(String encodedCredentials, HttpUrl url, Function<Response, G> handler) {
Request request = prepareRequestWithBasicAuthCredentials("Basic " + encodedCredentials, GET, url, null);
return doCall(request, handler);
}
protected <G> G doCall(Request request, Function<Response, G> handler) {
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
handleError(response);
}
return handler.apply(response);
} catch (IOException e) {
LOG.info(ERROR_BBC_SERVERS + ": {}", e.getMessage());
throw new IllegalStateException(ERROR_BBC_SERVERS, e);
}
}
private static void handleError(Response response) throws IOException {
ErrorDetails error = getError(response.body());
LOG.info(String.format(BBC_FAIL_WITH_RESPONSE, response.request().url(), response.code(), error.body));
if (error.parsedErrorMsg != null) {
throw new IllegalStateException(ERROR_BBC_SERVERS + ": " + error.parsedErrorMsg);
} else {
throw new IllegalStateException(UNABLE_TO_CONTACT_BBC_SERVERS);
}
}
private static ErrorDetails getError(@Nullable ResponseBody body) throws IOException {
return getErrorDetails(body, s -> {
Error gsonError = buildGson().fromJson(s, Error.class);
if (gsonError != null && gsonError.errorMsg != null && gsonError.errorMsg.message != null) {
return gsonError.errorMsg.message;
}
return null;
});
}
private static ErrorDetails getTokenError(@Nullable ResponseBody body) throws IOException {
if (body == null) {
return new ErrorDetails(null, null);
}
String bodyStr = body.string();
if (body.contentType() != null && Objects.equals(JSON_MEDIA_TYPE.type(), body.contentType().type())) {
try {
TokenError gsonError = buildGson().fromJson(bodyStr, TokenError.class);
if (gsonError != null && gsonError.error != null) {
return new ErrorDetails(gsonError.error, gsonError.errorDescription);
}
} catch (JsonParseException e) {
// ignore
}
}
return new ErrorDetails(bodyStr, null);
}
private static class ErrorDetails {
@Nullable
private final String body;
@Nullable
private final String parsedErrorMsg;
public ErrorDetails(@Nullable String body, @Nullable String parsedErrorMsg) {
this.body = body;
this.parsedErrorMsg = parsedErrorMsg;
}
}
private static ErrorDetails getErrorDetails(@Nullable ResponseBody body, UnaryOperator<String> parser) throws IOException {
if (body == null) {
return new ErrorDetails("", null);
}
String bodyStr = body.string();
if (body.contentType() != null && Objects.equals(JSON_MEDIA_TYPE.type(), body.contentType().type())) {
try {
return new ErrorDetails(bodyStr, parser.apply(bodyStr));
} catch (JsonParseException e) {
// ignore
}
}
return new ErrorDetails(bodyStr, null);
}
protected static Request prepareRequestWithAccessToken(String accessToken, String method, HttpUrl url, @Nullable RequestBody body) {
return new Request.Builder()
.method(method, body)
.url(url)
.header(AUTHORIZATION, "Bearer " + accessToken)
.build();
}
protected static Request prepareRequestWithBasicAuthCredentials(String encodedCredentials, String method,
HttpUrl url, @Nullable RequestBody body) {
return new Request.Builder()
.method(method, body)
.url(url)
.header(AUTHORIZATION, encodedCredentials)
.build();
}
public static Gson buildGson() {
return new GsonBuilder().create();
}
}
| 11,937 | 41.333333 | 180 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/bitbucket/bitbucketcloud/BitbucketCloudRestClientConfiguration.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.alm.client.bitbucket.bitbucketcloud;
import okhttp3.OkHttpClient;
import org.sonar.alm.client.TimeoutConfiguration;
import org.sonar.api.ce.ComputeEngineSide;
import org.sonar.api.server.ServerSide;
import org.sonarqube.ws.client.OkHttpClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
@ComputeEngineSide
@ServerSide
@Configuration
@Lazy
public class BitbucketCloudRestClientConfiguration {
private final TimeoutConfiguration timeoutConfiguration;
@Autowired
public BitbucketCloudRestClientConfiguration(TimeoutConfiguration timeoutConfiguration) {
this.timeoutConfiguration = timeoutConfiguration;
}
@Bean
public OkHttpClient bitbucketCloudHttpClient() {
OkHttpClientBuilder builder = new OkHttpClientBuilder();
builder.setConnectTimeoutMs(timeoutConfiguration.getConnectTimeout());
builder.setReadTimeoutMs(timeoutConfiguration.getReadTimeout());
builder.setFollowRedirects(false);
return builder.build();
}
@Bean
public BitbucketCloudRestClient bitbucketCloudRestClient() {
return new BitbucketCloudRestClient(bitbucketCloudHttpClient());
}
}
| 2,154 | 35.525424 | 91 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/bitbucket/bitbucketcloud/BitbucketCloudValidator.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.alm.client.bitbucket.bitbucketcloud;
import org.sonar.api.config.internal.Settings;
import org.sonar.api.server.ServerSide;
import org.sonar.db.alm.setting.AlmSettingDto;
import static java.util.Objects.requireNonNull;
@ServerSide
public class BitbucketCloudValidator {
private final BitbucketCloudRestClient bitbucketCloudRestClient;
private final Settings settings;
public BitbucketCloudValidator(BitbucketCloudRestClient bitbucketCloudRestClient, Settings settings) {
this.bitbucketCloudRestClient = bitbucketCloudRestClient;
this.settings = settings;
}
public void validate(AlmSettingDto dto) {
String clientId = requireNonNull(dto.getClientId());
String appId = requireNonNull(dto.getAppId());
String decryptedClientSecret = requireNonNull(dto.getDecryptedClientSecret(settings.getEncryption()));
bitbucketCloudRestClient.validate(clientId, decryptedClientSecret, appId);
}
}
| 1,785 | 37 | 106 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/bitbucket/bitbucketcloud/Error.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.alm.client.bitbucket.bitbucketcloud;
import com.google.gson.annotations.SerializedName;
public class Error {
@SerializedName("error")
public ErrorMsg errorMsg;
public static class ErrorMsg {
@SerializedName("message")
public String message;
}
}
| 1,125 | 33.121212 | 75 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/bitbucket/bitbucketcloud/MainBranch.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.alm.client.bitbucket.bitbucketcloud;
import com.google.gson.annotations.SerializedName;
public class MainBranch {
@SerializedName("type")
private String type;
@SerializedName("name")
private String name;
public MainBranch() {
// http://stackoverflow.com/a/18645370/229031
}
public MainBranch(String type, String name) {
this.type = type;
this.name = name;
}
public String getType() {
return type;
}
public String getName() {
return name;
}
}
| 1,355 | 26.673469 | 75 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/bitbucket/bitbucketcloud/Project.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.alm.client.bitbucket.bitbucketcloud;
import com.google.gson.annotations.SerializedName;
public class Project {
@SerializedName("key")
private String key;
@SerializedName("name")
private String name;
@SerializedName("uuid")
private String uuid;
public Project() {
// http://stackoverflow.com/a/18645370/229031
}
public Project(String uuid, String key, String name) {
this.uuid = uuid;
this.key = key;
this.name = name;
}
public String getKey() {
return key;
}
public String getName() {
return name;
}
public String getUuid() {
return uuid;
}
}
| 1,475 | 24.448276 | 75 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/bitbucket/bitbucketcloud/Repository.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.alm.client.bitbucket.bitbucketcloud;
import com.google.gson.annotations.SerializedName;
public class Repository {
@SerializedName("slug")
private String slug;
@SerializedName("name")
private String name;
@SerializedName("uuid")
private String uuid;
@SerializedName("project")
private Project project;
@SerializedName("mainbranch")
private MainBranch mainBranch;
public Repository() {
// http://stackoverflow.com/a/18645370/229031
}
public Repository(String uuid, String slug, String name, Project project, MainBranch mainBranch) {
this.uuid = uuid;
this.slug = slug;
this.name = name;
this.project = project;
this.mainBranch = mainBranch;
}
public String getSlug() {
return slug;
}
public String getName() {
return name;
}
public String getUuid() {
return uuid;
}
public Project getProject() {
return project;
}
public MainBranch getMainBranch() {
return mainBranch;
}
}
| 1,838 | 24.191781 | 100 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/bitbucket/bitbucketcloud/RepositoryList.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.alm.client.bitbucket.bitbucketcloud;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class RepositoryList {
@SerializedName("next")
private String next;
@SerializedName("page")
private Integer page;
@SerializedName("pagelen")
private Integer pagelen;
@SerializedName("values")
private List<Repository> values;
public RepositoryList() {
// http://stackoverflow.com/a/18645370/229031
}
public RepositoryList(String next, List<Repository> values, Integer page, Integer pagelen) {
this.next = next;
this.values = values;
this.page = page;
this.pagelen = pagelen;
}
public String getNext() {
return next;
}
public List<Repository> getValues() {
return values;
}
public Integer getPage() {
return page;
}
public Integer getPagelen() {
return pagelen;
}
}
| 1,732 | 24.865672 | 94 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/bitbucket/bitbucketcloud/Token.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.alm.client.bitbucket.bitbucketcloud;
import com.google.gson.annotations.SerializedName;
public class Token {
@SerializedName("scopes")
private String scopes;
@SerializedName("access_token")
private String accessToken;
@SerializedName("exires_in")
private long expiresIn;
@SerializedName("token_type")
private String tokenType;
@SerializedName("state")
private String state;
@SerializedName("refresh_token")
private String refreshToken;
public Token() {
// nothing to do here
}
public String getScopes() {
return scopes;
}
public String getAccessToken() {
return accessToken;
}
public long getExpiresIn() {
return expiresIn;
}
public String getTokenType() {
return tokenType;
}
public String getState() {
return state;
}
public String getRefreshToken() {
return refreshToken;
}
}
| 1,729 | 25.212121 | 75 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/bitbucket/bitbucketcloud/TokenError.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.alm.client.bitbucket.bitbucketcloud;
import com.google.gson.annotations.SerializedName;
public class TokenError {
@SerializedName("error")
String error;
@SerializedName("error_description")
String errorDescription;
}
| 1,089 | 34.16129 | 75 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/bitbucket/bitbucketcloud/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.
*/
@ParametersAreNonnullByDefault
package org.sonar.alm.client.bitbucket.bitbucketcloud;
import javax.annotation.ParametersAreNonnullByDefault;
| 986 | 38.48 | 75 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/bitbucketserver/BitbucketServerException.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.alm.client.bitbucketserver;
public class BitbucketServerException extends IllegalArgumentException {
private final int httpStatus;
public BitbucketServerException(int httpStatus, String clientErrorMessage) {
super(clientErrorMessage);
this.httpStatus = httpStatus;
}
public int getHttpStatus() {
return httpStatus;
}
}
| 1,205 | 34.470588 | 78 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/bitbucketserver/BitbucketServerRestClient.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.alm.client.bitbucketserver;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSyntaxException;
import com.google.gson.annotations.SerializedName;
import java.io.IOException;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.sonar.alm.client.TimeoutConfiguration;
import org.sonar.api.server.ServerSide;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonarqube.ws.client.OkHttpClientBuilder;
import static com.google.common.base.Strings.isNullOrEmpty;
import static java.lang.String.format;
import static java.net.HttpURLConnection.HTTP_NOT_FOUND;
import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
import static java.util.Locale.ENGLISH;
import static org.sonar.api.internal.apachecommons.lang.StringUtils.removeEnd;
@ServerSide
public class BitbucketServerRestClient {
private static final Logger LOG = LoggerFactory.getLogger(BitbucketServerRestClient.class);
private static final String GET = "GET";
protected static final String UNABLE_TO_CONTACT_BITBUCKET_SERVER = "Unable to contact Bitbucket server";
protected static final String UNEXPECTED_RESPONSE_FROM_BITBUCKET_SERVER = "Unexpected response from Bitbucket server";
protected final OkHttpClient client;
public BitbucketServerRestClient(TimeoutConfiguration timeoutConfiguration) {
OkHttpClientBuilder okHttpClientBuilder = new OkHttpClientBuilder();
client = okHttpClientBuilder
.setConnectTimeoutMs(timeoutConfiguration.getConnectTimeout())
.setReadTimeoutMs(timeoutConfiguration.getReadTimeout())
.setFollowRedirects(false)
.build();
}
public void validateUrl(String serverUrl) {
HttpUrl url = buildUrl(serverUrl, "/rest/api/1.0/repos");
doGet("", url, body -> buildGson().fromJson(body, RepositoryList.class));
}
public void validateToken(String serverUrl, String token) {
HttpUrl url = buildUrl(serverUrl, "/rest/api/1.0/users");
doGet(token, url, body -> buildGson().fromJson(body, UserList.class));
}
public void validateReadPermission(String serverUrl, String personalAccessToken) {
HttpUrl url = buildUrl(serverUrl, "/rest/api/1.0/repos");
doGet(personalAccessToken, url, body -> buildGson().fromJson(body, RepositoryList.class));
}
public RepositoryList getRepos(String serverUrl, String token, @Nullable String project, @Nullable String repo) {
String projectOrEmpty = Optional.ofNullable(project).orElse("");
String repoOrEmpty = Optional.ofNullable(repo).orElse("");
HttpUrl url = buildUrl(serverUrl, format("/rest/api/1.0/repos?projectname=%s&name=%s", projectOrEmpty, repoOrEmpty));
return doGet(token, url, body -> buildGson().fromJson(body, RepositoryList.class));
}
public Repository getRepo(String serverUrl, String token, String project, String repoSlug) {
HttpUrl url = buildUrl(serverUrl, format("/rest/api/1.0/projects/%s/repos/%s", project, repoSlug));
return doGet(token, url, body -> buildGson().fromJson(body, Repository.class));
}
public RepositoryList getRecentRepo(String serverUrl, String token) {
HttpUrl url = buildUrl(serverUrl, "/rest/api/1.0/profile/recent/repos");
return doGet(token, url, body -> buildGson().fromJson(body, RepositoryList.class));
}
public ProjectList getProjects(String serverUrl, String token) {
HttpUrl url = buildUrl(serverUrl, "/rest/api/1.0/projects");
return doGet(token, url, body -> buildGson().fromJson(body, ProjectList.class));
}
public BranchesList getBranches(String serverUrl, String token, String projectSlug, String repositorySlug) {
HttpUrl url = buildUrl(serverUrl, format("/rest/api/1.0/projects/%s/repos/%s/branches", projectSlug, repositorySlug));
return doGet(token, url, body -> buildGson().fromJson(body, BranchesList.class));
}
protected static HttpUrl buildUrl(@Nullable String serverUrl, String relativeUrl) {
if (serverUrl == null || !(serverUrl.toLowerCase(ENGLISH).startsWith("http://") || serverUrl.toLowerCase(ENGLISH).startsWith("https://"))) {
throw new IllegalArgumentException("url must start with http:// or https://");
}
return HttpUrl.parse(removeEnd(serverUrl, "/") + relativeUrl);
}
protected <G> G doGet(String token, HttpUrl url, Function<String, G> handler) {
Request request = prepareRequestWithBearerToken(token, GET, url, null);
return doCall(request, handler);
}
protected static Request prepareRequestWithBearerToken(@Nullable String token, String method, HttpUrl url, @Nullable RequestBody body) {
Request.Builder builder = new Request.Builder()
.method(method, body)
.url(url)
.addHeader("x-atlassian-token", "no-check")
.addHeader("Accept", "application/json");
if (!isNullOrEmpty(token)) {
builder.addHeader("Authorization", "Bearer " + token);
}
return builder.build();
}
protected <G> G doCall(Request request, Function<String, G> handler) {
String bodyString = getBodyString(request);
return applyHandler(handler, bodyString);
}
private String getBodyString(Request request) {
try (Response response = client.newCall(request).execute()) {
String bodyString = response.body() == null ? "" : response.body().string();
validateResponseBody(response.isSuccessful(), bodyString);
handleHttpErrorIfAny(response.isSuccessful(), response.code(), bodyString);
return bodyString;
} catch (IOException e) {
LOG.info(UNABLE_TO_CONTACT_BITBUCKET_SERVER + ": " + e.getMessage(), e);
throw new IllegalArgumentException(UNABLE_TO_CONTACT_BITBUCKET_SERVER, e);
}
}
protected static <G> G applyHandler(Function<String, G> handler, String bodyString) {
try {
return handler.apply(bodyString);
} catch (JsonSyntaxException e) {
LOG.info(UNABLE_TO_CONTACT_BITBUCKET_SERVER + ". Unexpected body response was : [{}]", bodyString);
LOG.info(UNABLE_TO_CONTACT_BITBUCKET_SERVER + ": {}", e.getMessage(), e);
throw new IllegalArgumentException(UNABLE_TO_CONTACT_BITBUCKET_SERVER + ", got an unexpected response", e);
}
}
protected static void validateResponseBody(boolean isSuccessful, String bodyString) {
if (isSuccessful) {
try {
buildGson().fromJson(bodyString, Object.class);
} catch (JsonParseException e) {
LOG.info(UNEXPECTED_RESPONSE_FROM_BITBUCKET_SERVER + " : [{}]", bodyString);
throw new IllegalArgumentException(UNEXPECTED_RESPONSE_FROM_BITBUCKET_SERVER, e);
}
}
}
protected static void handleHttpErrorIfAny(boolean isSuccessful, int httpCode, String bodyString) {
if (!isSuccessful) {
String errorMessage = getErrorMessage(bodyString);
LOG.info(UNABLE_TO_CONTACT_BITBUCKET_SERVER + ": {} {}", httpCode, errorMessage);
if (httpCode == HTTP_UNAUTHORIZED) {
throw new BitbucketServerException(HTTP_UNAUTHORIZED, "Invalid personal access token");
} else if (httpCode == HTTP_NOT_FOUND) {
throw new BitbucketServerException(HTTP_NOT_FOUND, "Error 404. The requested Bitbucket server is unreachable.");
}
throw new IllegalArgumentException(UNABLE_TO_CONTACT_BITBUCKET_SERVER);
}
}
protected static boolean equals(@Nullable MediaType first, @Nullable MediaType second) {
String s1 = first == null ? null : first.toString().toLowerCase(ENGLISH).replace(" ", "");
String s2 = second == null ? null : second.toString().toLowerCase(ENGLISH).replace(" ", "");
return s1 != null && s2 != null && s1.equals(s2);
}
protected static String getErrorMessage(String bodyString) {
if (!isNullOrEmpty(bodyString)) {
try {
return Stream.of(buildGson().fromJson(bodyString, Errors.class).errorData)
.map(e -> e.exceptionName + " " + e.message)
.collect(Collectors.joining("\n"));
} catch (JsonParseException e) {
return bodyString;
}
}
return bodyString;
}
protected static Gson buildGson() {
return new GsonBuilder()
.create();
}
protected static class Errors {
@SerializedName("errors")
public Error[] errorData;
public Errors() {
// http://stackoverflow.com/a/18645370/229031
}
public static class Error {
@SerializedName("message")
public String message;
@SerializedName("exceptionName")
public String exceptionName;
public Error() {
// http://stackoverflow.com/a/18645370/229031
}
}
}
}
| 9,657 | 39.410042 | 144 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/bitbucketserver/BitbucketServerSettingsValidator.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.alm.client.bitbucketserver;
import org.sonar.api.config.internal.Encryption;
import org.sonar.api.config.internal.Settings;
import org.sonar.api.server.ServerSide;
import org.sonar.db.alm.setting.AlmSettingDto;
@ServerSide
public class BitbucketServerSettingsValidator {
private final BitbucketServerRestClient bitbucketServerRestClient;
private final Encryption encryption;
public BitbucketServerSettingsValidator(BitbucketServerRestClient bitbucketServerRestClient, Settings settings) {
this.bitbucketServerRestClient = bitbucketServerRestClient;
this.encryption = settings.getEncryption();
}
public void validate(AlmSettingDto almSettingDto) {
String bitbucketUrl = almSettingDto.getUrl();
String bitbucketToken = almSettingDto.getDecryptedPersonalAccessToken(encryption);
if (bitbucketUrl == null || bitbucketToken == null) {
throw new IllegalArgumentException("Your global Bitbucket Server configuration is incomplete.");
}
bitbucketServerRestClient.validateUrl(bitbucketUrl);
bitbucketServerRestClient.validateToken(bitbucketUrl, bitbucketToken);
bitbucketServerRestClient.validateReadPermission(bitbucketUrl, bitbucketToken);
}
}
| 2,057 | 41 | 115 | java |
sonarqube | sonarqube-master/server/sonar-alm-client/src/main/java/org/sonar/alm/client/bitbucketserver/Branch.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program 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.
*
* This program 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.alm.client.bitbucketserver;
import com.google.gson.annotations.SerializedName;
public class Branch {
@SerializedName("displayId")
private String name;
@SerializedName("isDefault")
private boolean isDefault;
public Branch(){
// http://stackoverflow.com/a/18645370/229031
}
public Branch(String name, boolean isDefault) {
this.name = name;
this.isDefault = isDefault;
}
public boolean isDefault() {
return isDefault;
}
public String getName() {
return name;
}
}
| 1,374 | 26.5 | 75 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.