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/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/sensor/code/internal/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.
*/
@javax.annotation.ParametersAreNonnullByDefault
package org.sonar.api.batch.sensor.code.internal;
| 941 | 41.818182 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/sensor/coverage/internal/DefaultCoverage.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.api.batch.sensor.coverage.internal;
import java.util.Collections;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.annotation.Nullable;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.sensor.coverage.NewCoverage;
import org.sonar.api.batch.sensor.internal.DefaultStorable;
import org.sonar.api.batch.sensor.internal.SensorStorage;
import static java.util.Objects.requireNonNull;
import static org.sonar.api.utils.Preconditions.checkState;
public class DefaultCoverage extends DefaultStorable implements NewCoverage {
private InputFile inputFile;
private int totalCoveredLines = 0;
private int totalConditions = 0;
private int totalCoveredConditions = 0;
private SortedMap<Integer, Integer> hitsByLine = new TreeMap<>();
private SortedMap<Integer, Integer> conditionsByLine = new TreeMap<>();
private SortedMap<Integer, Integer> coveredConditionsByLine = new TreeMap<>();
public DefaultCoverage() {
super();
}
public DefaultCoverage(@Nullable SensorStorage storage) {
super(storage);
}
@Override
public DefaultCoverage onFile(InputFile inputFile) {
this.inputFile = inputFile;
return this;
}
public InputFile inputFile() {
return inputFile;
}
@Override
public NewCoverage lineHits(int line, int hits) {
validateFile();
if (isExcluded()) {
return this;
}
validateLine(line);
if (!hitsByLine.containsKey(line)) {
hitsByLine.put(line, hits);
if (hits > 0) {
totalCoveredLines += 1;
}
}
return this;
}
private void validateLine(int line) {
checkState(line <= inputFile.lines(), "Line %s is out of range in the file %s (lines: %s)", line, inputFile, inputFile.lines());
checkState(line > 0, "Line number must be strictly positive: %s", line);
}
private void validateFile() {
requireNonNull(inputFile, "Call onFile() first");
}
@Override
public NewCoverage conditions(int line, int conditions, int coveredConditions) {
validateFile();
if (isExcluded()) {
return this;
}
validateLine(line);
if (conditions > 0 && !conditionsByLine.containsKey(line)) {
totalConditions += conditions;
totalCoveredConditions += coveredConditions;
conditionsByLine.put(line, conditions);
coveredConditionsByLine.put(line, coveredConditions);
}
return this;
}
public int coveredLines() {
return totalCoveredLines;
}
public int linesToCover() {
return hitsByLine.size();
}
public int conditions() {
return totalConditions;
}
public int coveredConditions() {
return totalCoveredConditions;
}
public SortedMap<Integer, Integer> hitsByLine() {
return Collections.unmodifiableSortedMap(hitsByLine);
}
public SortedMap<Integer, Integer> conditionsByLine() {
return Collections.unmodifiableSortedMap(conditionsByLine);
}
public SortedMap<Integer, Integer> coveredConditionsByLine() {
return Collections.unmodifiableSortedMap(coveredConditionsByLine);
}
@Override
public void doSave() {
validateFile();
if (!isExcluded() && inputFile.type() != InputFile.Type.TEST) {
storage.store(this);
}
}
private boolean isExcluded() {
return ((DefaultInputFile) inputFile).isExcludedForCoverage();
}
}
| 4,223 | 27.734694 | 132 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/sensor/coverage/internal/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.
*/
@javax.annotation.ParametersAreNonnullByDefault
package org.sonar.api.batch.sensor.coverage.internal;
| 945 | 42 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/sensor/cpd/internal/DefaultCpdTokens.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.api.batch.sensor.cpd.internal;
import java.util.ArrayList;
import java.util.List;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.TextRange;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.sensor.cpd.NewCpdTokens;
import org.sonar.api.batch.sensor.internal.DefaultStorable;
import org.sonar.api.batch.sensor.internal.SensorStorage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static java.util.Collections.unmodifiableList;
import static java.util.Objects.requireNonNull;
import static org.sonar.api.utils.Preconditions.checkState;
public class DefaultCpdTokens extends DefaultStorable implements NewCpdTokens {
private static final Logger LOG = LoggerFactory.getLogger(DefaultCpdTokens.class);
private final List<TokensLine> result = new ArrayList<>();
private DefaultInputFile inputFile;
private int startLine = Integer.MIN_VALUE;
private int startIndex = 0;
private int currentIndex = 0;
private StringBuilder sb = new StringBuilder();
private TextRange lastRange;
private boolean loggedTestCpdWarning = false;
public DefaultCpdTokens(SensorStorage storage) {
super(storage);
}
@Override
public DefaultCpdTokens onFile(InputFile inputFile) {
this.inputFile = (DefaultInputFile) requireNonNull(inputFile, "file can't be null");
return this;
}
public InputFile inputFile() {
return inputFile;
}
@Override
public NewCpdTokens addToken(int startLine, int startLineOffset, int endLine, int endLineOffset, String image) {
checkInputFileNotNull();
TextRange newRange;
try {
newRange = inputFile.newRange(startLine, startLineOffset, endLine, endLineOffset);
} catch (Exception e) {
throw new IllegalArgumentException("Unable to register token in file " + inputFile, e);
}
return addToken(newRange, image);
}
@Override
public DefaultCpdTokens addToken(TextRange range, String image) {
requireNonNull(range, "Range should not be null");
requireNonNull(image, "Image should not be null");
checkInputFileNotNull();
if (isExcludedForDuplication()) {
return this;
}
checkState(lastRange == null || lastRange.end().compareTo(range.start()) <= 0,
"Tokens of file %s should be provided in order.\nPrevious token: %s\nLast token: %s", inputFile, lastRange, range);
int line = range.start().line();
if (line != startLine) {
addNewTokensLine(result, startIndex, currentIndex, startLine, sb);
startIndex = currentIndex + 1;
startLine = line;
}
currentIndex++;
sb.append(image);
lastRange = range;
return this;
}
private boolean isExcludedForDuplication() {
if (inputFile.isExcludedForDuplication()) {
return true;
}
if (inputFile.type() == InputFile.Type.TEST) {
if (!loggedTestCpdWarning) {
LOG.warn("Duplication reported for '{}' will be ignored because it's a test file.", inputFile);
loggedTestCpdWarning = true;
}
return true;
}
return false;
}
public List<TokensLine> getTokenLines() {
return unmodifiableList(new ArrayList<>(result));
}
private static void addNewTokensLine(List<TokensLine> result, int startUnit, int endUnit, int startLine, StringBuilder sb) {
if (sb.length() != 0) {
result.add(new TokensLine(startUnit, endUnit, startLine, sb.toString()));
sb.setLength(0);
}
}
@Override
protected void doSave() {
checkState(inputFile != null, "Call onFile() first");
if (isExcludedForDuplication()) {
return;
}
addNewTokensLine(result, startIndex, currentIndex, startLine, sb);
storage.store(this);
}
private void checkInputFileNotNull() {
checkState(inputFile != null, "Call onFile() first");
}
}
| 4,659 | 33.014599 | 126 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/sensor/cpd/internal/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.
*/
@javax.annotation.ParametersAreNonnullByDefault
package org.sonar.api.batch.sensor.cpd.internal;
| 940 | 41.772727 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/sensor/error/internal/DefaultAnalysisError.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.api.batch.sensor.error.internal;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.TextPointer;
import org.sonar.api.batch.sensor.error.AnalysisError;
import org.sonar.api.batch.sensor.error.NewAnalysisError;
import org.sonar.api.batch.sensor.internal.DefaultStorable;
import org.sonar.api.batch.sensor.internal.SensorStorage;
import static java.util.Objects.requireNonNull;
import static org.sonar.api.utils.Preconditions.checkArgument;
import static org.sonar.api.utils.Preconditions.checkState;
public class DefaultAnalysisError extends DefaultStorable implements NewAnalysisError, AnalysisError {
private InputFile inputFile;
private String message;
private TextPointer location;
public DefaultAnalysisError() {
super(null);
}
public DefaultAnalysisError(SensorStorage storage) {
super(storage);
}
@Override
public InputFile inputFile() {
return inputFile;
}
@Override
public String message() {
return message;
}
@Override
public TextPointer location() {
return location;
}
@Override
public NewAnalysisError onFile(InputFile inputFile) {
checkArgument(inputFile != null, "Cannot use a inputFile that is null");
checkState(this.inputFile == null, "onFile() already called");
this.inputFile = inputFile;
return this;
}
@Override
public NewAnalysisError message(String message) {
this.message = message;
return this;
}
@Override
public NewAnalysisError at(TextPointer location) {
checkState(this.location == null, "at() already called");
this.location = location;
return this;
}
@Override
protected void doSave() {
requireNonNull(this.inputFile, "inputFile is mandatory on AnalysisError");
storage.store(this);
}
}
| 2,631 | 28.573034 | 102 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/sensor/error/internal/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.api.batch.sensor.error.internal;
import javax.annotation.ParametersAreNonnullByDefault;
| 982 | 38.32 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/sensor/highlighting/internal/DefaultHighlighting.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.api.batch.sensor.highlighting.internal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.TextRange;
import org.sonar.api.batch.sensor.highlighting.NewHighlighting;
import org.sonar.api.batch.sensor.highlighting.TypeOfText;
import org.sonar.api.batch.sensor.internal.SensorStorage;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.sensor.internal.DefaultStorable;
import static java.util.Objects.requireNonNull;
import static org.sonar.api.utils.Preconditions.checkState;
public class DefaultHighlighting extends DefaultStorable implements NewHighlighting {
private final List<SyntaxHighlightingRule> syntaxHighlightingRules;
private DefaultInputFile inputFile;
public DefaultHighlighting(SensorStorage storage) {
super(storage);
syntaxHighlightingRules = new ArrayList<>();
}
public List<SyntaxHighlightingRule> getSyntaxHighlightingRuleSet() {
return syntaxHighlightingRules;
}
private void checkOverlappingBoundaries() {
if (syntaxHighlightingRules.size() > 1) {
Iterator<SyntaxHighlightingRule> it = syntaxHighlightingRules.iterator();
SyntaxHighlightingRule previous = it.next();
while (it.hasNext()) {
SyntaxHighlightingRule current = it.next();
if (previous.range().end().compareTo(current.range().start()) > 0 && (previous.range().end().compareTo(current.range().end()) < 0)) {
String errorMsg = String.format("Cannot register highlighting rule for characters at %s as it " +
"overlaps at least one existing rule", current.range());
throw new IllegalStateException(errorMsg);
}
previous = current;
}
}
}
@Override
public DefaultHighlighting onFile(InputFile inputFile) {
requireNonNull(inputFile, "file can't be null");
this.inputFile = (DefaultInputFile) inputFile;
return this;
}
public InputFile inputFile() {
return inputFile;
}
@Override
public DefaultHighlighting highlight(int startLine, int startLineOffset, int endLine, int endLineOffset, TypeOfText typeOfText) {
checkInputFileNotNull();
TextRange newRange;
try {
newRange = inputFile.newRange(startLine, startLineOffset, endLine, endLineOffset);
} catch (Exception e) {
throw new IllegalArgumentException("Unable to highlight file " + inputFile, e);
}
return highlight(newRange, typeOfText);
}
@Override
public DefaultHighlighting highlight(TextRange range, TypeOfText typeOfText) {
SyntaxHighlightingRule syntaxHighlightingRule = SyntaxHighlightingRule.create(range, typeOfText);
this.syntaxHighlightingRules.add(syntaxHighlightingRule);
return this;
}
@Override
protected void doSave() {
checkInputFileNotNull();
// Sort rules to avoid variation during consecutive runs
Collections.sort(syntaxHighlightingRules, (left, right) -> {
int result = left.range().start().compareTo(right.range().start());
if (result == 0) {
result = right.range().end().compareTo(left.range().end());
}
return result;
});
checkOverlappingBoundaries();
storage.store(this);
}
private void checkInputFileNotNull() {
checkState(inputFile != null, "Call onFile() first");
}
}
| 4,238 | 35.543103 | 141 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/sensor/highlighting/internal/SyntaxHighlightingRule.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.api.batch.sensor.highlighting.internal;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.sonar.api.batch.fs.TextRange;
import org.sonar.api.batch.sensor.highlighting.TypeOfText;
public class SyntaxHighlightingRule {
private final TextRange range;
private final TypeOfText textType;
private SyntaxHighlightingRule(TextRange range, TypeOfText textType) {
this.range = range;
this.textType = textType;
}
public static SyntaxHighlightingRule create(TextRange range, TypeOfText textType) {
return new SyntaxHighlightingRule(range, textType);
}
public TextRange range() {
return range;
}
public TypeOfText getTextType() {
return textType;
}
@Override
public String toString() {
return ReflectionToStringBuilder.toString(this, ToStringStyle.SIMPLE_STYLE);
}
}
| 1,754 | 31.5 | 85 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/sensor/highlighting/internal/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.api.batch.sensor.highlighting.internal;
import javax.annotation.ParametersAreNonnullByDefault;
| 989 | 38.6 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/sensor/internal/DefaultSensorDescriptor.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.api.batch.sensor.internal;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.api.config.Configuration;
public class DefaultSensorDescriptor implements SensorDescriptor {
public static final Set<String> HARDCODED_INDEPENDENT_FILE_SENSORS = Collections.unmodifiableSet(Stream.of(
"CSS Metrics",
"CSS Rules",
"HTML",
"XML Sensor"
).collect(Collectors.toSet()));
private String name;
private String[] languages = new String[0];
private InputFile.Type type = null;
private String[] ruleRepositories = new String[0];
private boolean global = false;
private Predicate<Configuration> configurationPredicate;
private boolean processesFilesIndependently = false;
public String name() {
return name;
}
public Collection<String> languages() {
return Arrays.asList(languages);
}
@Nullable
public InputFile.Type type() {
return type;
}
public Collection<String> ruleRepositories() {
return Arrays.asList(ruleRepositories);
}
public Predicate<Configuration> configurationPredicate() {
return configurationPredicate;
}
public boolean isGlobal() {
return global;
}
public boolean isProcessesFilesIndependently() {
return processesFilesIndependently;
}
@Override
public DefaultSensorDescriptor name(String name) {
// TODO: Remove this hardcoded list once all plugins will implement the new API "processFilesIndependently"
if (HARDCODED_INDEPENDENT_FILE_SENSORS.contains(name)) {
processesFilesIndependently = true;
}
this.name = name;
return this;
}
@Override
public DefaultSensorDescriptor onlyOnLanguage(String languageKey) {
return onlyOnLanguages(languageKey);
}
@Override
public DefaultSensorDescriptor onlyOnLanguages(String... languageKeys) {
this.languages = languageKeys;
return this;
}
@Override
public DefaultSensorDescriptor onlyOnFileType(InputFile.Type type) {
this.type = type;
return this;
}
@Override
public DefaultSensorDescriptor createIssuesForRuleRepository(String... repositoryKey) {
return createIssuesForRuleRepositories(repositoryKey);
}
@Override
public DefaultSensorDescriptor createIssuesForRuleRepositories(String... repositoryKeys) {
this.ruleRepositories = repositoryKeys;
return this;
}
@Override
public SensorDescriptor global() {
this.global = true;
return this;
}
@Override
public SensorDescriptor onlyWhenConfiguration(Predicate<Configuration> configurationPredicate) {
this.configurationPredicate = configurationPredicate;
return this;
}
@Override
public SensorDescriptor processesFilesIndependently() {
this.processesFilesIndependently = true;
return this;
}
}
| 3,919 | 27.823529 | 111 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/sensor/internal/DefaultStorable.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.api.batch.sensor.internal;
import javax.annotation.Nullable;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import static java.util.Objects.requireNonNull;
import static org.sonar.api.utils.Preconditions.checkState;
public abstract class DefaultStorable {
protected final SensorStorage storage;
private boolean saved = false;
public DefaultStorable() {
this.storage = null;
}
public DefaultStorable(@Nullable SensorStorage storage) {
this.storage = storage;
}
public final void save() {
requireNonNull(this.storage, "No persister on this object");
checkState(!saved, "This object was already saved");
doSave();
this.saved = true;
}
protected abstract void doSave();
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
}
| 1,776 | 30.175439 | 86 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/sensor/internal/InMemorySensorStorage.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.api.batch.sensor.internal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.sonar.api.batch.sensor.code.NewSignificantCode;
import org.sonar.api.batch.sensor.code.internal.DefaultSignificantCode;
import org.sonar.api.batch.sensor.coverage.NewCoverage;
import org.sonar.api.batch.sensor.coverage.internal.DefaultCoverage;
import org.sonar.api.batch.sensor.cpd.NewCpdTokens;
import org.sonar.api.batch.sensor.cpd.internal.DefaultCpdTokens;
import org.sonar.api.batch.sensor.error.AnalysisError;
import org.sonar.api.batch.sensor.highlighting.NewHighlighting;
import org.sonar.api.batch.sensor.highlighting.internal.DefaultHighlighting;
import org.sonar.api.batch.sensor.issue.ExternalIssue;
import org.sonar.api.batch.sensor.issue.Issue;
import org.sonar.api.batch.sensor.measure.Measure;
import org.sonar.api.batch.sensor.rule.AdHocRule;
import org.sonar.api.batch.sensor.symbol.NewSymbolTable;
import org.sonar.api.batch.sensor.symbol.internal.DefaultSymbolTable;
import static org.sonar.api.utils.Preconditions.checkArgument;
class InMemorySensorStorage implements SensorStorage {
Map<String, Map<String, Measure>> measuresByComponentAndMetric = new HashMap<>();
Collection<Issue> allIssues = new ArrayList<>();
Collection<ExternalIssue> allExternalIssues = new ArrayList<>();
Collection<AdHocRule> allAdHocRules = new ArrayList<>();
Collection<AnalysisError> allAnalysisErrors = new ArrayList<>();
Map<String, NewHighlighting> highlightingByComponent = new HashMap<>();
Map<String, DefaultCpdTokens> cpdTokensByComponent = new HashMap<>();
Map<String, List<DefaultCoverage>> coverageByComponent = new HashMap<>();
Map<String, DefaultSymbolTable> symbolsPerComponent = new HashMap<>();
Map<String, String> contextProperties = new HashMap<>();
Map<String, DefaultSignificantCode> significantCodePerComponent = new HashMap<>();
@Override
public void store(Measure measure) {
// Emulate duplicate measure check
String componentKey = measure.inputComponent().key();
String metricKey = measure.metric().key();
if (measuresByComponentAndMetric.getOrDefault(componentKey, Collections.emptyMap()).containsKey(metricKey)) {
throw new IllegalStateException("Can not add the same measure twice");
}
measuresByComponentAndMetric.computeIfAbsent(componentKey, x -> new HashMap<>()).put(metricKey, measure);
}
@Override
public void store(Issue issue) {
allIssues.add(issue);
}
@Override
public void store(AdHocRule adHocRule) {
allAdHocRules.add(adHocRule);
}
@Override
public void store(NewHighlighting newHighlighting) {
DefaultHighlighting highlighting = (DefaultHighlighting) newHighlighting;
String fileKey = highlighting.inputFile().key();
// Emulate duplicate storage check
if (highlightingByComponent.containsKey(fileKey)) {
throw new UnsupportedOperationException("Trying to save highlighting twice for the same file is not supported: " + highlighting.inputFile());
}
highlightingByComponent.put(fileKey, highlighting);
}
@Override
public void store(NewCoverage coverage) {
DefaultCoverage defaultCoverage = (DefaultCoverage) coverage;
String fileKey = defaultCoverage.inputFile().key();
coverageByComponent.computeIfAbsent(fileKey, x -> new ArrayList<>()).add(defaultCoverage);
}
@Override
public void store(NewCpdTokens cpdTokens) {
DefaultCpdTokens defaultCpdTokens = (DefaultCpdTokens) cpdTokens;
String fileKey = defaultCpdTokens.inputFile().key();
// Emulate duplicate storage check
if (cpdTokensByComponent.containsKey(fileKey)) {
throw new UnsupportedOperationException("Trying to save CPD tokens twice for the same file is not supported: " + defaultCpdTokens.inputFile());
}
cpdTokensByComponent.put(fileKey, defaultCpdTokens);
}
@Override
public void store(NewSymbolTable newSymbolTable) {
DefaultSymbolTable symbolTable = (DefaultSymbolTable) newSymbolTable;
String fileKey = symbolTable.inputFile().key();
// Emulate duplicate storage check
if (symbolsPerComponent.containsKey(fileKey)) {
throw new UnsupportedOperationException("Trying to save symbol table twice for the same file is not supported: " + symbolTable.inputFile());
}
symbolsPerComponent.put(fileKey, symbolTable);
}
@Override
public void store(AnalysisError analysisError) {
allAnalysisErrors.add(analysisError);
}
@Override
public void storeProperty(String key, String value) {
checkArgument(key != null, "Key of context property must not be null");
checkArgument(value != null, "Value of context property must not be null");
contextProperties.put(key, value);
}
@Override
public void store(ExternalIssue issue) {
allExternalIssues.add(issue);
}
@Override
public void store(NewSignificantCode newSignificantCode) {
DefaultSignificantCode significantCode = (DefaultSignificantCode) newSignificantCode;
String fileKey = significantCode.inputFile().key();
// Emulate duplicate storage check
if (significantCodePerComponent.containsKey(fileKey)) {
throw new UnsupportedOperationException("Trying to save significant code information twice for the same file is not supported: " + significantCode.inputFile());
}
significantCodePerComponent.put(fileKey, significantCode);
}
}
| 6,320 | 40.860927 | 166 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/sensor/internal/SensorContextTester.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.api.batch.sensor.internal;
import java.io.File;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.api.SonarQubeSide;
import org.sonar.api.SonarRuntime;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.InputModule;
import org.sonar.api.batch.fs.TextRange;
import org.sonar.api.batch.fs.internal.DefaultFileSystem;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.fs.internal.DefaultTextPointer;
import org.sonar.api.batch.rule.ActiveRules;
import org.sonar.api.batch.rule.internal.ActiveRulesBuilder;
import org.sonar.api.batch.sensor.Sensor;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.cache.ReadCache;
import org.sonar.api.batch.sensor.cache.WriteCache;
import org.sonar.api.batch.sensor.code.NewSignificantCode;
import org.sonar.api.batch.sensor.code.internal.DefaultSignificantCode;
import org.sonar.api.batch.sensor.coverage.NewCoverage;
import org.sonar.api.batch.sensor.coverage.internal.DefaultCoverage;
import org.sonar.api.batch.sensor.cpd.NewCpdTokens;
import org.sonar.api.batch.sensor.cpd.internal.DefaultCpdTokens;
import org.sonar.api.batch.sensor.cpd.internal.TokensLine;
import org.sonar.api.batch.sensor.error.AnalysisError;
import org.sonar.api.batch.sensor.error.NewAnalysisError;
import org.sonar.api.batch.sensor.error.internal.DefaultAnalysisError;
import org.sonar.api.batch.sensor.highlighting.NewHighlighting;
import org.sonar.api.batch.sensor.highlighting.TypeOfText;
import org.sonar.api.batch.sensor.highlighting.internal.DefaultHighlighting;
import org.sonar.api.batch.sensor.highlighting.internal.SyntaxHighlightingRule;
import org.sonar.api.batch.sensor.issue.ExternalIssue;
import org.sonar.api.batch.sensor.issue.Issue;
import org.sonar.api.batch.sensor.issue.NewExternalIssue;
import org.sonar.api.batch.sensor.issue.NewIssue;
import org.sonar.api.batch.sensor.issue.internal.DefaultExternalIssue;
import org.sonar.api.batch.sensor.issue.internal.DefaultIssue;
import org.sonar.api.batch.sensor.measure.Measure;
import org.sonar.api.batch.sensor.measure.NewMeasure;
import org.sonar.api.batch.sensor.measure.internal.DefaultMeasure;
import org.sonar.api.batch.sensor.rule.AdHocRule;
import org.sonar.api.batch.sensor.rule.NewAdHocRule;
import org.sonar.api.batch.sensor.rule.internal.DefaultAdHocRule;
import org.sonar.api.batch.sensor.symbol.NewSymbolTable;
import org.sonar.api.batch.sensor.symbol.internal.DefaultSymbolTable;
import org.sonar.api.config.Configuration;
import org.sonar.api.config.internal.ConfigurationBridge;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.internal.MetadataLoader;
import org.sonar.api.internal.SonarRuntimeImpl;
import org.sonar.api.measures.Metric;
import org.sonar.api.scanner.fs.InputProject;
import org.sonar.api.utils.System2;
import org.sonar.api.utils.Version;
import static java.util.Collections.unmodifiableMap;
/**
* Utility class to help testing {@link Sensor}. This is not an API and method signature may evolve.
* <p>
* Usage: call {@link #create(File)} to create an "in memory" implementation of {@link SensorContext} with a filesystem initialized with provided baseDir.
* <p>
* You have to manually register inputFiles using:
* <pre>
* sensorContextTester.fileSystem().add(new DefaultInputFile("myProjectKey", "src/Foo.java")
* .setLanguage("java")
* .initMetadata("public class Foo {\n}"));
* </pre>
* <p>
* Then pass it to your {@link Sensor}. You can then query elements provided by your sensor using methods {@link #allIssues()}, ...
*/
public class SensorContextTester implements SensorContext {
private MapSettings settings;
private DefaultFileSystem fs;
private ActiveRules activeRules;
private InMemorySensorStorage sensorStorage;
private DefaultInputProject project;
private DefaultInputModule module;
private SonarRuntime runtime;
private ReadCache readCache;
private WriteCache writeCache;
private boolean canSkipUnchangedFiles;
private boolean cancelled;
private boolean cacheEnabled = false;
private SensorContextTester(Path moduleBaseDir) {
this.settings = new MapSettings();
this.fs = new DefaultFileSystem(moduleBaseDir).setEncoding(Charset.defaultCharset());
this.activeRules = new ActiveRulesBuilder().build();
this.sensorStorage = new InMemorySensorStorage();
this.project = new DefaultInputProject(ProjectDefinition.create().setKey("projectKey").setBaseDir(moduleBaseDir.toFile()).setWorkDir(moduleBaseDir.resolve(".sonar").toFile()));
this.module = new DefaultInputModule(ProjectDefinition.create().setKey("projectKey").setBaseDir(moduleBaseDir.toFile()).setWorkDir(moduleBaseDir.resolve(".sonar").toFile()));
this.runtime = SonarRuntimeImpl.forSonarQube(MetadataLoader.loadApiVersion(System2.INSTANCE), SonarQubeSide.SCANNER, MetadataLoader.loadEdition(System2.INSTANCE));
}
public static SensorContextTester create(File moduleBaseDir) {
return new SensorContextTester(moduleBaseDir.toPath());
}
public static SensorContextTester create(Path moduleBaseDir) {
return new SensorContextTester(moduleBaseDir);
}
@Override
public MapSettings settings() {
return settings;
}
@Override
public Configuration config() {
return new ConfigurationBridge(settings);
}
public SensorContextTester setSettings(MapSettings settings) {
this.settings = settings;
return this;
}
@Override
public DefaultFileSystem fileSystem() {
return fs;
}
public SensorContextTester setFileSystem(DefaultFileSystem fs) {
this.fs = fs;
return this;
}
@Override
public ActiveRules activeRules() {
return activeRules;
}
public SensorContextTester setActiveRules(ActiveRules activeRules) {
this.activeRules = activeRules;
return this;
}
/**
* Default value is the version of this API at compilation time. You can override it
* using {@link #setRuntime(SonarRuntime)} to test your Sensor behaviour.
*/
@Override
public Version getSonarQubeVersion() {
return runtime().getApiVersion();
}
/**
* @see #setRuntime(SonarRuntime) to override defaults (SonarQube scanner with version
* of this API as used at compilation time).
*/
@Override
public SonarRuntime runtime() {
return runtime;
}
public SensorContextTester setRuntime(SonarRuntime runtime) {
this.runtime = runtime;
return this;
}
@Override
public boolean isCancelled() {
return cancelled;
}
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public boolean canSkipUnchangedFiles() {
return canSkipUnchangedFiles;
}
public SensorContextTester setCanSkipUnchangedFiles(boolean canSkipUnchangedFiles) {
this.canSkipUnchangedFiles = canSkipUnchangedFiles;
return this;
}
@Override
public InputModule module() {
return module;
}
@Override
public InputProject project() {
return project;
}
@Override
public <G extends Serializable> NewMeasure<G> newMeasure() {
return new DefaultMeasure<>(sensorStorage);
}
public Collection<Measure> measures(String componentKey) {
return sensorStorage.measuresByComponentAndMetric.getOrDefault(componentKey, Collections.emptyMap()).values();
}
public <G extends Serializable> Measure<G> measure(String componentKey, Metric<G> metric) {
return measure(componentKey, metric.key());
}
public <G extends Serializable> Measure<G> measure(String componentKey, String metricKey) {
return sensorStorage.measuresByComponentAndMetric.getOrDefault(componentKey, Collections.emptyMap()).get(metricKey);
}
@Override
public NewIssue newIssue() {
return new DefaultIssue(project, sensorStorage);
}
public Collection<Issue> allIssues() {
return sensorStorage.allIssues;
}
@Override
public NewExternalIssue newExternalIssue() {
return new DefaultExternalIssue(project, sensorStorage);
}
@Override
public NewAdHocRule newAdHocRule() {
return new DefaultAdHocRule(sensorStorage);
}
public Collection<ExternalIssue> allExternalIssues() {
return sensorStorage.allExternalIssues;
}
public Collection<AdHocRule> allAdHocRules() {
return sensorStorage.allAdHocRules;
}
public Collection<AnalysisError> allAnalysisErrors() {
return sensorStorage.allAnalysisErrors;
}
@CheckForNull
public Integer lineHits(String fileKey, int line) {
return sensorStorage.coverageByComponent.getOrDefault(fileKey, Collections.emptyList()).stream()
.map(c -> c.hitsByLine().get(line))
.filter(Objects::nonNull)
.reduce(null, SensorContextTester::sumOrNull);
}
@CheckForNull
public static Integer sumOrNull(@Nullable Integer o1, @Nullable Integer o2) {
return o1 == null ? o2 : (o1 + o2);
}
@CheckForNull
public Integer conditions(String fileKey, int line) {
return sensorStorage.coverageByComponent.getOrDefault(fileKey, Collections.emptyList()).stream()
.map(c -> c.conditionsByLine().get(line))
.filter(Objects::nonNull)
.reduce(null, SensorContextTester::maxOrNull);
}
@CheckForNull
public Integer coveredConditions(String fileKey, int line) {
return sensorStorage.coverageByComponent.getOrDefault(fileKey, Collections.emptyList()).stream()
.map(c -> c.coveredConditionsByLine().get(line))
.filter(Objects::nonNull)
.reduce(null, SensorContextTester::maxOrNull);
}
@CheckForNull
public TextRange significantCodeTextRange(String fileKey, int line) {
if (sensorStorage.significantCodePerComponent.containsKey(fileKey)) {
return sensorStorage.significantCodePerComponent.get(fileKey)
.significantCodePerLine()
.get(line);
}
return null;
}
@CheckForNull
public static Integer maxOrNull(@Nullable Integer o1, @Nullable Integer o2) {
return o1 == null ? o2 : Math.max(o1, o2);
}
@CheckForNull
public List<TokensLine> cpdTokens(String componentKey) {
DefaultCpdTokens defaultCpdTokens = sensorStorage.cpdTokensByComponent.get(componentKey);
return defaultCpdTokens != null ? defaultCpdTokens.getTokenLines() : null;
}
@Override
public NewHighlighting newHighlighting() {
return new DefaultHighlighting(sensorStorage);
}
@Override
public NewCoverage newCoverage() {
return new DefaultCoverage(sensorStorage);
}
@Override
public NewCpdTokens newCpdTokens() {
return new DefaultCpdTokens(sensorStorage);
}
@Override
public NewSymbolTable newSymbolTable() {
return new DefaultSymbolTable(sensorStorage);
}
@Override
public NewAnalysisError newAnalysisError() {
return new DefaultAnalysisError(sensorStorage);
}
/**
* Return list of syntax highlighting applied for a given position in a file. The result is a list because in theory you
* can apply several styles to the same range.
*
* @param componentKey Key of the file like 'myProjectKey:src/foo.php'
* @param line Line you want to query
* @param lineOffset Offset you want to query.
* @return List of styles applied to this position or empty list if there is no highlighting at this position.
*/
public List<TypeOfText> highlightingTypeAt(String componentKey, int line, int lineOffset) {
DefaultHighlighting syntaxHighlightingData = (DefaultHighlighting) sensorStorage.highlightingByComponent.get(componentKey);
if (syntaxHighlightingData == null) {
return Collections.emptyList();
}
List<TypeOfText> result = new ArrayList<>();
DefaultTextPointer location = new DefaultTextPointer(line, lineOffset);
for (SyntaxHighlightingRule sortedRule : syntaxHighlightingData.getSyntaxHighlightingRuleSet()) {
if (sortedRule.range().start().compareTo(location) <= 0 && sortedRule.range().end().compareTo(location) > 0) {
result.add(sortedRule.getTextType());
}
}
return result;
}
/**
* Return list of symbol references ranges for the symbol at a given position in a file.
*
* @param componentKey Key of the file like 'myProjectKey:src/foo.php'
* @param line Line you want to query
* @param lineOffset Offset you want to query.
* @return List of references for the symbol (potentially empty) or null if there is no symbol at this position.
*/
@CheckForNull
public Collection<TextRange> referencesForSymbolAt(String componentKey, int line, int lineOffset) {
DefaultSymbolTable symbolTable = sensorStorage.symbolsPerComponent.get(componentKey);
if (symbolTable == null) {
return null;
}
DefaultTextPointer location = new DefaultTextPointer(line, lineOffset);
for (Map.Entry<TextRange, Set<TextRange>> symbol : symbolTable.getReferencesBySymbol().entrySet()) {
if (symbol.getKey().start().compareTo(location) <= 0 && symbol.getKey().end().compareTo(location) > 0) {
return symbol.getValue();
}
}
return null;
}
@Override
public void addContextProperty(String key, String value) {
sensorStorage.storeProperty(key, value);
}
/**
* @return an immutable map of the context properties defined with {@link SensorContext#addContextProperty(String, String)}.
* @since 6.1
*/
public Map<String, String> getContextProperties() {
return unmodifiableMap(sensorStorage.contextProperties);
}
@Override
public void markForPublishing(InputFile inputFile) {
DefaultInputFile file = (DefaultInputFile) inputFile;
file.setPublished(true);
}
@Override
public void markAsUnchanged(InputFile inputFile) {
((DefaultInputFile) inputFile).setMarkedAsUnchanged(true);
}
@Override
public WriteCache nextCache() {
return writeCache;
}
public void setNextCache(WriteCache writeCache) {
this.writeCache = writeCache;
}
@Override
public ReadCache previousCache() {
return readCache;
}
public void setPreviousCache(ReadCache cache) {
this.readCache = cache;
}
@Override
public boolean isCacheEnabled() {
return cacheEnabled;
}
public void setCacheEnabled(boolean enabled) {
this.cacheEnabled = enabled;
}
@Override
public NewSignificantCode newSignificantCode() {
return new DefaultSignificantCode(sensorStorage);
}
}
| 15,574 | 33.381898 | 180 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/sensor/internal/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.api.batch.sensor.internal;
import javax.annotation.ParametersAreNonnullByDefault;
| 976 | 38.08 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/sensor/issue/internal/AbstractDefaultIssue.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.api.batch.sensor.issue.internal;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.sonar.api.batch.fs.InputComponent;
import org.sonar.api.batch.fs.internal.DefaultInputDir;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.sensor.internal.DefaultStorable;
import org.sonar.api.batch.sensor.internal.SensorStorage;
import org.sonar.api.batch.sensor.issue.Issue.Flow;
import org.sonar.api.batch.sensor.issue.IssueLocation;
import org.sonar.api.batch.sensor.issue.MessageFormatting;
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.utils.PathUtils;
import static org.sonar.api.utils.Preconditions.checkArgument;
import static org.sonar.api.utils.Preconditions.checkState;
public abstract class AbstractDefaultIssue<T extends AbstractDefaultIssue> extends DefaultStorable {
protected IssueLocation primaryLocation;
protected List<DefaultIssueFlow> flows = new ArrayList<>();
protected DefaultInputProject project;
public AbstractDefaultIssue(DefaultInputProject project, @Nullable SensorStorage storage) {
super(storage);
this.project = project;
}
public IssueLocation primaryLocation() {
return primaryLocation;
}
public List<Flow> flows() {
return Collections.unmodifiableList(flows);
}
public NewIssueLocation newLocation() {
return new DefaultIssueLocation();
}
public T at(NewIssueLocation primaryLocation) {
checkArgument(primaryLocation != null, "Cannot use a location that is null");
checkState(this.primaryLocation == null, "at() already called");
this.primaryLocation = rewriteLocation((DefaultIssueLocation) primaryLocation);
checkArgument(this.primaryLocation.inputComponent() != null, "Cannot use a location with no input component");
return (T) this;
}
public T addLocation(NewIssueLocation secondaryLocation) {
flows.add(new DefaultIssueFlow(List.of(rewriteLocation((DefaultIssueLocation) secondaryLocation)), FlowType.UNDEFINED, null));
return (T) this;
}
public T addFlow(Iterable<NewIssueLocation> locations) {
return addFlow(locations, FlowType.UNDEFINED, null);
}
public T addFlow(Iterable<NewIssueLocation> flowLocations, FlowType type, @Nullable String flowDescription) {
checkArgument(type != null, "Type can't be null");
List<IssueLocation> flowAsList = new ArrayList<>();
for (NewIssueLocation issueLocation : flowLocations) {
flowAsList.add(rewriteLocation((DefaultIssueLocation) issueLocation));
}
flows.add(new DefaultIssueFlow(flowAsList, type, flowDescription));
return (T) this;
}
private DefaultIssueLocation rewriteLocation(DefaultIssueLocation location) {
InputComponent component = location.inputComponent();
Optional<Path> dirOrModulePath = Optional.empty();
if (component instanceof DefaultInputDir) {
DefaultInputDir dirComponent = (DefaultInputDir) component;
dirOrModulePath = Optional.of(project.getBaseDir().relativize(dirComponent.path()));
} else if (component instanceof DefaultInputModule && !Objects.equals(project.key(), component.key())) {
DefaultInputModule moduleComponent = (DefaultInputModule) component;
dirOrModulePath = Optional.of(project.getBaseDir().relativize(moduleComponent.getBaseDir()));
}
if (dirOrModulePath.isPresent()) {
String path = PathUtils.sanitize(dirOrModulePath.get().toString());
DefaultIssueLocation fixedLocation = new DefaultIssueLocation();
fixedLocation.on(project);
StringBuilder fullMessage = new StringBuilder();
String prefixMessage;
if (path != null && !path.isEmpty()) {
prefixMessage = "[" + path + "] ";
} else {
prefixMessage = "";
}
fullMessage.append(prefixMessage);
fullMessage.append(location.message());
List<NewMessageFormatting> paddedFormattings = location.messageFormattings().stream()
.map(m -> padMessageFormatting(m, prefixMessage.length()))
.collect(Collectors.toList());
fixedLocation.message(fullMessage.toString(), paddedFormattings);
return fixedLocation;
} else {
return location;
}
}
private static NewMessageFormatting padMessageFormatting(MessageFormatting messageFormatting, int length) {
return new DefaultMessageFormatting().type(messageFormatting.type())
.start(messageFormatting.start() + length)
.end(messageFormatting.end() + length);
}
}
| 5,690 | 39.361702 | 130 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/sensor/issue/internal/DefaultExternalIssue.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.api.batch.sensor.issue.internal;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.rule.Severity;
import org.sonar.api.batch.sensor.internal.SensorStorage;
import org.sonar.api.batch.sensor.issue.ExternalIssue;
import org.sonar.api.batch.sensor.issue.NewExternalIssue;
import org.sonar.api.code.CodeCharacteristic;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rules.RuleType;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
import static org.sonar.api.utils.Preconditions.checkArgument;
import static org.sonar.api.utils.Preconditions.checkState;
public class DefaultExternalIssue extends AbstractDefaultIssue<DefaultExternalIssue> implements ExternalIssue, NewExternalIssue {
private Long effort;
private Severity severity;
private RuleType type;
private String engineId;
private String ruleId;
public DefaultExternalIssue(DefaultInputProject project) {
this(project, null);
}
public DefaultExternalIssue(DefaultInputProject project, @Nullable SensorStorage storage) {
super(project, storage);
}
@Override
public DefaultExternalIssue remediationEffortMinutes(@Nullable Long effort) {
checkArgument(effort == null || effort >= 0, format("effort must be greater than or equal 0 (got %s)", effort));
this.effort = effort;
return this;
}
@Override
public DefaultExternalIssue severity(Severity severity) {
this.severity = severity;
return this;
}
@Override
public String engineId() {
return engineId;
}
@Override
public String ruleId() {
return ruleId;
}
@Override
public Severity severity() {
return this.severity;
}
@Override
public Long remediationEffort() {
return this.effort;
}
@Override
public void doSave() {
requireNonNull(this.engineId, "Engine id is mandatory on external issue");
requireNonNull(this.ruleId, "Rule id is mandatory on external issue");
checkState(primaryLocation != null, "Primary location is mandatory on every external issue");
checkState(primaryLocation.message() != null, "External issues must have a message");
checkState(severity != null, "Severity is mandatory on every external issue");
checkState(type != null, "Type is mandatory on every external issue");
storage.store(this);
}
@Override
public RuleType type() {
return type;
}
@CheckForNull
@Override
public CodeCharacteristic characteristic() {
return null;
}
@Override
public NewExternalIssue engineId(String engineId) {
this.engineId = engineId;
return this;
}
@Override
public NewExternalIssue ruleId(String ruleId) {
this.ruleId = ruleId;
return this;
}
@Override
public DefaultExternalIssue forRule(RuleKey ruleKey) {
this.engineId = ruleKey.repository();
this.ruleId = ruleKey.rule();
return this;
}
@Override
public RuleKey ruleKey() {
if (engineId != null && ruleId != null) {
return RuleKey.of(RuleKey.EXTERNAL_RULE_REPO_PREFIX + engineId, ruleId);
}
return null;
}
@Override
public DefaultExternalIssue type(RuleType type) {
this.type = type;
return this;
}
@Override
public NewExternalIssue characteristic(CodeCharacteristic characteristic) {
// no op
return this;
}
}
| 4,260 | 27.790541 | 129 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/sensor/issue/internal/DefaultIssue.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.api.batch.sensor.issue.internal;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nullable;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.rule.Severity;
import org.sonar.api.batch.sensor.internal.SensorStorage;
import org.sonar.api.batch.sensor.issue.Issue;
import org.sonar.api.batch.sensor.issue.IssueLocation;
import org.sonar.api.batch.sensor.issue.NewIssue;
import org.sonar.api.batch.sensor.issue.fix.NewQuickFix;
import org.sonar.api.batch.sensor.issue.fix.QuickFix;
import org.sonar.api.rule.RuleKey;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
import static org.sonar.api.utils.Preconditions.checkArgument;
import static org.sonar.api.utils.Preconditions.checkState;
public class DefaultIssue extends AbstractDefaultIssue<DefaultIssue> implements Issue, NewIssue {
private RuleKey ruleKey;
private Double gap;
private Severity overriddenSeverity;
private boolean quickFixAvailable = false;
private String ruleDescriptionContextKey;
private List<String> codeVariants;
public DefaultIssue(DefaultInputProject project) {
this(project, null);
}
public DefaultIssue(DefaultInputProject project, @Nullable SensorStorage storage) {
super(project, storage);
}
public DefaultIssue forRule(RuleKey ruleKey) {
this.ruleKey = ruleKey;
return this;
}
public RuleKey ruleKey() {
return this.ruleKey;
}
@Override
public DefaultIssue gap(@Nullable Double gap) {
checkArgument(gap == null || gap >= 0, format("Gap must be greater than or equal 0 (got %s)", gap));
this.gap = gap;
return this;
}
@Override
public DefaultIssue overrideSeverity(@Nullable Severity severity) {
this.overriddenSeverity = severity;
return this;
}
@Override
public DefaultIssue setQuickFixAvailable(boolean quickFixAvailable) {
this.quickFixAvailable = quickFixAvailable;
return this;
}
@Override
public NewQuickFix newQuickFix() {
return new NoOpNewQuickFix();
}
@Override
public NewIssue addQuickFix(NewQuickFix newQuickFix) {
this.quickFixAvailable = true;
return this;
}
@Override
public DefaultIssue setRuleDescriptionContextKey(@Nullable String ruleDescriptionContextKey) {
this.ruleDescriptionContextKey = ruleDescriptionContextKey;
return this;
}
@Override
public DefaultIssue setCodeVariants(@Nullable Iterable<String> codeVariants) {
if (codeVariants != null) {
List<String> codeVariantsList = new ArrayList<>();
codeVariants.forEach(codeVariantsList::add);
this.codeVariants = codeVariantsList;
}
return this;
}
@Override
public boolean isQuickFixAvailable() {
return quickFixAvailable;
}
@Override
public Optional<String> ruleDescriptionContextKey() {
return Optional.ofNullable(ruleDescriptionContextKey);
}
@Override
public List<QuickFix> quickFixes() {
throw new UnsupportedOperationException();
}
@Override
public List<String> codeVariants() {
return codeVariants;
}
@Override
public Severity overriddenSeverity() {
return this.overriddenSeverity;
}
@Override
public Double gap() {
return this.gap;
}
@Override
public IssueLocation primaryLocation() {
return primaryLocation;
}
@Override
public void doSave() {
requireNonNull(this.ruleKey, "ruleKey is mandatory on issue");
checkState(primaryLocation != null, "Primary location is mandatory on every issue");
storage.store(this);
}
}
| 4,445 | 27.683871 | 104 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/sensor/issue/internal/DefaultIssueFlow.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.api.batch.sensor.issue.internal;
import java.util.List;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
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;
public class DefaultIssueFlow implements Issue.Flow {
private final List<IssueLocation> locations;
private final FlowType type;
@Nullable
private final String description;
public DefaultIssueFlow(List<IssueLocation> locations, FlowType type, @Nullable String description) {
this.locations = locations;
this.type = type;
this.description = description;
}
@Override
public List<IssueLocation> locations() {
return locations;
}
@Override
public FlowType type() {
return type;
}
@CheckForNull
@Override
public String description() {
return description;
}
}
| 1,765 | 29.982456 | 103 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/sensor/issue/internal/DefaultIssueLocation.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.api.batch.sensor.issue.internal;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.batch.fs.InputComponent;
import org.sonar.api.batch.fs.TextRange;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.sensor.issue.IssueLocation;
import org.sonar.api.batch.sensor.issue.MessageFormatting;
import org.sonar.api.batch.sensor.issue.NewIssueLocation;
import org.sonar.api.batch.sensor.issue.NewMessageFormatting;
import org.sonar.api.issue.Issue;
import static java.util.Objects.requireNonNull;
import static org.apache.commons.lang.StringUtils.abbreviate;
import static org.apache.commons.lang.StringUtils.trim;
import static org.sonar.api.utils.Preconditions.checkArgument;
import static org.sonar.api.utils.Preconditions.checkState;
public class DefaultIssueLocation implements NewIssueLocation, IssueLocation {
private static final String NULL_CHARACTER = "\u0000";
private static final String NULL_REPLACEMENT = "[NULL]";
private InputComponent component;
private TextRange textRange;
private String message;
private final List<MessageFormatting> messageFormattings = new ArrayList<>();
@Override
public DefaultIssueLocation on(InputComponent component) {
checkArgument(component != null, "Component can't be null");
checkState(this.component == null, "on() already called");
this.component = component;
return this;
}
@Override
public DefaultIssueLocation at(TextRange location) {
checkState(this.component != null, "at() should be called after on()");
checkState(this.component.isFile(), "at() should be called only for an InputFile.");
DefaultInputFile file = (DefaultInputFile) this.component;
file.validate(location);
this.textRange = location;
return this;
}
@Override
public DefaultIssueLocation message(String message) {
validateMessage(message);
String sanitizedMessage = sanitizeNulls(message);
this.message = abbreviate(trim(sanitizedMessage), Issue.MESSAGE_MAX_SIZE);
return this;
}
@Override
public DefaultIssueLocation message(String message, List<NewMessageFormatting> newMessageFormattings) {
validateMessage(message);
validateFormattings(newMessageFormattings, message);
String sanitizedMessage = sanitizeNulls(message);
this.message = abbreviate(sanitizedMessage, Issue.MESSAGE_MAX_SIZE);
for (NewMessageFormatting newMessageFormatting : newMessageFormattings) {
DefaultMessageFormatting messageFormatting = (DefaultMessageFormatting) newMessageFormatting;
if (messageFormatting.start() > Issue.MESSAGE_MAX_SIZE) {
continue;
}
if (messageFormatting.end() > Issue.MESSAGE_MAX_SIZE) {
messageFormatting = new DefaultMessageFormatting()
.start(messageFormatting.start())
.end( Issue.MESSAGE_MAX_SIZE)
.type(messageFormatting.type());
}
messageFormattings.add(messageFormatting);
}
return this;
}
private static void validateFormattings(List<NewMessageFormatting> newMessageFormattings, String message) {
checkArgument(newMessageFormattings != null, "messageFormattings can't be null");
newMessageFormattings.stream()
.map(DefaultMessageFormatting.class::cast)
.forEach(e -> e.validate(message));
}
private static void validateMessage(String message) {
requireNonNull(message, "Message can't be null");
}
private static String sanitizeNulls(String message) {
return StringUtils.replace(message, NULL_CHARACTER, NULL_REPLACEMENT);
}
@Override
public NewMessageFormatting newMessageFormatting() {
return new DefaultMessageFormatting();
}
@Override
public InputComponent inputComponent() {
return this.component;
}
@Override
public TextRange textRange() {
return textRange;
}
@Override
public String message() {
return this.message;
}
@Override
public List<MessageFormatting> messageFormattings() {
return this.messageFormattings;
}
}
| 4,917 | 34.128571 | 109 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/sensor/issue/internal/DefaultMessageFormatting.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.api.batch.sensor.issue.internal;
import org.sonar.api.batch.sensor.issue.MessageFormatting;
import org.sonar.api.batch.sensor.issue.NewMessageFormatting;
import static org.sonar.api.utils.Preconditions.checkArgument;
public class DefaultMessageFormatting implements MessageFormatting, NewMessageFormatting {
private int start;
private int end;
private Type type;
@Override
public int start() {
return start;
}
@Override
public int end() {
return end;
}
@Override
public Type type() {
return type;
}
@Override
public DefaultMessageFormatting start(int start) {
this.start = start;
return this;
}
@Override
public DefaultMessageFormatting end(int end) {
this.end = end;
return this;
}
@Override
public DefaultMessageFormatting type(Type type) {
this.type = type;
return this;
}
public void validate(String message) {
checkArgument(this.type() != null, "Message formatting type can't be null");
checkArgument(this.start() >= 0, "Message formatting start must be greater or equals to 0");
checkArgument(this.end() <= message.length(), "Message formatting end must be lesser or equal than message size");
checkArgument(this.end() > this.start(), "Message formatting end must be greater than start");
}
}
| 2,168 | 29.125 | 118 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/sensor/issue/internal/DefaultNoSonarFilter.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.api.batch.sensor.issue.internal;
import java.util.Set;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.issue.NoSonarFilter;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
public class DefaultNoSonarFilter extends NoSonarFilter {
public NoSonarFilter noSonarInFile(InputFile inputFile, Set<Integer> noSonarLines) {
((DefaultInputFile) inputFile).noSonarAt(noSonarLines);
return this;
}
}
| 1,286 | 38 | 86 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/sensor/issue/internal/NoOpNewQuickFix.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.api.batch.sensor.issue.internal;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.TextRange;
import org.sonar.api.batch.sensor.issue.fix.NewInputFileEdit;
import org.sonar.api.batch.sensor.issue.fix.NewQuickFix;
import org.sonar.api.batch.sensor.issue.fix.NewTextEdit;
public class NoOpNewQuickFix implements NewQuickFix {
@Override
public NewQuickFix message(String message) {
return this;
}
@Override
public NewInputFileEdit newInputFileEdit() {
return new NoOpNewInputFileEdit();
}
@Override
public NewQuickFix addInputFileEdit(NewInputFileEdit newInputFileEdit) {
return this;
}
public static class NoOpNewInputFileEdit implements NewInputFileEdit {
@Override
public NewInputFileEdit on(InputFile inputFile) {
return this;
}
@Override
public NewTextEdit newTextEdit() {
return new NoOpNewTextEdit();
}
@Override
public NewInputFileEdit addTextEdit(NewTextEdit newTextEdit) {
return this;
}
}
public static class NoOpNewTextEdit implements NewTextEdit {
@Override
public NewTextEdit at(TextRange range) {
return this;
}
@Override
public NewTextEdit withNewText(String newText) {
return this;
}
}
}
| 2,122 | 27.689189 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/sensor/issue/internal/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.api.batch.sensor.issue.internal;
import javax.annotation.ParametersAreNonnullByDefault;
| 982 | 38.32 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/sensor/measure/internal/DefaultMeasure.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.api.batch.sensor.measure.internal;
import java.io.Serializable;
import javax.annotation.Nullable;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.sonar.api.batch.fs.InputComponent;
import org.sonar.api.batch.measure.Metric;
import org.sonar.api.batch.sensor.internal.DefaultStorable;
import org.sonar.api.batch.sensor.internal.SensorStorage;
import org.sonar.api.batch.sensor.measure.Measure;
import org.sonar.api.batch.sensor.measure.NewMeasure;
import static java.util.Objects.requireNonNull;
import static org.sonar.api.utils.Preconditions.checkArgument;
import static org.sonar.api.utils.Preconditions.checkState;
public class DefaultMeasure<G extends Serializable> extends DefaultStorable implements Measure<G>, NewMeasure<G> {
private InputComponent component;
private Metric<G> metric;
private G value;
private boolean fromCore = false;
public DefaultMeasure() {
super();
}
public DefaultMeasure(@Nullable SensorStorage storage) {
super(storage);
}
@Override
public DefaultMeasure<G> on(InputComponent component) {
checkArgument(component != null, "Component can't be null");
checkState(this.component == null, "on() already called");
this.component = component;
return this;
}
@Override
public DefaultMeasure<G> forMetric(Metric<G> metric) {
checkState(this.metric == null, "Metric already defined");
requireNonNull(metric, "metric should be non null");
this.metric = metric;
return this;
}
@Override
public DefaultMeasure<G> withValue(G value) {
checkState(this.value == null, "Measure value already defined");
requireNonNull(value, "Measure value can't be null");
this.value = value;
return this;
}
/**
* For internal use.
*/
public boolean isFromCore() {
return fromCore;
}
/**
* For internal use. Used by core components to bypass check that prevent a plugin to store core measures.
*/
public DefaultMeasure<G> setFromCore() {
this.fromCore = true;
return this;
}
@Override
public void doSave() {
requireNonNull(this.value, "Measure value can't be null");
requireNonNull(this.metric, "Measure metric can't be null");
checkState(this.metric.valueType().equals(this.value.getClass()), "Measure value should be of type %s", this.metric.valueType());
storage.store(this);
}
@Override
public Metric<G> metric() {
return metric;
}
@Override
public InputComponent inputComponent() {
return component;
}
@Override
public G value() {
return value;
}
// For testing purpose
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (obj.getClass() != getClass()) {
return false;
}
DefaultMeasure<?> rhs = (DefaultMeasure<?>) obj;
return new EqualsBuilder()
.append(component, rhs.component)
.append(metric, rhs.metric)
.append(value, rhs.value)
.isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder(27, 45).append(component).append(metric).append(value).toHashCode();
}
}
| 4,079 | 27.93617 | 133 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/sensor/measure/internal/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.api.batch.sensor.measure.internal;
import javax.annotation.ParametersAreNonnullByDefault;
| 984 | 38.4 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/sensor/rule/internal/DefaultAdHocRule.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.api.batch.sensor.rule.internal;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.api.batch.rule.Severity;
import org.sonar.api.batch.sensor.internal.DefaultStorable;
import org.sonar.api.batch.sensor.internal.SensorStorage;
import org.sonar.api.batch.sensor.rule.AdHocRule;
import org.sonar.api.batch.sensor.rule.NewAdHocRule;
import org.sonar.api.code.CodeCharacteristic;
import org.sonar.api.rules.RuleType;
import static org.apache.commons.lang.StringUtils.isNotBlank;
import static org.sonar.api.utils.Preconditions.checkState;
public class DefaultAdHocRule extends DefaultStorable implements AdHocRule, NewAdHocRule {
private Severity severity;
private RuleType type;
private String name;
private String description;
private String engineId;
private String ruleId;
public DefaultAdHocRule() {
super(null);
}
public DefaultAdHocRule(@Nullable SensorStorage storage) {
super(storage);
}
@Override
public DefaultAdHocRule severity(Severity severity) {
this.severity = severity;
return this;
}
@Override
public String engineId() {
return engineId;
}
@Override
public String ruleId() {
return ruleId;
}
@Override
public String name() {
return name;
}
@CheckForNull
@Override
public String description() {
return description;
}
@Override
public Severity severity() {
return this.severity;
}
@Override
public void doSave() {
checkState(isNotBlank(engineId), "Engine id is mandatory on ad hoc rule");
checkState(isNotBlank(ruleId), "Rule id is mandatory on ad hoc rule");
checkState(isNotBlank(name), "Name is mandatory on every ad hoc rule");
checkState(severity != null, "Severity is mandatory on every ad hoc rule");
checkState(type != null, "Type is mandatory on every ad hoc rule");
storage.store(this);
}
@Override
public RuleType type() {
return type;
}
@CheckForNull
@Override
public CodeCharacteristic characteristic() {
return null;
}
@Override
public DefaultAdHocRule engineId(String engineId) {
this.engineId = engineId;
return this;
}
@Override
public DefaultAdHocRule ruleId(String ruleId) {
this.ruleId = ruleId;
return this;
}
@Override
public DefaultAdHocRule name(String name) {
this.name = name;
return this;
}
@Override
public DefaultAdHocRule description(@Nullable String description) {
this.description = description;
return this;
}
@Override
public DefaultAdHocRule type(RuleType type) {
this.type = type;
return this;
}
@Override
public NewAdHocRule characteristic(CodeCharacteristic characteristic) {
// no op
return this;
}
}
| 3,601 | 24.546099 | 90 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/sensor/rule/internal/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.
*/
@javax.annotation.ParametersAreNonnullByDefault
package org.sonar.api.batch.sensor.rule.internal;
| 941 | 41.818182 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/sensor/symbol/internal/DefaultSymbolTable.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.api.batch.sensor.symbol.internal;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.TextRange;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.sensor.internal.DefaultStorable;
import org.sonar.api.batch.sensor.internal.SensorStorage;
import org.sonar.api.batch.sensor.symbol.NewSymbol;
import org.sonar.api.batch.sensor.symbol.NewSymbolTable;
import static java.util.Objects.requireNonNull;
import static org.sonar.api.utils.Preconditions.checkArgument;
import static org.sonar.api.utils.Preconditions.checkState;
public class DefaultSymbolTable extends DefaultStorable implements NewSymbolTable {
private final Map<TextRange, Set<TextRange>> referencesBySymbol;
private DefaultInputFile inputFile;
public DefaultSymbolTable(SensorStorage storage) {
super(storage);
referencesBySymbol = new LinkedHashMap<>();
}
public Map<TextRange, Set<TextRange>> getReferencesBySymbol() {
return referencesBySymbol;
}
@Override
public DefaultSymbolTable onFile(InputFile inputFile) {
requireNonNull(inputFile, "file can't be null");
this.inputFile = (DefaultInputFile) inputFile;
return this;
}
public InputFile inputFile() {
return inputFile;
}
@Override
public NewSymbol newSymbol(int startLine, int startLineOffset, int endLine, int endLineOffset) {
checkInputFileNotNull();
TextRange declarationRange;
try {
declarationRange = inputFile.newRange(startLine, startLineOffset, endLine, endLineOffset);
} catch (Exception e) {
throw new IllegalArgumentException("Unable to create symbol on file " + inputFile, e);
}
return newSymbol(declarationRange);
}
@Override
public NewSymbol newSymbol(TextRange range) {
checkInputFileNotNull();
TreeSet<TextRange> references = new TreeSet<>((o1, o2) -> o1.start().compareTo(o2.start()));
referencesBySymbol.put(range, references);
return new DefaultSymbol(inputFile, range, references);
}
private static class DefaultSymbol implements NewSymbol {
private final Collection<TextRange> references;
private final DefaultInputFile inputFile;
private final TextRange declaration;
public DefaultSymbol(DefaultInputFile inputFile, TextRange declaration, Collection<TextRange> references) {
this.inputFile = inputFile;
this.declaration = declaration;
this.references = references;
}
@Override
public NewSymbol newReference(int startLine, int startLineOffset, int endLine, int endLineOffset) {
TextRange referenceRange;
try {
referenceRange = inputFile.newRange(startLine, startLineOffset, endLine, endLineOffset);
} catch (Exception e) {
throw new IllegalArgumentException("Unable to create symbol reference on file " + inputFile, e);
}
return newReference(referenceRange);
}
@Override
public NewSymbol newReference(TextRange range) {
requireNonNull(range, "Provided range is null");
checkArgument(!declaration.overlap(range), "Overlapping symbol declaration and reference for symbol at %s", declaration);
references.add(range);
return this;
}
}
@Override
protected void doSave() {
checkInputFileNotNull();
storage.store(this);
}
private void checkInputFileNotNull() {
checkState(inputFile != null, "Call onFile() first");
}
}
| 4,384 | 33.527559 | 127 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/batch/sensor/symbol/internal/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.
*/
@javax.annotation.ParametersAreNonnullByDefault
package org.sonar.api.batch.sensor.symbol.internal;
| 943 | 41.909091 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/config/internal/AesCipher.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.api.config.internal;
import java.io.File;
import java.io.IOException;
import java.security.Key;
import java.security.SecureRandom;
import javax.annotation.Nullable;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.sonar.api.CoreProperties.ENCRYPTION_SECRET_KEY_PATH;
abstract class AesCipher implements Cipher {
static final int KEY_SIZE_IN_BITS = 256;
private static final String CRYPTO_KEY = "AES";
private String pathToSecretKey;
AesCipher(@Nullable String pathToSecretKey) {
this.pathToSecretKey = pathToSecretKey;
}
/**
* This method checks the existence of the file, but not the validity of the contained key.
*/
boolean hasSecretKey() {
String path = getPathToSecretKey();
if (StringUtils.isNotBlank(path)) {
File file = new File(path);
return file.exists() && file.isFile();
}
return false;
}
protected Key loadSecretFile() throws IOException {
String path = getPathToSecretKey();
return loadSecretFileFromFile(path);
}
Key loadSecretFileFromFile(@Nullable String path) throws IOException {
if (StringUtils.isBlank(path)) {
throw new IllegalStateException("Secret key not found. Please set the property " + ENCRYPTION_SECRET_KEY_PATH);
}
File file = new File(path);
if (!file.exists() || !file.isFile()) {
throw new IllegalStateException("The property " + ENCRYPTION_SECRET_KEY_PATH + " does not link to a valid file: " + path);
}
String s = FileUtils.readFileToString(file, UTF_8);
if (StringUtils.isBlank(s)) {
throw new IllegalStateException("No secret key in the file: " + path);
}
return new SecretKeySpec(Base64.decodeBase64(StringUtils.trim(s)), CRYPTO_KEY);
}
String generateRandomSecretKey() {
try {
KeyGenerator keyGen = KeyGenerator.getInstance(CRYPTO_KEY);
keyGen.init(KEY_SIZE_IN_BITS, new SecureRandom());
SecretKey secretKey = keyGen.generateKey();
return Base64.encodeBase64String(secretKey.getEncoded());
} catch (Exception e) {
throw new IllegalStateException("Fail to generate secret key", e);
}
}
String getPathToSecretKey() {
if (StringUtils.isBlank(pathToSecretKey)) {
pathToSecretKey = new File(FileUtils.getUserDirectoryPath(), ".sonar/sonar-secret.txt").getPath();
}
return pathToSecretKey;
}
public void setPathToSecretKey(@Nullable String pathToSecretKey) {
this.pathToSecretKey = pathToSecretKey;
}
}
| 3,571 | 33.679612 | 128 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/config/internal/AesECBCipher.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.api.config.internal;
import java.nio.charset.StandardCharsets;
import javax.annotation.Nullable;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
/**
* @deprecated since 8.7.0
*/
@Deprecated
final class AesECBCipher extends AesCipher {
private static final String CRYPTO_ALGO = "AES";
AesECBCipher(@Nullable String pathToSecretKey) {
super(pathToSecretKey);
}
@Override
public String encrypt(String clearText) {
try {
javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance(CRYPTO_ALGO);
cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, loadSecretFile());
byte[] cipherData = cipher.doFinal(clearText.getBytes(StandardCharsets.UTF_8.name()));
return Base64.encodeBase64String(cipherData);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
@Override
public String decrypt(String encryptedText) {
try {
javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance(CRYPTO_ALGO);
cipher.init(javax.crypto.Cipher.DECRYPT_MODE, loadSecretFile());
byte[] cipherData = cipher.doFinal(Base64.decodeBase64(StringUtils.trim(encryptedText)));
return new String(cipherData, StandardCharsets.UTF_8);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
}
| 2,286 | 32.632353 | 95 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/config/internal/AesGCMCipher.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.api.config.internal;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import javax.annotation.Nullable;
import javax.crypto.spec.GCMParameterSpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
final class AesGCMCipher extends AesCipher {
private static final int GCM_TAG_LENGTH_IN_BITS = 128;
private static final int GCM_IV_LENGTH_IN_BYTES = 12;
private static final String CRYPTO_ALGO = "AES/GCM/NoPadding";
AesGCMCipher(@Nullable String pathToSecretKey) {
super(pathToSecretKey);
}
@Override
public String encrypt(String clearText) {
try {
javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance(CRYPTO_ALGO);
byte[] iv = new byte[GCM_IV_LENGTH_IN_BYTES];
new SecureRandom().nextBytes(iv);
cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, loadSecretFile(), new GCMParameterSpec(GCM_TAG_LENGTH_IN_BITS, iv));
byte[] encryptedText = cipher.doFinal(clearText.getBytes(StandardCharsets.UTF_8.name()));
return Base64.encodeBase64String(
ByteBuffer.allocate(GCM_IV_LENGTH_IN_BYTES + encryptedText.length)
.put(iv)
.put(encryptedText)
.array());
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
@Override
public String decrypt(String encryptedText) {
try {
javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance(CRYPTO_ALGO);
ByteBuffer byteBuffer = ByteBuffer.wrap(Base64.decodeBase64(StringUtils.trim(encryptedText)));
byte[] iv = new byte[GCM_IV_LENGTH_IN_BYTES];
byteBuffer.get(iv);
byte[] cipherText = new byte[byteBuffer.remaining()];
byteBuffer.get(cipherText);
cipher.init(javax.crypto.Cipher.DECRYPT_MODE, loadSecretFile(), new GCMParameterSpec(GCM_TAG_LENGTH_IN_BITS, iv));
byte[] cipherData = cipher.doFinal(cipherText);
return new String(cipherData, StandardCharsets.UTF_8);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
}
| 3,031 | 36.9 | 120 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/config/internal/Base64Cipher.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.api.config.internal;
import org.apache.commons.codec.binary.Base64;
import java.nio.charset.StandardCharsets;
final class Base64Cipher implements Cipher {
@Override
public String encrypt(String clearText) {
return Base64.encodeBase64String(clearText.getBytes(StandardCharsets.UTF_8));
}
@Override
public String decrypt(String encryptedText) {
return new String(Base64.decodeBase64(encryptedText), StandardCharsets.UTF_8);
}
}
| 1,311 | 34.459459 | 82 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/config/internal/Cipher.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.api.config.internal;
interface Cipher {
String encrypt(String clearText);
String decrypt(String encryptedText);
}
| 980 | 36.730769 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/config/internal/ConfigurationBridge.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.api.config.internal;
import java.util.Optional;
import org.sonar.api.config.Configuration;
/**
* Used to help migration from {@link Settings} to {@link Configuration}
*/
public class ConfigurationBridge implements Configuration {
private final Settings settings;
public ConfigurationBridge(Settings settings) {
this.settings = settings;
}
@Override
public Optional<String> get(String key) {
return Optional.ofNullable(settings.getString(key));
}
@Override
public boolean hasKey(String key) {
return settings.hasKey(key);
}
@Override
public String[] getStringArray(String key) {
return settings.getStringArray(key);
}
}
| 1,530 | 28.442308 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/config/internal/Encryption.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.api.config.internal;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
/**
* @since 3.0
*/
public final class Encryption {
private static final Pattern ENCRYPTED_PATTERN = Pattern.compile("^\\{([^{^}]*)}(.*)$");
private static final String BASE64_ALGORITHM = "b64";
private static final String AES_ECB_ALGORITHM = "aes";
private static final String AES_GCM_ALGORITHM = "aes-gcm";
private final AesECBCipher aesECBCipher;
private final AesGCMCipher aesGCMCipher;
private final Map<String, Cipher> ciphers;
public Encryption(@Nullable String pathToSecretKey) {
aesECBCipher = new AesECBCipher(pathToSecretKey);
aesGCMCipher = new AesGCMCipher(pathToSecretKey);
ciphers = new HashMap<>();
ciphers.put(BASE64_ALGORITHM, new Base64Cipher());
ciphers.put(AES_ECB_ALGORITHM, aesECBCipher);
ciphers.put(AES_GCM_ALGORITHM, aesGCMCipher);
}
public void setPathToSecretKey(@Nullable String pathToSecretKey) {
aesECBCipher.setPathToSecretKey(pathToSecretKey);
aesGCMCipher.setPathToSecretKey(pathToSecretKey);
}
/**
* Checks the availability of the secret key, that is required to encrypt and decrypt.
*/
public boolean hasSecretKey() {
return aesGCMCipher.hasSecretKey();
}
public boolean isEncrypted(String value) {
return value.indexOf('{') == 0 && value.indexOf('}') > 1;
}
public String encrypt(String clearText) {
return encrypt(AES_GCM_ALGORITHM, clearText);
}
public String scramble(String clearText) {
return encrypt(BASE64_ALGORITHM, clearText);
}
public String generateRandomSecretKey() {
return aesGCMCipher.generateRandomSecretKey();
}
public String decrypt(String encryptedText) {
Matcher matcher = ENCRYPTED_PATTERN.matcher(encryptedText);
if (matcher.matches()) {
Cipher cipher = ciphers.get(matcher.group(1).toLowerCase(Locale.ENGLISH));
if (cipher != null) {
return cipher.decrypt(matcher.group(2));
}
}
return encryptedText;
}
private String encrypt(String algorithm, String clearText) {
Cipher cipher = ciphers.get(algorithm);
if (cipher == null) {
throw new IllegalArgumentException("Unknown cipher algorithm: " + algorithm);
}
return String.format("{%s}%s", algorithm, cipher.encrypt(clearText));
}
}
| 3,283 | 31.84 | 90 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/config/internal/MapSettings.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.api.config.internal;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.sonar.api.config.Configuration;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.utils.System2;
import static java.util.Collections.unmodifiableMap;
import static java.util.Objects.requireNonNull;
/**
* In-memory map-based implementation of {@link Settings}. It must be used
* <b>only for unit tests</b>. This is not the implementation
* deployed at runtime, so non-test code must never cast
* {@link Settings} to {@link MapSettings}.
*
* @since 6.1
*/
public class MapSettings extends Settings {
private final Map<String, String> props = new HashMap<>();
private final ConfigurationBridge configurationBridge;
public MapSettings() {
this(new PropertyDefinitions(System2.INSTANCE));
}
public MapSettings(PropertyDefinitions definitions) {
super(definitions, new Encryption(null));
configurationBridge = new ConfigurationBridge(this);
}
@Override
protected Optional<String> get(String key) {
return Optional.ofNullable(props.get(key));
}
@Override
protected void set(String key, String value) {
props.put(
requireNonNull(key, "key can't be null"),
requireNonNull(value, "value can't be null").trim());
}
@Override
protected void remove(String key) {
props.remove(key);
}
@Override
public Map<String, String> getProperties() {
return unmodifiableMap(props);
}
/**
* Delete all properties
*/
public MapSettings clear() {
props.clear();
return this;
}
@Override
public MapSettings setProperty(String key, String value) {
return (MapSettings) super.setProperty(key, value);
}
@Override
public MapSettings setProperty(String key, Integer value) {
return (MapSettings) super.setProperty(key, value);
}
@Override
public MapSettings setProperty(String key, Boolean value) {
return (MapSettings) super.setProperty(key, value);
}
@Override
public MapSettings setProperty(String key, Long value) {
return (MapSettings) super.setProperty(key, value);
}
/**
* @return a {@link Configuration} proxy on top of this existing {@link Settings} implementation. Changes are reflected in the {@link Configuration} object.
* @since 6.5
*/
public Configuration asConfig() {
return configurationBridge;
}
}
| 3,249 | 28.017857 | 158 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/config/internal/MultivalueProperty.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.api.config.internal;
import java.io.IOException;
import java.io.StringReader;
import java.io.UncheckedIOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;
import java.util.function.UnaryOperator;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.lang.ArrayUtils;
import static java.util.function.UnaryOperator.identity;
public class MultivalueProperty {
private MultivalueProperty() {
// prevents instantiation
}
public static String[] parseAsCsv(String key, String value) {
return parseAsCsv(key, value, identity());
}
public static String[] parseAsCsv(String key, String value, UnaryOperator<String> valueProcessor) {
String cleanValue = MultivalueProperty.trimFieldsAndRemoveEmptyFields(value);
List<String> result = new ArrayList<>();
try (CSVParser csvParser = CSVFormat.RFC4180.builder()
.setSkipHeaderRecord(true)
.setIgnoreEmptyLines(true)
.setIgnoreSurroundingSpaces(true)
.build()
.parse(new StringReader(cleanValue))) {
List<CSVRecord> records = csvParser.getRecords();
if (records.isEmpty()) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
processRecords(result, records, valueProcessor);
return result.toArray(new String[result.size()]);
} catch (IOException | UncheckedIOException e) {
throw new IllegalStateException("Property: '" + key + "' doesn't contain a valid CSV value: '" + value + "'", e);
}
}
/**
* In most cases we expect a single record. <br>Having multiple records means the input value was splitted over multiple lines (this is common in Maven).
* For example:
* <pre>
* <sonar.exclusions>
* src/foo,
* src/bar,
* src/biz
* <sonar.exclusions>
* </pre>
* In this case records will be merged to form a single list of items. Last item of a record is appended to first item of next record.
* <p>
* This is a very curious case, but we try to preserve line break in the middle of an item:
* <pre>
* <sonar.exclusions>
* a
* b,
* c
* <sonar.exclusions>
* </pre>
* will produce ['a\nb', 'c']
*/
private static void processRecords(List<String> result, List<CSVRecord> records, Function<String, String> valueProcessor) {
for (CSVRecord csvRecord : records) {
Iterator<String> it = csvRecord.iterator();
if (!result.isEmpty()) {
String next = it.next();
if (!next.isEmpty()) {
int lastItemIdx = result.size() - 1;
String previous = result.get(lastItemIdx);
if (previous.isEmpty()) {
result.set(lastItemIdx, valueProcessor.apply(next));
} else {
result.set(lastItemIdx, valueProcessor.apply(previous + "\n" + next));
}
}
}
it.forEachRemaining(s -> {
String apply = valueProcessor.apply(s);
result.add(apply);
});
}
}
/**
* Removes the empty fields from the value of a multi-value property from empty fields, including trimming each field.
* <p>
* Quotes can be used to prevent an empty field to be removed (as it is used to preserve empty spaces).
* <ul>
* <li>{@code "" => ""}</li>
* <li>{@code " " => ""}</li>
* <li>{@code "," => ""}</li>
* <li>{@code ",," => ""}</li>
* <li>{@code ",,," => ""}</li>
* <li>{@code ",a" => "a"}</li>
* <li>{@code "a," => "a"}</li>
* <li>{@code ",a," => "a"}</li>
* <li>{@code "a,,b" => "a,b"}</li>
* <li>{@code "a, ,b" => "a,b"}</li>
* <li>{@code "a,\"\",b" => "a,b"}</li>
* <li>{@code "\"a\",\"b\"" => "\"a\",\"b\""}</li>
* <li>{@code "\" a \",\"b \"" => "\" a \",\"b \""}</li>
* <li>{@code "\"a\",\"\",\"b\"" => "\"a\",\"\",\"b\""}</li>
* <li>{@code "\"a\",\" \",\"b\"" => "\"a\",\" \",\"b\""}</li>
* <li>{@code "\" a,,b,c \",\"d \"" => "\" a,,b,c \",\"d \""}</li>
* <li>{@code "a,\" \",b" => "ab"]}</li>
* </ul>
*/
static String trimFieldsAndRemoveEmptyFields(String str) {
char[] chars = str.toCharArray();
char[] res = new char[chars.length];
/*
* set when reading the first non trimmable char after a separator char (or the beginning of the string)
* unset when reading a separator
*/
boolean inField = false;
boolean inQuotes = false;
int i = 0;
int resI = 0;
for (; i < chars.length; i++) {
boolean isSeparator = chars[i] == ',';
if (!inQuotes && isSeparator) {
// exiting field (may already be unset)
inField = false;
if (resI > 0) {
resI = retroTrim(res, resI);
}
} else {
boolean isTrimmed = !inQuotes && istrimmable(chars[i]);
if (isTrimmed && !inField) {
// we haven't meet any non trimmable char since the last separator yet
continue;
}
boolean isEscape = isEscapeChar(chars[i]);
if (isEscape) {
inQuotes = !inQuotes;
}
// add separator as we already had one field
if (!inField && resI > 0) {
res[resI] = ',';
resI++;
}
// register in field (may already be set)
inField = true;
// copy current char
res[resI] = chars[i];
resI++;
}
}
// inQuotes can only be true at this point if quotes are unbalanced
if (!inQuotes) {
// trim end of str
resI = retroTrim(res, resI);
}
return new String(res, 0, resI);
}
private static boolean isEscapeChar(char aChar) {
return aChar == '"';
}
private static boolean istrimmable(char aChar) {
return aChar <= ' ';
}
/**
* Reads from index {@code resI} to the beginning into {@code res} looking up the location of the trimmable char with
* the lowest index before encountering a non-trimmable char.
* <p>
* This basically trims {@code res} from any trimmable char at its end.
*
* @return index of next location to put new char in res
*/
private static int retroTrim(char[] res, int resI) {
int i = resI;
while (i >= 1) {
if (!istrimmable(res[i - 1])) {
return i;
}
i--;
}
return i;
}
}
| 7,253 | 32.897196 | 155 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/config/internal/Settings.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.api.config.internal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.stream.Collectors;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.config.PropertyDefinition;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.utils.DateUtils;
import static java.util.Objects.requireNonNull;
import static org.apache.commons.lang.StringUtils.trim;
/**
* Implementation of the deprecated Settings interface
*/
public abstract class Settings extends org.sonar.api.config.Settings {
private final PropertyDefinitions definitions;
private final Encryption encryption;
protected Settings(PropertyDefinitions definitions, Encryption encryption) {
this.definitions = requireNonNull(definitions);
this.encryption = requireNonNull(encryption);
}
protected abstract Optional<String> get(String key);
/**
* Add the settings with the specified key and value, both are trimmed and neither can be null.
*
* @throws NullPointerException if {@code key} and/or {@code value} is {@code null}.
*/
protected abstract void set(String key, String value);
protected abstract void remove(String key);
/**
* Immutable map of the properties that have non-default values.
* The default values defined by {@link PropertyDefinitions} are ignored,
* so the returned values are not the effective values. Basically only
* the non-empty results of {@link #getRawString(String)} are returned.
* <p>
* Values are not decrypted if they are encrypted with a secret key.
* </p>
*/
public abstract Map<String, String> getProperties();
public Encryption getEncryption() {
return encryption;
}
/**
* The value that overrides the default value. It
* may be encrypted with a secret key. Use {@link #getString(String)} to get
* the effective and decrypted value.
*
* @since 6.1
*/
public Optional<String> getRawString(String key) {
return get(definitions.validKey(requireNonNull(key)));
}
/**
* All the property definitions declared by core and plugins.
*/
public PropertyDefinitions getDefinitions() {
return definitions;
}
/**
* The definition related to the specified property. It may
* be empty.
*
* @since 6.1
*/
public Optional<PropertyDefinition> getDefinition(String key) {
return Optional.ofNullable(definitions.get(key));
}
/**
* @return {@code true} if the property has a non-default value, else {@code false}.
*/
@Override
public boolean hasKey(String key) {
return getRawString(key).isPresent();
}
@CheckForNull
public String getDefaultValue(String key) {
return definitions.getDefaultValue(key);
}
public boolean hasDefaultValue(String key) {
return StringUtils.isNotEmpty(getDefaultValue(key));
}
/**
* The effective value of the specified property. Can return
* {@code null} if the property is not set and has no
* defined default value.
* <p>
* If the property is encrypted with a secret key,
* then the returned value is decrypted.
* </p>
*
* @throws IllegalStateException if value is encrypted but fails to be decrypted.
*/
@CheckForNull
@Override
public String getString(String key) {
String effectiveKey = definitions.validKey(key);
Optional<String> value = getRawString(effectiveKey);
if (!value.isPresent()) {
// default values cannot be encrypted, so return value as-is.
return getDefaultValue(effectiveKey);
}
if (encryption.isEncrypted(value.get())) {
try {
return encryption.decrypt(value.get());
} catch (Exception e) {
throw new IllegalStateException("Fail to decrypt the property " + effectiveKey + ". Please check your secret key.", e);
}
}
return value.get();
}
/**
* Effective value as boolean. It is {@code false} if {@link #getString(String)}
* does not return {@code "true"}, even if it's not a boolean representation.
*
* @return {@code true} if the effective value is {@code "true"}, else {@code false}.
*/
@Override
public boolean getBoolean(String key) {
String value = getString(key);
return StringUtils.isNotEmpty(value) && Boolean.parseBoolean(value);
}
/**
* Effective value as {@code int}.
*
* @return the value as {@code int}. If the property does not have value nor default value, then {@code 0} is returned.
* @throws NumberFormatException if value is not empty and is not a parsable integer
*/
@Override
public int getInt(String key) {
String value = getString(key);
if (StringUtils.isNotEmpty(value)) {
return Integer.parseInt(value);
}
return 0;
}
/**
* Effective value as {@code long}.
*
* @return the value as {@code long}. If the property does not have value nor default value, then {@code 0L} is returned.
* @throws NumberFormatException if value is not empty and is not a parsable {@code long}
*/
@Override
public long getLong(String key) {
String value = getString(key);
if (StringUtils.isNotEmpty(value)) {
return Long.parseLong(value);
}
return 0L;
}
/**
* Effective value as {@link Date}, without time fields. Format is {@link DateUtils#DATE_FORMAT}.
*
* @return the value as a {@link Date}. If the property does not have value nor default value, then {@code null} is returned.
* @throws RuntimeException if value is not empty and is not in accordance with {@link DateUtils#DATE_FORMAT}.
*/
@CheckForNull
@Override
public Date getDate(String key) {
String value = getString(key);
if (StringUtils.isNotEmpty(value)) {
return DateUtils.parseDate(value);
}
return null;
}
/**
* Effective value as {@link Date}, with time fields. Format is {@link DateUtils#DATETIME_FORMAT}.
*
* @return the value as a {@link Date}. If the property does not have value nor default value, then {@code null} is returned.
* @throws RuntimeException if value is not empty and is not in accordance with {@link DateUtils#DATETIME_FORMAT}.
*/
@CheckForNull
@Override
public Date getDateTime(String key) {
String value = getString(key);
if (StringUtils.isNotEmpty(value)) {
return DateUtils.parseDateTime(value);
}
return null;
}
/**
* Effective value as {@code Float}.
*
* @return the value as {@code Float}. If the property does not have value nor default value, then {@code null} is returned.
* @throws NumberFormatException if value is not empty and is not a parsable number
*/
@CheckForNull
@Override
public Float getFloat(String key) {
String value = getString(key);
if (StringUtils.isNotEmpty(value)) {
try {
return Float.valueOf(value);
} catch (NumberFormatException e) {
throw new IllegalStateException(String.format("The property '%s' is not a float value", key));
}
}
return null;
}
/**
* Effective value as {@code Double}.
*
* @return the value as {@code Double}. If the property does not have value nor default value, then {@code null} is returned.
* @throws NumberFormatException if value is not empty and is not a parsable number
*/
@CheckForNull
@Override
public Double getDouble(String key) {
String value = getString(key);
if (StringUtils.isNotEmpty(value)) {
try {
return Double.valueOf(value);
} catch (NumberFormatException e) {
throw new IllegalStateException(String.format("The property '%s' is not a double value", key));
}
}
return null;
}
/**
* Value is split by comma and trimmed. Never returns null.
* <br>
* Examples :
* <ul>
* <li>"one,two,three " -> ["one", "two", "three"]</li>
* <li>" one, two, three " -> ["one", "two", "three"]</li>
* <li>"one, , three" -> ["one", "", "three"]</li>
* </ul>
*/
@Override
public String[] getStringArray(String key) {
String effectiveKey = definitions.validKey(key);
Optional<PropertyDefinition> def = getDefinition(effectiveKey);
if ((def.isPresent()) && (def.get().multiValues())) {
String value = getString(key);
if (value == null) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
return Arrays.stream(value.split(",", -1)).map(String::trim)
.map(s -> s.replace("%2C", ","))
.toArray(String[]::new);
}
return getStringArrayBySeparator(key, ",");
}
/**
* Value is split by carriage returns.
*
* @return non-null array of lines. The line termination characters are excluded.
* @since 3.2
*/
@Override
public String[] getStringLines(String key) {
String value = getString(key);
if (StringUtils.isEmpty(value)) {
return new String[0];
}
return value.split("\r?\n|\r", -1);
}
/**
* Value is split and trimmed.
*/
@Override
public String[] getStringArrayBySeparator(String key, String separator) {
String value = getString(key);
if (value != null) {
String[] strings = StringUtils.splitByWholeSeparator(value, separator);
String[] result = new String[strings.length];
for (int index = 0; index < strings.length; index++) {
result[index] = trim(strings[index]);
}
return result;
}
return ArrayUtils.EMPTY_STRING_ARRAY;
}
public Settings appendProperty(String key, @Nullable String value) {
Optional<String> existingValue = getRawString(definitions.validKey(key));
String newValue;
if (!existingValue.isPresent()) {
newValue = trim(value);
} else {
newValue = existingValue.get() + "," + trim(value);
}
return setProperty(key, newValue);
}
public Settings setProperty(String key, @Nullable String[] values) {
requireNonNull(key, "key can't be null");
String effectiveKey = key.trim();
Optional<PropertyDefinition> def = getDefinition(effectiveKey);
if (!def.isPresent() || (!def.get().multiValues())) {
throw new IllegalStateException("Fail to set multiple values on a single value property " + key);
}
String text = null;
if (values != null) {
List<String> escaped = new ArrayList<>();
for (String value : values) {
if (null != value) {
escaped.add(value.replace(",", "%2C"));
} else {
escaped.add("");
}
}
String escapedValue = escaped.stream().collect(Collectors.joining(","));
text = trim(escapedValue);
}
return setProperty(key, text);
}
/**
* Change a property value in a restricted scope only, depending on execution context. New value
* is <b>never</b> persisted. New value is ephemeral and kept in memory only:
* <ul>
* <li>during current analysis in the case of scanner stack</li>
* <li>during processing of current HTTP request in the case of web server stack</li>
* <li>during execution of current task in the case of Compute Engine stack</li>
* </ul>
* Property is temporarily removed if the parameter {@code value} is {@code null}
*/
public Settings setProperty(String key, @Nullable String value) {
String validKey = definitions.validKey(key);
if (value == null) {
removeProperty(validKey);
} else {
set(validKey, trim(value));
}
return this;
}
/**
* @see #setProperty(String, String)
*/
public Settings setProperty(String key, @Nullable Boolean value) {
return setProperty(key, value == null ? null : String.valueOf(value));
}
/**
* @see #setProperty(String, String)
*/
public Settings setProperty(String key, @Nullable Integer value) {
return setProperty(key, value == null ? null : String.valueOf(value));
}
/**
* @see #setProperty(String, String)
*/
public Settings setProperty(String key, @Nullable Long value) {
return setProperty(key, value == null ? null : String.valueOf(value));
}
/**
* @see #setProperty(String, String)
*/
public Settings setProperty(String key, @Nullable Double value) {
return setProperty(key, value == null ? null : String.valueOf(value));
}
/**
* @see #setProperty(String, String)
*/
public Settings setProperty(String key, @Nullable Float value) {
return setProperty(key, value == null ? null : String.valueOf(value));
}
/**
* @see #setProperty(String, String)
*/
public Settings setProperty(String key, @Nullable Date date) {
return setProperty(key, date, false);
}
public Settings addProperties(Map<String, String> props) {
for (Map.Entry<String, String> entry : props.entrySet()) {
setProperty(entry.getKey(), entry.getValue());
}
return this;
}
public Settings addProperties(Properties props) {
for (Map.Entry<Object, Object> entry : props.entrySet()) {
setProperty(entry.getKey().toString(), entry.getValue().toString());
}
return this;
}
/**
* @see #setProperty(String, String)
*/
public Settings setProperty(String key, @Nullable Date date, boolean includeTime) {
if (date == null) {
return removeProperty(key);
}
return setProperty(key, includeTime ? DateUtils.formatDateTime(date) : DateUtils.formatDate(date));
}
public Settings removeProperty(String key) {
remove(key);
return this;
}
@Override
public List<String> getKeysStartingWith(String prefix) {
return getProperties().keySet().stream()
.filter(key -> StringUtils.startsWith(key, prefix))
.collect(Collectors.toList());
}
}
| 14,585 | 30.435345 | 127 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/config/internal/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.api.config.internal;
import javax.annotation.ParametersAreNonnullByDefault;
| 969 | 39.416667 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/impl/server/RulesDefinitionContext.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.api.impl.server;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.server.rule.RulesDefinition;
import org.sonar.api.server.rule.internal.DefaultNewRepository;
import org.sonar.api.server.rule.internal.DefaultRepository;
import static java.util.Collections.unmodifiableList;
import static org.sonar.api.utils.Preconditions.checkState;
public class RulesDefinitionContext extends RulesDefinition.Context {
private final Map<String, RulesDefinition.Repository> repositoriesByKey = new HashMap<>();
private String currentPluginKey = null;
@Override
public RulesDefinition.NewRepository createRepository(String key, String language) {
return new DefaultNewRepository(this, key, language, false);
}
@Override
public RulesDefinition.NewRepository createExternalRepository(String engineId, String language) {
return new DefaultNewRepository(this, RuleKey.EXTERNAL_RULE_REPO_PREFIX + engineId, language, true);
}
@Override
@CheckForNull
public RulesDefinition.Repository repository(String key) {
return repositoriesByKey.get(key);
}
@Override
public List<RulesDefinition.Repository> repositories() {
return unmodifiableList(new ArrayList<>(repositoriesByKey.values()));
}
@Override
public void registerRepository(DefaultNewRepository newRepository) {
RulesDefinition.Repository existing = repositoriesByKey.get(newRepository.key());
if (existing != null) {
String existingLanguage = existing.language();
checkState(existingLanguage.equals(newRepository.language()),
"The rule repository '%s' must not be defined for two different languages: %s and %s",
newRepository.key(), existingLanguage, newRepository.language());
}
repositoriesByKey.put(newRepository.key(), new DefaultRepository(newRepository, existing));
}
@Override
public String currentPluginKey() {
return currentPluginKey;
}
@Override
public void setCurrentPluginKey(@Nullable String pluginKey) {
this.currentPluginKey = pluginKey;
}
}
| 3,054 | 35.807229 | 104 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/impl/server/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.api.impl.server;
import javax.annotation.ParametersAreNonnullByDefault;
| 966 | 37.68 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/impl/utils/AlwaysIncreasingSystem2.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.api.impl.utils;
import java.security.SecureRandom;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.LongSupplier;
import org.sonar.api.utils.System2;
import static org.sonar.api.utils.Preconditions.checkArgument;
/**
* A subclass of {@link System2} which implementation of {@link System2#now()} always return a bigger value than the
* previous returned value.
* <p>
* This class is intended to be used in Unit tests.
* </p>
*/
public class AlwaysIncreasingSystem2 extends System2 {
private static final SecureRandom rnd = new SecureRandom();
private final AtomicLong now;
private final long increment;
private AlwaysIncreasingSystem2(LongSupplier initialValueSupplier, long increment) {
checkArgument(increment > 0, "increment must be > 0");
long initialValue = initialValueSupplier.getAsLong();
checkArgument(initialValue >= 0, "Initial value must be >= 0");
this.now = new AtomicLong(initialValue);
this.increment = increment;
}
public AlwaysIncreasingSystem2(long increment) {
this(AlwaysIncreasingSystem2::randomInitialValue, increment);
}
public AlwaysIncreasingSystem2(long initialValue, int increment) {
this(() -> initialValue, increment);
}
/**
* Values returned by {@link #now()} will start with a random value and increment by 100.
*/
public AlwaysIncreasingSystem2() {
this(AlwaysIncreasingSystem2::randomInitialValue, 100);
}
@Override
public long now() {
return now.getAndAdd(increment);
}
private static long randomInitialValue() {
return Math.abs(rnd.nextInt(2_000_000));
}
}
| 2,472 | 32.876712 | 116 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/impl/utils/DefaultTempFolder.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.api.impl.utils;
import java.nio.file.FileVisitResult;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import org.apache.commons.io.FileUtils;
import org.sonar.api.Startable;
import org.sonar.api.utils.TempFolder;
import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DefaultTempFolder implements TempFolder, Startable {
private static final Logger LOG = LoggerFactory.getLogger(DefaultTempFolder.class);
private final File tempDir;
private final boolean deleteOnExit;
public DefaultTempFolder(File tempDir) {
this(tempDir, false);
}
public DefaultTempFolder(File tempDir, boolean deleteOnExit) {
this.tempDir = tempDir;
this.deleteOnExit = deleteOnExit;
}
@Override
public File newDir() {
return createTempDir(tempDir.toPath()).toFile();
}
private static Path createTempDir(Path baseDir) {
try {
return Files.createTempDirectory(baseDir, null);
} catch (IOException e) {
throw new IllegalStateException("Failed to create temp directory", e);
}
}
@Override
public File newDir(String name) {
File dir = new File(tempDir, name);
try {
FileUtils.forceMkdir(dir);
} catch (IOException e) {
throw new IllegalStateException("Failed to create temp directory - " + dir, e);
}
return dir;
}
@Override
public File newFile() {
return newFile(null, null);
}
@Override
public File newFile(@Nullable String prefix, @Nullable String suffix) {
return createTempFile(tempDir.toPath(), prefix, suffix).toFile();
}
private static Path createTempFile(Path baseDir, String prefix, String suffix) {
try {
return Files.createTempFile(baseDir, prefix, suffix);
} catch (IOException e) {
throw new IllegalStateException("Failed to create temp file", e);
}
}
public void clean() {
try {
if (tempDir.exists()) {
Files.walkFileTree(tempDir.toPath(), DeleteRecursivelyFileVisitor.INSTANCE);
}
} catch (IOException e) {
LOG.error("Failed to delete temp folder", e);
}
}
@Override
public void start() {
// nothing to do
}
@Override
public void stop() {
if (deleteOnExit) {
clean();
}
}
private static final class DeleteRecursivelyFileVisitor extends SimpleFileVisitor<Path> {
public static final DeleteRecursivelyFileVisitor INSTANCE = new DeleteRecursivelyFileVisitor();
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.deleteIfExists(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.deleteIfExists(dir);
return FileVisitResult.CONTINUE;
}
}
}
| 3,828 | 27.574627 | 99 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/impl/utils/JUnitTempFolder.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.api.impl.utils;
import java.io.File;
import java.io.IOException;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
import org.junit.rules.ExternalResource;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.sonar.api.utils.TempFolder;
/**
* Implementation of {@link org.sonar.api.utils.TempFolder} to be used
* only in JUnit tests. It wraps {@link org.junit.rules.TemporaryFolder}.
* <br>
* Example:
* <pre>
* public class MyTest {
* @@org.junit.Rule
* public JUnitTempFolder temp = new JUnitTempFolder();
*
* @@org.junit.Test
* public void myTest() throws Exception {
* File dir = temp.newDir();
* // ...
* }
* }
* </pre>
*
* @since 5.1
*/
public class JUnitTempFolder extends ExternalResource implements TempFolder {
private final TemporaryFolder junit = new TemporaryFolder();
@Override
public Statement apply(Statement base, Description description) {
return junit.apply(base, description);
}
@Override
protected void before() throws Throwable {
junit.create();
}
@Override
protected void after() {
junit.delete();
}
@Override
public File newDir() {
try {
return junit.newFolder();
} catch (IOException e) {
throw new IllegalStateException("Fail to create temp dir", e);
}
}
@Override
public File newDir(String name) {
try {
return junit.newFolder(name);
} catch (IOException e) {
throw new IllegalStateException("Fail to create temp dir", e);
}
}
@Override
public File newFile() {
try {
return junit.newFile();
} catch (IOException e) {
throw new IllegalStateException("Fail to create temp file", e);
}
}
@Override
public File newFile(@Nullable String prefix, @Nullable String suffix) {
try {
return junit.newFile(StringUtils.defaultString(prefix) + "-" + StringUtils.defaultString(suffix));
} catch (IOException e) {
throw new IllegalStateException("Fail to create temp file", e);
}
}
public File getRoot() {
return junit.getRoot();
}
}
| 3,029 | 26.297297 | 104 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/impl/utils/ScannerUtils.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.api.impl.utils;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
public class ScannerUtils {
private ScannerUtils() {
}
/**
* Clean provided string to remove chars that are not valid as file name.
*
* @param projectKey e.g. my:file
*/
public static String cleanKeyForFilename(String projectKey) {
String cleanKey = StringUtils.deleteWhitespace(projectKey);
return StringUtils.replace(cleanKey, ":", "_");
}
public static String encodeForUrl(@Nullable String url) {
try {
return URLEncoder.encode(url == null ? "" : url, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("Encoding not supported", e);
}
}
public static String describe(Object o) {
try {
if (o.getClass().getMethod("toString").getDeclaringClass() != Object.class) {
String str = o.toString();
if (str != null) {
return str;
}
}
} catch (Exception e) {
// fallback
}
return o.getClass().getName();
}
public static String pluralize(String str, int i) {
if (i == 1) {
return str;
}
return str + "s";
}
}
| 2,189 | 28.2 | 86 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/impl/utils/TestSystem2.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.api.impl.utils;
import java.util.TimeZone;
import org.sonar.api.utils.System2;
public class TestSystem2 extends System2 {
private long now = 0L;
private TimeZone defaultTimeZone = TimeZone.getTimeZone("UTC");
public TestSystem2 setNow(long l) {
this.now = l;
return this;
}
public TestSystem2 tick() {
throwExceptionIfNowLesserOrEqualZero();
this.now = this.now + 1;
return this;
}
@Override
public long now() {
throwExceptionIfNowLesserOrEqualZero();
return now;
}
private void throwExceptionIfNowLesserOrEqualZero() {
if (now <= 0L) {
throw new IllegalStateException("Method setNow() was not called by test");
}
}
public TestSystem2 setDefaultTimeZone(TimeZone defaultTimeZone) {
this.defaultTimeZone = defaultTimeZone;
return this;
}
@Override
public TimeZone getDefaultTimeZone() {
return defaultTimeZone;
}
}
| 1,770 | 27.111111 | 80 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/impl/utils/WorkDuration.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.api.impl.utils;
import java.io.Serializable;
import javax.annotation.Nullable;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
/**
* @since 4.2
*/
public class WorkDuration implements Serializable {
static final int DAY_POSITION_IN_LONG = 10_000;
static final int HOUR_POSITION_IN_LONG = 100;
static final int MINUTE_POSITION_IN_LONG = 1;
public enum UNIT {
DAYS, HOURS, MINUTES
}
private int hoursInDay;
private long durationInMinutes;
private int days;
private int hours;
private int minutes;
private WorkDuration(long durationInMinutes, int days, int hours, int minutes, int hoursInDay) {
this.durationInMinutes = durationInMinutes;
this.days = days;
this.hours = hours;
this.minutes = minutes;
this.hoursInDay = hoursInDay;
}
public static WorkDuration create(int days, int hours, int minutes, int hoursInDay) {
long durationInSeconds = 60L * days * hoursInDay;
durationInSeconds += 60L * hours;
durationInSeconds += minutes;
return new WorkDuration(durationInSeconds, days, hours, minutes, hoursInDay);
}
public static WorkDuration createFromValueAndUnit(int value, UNIT unit, int hoursInDay) {
switch (unit) {
case DAYS:
return create(value, 0, 0, hoursInDay);
case HOURS:
return create(0, value, 0, hoursInDay);
case MINUTES:
return create(0, 0, value, hoursInDay);
default:
throw new IllegalStateException("Cannot create work duration");
}
}
static WorkDuration createFromLong(long duration, int hoursInDay) {
int days = 0;
int hours = 0;
int minutes = 0;
long time = duration;
long currentTime = time / WorkDuration.DAY_POSITION_IN_LONG;
if (currentTime > 0) {
days = (int) currentTime;
time = time - (currentTime * WorkDuration.DAY_POSITION_IN_LONG);
}
currentTime = time / WorkDuration.HOUR_POSITION_IN_LONG;
if (currentTime > 0) {
hours = (int) currentTime;
time = time - (currentTime * WorkDuration.HOUR_POSITION_IN_LONG);
}
currentTime = time / WorkDuration.MINUTE_POSITION_IN_LONG;
if (currentTime > 0) {
minutes = (int) currentTime;
}
return WorkDuration.create(days, hours, minutes, hoursInDay);
}
static WorkDuration createFromMinutes(long duration, int hoursInDay) {
int days = (int)(duration / (double)hoursInDay / 60.0);
long currentDurationInMinutes = duration - (60L * days * hoursInDay);
int hours = (int)(currentDurationInMinutes / 60.0);
currentDurationInMinutes = currentDurationInMinutes - (60L * hours);
return new WorkDuration(duration, days, hours, (int) currentDurationInMinutes, hoursInDay);
}
/**
* Return the duration in number of working days.
* For instance, 3 days and 4 hours will return 3.5 days (if hoursIndDay is 8).
*/
public double toWorkingDays() {
return durationInMinutes / 60D / hoursInDay;
}
/**
* Return the duration using the following format DDHHMM, where DD is the number of days, HH is the number of months, and MM the number of minutes.
* For instance, 3 days and 4 hours will return 030400 (if hoursIndDay is 8).
*/
public long toLong() {
int workingDays = days;
int workingHours = hours;
if (hours >= hoursInDay) {
int nbAdditionalDays = hours / hoursInDay;
workingDays += nbAdditionalDays;
workingHours = hours - (nbAdditionalDays * hoursInDay);
}
return 1L * workingDays * DAY_POSITION_IN_LONG + workingHours * HOUR_POSITION_IN_LONG + minutes * MINUTE_POSITION_IN_LONG;
}
public long toMinutes() {
return durationInMinutes;
}
public WorkDuration add(@Nullable WorkDuration with) {
if (with != null) {
return WorkDuration.createFromMinutes(this.toMinutes() + with.toMinutes(), this.hoursInDay);
} else {
return this;
}
}
public WorkDuration subtract(@Nullable WorkDuration with) {
if (with != null) {
return WorkDuration.createFromMinutes(this.toMinutes() - with.toMinutes(), this.hoursInDay);
} else {
return this;
}
}
public WorkDuration multiply(int factor) {
return WorkDuration.createFromMinutes(this.toMinutes() * factor, this.hoursInDay);
}
public int days() {
return days;
}
public int hours() {
return hours;
}
public int minutes() {
return minutes;
}
int hoursInDay() {
return hoursInDay;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
WorkDuration that = (WorkDuration) o;
return durationInMinutes == that.durationInMinutes;
}
@Override
public int hashCode() {
return (int) (durationInMinutes ^ (durationInMinutes >>> 32));
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
}
| 5,855 | 29.030769 | 149 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/impl/utils/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.api.impl.utils;
import javax.annotation.ParametersAreNonnullByDefault;
| 965 | 37.64 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/impl/ws/PartImpl.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.api.impl.ws;
import java.io.InputStream;
import org.sonar.api.server.ws.Request;
public class PartImpl implements Request.Part {
private final InputStream inputStream;
private final String fileName;
public PartImpl(InputStream inputStream, String fileName) {
this.inputStream = inputStream;
this.fileName = fileName;
}
@Override
public InputStream getInputStream() {
return inputStream;
}
@Override
public String getFileName() {
return fileName;
}
}
| 1,353 | 29.088889 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/impl/ws/SimpleGetRequest.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.api.impl.ws;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.apache.commons.io.IOUtils;
import org.sonar.api.server.ws.LocalConnector;
import org.sonar.api.server.ws.Request;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.Objects.requireNonNull;
/**
* Fake implementation of {@link org.sonar.api.server.ws.Request} used
* for testing. Call the method {@link #setParam(String, String)} to
* emulate some parameter values.
*/
public class SimpleGetRequest extends Request {
private final Map<String, String[]> params = new HashMap<>();
private final Map<String, Part> parts = new HashMap<>();
private final Map<String, String> headers = new HashMap<>();
private String mediaType = "application/json";
private String path;
@Override
public String method() {
return "GET";
}
@Override
public String getMediaType() {
return mediaType;
}
public SimpleGetRequest setMediaType(String mediaType) {
requireNonNull(mediaType);
this.mediaType = mediaType;
return this;
}
@Override
public boolean hasParam(String key) {
return params.containsKey(key);
}
@Override
public String param(String key) {
String[] strings = params.get(key);
return strings == null || strings.length == 0 ? null : strings[0];
}
@Override
public List<String> multiParam(String key) {
String value = param(key);
return value == null ? emptyList() : singletonList(value);
}
@Override
@CheckForNull
public List<String> paramAsStrings(String key) {
String value = param(key);
if (value == null) {
return null;
}
return Arrays.stream(value.split(",")).map(String::trim).filter(x -> !x.isEmpty()).collect(Collectors.toList());
}
@Override
public InputStream paramAsInputStream(String key) {
return IOUtils.toInputStream(param(key), UTF_8);
}
public SimpleGetRequest setParam(String key, @Nullable String value) {
if (value != null) {
params.put(key, new String[] {value});
}
return this;
}
@Override
public Map<String, String[]> getParams() {
return params;
}
@Override
public Part paramAsPart(String key) {
return parts.get(key);
}
public SimpleGetRequest setPart(String key, InputStream input, String fileName) {
parts.put(key, new PartImpl(input, fileName));
return this;
}
@Override
public LocalConnector localConnector() {
throw new UnsupportedOperationException();
}
@Override
public String getPath() {
return path;
}
public SimpleGetRequest setPath(String path) {
this.path = path;
return this;
}
@Override
public Optional<String> header(String name) {
return Optional.ofNullable(headers.get(name));
}
public SimpleGetRequest setHeader(String name, String value) {
headers.put(name, value);
return this;
}
}
| 4,041 | 26.127517 | 116 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/impl/ws/StaticResources.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.api.impl.ws;
import java.util.Collection;
import java.util.List;
public class StaticResources {
private static final Collection<String> STATIC_RESOURCES = List.of("*.css", "*.css.map", "*.ico", "*.png",
"*.jpg", "*.jpeg", "*.gif", "*.svg", "*.js", "*.js.map", "*.pdf", "/json/*", "*.woff2", "/static/*",
"/robots.txt", "/favicon.ico", "/apple-touch-icon*", "/mstile*");
private StaticResources() {
// only static
}
public static Collection<String> patterns() {
return STATIC_RESOURCES;
}
}
| 1,381 | 35.368421 | 108 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/impl/ws/ValidatingRequest.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.api.impl.ws;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.api.server.ws.LocalConnector;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.WebService;
import static java.lang.String.format;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.Objects.requireNonNull;
import static org.apache.commons.lang.StringUtils.defaultString;
import static org.sonar.api.utils.Preconditions.checkArgument;
/**
* @since 4.2
*/
public abstract class ValidatingRequest extends Request {
private static final String COMMA_SPLITTER = ",";
private WebService.Action action;
private LocalConnector localConnector;
public void setAction(WebService.Action action) {
this.action = action;
}
public WebService.Action action() {
return action;
}
@Override
public LocalConnector localConnector() {
requireNonNull(localConnector, "Local connector has not been set");
return localConnector;
}
public void setLocalConnector(LocalConnector lc) {
this.localConnector = lc;
}
@Override
@CheckForNull
public String param(String key) {
WebService.Param definition = action.param(key);
String rawValue = readParam(key, definition);
String rawValueOrDefault = defaultString(rawValue, definition.defaultValue());
String value = rawValueOrDefault == null ? null : trim(rawValueOrDefault);
validateRequiredValue(key, definition, rawValue);
if (value == null) {
return null;
}
validatePossibleValues(key, value, definition);
validateMaximumLength(key, definition, rawValueOrDefault);
validateMinimumLength(key, definition, rawValueOrDefault);
validateMaximumValue(key, definition, value);
return value;
}
@Override
public List<String> multiParam(String key) {
WebService.Param definition = action.param(key);
if (definition == null) {
throw new IllegalArgumentException("Parameter '" + key + "' not found for action '" + action.key() + "'");
}
List<String> values = readMultiParamOrDefaultValue(key, definition);
return validateValues(values, definition);
}
private static String trim(String s) {
int begin;
for (begin = 0; begin < s.length(); begin++) {
if (!Character.isWhitespace(s.charAt(begin))) {
break;
}
}
int end;
for (end = s.length(); end > begin; end--) {
if (!Character.isWhitespace(s.charAt(end - 1))) {
break;
}
}
return s.substring(begin, end);
}
@Override
@CheckForNull
public InputStream paramAsInputStream(String key) {
return readInputStreamParam(key);
}
@Override
@CheckForNull
public Part paramAsPart(String key) {
return readPart(key);
}
@CheckForNull
@Override
public List<String> paramAsStrings(String key) {
WebService.Param definition = action.param(key);
String value = defaultString(readParam(key, definition), definition.defaultValue());
if (value == null) {
return null;
}
List<String> values = Arrays.stream(value.split(COMMA_SPLITTER))
.map(String::trim)
.filter(s -> !s.isEmpty())
.collect(Collectors.toList());
return validateValues(values, definition);
}
@CheckForNull
@Override
public <E extends Enum<E>> List<E> paramAsEnums(String key, Class<E> enumClass) {
List<String> values = paramAsStrings(key);
if (values == null) {
return null;
}
return values.stream()
.filter(s -> !s.isEmpty())
.map(value -> Enum.valueOf(enumClass, value))
.collect(Collectors.toList());
}
@CheckForNull
private String readParam(String key, @Nullable WebService.Param definition) {
checkArgument(definition != null, "BUG - parameter '%s' is undefined for action '%s'", key, action.key());
String deprecatedKey = definition.deprecatedKey();
String param = deprecatedKey != null ? defaultString(readParam(deprecatedKey), readParam(key)) : readParam(key);
if (param != null && param.contains("\0")) {
throw new IllegalArgumentException("Request parameters are not allowed to contain NUL character");
}
return param;
}
private List<String> readMultiParamOrDefaultValue(String key, @Nullable WebService.Param definition) {
checkArgument(definition != null, "BUG - parameter '%s' is undefined for action '%s'", key, action.key());
List<String> keyValues = readMultiParam(key);
if (!keyValues.isEmpty()) {
return keyValues;
}
String deprecatedKey = definition.deprecatedKey();
List<String> deprecatedKeyValues = deprecatedKey == null ? emptyList() : readMultiParam(deprecatedKey);
if (!deprecatedKeyValues.isEmpty()) {
return deprecatedKeyValues;
}
String defaultValue = definition.defaultValue();
return defaultValue == null ? emptyList() : singletonList(defaultValue);
}
@CheckForNull
protected abstract String readParam(String key);
protected abstract List<String> readMultiParam(String key);
@CheckForNull
protected abstract InputStream readInputStreamParam(String key);
@CheckForNull
protected abstract Part readPart(String key);
private static List<String> validateValues(List<String> values, WebService.Param definition) {
Integer maximumValues = definition.maxValuesAllowed();
checkArgument(maximumValues == null || values.size() <= maximumValues, "'%s' can contains only %s values, got %s", definition.key(), maximumValues, values.size());
values.forEach(value -> validatePossibleValues(definition.key(), value, definition));
return values;
}
private static void validatePossibleValues(String key, String value, WebService.Param definition) {
Set<String> possibleValues = definition.possibleValues();
if (possibleValues == null) {
return;
}
checkArgument(possibleValues.contains(value), "Value of parameter '%s' (%s) must be one of: %s", key, value, possibleValues);
}
private static void validateMaximumLength(String key, WebService.Param definition, String valueOrDefault) {
Integer maximumLength = definition.maximumLength();
if (maximumLength == null) {
return;
}
int valueLength = valueOrDefault.length();
checkArgument(valueLength <= maximumLength, "'%s' length (%s) is longer than the maximum authorized (%s)", key, valueLength, maximumLength);
}
private static void validateMinimumLength(String key, WebService.Param definition, String valueOrDefault) {
Integer minimumLength = definition.minimumLength();
if (minimumLength == null) {
return;
}
int valueLength = valueOrDefault.length();
checkArgument(valueLength >= minimumLength, "'%s' length (%s) is shorter than the minimum authorized (%s)", key, valueLength, minimumLength);
}
private static void validateMaximumValue(String key, WebService.Param definition, String value) {
Integer maximumValue = definition.maximumValue();
if (maximumValue == null) {
return;
}
int valueAsInt = validateAsNumeric(key, value);
checkArgument(valueAsInt <= maximumValue, "'%s' value (%s) must be less than %s", key, valueAsInt, maximumValue);
}
private static void validateRequiredValue(String key, WebService.Param definition, @Nullable String value) {
boolean required = definition.isRequired();
if (required) {
checkArgument(value != null, format(MSG_PARAMETER_MISSING, key));
}
}
private static int validateAsNumeric(String key, String value) {
try {
return Integer.parseInt(value);
} catch (NumberFormatException exception) {
throw new IllegalArgumentException(format("'%s' value '%s' cannot be parsed as an integer", key, value), exception);
}
}
}
| 8,772 | 34.092 | 167 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/impl/ws/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.api.impl.ws;
import javax.annotation.ParametersAreNonnullByDefault;
| 961 | 39.083333 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/internal/MetadataLoader.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.api.internal;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import java.util.Scanner;
import org.sonar.api.SonarEdition;
import org.sonar.api.utils.System2;
import org.sonar.api.utils.Version;
import static org.apache.commons.lang.StringUtils.trimToEmpty;
/**
* For internal use
*
* @since 7.8
*/
public class MetadataLoader {
private static final String SQ_VERSION_FILE_PATH = "/sq-version.txt";
private static final String SONAR_API_VERSION_FILE_PATH = "/sonar-api-version.txt";
private static final String EDITION_FILE_PATH = "/sonar-edition.txt";
private MetadataLoader() {
// only static methods
}
public static Version loadApiVersion(System2 system) {
return getVersion(system, SONAR_API_VERSION_FILE_PATH);
}
public static Version loadSQVersion(System2 system) {
return getVersion(system, SQ_VERSION_FILE_PATH);
}
private static Version getVersion(System2 system, String versionFilePath) {
URL url = system.getResource(versionFilePath);
try (Scanner scanner = new Scanner(url.openStream(), StandardCharsets.UTF_8.name())) {
String versionInFile = scanner.nextLine();
return Version.parse(versionInFile);
} catch (IOException e) {
throw new IllegalStateException("Can not load " + versionFilePath + " from classpath ", e);
}
}
public static SonarEdition loadEdition(System2 system) {
URL url = system.getResource(EDITION_FILE_PATH);
if (url == null) {
return SonarEdition.COMMUNITY;
}
try (Scanner scanner = new Scanner(url.openStream(), StandardCharsets.UTF_8.name())) {
String editionInFile = scanner.nextLine();
return parseEdition(editionInFile);
} catch (IOException e) {
throw new IllegalStateException("Can not load " + EDITION_FILE_PATH + " from classpath", e);
}
}
static SonarEdition parseEdition(String edition) {
String str = trimToEmpty(edition.toUpperCase(Locale.ENGLISH));
try {
return SonarEdition.valueOf(str);
} catch (IllegalArgumentException e) {
throw new IllegalStateException(String.format("Invalid edition found in '%s': '%s'", EDITION_FILE_PATH, str));
}
}
}
| 3,087 | 34.090909 | 116 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/internal/PluginContextImpl.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.api.internal;
import org.sonar.api.Plugin;
import org.sonar.api.SonarRuntime;
import org.sonar.api.config.Configuration;
import org.sonar.api.config.internal.MapSettings;
/**
* Implementation of {@link Plugin.Context} that plugins could use in their unit tests.
*
* Example:
*
* <pre>
* import org.sonar.api.internal.SonarRuntimeImpl;
* import org.sonar.api.config.internal.MapSettings;
*
* ...
*
* SonarRuntime runtime = SonarRuntimeImpl.forSonarQube(Version.create(7, 1), SonarQubeSide.SCANNER);
* MapSettings settings = new MapSettings().setProperty("foo", "bar");
* Plugin.Context context = new PluginContextImpl.Builder()
* .setSonarRuntime(runtime)
* .setBootConfiguration(settings.asConfig());
* .build();
* </pre>
*
* @since 7.1
*/
public class PluginContextImpl extends Plugin.Context {
private final Configuration bootConfiguration;
private PluginContextImpl(Builder builder) {
super(builder.sonarRuntime);
this.bootConfiguration = builder.bootConfiguration != null ? builder.bootConfiguration : new MapSettings().asConfig();
}
@Override
public Configuration getBootConfiguration() {
return bootConfiguration;
}
public static class Builder {
private SonarRuntime sonarRuntime;
private Configuration bootConfiguration;
/**
* Required.
* @see SonarRuntimeImpl
* @return this
*/
public Builder setSonarRuntime(SonarRuntime r) {
this.sonarRuntime = r;
return this;
}
/**
* If not set, then an empty configuration is used.
* @return this
*/
public Builder setBootConfiguration(Configuration c) {
this.bootConfiguration = c;
return this;
}
public Plugin.Context build() {
return new PluginContextImpl(this);
}
}
}
| 2,665 | 28.622222 | 122 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/internal/SonarRuntimeImpl.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.api.internal;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.SonarEdition;
import org.sonar.api.SonarProduct;
import org.sonar.api.SonarQubeSide;
import org.sonar.api.SonarRuntime;
import org.sonar.api.utils.Version;
import static java.util.Objects.requireNonNull;
import static org.sonar.api.utils.Preconditions.checkArgument;
/**
* @since 6.0
*/
@Immutable
public class SonarRuntimeImpl implements SonarRuntime {
private final Version apiVersion;
private final SonarProduct product;
private final SonarQubeSide sonarQubeSide;
private final SonarEdition edition;
private SonarRuntimeImpl(Version apiVersion, SonarProduct product, @Nullable SonarQubeSide sonarQubeSide, @Nullable SonarEdition edition) {
this.edition = edition;
requireNonNull(product);
checkArgument((product == SonarProduct.SONARQUBE) == (sonarQubeSide != null), "sonarQubeSide should be provided only for SonarQube product");
checkArgument((product == SonarProduct.SONARQUBE) == (edition != null), "edition should be provided only for SonarQube product");
this.apiVersion = requireNonNull(apiVersion);
this.product = product;
this.sonarQubeSide = sonarQubeSide;
}
@Override
public Version getApiVersion() {
return apiVersion;
}
@Override
public SonarProduct getProduct() {
return product;
}
@Override
public SonarQubeSide getSonarQubeSide() {
if (sonarQubeSide == null) {
throw new UnsupportedOperationException("Can only be called in SonarQube");
}
return sonarQubeSide;
}
@Override
public SonarEdition getEdition() {
if (sonarQubeSide == null) {
throw new UnsupportedOperationException("Can only be called in SonarQube");
}
return edition;
}
/**
* Create an instance for SonarQube runtime environment.
*/
public static SonarRuntime forSonarQube(Version apiVersion, SonarQubeSide side, SonarEdition edition) {
return new SonarRuntimeImpl(apiVersion, SonarProduct.SONARQUBE, side, edition);
}
/**
* Create an instance for SonarLint runtime environment.
*/
public static SonarRuntime forSonarLint(Version version) {
return new SonarRuntimeImpl(version, SonarProduct.SONARLINT, null, null);
}
}
| 3,131 | 31.968421 | 145 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/main/java/org/sonar/api/internal/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.api.internal;
import javax.annotation.ParametersAreNonnullByDefault;
| 963 | 37.56 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/fs/internal/DefaultIndexedFileTest.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.api.batch.fs.internal;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.apache.commons.lang.StringUtils;
import org.assertj.core.api.Assertions;
import org.junit.Test;
public class DefaultIndexedFileTest {
@Test
public void fail_to_index_if_file_key_too_long() {
String path = StringUtils.repeat("a", 395);
String projectKey = "12345";
Path baseDir = Paths.get("");
Assertions.assertThatThrownBy(() -> new DefaultIndexedFile(projectKey, baseDir, path, null))
.isInstanceOf(IllegalStateException.class)
.hasMessageEndingWith("length (401) is longer than the maximum authorized (400)");
}
@Test
public void sanitize_shouldThrow_whenRelativePathIsInvalid() {
String invalidPath = "./../foo/bar";
Assertions.assertThatThrownBy(() -> DefaultIndexedFile.checkSanitize(invalidPath))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining(invalidPath);
}
}
| 1,803 | 37.382979 | 96 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/fs/internal/charhandler/IntArrayListTest.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.api.batch.fs.internal.charhandler;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class IntArrayListTest {
@Test
public void addElements() {
IntArrayList list = new IntArrayList();
assertThat(list.trimAndGet()).isEmpty();
list.add(1);
list.add(2);
assertThat(list.trimAndGet()).containsExactly(1, 2);
}
@Test
public void trimIfNeeded() {
IntArrayList list = new IntArrayList();
list.add(1);
list.add(2);
assertThat(list.trimAndGet()).isSameAs(list.trimAndGet());
}
@Test
public void grow() {
// Default capacity is 10
IntArrayList list = new IntArrayList();
for (int i = 1; i <= 11; i++) {
list.add(i);
}
assertThat(list.trimAndGet()).hasSize(11);
}
}
| 1,641 | 28.321429 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/fs/internal/fs/DefaultFileSystemTest.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.api.batch.fs.internal.fs;
import java.io.File;
import java.nio.charset.StandardCharsets;
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.TestInputFileBuilder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class DefaultFileSystemTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private DefaultFileSystem fs;
private File basedir;
@Before
public void prepare() throws Exception {
basedir = temp.newFolder();
fs = new DefaultFileSystem(basedir.toPath());
}
@Test
public void test_directories() throws Exception {
assertThat(fs.baseDir()).isAbsolute().isDirectory().exists();
assertThat(fs.baseDir().getCanonicalPath()).isEqualTo(basedir.getCanonicalPath());
File workdir = temp.newFolder();
fs.setWorkDir(workdir.toPath());
assertThat(fs.workDir()).isAbsolute().isDirectory().exists();
assertThat(fs.workDir().getCanonicalPath()).isEqualTo(workdir.getCanonicalPath());
}
@Test
public void test_encoding() throws Exception {
fs.setEncoding(StandardCharsets.ISO_8859_1);
assertThat(fs.encoding()).isEqualTo(StandardCharsets.ISO_8859_1);
}
@Test
public void add_languages() {
assertThat(fs.languages()).isEmpty();
fs.add(new TestInputFileBuilder("foo", "src/Foo.php").setLanguage("php").build());
fs.add(new TestInputFileBuilder("foo", "src/Bar.java").setLanguage("java").build());
assertThat(fs.languages()).containsOnly("java", "php");
}
@Test
public void files() {
assertThat(fs.inputFiles(fs.predicates().all())).isEmpty();
fs.add(new TestInputFileBuilder("foo", "src/Foo.php").setLanguage("php").build());
fs.add(new TestInputFileBuilder("foo", "src/Bar.java").setLanguage("java").build());
fs.add(new TestInputFileBuilder("foo", "src/Baz.java").setLanguage("java").build());
// no language
fs.add(new TestInputFileBuilder("foo", "src/readme.txt").build());
assertThat(fs.inputFile(fs.predicates().hasRelativePath("src/Bar.java"))).isNotNull();
assertThat(fs.inputFile(fs.predicates().hasRelativePath("does/not/exist"))).isNull();
assertThat(fs.inputFile(fs.predicates().hasAbsolutePath(new File(basedir, "src/Bar.java").getAbsolutePath()))).isNotNull();
assertThat(fs.inputFile(fs.predicates().hasAbsolutePath(new File(basedir, "does/not/exist").getAbsolutePath()))).isNull();
assertThat(fs.inputFile(fs.predicates().hasAbsolutePath(new File(basedir, "../src/Bar.java").getAbsolutePath()))).isNull();
assertThat(fs.inputFile(fs.predicates().hasURI(new File(basedir, "src/Bar.java").toURI()))).isNotNull();
assertThat(fs.inputFile(fs.predicates().hasURI(new File(basedir, "does/not/exist").toURI()))).isNull();
assertThat(fs.inputFile(fs.predicates().hasURI(new File(basedir, "../src/Bar.java").toURI()))).isNull();
assertThat(fs.files(fs.predicates().all())).hasSize(4);
assertThat(fs.files(fs.predicates().hasLanguage("java"))).hasSize(2);
assertThat(fs.files(fs.predicates().hasLanguage("cobol"))).isEmpty();
assertThat(fs.hasFiles(fs.predicates().all())).isTrue();
assertThat(fs.hasFiles(fs.predicates().hasLanguage("java"))).isTrue();
assertThat(fs.hasFiles(fs.predicates().hasLanguage("cobol"))).isFalse();
assertThat(fs.inputFiles(fs.predicates().all())).hasSize(4);
assertThat(fs.inputFiles(fs.predicates().hasLanguage("php"))).hasSize(1);
assertThat(fs.inputFiles(fs.predicates().hasLanguage("java"))).hasSize(2);
assertThat(fs.inputFiles(fs.predicates().hasLanguage("cobol"))).isEmpty();
assertThat(fs.languages()).containsOnly("java", "php");
}
@Test
public void inputFiles_using_optimized_predicates() {
fs.add(new TestInputFileBuilder("foo", "src/Foo.php").setLanguage("php").build());
fs.add(new TestInputFileBuilder("foo", "src/Bar.java").setLanguage("java").build());
fs.add(new TestInputFileBuilder("foo", "src/Baz.java").setLanguage("java").build());
assertThat(fs.inputFiles(fs.predicates().hasFilename("Foo.php"))).hasSize(1);
assertThat(fs.inputFiles(fs.predicates().hasFilename("unknown"))).isEmpty();
assertThat(fs.inputFiles(fs.predicates().hasExtension("java"))).hasSize(2);
assertThat(fs.inputFiles(fs.predicates().hasExtension("unknown"))).isEmpty();
}
@Test
public void hasFiles_using_optimized_predicates() {
fs.add(new TestInputFileBuilder("foo", "src/Foo.php").setLanguage("php").build());
fs.add(new TestInputFileBuilder("foo", "src/Bar.java").setLanguage("java").build());
fs.add(new TestInputFileBuilder("foo", "src/Baz.java").setLanguage("java").build());
assertThat(fs.hasFiles(fs.predicates().hasFilename("Foo.php"))).isTrue();
assertThat(fs.hasFiles(fs.predicates().hasFilename("unknown"))).isFalse();
assertThat(fs.hasFiles(fs.predicates().hasExtension("java"))).isTrue();
assertThat(fs.hasFiles(fs.predicates().hasExtension("unknown"))).isFalse();
}
@Test
public void inputFile_returns_null_if_file_not_found() {
assertThat(fs.inputFile(fs.predicates().hasRelativePath("src/Bar.java"))).isNull();
assertThat(fs.inputFile(fs.predicates().hasLanguage("cobol"))).isNull();
}
@Test
public void inputFile_fails_if_too_many_results() {
fs.add(new TestInputFileBuilder("foo", "src/Bar.java").setLanguage("java").build());
fs.add(new TestInputFileBuilder("foo", "src/Baz.java").setLanguage("java").build());
assertThatThrownBy(() -> fs.inputFile(fs.predicates().all()))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("expected one element");
}
@Test
public void inputFile_supports_non_indexed_predicates() {
fs.add(new TestInputFileBuilder("foo", "src/Bar.java").setLanguage("java").build());
// it would fail if more than one java file
assertThat(fs.inputFile(fs.predicates().hasLanguage("java"))).isNotNull();
}
}
| 6,947 | 41.888889 | 127 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/fs/internal/fs/DefaultInputDirTest.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.api.batch.fs.internal.fs;
import java.io.File;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.internal.DefaultInputDir;
import static org.assertj.core.api.Assertions.assertThat;
public class DefaultInputDirTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Test
public void test() throws Exception {
File baseDir = temp.newFolder();
DefaultInputDir inputDir = new DefaultInputDir("ABCDE", "src")
.setModuleBaseDir(baseDir.toPath());
assertThat(inputDir.key()).isEqualTo("ABCDE:src");
assertThat(inputDir.file().getAbsolutePath()).isEqualTo(new File(baseDir, "src").getAbsolutePath());
assertThat(inputDir.relativePath()).isEqualTo("src");
assertThat(new File(inputDir.relativePath())).isRelative();
assertThat(inputDir.absolutePath()).endsWith("src");
assertThat(new File(inputDir.absolutePath())).isAbsolute();
}
@Test
public void testEqualsAndHashCode() {
DefaultInputDir inputDir1 = new DefaultInputDir("ABCDE", "src");
DefaultInputDir inputDir2 = new DefaultInputDir("ABCDE", "src");
assertThat(inputDir1.equals(inputDir1)).isTrue();
assertThat(inputDir1.equals(inputDir2)).isTrue();
assertThat(inputDir1.equals("foo")).isFalse();
assertThat(inputDir1.hashCode()).isEqualTo(63545559);
assertThat(inputDir1.toString()).contains("[moduleKey=ABCDE, relative=src, basedir=null");
}
}
| 2,325 | 34.242424 | 104 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/fs/internal/fs/DefaultInputFileTest.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.api.batch.fs.internal.fs;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.function.Consumer;
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.TextRange;
import org.sonar.api.batch.fs.internal.DefaultIndexedFile;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.FileMetadata;
import org.sonar.api.batch.fs.internal.Metadata;
import org.sonar.api.batch.fs.internal.SensorStrategy;
import org.sonar.api.notifications.AnalysisWarnings;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
public class DefaultInputFileTest {
private static final String PROJECT_RELATIVE_PATH = "module1/src/Foo.php";
private static final String MODULE_RELATIVE_PATH = "src/Foo.php";
private static final String OLD_RELATIVE_PATH = "src/previous/Foo.php";
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private DefaultIndexedFile indexedFile;
private Path baseDir;
private SensorStrategy sensorStrategy;
@Before
public void prepare() throws IOException {
baseDir = temp.newFolder().toPath();
sensorStrategy = new SensorStrategy();
indexedFile = new DefaultIndexedFile(baseDir.resolve(PROJECT_RELATIVE_PATH), "ABCDE", PROJECT_RELATIVE_PATH, MODULE_RELATIVE_PATH, InputFile.Type.TEST, "php", 0,
sensorStrategy);
}
@Test
public void status_whenScmAvailable_shouldUseScmToCompute() {
Consumer<DefaultInputFile> metadata = mock(Consumer.class);
Consumer<DefaultInputFile> scmStatus = f -> f.setStatus(InputFile.Status.SAME);
DefaultInputFile inputFile = new DefaultInputFile(indexedFile, metadata, scmStatus);
assertThat(inputFile.status()).isEqualTo(InputFile.Status.SAME);
assertThat(inputFile.isStatusSet()).isTrue();
verifyNoInteractions(metadata);
}
@Test
public void status_whenNoScmAvailable_shouldUseMetadataToCompute() {
Consumer<DefaultInputFile> metadata = f -> f.setStatus(InputFile.Status.ADDED);
Consumer<DefaultInputFile> scmStatus = mock(Consumer.class);
DefaultInputFile inputFile = new DefaultInputFile(indexedFile, metadata, scmStatus);
assertThat(inputFile.status()).isEqualTo(InputFile.Status.ADDED);
assertThat(inputFile.isStatusSet()).isTrue();
verify(scmStatus).accept(inputFile);
}
@Test
public void test() {
Metadata metadata = new Metadata(42, 42, "", new int[0], new int[0], 10);
DefaultInputFile inputFile = new DefaultInputFile(indexedFile, f -> f.setMetadata(metadata), NO_OP)
.setStatus(InputFile.Status.ADDED)
.setCharset(StandardCharsets.ISO_8859_1);
assertThat(inputFile.absolutePath()).endsWith("Foo.php");
assertThat(inputFile.filename()).isEqualTo("Foo.php");
assertThat(inputFile.uri()).hasPath(baseDir.resolve(PROJECT_RELATIVE_PATH).toUri().getPath());
assertThat(new File(inputFile.absolutePath())).isAbsolute();
assertThat(inputFile.language()).isEqualTo("php");
assertThat(inputFile.status()).isEqualTo(InputFile.Status.ADDED);
assertThat(inputFile.type()).isEqualTo(InputFile.Type.TEST);
assertThat(inputFile.lines()).isEqualTo(42);
assertThat(inputFile.charset()).isEqualTo(StandardCharsets.ISO_8859_1);
assertThat(inputFile.getModuleRelativePath()).isEqualTo(MODULE_RELATIVE_PATH);
assertThat(inputFile.getProjectRelativePath()).isEqualTo(PROJECT_RELATIVE_PATH);
sensorStrategy.setGlobal(false);
assertThat(inputFile.relativePath()).isEqualTo(MODULE_RELATIVE_PATH);
assertThat(new File(inputFile.relativePath())).isRelative();
sensorStrategy.setGlobal(true);
assertThat(inputFile.relativePath()).isEqualTo(PROJECT_RELATIVE_PATH);
assertThat(new File(inputFile.relativePath())).isRelative();
}
@Test
public void test_moved_file() {
DefaultIndexedFile indexedFileForMovedFile = new DefaultIndexedFile(baseDir.resolve(PROJECT_RELATIVE_PATH), "ABCDE", PROJECT_RELATIVE_PATH, MODULE_RELATIVE_PATH,
InputFile.Type.TEST, "php", 0,
sensorStrategy, OLD_RELATIVE_PATH);
Metadata metadata = new Metadata(42, 42, "", new int[0], new int[0], 10);
DefaultInputFile inputFile = new DefaultInputFile(indexedFileForMovedFile, f -> f.setMetadata(metadata), NO_OP)
.setStatus(InputFile.Status.ADDED)
.setCharset(StandardCharsets.ISO_8859_1);
assertThat(inputFile.oldRelativePath()).isEqualTo(OLD_RELATIVE_PATH);
}
@Test
public void test_content() throws IOException {
Path testFile = baseDir.resolve(PROJECT_RELATIVE_PATH);
Files.createDirectories(testFile.getParent());
String content = "test é string";
Files.writeString(testFile, content, StandardCharsets.ISO_8859_1);
assertThat(Files.readAllLines(testFile, StandardCharsets.ISO_8859_1).get(0)).hasSize(content.length());
Metadata metadata = new Metadata(42, 30, "", new int[0], new int[0], 10);
DefaultInputFile inputFile = new DefaultInputFile(indexedFile, f -> f.setMetadata(metadata), NO_OP)
.setStatus(InputFile.Status.ADDED)
.setCharset(StandardCharsets.ISO_8859_1);
assertThat(inputFile.contents()).isEqualTo(content);
try (InputStream inputStream = inputFile.inputStream()) {
String result = new BufferedReader(new InputStreamReader(inputStream, inputFile.charset())).lines().collect(Collectors.joining());
assertThat(result).isEqualTo(content);
}
}
@Test
public void test_content_exclude_bom() throws IOException {
Path testFile = baseDir.resolve(PROJECT_RELATIVE_PATH);
Files.createDirectories(testFile.getParent());
try (BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(testFile.toFile()), StandardCharsets.UTF_8))) {
out.write('\ufeff');
}
String content = "test é string €";
Files.write(testFile, content.getBytes(StandardCharsets.UTF_8), StandardOpenOption.APPEND);
assertThat(Files.readAllLines(testFile, StandardCharsets.UTF_8).get(0)).hasSize(content.length() + 1);
Metadata metadata = new Metadata(42, 30, "", new int[0], new int[0], 10);
DefaultInputFile inputFile = new DefaultInputFile(indexedFile, f -> f.setMetadata(metadata), NO_OP)
.setStatus(InputFile.Status.ADDED)
.setCharset(StandardCharsets.UTF_8);
assertThat(inputFile.contents()).isEqualTo(content);
try (InputStream inputStream = inputFile.inputStream()) {
String result = new BufferedReader(new InputStreamReader(inputStream, inputFile.charset())).lines().collect(Collectors.joining());
assertThat(result).isEqualTo(content);
}
}
@Test
public void test_equals_and_hashcode() {
DefaultInputFile f1 = new DefaultInputFile(new DefaultIndexedFile("ABCDE", Paths.get("module"), MODULE_RELATIVE_PATH, null), NO_OP, NO_OP);
DefaultInputFile f1a = new DefaultInputFile(new DefaultIndexedFile("ABCDE", Paths.get("module"), MODULE_RELATIVE_PATH, null), NO_OP, NO_OP);
DefaultInputFile f2 = new DefaultInputFile(new DefaultIndexedFile("ABCDE", Paths.get("module"), "src/Bar.php", null), NO_OP, NO_OP);
assertThat(f1)
.isEqualTo(f1)
.isEqualTo(f1a)
.isNotEqualTo(f2);
assertThat(f1.equals("foo")).isFalse();
assertThat(f1.equals(null)).isFalse();
assertThat(f1)
.hasSameHashCodeAs(f1)
.hasSameHashCodeAs(f1a);
}
@Test
public void test_toString() {
DefaultInputFile file = new DefaultInputFile(new DefaultIndexedFile("ABCDE", Paths.get("module"), MODULE_RELATIVE_PATH, null), NO_OP, NO_OP);
assertThat(file).hasToString(MODULE_RELATIVE_PATH);
}
@Test
public void checkValidPointer() {
Metadata metadata = new Metadata(2, 2, "", new int[] {0, 10}, new int[] {9, 15}, 16);
DefaultInputFile file = new DefaultInputFile(new DefaultIndexedFile("ABCDE", Paths.get("module"), MODULE_RELATIVE_PATH, null),
f -> f.setMetadata(metadata), NO_OP);
assertThat(file.newPointer(1, 0).line()).isOne();
assertThat(file.newPointer(1, 0).lineOffset()).isZero();
// Don't fail
file.newPointer(1, 9);
file.newPointer(2, 0);
file.newPointer(2, 5);
try {
file.newPointer(0, 1);
fail();
} catch (Exception e) {
assertThat(e).hasMessage("0 is not a valid line for a file");
}
try {
file.newPointer(3, 1);
fail();
} catch (Exception e) {
assertThat(e).hasMessage("3 is not a valid line for pointer. File src/Foo.php has 2 line(s)");
}
try {
file.newPointer(1, -1);
fail();
} catch (Exception e) {
assertThat(e).hasMessage("-1 is not a valid line offset for a file");
}
try {
file.newPointer(1, 10);
fail();
} catch (Exception e) {
assertThat(e).hasMessage("10 is not a valid line offset for pointer. File src/Foo.php has 9 character(s) at line 1");
}
}
@Test
public void checkValidPointerUsingGlobalOffset() {
Metadata metadata = new Metadata(2, 2, "", new int[] {0, 10}, new int[] {8, 15}, 16);
DefaultInputFile file = new DefaultInputFile(new DefaultIndexedFile("ABCDE", Paths.get("module"), MODULE_RELATIVE_PATH, null),
f -> f.setMetadata(metadata), f -> {
});
assertThat(file.newPointer(0).line()).isOne();
assertThat(file.newPointer(0).lineOffset()).isZero();
assertThat(file.newPointer(9).line()).isOne();
// Ignore eol characters
assertThat(file.newPointer(9).lineOffset()).isEqualTo(8);
assertThat(file.newPointer(10).line()).isEqualTo(2);
assertThat(file.newPointer(10).lineOffset()).isZero();
assertThat(file.newPointer(15).line()).isEqualTo(2);
assertThat(file.newPointer(15).lineOffset()).isEqualTo(5);
assertThat(file.newPointer(16).line()).isEqualTo(2);
// Ignore eol characters
assertThat(file.newPointer(16).lineOffset()).isEqualTo(5);
try {
file.newPointer(-1);
fail();
} catch (Exception e) {
assertThat(e).hasMessage("-1 is not a valid offset for a file");
}
try {
file.newPointer(17);
fail();
} catch (Exception e) {
assertThat(e).hasMessage("17 is not a valid offset for file src/Foo.php. Max offset is 16");
}
}
@Test
public void checkValidRange() {
Metadata metadata = new FileMetadata(mock(AnalysisWarnings.class)).readMetadata(new StringReader("bla bla a\nabcde"));
DefaultInputFile file = new DefaultInputFile(new DefaultIndexedFile("ABCDE", Paths.get("module"), MODULE_RELATIVE_PATH, null),
f -> f.setMetadata(metadata), NO_OP);
assertThat(file.newRange(file.newPointer(1, 0), file.newPointer(2, 1)).start().line()).isOne();
// Don't fail
file.newRange(file.newPointer(1, 0), file.newPointer(1, 1));
file.newRange(file.newPointer(1, 0), file.newPointer(1, 9));
file.newRange(file.newPointer(1, 0), file.newPointer(2, 0));
assertThat(file.newRange(file.newPointer(1, 0), file.newPointer(2, 5))).isEqualTo(file.newRange(0, 15));
try {
file.newRange(file.newPointer(1, 0), file.newPointer(1, 0));
fail();
} catch (Exception e) {
assertThat(e).hasMessage("Start pointer [line=1, lineOffset=0] should be before end pointer [line=1, lineOffset=0]");
}
try {
file.newRange(file.newPointer(1, 0), file.newPointer(1, 10));
fail();
} catch (Exception e) {
assertThat(e).hasMessage("10 is not a valid line offset for pointer. File src/Foo.php has 9 character(s) at line 1");
}
}
@Test
public void selectLine() {
Metadata metadata = new FileMetadata(mock(AnalysisWarnings.class)).readMetadata(new StringReader("bla bla a\nabcde\n\nabc"));
DefaultInputFile file = new DefaultInputFile(new DefaultIndexedFile("ABCDE", Paths.get("module"), MODULE_RELATIVE_PATH, null),
f -> f.setMetadata(metadata), NO_OP);
assertThat(file.selectLine(1).start().line()).isOne();
assertThat(file.selectLine(1).start().lineOffset()).isZero();
assertThat(file.selectLine(1).end().line()).isOne();
assertThat(file.selectLine(1).end().lineOffset()).isEqualTo(9);
// Don't fail when selecting empty line
assertThat(file.selectLine(3).start().line()).isEqualTo(3);
assertThat(file.selectLine(3).start().lineOffset()).isZero();
assertThat(file.selectLine(3).end().line()).isEqualTo(3);
assertThat(file.selectLine(3).end().lineOffset()).isZero();
try {
file.selectLine(5);
fail();
} catch (Exception e) {
assertThat(e).hasMessage("5 is not a valid line for pointer. File src/Foo.php has 4 line(s)");
}
}
@Test
public void checkValidRangeUsingGlobalOffset() {
Metadata metadata = new Metadata(2, 2, "", new int[] {0, 10}, new int[] {9, 15}, 16);
DefaultInputFile file = new DefaultInputFile(new DefaultIndexedFile("ABCDE", Paths.get("module"), MODULE_RELATIVE_PATH, null),
f -> f.setMetadata(metadata), NO_OP);
TextRange newRange = file.newRange(10, 13);
assertThat(newRange.start().line()).isEqualTo(2);
assertThat(newRange.start().lineOffset()).isZero();
assertThat(newRange.end().line()).isEqualTo(2);
assertThat(newRange.end().lineOffset()).isEqualTo(3);
}
@Test
public void testRangeOverlap() {
Metadata metadata = new Metadata(2, 2, "", new int[] {0, 10}, new int[] {9, 15}, 16);
DefaultInputFile file = new DefaultInputFile(new DefaultIndexedFile("ABCDE", Paths.get("module"), MODULE_RELATIVE_PATH, null),
f -> f.setMetadata(metadata), NO_OP);
// Don't fail
assertThat(file.newRange(file.newPointer(1, 0), file.newPointer(1, 1)).overlap(file.newRange(file.newPointer(1, 0), file.newPointer(1, 1)))).isTrue();
assertThat(file.newRange(file.newPointer(1, 0), file.newPointer(1, 1)).overlap(file.newRange(file.newPointer(1, 0), file.newPointer(1, 2)))).isTrue();
assertThat(file.newRange(file.newPointer(1, 0), file.newPointer(1, 1)).overlap(file.newRange(file.newPointer(1, 1), file.newPointer(1, 2)))).isFalse();
assertThat(file.newRange(file.newPointer(1, 2), file.newPointer(1, 3)).overlap(file.newRange(file.newPointer(1, 0), file.newPointer(1, 2)))).isFalse();
}
private static final Consumer<DefaultInputFile> NO_OP = f -> {
};
}
| 15,629 | 41.243243 | 165 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/fs/internal/fs/DefaultInputModuleTest.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.api.batch.fs.internal.fs;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import static org.assertj.core.api.Assertions.assertThat;
public class DefaultInputModuleTest {
private static final String FILE_1 = "file1";
private static final String TEST_1 = "test1";
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Test
public void check_getters() throws IOException {
ProjectDefinition def = ProjectDefinition.create();
def.setKey("moduleKey");
File baseDir = temp.newFolder();
Path src = baseDir.toPath().resolve(FILE_1);
Files.createFile(src);
Path test = baseDir.toPath().resolve(TEST_1);
Files.createFile(test);
def.setBaseDir(baseDir);
File workDir = temp.newFolder();
def.setWorkDir(workDir);
def.setSources(FILE_1);
def.setTests(TEST_1);
DefaultInputModule module = new DefaultInputModule(def);
assertThat(module.key()).isEqualTo("moduleKey");
assertThat(module.definition()).isEqualTo(def);
assertThat(module.getBaseDir())
.isEqualTo(baseDir.toPath().toRealPath(LinkOption.NOFOLLOW_LINKS));
assertThat(module.getWorkDir()).isEqualTo(workDir.toPath());
assertThat(module.getEncoding()).isEqualTo(Charset.defaultCharset());
assertThat(module.getSourceDirsOrFiles().get()).containsExactlyInAnyOrder(src.toRealPath(LinkOption.NOFOLLOW_LINKS));
assertThat(module.getTestDirsOrFiles().get()).containsExactlyInAnyOrder(test.toRealPath(LinkOption.NOFOLLOW_LINKS));
assertThat(module.getEncoding()).isEqualTo(Charset.defaultCharset());
assertThat(module.isFile()).isFalse();
}
@Test
public void no_sources() throws IOException {
ProjectDefinition def = ProjectDefinition.create();
def.setKey("moduleKey");
File baseDir = temp.newFolder();
Path src = baseDir.toPath().resolve(FILE_1);
Files.createFile(src);
Path test = baseDir.toPath().resolve(TEST_1);
Files.createFile(test);
def.setBaseDir(baseDir);
File workDir = temp.newFolder();
def.setWorkDir(workDir);
DefaultInputModule module = new DefaultInputModule(def);
assertThat(module.key()).isEqualTo("moduleKey");
assertThat(module.definition()).isEqualTo(def);
assertThat(module.getBaseDir()).isEqualTo(baseDir.toPath().toRealPath(LinkOption.NOFOLLOW_LINKS));
assertThat(module.getWorkDir()).isEqualTo(workDir.toPath());
assertThat(module.getEncoding()).isEqualTo(Charset.defaultCharset());
assertThat(module.getSourceDirsOrFiles()).isNotPresent();
assertThat(module.getTestDirsOrFiles()).isNotPresent();
assertThat(module.getEncoding()).isEqualTo(Charset.defaultCharset());
assertThat(module.isFile()).isFalse();
}
@Test
public void working_directory_should_be_hidden() throws IOException {
ProjectDefinition def = ProjectDefinition.create();
File workDir = temp.newFolder(".sonar");
def.setWorkDir(workDir);
File baseDir = temp.newFolder();
def.setBaseDir(baseDir);
DefaultInputModule module = new DefaultInputModule(def);
assertThat(workDir.isHidden()).isTrue();
}
}
| 4,254 | 37.681818 | 121 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/fs/internal/fs/DefaultInputProjectTest.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.api.batch.fs.internal.fs;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.LinkOption;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.batch.fs.internal.AbstractProjectOrModule;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import static org.assertj.core.api.Assertions.assertThat;
public class DefaultInputProjectTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Test
public void testGetters() throws IOException {
ProjectDefinition def = ProjectDefinition.create();
def.setKey("projectKey");
def.setName("projectName");
File baseDir = temp.newFolder();
def.setBaseDir(baseDir);
def.setDescription("desc");
File workDir = temp.newFolder();
def.setWorkDir(workDir);
def.setSources("file1");
def.setTests("test1");
AbstractProjectOrModule project = new DefaultInputProject(def);
assertThat(project.key()).isEqualTo("projectKey");
assertThat(project.getName()).isEqualTo("projectName");
assertThat(project.getOriginalName()).isEqualTo("projectName");
assertThat(project.definition()).isEqualTo(def);
assertThat(project.getBaseDir()).isEqualTo(baseDir.toPath().toRealPath(LinkOption.NOFOLLOW_LINKS));
assertThat(project.getDescription()).isEqualTo("desc");
assertThat(project.getWorkDir()).isEqualTo(workDir.toPath());
assertThat(project.getEncoding()).isEqualTo(Charset.defaultCharset());
assertThat(project.properties()).hasSize(5);
assertThat(project.isFile()).isFalse();
}
@Test
public void testEncoding() throws IOException {
ProjectDefinition def = ProjectDefinition.create();
def.setKey("projectKey");
def.setName("projectName");
File baseDir = temp.newFolder();
def.setBaseDir(baseDir);
def.setProjectVersion("version");
def.setDescription("desc");
File workDir = temp.newFolder();
def.setWorkDir(workDir);
def.setSources("file1");
def.setProperty("sonar.sourceEncoding", "UTF-16");
AbstractProjectOrModule project = new DefaultInputProject(def);
assertThat(project.getEncoding()).isEqualTo(StandardCharsets.UTF_16);
}
}
| 3,192 | 35.284091 | 103 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/fs/internal/fs/FileMetadataTest.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.api.batch.fs.internal.fs;
import java.io.File;
import java.io.FileInputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import javax.annotation.Nullable;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.slf4j.event.Level;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.FileMetadata;
import org.sonar.api.batch.fs.internal.Metadata;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.notifications.AnalysisWarnings;
import org.sonar.api.testfixtures.log.LogTester;
import static org.apache.commons.codec.digest.DigestUtils.md5Hex;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class FileMetadataTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Rule
public LogTester logTester = new LogTester();
private AnalysisWarnings analysisWarnings = mock(AnalysisWarnings.class);
@Test
public void empty_file() throws Exception {
File tempFile = temp.newFile();
FileUtils.touch(tempFile);
Metadata metadata = new FileMetadata(analysisWarnings).readMetadata(new FileInputStream(tempFile), StandardCharsets.UTF_8, tempFile.getName());
assertThat(metadata.lines()).isOne();
assertThat(metadata.nonBlankLines()).isZero();
assertThat(metadata.hash()).isNotEmpty();
assertThat(metadata.originalLineStartOffsets()).containsOnly(0);
assertThat(metadata.originalLineEndOffsets()).containsOnly(0);
assertThat(metadata.isEmpty()).isTrue();
}
@Test
public void windows_without_latest_eol() throws Exception {
File tempFile = temp.newFile();
FileUtils.write(tempFile, "foo\r\nbar\r\nbaz", StandardCharsets.UTF_8, true);
Metadata metadata = new FileMetadata(analysisWarnings).readMetadata(new FileInputStream(tempFile), StandardCharsets.UTF_8, tempFile.getName());
assertThat(metadata.lines()).isEqualTo(3);
assertThat(metadata.nonBlankLines()).isEqualTo(3);
assertThat(metadata.hash()).isEqualTo(md5Hex("foo\nbar\nbaz"));
assertThat(metadata.originalLineStartOffsets()).containsOnly(0, 5, 10);
assertThat(metadata.originalLineEndOffsets()).containsOnly(3, 8, 13);
assertThat(metadata.isEmpty()).isFalse();
}
@Test
public void read_with_wrong_encoding() throws Exception {
File tempFile = temp.newFile();
FileUtils.write(tempFile, "marker´s\n", Charset.forName("cp1252"));
Metadata metadata = new FileMetadata(analysisWarnings).readMetadata(new FileInputStream(tempFile), StandardCharsets.UTF_8, tempFile.getName());
assertThat(metadata.lines()).isEqualTo(2);
assertThat(metadata.hash()).isEqualTo(md5Hex("marker\ufffds\n"));
assertThat(metadata.originalLineStartOffsets()).containsOnly(0, 9);
}
@Test
public void non_ascii_utf_8() throws Exception {
File tempFile = temp.newFile();
FileUtils.write(tempFile, "föo\r\nbàr\r\n\u1D11Ebaßz\r\n", StandardCharsets.UTF_8, true);
Metadata metadata = new FileMetadata(analysisWarnings).readMetadata(new FileInputStream(tempFile), StandardCharsets.UTF_8, tempFile.getName());
assertThat(metadata.lines()).isEqualTo(4);
assertThat(metadata.nonBlankLines()).isEqualTo(3);
assertThat(metadata.hash()).isEqualTo(md5Hex("föo\nbàr\n\u1D11Ebaßz\n"));
assertThat(metadata.originalLineStartOffsets()).containsOnly(0, 5, 10, 18);
}
@Test
public void non_ascii_utf_16() throws Exception {
File tempFile = temp.newFile();
FileUtils.write(tempFile, "föo\r\nbàr\r\n\u1D11Ebaßz\r\n", StandardCharsets.UTF_16, true);
Metadata metadata = new FileMetadata(analysisWarnings).readMetadata(new FileInputStream(tempFile), StandardCharsets.UTF_16, tempFile.getName());
assertThat(metadata.lines()).isEqualTo(4);
assertThat(metadata.nonBlankLines()).isEqualTo(3);
assertThat(metadata.hash()).isEqualTo(md5Hex("föo\nbàr\n\u1D11Ebaßz\n".getBytes(StandardCharsets.UTF_8)));
assertThat(metadata.originalLineStartOffsets()).containsOnly(0, 5, 10, 18);
}
@Test
public void unix_without_latest_eol() throws Exception {
File tempFile = temp.newFile();
FileUtils.write(tempFile, "foo\nbar\nbaz", StandardCharsets.UTF_8, true);
Metadata metadata = new FileMetadata(analysisWarnings).readMetadata(new FileInputStream(tempFile), StandardCharsets.UTF_8, tempFile.getName());
assertThat(metadata.lines()).isEqualTo(3);
assertThat(metadata.nonBlankLines()).isEqualTo(3);
assertThat(metadata.hash()).isEqualTo(md5Hex("foo\nbar\nbaz"));
assertThat(metadata.originalLineStartOffsets()).containsOnly(0, 4, 8);
assertThat(metadata.originalLineEndOffsets()).containsOnly(3, 7, 11);
assertThat(metadata.isEmpty()).isFalse();
}
@Test
public void unix_with_latest_eol() throws Exception {
File tempFile = temp.newFile();
FileUtils.write(tempFile, "foo\nbar\nbaz\n", StandardCharsets.UTF_8, true);
Metadata metadata = new FileMetadata(analysisWarnings).readMetadata(new FileInputStream(tempFile), StandardCharsets.UTF_8, tempFile.getName());
assertThat(metadata.lines()).isEqualTo(4);
assertThat(metadata.nonBlankLines()).isEqualTo(3);
assertThat(metadata.hash()).isEqualTo(md5Hex("foo\nbar\nbaz\n"));
assertThat(metadata.originalLineStartOffsets()).containsOnly(0, 4, 8, 12);
assertThat(metadata.originalLineEndOffsets()).containsOnly(3, 7, 11, 12);
}
@Test
public void mac_without_latest_eol() throws Exception {
File tempFile = temp.newFile();
FileUtils.write(tempFile, "foo\rbar\rbaz", StandardCharsets.UTF_8, true);
Metadata metadata = new FileMetadata(analysisWarnings).readMetadata(new FileInputStream(tempFile), StandardCharsets.UTF_8, tempFile.getName());
assertThat(metadata.lines()).isEqualTo(3);
assertThat(metadata.nonBlankLines()).isEqualTo(3);
assertThat(metadata.hash()).isEqualTo(md5Hex("foo\nbar\nbaz"));
assertThat(metadata.originalLineStartOffsets()).containsOnly(0, 4, 8);
assertThat(metadata.originalLineEndOffsets()).containsOnly(3, 7, 11);
}
@Test
public void mac_with_latest_eol() throws Exception {
File tempFile = temp.newFile();
FileUtils.write(tempFile, "foo\rbar\rbaz\r", StandardCharsets.UTF_8, true);
Metadata metadata = new FileMetadata(analysisWarnings).readMetadata(new FileInputStream(tempFile), StandardCharsets.UTF_8, tempFile.getName());
assertThat(metadata.lines()).isEqualTo(4);
assertThat(metadata.nonBlankLines()).isEqualTo(3);
assertThat(metadata.hash()).isEqualTo(md5Hex("foo\nbar\nbaz\n"));
assertThat(metadata.originalLineStartOffsets()).containsOnly(0, 4, 8, 12);
assertThat(metadata.originalLineEndOffsets()).containsOnly(3, 7, 11, 12);
}
@Test
public void mix_of_newlines_with_latest_eol() throws Exception {
File tempFile = temp.newFile();
FileUtils.write(tempFile, "foo\nbar\r\nbaz\n", StandardCharsets.UTF_8, true);
Metadata metadata = new FileMetadata(analysisWarnings).readMetadata(new FileInputStream(tempFile), StandardCharsets.UTF_8, tempFile.getName());
assertThat(metadata.lines()).isEqualTo(4);
assertThat(metadata.nonBlankLines()).isEqualTo(3);
assertThat(metadata.hash()).isEqualTo(md5Hex("foo\nbar\nbaz\n"));
assertThat(metadata.originalLineStartOffsets()).containsOnly(0, 4, 9, 13);
assertThat(metadata.originalLineEndOffsets()).containsOnly(3, 7, 12, 13);
}
@Test
public void several_new_lines() throws Exception {
File tempFile = temp.newFile();
FileUtils.write(tempFile, "foo\n\n\nbar", StandardCharsets.UTF_8, true);
Metadata metadata = new FileMetadata(analysisWarnings).readMetadata(new FileInputStream(tempFile), StandardCharsets.UTF_8, tempFile.getName());
assertThat(metadata.lines()).isEqualTo(4);
assertThat(metadata.nonBlankLines()).isEqualTo(2);
assertThat(metadata.hash()).isEqualTo(md5Hex("foo\n\n\nbar"));
assertThat(metadata.originalLineStartOffsets()).containsOnly(0, 4, 5, 6);
assertThat(metadata.originalLineEndOffsets()).containsOnly(3, 4, 5, 9);
}
@Test
public void mix_of_newlines_without_latest_eol() throws Exception {
File tempFile = temp.newFile();
FileUtils.write(tempFile, "foo\nbar\r\nbaz", StandardCharsets.UTF_8, true);
Metadata metadata = new FileMetadata(analysisWarnings).readMetadata(new FileInputStream(tempFile), StandardCharsets.UTF_8, tempFile.getName());
assertThat(metadata.lines()).isEqualTo(3);
assertThat(metadata.nonBlankLines()).isEqualTo(3);
assertThat(metadata.hash()).isEqualTo(md5Hex("foo\nbar\nbaz"));
assertThat(metadata.originalLineStartOffsets()).containsOnly(0, 4, 9);
assertThat(metadata.originalLineEndOffsets()).containsOnly(3, 7, 12);
}
@Test
public void start_with_newline() throws Exception {
File tempFile = temp.newFile();
FileUtils.write(tempFile, "\nfoo\nbar\r\nbaz", StandardCharsets.UTF_8, true);
Metadata metadata = new FileMetadata(analysisWarnings).readMetadata(new FileInputStream(tempFile), StandardCharsets.UTF_8, tempFile.getName());
assertThat(metadata.lines()).isEqualTo(4);
assertThat(metadata.nonBlankLines()).isEqualTo(3);
assertThat(metadata.hash()).isEqualTo(md5Hex("\nfoo\nbar\nbaz"));
assertThat(metadata.originalLineStartOffsets()).containsOnly(0, 1, 5, 10);
assertThat(metadata.originalLineEndOffsets()).containsOnly(0, 4, 8, 13);
}
@Test
public void ignore_whitespace_when_computing_line_hashes() throws Exception {
File tempFile = temp.newFile();
FileUtils.write(tempFile, " foo\nb ar\r\nbaz \t", StandardCharsets.UTF_8, true);
DefaultInputFile f = new TestInputFileBuilder("foo", tempFile.getName())
.setModuleBaseDir(tempFile.getParentFile().toPath())
.setCharset(StandardCharsets.UTF_8)
.build();
FileMetadata.computeLineHashesForIssueTracking(f, new FileMetadata.LineHashConsumer() {
@Override
public void consume(int lineIdx, @Nullable byte[] hash) {
switch (lineIdx) {
case 1:
assertThat(Hex.encodeHexString(hash)).isEqualTo(md5Hex("foo"));
break;
case 2:
assertThat(Hex.encodeHexString(hash)).isEqualTo(md5Hex("bar"));
break;
case 3:
assertThat(Hex.encodeHexString(hash)).isEqualTo(md5Hex("baz"));
break;
default:
fail("Invalid line");
}
}
});
}
@Test
public void dont_fail_on_empty_file() throws Exception {
File tempFile = temp.newFile();
FileUtils.write(tempFile, "", StandardCharsets.UTF_8, true);
DefaultInputFile f = new TestInputFileBuilder("foo", tempFile.getName())
.setModuleBaseDir(tempFile.getParentFile().toPath())
.setCharset(StandardCharsets.UTF_8)
.build();
FileMetadata.computeLineHashesForIssueTracking(f, new FileMetadata.LineHashConsumer() {
@Override
public void consume(int lineIdx, @Nullable byte[] hash) {
switch (lineIdx) {
case 1:
assertThat(hash).isNull();
break;
default:
fail("Invalid line");
}
}
});
}
@Test
public void line_feed_is_included_into_hash() throws Exception {
File file1 = temp.newFile();
FileUtils.write(file1, "foo\nbar\n", StandardCharsets.UTF_8, true);
// same as file1, except an additional return carriage
File file1a = temp.newFile();
FileUtils.write(file1a, "foo\r\nbar\n", StandardCharsets.UTF_8, true);
File file2 = temp.newFile();
FileUtils.write(file2, "foo\nbar", StandardCharsets.UTF_8, true);
String hash1 = new FileMetadata(analysisWarnings).readMetadata(new FileInputStream(file1), StandardCharsets.UTF_8, file1.getName()).hash();
String hash1a = new FileMetadata(analysisWarnings).readMetadata(new FileInputStream(file1a), StandardCharsets.UTF_8, file1a.getName()).hash();
String hash2 = new FileMetadata(analysisWarnings).readMetadata(new FileInputStream(file2), StandardCharsets.UTF_8, file2.getName()).hash();
assertThat(hash1)
.isEqualTo(hash1a)
.isNotEqualTo(hash2);
}
@Test
public void binary_file_with_unmappable_character() throws Exception {
File woff = new File(this.getClass().getResource("glyphicons-halflings-regular.woff").toURI());
Metadata metadata = new FileMetadata(analysisWarnings).readMetadata(new FileInputStream(woff), StandardCharsets.UTF_8, woff.getAbsolutePath());
assertThat(metadata.lines()).isEqualTo(135);
assertThat(metadata.nonBlankLines()).isEqualTo(133);
assertThat(metadata.hash()).isNotEmpty();
assertThat(logTester.logs(Level.WARN).get(0)).contains("Invalid character encountered in file");
verify(analysisWarnings).addUnique("There are problems with file encoding in the source code. Please check the scanner logs for more details.");
assertThat(logTester.logs(Level.WARN).get(0)).contains(
"glyphicons-halflings-regular.woff at line 1 for encoding UTF-8. Please fix file content or configure the encoding to be used using property 'sonar.sourceEncoding'.");
}
}
| 14,156 | 43.800633 | 173 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/fs/internal/fs/MetadataTest.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.api.batch.fs.internal.fs;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import org.sonar.api.batch.fs.internal.Metadata;
public class MetadataTest {
@Test
public void testRoundtrip() {
Metadata metadata = new Metadata(10, 20, "hash", new int[] {1, 3}, new int[] {2, 4}, 5);
assertThat(metadata.isEmpty()).isFalse();
assertThat(metadata.lines()).isEqualTo(10);
assertThat(metadata.nonBlankLines()).isEqualTo(20);
assertThat(metadata.originalLineStartOffsets()).isEqualTo(new int[] {1, 3});
assertThat(metadata.originalLineEndOffsets()).isEqualTo(new int[] {2, 4});
assertThat(metadata.lastValidOffset()).isEqualTo(5);
assertThat(metadata.hash()).isEqualTo("hash");
}
}
| 1,605 | 39.15 | 92 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/fs/internal/fs/PathPatternTest.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.api.batch.fs.internal.fs;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.IndexedFile;
import org.sonar.api.batch.fs.internal.DefaultIndexedFile;
import org.sonar.api.batch.fs.internal.PathPattern;
import static org.assertj.core.api.Assertions.assertThat;
public class PathPatternTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private Path baseDir;
@Before
public void setUp() throws IOException {
baseDir = temp.newFolder().toPath();
}
@Test
public void match_relative_path() {
PathPattern pattern = PathPattern.create("**/*Foo.java");
assertThat(pattern).hasToString("**/*Foo.java");
IndexedFile indexedFile = new DefaultIndexedFile("ABCDE", baseDir, "src/main/java/org/MyFoo.java", null);
assertThat(pattern.match(indexedFile.path(), Paths.get(indexedFile.relativePath()))).isTrue();
// case sensitive by default
indexedFile = new DefaultIndexedFile("ABCDE", baseDir, "src/main/java/org/MyFoo.JAVA", null);
assertThat(pattern.match(indexedFile.path(), Paths.get(indexedFile.relativePath()))).isFalse();
indexedFile = new DefaultIndexedFile("ABCDE", baseDir, "src/main/java/org/Other.java", null);
assertThat(pattern.match(indexedFile.path(), Paths.get(indexedFile.relativePath()))).isFalse();
}
@Test
public void match_relative_path_and_insensitive_file_extension() {
PathPattern pattern = PathPattern.create("**/*Foo.java");
IndexedFile indexedFile = new DefaultIndexedFile("ABCDE", baseDir, "src/main/java/org/MyFoo.JAVA", null);
assertThat(pattern.match(indexedFile.path(), Paths.get(indexedFile.relativePath()), false)).isTrue();
indexedFile = new DefaultIndexedFile("ABCDE", baseDir, "src/main/java/org/Other.java", null);
assertThat(pattern.match(indexedFile.path(), Paths.get(indexedFile.relativePath()), false)).isFalse();
}
@Test
public void match_absolute_path() {
PathPattern pattern = PathPattern.create("file:**/src/main/**Foo.java");
assertThat(pattern).hasToString("file:**/src/main/**Foo.java");
IndexedFile indexedFile = new DefaultIndexedFile("ABCDE", baseDir, "src/main/java/org/MyFoo.java", null);
assertThat(pattern.match(indexedFile.path(), Paths.get(indexedFile.relativePath()))).isTrue();
// case sensitive by default
indexedFile = new DefaultIndexedFile("ABCDE", baseDir, "src/main/java/org/MyFoo.JAVA", null);
assertThat(pattern.match(indexedFile.path(), Paths.get(indexedFile.relativePath()))).isFalse();
indexedFile = new DefaultIndexedFile("ABCDE", baseDir, "src/main/java/org/Other.java", null);
assertThat(pattern.match(indexedFile.path(), Paths.get(indexedFile.relativePath()))).isFalse();
}
@Test
public void match_absolute_path_and_insensitive_file_extension() {
PathPattern pattern = PathPattern.create("file:**/src/main/**Foo.java");
assertThat(pattern).hasToString("file:**/src/main/**Foo.java");
IndexedFile indexedFile = new DefaultIndexedFile("ABCDE", baseDir, "src/main/java/org/MyFoo.JAVA", null);
assertThat(pattern.match(indexedFile.path(), Paths.get(indexedFile.relativePath()), false)).isTrue();
indexedFile = new DefaultIndexedFile("ABCDE", baseDir, "src/main/java/org/Other.JAVA", null);
assertThat(pattern.match(indexedFile.path(), Paths.get(indexedFile.relativePath()), false)).isFalse();
}
@Test
public void create_array_of_patterns() {
PathPattern[] patterns = PathPattern.create(new String[] {
"**/src/main/**Foo.java",
"file:**/src/main/**Bar.java"
});
assertThat(patterns).hasSize(2);
assertThat(patterns[0]).hasToString("**/src/main/**Foo.java");
assertThat(patterns[1]).hasToString("file:**/src/main/**Bar.java");
}
}
| 4,747 | 41.774775 | 109 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/fs/internal/fs/TestInputFileBuilderTest.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.api.batch.fs.internal.fs;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.LinkOption;
import org.apache.commons.io.IOUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.InputFile.Status;
import org.sonar.api.batch.fs.InputFile.Type;
import org.sonar.api.batch.fs.internal.AbstractProjectOrModule;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import static org.assertj.core.api.Assertions.assertThat;
public class TestInputFileBuilderTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Test
public void setContent() throws IOException {
DefaultInputFile file = TestInputFileBuilder.create("module", "invalidPath")
.setContents("my content")
.setCharset(StandardCharsets.UTF_8)
.build();
assertThat(file.contents()).isEqualTo("my content");
assertThat(IOUtils.toString(file.inputStream())).isEqualTo("my content");
}
@Test
public void testGetters() {
DefaultInputFile file = TestInputFileBuilder.create("module", new File("baseDir"), new File("baseDir", "path"))
.setStatus(Status.SAME)
.setType(Type.MAIN)
.build();
assertThat(file.type()).isEqualTo(Type.MAIN);
assertThat(file.status()).isEqualTo(Status.SAME);
assertThat(file.isPublished()).isTrue();
assertThat(file.type()).isEqualTo(Type.MAIN);
assertThat(file.relativePath()).isEqualTo("path");
assertThat(file.absolutePath()).isEqualTo("baseDir/path");
}
@Test
public void testCreateInputModule() throws IOException {
File baseDir = temp.newFolder();
AbstractProjectOrModule module = TestInputFileBuilder.newDefaultInputModule("key", baseDir);
assertThat(module.key()).isEqualTo("key");
assertThat(module.getBaseDir()).isEqualTo(baseDir.toPath().toRealPath(LinkOption.NOFOLLOW_LINKS));
}
}
| 2,852 | 36.051948 | 115 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/fs/internal/predicates/AndPredicateTest.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.api.batch.fs.internal.predicates;
import java.util.Arrays;
import org.junit.Test;
import org.sonar.api.batch.fs.FilePredicate;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.PathPattern;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class AndPredicateTest {
@Test
public void flattenNestedAnd() {
PathPatternPredicate pathPatternPredicate1 = new PathPatternPredicate(PathPattern.create("foo1/**"));
PathPatternPredicate pathPatternPredicate2 = new PathPatternPredicate(PathPattern.create("foo2/**"));
PathPatternPredicate pathPatternPredicate3 = new PathPatternPredicate(PathPattern.create("foo3/**"));
FilePredicate andPredicate = AndPredicate.create(Arrays.asList(pathPatternPredicate1,
AndPredicate.create(Arrays.asList(pathPatternPredicate2, pathPatternPredicate3))));
assertThat(((AndPredicate) andPredicate).predicates()).containsExactly(pathPatternPredicate1, pathPatternPredicate2, pathPatternPredicate3);
}
@Test
public void applyPredicates() {
PathPatternPredicate pathPatternPredicate1 = new PathPatternPredicate(PathPattern.create("foo/**"));
PathPatternPredicate pathPatternPredicate2 = new PathPatternPredicate(PathPattern.create("foo/file1"));
PathPatternPredicate pathPatternPredicate3 = new PathPatternPredicate(PathPattern.create("**"));
FilePredicate andPredicate = AndPredicate.create(Arrays.asList(pathPatternPredicate1,
AndPredicate.create(Arrays.asList(pathPatternPredicate2, pathPatternPredicate3))));
InputFile file1 = TestInputFileBuilder.create("module", "foo/file1").build();
InputFile file2 = TestInputFileBuilder.create("module", "foo2/file1").build();
InputFile file3 = TestInputFileBuilder.create("module", "foo/file2").build();
assertThat(andPredicate.apply(file1)).isTrue();
assertThat(andPredicate.apply(file2)).isFalse();
assertThat(andPredicate.apply(file3)).isFalse();
}
@Test
public void filterIndex() {
PathPatternPredicate pathPatternPredicate1 = new PathPatternPredicate(PathPattern.create("foo/**"));
PathPatternPredicate pathPatternPredicate2 = new PathPatternPredicate(PathPattern.create("foo/file1"));
PathPatternPredicate pathPatternPredicate3 = new PathPatternPredicate(PathPattern.create("**"));
InputFile file1 = TestInputFileBuilder.create("module", "foo/file1").build();
InputFile file2 = TestInputFileBuilder.create("module", "foo2/file1").build();
InputFile file3 = TestInputFileBuilder.create("module", "foo/file2").build();
FileSystem.Index index = mock(FileSystem.Index.class);
when(index.inputFiles()).thenReturn(Arrays.asList(file1, file2, file3));
OptimizedFilePredicate andPredicate = (OptimizedFilePredicate) AndPredicate.create(Arrays.asList(pathPatternPredicate1,
AndPredicate.create(Arrays.asList(pathPatternPredicate2, pathPatternPredicate3))));
assertThat(andPredicate.get(index)).containsOnly(file1);
}
@Test
public void sortPredicatesByPriority() {
PathPatternPredicate pathPatternPredicate1 = new PathPatternPredicate(PathPattern.create("foo1/**"));
PathPatternPredicate pathPatternPredicate2 = new PathPatternPredicate(PathPattern.create("foo2/**"));
RelativePathPredicate relativePathPredicate = new RelativePathPredicate("foo");
FilePredicate andPredicate = AndPredicate.create(Arrays.asList(pathPatternPredicate1,
relativePathPredicate, pathPatternPredicate2));
assertThat(((AndPredicate) andPredicate).predicates()).containsExactly(relativePathPredicate, pathPatternPredicate1, pathPatternPredicate2);
}
@Test
public void simplifyAndExpressionsWhenEmpty() {
FilePredicate andPredicate = AndPredicate.create(Arrays.asList());
assertThat(andPredicate).isEqualTo(TruePredicate.TRUE);
}
@Test
public void simplifyAndExpressionsWhenTrue() {
PathPatternPredicate pathPatternPredicate1 = new PathPatternPredicate(PathPattern.create("foo1/**"));
PathPatternPredicate pathPatternPredicate2 = new PathPatternPredicate(PathPattern.create("foo2/**"));
FilePredicate andPredicate = AndPredicate.create(Arrays.asList(pathPatternPredicate1,
TruePredicate.TRUE, pathPatternPredicate2));
assertThat(((AndPredicate) andPredicate).predicates()).containsExactly(pathPatternPredicate1, pathPatternPredicate2);
}
@Test
public void simplifyAndExpressionsWhenFalse() {
PathPatternPredicate pathPatternPredicate1 = new PathPatternPredicate(PathPattern.create("foo1/**"));
PathPatternPredicate pathPatternPredicate2 = new PathPatternPredicate(PathPattern.create("foo2/**"));
FilePredicate andPredicate = AndPredicate.create(Arrays.asList(pathPatternPredicate1,
FalsePredicate.FALSE, pathPatternPredicate2));
assertThat(andPredicate).isEqualTo(FalsePredicate.FALSE);
}
}
| 5,870 | 49.179487 | 144 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/fs/internal/predicates/ChangedFilePredicateTest.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.api.batch.fs.internal.predicates;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.sonar.api.batch.fs.FilePredicate;
import org.sonar.api.batch.fs.InputFile;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class ChangedFilePredicateTest {
private final FilePredicate predicate = mock(FilePredicate.class);
private final InputFile inputFile = mock(InputFile.class);
private final ChangedFilePredicate underTest = new ChangedFilePredicate(predicate);
@Test
public void apply_when_file_is_changed_and_predicate_is_true() {
when(inputFile.status()).thenReturn(InputFile.Status.CHANGED);
when(predicate.apply(inputFile)).thenReturn(true);
Assertions.assertThat(underTest.apply(inputFile)).isTrue();
verify(predicate, times(1)).apply(any());
verify(inputFile, times(1)).status();
}
@Test
public void apply_when_file_is_added_and_predicate_is_true() {
when(inputFile.status()).thenReturn(InputFile.Status.ADDED);
when(predicate.apply(inputFile)).thenReturn(true);
Assertions.assertThat(underTest.apply(inputFile)).isTrue();
verify(predicate, times(1)).apply(any());
verify(inputFile, times(1)).status();
}
@Test
public void do_not_apply_when_file_is_same_and_predicate_is_true() {
when(inputFile.status()).thenReturn(InputFile.Status.SAME);
when(predicate.apply(inputFile)).thenReturn(true);
Assertions.assertThat(underTest.apply(inputFile)).isFalse();
verify(predicate, times(1)).apply(any());
verify(inputFile, times(1)).status();
}
@Test
public void predicate_is_evaluated_before_file_status() {
when(predicate.apply(inputFile)).thenReturn(false);
Assertions.assertThat(underTest.apply(inputFile)).isFalse();
verify(inputFile, never()).status();
}
@Test
public void do_not_apply_when_file_is_same_and_predicate_is_false() {
when(inputFile.status()).thenReturn(InputFile.Status.SAME);
when(predicate.apply(inputFile)).thenReturn(true);
Assertions.assertThat(underTest.apply(inputFile)).isFalse();
verify(predicate, times(1)).apply(any());
verify(inputFile, times(1)).status();
}
}
| 3,222 | 32.926316 | 85 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/fs/internal/predicates/DefaultFilePredicatesTest.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.api.batch.fs.internal.predicates;
import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collections;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.fs.FilePredicate;
import org.sonar.api.batch.fs.FilePredicates;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.InputFile.Status;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import static org.assertj.core.api.Assertions.assertThat;
public class DefaultFilePredicatesTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private Path moduleBasePath;
@Before
public void setUp() throws IOException {
moduleBasePath = temp.newFolder().toPath();
}
InputFile javaFile;
FilePredicates predicates;
@Before
public void before() throws IOException {
predicates = new DefaultFilePredicates(temp.newFolder().toPath());
javaFile = new TestInputFileBuilder("foo", "src/main/java/struts/Action.java")
.setModuleBaseDir(moduleBasePath)
.setLanguage("java")
.setStatus(Status.SAME)
.build();
}
@Test
public void all() {
assertThat(predicates.all().apply(javaFile)).isTrue();
}
@Test
public void none() {
assertThat(predicates.none().apply(javaFile)).isFalse();
}
@Test
public void matches_inclusion_pattern() {
assertThat(predicates.matchesPathPattern("src/main/**/Action.java").apply(javaFile)).isTrue();
assertThat(predicates.matchesPathPattern("Action.java").apply(javaFile)).isFalse();
assertThat(predicates.matchesPathPattern("src/**/*.php").apply(javaFile)).isFalse();
}
@Test
public void matches_inclusion_patterns() {
assertThat(predicates.matchesPathPatterns(new String[] {"src/other/**.java", "src/main/**/Action.java"}).apply(javaFile)).isTrue();
assertThat(predicates.matchesPathPatterns(new String[] {}).apply(javaFile)).isTrue();
assertThat(predicates.matchesPathPatterns(new String[] {"src/other/**.java", "src/**/*.php"}).apply(javaFile)).isFalse();
}
@Test
public void does_not_match_exclusion_pattern() {
assertThat(predicates.doesNotMatchPathPattern("src/main/**/Action.java").apply(javaFile)).isFalse();
assertThat(predicates.doesNotMatchPathPattern("Action.java").apply(javaFile)).isTrue();
assertThat(predicates.doesNotMatchPathPattern("src/**/*.php").apply(javaFile)).isTrue();
}
@Test
public void does_not_match_exclusion_patterns() {
assertThat(predicates.doesNotMatchPathPatterns(new String[] {}).apply(javaFile)).isTrue();
assertThat(predicates.doesNotMatchPathPatterns(new String[] {"src/other/**.java", "src/**/*.php"}).apply(javaFile)).isTrue();
assertThat(predicates.doesNotMatchPathPatterns(new String[] {"src/other/**.java", "src/main/**/Action.java"}).apply(javaFile)).isFalse();
}
@Test
public void has_relative_path() {
assertThat(predicates.hasRelativePath("src/main/java/struts/Action.java").apply(javaFile)).isTrue();
assertThat(predicates.hasRelativePath("src/main/java/struts/Other.java").apply(javaFile)).isFalse();
// path is normalized
assertThat(predicates.hasRelativePath("src/main/java/../java/struts/Action.java").apply(javaFile)).isTrue();
assertThat(predicates.hasRelativePath("src\\main\\java\\struts\\Action.java").apply(javaFile)).isTrue();
assertThat(predicates.hasRelativePath("src\\main\\java\\struts\\Other.java").apply(javaFile)).isFalse();
assertThat(predicates.hasRelativePath("src\\main\\java\\struts\\..\\struts\\Action.java").apply(javaFile)).isTrue();
}
@Test
public void has_absolute_path() throws Exception {
String path = javaFile.file().getAbsolutePath();
assertThat(predicates.hasAbsolutePath(path).apply(javaFile)).isTrue();
assertThat(predicates.hasAbsolutePath(path.replaceAll("/", "\\\\")).apply(javaFile)).isTrue();
assertThat(predicates.hasAbsolutePath(temp.newFile().getAbsolutePath()).apply(javaFile)).isFalse();
assertThat(predicates.hasAbsolutePath("src/main/java/struts/Action.java").apply(javaFile)).isFalse();
}
@Test
public void has_uri() throws Exception {
URI uri = javaFile.uri();
assertThat(predicates.hasURI(uri).apply(javaFile)).isTrue();
assertThat(predicates.hasURI(temp.newFile().toURI()).apply(javaFile)).isFalse();
}
@Test
public void has_path() throws Exception {
// is relative path
assertThat(predicates.hasPath("src/main/java/struts/Action.java").apply(javaFile)).isTrue();
assertThat(predicates.hasPath("src/main/java/struts/Other.java").apply(javaFile)).isFalse();
// is absolute path
String path = javaFile.file().getAbsolutePath();
assertThat(predicates.hasAbsolutePath(path).apply(javaFile)).isTrue();
assertThat(predicates.hasPath(temp.newFile().getAbsolutePath()).apply(javaFile)).isFalse();
}
@Test
public void is_file() throws Exception {
Files.createParentDirs(javaFile.file());
Files.touch(javaFile.file());
// relative file
Path relativePath = moduleBasePath.relativize(javaFile.path());
assertThat(predicates.is(relativePath.toFile()).apply(javaFile)).isTrue();
// absolute file
assertThat(predicates.is(javaFile.file()).apply(javaFile)).isTrue();
assertThat(predicates.is(javaFile.file().getAbsoluteFile()).apply(javaFile)).isTrue();
assertThat(predicates.is(new File(javaFile.file().toURI())).apply(javaFile)).isTrue();
assertThat(predicates.is(temp.newFile()).apply(javaFile)).isFalse();
}
@Test
public void has_language() {
assertThat(predicates.hasLanguage("java").apply(javaFile)).isTrue();
assertThat(predicates.hasLanguage("php").apply(javaFile)).isFalse();
}
@Test
public void has_languages() {
assertThat(predicates.hasLanguages(Arrays.asList("java", "php")).apply(javaFile)).isTrue();
assertThat(predicates.hasLanguages(Arrays.asList("cobol", "php")).apply(javaFile)).isFalse();
assertThat(predicates.hasLanguages(Collections.emptyList()).apply(javaFile)).isTrue();
}
@Test
public void has_type() {
assertThat(predicates.hasType(InputFile.Type.MAIN).apply(javaFile)).isTrue();
assertThat(predicates.hasType(InputFile.Type.TEST).apply(javaFile)).isFalse();
}
@Test
public void has_status() {
assertThat(predicates.hasAnyStatus().apply(javaFile)).isTrue();
assertThat(predicates.hasStatus(InputFile.Status.SAME).apply(javaFile)).isTrue();
assertThat(predicates.hasStatus(InputFile.Status.ADDED).apply(javaFile)).isFalse();
}
@Test
public void not() {
assertThat(predicates.not(predicates.hasType(InputFile.Type.MAIN)).apply(javaFile)).isFalse();
assertThat(predicates.not(predicates.hasType(InputFile.Type.TEST)).apply(javaFile)).isTrue();
}
@Test
public void and() {
// empty
assertThat(predicates.and().apply(javaFile)).isTrue();
assertThat(predicates.and(new FilePredicate[0]).apply(javaFile)).isTrue();
assertThat(predicates.and(Collections.emptyList()).apply(javaFile)).isTrue();
// two arguments
assertThat(predicates.and(predicates.all(), predicates.all()).apply(javaFile)).isTrue();
assertThat(predicates.and(predicates.all(), predicates.none()).apply(javaFile)).isFalse();
assertThat(predicates.and(predicates.none(), predicates.all()).apply(javaFile)).isFalse();
// collection
assertThat(predicates.and(Arrays.asList(predicates.all(), predicates.all())).apply(javaFile)).isTrue();
assertThat(predicates.and(Arrays.asList(predicates.all(), predicates.none())).apply(javaFile)).isFalse();
// array
assertThat(predicates.and(new FilePredicate[] {predicates.all(), predicates.all()}).apply(javaFile)).isTrue();
assertThat(predicates.and(new FilePredicate[] {predicates.all(), predicates.none()}).apply(javaFile)).isFalse();
}
@Test
public void or() {
// empty
assertThat(predicates.or().apply(javaFile)).isTrue();
assertThat(predicates.or(new FilePredicate[0]).apply(javaFile)).isTrue();
assertThat(predicates.or(Collections.emptyList()).apply(javaFile)).isTrue();
// two arguments
assertThat(predicates.or(predicates.all(), predicates.all()).apply(javaFile)).isTrue();
assertThat(predicates.or(predicates.all(), predicates.none()).apply(javaFile)).isTrue();
assertThat(predicates.or(predicates.none(), predicates.all()).apply(javaFile)).isTrue();
assertThat(predicates.or(predicates.none(), predicates.none()).apply(javaFile)).isFalse();
// collection
assertThat(predicates.or(Arrays.asList(predicates.all(), predicates.all())).apply(javaFile)).isTrue();
assertThat(predicates.or(Arrays.asList(predicates.all(), predicates.none())).apply(javaFile)).isTrue();
assertThat(predicates.or(Arrays.asList(predicates.none(), predicates.none())).apply(javaFile)).isFalse();
// array
assertThat(predicates.or(new FilePredicate[] {predicates.all(), predicates.all()}).apply(javaFile)).isTrue();
assertThat(predicates.or(new FilePredicate[] {predicates.all(), predicates.none()}).apply(javaFile)).isTrue();
assertThat(predicates.or(new FilePredicate[] {predicates.none(), predicates.none()}).apply(javaFile)).isFalse();
}
@Test
public void hasFilename() {
assertThat(predicates.hasFilename("Action.java").apply(javaFile)).isTrue();
}
@Test
public void hasExtension() {
assertThat(predicates.hasExtension("java").apply(javaFile)).isTrue();
}
}
| 10,399 | 40.269841 | 141 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/fs/internal/predicates/FileExtensionPredicateTest.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.api.batch.fs.internal.predicates;
import java.io.IOException;
import org.junit.Test;
import org.sonar.api.batch.fs.InputFile;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.api.batch.fs.internal.predicates.FileExtensionPredicate.getExtension;
public class FileExtensionPredicateTest {
@Test
public void should_match_correct_extension() throws IOException {
FileExtensionPredicate predicate = new FileExtensionPredicate("bat");
assertThat(predicate.apply(mockWithName("prog.bat"))).isTrue();
assertThat(predicate.apply(mockWithName("prog.bat.bat"))).isTrue();
}
@Test
public void should_not_match_incorrect_extension() throws IOException {
FileExtensionPredicate predicate = new FileExtensionPredicate("bat");
assertThat(predicate.apply(mockWithName("prog.batt"))).isFalse();
assertThat(predicate.apply(mockWithName("prog.abat"))).isFalse();
assertThat(predicate.apply(mockWithName("prog."))).isFalse();
assertThat(predicate.apply(mockWithName("prog.bat."))).isFalse();
assertThat(predicate.apply(mockWithName("prog.bat.batt"))).isFalse();
assertThat(predicate.apply(mockWithName("prog"))).isFalse();
}
@Test
public void should_match_correct_extension_case_insensitively() throws IOException {
FileExtensionPredicate predicate = new FileExtensionPredicate("jAVa");
assertThat(predicate.apply(mockWithName("Program.java"))).isTrue();
assertThat(predicate.apply(mockWithName("Program.JAVA"))).isTrue();
assertThat(predicate.apply(mockWithName("Program.Java"))).isTrue();
assertThat(predicate.apply(mockWithName("Program.JaVa"))).isTrue();
}
@Test
public void test_empty_extension() {
assertThat(getExtension("prog")).isEmpty();
assertThat(getExtension("prog.")).isEmpty();
assertThat(getExtension(".")).isEmpty();
}
private InputFile mockWithName(String filename) throws IOException {
InputFile inputFile = mock(InputFile.class);
when(inputFile.filename()).thenReturn(filename);
return inputFile;
}
}
| 2,994 | 40.027397 | 93 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/fs/internal/predicates/FilenamePredicateTest.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.api.batch.fs.internal.predicates;
import java.util.Collections;
import org.junit.Test;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class FilenamePredicateTest {
@Test
public void should_match_file_by_filename() {
String filename = "some name";
InputFile inputFile = mock(InputFile.class);
when(inputFile.filename()).thenReturn(filename);
assertThat(new FilenamePredicate(filename).apply(inputFile)).isTrue();
}
@Test
public void should_not_match_file_by_different_filename() {
String filename = "some name";
InputFile inputFile = mock(InputFile.class);
when(inputFile.filename()).thenReturn(filename + "x");
assertThat(new FilenamePredicate(filename).apply(inputFile)).isFalse();
}
@Test
public void should_find_matching_file_in_index() {
String filename = "some name";
InputFile inputFile = mock(InputFile.class);
when(inputFile.filename()).thenReturn(filename);
FileSystem.Index index = mock(FileSystem.Index.class);
when(index.getFilesByName(filename)).thenReturn(Collections.singleton(inputFile));
assertThat(new FilenamePredicate(filename).get(index)).containsOnly(inputFile);
}
}
| 2,215 | 34.174603 | 86 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/fs/internal/predicates/OrPredicateTest.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.api.batch.fs.internal.predicates;
import org.junit.Test;
import org.sonar.api.batch.fs.FilePredicate;
import java.util.Arrays;
import org.sonar.api.batch.fs.internal.PathPattern;
import static org.assertj.core.api.Assertions.assertThat;
public class OrPredicateTest {
@Test
public void flattenNestedOr() {
PathPatternPredicate pathPatternPredicate1 = new PathPatternPredicate(PathPattern.create("foo1/**"));
PathPatternPredicate pathPatternPredicate2 = new PathPatternPredicate(PathPattern.create("foo2/**"));
PathPatternPredicate pathPatternPredicate3 = new PathPatternPredicate(PathPattern.create("foo3/**"));
FilePredicate orPredicate = OrPredicate.create(Arrays.asList(pathPatternPredicate1,
OrPredicate.create(Arrays.asList(pathPatternPredicate2, pathPatternPredicate3))));
assertThat(((OrPredicate) orPredicate).predicates()).containsExactly(pathPatternPredicate1, pathPatternPredicate2, pathPatternPredicate3);
}
@Test
public void simplifyOrExpressionsWhenEmpty() {
FilePredicate orPredicate = OrPredicate.create(Arrays.asList());
assertThat(orPredicate).isEqualTo(TruePredicate.TRUE);
}
@Test
public void simplifyOrExpressionsWhenFalse() {
PathPatternPredicate pathPatternPredicate1 = new PathPatternPredicate(PathPattern.create("foo1/**"));
PathPatternPredicate pathPatternPredicate2 = new PathPatternPredicate(PathPattern.create("foo2/**"));
FilePredicate andPredicate = OrPredicate.create(Arrays.asList(pathPatternPredicate1,
FalsePredicate.FALSE, pathPatternPredicate2));
assertThat(((OrPredicate) andPredicate).predicates()).containsExactly(pathPatternPredicate1, pathPatternPredicate2);
}
@Test
public void simplifyAndExpressionsWhenTrue() {
PathPatternPredicate pathPatternPredicate1 = new PathPatternPredicate(PathPattern.create("foo1/**"));
PathPatternPredicate pathPatternPredicate2 = new PathPatternPredicate(PathPattern.create("foo2/**"));
FilePredicate andPredicate = OrPredicate.create(Arrays.asList(pathPatternPredicate1,
TruePredicate.TRUE, pathPatternPredicate2));
assertThat(andPredicate).isEqualTo(TruePredicate.TRUE);
}
}
| 3,022 | 44.119403 | 142 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/fs/internal/predicates/RelativePathPredicateTest.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.api.batch.fs.internal.predicates;
import org.junit.Test;
import org.sonar.api.batch.fs.InputFile;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class RelativePathPredicateTest {
@Test
public void returns_false_when_path_is_invalid() {
RelativePathPredicate predicate = new RelativePathPredicate("..");
InputFile inputFile = mock(InputFile.class);
when(inputFile.relativePath()).thenReturn("path");
assertThat(predicate.apply(inputFile)).isFalse();
}
@Test
public void returns_true_if_matches() {
RelativePathPredicate predicate = new RelativePathPredicate("path");
InputFile inputFile = mock(InputFile.class);
when(inputFile.relativePath()).thenReturn("path");
assertThat(predicate.apply(inputFile)).isTrue();
}
@Test
public void returns_false_if_doesnt_match() {
RelativePathPredicate predicate = new RelativePathPredicate("path1");
InputFile inputFile = mock(InputFile.class);
when(inputFile.relativePath()).thenReturn("path2");
assertThat(predicate.apply(inputFile)).isFalse();
}
}
| 2,016 | 36.351852 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/rule/internal/DefaultActiveRulesTest.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.api.batch.rule.internal;
import com.google.common.collect.ImmutableSet;
import java.util.Collections;
import org.junit.Test;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.utils.WildcardPattern;
import static java.util.Collections.singleton;
import static org.assertj.core.api.Assertions.assertThat;
public class DefaultActiveRulesTest {
private final RuleKey ruleKey = RuleKey.of("repo", "rule");
@Test
public void empty_returns_nothing() {
DefaultActiveRules underTest = new DefaultActiveRules(Collections.emptyList());
assertThat(underTest.getDeprecatedRuleKeys(ruleKey)).isEmpty();
assertThat(underTest.matchesDeprecatedKeys(ruleKey, WildcardPattern.create("**"))).isFalse();
}
@Test
public void finds_match() {
DefaultActiveRules underTest = new DefaultActiveRules(ImmutableSet.of(new NewActiveRule.Builder()
.setRuleKey(ruleKey)
.setDeprecatedKeys(singleton(RuleKey.of("oldrepo", "oldrule")))
.build()));
assertThat(underTest.getDeprecatedRuleKeys(ruleKey)).containsOnly("oldrepo:oldrule");
assertThat(underTest.matchesDeprecatedKeys(ruleKey, WildcardPattern.create("oldrepo:oldrule"))).isTrue();
}
@Test
public void finds_match_with_multiple_deprecated_keys() {
DefaultActiveRules underTest = new DefaultActiveRules(ImmutableSet.of(new NewActiveRule.Builder()
.setRuleKey(ruleKey)
.setDeprecatedKeys(ImmutableSet.of(RuleKey.of("oldrepo", "oldrule"), (RuleKey.of("oldrepo2", "oldrule2"))))
.build()));
assertThat(underTest.getDeprecatedRuleKeys(ruleKey)).containsOnly("oldrepo:oldrule", "oldrepo2:oldrule2");
assertThat(underTest.matchesDeprecatedKeys(ruleKey, WildcardPattern.create("oldrepo:oldrule"))).isTrue();
}
}
| 2,596 | 39.578125 | 113 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/rule/internal/DefaultRulesTest.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.api.batch.rule.internal;
import java.util.LinkedList;
import java.util.List;
import org.junit.Test;
import org.sonar.api.rule.RuleKey;
import static org.assertj.core.api.Assertions.assertThat;
public class DefaultRulesTest {
@Test
public void testRepeatedInternalKey() {
List<NewRule> newRules = new LinkedList<>();
newRules.add(createRule("key1", "repo", "internal"));
newRules.add(createRule("key2", "repo", "internal"));
DefaultRules rules = new DefaultRules(newRules);
assertThat(rules.findByInternalKey("repo", "internal")).hasSize(2);
assertThat(rules.find(RuleKey.of("repo", "key1"))).isNotNull();
assertThat(rules.find(RuleKey.of("repo", "key2"))).isNotNull();
assertThat(rules.findByRepository("repo")).hasSize(2);
}
@Test
public void testNonExistingKey() {
List<NewRule> newRules = new LinkedList<>();
newRules.add(createRule("key1", "repo", "internal"));
newRules.add(createRule("key2", "repo", "internal"));
DefaultRules rules = new DefaultRules(newRules);
assertThat(rules.findByInternalKey("xx", "xx")).isEmpty();
assertThat(rules.find(RuleKey.of("xxx", "xx"))).isNull();
assertThat(rules.findByRepository("xxxx")).isEmpty();
}
@Test
public void testRepeatedRule() {
List<NewRule> newRules = new LinkedList<>();
newRules.add(createRule("key", "repo", "internal"));
newRules.add(createRule("key", "repo", "internal"));
DefaultRules rules = new DefaultRules(newRules);
assertThat(rules.find(RuleKey.of("repo", "key"))).isNotNull();
}
private NewRule createRule(String key, String repo, String internalKey) {
RuleKey ruleKey = RuleKey.of(repo, key);
NewRule newRule = new NewRule(ruleKey);
newRule.setInternalKey(internalKey);
return newRule;
}
}
| 2,669 | 35.575342 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/rule/internal/NewActiveRuleTest.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.api.batch.rule.internal;
import com.google.common.collect.ImmutableMap;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.batch.rule.internal.NewActiveRule;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.Severity;
import static org.assertj.core.api.Assertions.assertThat;
public class NewActiveRuleTest {
private NewActiveRule.Builder builder;
@Before
public void setBuilder() {
builder = new NewActiveRule.Builder();
}
@Test
public void builder_should_set_every_param() {
NewActiveRule rule = builder
.setRuleKey(RuleKey.of("foo", "bar"))
.setName("name")
.setSeverity(org.sonar.api.rule.Severity.CRITICAL)
.setParam("key", "value")
.setCreatedAt(1_000L)
.setUpdatedAt(1_000L)
.setInternalKey("internal_key")
.setLanguage("language")
.setTemplateRuleKey("templateRuleKey")
.setQProfileKey("qProfileKey")
.build();
assertThat(rule.ruleKey).isEqualTo(RuleKey.of("foo", "bar"));
assertThat(rule.name).isEqualTo("name");
assertThat(rule.severity).isEqualTo(org.sonar.api.rule.Severity.CRITICAL);
assertThat(rule.params).isEqualTo(ImmutableMap.of("key", "value"));
assertThat(rule.createdAt).isEqualTo(1_000L);
assertThat(rule.updatedAt).isEqualTo(1_000L);
assertThat(rule.internalKey).isEqualTo("internal_key");
assertThat(rule.language).isEqualTo("language");
assertThat(rule.templateRuleKey).isEqualTo("templateRuleKey");
assertThat(rule.qProfileKey).isEqualTo("qProfileKey");
}
@Test
public void severity_should_have_default_value() {
NewActiveRule rule = builder.build();
assertThat(rule.severity).isEqualTo(Severity.defaultSeverity());
}
@Test
public void params_should_be_empty_map_if_no_params() {
NewActiveRule rule = builder.build();
assertThat(rule.params).isEqualTo(ImmutableMap.of());
}
@Test
public void set_param_remove_param_if_value_is_null() {
NewActiveRule rule = builder
.setParam("foo", "bar")
.setParam("removed", "value")
.setParam("removed", null)
.build();
assertThat(rule.params).isEqualTo(ImmutableMap.of("foo", "bar"));
}
}
| 3,046 | 33.235955 | 78 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/rule/internal/RulesBuilderTest.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.api.batch.rule.internal;
import org.junit.Test;
import org.sonar.api.batch.rule.Rule;
import org.sonar.api.batch.rule.Rules;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.rule.Severity;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class RulesBuilderTest {
@Test
public void no_rules() {
RulesBuilder builder = new RulesBuilder();
Rules rules = builder.build();
assertThat(rules.findAll()).isEmpty();
}
@Test
public void build_rules() {
RulesBuilder builder = new RulesBuilder();
NewRule newJava1 = builder.add(RuleKey.of("java", "S0001"));
newJava1.setName("Detect bug");
newJava1.setDescription("Detect potential bug");
newJava1.setInternalKey("foo=bar");
newJava1.setSeverity(org.sonar.api.rule.Severity.CRITICAL);
newJava1.setStatus(RuleStatus.BETA);
newJava1.addParam("min");
newJava1.addParam("max").setDescription("Maximum");
// most simple rule
builder.add(RuleKey.of("java", "S0002"));
builder.add(RuleKey.of("findbugs", "NPE"));
Rules rules = builder.build();
assertThat(rules.findAll()).hasSize(3);
assertThat(rules.findByRepository("java")).hasSize(2);
assertThat(rules.findByRepository("findbugs")).hasSize(1);
assertThat(rules.findByRepository("unknown")).isEmpty();
Rule java1 = rules.find(RuleKey.of("java", "S0001"));
assertThat(java1.key().repository()).isEqualTo("java");
assertThat(java1.key().rule()).isEqualTo("S0001");
assertThat(java1.name()).isEqualTo("Detect bug");
assertThat(java1.description()).isEqualTo("Detect potential bug");
assertThat(java1.internalKey()).isEqualTo("foo=bar");
assertThat(java1.status()).isEqualTo(RuleStatus.BETA);
assertThat(java1.severity()).isEqualTo(org.sonar.api.rule.Severity.CRITICAL);
assertThat(java1.params()).hasSize(2);
assertThat(java1.param("min").key()).isEqualTo("min");
assertThat(java1.param("min").description()).isNull();
assertThat(java1.param("max").key()).isEqualTo("max");
assertThat(java1.param("max").description()).isEqualTo("Maximum");
Rule java2 = rules.find(RuleKey.of("java", "S0002"));
assertThat(java2.key().repository()).isEqualTo("java");
assertThat(java2.key().rule()).isEqualTo("S0002");
assertThat(java2.description()).isNull();
assertThat(java2.internalKey()).isNull();
assertThat(java2.status()).isEqualTo(RuleStatus.defaultStatus());
assertThat(java2.severity()).isEqualTo(Severity.defaultSeverity());
assertThat(java2.params()).isEmpty();
}
@Test
public void fail_to_add_twice_the_same_rule() {
RulesBuilder builder = new RulesBuilder();
builder.add(RuleKey.of("java", "S0001"));
assertThatThrownBy(() -> builder.add(RuleKey.of("java", "S0001")))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Rule 'java:S0001' already exists");
}
@Test
public void fail_to_add_twice_the_same_param() {
RulesBuilder builder = new RulesBuilder();
NewRule newRule = builder.add(RuleKey.of("java", "S0001"));
newRule.addParam("min");
newRule.addParam("max");
assertThatThrownBy(() -> newRule.addParam("min"))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Parameter 'min' already exists on rule 'java:S0001'");
}
}
| 4,260 | 38.091743 | 81 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/sensor/code/internal/DefaultSignificantCodeTest.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.api.batch.sensor.code.internal;
import org.junit.Test;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.sensor.internal.SensorStorage;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class DefaultSignificantCodeTest {
private SensorStorage sensorStorage = mock(SensorStorage.class);
private DefaultSignificantCode underTest = new DefaultSignificantCode(sensorStorage);
private InputFile inputFile = TestInputFileBuilder.create("module", "file1.xoo")
.setContents("this is\na file\n with some code")
.build();
@Test
public void should_save_ranges() {
underTest.onFile(inputFile)
.addRange(inputFile.selectLine(1))
.save();
verify(sensorStorage).store(underTest);
}
@Test
public void fail_if_save_without_file() {
assertThatThrownBy(() -> underTest.save())
.isInstanceOf(IllegalStateException.class)
.hasMessage("Call onFile() first");
}
@Test
public void fail_if_add_range_to_same_line_twice() {
underTest.onFile(inputFile);
underTest.addRange(inputFile.selectLine(1));
assertThatThrownBy(() -> underTest.addRange(inputFile.selectLine(1)))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Significant code was already reported for line '1'.");
}
@Test
public void fail_if_range_includes_many_lines() {
underTest.onFile(inputFile);
assertThatThrownBy(() -> underTest.addRange(inputFile.newRange(1, 1, 2, 1)))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Ranges of significant code must be located in a single line");
}
@Test
public void fail_if_add_range_before_setting_file() {
assertThatThrownBy(() -> underTest.addRange(inputFile.selectLine(1)))
.isInstanceOf(IllegalStateException.class)
.hasMessage("addRange() should be called after on()");
}
}
| 2,878 | 35.443038 | 87 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/sensor/cpd/internal/DefaultCpdTokensTest.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.api.batch.sensor.cpd.internal;
import org.junit.Test;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.sensor.internal.SensorStorage;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.tuple;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
public class DefaultCpdTokensTest {
private final SensorStorage sensorStorage = mock(SensorStorage.class);
private final DefaultInputFile inputFile = new TestInputFileBuilder("foo", "src/Foo.java")
.setLines(2)
.setOriginalLineStartOffsets(new int[] {0, 50})
.setOriginalLineEndOffsets(new int[] {49, 100})
.setLastValidOffset(101)
.build();
@Test
public void save_no_tokens() {
DefaultCpdTokens tokens = new DefaultCpdTokens(sensorStorage)
.onFile(inputFile);
tokens.save();
verify(sensorStorage).store(tokens);
assertThat(tokens.inputFile()).isEqualTo(inputFile);
}
@Test
public void save_one_token() {
DefaultCpdTokens tokens = new DefaultCpdTokens(sensorStorage)
.onFile(inputFile)
.addToken(inputFile.newRange(1, 2, 1, 5), "foo");
tokens.save();
verify(sensorStorage).store(tokens);
assertThat(tokens.getTokenLines()).extracting("value", "startLine", "hashCode", "startUnit", "endUnit").containsExactly(tuple("foo", 1, "foo".hashCode(), 1, 1));
}
@Test
public void handle_exclusions() {
inputFile.setExcludedForDuplication(true);
DefaultCpdTokens tokens = new DefaultCpdTokens(sensorStorage)
.onFile(inputFile)
.addToken(inputFile.newRange(1, 2, 1, 5), "foo");
tokens.save();
verifyNoInteractions(sensorStorage);
assertThat(tokens.getTokenLines()).isEmpty();
}
@Test
public void dont_save_for_test_files() {
DefaultInputFile testInputFile = new TestInputFileBuilder("foo", "src/Foo.java")
.setLines(2)
.setOriginalLineStartOffsets(new int[] {0, 50})
.setOriginalLineEndOffsets(new int[] {49, 100})
.setLastValidOffset(101)
.setType(InputFile.Type.TEST)
.build();
DefaultCpdTokens tokens = new DefaultCpdTokens(sensorStorage)
.onFile(testInputFile)
.addToken(testInputFile.newRange(1, 2, 1, 5), "foo");
tokens.save();
verifyNoInteractions(sensorStorage);
assertThat(tokens.getTokenLines()).isEmpty();
}
@Test
public void save_many_tokens() {
DefaultCpdTokens tokens = new DefaultCpdTokens(sensorStorage)
.onFile(inputFile)
.addToken(inputFile.newRange(1, 2, 1, 5), "foo")
.addToken(inputFile.newRange(1, 6, 1, 10), "bar")
.addToken(inputFile.newRange(1, 20, 1, 25), "biz")
.addToken(inputFile.newRange(2, 1, 2, 10), "next");
tokens.save();
verify(sensorStorage).store(tokens);
assertThat(tokens.getTokenLines())
.extracting("value", "startLine", "hashCode", "startUnit", "endUnit")
.containsExactly(
tuple("foobarbiz", 1, "foobarbiz".hashCode(), 1, 3),
tuple("next", 2, "next".hashCode(), 4, 4));
}
@Test
public void basic_validation() {
SensorStorage sensorStorage = mock(SensorStorage.class);
DefaultCpdTokens tokens = new DefaultCpdTokens(sensorStorage);
try {
tokens.save();
fail("Expected exception");
} catch (Exception e) {
assertThat(e).hasMessage("Call onFile() first");
}
try {
tokens.addToken(inputFile.newRange(1, 2, 1, 5), "foo");
fail("Expected exception");
} catch (Exception e) {
assertThat(e).hasMessage("Call onFile() first");
}
try {
tokens.addToken(null, "foo");
fail("Expected exception");
} catch (Exception e) {
assertThat(e).hasMessage("Range should not be null");
}
try {
tokens.addToken(inputFile.newRange(1, 2, 1, 5), null);
fail("Expected exception");
} catch (Exception e) {
assertThat(e).hasMessage("Image should not be null");
}
}
@Test
public void validate_tokens_order() {
SensorStorage sensorStorage = mock(SensorStorage.class);
DefaultCpdTokens tokens = new DefaultCpdTokens(sensorStorage)
.onFile(inputFile)
.addToken(inputFile.newRange(1, 6, 1, 10), "bar");
try {
tokens.addToken(inputFile.newRange(1, 2, 1, 5), "foo");
fail("Expected exception");
} catch (Exception e) {
assertThat(e).hasMessage("Tokens of file src/Foo.java should be provided in order.\n" +
"Previous token: Range[from [line=1, lineOffset=6] to [line=1, lineOffset=10]]\n" +
"Last token: Range[from [line=1, lineOffset=2] to [line=1, lineOffset=5]]");
}
}
}
| 5,712 | 32.409357 | 165 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/sensor/error/internal/DefaultAnalysisErrorTest.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.api.batch.sensor.error.internal;
import org.assertj.core.api.Assertions;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.TextPointer;
import org.sonar.api.batch.fs.internal.DefaultTextPointer;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.sensor.error.NewAnalysisError;
import org.sonar.api.batch.sensor.internal.SensorStorage;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.fail;
public class DefaultAnalysisErrorTest {
private InputFile inputFile;
private SensorStorage storage;
private TextPointer textPointer;
@Before
public void setUp() {
inputFile = new TestInputFileBuilder("module1", "src/File.java").build();
textPointer = new DefaultTextPointer(5, 2);
storage = Mockito.mock(SensorStorage.class);
}
@Test
public void test_analysis_error() {
DefaultAnalysisError analysisError = new DefaultAnalysisError(storage);
analysisError.onFile(inputFile)
.at(textPointer)
.message("msg");
Assertions.assertThat(analysisError.location()).isEqualTo(textPointer);
Assertions.assertThat(analysisError.message()).isEqualTo("msg");
Assertions.assertThat(analysisError.inputFile()).isEqualTo(inputFile);
}
@Test
public void test_save() {
DefaultAnalysisError analysisError = new DefaultAnalysisError(storage);
analysisError.onFile(inputFile).save();
Mockito.verify(storage).store(analysisError);
Mockito.verifyNoMoreInteractions(storage);
}
@Test
public void test_no_storage() {
DefaultAnalysisError analysisError = new DefaultAnalysisError();
assertThatThrownBy(() -> analysisError.onFile(inputFile).save())
.isInstanceOf(NullPointerException.class);
}
@Test
public void test_validation() {
try {
new DefaultAnalysisError(storage).onFile(null);
fail("Expected exception");
} catch (IllegalArgumentException e) {
// expected
}
NewAnalysisError error = new DefaultAnalysisError(storage).onFile(inputFile);
try {
error.onFile(inputFile);
fail("Expected exception");
} catch (IllegalStateException e) {
// expected
}
error = new DefaultAnalysisError(storage).at(textPointer);
try {
error.at(textPointer);
fail("Expected exception");
} catch (IllegalStateException e) {
// expected
}
try {
new DefaultAnalysisError(storage).save();
fail("Expected exception");
} catch (NullPointerException e) {
// expected
}
}
}
| 3,506 | 30.881818 | 81 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/sensor/highlighting/internal/DefaultHighlightingTest.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.api.batch.sensor.highlighting.internal;
import java.util.Collection;
import org.assertj.core.api.Assertions;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
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.SensorStorage;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.api.batch.sensor.highlighting.TypeOfText.COMMENT;
import static org.sonar.api.batch.sensor.highlighting.TypeOfText.KEYWORD;
public class DefaultHighlightingTest {
private static final InputFile INPUT_FILE = new TestInputFileBuilder("foo", "src/Foo.java")
.setLines(2)
.setOriginalLineStartOffsets(new int[]{0, 50})
.setOriginalLineEndOffsets(new int[]{49, 100})
.setLastValidOffset(101)
.build();
private Collection<SyntaxHighlightingRule> highlightingRules;
@Before
public void setUpSampleRules() {
DefaultHighlighting highlightingDataBuilder = new DefaultHighlighting(Mockito.mock(SensorStorage.class))
.onFile(INPUT_FILE)
.highlight(1, 0, 1, 10, COMMENT)
.highlight(1, 10, 1, 12, KEYWORD)
.highlight(1, 24, 1, 38, KEYWORD)
.highlight(1, 42, 2, 0, KEYWORD)
.highlight(1, 24, 2, 15, COMMENT)
.highlight(1, 12, 1, 20, COMMENT);
highlightingDataBuilder.save();
highlightingRules = highlightingDataBuilder.getSyntaxHighlightingRuleSet();
}
@Test
public void should_register_highlighting_rule() {
Assertions.assertThat(highlightingRules).hasSize(6);
}
private static TextRange rangeOf(int startLine, int startOffset, int endLine, int endOffset) {
return new DefaultTextRange(new DefaultTextPointer(startLine, startOffset), new DefaultTextPointer(endLine, endOffset));
}
@Test
public void should_order_by_start_then_end_offset() {
Assertions.assertThat(highlightingRules).extracting("range", TextRange.class).containsExactly(
rangeOf(1, 0, 1, 10),
rangeOf(1, 10, 1, 12),
rangeOf(1, 12, 1, 20),
rangeOf(1, 24, 2, 15),
rangeOf(1, 24, 1, 38),
rangeOf(1, 42, 2, 0));
Assertions.assertThat(highlightingRules).extracting("textType").containsExactly(COMMENT, KEYWORD, COMMENT, COMMENT, KEYWORD, KEYWORD);
}
@Test
public void should_support_overlapping() {
new DefaultHighlighting(Mockito.mock(SensorStorage.class))
.onFile(INPUT_FILE)
.highlight(1, 0, 1, 15, KEYWORD)
.highlight(1, 8, 1, 12, COMMENT)
.save();
}
@Test
public void should_prevent_start_equal_end() {
assertThatThrownBy(() -> new DefaultHighlighting(Mockito.mock(SensorStorage.class))
.onFile(INPUT_FILE)
.highlight(1, 10, 1, 10, KEYWORD)
.save())
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("Unable to highlight file");
}
@Test
public void should_prevent_boudaries_overlapping() {
assertThatThrownBy(() -> new DefaultHighlighting(Mockito.mock(SensorStorage.class))
.onFile(INPUT_FILE)
.highlight(1, 0, 1, 10, KEYWORD)
.highlight(1, 8, 1, 15, KEYWORD)
.save())
.isInstanceOf(IllegalStateException.class)
.hasMessage("Cannot register highlighting rule for characters at Range[from [line=1, lineOffset=8] to [line=1, lineOffset=15]] " +
"as it overlaps at least one existing rule");
}
}
| 4,411 | 36.07563 | 138 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/sensor/internal/DefaultSensorDescriptorTest.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.api.batch.sensor.internal;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.config.internal.MapSettings;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(DataProviderRunner.class)
public class DefaultSensorDescriptorTest {
@Test
public void describe_defaults() {
DefaultSensorDescriptor descriptor = new DefaultSensorDescriptor();
descriptor
.name("Foo");
assertThat(descriptor.name()).isEqualTo("Foo");
assertThat(descriptor.languages()).isEmpty();
assertThat(descriptor.type()).isNull();
assertThat(descriptor.ruleRepositories()).isEmpty();
assertThat(descriptor.isProcessesFilesIndependently()).isFalse();
}
@Test
public void describe() {
DefaultSensorDescriptor descriptor = new DefaultSensorDescriptor();
descriptor
.name("Foo")
.onlyOnLanguage("java")
.onlyOnFileType(InputFile.Type.MAIN)
.onlyWhenConfiguration(c -> c.hasKey("sonar.foo.reportPath2") && c.hasKey("sonar.foo.reportPath"))
.createIssuesForRuleRepository("java-java")
.processesFilesIndependently();
assertThat(descriptor.name()).isEqualTo("Foo");
assertThat(descriptor.languages()).containsOnly("java");
assertThat(descriptor.type()).isEqualTo(InputFile.Type.MAIN);
MapSettings settings = new MapSettings();
settings.setProperty("sonar.foo.reportPath", "foo");
assertThat(descriptor.configurationPredicate().test(settings.asConfig())).isFalse();
settings.setProperty("sonar.foo.reportPath2", "foo");
assertThat(descriptor.configurationPredicate().test(settings.asConfig())).isTrue();
assertThat(descriptor.ruleRepositories()).containsOnly("java-java");
assertThat(descriptor.isProcessesFilesIndependently()).isTrue();
}
@Test
@UseDataProvider("independentFilesSensors")
public void describe_with_restricted_sensor(String sensorName) {
DefaultSensorDescriptor descriptor = new DefaultSensorDescriptor();
descriptor
.name(sensorName);
assertThat(descriptor.isProcessesFilesIndependently()).isTrue();
}
@Test
@UseDataProvider("independentFilesSensors")
public void describe_with_non_restricted_sensor(String sensorName) {
DefaultSensorDescriptor descriptor = new DefaultSensorDescriptor();
descriptor
.name(sensorName + "other");
assertThat(descriptor.isProcessesFilesIndependently()).isFalse();
}
@DataProvider
public static Object[][] independentFilesSensors() {
return new Object[][] {DefaultSensorDescriptor.HARDCODED_INDEPENDENT_FILE_SENSORS.toArray()};
}
}
| 3,670 | 36.845361 | 104 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/sensor/internal/InMemorySensorStorageTest.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.api.batch.sensor.internal;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.data.MapEntry.entry;
public class InMemorySensorStorageTest {
InMemorySensorStorage underTest = new InMemorySensorStorage();
@Test
public void test_storeProperty() {
assertThat(underTest.contextProperties).isEmpty();
underTest.storeProperty("foo", "bar");
assertThat(underTest.contextProperties).containsOnly(entry("foo", "bar"));
}
@Test
public void storeProperty_throws_IAE_if_key_is_null() {
assertThatThrownBy(() -> underTest.storeProperty(null, "bar"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Key of context property must not be null");
}
@Test
public void storeProperty_throws_IAE_if_value_is_null() {
assertThatThrownBy(() -> underTest.storeProperty("foo", null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Value of context property must not be null");
}
}
| 1,937 | 34.888889 | 78 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/sensor/internal/SensorContextTesterTest.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.api.batch.sensor.internal;
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 org.sonar.api.batch.bootstrap.ProjectDefinition;
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.DefaultInputModule;
import org.sonar.api.batch.fs.internal.DefaultTextPointer;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.rule.ActiveRules;
import org.sonar.api.batch.rule.Severity;
import org.sonar.api.batch.rule.internal.ActiveRulesBuilder;
import org.sonar.api.batch.rule.internal.NewActiveRule;
import org.sonar.api.batch.sensor.cache.ReadCache;
import org.sonar.api.batch.sensor.cache.WriteCache;
import org.sonar.api.batch.sensor.error.AnalysisError;
import org.sonar.api.batch.sensor.error.NewAnalysisError;
import org.sonar.api.batch.sensor.highlighting.TypeOfText;
import org.sonar.api.batch.sensor.issue.NewExternalIssue;
import org.sonar.api.batch.sensor.issue.NewIssue;
import org.sonar.api.batch.sensor.symbol.NewSymbolTable;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rules.RuleType;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.tuple;
import static org.assertj.core.data.MapEntry.entry;
import static org.mockito.Mockito.mock;
public class SensorContextTesterTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private SensorContextTester tester;
private File baseDir;
@Before
public void prepare() throws Exception {
baseDir = temp.newFolder();
tester = SensorContextTester.create(baseDir);
}
@Test
public void testSettings() {
MapSettings settings = new MapSettings();
settings.setProperty("foo", "bar");
tester.setSettings(settings);
assertThat(tester.config().get("foo")).contains("bar");
}
@Test
public void test_canSkipUnchangedFiles() {
assertThat(tester.canSkipUnchangedFiles()).isFalse();
tester.setCanSkipUnchangedFiles(true);
assertThat(tester.canSkipUnchangedFiles()).isTrue();
}
@Test
public void testPluginCache() {
assertThat(tester.nextCache()).isNull();
assertThat(tester.previousCache()).isNull();
assertThat(tester.isCacheEnabled()).isFalse();
ReadCache readCache = mock(ReadCache.class);
WriteCache writeCache = mock(WriteCache.class);
tester.setPreviousCache(readCache);
tester.setNextCache(writeCache);
tester.setCacheEnabled(true);
assertThat(tester.nextCache()).isEqualTo(writeCache);
assertThat(tester.previousCache()).isEqualTo(readCache);
assertThat(tester.isCacheEnabled()).isTrue();
}
@Test
public void testActiveRules() {
NewActiveRule activeRule = new NewActiveRule.Builder()
.setRuleKey(RuleKey.of("foo", "bar"))
.build();
ActiveRules activeRules = new ActiveRulesBuilder().addRule(activeRule).build();
tester.setActiveRules(activeRules);
assertThat(tester.activeRules().findAll()).hasSize(1);
}
@Test
public void testFs() throws Exception {
DefaultFileSystem fs = new DefaultFileSystem(temp.newFolder());
tester.setFileSystem(fs);
assertThat(tester.fileSystem().baseDir()).isNotEqualTo(baseDir);
}
@Test
public void testIssues() {
assertThat(tester.allIssues()).isEmpty();
NewIssue newIssue = tester.newIssue();
newIssue
.at(newIssue.newLocation().on(new TestInputFileBuilder("foo", "src/Foo.java").build()))
.forRule(RuleKey.of("repo", "rule"))
.save();
newIssue = tester.newIssue();
newIssue
.at(newIssue.newLocation().on(new TestInputFileBuilder("foo", "src/Foo.java").build()))
.forRule(RuleKey.of("repo", "rule"))
.save();
assertThat(tester.allIssues()).hasSize(2);
}
@Test
public void testExternalIssues() {
assertThat(tester.allExternalIssues()).isEmpty();
NewExternalIssue newExternalIssue = tester.newExternalIssue();
newExternalIssue
.at(newExternalIssue.newLocation().message("message").on(new TestInputFileBuilder("foo", "src/Foo.java").build()))
.forRule(RuleKey.of("repo", "rule"))
.type(RuleType.BUG)
.severity(Severity.BLOCKER)
.save();
newExternalIssue = tester.newExternalIssue();
newExternalIssue
.at(newExternalIssue.newLocation().message("message").on(new TestInputFileBuilder("foo", "src/Foo.java").build()))
.type(RuleType.BUG)
.severity(Severity.BLOCKER)
.forRule(RuleKey.of("repo", "rule"))
.save();
assertThat(tester.allExternalIssues()).hasSize(2);
}
@Test
public void testAnalysisErrors() {
assertThat(tester.allAnalysisErrors()).isEmpty();
NewAnalysisError newAnalysisError = tester.newAnalysisError();
InputFile file = new TestInputFileBuilder("foo", "src/Foo.java").build();
newAnalysisError.onFile(file)
.message("error")
.at(new DefaultTextPointer(5, 2))
.save();
assertThat(tester.allAnalysisErrors()).hasSize(1);
AnalysisError analysisError = tester.allAnalysisErrors().iterator().next();
assertThat(analysisError.inputFile()).isEqualTo(file);
assertThat(analysisError.message()).isEqualTo("error");
assertThat(analysisError.location()).isEqualTo(new DefaultTextPointer(5, 2));
}
@Test
public void testMeasures() throws IOException {
assertThat(tester.measures("foo:src/Foo.java")).isEmpty();
assertThat(tester.measure("foo:src/Foo.java", "ncloc")).isNull();
tester.<Integer>newMeasure()
.on(new TestInputFileBuilder("foo", "src/Foo.java").build())
.forMetric(CoreMetrics.NCLOC)
.withValue(2)
.save();
assertThat(tester.measures("foo:src/Foo.java")).hasSize(1);
assertThat(tester.measure("foo:src/Foo.java", "ncloc")).isNotNull();
tester.<Integer>newMeasure()
.on(new TestInputFileBuilder("foo", "src/Foo.java").build())
.forMetric(CoreMetrics.LINES)
.withValue(4)
.save();
assertThat(tester.measures("foo:src/Foo.java")).hasSize(2);
assertThat(tester.measure("foo:src/Foo.java", "ncloc")).isNotNull();
assertThat(tester.measure("foo:src/Foo.java", "lines")).isNotNull();
tester.<Integer>newMeasure()
.on(new DefaultInputModule(ProjectDefinition.create().setKey("foo").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder())))
.forMetric(CoreMetrics.DIRECTORIES)
.withValue(4)
.save();
assertThat(tester.measures("foo")).hasSize(1);
assertThat(tester.measure("foo", "directories")).isNotNull();
}
@Test(expected = IllegalStateException.class)
public void duplicateMeasures() {
tester.<Integer>newMeasure()
.on(new TestInputFileBuilder("foo", "src/Foo.java").build())
.forMetric(CoreMetrics.NCLOC)
.withValue(2)
.save();
tester.<Integer>newMeasure()
.on(new TestInputFileBuilder("foo", "src/Foo.java").build())
.forMetric(CoreMetrics.NCLOC)
.withValue(2)
.save();
}
@Test
public void testHighlighting() {
assertThat(tester.highlightingTypeAt("foo:src/Foo.java", 1, 3)).isEmpty();
tester.newHighlighting()
.onFile(new TestInputFileBuilder("foo", "src/Foo.java").initMetadata("annot dsf fds foo bar").build())
.highlight(1, 0, 1, 5, TypeOfText.ANNOTATION)
.highlight(1, 8, 1, 10, TypeOfText.CONSTANT)
.highlight(1, 9, 1, 10, TypeOfText.COMMENT)
.save();
assertThat(tester.highlightingTypeAt("foo:src/Foo.java", 1, 3)).containsExactly(TypeOfText.ANNOTATION);
assertThat(tester.highlightingTypeAt("foo:src/Foo.java", 1, 9)).containsExactly(TypeOfText.CONSTANT, TypeOfText.COMMENT);
}
@Test(expected = UnsupportedOperationException.class)
public void duplicateHighlighting() {
tester.newHighlighting()
.onFile(new TestInputFileBuilder("foo", "src/Foo.java").initMetadata("annot dsf fds foo bar").build())
.highlight(1, 0, 1, 5, TypeOfText.ANNOTATION)
.save();
tester.newHighlighting()
.onFile(new TestInputFileBuilder("foo", "src/Foo.java").initMetadata("annot dsf fds foo bar").build())
.highlight(1, 0, 1, 5, TypeOfText.ANNOTATION)
.save();
}
@Test
public void testSymbolReferences() {
assertThat(tester.referencesForSymbolAt("foo:src/Foo.java", 1, 0)).isNull();
NewSymbolTable symbolTable = tester.newSymbolTable()
.onFile(new TestInputFileBuilder("foo", "src/Foo.java").initMetadata("annot dsf fds foo bar").build());
symbolTable
.newSymbol(1, 8, 1, 10);
symbolTable
.newSymbol(1, 1, 1, 5)
.newReference(1, 10, 1, 13);
symbolTable.save();
assertThat(tester.referencesForSymbolAt("foo:src/Foo.java", 1, 0)).isNull();
assertThat(tester.referencesForSymbolAt("foo:src/Foo.java", 1, 8)).isEmpty();
assertThat(tester.referencesForSymbolAt("foo:src/Foo.java", 1, 3))
.extracting("start.line", "start.lineOffset", "end.line", "end.lineOffset")
.containsExactly(tuple(1, 10, 1, 13));
}
@Test(expected = UnsupportedOperationException.class)
public void duplicateSymbolReferences() {
NewSymbolTable symbolTable = tester.newSymbolTable()
.onFile(new TestInputFileBuilder("foo", "src/Foo.java").initMetadata("annot dsf fds foo bar").build());
symbolTable
.newSymbol(1, 8, 1, 10);
symbolTable.save();
symbolTable = tester.newSymbolTable()
.onFile(new TestInputFileBuilder("foo", "src/Foo.java").initMetadata("annot dsf fds foo bar").build());
symbolTable
.newSymbol(1, 8, 1, 10);
symbolTable.save();
}
@Test
public void testCoverageAtLineZero() {
assertThat(tester.lineHits("foo:src/Foo.java", 1)).isNull();
assertThat(tester.lineHits("foo:src/Foo.java", 4)).isNull();
assertThatThrownBy(() -> tester.newCoverage()
.onFile(new TestInputFileBuilder("foo", "src/Foo.java").initMetadata("annot dsf fds foo bar").build())
.lineHits(0, 3))
.isInstanceOf(IllegalStateException.class);
}
@Test
public void testCoverageAtLineOutOfRange() {
assertThat(tester.lineHits("foo:src/Foo.java", 1)).isNull();
assertThat(tester.lineHits("foo:src/Foo.java", 4)).isNull();
assertThatThrownBy(() -> tester.newCoverage()
.onFile(new TestInputFileBuilder("foo", "src/Foo.java").initMetadata("annot dsf fds foo bar").build())
.lineHits(4, 3))
.isInstanceOf(IllegalStateException.class);
}
@Test
public void testLineHits() {
assertThat(tester.lineHits("foo:src/Foo.java", 1)).isNull();
assertThat(tester.lineHits("foo:src/Foo.java", 4)).isNull();
tester.newCoverage()
.onFile(new TestInputFileBuilder("foo", "src/Foo.java").initMetadata("annot dsf fds foo bar\nasdas").build())
.lineHits(1, 2)
.lineHits(2, 3)
.save();
assertThat(tester.lineHits("foo:src/Foo.java", 1)).isEqualTo(2);
assertThat(tester.lineHits("foo:src/Foo.java", 2)).isEqualTo(3);
}
public void multipleCoverage() {
tester.newCoverage()
.onFile(new TestInputFileBuilder("foo", "src/Foo.java").initMetadata("annot dsf fds foo bar\nasdas").build())
.lineHits(1, 2)
.conditions(3, 4, 2)
.save();
tester.newCoverage()
.onFile(new TestInputFileBuilder("foo", "src/Foo.java").initMetadata("annot dsf fds foo bar\nasdas").build())
.lineHits(1, 2)
.conditions(3, 4, 3)
.save();
assertThat(tester.lineHits("foo:src/Foo.java", 1)).isEqualTo(4);
assertThat(tester.conditions("foo:src/Foo.java", 3)).isEqualTo(4);
assertThat(tester.coveredConditions("foo:src/Foo.java", 3)).isEqualTo(3);
}
@Test
public void testConditions() {
assertThat(tester.conditions("foo:src/Foo.java", 1)).isNull();
assertThat(tester.coveredConditions("foo:src/Foo.java", 1)).isNull();
tester.newCoverage()
.onFile(new TestInputFileBuilder("foo", "src/Foo.java")
.initMetadata("annot dsf fds foo bar\nasd\nasdas\nasdfas")
.build())
.conditions(1, 4, 2)
.save();
assertThat(tester.conditions("foo:src/Foo.java", 1)).isEqualTo(4);
assertThat(tester.coveredConditions("foo:src/Foo.java", 1)).isEqualTo(2);
}
@Test
public void testCpdTokens() {
assertThat(tester.cpdTokens("foo:src/Foo.java")).isNull();
DefaultInputFile inputFile = new TestInputFileBuilder("foo", "src/Foo.java")
.initMetadata("public class Foo {\n\n}")
.build();
tester.newCpdTokens()
.onFile(inputFile)
.addToken(inputFile.newRange(0, 6), "public")
.addToken(inputFile.newRange(7, 12), "class")
.addToken(inputFile.newRange(13, 16), "$IDENTIFIER")
.addToken(inputFile.newRange(17, 18), "{")
.addToken(inputFile.newRange(3, 0, 3, 1), "}")
.save();
assertThat(tester.cpdTokens("foo:src/Foo.java")).extracting("value", "startLine", "startUnit", "endUnit")
.containsExactly(
tuple("publicclass$IDENTIFIER{", 1, 1, 4),
tuple("}", 3, 5, 5));
}
@Test(expected = UnsupportedOperationException.class)
public void duplicateCpdTokens() {
DefaultInputFile inputFile = new TestInputFileBuilder("foo", "src/Foo.java")
.initMetadata("public class Foo {\n\n}")
.build();
tester.newCpdTokens()
.onFile(inputFile)
.addToken(inputFile.newRange(0, 6), "public")
.save();
tester.newCpdTokens()
.onFile(inputFile)
.addToken(inputFile.newRange(0, 6), "public")
.save();
}
@Test
public void testCancellation() {
assertThat(tester.isCancelled()).isFalse();
tester.setCancelled(true);
assertThat(tester.isCancelled()).isTrue();
}
@Test
public void testContextProperties() {
assertThat(tester.getContextProperties()).isEmpty();
tester.addContextProperty("foo", "bar");
assertThat(tester.getContextProperties()).containsOnly(entry("foo", "bar"));
}
}
| 14,953 | 36.385 | 133 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/sensor/issue/internal/DefaultExternalIssueTest.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.api.batch.sensor.issue.internal;
import java.io.IOException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.rule.Severity;
import org.sonar.api.batch.sensor.internal.SensorStorage;
import org.sonar.api.code.CodeCharacteristic;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rules.RuleType;
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.verify;
public class DefaultExternalIssueTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private DefaultInputProject project;
@Before
public void setup() throws IOException {
project = new DefaultInputProject(ProjectDefinition.create()
.setKey("foo")
.setBaseDir(temp.newFolder())
.setWorkDir(temp.newFolder()));
}
private DefaultInputFile inputFile = new TestInputFileBuilder("foo", "src/Foo.php")
.initMetadata("Foo\nBar\n")
.build();
@Test
public void build_file_issue() {
SensorStorage storage = mock(SensorStorage.class);
DefaultExternalIssue issue = new DefaultExternalIssue(project, storage)
.at(new DefaultIssueLocation()
.on(inputFile)
.at(inputFile.selectLine(1))
.message("Wrong way!"))
.forRule(RuleKey.of("repo", "rule"))
.remediationEffortMinutes(10L)
.type(RuleType.BUG)
.severity(Severity.BLOCKER);
assertThat(issue.primaryLocation().inputComponent()).isEqualTo(inputFile);
assertThat(issue.ruleKey()).isEqualTo(RuleKey.of("external_repo", "rule"));
assertThat(issue.engineId()).isEqualTo("repo");
assertThat(issue.ruleId()).isEqualTo("rule");
assertThat(issue.primaryLocation().textRange().start().line()).isOne();
assertThat(issue.remediationEffort()).isEqualTo(10L);
assertThat(issue.type()).isEqualTo(RuleType.BUG);
assertThat(issue.severity()).isEqualTo(Severity.BLOCKER);
assertThat(issue.primaryLocation().message()).isEqualTo("Wrong way!");
issue.save();
verify(storage).store(issue);
}
@Test
public void build_project_issue() {
SensorStorage storage = mock(SensorStorage.class);
DefaultExternalIssue issue = new DefaultExternalIssue(project, storage)
.at(new DefaultIssueLocation()
.on(project)
.message("Wrong way!"))
.forRule(RuleKey.of("repo", "rule"))
.remediationEffortMinutes(10L)
.type(RuleType.BUG)
.severity(Severity.BLOCKER);
assertThat(issue.primaryLocation().inputComponent()).isEqualTo(project);
assertThat(issue.ruleKey()).isEqualTo(RuleKey.of("external_repo", "rule"));
assertThat(issue.engineId()).isEqualTo("repo");
assertThat(issue.ruleId()).isEqualTo("rule");
assertThat(issue.primaryLocation().textRange()).isNull();
assertThat(issue.remediationEffort()).isEqualTo(10L);
assertThat(issue.type()).isEqualTo(RuleType.BUG);
assertThat(issue.severity()).isEqualTo(Severity.BLOCKER);
assertThat(issue.primaryLocation().message()).isEqualTo("Wrong way!");
issue.save();
verify(storage).store(issue);
}
@Test
public void fail_to_store_if_no_type() {
SensorStorage storage = mock(SensorStorage.class);
DefaultExternalIssue issue = new DefaultExternalIssue(project, storage)
.at(new DefaultIssueLocation()
.on(inputFile)
.at(inputFile.selectLine(1))
.message("Wrong way!"))
.forRule(RuleKey.of("repo", "rule"))
.remediationEffortMinutes(10L)
.severity(Severity.BLOCKER);
assertThatThrownBy(() -> issue.save())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Type is mandatory");
}
@Test
public void fail_to_store_if_primary_location_has_no_message() {
SensorStorage storage = mock(SensorStorage.class);
DefaultExternalIssue issue = new DefaultExternalIssue(project, storage)
.at(new DefaultIssueLocation()
.on(inputFile)
.at(inputFile.selectLine(1)))
.forRule(RuleKey.of("repo", "rule"))
.remediationEffortMinutes(10L)
.type(RuleType.BUG)
.severity(Severity.BLOCKER);
assertThatThrownBy(() -> issue.save())
.isInstanceOf(IllegalStateException.class)
.hasMessage("External issues must have a message");
}
@Test
public void fail_to_store_if_no_severity() {
SensorStorage storage = mock(SensorStorage.class);
DefaultExternalIssue issue = new DefaultExternalIssue(project, storage)
.at(new DefaultIssueLocation()
.on(inputFile)
.at(inputFile.selectLine(1))
.message("Wrong way!"))
.forRule(RuleKey.of("repo", "rule"))
.remediationEffortMinutes(10L)
.type(RuleType.BUG);
assertThatThrownBy(() -> issue.save())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Severity is mandatory");
}
@Test
public void characteristic_shouldBeNoOp() {
SensorStorage storage = mock(SensorStorage.class);
DefaultExternalIssue issue = new DefaultExternalIssue(project, storage);
issue.characteristic(CodeCharacteristic.ROBUST);
assertThat(issue.characteristic()).isNull();
}
}
| 6,361 | 35.354286 | 85 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/sensor/issue/internal/DefaultIssueLocationTest.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.api.batch.sensor.issue.internal;
import java.util.Collections;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.sensor.issue.MessageFormatting;
import org.sonar.api.batch.sensor.issue.NewMessageFormatting;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.AssertionsForClassTypes.tuple;
public class DefaultIssueLocationTest {
private final InputFile inputFile = new TestInputFileBuilder("foo", "src/Foo.php")
.initMetadata("Foo\nBar\n")
.build();
@Test
public void should_build() {
assertThat(new DefaultIssueLocation()
.on(inputFile)
.message("pipo bimbo")
.message()
).isEqualTo("pipo bimbo");
}
@Test
public void not_allowed_to_call_on_twice() {
assertThatThrownBy(() -> new DefaultIssueLocation()
.on(inputFile)
.on(inputFile)
.message("Wrong way!"))
.isInstanceOf(IllegalStateException.class)
.hasMessage("on() already called");
}
@Test
public void prevent_too_long_messages() {
assertThat(new DefaultIssueLocation()
.on(inputFile)
.message(StringUtils.repeat("a", 1333)).message()).hasSize(1333);
assertThat(new DefaultIssueLocation()
.on(inputFile)
.message(StringUtils.repeat("a", 1334)).message()).hasSize(1333);
}
@Test
public void should_ignore_messageFormatting_if_message_is_trimmed() {
DefaultMessageFormatting messageFormatting = new DefaultMessageFormatting()
.start(1500)
.end(1501)
.type(MessageFormatting.Type.CODE);
DefaultIssueLocation location = new DefaultIssueLocation()
.message(StringUtils.repeat("a", 2000), List.of(messageFormatting));
assertThat(location.messageFormattings()).isEmpty();
}
@Test
public void should_truncate_messageFormatting_if_necessary() {
DefaultMessageFormatting messageFormatting = new DefaultMessageFormatting()
.start(1300)
.end(1501)
.type(MessageFormatting.Type.CODE);
DefaultIssueLocation location = new DefaultIssueLocation()
.message(StringUtils.repeat("a", 2000), List.of(messageFormatting));
assertThat(location.messageFormattings())
.extracting(MessageFormatting::start, MessageFormatting::end)
.containsOnly(tuple(1300, 1333));
}
@Test
public void should_validate_message_formatting() {
List<NewMessageFormatting> messageFormattings = List.of(new DefaultMessageFormatting()
.start(1)
.end(3)
.type(MessageFormatting.Type.CODE));
DefaultIssueLocation location = new DefaultIssueLocation();
assertThatThrownBy(() -> location.message("aa", messageFormattings))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void message_whenSettingMessage_shouldReplaceNullChar() {
assertThat(new DefaultIssueLocation().message("test " + '\u0000' + "123").message()).isEqualTo("test [NULL]123");
}
@Test
public void message_whenSettingMessageWithFormattings_shouldReplaceNullChar() {
assertThat(new DefaultIssueLocation().message("test " + '\u0000' + "123", Collections.emptyList()).message()).isEqualTo("test [NULL]123");
}
@Test
public void should_trim_on_default_message_method(){
assertThat(new DefaultIssueLocation().message(" message ").message()).isEqualTo("message");
}
@Test
public void should_not_trim_on_messageFormattings_message_method(){
assertThat(new DefaultIssueLocation().message(" message ", Collections.emptyList()).message()).isEqualTo(" message ");
}
}
| 4,592 | 34.061069 | 142 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/sensor/issue/internal/DefaultIssueTest.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.api.batch.sensor.issue.internal;
import java.io.File;
import java.io.IOException;
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.bootstrap.ProjectDefinition;
import org.sonar.api.batch.fs.TextRange;
import org.sonar.api.batch.fs.internal.DefaultInputDir;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
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.rule.Severity;
import org.sonar.api.batch.sensor.internal.SensorStorage;
import org.sonar.api.batch.sensor.issue.Issue.Flow;
import org.sonar.api.batch.sensor.issue.MessageFormatting;
import org.sonar.api.batch.sensor.issue.NewIssue.FlowType;
import org.sonar.api.batch.sensor.issue.fix.NewQuickFix;
import org.sonar.api.rule.RuleKey;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.tuple;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class DefaultIssueTest {
private static final RuleKey RULE_KEY = RuleKey.of("repo", "rule");
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private final SensorStorage storage = mock(SensorStorage.class);
private final DefaultInputFile inputFile = new TestInputFileBuilder("foo", "src/Foo.php")
.initMetadata("Foo\nBar\n")
.build();
private DefaultInputProject project;
private final NewQuickFix quickFix = mock(NewQuickFix.class);
@Before
public void prepare() throws IOException {
project = new DefaultInputProject(ProjectDefinition.create()
.setKey("foo")
.setBaseDir(temp.newFolder())
.setWorkDir(temp.newFolder()));
}
@Test
public void build_file_issue() {
DefaultIssue issue = new DefaultIssue(project, storage)
.at(new DefaultIssueLocation()
.on(inputFile)
.at(inputFile.selectLine(1))
.message("Wrong way!"))
.forRule(RULE_KEY)
.gap(10.0)
.setRuleDescriptionContextKey("spring")
.setCodeVariants(List.of("variant1", "variant2"));
assertThat(issue.primaryLocation().inputComponent()).isEqualTo(inputFile);
assertThat(issue.ruleKey()).isEqualTo(RuleKey.of("repo", "rule"));
assertThat(issue.primaryLocation().textRange().start().line()).isOne();
assertThat(issue.gap()).isEqualTo(10.0);
assertThat(issue.primaryLocation().message()).isEqualTo("Wrong way!");
assertThat(issue.ruleDescriptionContextKey()).contains("spring");
assertThat(issue.codeVariants()).containsOnly("variant1", "variant2");
issue.save();
verify(storage).store(issue);
}
@Test
public void build_issue_with_flows() {
TextRange range1 = new DefaultTextRange(new DefaultTextPointer(1, 1), new DefaultTextPointer(1, 2));
TextRange range2 = new DefaultTextRange(new DefaultTextPointer(2, 1), new DefaultTextPointer(2, 2));
DefaultIssue issue = new DefaultIssue(project, storage)
.at(new DefaultIssueLocation().on(inputFile))
.addFlow(List.of(new DefaultIssueLocation().message("loc1").on(inputFile)), FlowType.DATA, "desc")
.addFlow(List.of(new DefaultIssueLocation().message("loc1").on(inputFile).at(range1), new DefaultIssueLocation().message("loc1").on(inputFile).at(range2)))
.forRule(RULE_KEY);
assertThat(issue.flows())
.extracting(Flow::type, Flow::description)
.containsExactly(tuple(FlowType.DATA, "desc"), tuple(FlowType.UNDEFINED, null));
assertThat(issue.flows().get(0).locations()).hasSize(1);
assertThat(issue.flows().get(1).locations()).hasSize(2);
}
@Test
public void build_issue_with_secondary_locations() {
TextRange range1 = new DefaultTextRange(new DefaultTextPointer(1, 1), new DefaultTextPointer(1, 2));
TextRange range2 = new DefaultTextRange(new DefaultTextPointer(2, 1), new DefaultTextPointer(2, 2));
DefaultIssue issue = new DefaultIssue(project, storage)
.at(new DefaultIssueLocation().on(inputFile))
.addLocation(new DefaultIssueLocation().on(inputFile).at(range1).message("loc1"))
.addLocation(new DefaultIssueLocation().on(inputFile).at(range2).message("loc2"))
.forRule(RULE_KEY);
assertThat(issue.flows())
.extracting(Flow::type, Flow::description)
.containsExactly(tuple(FlowType.UNDEFINED, null), tuple(FlowType.UNDEFINED, null));
assertThat(issue.flows().get(0).locations()).hasSize(1);
assertThat(issue.flows().get(1).locations()).hasSize(1);
}
@Test
public void move_directory_issue_to_project_root() {
DefaultIssue issue = new DefaultIssue(project, storage)
.at(new DefaultIssueLocation()
.on(new DefaultInputDir("foo", "src/main").setModuleBaseDir(project.getBaseDir()))
.message("Wrong way!"))
.forRule(RuleKey.of("repo", "rule"))
.overrideSeverity(Severity.BLOCKER);
assertThat(issue.primaryLocation().inputComponent()).isEqualTo(project);
assertThat(issue.ruleKey()).isEqualTo(RuleKey.of("repo", "rule"));
assertThat(issue.primaryLocation().textRange()).isNull();
assertThat(issue.primaryLocation().message()).isEqualTo("[src/main] Wrong way!");
assertThat(issue.overriddenSeverity()).isEqualTo(Severity.BLOCKER);
issue.save();
verify(storage).store(issue);
}
@Test
public void move_submodule_issue_to_project_root() {
File subModuleDirectory = new File(project.getBaseDir().toString(), "bar");
subModuleDirectory.mkdir();
ProjectDefinition subModuleDefinition = ProjectDefinition.create()
.setKey("foo/bar")
.setBaseDir(subModuleDirectory)
.setWorkDir(subModuleDirectory);
project.definition().addSubProject(subModuleDefinition);
DefaultInputModule subModule = new DefaultInputModule(subModuleDefinition);
DefaultIssue issue = new DefaultIssue(project, storage)
.at(new DefaultIssueLocation()
.on(subModule)
.message("Wrong way! with code snippet", List.of(new DefaultMessageFormatting().start(16).end(27).type(MessageFormatting.Type.CODE))))
.forRule(RULE_KEY)
.overrideSeverity(Severity.BLOCKER);
assertThat(issue.primaryLocation().inputComponent()).isEqualTo(project);
assertThat(issue.ruleKey()).isEqualTo(RuleKey.of("repo", "rule"));
assertThat(issue.primaryLocation().textRange()).isNull();
assertThat(issue.primaryLocation().message()).isEqualTo("[bar] Wrong way! with code snippet");
assertThat(issue.overriddenSeverity()).isEqualTo(Severity.BLOCKER);
assertThat(issue.primaryLocation().messageFormattings().get(0)).extracting(MessageFormatting::start,
MessageFormatting::end, MessageFormatting::type)
.as("Formatting ranges are padded with the new message")
.containsExactly(22, 33, MessageFormatting.Type.CODE);
issue.save();
verify(storage).store(issue);
}
@Test
public void build_project_issue() throws IOException {
DefaultInputModule inputModule = new DefaultInputModule(ProjectDefinition.create().setKey("foo").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()));
DefaultIssue issue = new DefaultIssue(project, storage)
.at(new DefaultIssueLocation()
.on(inputModule)
.message("Wrong way!"))
.forRule(RULE_KEY)
.gap(10.0);
assertThat(issue.primaryLocation().inputComponent()).isEqualTo(inputModule);
assertThat(issue.ruleKey()).isEqualTo(RuleKey.of("repo", "rule"));
assertThat(issue.primaryLocation().textRange()).isNull();
assertThat(issue.gap()).isEqualTo(10.0);
assertThat(issue.primaryLocation().message()).isEqualTo("Wrong way!");
issue.save();
verify(storage).store(issue);
}
@Test
public void at_fails_if_called_twice() {
DefaultIssueLocation loc = new DefaultIssueLocation().on(inputFile);
DefaultIssue issue = new DefaultIssue(project, storage).at(loc);
assertThatThrownBy(() -> issue.at(loc)).isInstanceOf(IllegalStateException.class);
}
@Test
public void at_fails_if_location_is_null() {
DefaultIssue issue = new DefaultIssue(project, storage);
assertThatThrownBy(() -> issue.at(null)).isInstanceOf(IllegalArgumentException.class);
}
@Test
public void default_issue_has_no_quickfix() {
DefaultIssue issue = new DefaultIssue(project, storage);
assertThat(issue.isQuickFixAvailable()).isFalse();
}
@Test
public void issue_can_have_quickfix() {
DefaultIssue issue = new DefaultIssue(project, storage).setQuickFixAvailable(true);
assertThat(issue.isQuickFixAvailable()).isTrue();
}
@Test
public void quickfix_only_sets_flag_to_true() {
DefaultIssue issue = new DefaultIssue(project);
NewQuickFix newQuickFix = issue.newQuickFix();
assertThat(newQuickFix).isInstanceOf(NoOpNewQuickFix.class);
assertThat(issue.isQuickFixAvailable()).isFalse();
issue.addQuickFix(newQuickFix);
assertThat(issue.isQuickFixAvailable()).isTrue();
}
}
| 10,089 | 39.522088 | 161 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/sensor/issue/internal/DefaultMessageFormattingTest.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.api.batch.sensor.issue.internal;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.sonar.api.batch.sensor.issue.MessageFormatting;
public class DefaultMessageFormattingTest {
@Test
public void negative_start_should_throw_exception() {
DefaultMessageFormatting format = new DefaultMessageFormatting().start(-1).end(1).type(MessageFormatting.Type.CODE);
Assertions.assertThatThrownBy(() -> format.validate("message"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Message formatting start must be greater or equals to 0");
}
@Test
public void missing_type_should_throw_exception() {
DefaultMessageFormatting format = new DefaultMessageFormatting().start(0).end(1);
Assertions.assertThatThrownBy(() -> format.validate("message"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Message formatting type can't be null");
}
@Test
public void end_lesser_than_start_should_throw_exception() {
DefaultMessageFormatting format = new DefaultMessageFormatting().start(3).end(2).type(MessageFormatting.Type.CODE);
Assertions.assertThatThrownBy(() -> format.validate("message"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Message formatting end must be greater than start");
}
@Test
public void end_greater_or_equals_to_message_size_throw_exception() {
DefaultMessageFormatting format = new DefaultMessageFormatting().start(0).end(8).type(MessageFormatting.Type.CODE);
Assertions.assertThatThrownBy(() -> format.validate("message"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Message formatting end must be lesser or equal than message size");
}
@Test
public void full_range_on_message_should_work() {
DefaultMessageFormatting format = new DefaultMessageFormatting().start(0).end(6).type(MessageFormatting.Type.CODE);
Assertions.assertThatCode(() -> format.validate("message")).doesNotThrowAnyException();
}
}
| 2,862 | 42.378788 | 120 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/sensor/issue/internal/NoOpNewQuickFixTest.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.api.batch.sensor.issue.internal;
import org.junit.Test;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.TextRange;
import org.sonar.api.batch.sensor.issue.fix.NewInputFileEdit;
import org.sonar.api.batch.sensor.issue.fix.NewTextEdit;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
public class NoOpNewQuickFixTest {
@Test
public void newInputFileEdit_creates_no_ops() {
NoOpNewQuickFix newQuickFix = new NoOpNewQuickFix();
NewInputFileEdit newInputFileEdit = newQuickFix.newInputFileEdit();
assertThat(newInputFileEdit).isInstanceOf(NoOpNewQuickFix.NoOpNewInputFileEdit.class);
NewTextEdit newTextEdit = newInputFileEdit.newTextEdit();
assertThat(newTextEdit).isInstanceOf(NoOpNewQuickFix.NoOpNewTextEdit.class);
}
@Test
public void no_method_throws_exception() {
NoOpNewQuickFix newQuickFix = new NoOpNewQuickFix();
assertThat(newQuickFix.message("msg")).isEqualTo(newQuickFix);
NewInputFileEdit newInputFileEdit = newQuickFix.newInputFileEdit();
assertThat(newQuickFix.addInputFileEdit(newInputFileEdit)).isEqualTo(newQuickFix);
assertThat(newInputFileEdit.on(mock(InputFile.class))).isEqualTo(newInputFileEdit);
NewTextEdit newTextEdit = newInputFileEdit.newTextEdit();
assertThat(newInputFileEdit.addTextEdit(newTextEdit)).isEqualTo(newInputFileEdit);
assertThat(newTextEdit.at(mock(TextRange.class))).isEqualTo(newTextEdit);
assertThat(newTextEdit.withNewText("text")).isEqualTo(newTextEdit);
}
}
| 2,410 | 42.836364 | 90 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/sensor/measure/internal/DefaultMeasureTest.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.api.batch.sensor.measure.internal;
import java.io.IOException;
import org.assertj.core.api.Assertions;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.mockito.Mockito;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.batch.fs.internal.AbstractProjectOrModule;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.sensor.internal.SensorStorage;
import org.sonar.api.measures.CoreMetrics;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class DefaultMeasureTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Test
public void build_file_measure() {
SensorStorage storage = Mockito.mock(SensorStorage.class);
DefaultMeasure<Integer> newMeasure = new DefaultMeasure<Integer>(storage)
.forMetric(CoreMetrics.LINES)
.on(new TestInputFileBuilder("foo", "src/Foo.php").build())
.withValue(3);
Assertions.assertThat(newMeasure.inputComponent()).isEqualTo(new TestInputFileBuilder("foo", "src/Foo.php").build());
Assertions.assertThat(newMeasure.metric()).isEqualTo(CoreMetrics.LINES);
Assertions.assertThat(newMeasure.value()).isEqualTo(3);
newMeasure.save();
Mockito.verify(storage).store(newMeasure);
}
@Test
public void build_project_measure() throws IOException {
SensorStorage storage = Mockito.mock(SensorStorage.class);
AbstractProjectOrModule module = new DefaultInputProject(ProjectDefinition.create().setKey("foo").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()));
DefaultMeasure<Integer> newMeasure = new DefaultMeasure<Integer>(storage)
.forMetric(CoreMetrics.LINES)
.on(module)
.withValue(3);
Assertions.assertThat(newMeasure.inputComponent()).isEqualTo(module);
Assertions.assertThat(newMeasure.metric()).isEqualTo(CoreMetrics.LINES);
Assertions.assertThat(newMeasure.value()).isEqualTo(3);
newMeasure.save();
Mockito.verify(storage).store(newMeasure);
}
@Test
public void not_allowed_to_call_on_twice() {
assertThatThrownBy(() -> new DefaultMeasure<Integer>()
.on(new DefaultInputProject(ProjectDefinition.create().setKey("foo").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder())))
.on(new TestInputFileBuilder("foo", "src/Foo.php").build())
.withValue(3)
.save())
.isInstanceOf(IllegalStateException.class)
.hasMessage("on() already called");
}
}
| 3,416 | 37.393258 | 161 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/sensor/rule/internal/DefaultAdHocRuleTest.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.api.batch.sensor.rule.internal;
import org.junit.Test;
import org.sonar.api.batch.rule.Severity;
import org.sonar.api.batch.sensor.internal.SensorStorage;
import org.sonar.api.batch.sensor.rule.NewAdHocRule;
import org.sonar.api.code.CodeCharacteristic;
import org.sonar.api.rules.RuleType;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class DefaultAdHocRuleTest {
@Test
public void store() {
SensorStorage storage = mock(SensorStorage.class);
DefaultAdHocRule rule = new DefaultAdHocRule(storage)
.engineId("engine")
.ruleId("ruleId")
.name("name")
.description("desc")
.severity(Severity.BLOCKER)
.type(RuleType.CODE_SMELL);
rule.save();
assertThat(rule.engineId()).isEqualTo("engine");
assertThat(rule.ruleId()).isEqualTo("ruleId");
assertThat(rule.name()).isEqualTo("name");
assertThat(rule.description()).isEqualTo("desc");
assertThat(rule.severity()).isEqualTo(Severity.BLOCKER);
assertThat(rule.type()).isEqualTo(RuleType.CODE_SMELL);
verify(storage).store(any(DefaultAdHocRule.class));
}
@Test
public void description_is_optional() {
SensorStorage storage = mock(SensorStorage.class);
new DefaultAdHocRule(storage)
.engineId("engine")
.ruleId("ruleId")
.name("name")
.severity(Severity.BLOCKER)
.type(RuleType.CODE_SMELL)
.save();
verify(storage).store(any(DefaultAdHocRule.class));
}
@Test
public void fail_to_store_if_no_engine_id() {
SensorStorage storage = mock(SensorStorage.class);
NewAdHocRule rule = new DefaultAdHocRule(storage)
.engineId(" ")
.ruleId("ruleId")
.name("name")
.description("desc")
.severity(Severity.BLOCKER)
.type(RuleType.CODE_SMELL);
assertThatThrownBy(() -> rule.save())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Engine id is mandatory");
}
@Test
public void fail_to_store_if_no_rule_id() {
SensorStorage storage = mock(SensorStorage.class);
NewAdHocRule rule = new DefaultAdHocRule(storage)
.engineId("engine")
.ruleId(" ")
.name("name")
.description("desc")
.severity(Severity.BLOCKER)
.type(RuleType.CODE_SMELL);
assertThatThrownBy(() -> rule.save())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Rule id is mandatory");
}
@Test
public void fail_to_store_if_no_name() {
SensorStorage storage = mock(SensorStorage.class);
NewAdHocRule rule = new DefaultAdHocRule(storage)
.engineId("engine")
.ruleId("ruleId")
.name(" ")
.description("desc")
.severity(Severity.BLOCKER)
.type(RuleType.CODE_SMELL);
assertThatThrownBy(() -> rule.save())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Name is mandatory");
}
@Test
public void fail_to_store_if_no_severity() {
SensorStorage storage = mock(SensorStorage.class);
NewAdHocRule rule = new DefaultAdHocRule(storage)
.engineId("engine")
.ruleId("ruleId")
.name("name")
.description("desc")
.type(RuleType.CODE_SMELL);
assertThatThrownBy(() -> rule.save())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Severity is mandatory");
}
@Test
public void fail_to_store_if_no_type() {
SensorStorage storage = mock(SensorStorage.class);
NewAdHocRule rule = new DefaultAdHocRule(storage)
.engineId("engine")
.ruleId("ruleId")
.name("name")
.description("desc")
.severity(Severity.BLOCKER);
assertThatThrownBy(() -> rule.save())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Type is mandatory");
}
@Test
public void characteristic_shouldBeNoOp() {
SensorStorage storage = mock(SensorStorage.class);
DefaultAdHocRule rule = new DefaultAdHocRule(storage);
rule.characteristic(CodeCharacteristic.CLEAR);
assertThat(rule.characteristic()).isNull();
}
}
| 5,094 | 31.044025 | 75 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/batch/sensor/symbol/internal/DefaultSymbolTableTest.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.api.batch.sensor.symbol.internal;
import java.util.Map;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.TextRange;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import org.sonar.api.batch.sensor.internal.SensorStorage;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
public class DefaultSymbolTableTest {
private static final InputFile INPUT_FILE = new TestInputFileBuilder("foo", "src/Foo.java")
.setLines(2)
.setOriginalLineStartOffsets(new int[] {0, 50})
.setOriginalLineEndOffsets(new int[] {49, 100})
.setLastValidOffset(101)
.build();
private Map<TextRange, Set<TextRange>> referencesPerSymbol;
@Before
public void setUpSampleSymbols() {
DefaultSymbolTable symbolTableBuilder = new DefaultSymbolTable(mock(SensorStorage.class))
.onFile(INPUT_FILE);
symbolTableBuilder
.newSymbol(1, 0, 1, 10)
.newReference(2, 10, 2, 15)
.newReference(1, 16, 1, 20);
symbolTableBuilder
.newSymbol(1, 12, 1, 15)
.newReference(2, 1, 2, 5);
symbolTableBuilder.save();
referencesPerSymbol = symbolTableBuilder.getReferencesBySymbol();
}
@Test
public void should_register_symbols() {
assertThat(referencesPerSymbol).hasSize(2);
}
}
| 2,241 | 30.577465 | 93 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/config/internal/AesECBCipherTest.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.api.config.internal;
import java.io.File;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.Key;
import javax.crypto.BadPaddingException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.fail;
public class AesECBCipherTest {
@Test
public void generateRandomSecretKey() {
AesECBCipher cipher = new AesECBCipher(null);
String key = cipher.generateRandomSecretKey();
assertThat(StringUtils.isNotBlank(key)).isTrue();
assertThat(Base64.isArrayByteBase64(key.getBytes())).isTrue();
}
@Test
public void encrypt() throws Exception {
AesECBCipher cipher = new AesECBCipher(pathToSecretKey());
String encryptedText = cipher.encrypt("this is a secret");
assertThat(StringUtils.isNotBlank(encryptedText)).isTrue();
assertThat(Base64.isArrayByteBase64(encryptedText.getBytes())).isTrue();
}
@Test
public void encrypt_bad_key() throws Exception {
URL resource = getClass().getResource("/org/sonar/api/config/internal/AesCipherTest/bad_secret_key.txt");
AesECBCipher cipher = new AesECBCipher(new File(resource.toURI()).getCanonicalPath());
assertThatThrownBy(() -> cipher.encrypt("this is a secret"))
.isInstanceOf(RuntimeException.class)
.hasMessageContaining("Invalid AES key");
}
@Test
public void decrypt() throws Exception {
AesECBCipher cipher = new AesECBCipher(pathToSecretKey());
// the following value has been encrypted with the key /org/sonar/api/config/internal/AesCipherTest/aes_secret_key.txt
String clearText = cipher.decrypt("9mx5Zq4JVyjeChTcVjEide4kWCwusFl7P2dSVXtg9IY=");
assertThat(clearText).isEqualTo("this is a secret");
}
@Test
public void decrypt_bad_key() throws Exception {
URL resource = getClass().getResource("/org/sonar/api/config/internal/AesCipherTest/bad_secret_key.txt");
AesECBCipher cipher = new AesECBCipher(new File(resource.toURI()).getCanonicalPath());
try {
cipher.decrypt("9mx5Zq4JVyjeChTcVjEide4kWCwusFl7P2dSVXtg9IY=");
fail();
} catch (RuntimeException e) {
assertThat(e.getCause()).isInstanceOf(InvalidKeyException.class);
}
}
@Test
public void decrypt_other_key() throws Exception {
URL resource = getClass().getResource("/org/sonar/api/config/internal/AesCipherTest/other_secret_key.txt");
AesECBCipher cipher = new AesECBCipher(new File(resource.toURI()).getCanonicalPath());
try {
// text encrypted with another key
cipher.decrypt("9mx5Zq4JVyjeChTcVjEide4kWCwusFl7P2dSVXtg9IY=");
fail();
} catch (RuntimeException e) {
assertThat(e.getCause()).isInstanceOf(BadPaddingException.class);
}
}
@Test
public void encryptThenDecrypt() throws Exception {
AesECBCipher cipher = new AesECBCipher(pathToSecretKey());
assertThat(cipher.decrypt(cipher.encrypt("foo"))).isEqualTo("foo");
}
@Test
public void testDefaultPathToSecretKey() {
AesECBCipher cipher = new AesECBCipher(null);
String path = cipher.getPathToSecretKey();
assertThat(StringUtils.isNotBlank(path)).isTrue();
assertThat(new File(path)).hasName("sonar-secret.txt");
}
@Test
public void loadSecretKeyFromFile() throws Exception {
AesECBCipher cipher = new AesECBCipher(null);
Key secretKey = cipher.loadSecretFileFromFile(pathToSecretKey());
assertThat(secretKey.getAlgorithm()).isEqualTo("AES");
assertThat(secretKey.getEncoded()).hasSizeGreaterThan(10);
}
@Test
public void loadSecretKeyFromFile_trim_content() throws Exception {
URL resource = getClass().getResource("/org/sonar/api/config/internal/AesCipherTest/non_trimmed_secret_key.txt");
String path = new File(resource.toURI()).getCanonicalPath();
AesECBCipher cipher = new AesECBCipher(null);
Key secretKey = cipher.loadSecretFileFromFile(path);
assertThat(secretKey.getAlgorithm()).isEqualTo("AES");
assertThat(secretKey.getEncoded()).hasSizeGreaterThan(10);
}
@Test
public void loadSecretKeyFromFile_file_does_not_exist() throws Exception {
AesECBCipher cipher = new AesECBCipher(null);
assertThatThrownBy(() -> cipher.loadSecretFileFromFile("/file/does/not/exist"))
.isInstanceOf(IllegalStateException.class);
}
@Test
public void loadSecretKeyFromFile_no_property() throws Exception {
AesECBCipher cipher = new AesECBCipher(null);
assertThatThrownBy(() -> cipher.loadSecretFileFromFile(null))
.isInstanceOf(IllegalStateException.class);
}
@Test
public void hasSecretKey() throws Exception {
AesECBCipher cipher = new AesECBCipher(pathToSecretKey());
assertThat(cipher.hasSecretKey()).isTrue();
}
@Test
public void doesNotHaveSecretKey() {
AesECBCipher cipher = new AesECBCipher("/my/twitter/id/is/SimonBrandhof");
assertThat(cipher.hasSecretKey()).isFalse();
}
private String pathToSecretKey() throws Exception {
URL resource = getClass().getResource("/org/sonar/api/config/internal/AesCipherTest/aes_secret_key.txt");
return new File(resource.toURI()).getCanonicalPath();
}
}
| 6,141 | 33.700565 | 122 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/config/internal/AesGCMCipherTest.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.api.config.internal;
import java.io.File;
import java.net.URL;
import java.security.InvalidKeyException;
import javax.crypto.BadPaddingException;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class AesGCMCipherTest {
@Test
public void encrypt_should_generate_different_value_everytime() throws Exception {
AesGCMCipher cipher = new AesGCMCipher(pathToSecretKey());
String encryptedText1 = cipher.encrypt("this is a secret");
String encryptedText2 = cipher.encrypt("this is a secret");
assertThat(StringUtils.isNotBlank(encryptedText1)).isTrue();
assertThat(StringUtils.isNotBlank(encryptedText2)).isTrue();
assertThat(encryptedText1).isNotEqualTo(encryptedText2);
}
@Test
public void encrypt_bad_key() throws Exception {
URL resource = getClass().getResource("/org/sonar/api/config/internal/AesCipherTest/bad_secret_key.txt");
AesGCMCipher cipher = new AesGCMCipher(new File(resource.toURI()).getCanonicalPath());
assertThatThrownBy(() -> cipher.encrypt("this is a secret"))
.hasRootCauseInstanceOf(InvalidKeyException.class)
.hasMessageContaining("Invalid AES key");
}
@Test
public void decrypt() throws Exception {
AesGCMCipher cipher = new AesGCMCipher(pathToSecretKey());
String input1 = "this is a secret";
String input2 = "asdkfja;ksldjfowiaqueropijadfskncmnv/sdjflskjdflkjiqoeuwroiqu./qewirouasoidfhjaskldfhjkhckjnkiuoewiruoasdjkfalkufoiwueroijuqwoerjsdkjflweoiru";
assertThat(cipher.decrypt(cipher.encrypt(input1))).isEqualTo(input1);
assertThat(cipher.decrypt(cipher.encrypt(input1))).isEqualTo(input1);
assertThat(cipher.decrypt(cipher.encrypt(input2))).isEqualTo(input2);
assertThat(cipher.decrypt(cipher.encrypt(input2))).isEqualTo(input2);
}
@Test
public void decrypt_bad_key() throws Exception {
URL resource = getClass().getResource("/org/sonar/api/config/internal/AesCipherTest/bad_secret_key.txt");
AesGCMCipher cipher = new AesGCMCipher(new File(resource.toURI()).getCanonicalPath());
assertThatThrownBy(() -> cipher.decrypt("9mx5Zq4JVyjeChTcVjEide4kWCwusFl7P2dSVXtg9IY="))
.hasRootCauseInstanceOf(InvalidKeyException.class)
.hasMessageContaining("Invalid AES key");
}
@Test
public void decrypt_other_key() throws Exception {
URL resource = getClass().getResource("/org/sonar/api/config/internal/AesCipherTest/other_secret_key.txt");
AesGCMCipher originalCipher = new AesGCMCipher(pathToSecretKey());
AesGCMCipher cipher = new AesGCMCipher(new File(resource.toURI()).getCanonicalPath());
assertThatThrownBy(() -> cipher.decrypt(originalCipher.encrypt("this is a secret")))
.hasRootCauseInstanceOf(BadPaddingException.class);
}
private String pathToSecretKey() throws Exception {
URL resource = getClass().getResource("/org/sonar/api/config/internal/AesCipherTest/aes_secret_key.txt");
return new File(resource.toURI()).getCanonicalPath();
}
}
| 3,954 | 41.074468 | 164 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/config/internal/EncryptionTest.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.api.config.internal;
import java.io.File;
import java.net.URL;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class EncryptionTest {
@Test
public void isEncrypted() {
Encryption encryption = new Encryption(null);
assertThat(encryption.isEncrypted("{aes}ADASDASAD")).isTrue();
assertThat(encryption.isEncrypted("{b64}ADASDASAD")).isTrue();
assertThat(encryption.isEncrypted("{abc}ADASDASAD")).isTrue();
assertThat(encryption.isEncrypted("{}")).isFalse();
assertThat(encryption.isEncrypted("{foo")).isFalse();
assertThat(encryption.isEncrypted("foo{aes}")).isFalse();
}
@Test
public void scramble() {
Encryption encryption = new Encryption(null);
assertThat(encryption.scramble("foo")).isEqualTo("{b64}Zm9v");
}
@Test
public void decrypt() {
Encryption encryption = new Encryption(null);
assertThat(encryption.decrypt("{b64}Zm9v")).isEqualTo("foo");
}
@Test
public void loadSecretKey() throws Exception {
Encryption encryption = new Encryption(null);
encryption.setPathToSecretKey(pathToSecretKey());
assertThat(encryption.hasSecretKey()).isTrue();
}
@Test
public void generate_secret_key() {
Encryption encryption = new Encryption(null);
String key1 = encryption.generateRandomSecretKey();
String key2 = encryption.generateRandomSecretKey();
assertThat(key1).isNotEqualTo(key2);
}
@Test
public void gcm_encryption() throws Exception {
Encryption encryption = new Encryption(pathToSecretKey());
String clearText = "this is a secrit";
String cipherText = encryption.encrypt(clearText);
String decryptedText = encryption.decrypt(cipherText);
assertThat(cipherText)
.startsWith("{aes-gcm}")
.isNotEqualTo(clearText);
assertThat(decryptedText).isEqualTo(clearText);
}
@Test
public void decrypt_unknown_algorithm() {
Encryption encryption = new Encryption(null);
assertThat(encryption.decrypt("{xxx}Zm9v")).isEqualTo("{xxx}Zm9v");
}
@Test
public void decrypt_uncrypted_text() {
Encryption encryption = new Encryption(null);
assertThat(encryption.decrypt("foo")).isEqualTo("foo");
}
@Test
public void should_notDecryptText_whenBadBraceSyntax(){
Encryption encryption = new Encryption(null);
assertThat(encryption.decrypt("}xxx{Zm9v")).isEqualTo("}xxx{Zm9v");
assertThat(encryption.decrypt("}dcd}59LK")).isEqualTo("}dcd}59LK");
assertThat(encryption.decrypt("}rrrRg6")).isEqualTo("}rrrRg6");
assertThat(encryption.decrypt("{closedjdk")).isEqualTo("{closedjdk");
}
private String pathToSecretKey() throws Exception {
URL resource = getClass().getResource("/org/sonar/api/config/internal/AesCipherTest/aes_secret_key.txt");
return new File(resource.toURI()).getCanonicalPath();
}
}
| 3,699 | 32.944954 | 109 | java |
sonarqube | sonarqube-master/sonar-plugin-api-impl/src/test/java/org/sonar/api/config/internal/MapSettingsTest.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.api.config.internal;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.function.BiConsumer;
import java.util.stream.IntStream;
import org.assertj.core.api.Assertions;
import org.assertj.core.data.Offset;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.Properties;
import org.sonar.api.Property;
import org.sonar.api.PropertyType;
import org.sonar.api.config.PropertyDefinition;
import org.sonar.api.config.PropertyDefinitions;
import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.System2;
import static java.util.Collections.singletonList;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.ThrowableAssert.ThrowingCallable;
@RunWith(DataProviderRunner.class)
public class MapSettingsTest {
private PropertyDefinitions definitions;
@Properties({
@Property(key = "hello", name = "Hello", defaultValue = "world"),
@Property(key = "date", name = "Date", defaultValue = "2010-05-18"),
@Property(key = "datetime", name = "DateTime", defaultValue = "2010-05-18T15:50:45+0100"),
@Property(key = "boolean", name = "Boolean", defaultValue = "true"),
@Property(key = "falseboolean", name = "False Boolean", defaultValue = "false"),
@Property(key = "integer", name = "Integer", defaultValue = "12345"),
@Property(key = "array", name = "Array", defaultValue = "one,two,three"),
@Property(key = "multi_values", name = "Array", defaultValue = "1,2,3", multiValues = true),
@Property(key = "sonar.jira", name = "Jira Server", type = PropertyType.PROPERTY_SET, propertySetKey = "jira"),
@Property(key = "newKey", name = "New key", deprecatedKey = "oldKey"),
@Property(key = "newKeyWithDefaultValue", name = "New key with default value", deprecatedKey = "oldKeyWithDefaultValue", defaultValue = "default_value"),
@Property(key = "new_multi_values", name = "New multi values", defaultValue = "1,2,3", multiValues = true, deprecatedKey = "old_multi_values")
})
private static class Init {
}
@Before
public void init_definitions() {
definitions = new PropertyDefinitions(System2.INSTANCE);
definitions.addComponent(Init.class);
}
@Test
public void set_throws_NPE_if_key_is_null() {
MapSettings underTest = new MapSettings();
expectKeyNullNPE(() -> underTest.set(null, randomAlphanumeric(3)));
}
@Test
public void set_throws_NPE_if_value_is_null() {
MapSettings underTest = new MapSettings();
assertThatThrownBy(() -> underTest.set(randomAlphanumeric(3), null))
.isInstanceOf(NullPointerException.class)
.hasMessage("value can't be null");
}
@Test
public void set_accepts_empty_value_and_trims_it() {
MapSettings underTest = new MapSettings();
Random random = new Random();
String key = randomAlphanumeric(3);
underTest.set(key, blank(random));
assertThat(underTest.getString(key)).isEmpty();
}
@Test
public void default_values_should_be_loaded_from_definitions() {
Settings settings = new MapSettings(definitions);
assertThat(settings.getDefaultValue("hello")).isEqualTo("world");
}
@Test
@UseDataProvider("setPropertyCalls")
public void all_setProperty_methods_throws_NPE_if_key_is_null(BiConsumer<Settings, String> setPropertyCaller) {
Settings settings = new MapSettings();
expectKeyNullNPE(() -> setPropertyCaller.accept(settings, null));
}
@Test
public void set_property_string_throws_NPE_if_key_is_null() {
String key = randomAlphanumeric(3);
Settings underTest = new MapSettings(new PropertyDefinitions(System2.INSTANCE, singletonList(PropertyDefinition.builder(key).multiValues(true).build())));
expectKeyNullNPE(() -> underTest.setProperty(null, new String[]{"1", "2"}));
}
private void expectKeyNullNPE(ThrowingCallable shouldRaiseException) {
assertThatThrownBy(shouldRaiseException)
.isInstanceOf(NullPointerException.class)
.hasMessage("key can't be null");
}
@Test
@UseDataProvider("setPropertyCalls")
public void all_set_property_methods_trims_key(BiConsumer<Settings, String> setPropertyCaller) {
Settings underTest = new MapSettings();
Random random = new Random();
String blankBefore = blank(random);
String blankAfter = blank(random);
String key = randomAlphanumeric(3);
setPropertyCaller.accept(underTest, blankBefore + key + blankAfter);
assertThat(underTest.hasKey(key)).isTrue();
}
@Test
public void set_property_string_array_trims_key() {
String key = randomAlphanumeric(3);
Settings underTest = new MapSettings(new PropertyDefinitions(System2.INSTANCE, singletonList(PropertyDefinition.builder(key).multiValues(true).build())));
Random random = new Random();
String blankBefore = blank(random);
String blankAfter = blank(random);
underTest.setProperty(blankBefore + key + blankAfter, new String[]{"1", "2"});
assertThat(underTest.hasKey(key)).isTrue();
}
private static String blank(Random random) {
StringBuilder b = new StringBuilder();
IntStream.range(0, random.nextInt(3)).mapToObj(s -> " ").forEach(b::append);
return b.toString();
}
@DataProvider
public static Object[][] setPropertyCalls() {
List<BiConsumer<Settings, String>> callers = Arrays.asList(
(settings, key) -> settings.setProperty(key, 123),
(settings, key) -> settings.setProperty(key, 123L),
(settings, key) -> settings.setProperty(key, 123.2F),
(settings, key) -> settings.setProperty(key, 123.2D),
(settings, key) -> settings.setProperty(key, false),
(settings, key) -> settings.setProperty(key, new Date()),
(settings, key) -> settings.setProperty(key, new Date(), true));
return callers.stream().map(t -> new Object[]{t}).toArray(Object[][]::new);
}
@Test
public void setProperty_methods_trims_value() {
Settings underTest = new MapSettings();
Random random = new Random();
String blankBefore = blank(random);
String blankAfter = blank(random);
String key = randomAlphanumeric(3);
String value = randomAlphanumeric(3);
underTest.setProperty(key, blankBefore + value + blankAfter);
assertThat(underTest.getString(key)).isEqualTo(value);
}
@Test
public void set_property_int() {
Settings settings = new MapSettings();
settings.setProperty("foo", 123);
assertThat(settings.getInt("foo")).isEqualTo(123);
assertThat(settings.getString("foo")).isEqualTo("123");
assertThat(settings.getBoolean("foo")).isFalse();
}
@Test
public void default_number_values_are_zero() {
Settings settings = new MapSettings();
assertThat(settings.getInt("foo")).isZero();
assertThat(settings.getLong("foo")).isZero();
}
@Test
public void getInt_value_must_be_valid() {
Settings settings = new MapSettings();
settings.setProperty("foo", "not a number");
assertThatThrownBy(() -> settings.getInt("foo"))
.isInstanceOf(NumberFormatException.class);
}
@Test
public void all_values_should_be_trimmed_set_property() {
Settings settings = new MapSettings();
settings.setProperty("foo", " FOO ");
assertThat(settings.getString("foo")).isEqualTo("FOO");
}
@Test
public void test_get_default_value() {
Settings settings = new MapSettings(definitions);
assertThat(settings.getDefaultValue("unknown")).isNull();
}
@Test
public void test_get_string() {
Settings settings = new MapSettings(definitions);
settings.setProperty("hello", "Russia");
assertThat(settings.getString("hello")).isEqualTo("Russia");
}
@Test
public void setProperty_date() {
Settings settings = new MapSettings();
Date date = DateUtils.parseDateTime("2010-05-18T15:50:45+0100");
settings.setProperty("aDate", date);
settings.setProperty("aDateTime", date, true);
assertThat(settings.getString("aDate")).isEqualTo("2010-05-18");
assertThat(settings.getString("aDateTime")).startsWith("2010-05-18T");
}
@Test
public void test_get_date() {
Settings settings = new MapSettings(definitions);
assertThat(settings.getDate("unknown")).isNull();
assertThat(settings.getDate("date").getDate()).isEqualTo(18);
assertThat(settings.getDate("date").getMonth()).isEqualTo(4);
}
@Test
public void test_get_date_not_found() {
Settings settings = new MapSettings(definitions);
assertThat(settings.getDate("unknown")).isNull();
}
@Test
public void test_get_datetime() {
Settings settings = new MapSettings(definitions);
assertThat(settings.getDateTime("unknown")).isNull();
assertThat(settings.getDateTime("datetime").getDate()).isEqualTo(18);
assertThat(settings.getDateTime("datetime").getMonth()).isEqualTo(4);
assertThat(settings.getDateTime("datetime").getMinutes()).isEqualTo(50);
}
@Test
public void test_get_double() {
Settings settings = new MapSettings();
settings.setProperty("from_double", 3.14159);
settings.setProperty("from_string", "3.14159");
assertThat(settings.getDouble("from_double")).isEqualTo(3.14159, Offset.offset(0.00001));
assertThat(settings.getDouble("from_string")).isEqualTo(3.14159, Offset.offset(0.00001));
assertThat(settings.getDouble("unknown")).isNull();
}
@Test
public void test_get_float() {
Settings settings = new MapSettings();
settings.setProperty("from_float", 3.14159f);
settings.setProperty("from_string", "3.14159");
assertThat(settings.getDouble("from_float")).isEqualTo(3.14159f, Offset.offset(0.00001));
assertThat(settings.getDouble("from_string")).isEqualTo(3.14159f, Offset.offset(0.00001));
assertThat(settings.getDouble("unknown")).isNull();
}
@Test
public void test_get_bad_float() {
Settings settings = new MapSettings();
settings.setProperty("foo", "bar");
assertThatThrownBy(() -> settings.getFloat("foo"))
.isInstanceOf(IllegalStateException.class)
.hasMessage("The property 'foo' is not a float value");
}
@Test
public void test_get_bad_double() {
Settings settings = new MapSettings();
settings.setProperty("foo", "bar");
assertThatThrownBy(() -> settings.getDouble("foo"))
.isInstanceOf(IllegalStateException.class)
.hasMessage("The property 'foo' is not a double value");
}
@Test
public void testSetNullFloat() {
Settings settings = new MapSettings();
settings.setProperty("foo", (Float) null);
assertThat(settings.getFloat("foo")).isNull();
}
@Test
public void testSetNullDouble() {
Settings settings = new MapSettings();
settings.setProperty("foo", (Double) null);
assertThat(settings.getDouble("foo")).isNull();
}
@Test
public void getStringArray() {
Settings settings = new MapSettings(definitions);
String[] array = settings.getStringArray("array");
assertThat(array).isEqualTo(new String[]{"one", "two", "three"});
}
@Test
public void setStringArray() {
Settings settings = new MapSettings(definitions);
settings.setProperty("multi_values", new String[]{"A", "B"});
String[] array = settings.getStringArray("multi_values");
assertThat(array).isEqualTo(new String[]{"A", "B"});
}
@Test
public void setStringArrayTrimValues() {
Settings settings = new MapSettings(definitions);
settings.setProperty("multi_values", new String[]{" A ", " B "});
String[] array = settings.getStringArray("multi_values");
assertThat(array).isEqualTo(new String[]{"A", "B"});
}
@Test
public void setStringArrayEscapeCommas() {
Settings settings = new MapSettings(definitions);
settings.setProperty("multi_values", new String[]{"A,B", "C,D"});
String[] array = settings.getStringArray("multi_values");
assertThat(array).isEqualTo(new String[]{"A,B", "C,D"});
}
@Test
public void setStringArrayWithEmptyValues() {
Settings settings = new MapSettings(definitions);
settings.setProperty("multi_values", new String[]{"A,B", "", "C,D"});
String[] array = settings.getStringArray("multi_values");
assertThat(array).isEqualTo(new String[]{"A,B", "", "C,D"});
}
@Test
public void setStringArrayWithNullValues() {
Settings settings = new MapSettings(definitions);
settings.setProperty("multi_values", new String[]{"A,B", null, "C,D"});
String[] array = settings.getStringArray("multi_values");
assertThat(array).isEqualTo(new String[]{"A,B", "", "C,D"});
}
@Test(expected = IllegalStateException.class)
public void shouldFailToSetArrayValueOnSingleValueProperty() {
Settings settings = new MapSettings(definitions);
settings.setProperty("array", new String[]{"A", "B", "C"});
}
@Test
public void getStringArray_no_value() {
Settings settings = new MapSettings();
String[] array = settings.getStringArray("array");
assertThat(array).isEmpty();
}
@Test
public void shouldTrimArray() {
Settings settings = new MapSettings();
settings.setProperty("foo", " one, two, three ");
String[] array = settings.getStringArray("foo");
assertThat(array).isEqualTo(new String[]{"one", "two", "three"});
}
@Test
public void shouldKeepEmptyValuesWhenSplitting() {
Settings settings = new MapSettings();
settings.setProperty("foo", " one, , two");
String[] array = settings.getStringArray("foo");
assertThat(array).isEqualTo(new String[]{"one", "", "two"});
}
@Test
public void testDefaultValueOfGetString() {
Settings settings = new MapSettings(definitions);
assertThat(settings.getString("hello")).isEqualTo("world");
}
@Test
public void set_property_boolean() {
Settings settings = new MapSettings();
settings.setProperty("foo", true);
settings.setProperty("bar", false);
assertThat(settings.getBoolean("foo")).isTrue();
assertThat(settings.getBoolean("bar")).isFalse();
assertThat(settings.getString("foo")).isEqualTo("true");
assertThat(settings.getString("bar")).isEqualTo("false");
}
@Test
public void ignore_case_of_boolean_values() {
Settings settings = new MapSettings();
settings.setProperty("foo", "true");
settings.setProperty("bar", "TRUE");
// labels in UI
settings.setProperty("baz", "True");
assertThat(settings.getBoolean("foo")).isTrue();
assertThat(settings.getBoolean("bar")).isTrue();
assertThat(settings.getBoolean("baz")).isTrue();
}
@Test
public void get_boolean() {
Settings settings = new MapSettings(definitions);
assertThat(settings.getBoolean("boolean")).isTrue();
assertThat(settings.getBoolean("falseboolean")).isFalse();
assertThat(settings.getBoolean("unknown")).isFalse();
assertThat(settings.getBoolean("hello")).isFalse();
}
@Test
public void shouldCreateByIntrospectingComponent() {
Settings settings = new MapSettings();
settings.getDefinitions().addComponent(MyComponent.class);
// property definition has been loaded, ie for default value
assertThat(settings.getDefaultValue("foo")).isEqualTo("bar");
}
@Property(key = "foo", name = "Foo", defaultValue = "bar")
public static class MyComponent {
}
@Test
public void getStringLines_no_value() {
Assertions.assertThat(new MapSettings().getStringLines("foo")).isEmpty();
}
@Test
public void getStringLines_single_line() {
Settings settings = new MapSettings();
settings.setProperty("foo", "the line");
assertThat(settings.getStringLines("foo")).isEqualTo(new String[]{"the line"});
}
@Test
public void getStringLines_linux() {
Settings settings = new MapSettings();
settings.setProperty("foo", "one\ntwo");
assertThat(settings.getStringLines("foo")).isEqualTo(new String[]{"one", "two"});
settings.setProperty("foo", "one\ntwo\n");
assertThat(settings.getStringLines("foo")).isEqualTo(new String[]{"one", "two"});
}
@Test
public void getStringLines_windows() {
Settings settings = new MapSettings();
settings.setProperty("foo", "one\r\ntwo");
assertThat(settings.getStringLines("foo")).isEqualTo(new String[]{"one", "two"});
settings.setProperty("foo", "one\r\ntwo\r\n");
assertThat(settings.getStringLines("foo")).isEqualTo(new String[]{"one", "two"});
}
@Test
public void getStringLines_mix() {
Settings settings = new MapSettings();
settings.setProperty("foo", "one\r\ntwo\nthree");
assertThat(settings.getStringLines("foo")).isEqualTo(new String[]{"one", "two", "three"});
}
@Test
public void getKeysStartingWith() {
Settings settings = new MapSettings();
settings.setProperty("sonar.jdbc.url", "foo");
settings.setProperty("sonar.jdbc.username", "bar");
settings.setProperty("sonar.security", "admin");
assertThat(settings.getKeysStartingWith("sonar")).containsOnly("sonar.jdbc.url", "sonar.jdbc.username", "sonar.security");
assertThat(settings.getKeysStartingWith("sonar.jdbc")).containsOnly("sonar.jdbc.url", "sonar.jdbc.username");
assertThat(settings.getKeysStartingWith("other")).isEmpty();
}
@Test
public void should_fallback_deprecated_key_to_default_value_of_new_key() {
Settings settings = new MapSettings(definitions);
assertThat(settings.getString("newKeyWithDefaultValue")).isEqualTo("default_value");
assertThat(settings.getString("oldKeyWithDefaultValue")).isEqualTo("default_value");
}
@Test
public void should_fallback_deprecated_key_to_new_key() {
Settings settings = new MapSettings(definitions);
settings.setProperty("newKey", "value of newKey");
assertThat(settings.getString("newKey")).isEqualTo("value of newKey");
assertThat(settings.getString("oldKey")).isEqualTo("value of newKey");
}
@Test
public void should_load_value_of_deprecated_key() {
// it's used for example when deprecated settings are set through command-line
Settings settings = new MapSettings(definitions);
settings.setProperty("oldKey", "value of oldKey");
assertThat(settings.getString("newKey")).isEqualTo("value of oldKey");
assertThat(settings.getString("oldKey")).isEqualTo("value of oldKey");
}
@Test
public void should_load_values_of_deprecated_key() {
Settings settings = new MapSettings(definitions);
settings.setProperty("oldKey", "a,b");
assertThat(settings.getStringArray("newKey")).containsOnly("a", "b");
assertThat(settings.getStringArray("oldKey")).containsOnly("a", "b");
}
@Test
public void should_support_deprecated_props_with_multi_values() {
Settings settings = new MapSettings(definitions);
settings.setProperty("new_multi_values", new String[]{" A ", " B "});
assertThat(settings.getStringArray("new_multi_values")).isEqualTo(new String[]{"A", "B"});
assertThat(settings.getStringArray("old_multi_values")).isEqualTo(new String[]{"A", "B"});
}
}
| 20,056 | 35.073741 | 158 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.