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-scanner-engine/src/main/java/org/sonar/scanner/ci/vendors/DroneCi.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.scanner.ci.vendors;
import org.sonar.api.utils.System2;
import org.sonar.scanner.ci.CiConfiguration;
import org.sonar.scanner.ci.CiConfigurationImpl;
import org.sonar.scanner.ci.CiVendor;
/**
* Support https://drone.io
* <p>
* Environment variables are documented at https://docs.drone.io/reference/environ/
*/
public class DroneCi implements CiVendor {
private final System2 system;
public DroneCi(System2 system) {
this.system = system;
}
@Override
public String getName() {
return "DroneCI";
}
@Override
public boolean isDetected() {
return "true".equals(system.envVariable("CI")) && "true".equals(system.envVariable("DRONE"));
}
@Override
public CiConfiguration loadConfiguration() {
String revision = system.envVariable("DRONE_COMMIT_SHA");
return new CiConfigurationImpl(revision, getName());
}
}
| 1,718 | 30.254545 | 97 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/ci/vendors/GithubActions.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.scanner.ci.vendors;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.utils.System2;
import org.slf4j.LoggerFactory;
import org.sonar.scanner.ci.CiConfiguration;
import org.sonar.scanner.ci.CiConfigurationImpl;
import org.sonar.scanner.ci.CiVendor;
import static org.apache.commons.lang.StringUtils.isEmpty;
/**
* Support of https://github.com/features/actions
* <p>
* Environment variables: https://developer.github.com/actions/creating-github-actions/accessing-the-runtime-environment/#environment-variables
*/
public class GithubActions implements CiVendor {
private static final String PROPERTY_COMMIT = "GITHUB_SHA";
private final System2 system;
public GithubActions(System2 system) {
this.system = system;
}
@Override
public String getName() {
return "Github Actions";
}
@Override
public boolean isDetected() {
return StringUtils.isNotBlank(system.envVariable("GITHUB_ACTION"));
}
@Override
public CiConfiguration loadConfiguration() {
String revision = system.envVariable(PROPERTY_COMMIT);
if (isEmpty(revision)) {
LoggerFactory.getLogger(getClass()).warn("Missing environment variable " + PROPERTY_COMMIT);
}
return new CiConfigurationImpl(revision, getName());
}
}
| 2,124 | 31.692308 | 143 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/ci/vendors/GitlabCi.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.scanner.ci.vendors;
import org.sonar.api.utils.System2;
import org.sonar.scanner.ci.CiConfiguration;
import org.sonar.scanner.ci.CiConfigurationImpl;
import org.sonar.scanner.ci.CiVendor;
/**
* https://docs.gitlab.com/ee/ci/variables/
*/
public class GitlabCi implements CiVendor {
private final System2 system;
public GitlabCi(System2 system) {
this.system = system;
}
@Override
public String getName() {
return "Gitlab CI";
}
@Override
public boolean isDetected() {
return "true".equalsIgnoreCase(system.envVariable("GITLAB_CI"));
}
@Override
public CiConfiguration loadConfiguration() {
String revision = system.envVariable("CI_COMMIT_SHA");
return new CiConfigurationImpl(revision, getName());
}
}
| 1,615 | 29.490566 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/ci/vendors/Jenkins.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.scanner.ci.vendors;
import java.nio.file.Path;
import java.util.Optional;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.lib.RepositoryBuilder;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.utils.System2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.scanner.ci.CiConfiguration;
import org.sonar.scanner.ci.CiConfigurationImpl;
import org.sonar.scanner.ci.CiVendor;
import static org.apache.commons.lang.StringUtils.isNotBlank;
public class Jenkins implements CiVendor {
private static final Logger LOG = LoggerFactory.getLogger(Jenkins.class);
private final System2 system;
private final DefaultInputProject inputProject;
public Jenkins(System2 system, DefaultInputProject inputProject) {
this.system = system;
this.inputProject = inputProject;
}
@Override
public String getName() {
return "Jenkins";
}
@Override
public boolean isDetected() {
// https://wiki.jenkins-ci.org/display/JENKINS/Building+a+software+project
// JENKINS_URL is not enough to identify Jenkins. It can be easily used on a non-Jenkins job.
return isNotBlank(system.envVariable("JENKINS_URL")) && isNotBlank(system.envVariable("EXECUTOR_NUMBER"));
}
@Override
public CiConfiguration loadConfiguration() {
// https://wiki.jenkins-ci.org/display/JENKINS/GitHub+pull+request+builder+plugin#GitHubpullrequestbuilderplugin-EnvironmentVariables
// https://wiki.jenkins-ci.org/display/JENKINS/Building+a+software+project
String revision = system.envVariable("ghprbActualCommit");
if (StringUtils.isNotBlank(revision)) {
return new CiConfigurationImpl(revision, getName());
}
revision = system.envVariable("GIT_COMMIT");
if (StringUtils.isNotBlank(revision)) {
if (StringUtils.isNotBlank(system.envVariable("CHANGE_ID"))) {
String jenkinsGitPrSha1 = getJenkinsGitPrSha1();
if (StringUtils.isNotBlank(jenkinsGitPrSha1)) {
return new CiConfigurationImpl(jenkinsGitPrSha1, getName());
}
}
return new CiConfigurationImpl(revision, getName());
}
revision = system.envVariable("SVN_COMMIT");
return new CiConfigurationImpl(revision, getName());
}
private String getJenkinsGitPrSha1() {
String gitBranch = system.envVariable("GIT_BRANCH");
if (StringUtils.isBlank(gitBranch)) {
return null;
}
Path baseDir = inputProject.getBaseDir();
RepositoryBuilder builder = new RepositoryBuilder()
.findGitDir(baseDir.toFile())
.setMustExist(true);
if (builder.getGitDir() == null) {
return null;
}
String refName = "refs/remotes/origin/" + gitBranch;
try (Repository repo = builder.build()) {
return Optional.ofNullable(repo.exactRef(refName))
.map(Ref::getObjectId)
.map(ObjectId::getName)
.orElse(null);
} catch (Exception e) {
LOG.debug("Couldn't find git sha1 in '{}': {}", refName, e.getMessage());
}
return null;
}
}
| 4,004 | 33.826087 | 137 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/ci/vendors/SemaphoreCi.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.scanner.ci.vendors;
import org.sonar.api.utils.System2;
import org.sonar.scanner.ci.CiConfiguration;
import org.sonar.scanner.ci.CiConfigurationImpl;
import org.sonar.scanner.ci.CiVendor;
import static org.apache.commons.lang.StringUtils.isNotEmpty;
/**
* Support https://semaphoreci.com
*/
public class SemaphoreCi implements CiVendor {
private final System2 system;
public SemaphoreCi(System2 system) {
this.system = system;
}
@Override
public String getName() {
return "SemaphoreCI";
}
@Override
public boolean isDetected() {
return "true".equals(system.envVariable("SEMAPHORE")) && isNotEmpty(system.envVariable("SEMAPHORE_PROJECT_ID"));
}
@Override
public CiConfiguration loadConfiguration() {
String revision = system.envVariable("SEMAPHORE_GIT_SHA");
return new CiConfigurationImpl(revision, getName());
}
}
| 1,729 | 30.454545 | 116 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/ci/vendors/TravisCi.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.scanner.ci.vendors;
import org.sonar.api.utils.System2;
import org.sonar.scanner.ci.CiConfiguration;
import org.sonar.scanner.ci.CiConfigurationImpl;
import org.sonar.scanner.ci.CiVendor;
import static org.apache.commons.lang.StringUtils.isBlank;
/**
* Support of https://travis-ci.com
* <p>
* Environment variables: https://docs.travis-ci.com/user/environment-variables/
*/
public class TravisCi implements CiVendor {
private final System2 system;
public TravisCi(System2 system) {
this.system = system;
}
@Override
public String getName() {
return "TravisCI";
}
@Override
public boolean isDetected() {
return "true".equals(system.envVariable("CI")) && "true".equals(system.envVariable("TRAVIS"));
}
@Override
public CiConfiguration loadConfiguration() {
String pr = system.envVariable("TRAVIS_PULL_REQUEST");
String revision;
if (isBlank(pr) || "false".equals(pr)) {
revision = system.envVariable("TRAVIS_COMMIT");
} else {
revision = system.envVariable("TRAVIS_PULL_REQUEST_SHA");
}
return new CiConfigurationImpl(revision, getName());
}
}
| 1,988 | 30.078125 | 98 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/ci/vendors/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.scanner.ci.vendors;
import javax.annotation.ParametersAreNonnullByDefault;
| 968 | 39.375 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/config/DefaultConfiguration.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.scanner.config;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import javax.annotation.concurrent.Immutable;
import org.apache.commons.lang.ArrayUtils;
import org.sonar.api.config.Configuration;
import org.sonar.api.config.internal.Encryption;
import org.sonar.api.config.PropertyDefinition;
import org.sonar.api.config.PropertyDefinitions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static java.util.Objects.requireNonNull;
import static org.apache.commons.lang.StringUtils.trim;
import static org.sonar.api.config.internal.MultivalueProperty.parseAsCsv;
@Immutable
public abstract class DefaultConfiguration implements Configuration {
private static final Logger LOG = LoggerFactory.getLogger(DefaultConfiguration.class);
private final PropertyDefinitions definitions;
private final Encryption encryption;
private final Map<String, String> properties;
private final Map<String, String> originalProperties;
public DefaultConfiguration(PropertyDefinitions propertyDefinitions, Encryption encryption, Map<String, String> props) {
this.definitions = requireNonNull(propertyDefinitions);
this.encryption = encryption;
this.properties = unmodifiableMapWithTrimmedValues(definitions, props);
this.originalProperties = Collections.unmodifiableMap(props);
}
protected static Map<String, String> unmodifiableMapWithTrimmedValues(PropertyDefinitions definitions, Map<String, String> props) {
Map<String, String> map = new HashMap<>(props.size());
props.forEach((k, v) -> {
String validKey = definitions.validKey(k);
map.put(validKey, trim(v));
});
return Collections.unmodifiableMap(map);
}
public Encryption getEncryption() {
return encryption;
}
public PropertyDefinitions getDefinitions() {
return definitions;
}
public Map<String, String> getProperties() {
return properties;
}
public Map<String, String> getOriginalProperties() {
return originalProperties;
}
@Override
public boolean hasKey(String key) {
return properties.containsKey(key);
}
@Override
public Optional<String> get(String key) {
String effectiveKey = definitions.validKey(key);
PropertyDefinition def = definitions.get(effectiveKey);
if (def != null && (def.multiValues() || !def.fields().isEmpty())) {
LOG.warn("Access to the multi-values/property set property '{}' should be made using 'getStringArray' method. The SonarQube plugin using this property should be updated.",
key);
}
return getInternal(effectiveKey);
}
@Override
public String[] getStringArray(String key) {
String effectiveKey = definitions.validKey(key);
PropertyDefinition def = definitions.get(effectiveKey);
if (def != null && !def.multiValues() && def.fields().isEmpty()) {
LOG.warn(
"Property '{}' is not declared as multi-values/property set but was read using 'getStringArray' method. The SonarQube plugin declaring this property should be updated.",
key);
}
Optional<String> value = getInternal(effectiveKey);
if (value.isPresent()) {
return parseAsCsv(effectiveKey, value.get());
}
return ArrayUtils.EMPTY_STRING_ARRAY;
}
private Optional<String> getInternal(String key) {
Optional<String> value = Optional.ofNullable(properties.get(key));
if (!value.isPresent()) {
// default values cannot be encrypted, so return value as-is.
return Optional.ofNullable(definitions.getDefaultValue(key));
}
if (encryption.isEncrypted(value.get())) {
try {
return Optional.of(encryption.decrypt(value.get()));
} catch (Exception e) {
throw new IllegalStateException("Fail to decrypt the property " + key + ". Please check your secret key.", e);
}
}
return value;
}
}
| 4,730 | 35.392308 | 177 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/config/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.scanner.config;
import javax.annotation.ParametersAreNonnullByDefault;
| 964 | 39.208333 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/CpdExecutor.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.scanner.cpd;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.batch.fs.InputComponent;
import org.sonar.api.batch.fs.internal.DefaultInputComponent;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.duplications.block.Block;
import org.sonar.duplications.detector.suffixtree.SuffixTreeCloneDetectionAlgorithm;
import org.sonar.duplications.index.CloneGroup;
import org.sonar.duplications.index.ClonePart;
import org.sonar.duplications.index.PackedMemoryCloneIndex.ResourceBlocks;
import org.sonar.scanner.cpd.index.SonarCpdBlockIndex;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.protocol.output.ScannerReport.Duplicate;
import org.sonar.scanner.protocol.output.ScannerReport.Duplication;
import org.sonar.scanner.report.ReportPublisher;
import org.sonar.scanner.scan.filesystem.InputComponentStore;
import org.sonar.scanner.util.ProgressReport;
/**
* Runs on the root module, at the end of the project analysis.
* It executes copy paste detection involving all files of all modules, which were indexed during sensors execution for each module.
* The sensors are responsible for handling exclusions and block sizes.
*/
public class CpdExecutor {
private static final Logger LOG = LoggerFactory.getLogger(CpdExecutor.class);
// timeout for the computation of duplicates in a file (seconds)
private static final int TIMEOUT = 5 * 60 * 1000;
static final int MAX_CLONE_GROUP_PER_FILE = 100;
static final int MAX_CLONE_PART_PER_GROUP = 100;
private final SonarCpdBlockIndex index;
private final ReportPublisher publisher;
private final InputComponentStore componentStore;
private final ProgressReport progressReport;
private final CpdSettings settings;
private final ExecutorService executorService;
private int count = 0;
private int total;
@Inject
public CpdExecutor(CpdSettings settings, SonarCpdBlockIndex index, ReportPublisher publisher, InputComponentStore inputComponentCache) {
this(settings, index, publisher, inputComponentCache, Executors.newSingleThreadExecutor());
}
public CpdExecutor(CpdSettings settings, SonarCpdBlockIndex index, ReportPublisher publisher, InputComponentStore inputComponentCache, ExecutorService executorService) {
this.settings = settings;
this.index = index;
this.publisher = publisher;
this.componentStore = inputComponentCache;
this.progressReport = new ProgressReport("CPD computation", TimeUnit.SECONDS.toMillis(10));
this.executorService = executorService;
}
public void execute() {
execute(TIMEOUT);
}
void execute(long timeout) {
List<FileBlocks> components = new ArrayList<>(index.noResources());
Iterator<ResourceBlocks> it = index.iterator();
while (it.hasNext()) {
ResourceBlocks resourceBlocks = it.next();
Optional<FileBlocks> fileBlocks = toFileBlocks(resourceBlocks.resourceId(), resourceBlocks.blocks());
if (!fileBlocks.isPresent()) {
continue;
}
components.add(fileBlocks.get());
}
int filesWithoutBlocks = index.noIndexedFiles() - index.noResources();
if (filesWithoutBlocks > 0) {
LOG.info("CPD Executor {} {} had no CPD blocks", filesWithoutBlocks, pluralize(filesWithoutBlocks));
}
total = components.size();
progressReport.start(String.format("CPD Executor Calculating CPD for %d %s", total, pluralize(total)));
try {
for (FileBlocks fileBlocks : components) {
runCpdAnalysis(executorService, fileBlocks.getInputFile(), fileBlocks.getBlocks(), timeout);
count++;
}
progressReport.stopAndLogTotalTime("CPD Executor CPD calculation finished");
} catch (Exception e) {
progressReport.stop("");
throw e;
} finally {
executorService.shutdown();
}
}
private static String pluralize(int files) {
return files == 1 ? "file" : "files";
}
void runCpdAnalysis(ExecutorService executorService, DefaultInputFile inputFile, Collection<Block> fileBlocks, long timeout) {
LOG.debug("Detection of duplications for {}", inputFile.absolutePath());
progressReport.message(String.format("%d/%d - current file: %s", count, total, inputFile.absolutePath()));
List<CloneGroup> duplications;
Future<List<CloneGroup>> futureResult = executorService.submit(() -> SuffixTreeCloneDetectionAlgorithm.detect(index, fileBlocks));
try {
duplications = futureResult.get(timeout, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
LOG.warn("Timeout during detection of duplications for {}", inputFile.absolutePath());
futureResult.cancel(true);
return;
} catch (Exception e) {
throw new IllegalStateException("Fail during detection of duplication for " + inputFile.absolutePath(), e);
}
List<CloneGroup> filtered;
if (!"java".equalsIgnoreCase(inputFile.language())) {
int minTokens = settings.getMinimumTokens(inputFile.language());
Predicate<CloneGroup> minimumTokensPredicate = DuplicationPredicates.numberOfUnitsNotLessThan(minTokens);
filtered = duplications.stream()
.filter(minimumTokensPredicate)
.collect(Collectors.toList());
} else {
filtered = duplications;
}
saveDuplications(inputFile, filtered);
}
final void saveDuplications(final DefaultInputComponent component, List<CloneGroup> duplications) {
if (duplications.size() > MAX_CLONE_GROUP_PER_FILE) {
LOG.warn("Too many duplication groups on file {}. Keep only the first {} groups.", component, MAX_CLONE_GROUP_PER_FILE);
}
Iterable<ScannerReport.Duplication> reportDuplications = duplications.stream()
.limit(MAX_CLONE_GROUP_PER_FILE)
.map(
new Function<CloneGroup, Duplication>() {
private final ScannerReport.Duplication.Builder dupBuilder = ScannerReport.Duplication.newBuilder();
private final ScannerReport.Duplicate.Builder blockBuilder = ScannerReport.Duplicate.newBuilder();
@Override
public ScannerReport.Duplication apply(CloneGroup input) {
return toReportDuplication(component, dupBuilder, blockBuilder, input);
}
})::iterator;
publisher.getWriter().writeComponentDuplications(component.scannerId(), reportDuplications);
}
private Optional<FileBlocks> toFileBlocks(String componentKey, Collection<Block> fileBlocks) {
DefaultInputFile component = (DefaultInputFile) componentStore.getByKey(componentKey);
if (component == null) {
LOG.error("Resource not found in component store: {}. Skipping CPD computation for it", componentKey);
return Optional.empty();
}
return Optional.of(new FileBlocks(component, fileBlocks));
}
private Duplication toReportDuplication(InputComponent component, Duplication.Builder dupBuilder, Duplicate.Builder blockBuilder, CloneGroup input) {
dupBuilder.clear();
ClonePart originBlock = input.getOriginPart();
blockBuilder.clear();
dupBuilder.setOriginPosition(ScannerReport.TextRange.newBuilder()
.setStartLine(originBlock.getStartLine())
.setEndLine(originBlock.getEndLine())
.build());
int clonePartCount = 0;
for (ClonePart duplicate : input.getCloneParts()) {
if (!duplicate.equals(originBlock)) {
clonePartCount++;
if (clonePartCount > MAX_CLONE_PART_PER_GROUP) {
LOG.warn("Too many duplication references on file " + component + " for block at line " +
originBlock.getStartLine() + ". Keep only the first "
+ MAX_CLONE_PART_PER_GROUP + " references.");
break;
}
blockBuilder.clear();
String componentKey = duplicate.getResourceId();
if (!component.key().equals(componentKey)) {
DefaultInputComponent sameProjectComponent = (DefaultInputComponent) componentStore.getByKey(componentKey);
blockBuilder.setOtherFileRef(sameProjectComponent.scannerId());
}
dupBuilder.addDuplicate(blockBuilder
.setRange(ScannerReport.TextRange.newBuilder()
.setStartLine(duplicate.getStartLine())
.setEndLine(duplicate.getEndLine())
.build())
.build());
}
}
return dupBuilder.build();
}
private static class FileBlocks {
private final DefaultInputFile inputFile;
private final Collection<Block> blocks;
public FileBlocks(DefaultInputFile inputFile, Collection<Block> blocks) {
this.inputFile = inputFile;
this.blocks = blocks;
}
public DefaultInputFile getInputFile() {
return inputFile;
}
public Collection<Block> getBlocks() {
return blocks;
}
}
}
| 10,037 | 40.308642 | 171 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/CpdSettings.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.scanner.cpd;
import org.sonar.api.CoreProperties;
import org.sonar.api.config.Configuration;
import org.sonar.duplications.block.BlockChunker;
public class CpdSettings {
private final Configuration settings;
public CpdSettings(Configuration config) {
this.settings = config;
}
public boolean isCrossProjectDuplicationEnabled() {
return settings.getBoolean(CoreProperties.CPD_CROSS_PROJECT).orElse(false);
}
/**
* Not applicable to Java, as the {@link BlockChunker} that it uses does not record start and end units of each block.
* Also, it uses statements instead of tokens.
*/
int getMinimumTokens(String languageKey) {
return settings.getInt("sonar.cpd." + languageKey + ".minimumTokens").orElse(100);
}
}
| 1,611 | 34.822222 | 120 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/DuplicationPredicates.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.scanner.cpd;
import java.util.function.Predicate;
import org.sonar.duplications.index.CloneGroup;
public final class DuplicationPredicates {
private DuplicationPredicates() {
}
public static Predicate<CloneGroup> numberOfUnitsNotLessThan(int min) {
return input -> input != null && input.getLengthInUnits() >= min;
}
}
| 1,196 | 34.205882 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/JavaCpdBlockIndexerSensor.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.scanner.cpd;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.batch.Phase;
import org.sonar.api.batch.fs.FilePredicates;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.api.scanner.sensor.ProjectSensor;
import org.sonar.duplications.block.Block;
import org.sonar.duplications.block.BlockChunker;
import org.sonar.duplications.java.JavaStatementBuilder;
import org.sonar.duplications.java.JavaTokenProducer;
import org.sonar.duplications.statement.Statement;
import org.sonar.duplications.statement.StatementChunker;
import org.sonar.duplications.token.TokenChunker;
import org.sonar.scanner.cpd.index.SonarCpdBlockIndex;
/**
* Special case for Java that use a dedicated block indexer.
*/
@Phase(name = Phase.Name.POST)
public class JavaCpdBlockIndexerSensor implements ProjectSensor {
private static final int BLOCK_SIZE = 10;
private static final Logger LOG = LoggerFactory.getLogger(JavaCpdBlockIndexerSensor.class);
private final SonarCpdBlockIndex index;
public JavaCpdBlockIndexerSensor(SonarCpdBlockIndex index) {
this.index = index;
}
@Override
public void describe(SensorDescriptor descriptor) {
descriptor.name("Java CPD Block Indexer")
.onlyOnLanguage("java");
}
@Override
public void execute(SensorContext context) {
FilePredicates p = context.fileSystem().predicates();
List<InputFile> sourceFiles = StreamSupport.stream(
context.fileSystem().inputFiles(
p.and(
p.hasType(InputFile.Type.MAIN),
p.hasLanguage("java")
)
).spliterator(), false)
.filter(f -> !((DefaultInputFile) f).isExcludedForDuplication())
.collect(Collectors.toList());
if (sourceFiles.isEmpty()) {
return;
}
createIndex(sourceFiles);
}
private void createIndex(Iterable<InputFile> sourceFiles) {
TokenChunker tokenChunker = JavaTokenProducer.build();
StatementChunker statementChunker = JavaStatementBuilder.build();
BlockChunker blockChunker = new BlockChunker(BLOCK_SIZE);
for (InputFile inputFile : sourceFiles) {
LOG.debug("Populating index from {}", inputFile);
String resourceEffectiveKey = inputFile.key();
List<Statement> statements;
try (InputStream is = inputFile.inputStream();
Reader reader = new InputStreamReader(is, inputFile.charset())) {
statements = statementChunker.chunk(tokenChunker.chunk(reader));
} catch (FileNotFoundException e) {
throw new IllegalStateException("Cannot find file " + inputFile.file(), e);
} catch (IOException e) {
throw new IllegalStateException("Exception handling file: " + inputFile.file(), e);
}
List<Block> blocks;
try {
blocks = blockChunker.chunk(resourceEffectiveKey, statements);
} catch (Exception e) {
throw new IllegalStateException("Cannot process file " + inputFile.file(), e);
}
index.insert(inputFile, blocks);
}
}
}
| 4,245 | 35.290598 | 93 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/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.scanner.cpd;
import javax.annotation.ParametersAreNonnullByDefault;
| 962 | 37.52 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/index/SonarCpdBlockIndex.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.scanner.cpd.index;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.duplications.block.Block;
import org.sonar.duplications.block.ByteArray;
import org.sonar.duplications.index.AbstractCloneIndex;
import org.sonar.duplications.index.CloneIndex;
import org.sonar.duplications.index.PackedMemoryCloneIndex;
import org.sonar.duplications.index.PackedMemoryCloneIndex.ResourceBlocks;
import org.sonar.scanner.cpd.CpdSettings;
import org.sonar.scanner.protocol.output.FileStructure;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.report.ReportPublisher;
public class SonarCpdBlockIndex extends AbstractCloneIndex {
private static final Logger LOG = LoggerFactory.getLogger(SonarCpdBlockIndex.class);
private final CloneIndex mem = new PackedMemoryCloneIndex();
private final ReportPublisher publisher;
// Files already tokenized
private final Set<InputFile> indexedFiles = new HashSet<>();
private final CpdSettings settings;
public SonarCpdBlockIndex(ReportPublisher publisher, CpdSettings settings) {
this.publisher = publisher;
this.settings = settings;
}
public void insert(InputFile inputFile, Collection<Block> blocks) {
if (settings.isCrossProjectDuplicationEnabled()) {
int id = ((DefaultInputFile) inputFile).scannerId();
if (publisher.getWriter().hasComponentData(FileStructure.Domain.CPD_TEXT_BLOCKS, id)) {
throw new UnsupportedOperationException("Trying to save CPD tokens twice for the same file is not supported: " + inputFile.absolutePath());
}
final ScannerReport.CpdTextBlock.Builder builder = ScannerReport.CpdTextBlock.newBuilder();
publisher.getWriter().writeCpdTextBlocks(id, blocks.stream().map(block -> {
builder.clear();
builder.setStartLine(block.getStartLine());
builder.setEndLine(block.getEndLine());
builder.setStartTokenIndex(block.getStartUnit());
builder.setEndTokenIndex(block.getEndUnit());
builder.setHash(block.getBlockHash().toHexString());
return builder.build();
}).collect(Collectors.toList()));
}
for (Block block : blocks) {
mem.insert(block);
}
if (blocks.isEmpty()) {
LOG.debug("Not enough content in '{}' to have CPD blocks, it will not be part of the duplication detection", inputFile.relativePath());
}
indexedFiles.add(inputFile);
}
public int noIndexedFiles() {
return indexedFiles.size();
}
public boolean isIndexed(InputFile inputFile) {
return indexedFiles.contains(inputFile);
}
public Collection<Block> getByInputFile(String resourceKey) {
return mem.getByResourceId(resourceKey);
}
@Override
public Collection<Block> getBySequenceHash(ByteArray hash) {
return mem.getBySequenceHash(hash);
}
@Override
public Collection<Block> getByResourceId(String resourceId) {
throw new UnsupportedOperationException();
}
@Override
public void insert(Block block) {
throw new UnsupportedOperationException();
}
@Override
public Iterator<ResourceBlocks> iterator() {
return mem.iterator();
}
@Override
public int noResources() {
return mem.noResources();
}
}
| 4,308 | 35.210084 | 147 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/index/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.scanner.cpd.index;
import javax.annotation.ParametersAreNonnullByDefault;
| 968 | 37.76 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/deprecated/test/DefaultTestCase.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.scanner.deprecated.test;
import java.util.Locale;
import javax.annotation.Nullable;
public class DefaultTestCase {
public enum Status {
OK, FAILURE, ERROR, SKIPPED;
public static Status of(@Nullable String s) {
return s == null ? null : valueOf(s.toUpperCase(Locale.ENGLISH));
}
}
private String type;
private Long durationInMs;
private Status status;
private String name;
public String type() {
return type;
}
public DefaultTestCase setType(@Nullable String s) {
this.type = s;
return this;
}
public Long durationInMs() {
return durationInMs;
}
public DefaultTestCase setDurationInMs(@Nullable Long l) {
if (l != null && l < 0) {
throw new IllegalStateException("Test duration must be positive (got: " + l + ")");
}
this.durationInMs = l;
return this;
}
public Status status() {
return status;
}
public DefaultTestCase setStatus(@Nullable Status s) {
this.status = s;
return this;
}
public String name() {
return name;
}
public DefaultTestCase setName(String s) {
this.name = s;
return this;
}
}
| 1,994 | 24.576923 | 89 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/deprecated/test/DefaultTestPlan.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.scanner.deprecated.test;
import java.util.ArrayList;
import java.util.List;
public class DefaultTestPlan {
private final List<DefaultTestCase> testCases = new ArrayList<>();
public DefaultTestCase addTestCase(String name) {
DefaultTestCase testCase = new DefaultTestCase();
testCase.setName(name);
testCases.add(testCase);
return testCase;
}
public Iterable<DefaultTestCase> testCases() {
return testCases;
}
}
| 1,307 | 31.7 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/deprecated/test/TestPlanBuilder.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.scanner.deprecated.test;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.CheckForNull;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.scanner.ScannerSide;
@ScannerSide
public class TestPlanBuilder {
private final Map<InputFile, DefaultTestPlan> testPlanByFile = new HashMap<>();
public DefaultTestPlan getTestPlan(InputFile component) {
DefaultInputFile inputFile = (DefaultInputFile) component;
inputFile.setPublished(true);
if (!testPlanByFile.containsKey(inputFile)) {
testPlanByFile.put(inputFile, new DefaultTestPlan());
}
return testPlanByFile.get(inputFile);
}
@CheckForNull
public DefaultTestPlan getTestPlanByFile(InputFile inputFile) {
return testPlanByFile.get(inputFile);
}
}
| 1,691 | 35 | 81 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/deprecated/test/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.scanner.deprecated.test;
import javax.annotation.ParametersAreNonnullByDefault;
| 973 | 39.583333 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/extension/ScannerCoreExtensionsInstaller.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.scanner.extension;
import org.sonar.api.SonarRuntime;
import org.sonar.api.scanner.ScannerSide;
import org.sonar.core.extension.CoreExtensionRepository;
import org.sonar.core.extension.CoreExtensionsInstaller;
@ScannerSide
public class ScannerCoreExtensionsInstaller extends CoreExtensionsInstaller {
public ScannerCoreExtensionsInstaller(SonarRuntime sonarRuntime, CoreExtensionRepository coreExtensionRepository) {
super(sonarRuntime, coreExtensionRepository, ScannerSide.class);
}
}
| 1,357 | 40.151515 | 117 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/extension/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.scanner.extension;
import javax.annotation.ParametersAreNonnullByDefault;
| 967 | 39.333333 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/externalissue/ExternalIssueImporter.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.scanner.externalissue;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.CheckForNull;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.TextPointer;
import org.sonar.api.batch.rule.Severity;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.issue.NewExternalIssue;
import org.sonar.api.batch.sensor.issue.NewIssueLocation;
import org.sonar.api.rules.RuleType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.scanner.externalissue.ReportParser.Issue;
import org.sonar.scanner.externalissue.ReportParser.Location;
import org.sonar.scanner.externalissue.ReportParser.Report;
public class ExternalIssueImporter {
private static final Logger LOG = LoggerFactory.getLogger(ExternalIssueImporter.class);
private static final int MAX_UNKNOWN_FILE_PATHS_TO_PRINT = 5;
private final SensorContext context;
private final Report report;
private final Set<String> unknownFiles = new LinkedHashSet<>();
private final Set<String> knownFiles = new LinkedHashSet<>();
public ExternalIssueImporter(SensorContext context, Report report) {
this.context = context;
this.report = report;
}
public void execute() {
int issueCount = 0;
for (Issue issue : report.issues) {
if (importIssue(issue)) {
issueCount++;
}
}
LOG.info("Imported {} {} in {} {}", issueCount, pluralize("issue", issueCount), knownFiles.size(), pluralize("file", knownFiles.size()));
int numberOfUnknownFiles = unknownFiles.size();
if (numberOfUnknownFiles > 0) {
LOG.info("External issues ignored for " + numberOfUnknownFiles + " unknown files, including: "
+ unknownFiles.stream().limit(MAX_UNKNOWN_FILE_PATHS_TO_PRINT).collect(Collectors.joining(", ")));
}
}
private boolean importIssue(Issue issue) {
NewExternalIssue externalIssue = context.newExternalIssue()
.engineId(issue.engineId)
.ruleId(issue.ruleId)
.severity(Severity.valueOf(issue.severity))
.type(RuleType.valueOf(issue.type));
if (issue.effortMinutes != null) {
externalIssue.remediationEffortMinutes(Long.valueOf(issue.effortMinutes));
}
NewIssueLocation primary = fillLocation(context, externalIssue.newLocation(), issue.primaryLocation);
if (primary != null) {
knownFiles.add(issue.primaryLocation.filePath);
externalIssue.at(primary);
if (issue.secondaryLocations != null) {
for (Location l : issue.secondaryLocations) {
NewIssueLocation secondary = fillLocation(context, externalIssue.newLocation(), l);
if (secondary != null) {
externalIssue.addLocation(secondary);
}
}
}
externalIssue.save();
return true;
} else {
unknownFiles.add(issue.primaryLocation.filePath);
return false;
}
}
private static String pluralize(String msg, int count) {
if (count == 1) {
return msg;
}
return msg + "s";
}
@CheckForNull
private static NewIssueLocation fillLocation(SensorContext context, NewIssueLocation newLocation, Location location) {
InputFile file = findFile(context, location.filePath);
if (file == null) {
return null;
}
newLocation.on(file);
if (location.message != null) {
newLocation.message(location.message);
}
if (location.textRange != null) {
if (location.textRange.startColumn != null) {
TextPointer start = file.newPointer(location.textRange.startLine, location.textRange.startColumn);
int endLine = (location.textRange.endLine != null) ? location.textRange.endLine : location.textRange.startLine;
int endColumn;
if (location.textRange.endColumn == null) {
// assume it's until the last character of the end line
endColumn = file.selectLine(endLine).end().lineOffset();
} else {
endColumn = location.textRange.endColumn;
}
TextPointer end = file.newPointer(endLine, endColumn);
newLocation.at(file.newRange(start, end));
} else {
newLocation.at(file.selectLine(location.textRange.startLine));
}
}
return newLocation;
}
@CheckForNull
private static InputFile findFile(SensorContext context, String filePath) {
return context.fileSystem().inputFile(context.fileSystem().predicates().hasPath(filePath));
}
}
| 5,315 | 35.163265 | 141 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/externalissue/ExternalIssuesImportSensor.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.scanner.externalissue;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.sonar.api.CoreProperties;
import org.sonar.api.batch.sensor.Sensor;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.api.config.Configuration;
import org.sonar.api.config.PropertyDefinition;
import org.sonar.api.resources.Qualifiers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.scanner.externalissue.ReportParser.Report;
public class ExternalIssuesImportSensor implements Sensor {
private static final Logger LOG = LoggerFactory.getLogger(ExternalIssuesImportSensor.class);
static final String REPORT_PATHS_PROPERTY_KEY = "sonar.externalIssuesReportPaths";
private final Configuration config;
public ExternalIssuesImportSensor(Configuration config) {
this.config = config;
}
public static List<PropertyDefinition> properties() {
return Collections.singletonList(
PropertyDefinition.builder(REPORT_PATHS_PROPERTY_KEY)
.name("Issues report paths")
.description("List of comma-separated paths (absolute or relative) containing report with issues created by external rule engines.")
.category(CoreProperties.CATEGORY_EXTERNAL_ISSUES)
.onQualifiers(Qualifiers.PROJECT)
.build());
}
@Override
public void describe(SensorDescriptor descriptor) {
descriptor.name("Import external issues report")
.onlyWhenConfiguration(c -> c.hasKey(REPORT_PATHS_PROPERTY_KEY));
}
@Override
public void execute(SensorContext context) {
Set<String> reportPaths = loadReportPaths();
for (String reportPath : reportPaths) {
LOG.debug("Importing issues from '{}'", reportPath);
Path reportFilePath = context.fileSystem().resolvePath(reportPath).toPath();
ReportParser parser = new ReportParser(reportFilePath);
Report report = parser.parse();
ExternalIssueImporter issueImporter = new ExternalIssueImporter(context, report);
issueImporter.execute();
}
}
private Set<String> loadReportPaths() {
return Arrays.stream(config.getStringArray(REPORT_PATHS_PROPERTY_KEY)).collect(Collectors.toSet());
}
}
| 3,181 | 37.337349 | 140 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/externalissue/ReportParser.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.scanner.externalissue;
import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import java.io.IOException;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
public class ReportParser {
private Gson gson = new Gson();
private Path filePath;
public ReportParser(Path filePath) {
this.filePath = filePath;
}
public Report parse() {
try (Reader reader = Files.newBufferedReader(filePath, StandardCharsets.UTF_8)) {
return validate(gson.fromJson(reader, Report.class));
} catch (JsonIOException | IOException e) {
throw new IllegalStateException("Failed to read external issues report '" + filePath + "'", e);
} catch (JsonSyntaxException e) {
throw new IllegalStateException("Failed to read external issues report '" + filePath + "': invalid JSON syntax", e);
}
}
private Report validate(Report report) {
for (Issue issue : report.issues) {
mandatoryField(issue.primaryLocation, "primaryLocation");
mandatoryField(issue.engineId, "engineId");
mandatoryField(issue.ruleId, "ruleId");
mandatoryField(issue.severity, "severity");
mandatoryField(issue.type, "type");
mandatoryField(issue.primaryLocation, "primaryLocation");
mandatoryFieldPrimaryLocation(issue.primaryLocation.filePath, "filePath");
mandatoryFieldPrimaryLocation(issue.primaryLocation.message, "message");
if (issue.primaryLocation.textRange != null) {
mandatoryFieldPrimaryLocation(issue.primaryLocation.textRange.startLine, "startLine of the text range");
}
if (issue.secondaryLocations != null) {
for (Location l : issue.secondaryLocations) {
mandatoryFieldSecondaryLocation(l.filePath, "filePath");
mandatoryFieldSecondaryLocation(l.textRange, "textRange");
mandatoryFieldSecondaryLocation(l.textRange.startLine, "startLine of the text range");
}
}
}
return report;
}
private void mandatoryFieldPrimaryLocation(@Nullable Object value, String fieldName) {
if (value == null) {
throw new IllegalStateException(String.format("Failed to parse report '%s': missing mandatory field '%s' in the primary location of the issue.", filePath, fieldName));
}
}
private void mandatoryFieldSecondaryLocation(@Nullable Object value, String fieldName) {
if (value == null) {
throw new IllegalStateException(String.format("Failed to parse report '%s': missing mandatory field '%s' in a secondary location of the issue.", filePath, fieldName));
}
}
private void mandatoryField(@Nullable Object value, String fieldName) {
if (value == null) {
throw new IllegalStateException(String.format("Failed to parse report '%s': missing mandatory field '%s'.", filePath, fieldName));
}
}
private void mandatoryField(@Nullable String value, String fieldName) {
if (StringUtils.isBlank(value)) {
throw new IllegalStateException(String.format("Failed to parse report '%s': missing mandatory field '%s'.", filePath, fieldName));
}
}
static class Report {
Issue[] issues;
public Report() {
// http://stackoverflow.com/a/18645370/229031
}
}
static class Issue {
String engineId;
String ruleId;
String severity;
String type;
@Nullable
Integer effortMinutes;
Location primaryLocation;
@Nullable
Location[] secondaryLocations;
public Issue() {
// http://stackoverflow.com/a/18645370/229031
}
}
static class Location {
@Nullable
String message;
String filePath;
@Nullable
TextRange textRange;
public Location() {
// http://stackoverflow.com/a/18645370/229031
}
}
static class TextRange {
Integer startLine;
@Nullable
Integer startColumn;
@Nullable
Integer endLine;
@Nullable
Integer endColumn;
public TextRange() {
// http://stackoverflow.com/a/18645370/229031
}
}
}
| 5,008 | 31.953947 | 173 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/externalissue/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.scanner.externalissue;
import javax.annotation.ParametersAreNonnullByDefault;
| 972 | 37.92 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/externalissue/sarif/DefaultSarif210Importer.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.scanner.externalissue.sarif;
import java.util.List;
import java.util.Set;
import javax.annotation.CheckForNull;
import org.sonar.api.batch.sensor.issue.NewExternalIssue;
import org.sonar.api.scanner.ScannerSide;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.core.sarif.Run;
import org.sonar.core.sarif.Sarif210;
import static java.util.Objects.requireNonNull;
@ScannerSide
public class DefaultSarif210Importer implements Sarif210Importer {
private static final Logger LOG = LoggerFactory.getLogger(DefaultSarif210Importer.class);
private final RunMapper runMapper;
DefaultSarif210Importer(RunMapper runMapper) {
this.runMapper = runMapper;
}
@Override
public SarifImportResults importSarif(Sarif210 sarif210) {
int successFullyImportedIssues = 0;
int successFullyImportedRuns = 0;
int failedRuns = 0;
Set<Run> runs = requireNonNull(sarif210.getRuns(), "The runs section of the Sarif report is null");
for (Run run : runs) {
List<NewExternalIssue> newExternalIssues = toNewExternalIssues(run);
if (newExternalIssues == null) {
failedRuns += 1;
} else {
successFullyImportedRuns += 1;
successFullyImportedIssues += newExternalIssues.size();
newExternalIssues.forEach(NewExternalIssue::save);
}
}
return SarifImportResults.builder()
.successFullyImportedIssues(successFullyImportedIssues)
.successFullyImportedRuns(successFullyImportedRuns)
.failedRuns(failedRuns)
.build();
}
@CheckForNull
private List<NewExternalIssue> toNewExternalIssues(Run run) {
try {
return runMapper.mapRun(run);
} catch (Exception exception) {
LOG.warn("Failed to import a sarif run, error: {}", exception.getMessage());
return null;
}
}
}
| 2,674 | 32.860759 | 103 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/externalissue/sarif/LocationMapper.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.scanner.externalissue.sarif;
import com.google.common.annotations.VisibleForTesting;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.predicates.AbstractFilePredicate;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.issue.NewIssueLocation;
import org.sonar.api.scanner.ScannerSide;
import org.sonar.core.sarif.ArtifactLocation;
import org.sonar.core.sarif.Location;
import org.sonar.core.sarif.PhysicalLocation;
import org.sonar.core.sarif.Result;
import static java.util.Objects.requireNonNull;
import static org.sonar.api.utils.Preconditions.checkArgument;
@ScannerSide
public class LocationMapper {
private final SensorContext sensorContext;
private final RegionMapper regionMapper;
LocationMapper(SensorContext sensorContext, RegionMapper regionMapper) {
this.sensorContext = sensorContext;
this.regionMapper = regionMapper;
}
NewIssueLocation fillIssueInProjectLocation(Result result, NewIssueLocation newIssueLocation) {
return newIssueLocation
.message(getResultMessageOrThrow(result))
.on(sensorContext.project());
}
@CheckForNull
NewIssueLocation fillIssueInFileLocation(Result result, NewIssueLocation newIssueLocation, Location location) {
newIssueLocation.message(getResultMessageOrThrow(result));
PhysicalLocation physicalLocation = location.getPhysicalLocation();
String fileUri = getFileUriOrThrow(location);
InputFile file = findFile(sensorContext, fileUri);
if (file == null) {
return null;
}
newIssueLocation.on(file);
regionMapper.mapRegion(physicalLocation.getRegion(), file).ifPresent(newIssueLocation::at);
return newIssueLocation;
}
private static String getResultMessageOrThrow(Result result) {
requireNonNull(result.getMessage(), "No messages found for issue thrown by rule " + result.getRuleId());
return requireNonNull(result.getMessage().getText(), "No text found for messages in issue thrown by rule " + result.getRuleId());
}
private static String getFileUriOrThrow(Location location) {
PhysicalLocation physicalLocation = location.getPhysicalLocation();
checkArgument(hasUriFieldPopulated(physicalLocation), "The field location.physicalLocation.artifactLocation.uri is not set.");
return physicalLocation.getArtifactLocation().getUri();
}
private static boolean hasUriFieldPopulated(@Nullable PhysicalLocation location) {
return Optional.ofNullable(location).map(PhysicalLocation::getArtifactLocation).map(ArtifactLocation::getUri).isPresent();
}
@CheckForNull
private static InputFile findFile(SensorContext context, String filePath) {
// we use a custom predicate (which is not optimized) because fileSystem().predicates().is() doesn't handle symlinks correctly
return context.fileSystem().inputFile(new IsPredicate(getFileFromAbsoluteUriOrPath(filePath).toPath()));
}
private static File getFileFromAbsoluteUriOrPath(String filePath) {
URI uri = URI.create(filePath);
if (uri.isAbsolute()) {
return new File(uri);
} else {
return new File(filePath);
}
}
@VisibleForTesting
static class IsPredicate extends AbstractFilePredicate {
private final Path path;
public IsPredicate(Path path) {
this.path = path;
}
@Override
public boolean apply(InputFile inputFile) {
try {
return Files.isSameFile(path, inputFile.path());
} catch (IOException e) {
return false;
}
}
}
}
| 4,601 | 36.112903 | 133 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/externalissue/sarif/RegionMapper.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.scanner.externalissue.sarif;
import java.util.Objects;
import java.util.Optional;
import javax.annotation.Nullable;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.TextRange;
import org.sonar.api.scanner.ScannerSide;
import org.sonar.core.sarif.Region;
@ScannerSide
public class RegionMapper {
Optional<TextRange> mapRegion(@Nullable Region region, InputFile file) {
if (region == null) {
return Optional.empty();
}
int startLine = Objects.requireNonNull(region.getStartLine(), "No start line defined for the region.");
int endLine = Optional.ofNullable(region.getEndLine()).orElse(startLine);
int startColumn = Optional.ofNullable(region.getStartColumn()).map(RegionMapper::adjustSarifColumnIndexToSqIndex).orElse(0);
int endColumn = Optional.ofNullable(region.getEndColumn()).map(RegionMapper::adjustSarifColumnIndexToSqIndex)
.orElseGet(() -> file.selectLine(endLine).end().lineOffset());
if (rangeIsEmpty(startLine, endLine, startColumn, endColumn)) {
return Optional.of(file.selectLine(startLine));
} else {
return Optional.of(file.newRange(startLine, startColumn, endLine, endColumn));
}
}
private static int adjustSarifColumnIndexToSqIndex(int index) {
return index - 1;
}
private static boolean rangeIsEmpty(int startLine, int endLine, int startColumn, int endColumn) {
return startLine == endLine && startColumn == endColumn;
}
}
| 2,308 | 39.508772 | 128 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/externalissue/sarif/ResultMapper.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.scanner.externalissue.sarif;
import com.google.common.collect.ImmutableMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Nullable;
import org.sonar.api.batch.rule.Severity;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.issue.NewExternalIssue;
import org.sonar.api.batch.sensor.issue.NewIssueLocation;
import org.sonar.api.rules.RuleType;
import org.sonar.api.scanner.ScannerSide;
import org.sonar.core.sarif.Location;
import org.sonar.core.sarif.Result;
import static java.util.Objects.requireNonNull;
@ScannerSide
public class ResultMapper {
public static final Severity DEFAULT_SEVERITY = Severity.MAJOR;
private static final Map<String, Severity> SEVERITY_MAPPING = ImmutableMap.<String, Severity>builder()
.put("error", Severity.CRITICAL)
.put("warning", Severity.MAJOR)
.put("note", Severity.MINOR)
.put("none", Severity.INFO)
.build();
private static final RuleType DEFAULT_TYPE = RuleType.VULNERABILITY;
private final SensorContext sensorContext;
private final LocationMapper locationMapper;
ResultMapper(SensorContext sensorContext, LocationMapper locationMapper) {
this.sensorContext = sensorContext;
this.locationMapper = locationMapper;
}
NewExternalIssue mapResult(String driverName, @Nullable String ruleSeverity, Result result) {
NewExternalIssue newExternalIssue = sensorContext.newExternalIssue();
newExternalIssue.type(DEFAULT_TYPE);
newExternalIssue.engineId(driverName);
newExternalIssue.severity(toSonarQubeSeverity(ruleSeverity));
newExternalIssue.ruleId(requireNonNull(result.getRuleId(), "No ruleId found for issue thrown by driver " + driverName));
mapLocations(result, newExternalIssue);
return newExternalIssue;
}
private static Severity toSonarQubeSeverity(@Nullable String ruleSeverity) {
return SEVERITY_MAPPING.getOrDefault(ruleSeverity, DEFAULT_SEVERITY);
}
private void mapLocations(Result result, NewExternalIssue newExternalIssue) {
NewIssueLocation newIssueLocation = newExternalIssue.newLocation();
Set<Location> locations = result.getLocations();
if (locations == null || locations.isEmpty()) {
newExternalIssue.at(locationMapper.fillIssueInProjectLocation(result, newIssueLocation));
} else {
Location firstLocation = locations.iterator().next();
NewIssueLocation primaryLocation = fillFileOrProjectLocation(result, newIssueLocation, firstLocation);
newExternalIssue.at(primaryLocation);
}
}
private NewIssueLocation fillFileOrProjectLocation(Result result, NewIssueLocation newIssueLocation, Location firstLocation) {
return Optional.ofNullable(locationMapper.fillIssueInFileLocation(result, newIssueLocation, firstLocation))
.orElseGet(() -> locationMapper.fillIssueInProjectLocation(result, newIssueLocation));
}
}
| 3,761 | 39.891304 | 128 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/externalissue/sarif/RulesSeverityDetector.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.scanner.externalissue.sarif;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import javax.annotation.Nullable;
import org.sonar.api.batch.rule.Severity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.core.sarif.DefaultConfiguration;
import org.sonar.core.sarif.Extension;
import org.sonar.core.sarif.Result;
import org.sonar.core.sarif.Rule;
import org.sonar.core.sarif.Run;
import org.sonar.core.sarif.Tool;
import static java.lang.String.format;
import static java.util.Collections.emptyMap;
import static java.util.Collections.emptySet;
import static java.util.stream.Collectors.toMap;
import static org.sonar.scanner.externalissue.sarif.ResultMapper.DEFAULT_SEVERITY;
public class RulesSeverityDetector {
private static final Logger LOG = LoggerFactory.getLogger(RulesSeverityDetector.class);
public static final String UNSUPPORTED_RULE_SEVERITIES_WARNING = "Unable to detect rules severity for issue detected by tool %s, falling back to default rule severity: %s";
private RulesSeverityDetector() {}
public static Map<String, String> detectRulesSeverities(Run run, String driverName) {
Map<String, String> resultDefinedRuleSeverities = getResultDefinedRuleSeverities(run);
if (!resultDefinedRuleSeverities.isEmpty()) {
return resultDefinedRuleSeverities;
}
Map<String, String> driverDefinedRuleSeverities = getDriverDefinedRuleSeverities(run);
if (!driverDefinedRuleSeverities.isEmpty()) {
return driverDefinedRuleSeverities;
}
Map<String, String> extensionDefinedRuleSeverities = getExtensionsDefinedRuleSeverities(run);
if (!extensionDefinedRuleSeverities.isEmpty()) {
return extensionDefinedRuleSeverities;
}
LOG.warn(composeUnsupportedRuleSeveritiesDefinitionWarningMessage(driverName, DEFAULT_SEVERITY));
return emptyMap();
}
private static Map<String, String> getResultDefinedRuleSeverities(Run run) {
Predicate<Result> hasResultDefinedLevel = result -> Optional.ofNullable(result).map(Result::getLevel).isPresent();
return run.getResults()
.stream()
.filter(hasResultDefinedLevel)
.collect(toMap(Result::getRuleId, Result::getLevel, (x, y) -> y));
}
private static Map<String, String> getDriverDefinedRuleSeverities(Run run) {
return run.getTool().getDriver().getRules()
.stream()
.filter(RulesSeverityDetector::hasRuleDefinedLevel)
.collect(toMap(Rule::getId, x -> x.getDefaultConfiguration().getLevel()));
}
private static Map<String, String> getExtensionsDefinedRuleSeverities(Run run) {
return getExtensions(run)
.stream()
.map(Extension::getRules)
.filter(Objects::nonNull)
.flatMap(Collection::stream)
.filter(RulesSeverityDetector::hasRuleDefinedLevel)
.collect(toMap(Rule::getId, rule -> rule.getDefaultConfiguration().getLevel()));
}
private static Set<Extension> getExtensions(Run run) {
return Optional.of(run)
.map(Run::getTool)
.map(Tool::getExtensions)
.orElse(emptySet());
}
private static boolean hasRuleDefinedLevel(@Nullable Rule rule) {
return Optional.ofNullable(rule)
.map(Rule::getDefaultConfiguration)
.map(DefaultConfiguration::getLevel)
.isPresent();
}
private static String composeUnsupportedRuleSeveritiesDefinitionWarningMessage(String driverName, Severity defaultSeverity) {
return format(UNSUPPORTED_RULE_SEVERITIES_WARNING, driverName, defaultSeverity);
}
}
| 4,454 | 36.754237 | 174 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/externalissue/sarif/RunMapper.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.scanner.externalissue.sarif;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nullable;
import org.sonar.api.batch.sensor.issue.NewExternalIssue;
import org.sonar.api.scanner.ScannerSide;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.core.sarif.Driver;
import org.sonar.core.sarif.Result;
import org.sonar.core.sarif.Run;
import org.sonar.core.sarif.Tool;
import static java.util.Collections.emptyList;
import static java.util.stream.Collectors.toList;
import static org.sonar.api.utils.Preconditions.checkArgument;
@ScannerSide
public class RunMapper {
private static final Logger LOG = LoggerFactory.getLogger(RunMapper.class);
private final ResultMapper resultMapper;
RunMapper(ResultMapper resultMapper) {
this.resultMapper = resultMapper;
}
List<NewExternalIssue> mapRun(Run run) {
if (run.getResults().isEmpty()) {
return emptyList();
}
String driverName = getToolDriverName(run);
Map<String, String> ruleSeveritiesByRuleId = RulesSeverityDetector.detectRulesSeverities(run, driverName);
return run.getResults()
.stream()
.map(result -> toNewExternalIssue(driverName, ruleSeveritiesByRuleId.get(result.getRuleId()), result))
.filter(Optional::isPresent)
.map(Optional::get)
.collect(toList());
}
private static String getToolDriverName(Run run) throws IllegalArgumentException {
checkArgument(hasToolDriverNameDefined(run), "The run does not have a tool driver name defined.");
return run.getTool().getDriver().getName();
}
private Optional<NewExternalIssue> toNewExternalIssue(String driverName, @Nullable String ruleSeverity, Result result) {
try {
return Optional.of(resultMapper.mapResult(driverName, ruleSeverity, result));
} catch (Exception exception) {
LOG.warn("Failed to import an issue raised by tool {}, error: {}", driverName, exception.getMessage());
return Optional.empty();
}
}
private static boolean hasToolDriverNameDefined(Run run) {
return Optional.ofNullable(run)
.map(Run::getTool)
.map(Tool::getDriver)
.map(Driver::getName)
.isPresent();
}
}
| 3,068 | 34.686047 | 122 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/externalissue/sarif/Sarif210Importer.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.scanner.externalissue.sarif;
import org.sonar.core.sarif.Sarif210;
public interface Sarif210Importer {
/**
*
* @param sarif210 the deserialized sarif report
* @return the number of issues imported
*/
SarifImportResults importSarif(Sarif210 sarif210);
}
| 1,133 | 33.363636 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/externalissue/sarif/SarifImportResults.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.scanner.externalissue.sarif;
class SarifImportResults {
private final int successFullyImportedIssues;
private final int successFullyImportedRuns;
private final int failedRuns;
SarifImportResults(int successFullyImportedIssues, int successFullyImportedRuns, int failedRuns) {
this.successFullyImportedIssues = successFullyImportedIssues;
this.successFullyImportedRuns = successFullyImportedRuns;
this.failedRuns = failedRuns;
}
int getSuccessFullyImportedIssues() {
return successFullyImportedIssues;
}
int getSuccessFullyImportedRuns() {
return successFullyImportedRuns;
}
int getFailedRuns() {
return failedRuns;
}
static SarifImportResultBuilder builder() {
return new SarifImportResultBuilder();
}
static final class SarifImportResultBuilder {
private int successFullyImportedIssues;
private int successFullyImportedRuns;
private int failedRuns;
private SarifImportResultBuilder() {
}
SarifImportResultBuilder successFullyImportedIssues(int successFullyImportedIssues) {
this.successFullyImportedIssues = successFullyImportedIssues;
return this;
}
SarifImportResultBuilder successFullyImportedRuns(int successFullyImportedRuns) {
this.successFullyImportedRuns = successFullyImportedRuns;
return this;
}
SarifImportResultBuilder failedRuns(int failedRuns) {
this.failedRuns = failedRuns;
return this;
}
SarifImportResults build() {
return new SarifImportResults(successFullyImportedIssues, successFullyImportedRuns, failedRuns);
}
}
}
| 2,464 | 30.202532 | 102 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/externalissue/sarif/SarifIssuesImportSensor.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.scanner.externalissue.sarif;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.CoreProperties;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.api.config.Configuration;
import org.sonar.api.config.PropertyDefinition;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.scanner.ScannerSide;
import org.sonar.api.scanner.sensor.ProjectSensor;
import org.sonar.api.utils.MessageException;
import org.sonar.core.sarif.Sarif210;
import org.sonar.core.sarif.SarifSerializer;
import static java.lang.String.format;
@ScannerSide
public class SarifIssuesImportSensor implements ProjectSensor {
private static final Logger LOG = LoggerFactory.getLogger(SarifIssuesImportSensor.class);
static final String SARIF_REPORT_PATHS_PROPERTY_KEY = "sonar.sarifReportPaths";
private final SarifSerializer sarifSerializer;
private final Sarif210Importer sarifImporter;
private final Configuration config;
public SarifIssuesImportSensor(SarifSerializer sarifSerializer, Sarif210Importer sarifImporter, Configuration config) {
this.sarifSerializer = sarifSerializer;
this.sarifImporter = sarifImporter;
this.config = config;
}
public static List<PropertyDefinition> properties() {
return Collections.singletonList(
PropertyDefinition.builder(SARIF_REPORT_PATHS_PROPERTY_KEY)
.name("SARIF report paths")
.description("List of comma-separated paths (absolute or relative) containing a SARIF report with issues created by external rule engines.")
.category(CoreProperties.CATEGORY_EXTERNAL_ISSUES)
.onQualifiers(Qualifiers.PROJECT)
.build());
}
@Override
public void describe(SensorDescriptor descriptor) {
descriptor.name("Import external issues report from SARIF file.")
.onlyWhenConfiguration(c -> c.hasKey(SARIF_REPORT_PATHS_PROPERTY_KEY));
}
@Override
public void execute(SensorContext context) {
Set<String> reportPaths = loadReportPaths();
Map<String, SarifImportResults> filePathToImportResults = new HashMap<>();
for (String reportPath : reportPaths) {
try {
SarifImportResults sarifImportResults = processReport(context, reportPath);
filePathToImportResults.put(reportPath, sarifImportResults);
} catch (NoSuchFileException e) {
throw MessageException.of(format("SARIF report file not found: %s", e.getFile()));
} catch (Exception exception) {
LOG.warn("Failed to process SARIF report from file '{}', error: '{}'", reportPath, exception.getMessage());
}
}
filePathToImportResults.forEach(SarifIssuesImportSensor::displayResults);
}
private Set<String> loadReportPaths() {
return Arrays.stream(config.getStringArray(SARIF_REPORT_PATHS_PROPERTY_KEY)).collect(Collectors.toSet());
}
private SarifImportResults processReport(SensorContext context, String reportPath) throws NoSuchFileException {
LOG.debug("Importing SARIF issues from '{}'", reportPath);
Path reportFilePath = context.fileSystem().resolvePath(reportPath).toPath();
Sarif210 sarifReport = sarifSerializer.deserialize(reportFilePath);
return sarifImporter.importSarif(sarifReport);
}
private static void displayResults(String filePath, SarifImportResults sarifImportResults) {
if (sarifImportResults.getFailedRuns() > 0 && sarifImportResults.getSuccessFullyImportedRuns() > 0) {
LOG.warn("File {}: {} run(s) could not be imported (see warning above) and {} run(s) successfully imported ({} vulnerabilities in total).",
filePath, sarifImportResults.getFailedRuns(), sarifImportResults.getSuccessFullyImportedRuns(), sarifImportResults.getSuccessFullyImportedIssues());
} else if (sarifImportResults.getFailedRuns() > 0) {
LOG.warn("File {}: {} run(s) could not be imported (see warning above).",
filePath, sarifImportResults.getFailedRuns());
} else {
LOG.info("File {}: {} run(s) successfully imported ({} vulnerabilities in total).",
filePath, sarifImportResults.getSuccessFullyImportedRuns(), sarifImportResults.getSuccessFullyImportedIssues());
}
}
}
| 5,305 | 42.491803 | 156 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/externalissue/sarif/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.scanner.externalissue.sarif;
import javax.annotation.ParametersAreNonnullByDefault;
| 977 | 39.75 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/fs/InputModuleHierarchy.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.scanner.fs;
import java.util.Collection;
import javax.annotation.CheckForNull;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
@Immutable
public interface InputModuleHierarchy {
DefaultInputModule root();
boolean isRoot(DefaultInputModule module);
Collection<DefaultInputModule> children(DefaultInputModule module);
@CheckForNull
DefaultInputModule parent(DefaultInputModule module);
@CheckForNull
String relativePath(DefaultInputModule module);
@CheckForNull
String relativePathToRoot(DefaultInputModule module);
}
| 1,459 | 32.181818 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/fs/SensorStrategy.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.scanner.fs;
import org.sonar.api.batch.fs.InputFile;
/**
* A shared, mutable object in the project container.
* It's used during the execution of sensors to decide whether
* sensors should be executed once for the entire project, or per-module.
* It is also injected into each InputFile to change the behavior of {@link InputFile#relativePath()}
*/
public class SensorStrategy {
private boolean global = true;
public boolean isGlobal() {
return global;
}
public void setGlobal(boolean global) {
this.global = global;
}
}
| 1,410 | 32.595238 | 101 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/fs/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.scanner.fs;
import javax.annotation.ParametersAreNonnullByDefault;
| 961 | 37.48 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/genericcoverage/GenericCoverageReportParser.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.scanner.genericcoverage;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.xml.stream.XMLStreamException;
import org.codehaus.staxmate.in.SMHierarchicCursor;
import org.codehaus.staxmate.in.SMInputCursor;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.coverage.NewCoverage;
import org.sonar.api.utils.MessageException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GenericCoverageReportParser {
private static final Logger LOG = LoggerFactory.getLogger(GenericCoverageReportParser.class);
private static final String LINE_NUMBER_ATTR = "lineNumber";
private static final String COVERED_ATTR = "covered";
private static final String BRANCHES_TO_COVER_ATTR = "branchesToCover";
private static final String COVERED_BRANCHES_ATTR = "coveredBranches";
private static final int MAX_STORED_UNKNOWN_FILE_PATHS = 5;
private int numberOfUnknownFiles;
private final List<String> firstUnknownFiles = new ArrayList<>();
private final Set<String> matchedFileKeys = new HashSet<>();
public void parse(File reportFile, SensorContext context) {
try (InputStream inputStream = new FileInputStream(reportFile)) {
parse(inputStream, context);
} catch (Exception e) {
throw MessageException.of("Error during parsing of the generic coverage report '" + reportFile + "'. Look at SonarQube documentation to know the expected XML format.",
e);
}
}
private void parse(InputStream inputStream, SensorContext context) throws XMLStreamException {
new StaxParser(rootCursor -> {
rootCursor.advance();
parseRootNode(rootCursor, context);
}).parse(inputStream);
}
private void parseRootNode(SMHierarchicCursor rootCursor, SensorContext context) throws XMLStreamException {
checkElementName(rootCursor, "coverage");
String version = rootCursor.getAttrValue("version");
if (!"1".equals(version)) {
throw new IllegalStateException("Unknown report version: " + version + ". This parser only handles version 1.");
}
parseFiles(rootCursor.childElementCursor(), context);
}
private void parseFiles(SMInputCursor fileCursor, SensorContext context) throws XMLStreamException {
while (fileCursor.getNext() != null) {
checkElementName(fileCursor, "file");
String filePath = mandatoryAttribute(fileCursor, "path");
InputFile inputFile = context.fileSystem().inputFile(context.fileSystem().predicates().hasPath(filePath));
if (inputFile == null || inputFile.language() == null) {
numberOfUnknownFiles++;
if (numberOfUnknownFiles <= MAX_STORED_UNKNOWN_FILE_PATHS) {
firstUnknownFiles.add(filePath);
}
if (inputFile != null) {
LOG.debug("Skipping file '{}' in the generic coverage report because it doesn't have a known language", filePath);
}
continue;
}
matchedFileKeys.add(inputFile.key());
NewCoverage newCoverage = context.newCoverage().onFile(inputFile);
SMInputCursor lineToCoverCursor = fileCursor.childElementCursor();
while (lineToCoverCursor.getNext() != null) {
parseLineToCover(lineToCoverCursor, newCoverage);
}
newCoverage.save();
}
}
private static void parseLineToCover(SMInputCursor cursor, NewCoverage newCoverage)
throws XMLStreamException {
checkElementName(cursor, "lineToCover");
String lineNumberAsString = mandatoryAttribute(cursor, LINE_NUMBER_ATTR);
int lineNumber = intValue(lineNumberAsString, cursor, LINE_NUMBER_ATTR, 1);
boolean covered = getCoveredValue(cursor);
newCoverage.lineHits(lineNumber, covered ? 1 : 0);
String branchesToCoverAsString = cursor.getAttrValue(BRANCHES_TO_COVER_ATTR);
if (branchesToCoverAsString != null) {
int branchesToCover = intValue(branchesToCoverAsString, cursor, BRANCHES_TO_COVER_ATTR, 0);
String coveredBranchesAsString = cursor.getAttrValue(COVERED_BRANCHES_ATTR);
int coveredBranches = 0;
if (coveredBranchesAsString != null) {
coveredBranches = intValue(coveredBranchesAsString, cursor, COVERED_BRANCHES_ATTR, 0);
if (coveredBranches > branchesToCover) {
throw new IllegalStateException("\"coveredBranches\" should not be greater than \"branchesToCover\" on line " + cursor.getCursorLocation().getLineNumber());
}
}
newCoverage.conditions(lineNumber, branchesToCover, coveredBranches);
}
}
private static boolean getCoveredValue(SMInputCursor cursor) throws XMLStreamException {
String coveredAsString = mandatoryAttribute(cursor, COVERED_ATTR);
if (!"true".equalsIgnoreCase(coveredAsString) && !"false".equalsIgnoreCase(coveredAsString)) {
throw new IllegalStateException(expectedMessage("boolean value", COVERED_ATTR, coveredAsString, cursor.getCursorLocation().getLineNumber()));
}
return Boolean.parseBoolean(coveredAsString);
}
static void checkElementName(SMInputCursor cursor, String expectedName) throws XMLStreamException {
String elementName = cursor.getLocalName();
if (!expectedName.equals(elementName)) {
throw new IllegalStateException("Unknown XML node, expected \"" + expectedName + "\" but got \"" + elementName + "\" at line " + cursor.getCursorLocation().getLineNumber());
}
}
static String mandatoryAttribute(SMInputCursor cursor, String attributeName) throws XMLStreamException {
String attributeValue = cursor.getAttrValue(attributeName);
if (attributeValue == null) {
throw new IllegalStateException(
"Missing attribute \"" + attributeName + "\" in element \"" + cursor.getLocalName() + "\" at line " + cursor.getCursorLocation().getLineNumber());
}
return attributeValue;
}
static int intValue(String stringValue, SMInputCursor cursor, String attributeName, int minimum) throws XMLStreamException {
int intValue;
try {
intValue = Integer.valueOf(stringValue);
} catch (NumberFormatException e) {
throw new IllegalStateException(expectedMessage("integer value", attributeName, stringValue, cursor.getCursorLocation().getLineNumber()), e);
}
if (intValue < minimum) {
throw new IllegalStateException("Value of attribute \"" + attributeName + "\" at line " + cursor.getCursorLocation().getLineNumber() + " is \"" + intValue
+ "\" but it should be greater than or equal to " + minimum);
}
return intValue;
}
static long longValue(String stringValue, SMInputCursor cursor, String attributeName, long minimum) throws XMLStreamException {
long longValue;
try {
longValue = Long.valueOf(stringValue);
} catch (NumberFormatException e) {
throw new IllegalStateException(expectedMessage("long value", attributeName, stringValue, cursor.getCursorLocation().getLineNumber()), e);
}
if (longValue < minimum) {
throw new IllegalStateException("Value of attribute \"" + attributeName + "\" at line " + cursor.getCursorLocation().getLineNumber() + " is \"" + longValue
+ "\" but it should be greater than or equal to " + minimum);
}
return longValue;
}
private static String expectedMessage(String expected, String attributeName, String stringValue, int line) {
return "Expected " + expected + " for attribute \"" + attributeName + "\" at line " + line + " but got \"" + stringValue + "\"";
}
public int numberOfMatchedFiles() {
return matchedFileKeys.size();
}
public int numberOfUnknownFiles() {
return numberOfUnknownFiles;
}
public List<String> firstUnknownFiles() {
return firstUnknownFiles;
}
}
| 8,663 | 42.757576 | 179 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/genericcoverage/GenericCoverageSensor.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.scanner.genericcoverage;
import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.api.config.PropertyDefinition;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.scanner.sensor.ProjectSensor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.scanner.config.DefaultConfiguration;
import static org.sonar.api.CoreProperties.CATEGORY_CODE_COVERAGE;
public class GenericCoverageSensor implements ProjectSensor {
private static final Logger LOG = LoggerFactory.getLogger(GenericCoverageSensor.class);
static final String REPORT_PATHS_PROPERTY_KEY = "sonar.coverageReportPaths";
private final DefaultConfiguration config;
public GenericCoverageSensor(DefaultConfiguration config) {
this.config = config;
}
public static List<PropertyDefinition> properties() {
return Collections.singletonList(
PropertyDefinition.builder(REPORT_PATHS_PROPERTY_KEY)
.name("Coverage report paths")
.description("List of comma-separated paths (absolute or relative) containing coverage report.")
.category(CATEGORY_CODE_COVERAGE)
.onQualifiers(Qualifiers.PROJECT)
.multiValues(true)
.build());
}
@Override
public void describe(SensorDescriptor descriptor) {
descriptor.name("Generic Coverage Report")
.onlyWhenConfiguration(c -> c.hasKey(REPORT_PATHS_PROPERTY_KEY));
}
@Override
public void execute(SensorContext context) {
Set<String> reportPaths = loadReportPaths();
for (String reportPath : reportPaths) {
File reportFile = context.fileSystem().resolvePath(reportPath);
LOG.info("Parsing {}", reportFile);
GenericCoverageReportParser parser = new GenericCoverageReportParser();
parser.parse(reportFile, context);
LOG.info("Imported coverage data for {} files", parser.numberOfMatchedFiles());
int numberOfUnknownFiles = parser.numberOfUnknownFiles();
if (numberOfUnknownFiles > 0) {
LOG.info("Coverage data ignored for " + numberOfUnknownFiles + " unknown files, including:\n" + parser.firstUnknownFiles().stream().collect(Collectors.joining("\n")));
}
}
}
Set<String> loadReportPaths() {
return new LinkedHashSet<>(Arrays.asList(config.getStringArray(REPORT_PATHS_PROPERTY_KEY)));
}
}
| 3,401 | 35.978261 | 175 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/genericcoverage/GenericTestExecutionReportParser.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.scanner.genericcoverage;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.xml.stream.XMLStreamException;
import org.codehaus.staxmate.in.SMHierarchicCursor;
import org.codehaus.staxmate.in.SMInputCursor;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.utils.MessageException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.scanner.deprecated.test.DefaultTestCase;
import org.sonar.scanner.deprecated.test.DefaultTestCase.Status;
import org.sonar.scanner.deprecated.test.DefaultTestPlan;
import org.sonar.scanner.deprecated.test.TestPlanBuilder;
import static org.sonar.api.utils.Preconditions.checkState;
import static org.sonar.scanner.genericcoverage.GenericCoverageReportParser.checkElementName;
import static org.sonar.scanner.genericcoverage.GenericCoverageReportParser.longValue;
import static org.sonar.scanner.genericcoverage.GenericCoverageReportParser.mandatoryAttribute;
public class GenericTestExecutionReportParser {
private static final String ROOT_ELEMENT = "testExecutions";
private static final String OLD_ROOT_ELEMENT = "unitTest";
private static final Logger LOG = LoggerFactory.getLogger(GenericTestExecutionReportParser.class);
private static final String NAME_ATTR = "name";
private static final String DURATION_ATTR = "duration";
public static final String ERROR = "error";
public static final String FAILURE = "failure";
public static final String SKIPPED = "skipped";
private static final int MAX_STORED_UNKNOWN_FILE_PATHS = 5;
private final TestPlanBuilder testPlanBuilder;
private int numberOfUnknownFiles;
private final List<String> firstUnknownFiles = new ArrayList<>();
private final Set<String> matchedFileKeys = new HashSet<>();
public GenericTestExecutionReportParser(TestPlanBuilder testPlanBuilder) {
this.testPlanBuilder = testPlanBuilder;
}
public void parse(File reportFile, SensorContext context) {
try (InputStream inputStream = new FileInputStream(reportFile)) {
parse(inputStream, context);
} catch (Exception e) {
throw MessageException.of(
"Error during parsing of generic test execution report '" + reportFile + "'. Look at the SonarQube documentation to know the expected XML format.", e);
}
}
private void parse(InputStream inputStream, SensorContext context) throws XMLStreamException {
new StaxParser(rootCursor -> {
rootCursor.advance();
parseRootNode(rootCursor, context);
}).parse(inputStream);
}
private void parseRootNode(SMHierarchicCursor rootCursor, SensorContext context) throws XMLStreamException {
String elementName = rootCursor.getLocalName();
if (!OLD_ROOT_ELEMENT.equals(elementName) && !ROOT_ELEMENT.equals(elementName)) {
throw new IllegalStateException(
"Unknown XML node, expected \"" + ROOT_ELEMENT + "\" but got \"" + elementName + "\" at line " + rootCursor.getCursorLocation().getLineNumber());
}
if (OLD_ROOT_ELEMENT.equals(elementName)) {
LOG.warn("Using '" + OLD_ROOT_ELEMENT + "' as root element of the report is deprecated. Please change to '" + ROOT_ELEMENT + "'.");
}
String version = rootCursor.getAttrValue("version");
if (!"1".equals(version)) {
throw new IllegalStateException("Unknown report version: " + version + ". This parser only handles version 1.");
}
parseFiles(rootCursor.childElementCursor(), context);
}
private void parseFiles(SMInputCursor fileCursor, SensorContext context) throws XMLStreamException {
while (fileCursor.getNext() != null) {
checkElementName(fileCursor, "file");
String filePath = mandatoryAttribute(fileCursor, "path");
InputFile inputFile = context.fileSystem().inputFile(context.fileSystem().predicates().hasPath(filePath));
if (inputFile == null || inputFile.language() == null) {
numberOfUnknownFiles++;
if (numberOfUnknownFiles <= MAX_STORED_UNKNOWN_FILE_PATHS) {
firstUnknownFiles.add(filePath);
}
if (inputFile != null) {
LOG.debug("Skipping file '{}' in the generic test execution report because it doesn't have a known language", filePath);
}
continue;
}
checkState(
inputFile.type() != InputFile.Type.MAIN,
"Line %s of report refers to a file which is not configured as a test file: %s",
fileCursor.getCursorLocation().getLineNumber(),
filePath);
matchedFileKeys.add(inputFile.absolutePath());
DefaultTestPlan testPlan = testPlanBuilder.getTestPlan(inputFile);
SMInputCursor testCaseCursor = fileCursor.childElementCursor();
while (testCaseCursor.getNext() != null) {
parseTestCase(testCaseCursor, testPlan);
}
}
}
private static void parseTestCase(SMInputCursor cursor, DefaultTestPlan testPlan) throws XMLStreamException {
checkElementName(cursor, "testCase");
DefaultTestCase testCase = testPlan.addTestCase(mandatoryAttribute(cursor, NAME_ATTR));
Status status = Status.OK;
testCase.setDurationInMs(longValue(mandatoryAttribute(cursor, DURATION_ATTR), cursor, DURATION_ATTR, 0));
SMInputCursor child = cursor.descendantElementCursor();
if (child.getNext() != null) {
String elementName = child.getLocalName();
if (SKIPPED.equals(elementName)) {
status = Status.SKIPPED;
} else if (FAILURE.equals(elementName)) {
status = Status.FAILURE;
} else if (ERROR.equals(elementName)) {
status = Status.ERROR;
}
}
testCase.setStatus(status);
}
public int numberOfMatchedFiles() {
return matchedFileKeys.size();
}
public int numberOfUnknownFiles() {
return numberOfUnknownFiles;
}
public List<String> firstUnknownFiles() {
return firstUnknownFiles;
}
}
| 6,850 | 39.3 | 159 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/genericcoverage/GenericTestExecutionSensor.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.scanner.genericcoverage;
import java.io.File;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import org.sonar.api.batch.sensor.Sensor;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.api.config.PropertyDefinition;
import org.sonar.api.resources.Qualifiers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.scanner.config.DefaultConfiguration;
import org.sonar.scanner.deprecated.test.TestPlanBuilder;
import static org.sonar.api.CoreProperties.CATEGORY_CODE_COVERAGE;
public class GenericTestExecutionSensor implements Sensor {
private static final Logger LOG = LoggerFactory.getLogger(GenericTestExecutionSensor.class);
static final String REPORT_PATHS_PROPERTY_KEY = "sonar.testExecutionReportPaths";
/**
* @deprecated since 6.2
*/
@Deprecated
static final String OLD_UNIT_TEST_REPORT_PATHS_PROPERTY_KEY = "sonar.genericcoverage.unitTestReportPaths";
private final TestPlanBuilder testPlanBuilder;
private final DefaultConfiguration configuration;
public GenericTestExecutionSensor(TestPlanBuilder testPlanBuilder, DefaultConfiguration configuration) {
this.testPlanBuilder = testPlanBuilder;
this.configuration = configuration;
}
public static List<PropertyDefinition> properties() {
return Collections.singletonList(
PropertyDefinition.builder(REPORT_PATHS_PROPERTY_KEY)
.name("Unit tests results report paths")
.description("List of comma-separated paths (absolute or relative) containing unit tests results report.")
.category(CATEGORY_CODE_COVERAGE)
.onQualifiers(Qualifiers.PROJECT)
.multiValues(true)
.deprecatedKey(OLD_UNIT_TEST_REPORT_PATHS_PROPERTY_KEY)
.build());
}
@Override
public void describe(SensorDescriptor descriptor) {
descriptor.name("Generic Test Executions Report")
.global()
.onlyWhenConfiguration(conf -> conf.hasKey(REPORT_PATHS_PROPERTY_KEY));
}
@Override
public void execute(SensorContext context) {
if (configuration.getOriginalProperties().containsKey(OLD_UNIT_TEST_REPORT_PATHS_PROPERTY_KEY)) {
LOG.warn("Property '{}' is deprecated. Please use '{}' instead.", OLD_UNIT_TEST_REPORT_PATHS_PROPERTY_KEY, REPORT_PATHS_PROPERTY_KEY);
}
for (String reportPath : configuration.getStringArray(REPORT_PATHS_PROPERTY_KEY)) {
File reportFile = context.fileSystem().resolvePath(reportPath);
LOG.info("Parsing {}", reportFile);
GenericTestExecutionReportParser parser = new GenericTestExecutionReportParser(testPlanBuilder);
parser.parse(reportFile, context);
LOG.info("Imported test execution data for {} files", parser.numberOfMatchedFiles());
int numberOfUnknownFiles = parser.numberOfUnknownFiles();
if (numberOfUnknownFiles > 0) {
LOG.info("Test execution data ignored for {} unknown files, including:\n{}", numberOfUnknownFiles, parser.firstUnknownFiles().stream().collect(Collectors.joining("\n")));
}
}
}
}
| 3,956 | 39.377551 | 178 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/genericcoverage/StaxParser.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.scanner.genericcoverage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.net.URL;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLResolver;
import javax.xml.stream.XMLStreamException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.codehaus.staxmate.SMInputFactory;
import org.codehaus.staxmate.in.SMHierarchicCursor;
public class StaxParser {
private SMInputFactory inf;
private XmlStreamHandler streamHandler;
private boolean isoControlCharsAwareParser;
/**
* Stax parser for a given stream handler and iso control chars set awarness to off
*
* @param streamHandler the xml stream handler
*/
public StaxParser(XmlStreamHandler streamHandler) {
this(streamHandler, false);
}
/**
* Stax parser for a given stream handler and iso control chars set awarness to on.
* The iso control chars in the xml file will be replaced by simple spaces, usefull for
* potentially bogus XML files to parse, this has a small perfs overhead so use it only when necessary
*
* @param streamHandler the xml stream handler
* @param isoControlCharsAwareParser true or false
*/
public StaxParser(XmlStreamHandler streamHandler, boolean isoControlCharsAwareParser) {
this.streamHandler = streamHandler;
XMLInputFactory xmlFactory = XMLInputFactory.newInstance();
xmlFactory.setProperty(XMLInputFactory.IS_VALIDATING, false);
xmlFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
xmlFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, false);
this.isoControlCharsAwareParser = isoControlCharsAwareParser;
inf = new SMInputFactory(xmlFactory);
}
public void parse(File xmlFile) throws XMLStreamException {
FileInputStream input = null;
try {
input = new FileInputStream(xmlFile);
parse(input);
} catch (FileNotFoundException e) {
throw new XMLStreamException(e);
} finally {
IOUtils.closeQuietly(input);
}
}
public void parse(InputStream xmlInput) throws XMLStreamException {
xmlInput = isoControlCharsAwareParser ? new ISOControlCharAwareInputStream(xmlInput) : xmlInput;
parse(inf.rootElementCursor(xmlInput));
}
public void parse(Reader xmlReader) throws XMLStreamException {
if (isoControlCharsAwareParser) {
throw new IllegalStateException("Method call not supported when isoControlCharsAwareParser=true");
}
parse(inf.rootElementCursor(xmlReader));
}
public void parse(URL xmlUrl) throws XMLStreamException {
try {
parse(xmlUrl.openStream());
} catch (IOException e) {
throw new XMLStreamException(e);
}
}
private void parse(SMHierarchicCursor rootCursor) throws XMLStreamException {
try {
streamHandler.stream(rootCursor);
} finally {
rootCursor.getStreamReader().closeCompletely();
}
}
private static class UndeclaredEntitiesXMLResolver implements XMLResolver {
@Override
public Object resolveEntity(String arg0, String arg1, String fileName, String undeclaredEntity) throws XMLStreamException {
// avoid problems with XML docs containing undeclared entities.. return the entity under its raw form if not an unicode expression
if (StringUtils.startsWithIgnoreCase(undeclaredEntity, "u") && undeclaredEntity.length() == 5) {
int unicodeCharHexValue = Integer.parseInt(undeclaredEntity.substring(1), 16);
if (Character.isDefined(unicodeCharHexValue)) {
undeclaredEntity = new String(new char[] {(char) unicodeCharHexValue});
}
}
return undeclaredEntity;
}
}
/**
* Simple interface for handling XML stream to parse
*/
public interface XmlStreamHandler {
void stream(SMHierarchicCursor rootCursor) throws XMLStreamException;
}
private static class ISOControlCharAwareInputStream extends InputStream {
private InputStream inputToCheck;
public ISOControlCharAwareInputStream(InputStream inputToCheck) {
super();
this.inputToCheck = inputToCheck;
}
@Override
public int read() throws IOException {
return inputToCheck.read();
}
@Override
public int available() throws IOException {
return inputToCheck.available();
}
@Override
public void close() throws IOException {
inputToCheck.close();
}
@Override
public synchronized void mark(int readlimit) {
inputToCheck.mark(readlimit);
}
@Override
public boolean markSupported() {
return inputToCheck.markSupported();
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
int readen = inputToCheck.read(b, off, len);
checkBufferForISOControlChars(b, off, len);
return readen;
}
@Override
public int read(byte[] b) throws IOException {
int readen = inputToCheck.read(b);
checkBufferForISOControlChars(b, 0, readen);
return readen;
}
@Override
public synchronized void reset() throws IOException {
inputToCheck.reset();
}
@Override
public long skip(long n) throws IOException {
return inputToCheck.skip(n);
}
private static void checkBufferForISOControlChars(byte[] buffer, int off, int len) {
for (int i = off; i < len; i++) {
char streamChar = (char) buffer[i];
if (Character.isISOControl(streamChar) && streamChar != '\n') {
// replace control chars by a simple space
buffer[i] = ' ';
}
}
}
}
}
| 6,532 | 31.665 | 136 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/genericcoverage/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.scanner.genericcoverage;
import javax.annotation.ParametersAreNonnullByDefault;
| 974 | 38 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/DefaultFilterableIssue.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.scanner.issue;
import javax.annotation.concurrent.ThreadSafe;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.sonar.api.batch.fs.InputComponent;
import org.sonar.api.batch.fs.TextRange;
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.rule.RuleKey;
import org.sonar.api.scan.issue.filter.FilterableIssue;
import org.sonar.scanner.protocol.output.ScannerReport.Issue;
@ThreadSafe
public class DefaultFilterableIssue implements FilterableIssue {
private final Issue rawIssue;
private final InputComponent component;
private DefaultInputProject project;
public DefaultFilterableIssue(DefaultInputProject project, Issue rawIssue, InputComponent component) {
this.project = project;
this.rawIssue = rawIssue;
this.component = component;
}
@Override
public String componentKey() {
return component.key();
}
@Override
public RuleKey ruleKey() {
return RuleKey.of(rawIssue.getRuleRepository(), rawIssue.getRuleKey());
}
@Override
public String severity() {
return rawIssue.getSeverity().name();
}
@Override
public String message() {
return rawIssue.getMsg();
}
@Deprecated
@Override
public Integer line() {
return rawIssue.hasTextRange() ? rawIssue.getTextRange().getStartLine() : null;
}
@Override
public TextRange textRange() {
if (!rawIssue.hasTextRange()) {
return null;
}
return new DefaultTextRange(
new DefaultTextPointer(rawIssue.getTextRange().getStartLine(), rawIssue.getTextRange().getStartOffset()),
new DefaultTextPointer(rawIssue.getTextRange().getEndLine(), rawIssue.getTextRange().getEndOffset()));
}
@Override
public Double gap() {
return Double.compare(rawIssue.getGap(), 0D) != 0 ? rawIssue.getGap() : null;
}
@Override
public String projectKey() {
return project.key();
}
public InputComponent getComponent() {
return component;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
}
| 3,112 | 29.223301 | 111 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/DefaultIssueFilterChain.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.scanner.issue;
import java.util.Collections;
import java.util.List;
import javax.annotation.concurrent.ThreadSafe;
import org.sonar.api.scan.issue.filter.FilterableIssue;
import org.sonar.api.scan.issue.filter.IssueFilter;
import org.sonar.api.scan.issue.filter.IssueFilterChain;
@ThreadSafe
public class DefaultIssueFilterChain implements IssueFilterChain {
private final List<IssueFilter> filters;
public DefaultIssueFilterChain(IssueFilter... filters) {
this.filters = List.of(filters);
}
public DefaultIssueFilterChain() {
this.filters = Collections.emptyList();
}
private DefaultIssueFilterChain(List<IssueFilter> filters) {
this.filters = filters;
}
@Override
public boolean accept(FilterableIssue issue) {
if (filters.isEmpty()) {
return true;
} else {
return filters.get(0).accept(issue, new DefaultIssueFilterChain(filters.subList(1, filters.size())));
}
}
}
| 1,792 | 31.6 | 107 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/IssueFilters.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.scanner.issue;
import org.sonar.api.batch.fs.InputComponent;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.scan.issue.filter.FilterableIssue;
import org.sonar.api.scan.issue.filter.IssueFilter;
import org.sonar.api.scan.issue.filter.IssueFilterChain;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.springframework.beans.factory.annotation.Autowired;
/**
* @deprecated since 7.6, {@link IssueFilter} is deprecated
*/
@Deprecated
public class IssueFilters {
private final IssueFilterChain filterChain;
private final DefaultInputProject project;
@Autowired(required = false)
public IssueFilters(DefaultInputProject project, IssueFilter[] exclusionFilters) {
this.project = project;
this.filterChain = new DefaultIssueFilterChain(exclusionFilters);
}
@Autowired(required = false)
public IssueFilters(DefaultInputProject project) {
this(project, new IssueFilter[0]);
}
public boolean accept(InputComponent component, ScannerReport.Issue rawIssue) {
FilterableIssue fIssue = new DefaultFilterableIssue(project, rawIssue, component);
return filterChain.accept(fIssue);
}
}
| 2,030 | 35.927273 | 86 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/IssuePublisher.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.scanner.issue;
import java.util.Collection;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import javax.annotation.concurrent.ThreadSafe;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.batch.fs.TextRange;
import org.sonar.api.batch.fs.internal.DefaultInputComponent;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.rule.ActiveRule;
import org.sonar.api.batch.rule.ActiveRules;
import org.sonar.api.batch.sensor.issue.ExternalIssue;
import org.sonar.api.batch.sensor.issue.Issue;
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.internal.DefaultIssueFlow;
import org.sonar.scanner.protocol.Constants.Severity;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.protocol.output.ScannerReport.IssueLocation;
import org.sonar.scanner.protocol.output.ScannerReport.IssueType;
import org.sonar.scanner.report.ReportPublisher;
/**
* Initialize the issues raised during scan.
*/
@ThreadSafe
public class IssuePublisher {
private final ActiveRules activeRules;
private final IssueFilters filters;
private final ReportPublisher reportPublisher;
public IssuePublisher(ActiveRules activeRules, IssueFilters filters, ReportPublisher reportPublisher) {
this.activeRules = activeRules;
this.filters = filters;
this.reportPublisher = reportPublisher;
}
public boolean initAndAddIssue(Issue issue) {
DefaultInputComponent inputComponent = (DefaultInputComponent) issue.primaryLocation().inputComponent();
if (noSonar(inputComponent, issue)) {
return false;
}
ActiveRule activeRule = activeRules.find(issue.ruleKey());
if (activeRule == null) {
// rule does not exist or is not enabled -> ignore the issue
return false;
}
ScannerReport.Issue rawIssue = createReportIssue(issue, inputComponent.scannerId(), activeRule.severity());
if (filters.accept(inputComponent, rawIssue)) {
write(inputComponent.scannerId(), rawIssue);
return true;
}
return false;
}
private static boolean noSonar(DefaultInputComponent inputComponent, Issue issue) {
TextRange textRange = issue.primaryLocation().textRange();
return inputComponent.isFile()
&& textRange != null
&& ((DefaultInputFile) inputComponent).hasNoSonarAt(textRange.start().line())
&& !StringUtils.containsIgnoreCase(issue.ruleKey().rule(), "nosonar");
}
public void initAndAddExternalIssue(ExternalIssue issue) {
DefaultInputComponent inputComponent = (DefaultInputComponent) issue.primaryLocation().inputComponent();
ScannerReport.ExternalIssue rawExternalIssue = createReportExternalIssue(issue, inputComponent.scannerId());
write(inputComponent.scannerId(), rawExternalIssue);
}
private static String nullToEmpty(@Nullable String str) {
if (str == null) {
return "";
}
return str;
}
private static ScannerReport.Issue createReportIssue(Issue issue, int componentRef, String activeRuleSeverity) {
String primaryMessage = nullToEmpty(issue.primaryLocation().message());
org.sonar.api.batch.rule.Severity overriddenSeverity = issue.overriddenSeverity();
Severity severity = overriddenSeverity != null ? Severity.valueOf(overriddenSeverity.name()) : Severity.valueOf(activeRuleSeverity);
ScannerReport.Issue.Builder builder = ScannerReport.Issue.newBuilder();
ScannerReport.IssueLocation.Builder locationBuilder = IssueLocation.newBuilder();
ScannerReport.TextRange.Builder textRangeBuilder = ScannerReport.TextRange.newBuilder();
// non-null fields
builder.setSeverity(severity);
builder.setRuleRepository(issue.ruleKey().repository());
builder.setRuleKey(issue.ruleKey().rule());
builder.setMsg(primaryMessage);
builder.addAllMsgFormatting(toProtobufMessageFormattings(issue.primaryLocation().messageFormattings()));
locationBuilder.setMsg(primaryMessage);
locationBuilder.addAllMsgFormatting(toProtobufMessageFormattings(issue.primaryLocation().messageFormattings()));
locationBuilder.setComponentRef(componentRef);
TextRange primaryTextRange = issue.primaryLocation().textRange();
if (primaryTextRange != null) {
builder.setTextRange(toProtobufTextRange(textRangeBuilder, primaryTextRange));
}
Double gap = issue.gap();
if (gap != null) {
builder.setGap(gap);
}
applyFlows(builder::addFlow, locationBuilder, textRangeBuilder, issue.flows());
builder.setQuickFixAvailable(issue.isQuickFixAvailable());
issue.ruleDescriptionContextKey().ifPresent(builder::setRuleDescriptionContextKey);
List<String> codeVariants = issue.codeVariants();
if (codeVariants != null) {
builder.addAllCodeVariants(codeVariants);
}
return builder.build();
}
private static List<ScannerReport.MessageFormatting> toProtobufMessageFormattings(List<MessageFormatting> messageFormattings) {
return messageFormattings.stream()
.map(m -> ScannerReport.MessageFormatting.newBuilder()
.setStart(m.start())
.setEnd(m.end())
.setType(ScannerReport.MessageFormattingType.valueOf(m.type().name()))
.build())
.collect(Collectors.toList());
}
private static ScannerReport.ExternalIssue createReportExternalIssue(ExternalIssue issue, int componentRef) {
// primary location of an external issue must have a message
String primaryMessage = issue.primaryLocation().message();
Severity severity = Severity.valueOf(issue.severity().name());
IssueType issueType = IssueType.valueOf(issue.type().name());
ScannerReport.ExternalIssue.Builder builder = ScannerReport.ExternalIssue.newBuilder();
ScannerReport.IssueLocation.Builder locationBuilder = IssueLocation.newBuilder();
ScannerReport.TextRange.Builder textRangeBuilder = ScannerReport.TextRange.newBuilder();
// non-null fields
builder.setSeverity(severity);
builder.setType(issueType);
builder.setEngineId(issue.engineId());
builder.setRuleId(issue.ruleId());
builder.setMsg(primaryMessage);
builder.addAllMsgFormatting(toProtobufMessageFormattings(issue.primaryLocation().messageFormattings()));
locationBuilder.setMsg(primaryMessage);
locationBuilder.addAllMsgFormatting(toProtobufMessageFormattings(issue.primaryLocation().messageFormattings()));
locationBuilder.setComponentRef(componentRef);
TextRange primaryTextRange = issue.primaryLocation().textRange();
if (primaryTextRange != null) {
builder.setTextRange(toProtobufTextRange(textRangeBuilder, primaryTextRange));
}
Long effort = issue.remediationEffort();
if (effort != null) {
builder.setEffort(effort);
}
applyFlows(builder::addFlow, locationBuilder, textRangeBuilder, issue.flows());
return builder.build();
}
private static void applyFlows(Consumer<ScannerReport.Flow> consumer, ScannerReport.IssueLocation.Builder locationBuilder,
ScannerReport.TextRange.Builder textRangeBuilder, Collection<Flow> flows) {
ScannerReport.Flow.Builder flowBuilder = ScannerReport.Flow.newBuilder();
for (Flow f : flows) {
DefaultIssueFlow flow = (DefaultIssueFlow) f;
if (flow.locations().isEmpty()) {
return;
}
flowBuilder.clear();
for (org.sonar.api.batch.sensor.issue.IssueLocation location : flow.locations()) {
int locationComponentRef = ((DefaultInputComponent) location.inputComponent()).scannerId();
locationBuilder.clear();
locationBuilder.setComponentRef(locationComponentRef);
String message = location.message();
if (message != null) {
locationBuilder.setMsg(message);
locationBuilder.addAllMsgFormatting(toProtobufMessageFormattings(location.messageFormattings()));
}
TextRange textRange = location.textRange();
if (textRange != null) {
locationBuilder.setTextRange(toProtobufTextRange(textRangeBuilder, textRange));
}
flowBuilder.addLocation(locationBuilder.build());
}
if (flow.description() != null) {
flowBuilder.setDescription(flow.description());
}
flowBuilder.setType(toProtobufFlowType(flow.type()));
consumer.accept(flowBuilder.build());
}
}
private static ScannerReport.FlowType toProtobufFlowType(FlowType flowType) {
switch (flowType) {
case EXECUTION:
return ScannerReport.FlowType.EXECUTION;
case DATA:
return ScannerReport.FlowType.DATA;
case UNDEFINED:
return ScannerReport.FlowType.UNDEFINED;
default:
throw new IllegalArgumentException("Unrecognized flow type: " + flowType);
}
}
private static ScannerReport.TextRange toProtobufTextRange(ScannerReport.TextRange.Builder textRangeBuilder, TextRange primaryTextRange) {
textRangeBuilder.clear();
textRangeBuilder.setStartLine(primaryTextRange.start().line());
textRangeBuilder.setStartOffset(primaryTextRange.start().lineOffset());
textRangeBuilder.setEndLine(primaryTextRange.end().line());
textRangeBuilder.setEndOffset(primaryTextRange.end().lineOffset());
return textRangeBuilder.build();
}
public void write(int batchId, ScannerReport.Issue rawIssue) {
reportPublisher.getWriter().appendComponentIssue(batchId, rawIssue);
}
public void write(int batchId, ScannerReport.ExternalIssue rawIssue) {
reportPublisher.getWriter().appendComponentExternalIssue(batchId, rawIssue);
}
}
| 10,546 | 42.22541 | 140 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/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.scanner.issue;
import javax.annotation.ParametersAreNonnullByDefault;
| 963 | 39.166667 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/ignore/EnforceIssuesFilter.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.scanner.issue.ignore;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.concurrent.ThreadSafe;
import org.sonar.api.batch.fs.InputComponent;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.rule.internal.DefaultActiveRules;
import org.sonar.api.notifications.AnalysisWarnings;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.scan.issue.filter.FilterableIssue;
import org.sonar.api.scan.issue.filter.IssueFilter;
import org.sonar.api.scan.issue.filter.IssueFilterChain;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.scanner.issue.DefaultFilterableIssue;
import org.sonar.scanner.issue.ignore.pattern.IssueInclusionPatternInitializer;
import org.sonar.scanner.issue.ignore.pattern.IssuePattern;
@ThreadSafe
public class EnforceIssuesFilter implements IssueFilter {
private static final Logger LOG = LoggerFactory.getLogger(EnforceIssuesFilter.class);
private final List<IssuePattern> multicriteriaPatterns;
private final AnalysisWarnings analysisWarnings;
private final DefaultActiveRules activeRules;
private final Set<RuleKey> warnedDeprecatedRuleKeys = new LinkedHashSet<>();
private boolean warnDeprecatedIssuePatternAlreadyLogged;
public EnforceIssuesFilter(IssueInclusionPatternInitializer patternInitializer, AnalysisWarnings analysisWarnings, DefaultActiveRules activeRules) {
this.multicriteriaPatterns = List.copyOf(patternInitializer.getMulticriteriaPatterns());
this.analysisWarnings = analysisWarnings;
this.activeRules = activeRules;
}
@Override
public boolean accept(FilterableIssue issue, IssueFilterChain chain) {
boolean atLeastOneRuleMatched = false;
boolean atLeastOnePatternFullyMatched = false;
IssuePattern matchingPattern = null;
for (IssuePattern pattern : multicriteriaPatterns) {
if (ruleMatches(pattern, issue.ruleKey())) {
atLeastOneRuleMatched = true;
InputComponent component = ((DefaultFilterableIssue) issue).getComponent();
if (component.isFile()) {
DefaultInputFile file = (DefaultInputFile) component;
if (pattern.matchFile(file.getProjectRelativePath())) {
atLeastOnePatternFullyMatched = true;
matchingPattern = pattern;
} else if (pattern.matchFile(file.getModuleRelativePath())) {
warnOnceDeprecatedIssuePattern(
"Specifying module-relative paths at project level in property '" + IssueInclusionPatternInitializer.CONFIG_KEY + "' is deprecated. " +
"To continue matching files like '" + file.getProjectRelativePath() + "', update this property so that patterns refer to project-relative paths.");
atLeastOnePatternFullyMatched = true;
matchingPattern = pattern;
}
}
}
}
if (atLeastOneRuleMatched) {
if (atLeastOnePatternFullyMatched) {
LOG.debug("Issue '{}' enforced by pattern '{}'", issue, matchingPattern);
}
return atLeastOnePatternFullyMatched;
} else {
return chain.accept(issue);
}
}
private boolean ruleMatches(IssuePattern pattern, RuleKey ruleKey) {
if (activeRules.matchesDeprecatedKeys(ruleKey, pattern.getRulePattern())) {
String msg = String.format("A multicriteria issue enforce uses the rule key '%s' that has been changed. The pattern should be updated to '%s'",
pattern.getRulePattern(), ruleKey);
analysisWarnings.addUnique(msg);
if (warnedDeprecatedRuleKeys.add(ruleKey)) {
LOG.warn(msg);
}
return true;
}
return pattern.matchRule(ruleKey);
}
private void warnOnceDeprecatedIssuePattern(String msg) {
if (!warnDeprecatedIssuePatternAlreadyLogged) {
LOG.warn(msg);
analysisWarnings.addUnique(msg);
warnDeprecatedIssuePatternAlreadyLogged = true;
}
}
}
| 4,768 | 40.112069 | 163 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/ignore/IgnoreIssuesFilter.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.scanner.issue.ignore;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.sonar.api.batch.fs.InputComponent;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.rule.internal.DefaultActiveRules;
import org.sonar.api.notifications.AnalysisWarnings;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.scan.issue.filter.FilterableIssue;
import org.sonar.api.scan.issue.filter.IssueFilter;
import org.sonar.api.scan.issue.filter.IssueFilterChain;
import org.sonar.api.utils.WildcardPattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.scanner.issue.DefaultFilterableIssue;
public class IgnoreIssuesFilter implements IssueFilter {
private static final Logger LOG = LoggerFactory.getLogger(IgnoreIssuesFilter.class);
private final DefaultActiveRules activeRules;
private final AnalysisWarnings analysisWarnings;
private final Map<InputComponent, List<WildcardPattern>> rulePatternByComponent = new HashMap<>();
private final Set<RuleKey> warnedDeprecatedRuleKeys = new LinkedHashSet<>();
public IgnoreIssuesFilter(DefaultActiveRules activeRules, AnalysisWarnings analysisWarnings) {
this.activeRules = activeRules;
this.analysisWarnings = analysisWarnings;
}
@Override
public boolean accept(FilterableIssue issue, IssueFilterChain chain) {
InputComponent component = ((DefaultFilterableIssue) issue).getComponent();
if (isIgnoreIssue(component, issue)) {
return false;
}
if (hasRuleMatchFor(component, issue)) {
return false;
}
return chain.accept(issue);
}
private static boolean isIgnoreIssue(InputComponent component, FilterableIssue issue) {
if (component.isFile()) {
DefaultInputFile inputFile = (DefaultInputFile) component;
return inputFile.isIgnoreAllIssues() || inputFile.isIgnoreAllIssuesOnLine(issue.line());
}
return false;
}
public void addRuleExclusionPatternForComponent(DefaultInputFile inputFile, WildcardPattern rulePattern) {
if ("*".equals(rulePattern.toString())) {
inputFile.setIgnoreAllIssues(true);
} else {
rulePatternByComponent.computeIfAbsent(inputFile, x -> new LinkedList<>()).add(rulePattern);
}
}
private boolean hasRuleMatchFor(InputComponent component, FilterableIssue issue) {
for (WildcardPattern pattern : rulePatternByComponent.getOrDefault(component, Collections.emptyList())) {
if (pattern.match(issue.ruleKey().toString())) {
LOG.debug("Issue '{}' ignored by exclusion pattern '{}'", issue, pattern);
return true;
}
RuleKey ruleKey = issue.ruleKey();
if (activeRules.matchesDeprecatedKeys(ruleKey, pattern)) {
String msg = String.format("A multicriteria issue exclusion uses the rule key '%s' that has been changed. The pattern should be updated to '%s'", pattern, ruleKey);
analysisWarnings.addUnique(msg);
if (warnedDeprecatedRuleKeys.add(ruleKey)) {
LOG.warn(msg);
}
LOG.debug("Issue '{}' ignored by exclusion pattern '{}' matching a deprecated rule key", issue, pattern);
return true;
}
}
return false;
}
}
| 4,169 | 37.971963 | 172 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/ignore/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.scanner.issue.ignore;
import javax.annotation.ParametersAreNonnullByDefault;
| 970 | 39.458333 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/ignore/pattern/AbstractPatternInitializer.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.scanner.issue.ignore.pattern;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.config.Configuration;
import org.sonar.api.utils.MessageException;
public abstract class AbstractPatternInitializer {
private final Configuration settings;
private List<IssuePattern> multicriteriaPatterns;
protected AbstractPatternInitializer(Configuration config) {
this.settings = config;
initPatterns();
}
protected Configuration getSettings() {
return settings;
}
public List<IssuePattern> getMulticriteriaPatterns() {
return multicriteriaPatterns;
}
public boolean hasConfiguredPatterns() {
return hasMulticriteriaPatterns();
}
public boolean hasMulticriteriaPatterns() {
return !multicriteriaPatterns.isEmpty();
}
protected final void initPatterns() {
// Patterns Multicriteria
multicriteriaPatterns = new ArrayList<>();
for (String id : settings.getStringArray(getMulticriteriaConfigurationKey())) {
String propPrefix = getMulticriteriaConfigurationKey() + "." + id + ".";
String filePathPattern = settings.get(propPrefix + "resourceKey").orElse(null);
if (StringUtils.isBlank(filePathPattern)) {
throw MessageException.of("Issue exclusions are misconfigured. File pattern is mandatory for each entry of '" + getMulticriteriaConfigurationKey() + "'");
}
String ruleKeyPattern = settings.get(propPrefix + "ruleKey").orElse(null);
if (StringUtils.isBlank(ruleKeyPattern)) {
throw MessageException.of("Issue exclusions are misconfigured. Rule key pattern is mandatory for each entry of '" + getMulticriteriaConfigurationKey() + "'");
}
IssuePattern pattern = new IssuePattern(filePathPattern, ruleKeyPattern);
multicriteriaPatterns.add(pattern);
}
}
protected abstract String getMulticriteriaConfigurationKey();
}
| 2,775 | 36.513514 | 166 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/ignore/pattern/BlockIssuePattern.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.scanner.issue.ignore.pattern;
public class BlockIssuePattern {
private String beginBlockRegexp;
private String endBlockRegexp;
public BlockIssuePattern(String beginBlockRegexp, String endBlockRegexp) {
this.beginBlockRegexp = beginBlockRegexp;
this.endBlockRegexp = endBlockRegexp;
}
public String getBeginBlockRegexp() {
return beginBlockRegexp;
}
public String getEndBlockRegexp() {
return endBlockRegexp;
}
}
| 1,309 | 32.589744 | 76 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/ignore/pattern/IssueExclusionPatternInitializer.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.scanner.issue.ignore.pattern;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.config.Configuration;
import org.sonar.api.utils.MessageException;
import org.sonar.core.config.IssueExclusionProperties;
public class IssueExclusionPatternInitializer extends AbstractPatternInitializer {
public static final String CONFIG_KEY = IssueExclusionProperties.EXCLUSION_KEY_PREFIX + ".multicriteria";
private List<BlockIssuePattern> blockPatterns;
private List<String> allFilePatterns;
public IssueExclusionPatternInitializer(Configuration settings) {
super(settings);
loadFileContentPatterns();
}
@Override
protected String getMulticriteriaConfigurationKey() {
return CONFIG_KEY;
}
@Override
public boolean hasConfiguredPatterns() {
return hasFileContentPattern() || hasMulticriteriaPatterns();
}
private void loadFileContentPatterns() {
// Patterns Block
blockPatterns = new ArrayList<>();
for (String id : getSettings().getStringArray(IssueExclusionProperties.PATTERNS_BLOCK_KEY)) {
String propPrefix = IssueExclusionProperties.PATTERNS_BLOCK_KEY + "." + id + ".";
String beginBlockRegexp = getSettings().get(propPrefix + IssueExclusionProperties.BEGIN_BLOCK_REGEXP).orElse(null);
if (StringUtils.isBlank(beginBlockRegexp)) {
throw MessageException.of("Issue exclusions are misconfigured. Start block regexp is mandatory for each entry of '" + IssueExclusionProperties.PATTERNS_BLOCK_KEY + "'");
}
String endBlockRegexp = getSettings().get(propPrefix + IssueExclusionProperties.END_BLOCK_REGEXP).orElse(null);
// As per configuration help, missing second field means: from start regexp to EOF
BlockIssuePattern pattern = new BlockIssuePattern(nullToEmpty(beginBlockRegexp), nullToEmpty(endBlockRegexp));
blockPatterns.add(pattern);
}
blockPatterns = Collections.unmodifiableList(blockPatterns);
// Patterns All File
allFilePatterns = new ArrayList<>();
for (String id : getSettings().getStringArray(IssueExclusionProperties.PATTERNS_ALLFILE_KEY)) {
String propPrefix = IssueExclusionProperties.PATTERNS_ALLFILE_KEY + "." + id + ".";
String allFileRegexp = getSettings().get(propPrefix + IssueExclusionProperties.FILE_REGEXP).orElse(null);
if (StringUtils.isBlank(allFileRegexp)) {
throw MessageException.of("Issue exclusions are misconfigured. Remove blank entries from '" + IssueExclusionProperties.PATTERNS_ALLFILE_KEY + "'");
}
allFilePatterns.add(nullToEmpty(allFileRegexp));
}
allFilePatterns = Collections.unmodifiableList(allFilePatterns);
}
private static String nullToEmpty(@Nullable String str) {
if (str == null) {
return "";
}
return str;
}
public List<BlockIssuePattern> getBlockPatterns() {
return blockPatterns;
}
public List<String> getAllFilePatterns() {
return allFilePatterns;
}
public boolean hasFileContentPattern() {
return !(blockPatterns.isEmpty() && allFilePatterns.isEmpty());
}
}
| 4,025 | 39.26 | 177 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/ignore/pattern/IssueInclusionPatternInitializer.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.scanner.issue.ignore.pattern;
import org.sonar.api.config.Configuration;
import org.sonar.core.config.IssueExclusionProperties;
public class IssueInclusionPatternInitializer extends AbstractPatternInitializer {
public static final String CONFIG_KEY = IssueExclusionProperties.INCLUSION_KEY_PREFIX + ".multicriteria";
public IssueInclusionPatternInitializer(Configuration settings) {
super(settings);
}
@Override
protected String getMulticriteriaConfigurationKey() {
return CONFIG_KEY;
}
}
| 1,375 | 35.210526 | 107 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/ignore/pattern/IssuePattern.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.scanner.issue.ignore.pattern;
import com.google.common.base.MoreObjects;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.utils.WildcardPattern;
@Immutable
public class IssuePattern {
private final WildcardPattern filePattern;
private final WildcardPattern rulePattern;
public IssuePattern(String filePattern, String rulePattern) {
this.filePattern = WildcardPattern.create(filePattern);
this.rulePattern = WildcardPattern.create(rulePattern);
}
public WildcardPattern getRulePattern() {
return rulePattern;
}
public boolean matchRule(RuleKey rule) {
return rulePattern.match(rule.toString());
}
public boolean matchFile(@Nullable String filePath) {
return filePath != null && filePattern.match(filePath);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("filePattern", filePattern)
.add("rulePattern", rulePattern)
.toString();
}
}
| 1,893 | 30.566667 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/ignore/pattern/LineRange.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.scanner.issue.ignore.pattern;
import java.util.LinkedHashSet;
import java.util.Objects;
import java.util.Set;
import static org.sonar.api.utils.Preconditions.checkArgument;
public class LineRange {
private int from;
private int to;
public LineRange(int line) {
this(line, line);
}
public LineRange(int from, int to) {
checkArgument(from <= to, "Line range is not valid: %s must be greater or equal than %s", to, from);
this.from = from;
this.to = to;
}
public boolean in(int lineId) {
return from <= lineId && lineId <= to;
}
public Set<Integer> toLines() {
Set<Integer> lines = new LinkedHashSet<>(to - from + 1);
for (int index = from; index <= to; index++) {
lines.add(index);
}
return lines;
}
public int from() {
return from;
}
public int to() {
return to;
}
@Override
public String toString() {
return "[" + from + "-" + to + "]";
}
@Override
public int hashCode() {
return Objects.hash(from, to);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
if (fieldsDiffer((LineRange) obj)) {
return false;
}
return true;
}
private boolean fieldsDiffer(LineRange other) {
return from != other.from || to != other.to;
}
}
| 2,285 | 23.319149 | 104 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/ignore/pattern/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.scanner.issue.ignore.pattern;
import javax.annotation.ParametersAreNonnullByDefault;
| 978 | 39.791667 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/ignore/scanner/IssueExclusionsLoader.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.scanner.issue.ignore.scanner;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.CheckForNull;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.notifications.AnalysisWarnings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.charhandler.CharHandler;
import org.sonar.scanner.issue.ignore.IgnoreIssuesFilter;
import org.sonar.scanner.issue.ignore.pattern.BlockIssuePattern;
import org.sonar.scanner.issue.ignore.pattern.IssueExclusionPatternInitializer;
import org.sonar.scanner.issue.ignore.pattern.IssuePattern;
public final class IssueExclusionsLoader {
private static final Logger LOG = LoggerFactory.getLogger(IssueExclusionsLoader.class);
private final List<java.util.regex.Pattern> allFilePatterns;
private final List<DoubleRegexpMatcher> blockMatchers;
private final IgnoreIssuesFilter ignoreIssuesFilter;
private final AnalysisWarnings analysisWarnings;
private final IssueExclusionPatternInitializer patternsInitializer;
private final boolean enableCharHandler;
private boolean warnDeprecatedIssuePatternAlreadyLogged;
public IssueExclusionsLoader(IssueExclusionPatternInitializer patternsInitializer, IgnoreIssuesFilter ignoreIssuesFilter, AnalysisWarnings analysisWarnings) {
this.patternsInitializer = patternsInitializer;
this.ignoreIssuesFilter = ignoreIssuesFilter;
this.analysisWarnings = analysisWarnings;
this.allFilePatterns = new ArrayList<>();
this.blockMatchers = new ArrayList<>();
for (String pattern : patternsInitializer.getAllFilePatterns()) {
allFilePatterns.add(java.util.regex.Pattern.compile(pattern));
}
for (BlockIssuePattern pattern : patternsInitializer.getBlockPatterns()) {
blockMatchers.add(new DoubleRegexpMatcher(
java.util.regex.Pattern.compile(pattern.getBeginBlockRegexp()),
java.util.regex.Pattern.compile(pattern.getEndBlockRegexp())));
}
enableCharHandler = !allFilePatterns.isEmpty() || !blockMatchers.isEmpty();
}
public void addMulticriteriaPatterns(DefaultInputFile inputFile) {
for (IssuePattern pattern : patternsInitializer.getMulticriteriaPatterns()) {
if (pattern.matchFile(inputFile.getProjectRelativePath())) {
ignoreIssuesFilter.addRuleExclusionPatternForComponent(inputFile, pattern.getRulePattern());
} else if (pattern.matchFile(inputFile.getModuleRelativePath())) {
warnOnceDeprecatedIssuePattern(
"Specifying module-relative paths at project level in property '" + IssueExclusionPatternInitializer.CONFIG_KEY + "' is deprecated. " +
"To continue matching files like '" + inputFile.getProjectRelativePath() + "', update this property so that patterns refer to project-relative paths.");
ignoreIssuesFilter.addRuleExclusionPatternForComponent(inputFile, pattern.getRulePattern());
}
}
}
private void warnOnceDeprecatedIssuePattern(String msg) {
if (!warnDeprecatedIssuePatternAlreadyLogged) {
LOG.warn(msg);
analysisWarnings.addUnique(msg);
warnDeprecatedIssuePatternAlreadyLogged = true;
}
}
@CheckForNull
public CharHandler createCharHandlerFor(DefaultInputFile inputFile) {
if (enableCharHandler) {
return new IssueExclusionsRegexpScanner(inputFile, allFilePatterns, blockMatchers);
}
return null;
}
public static class DoubleRegexpMatcher {
private java.util.regex.Pattern firstPattern;
private java.util.regex.Pattern secondPattern;
DoubleRegexpMatcher(java.util.regex.Pattern firstPattern, java.util.regex.Pattern secondPattern) {
this.firstPattern = firstPattern;
this.secondPattern = secondPattern;
}
boolean matchesFirstPattern(String line) {
return firstPattern.matcher(line).find();
}
boolean matchesSecondPattern(String line) {
return hasSecondPattern() && secondPattern.matcher(line).find();
}
boolean hasSecondPattern() {
return StringUtils.isNotEmpty(secondPattern.toString());
}
}
@Override
public String toString() {
return "Issues Exclusions - Source Scanner";
}
}
| 5,066 | 40.532787 | 164 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/ignore/scanner/IssueExclusionsRegexpScanner.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.scanner.issue.ignore.scanner;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.charhandler.CharHandler;
import org.sonar.scanner.issue.ignore.pattern.LineRange;
import org.sonar.scanner.issue.ignore.scanner.IssueExclusionsLoader.DoubleRegexpMatcher;
public class IssueExclusionsRegexpScanner extends CharHandler {
private static final Logger LOG = LoggerFactory.getLogger(IssueExclusionsRegexpScanner.class);
private final StringBuilder sb = new StringBuilder();
private final List<Pattern> allFilePatterns;
private final List<DoubleRegexpMatcher> blockMatchers;
private final DefaultInputFile inputFile;
private int lineIndex = 1;
private List<LineExclusion> lineExclusions = new ArrayList<>();
private LineExclusion currentLineExclusion = null;
private int fileLength = 0;
private DoubleRegexpMatcher currentMatcher;
private boolean ignoreAllIssues;
IssueExclusionsRegexpScanner(DefaultInputFile inputFile, List<Pattern> allFilePatterns, List<DoubleRegexpMatcher> blockMatchers) {
this.allFilePatterns = allFilePatterns;
this.blockMatchers = blockMatchers;
this.inputFile = inputFile;
LOG.debug("Evaluate issue exclusions for '{}'", inputFile.getProjectRelativePath());
}
@Override
public void handleIgnoreEoL(char c) {
if (ignoreAllIssues) {
return;
}
sb.append(c);
}
@Override
public void newLine() {
if (ignoreAllIssues) {
return;
}
processLine(sb.toString());
sb.setLength(0);
lineIndex++;
}
@Override
public void eof() {
if (ignoreAllIssues) {
return;
}
processLine(sb.toString());
if (currentMatcher != null && !currentMatcher.hasSecondPattern()) {
// this will happen when there is a start block regexp but no end block regexp
endExclusion(lineIndex + 1);
}
// now create the new line-based pattern for this file if there are exclusions
fileLength = lineIndex;
if (!lineExclusions.isEmpty()) {
Set<LineRange> lineRanges = convertLineExclusionsToLineRanges();
LOG.debug(" - Line exclusions found: {}", lineRanges.stream().map(LineRange::toString).collect(Collectors.joining(",")));
inputFile.addIgnoreIssuesOnLineRanges(lineRanges.stream().map(r -> new int[] {r.from(), r.to()}).collect(Collectors.toList()));
}
}
private void processLine(String line) {
if (line.trim().length() == 0) {
return;
}
// first check the single regexp patterns that can be used to totally exclude a file
for (Pattern pattern : allFilePatterns) {
if (pattern.matcher(line).find()) {
// nothing more to do on this file
LOG.debug(" - Exclusion pattern '{}': all issues in this file will be ignored.", pattern);
ignoreAllIssues = true;
inputFile.setIgnoreAllIssues(true);
return;
}
}
// then check the double regexps if we're still here
checkDoubleRegexps(line, lineIndex);
}
private Set<LineRange> convertLineExclusionsToLineRanges() {
Set<LineRange> lineRanges = new HashSet<>(lineExclusions.size());
for (LineExclusion lineExclusion : lineExclusions) {
lineRanges.add(lineExclusion.toLineRange(fileLength));
}
return lineRanges;
}
private void checkDoubleRegexps(String line, int lineIndex) {
if (currentMatcher == null) {
for (DoubleRegexpMatcher matcher : blockMatchers) {
if (matcher.matchesFirstPattern(line)) {
startExclusion(lineIndex);
currentMatcher = matcher;
break;
}
}
} else {
if (currentMatcher.matchesSecondPattern(line)) {
endExclusion(lineIndex);
currentMatcher = null;
}
}
}
private void startExclusion(int lineIndex) {
currentLineExclusion = new LineExclusion(lineIndex);
lineExclusions.add(currentLineExclusion);
}
private void endExclusion(int lineIndex) {
currentLineExclusion.setEnd(lineIndex);
currentLineExclusion = null;
}
private static class LineExclusion {
private int start;
private int end;
LineExclusion(int start) {
this.start = start;
this.end = -1;
}
void setEnd(int end) {
this.end = end;
}
public LineRange toLineRange(int fileLength) {
return new LineRange(start, end == -1 ? fileLength : end);
}
}
}
| 5,456 | 31.289941 | 133 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/ignore/scanner/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.scanner.issue.ignore.scanner;
import javax.annotation.ParametersAreNonnullByDefault;
| 978 | 39.791667 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/mediumtest/AnalysisObserver.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.scanner.mediumtest;
import org.sonar.api.ExtensionPoint;
import org.sonar.api.scanner.ScannerSide;
import org.sonar.scanner.scan.SpringProjectScanContainer;
@ScannerSide
@ExtensionPoint
@FunctionalInterface
public interface AnalysisObserver {
void analysisCompleted(SpringProjectScanContainer container);
}
| 1,174 | 33.558824 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/mediumtest/AnalysisObservers.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.scanner.mediumtest;
import org.sonar.scanner.scan.SpringProjectScanContainer;
public class AnalysisObservers {
private final AnalysisObserver[] observers;
private final SpringProjectScanContainer projectScanContainer;
public AnalysisObservers(SpringProjectScanContainer projectScanContainer, AnalysisObserver... observers) {
this.projectScanContainer = projectScanContainer;
this.observers = observers;
}
public void notifyEndOfScanTask() {
for (AnalysisObserver analysisObserver : observers) {
analysisObserver.analysisCompleted(projectScanContainer);
}
}
}
| 1,460 | 34.634146 | 108 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/mediumtest/AnalysisResult.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.scanner.mediumtest;
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 javax.annotation.CheckForNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.batch.fs.InputComponent;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.TextPointer;
import org.sonar.api.batch.fs.TextRange;
import org.sonar.api.batch.fs.internal.DefaultInputComponent;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.sensor.highlighting.TypeOfText;
import org.sonar.api.scanner.fs.InputProject;
import org.sonar.core.util.CloseableIterator;
import org.sonar.scanner.protocol.output.FileStructure;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.protocol.output.ScannerReport.Component;
import org.sonar.scanner.protocol.output.ScannerReport.Symbol;
import org.sonar.scanner.protocol.output.ScannerReportReader;
import org.sonar.scanner.report.ScannerReportUtils;
import org.sonar.scanner.scan.SpringProjectScanContainer;
import org.sonar.scanner.scan.filesystem.InputComponentStore;
public class AnalysisResult implements AnalysisObserver {
private static final Logger LOG = LoggerFactory.getLogger(AnalysisResult.class);
private Map<String, InputFile> inputFilesByKeys = new HashMap<>();
private InputProject project;
private ScannerReportReader reader;
@Override
public void analysisCompleted(SpringProjectScanContainer container) {
LOG.info("Store analysis results in memory for later assertions in medium test");
FileStructure fileStructure = container.getComponentByType(FileStructure.class);
reader = new ScannerReportReader(fileStructure);
project = container.getComponentByType(InputProject.class);
storeFs(container);
}
public ScannerReportReader getReportReader() {
return reader;
}
private void storeFs(SpringProjectScanContainer container) {
InputComponentStore inputFileCache = container.getComponentByType(InputComponentStore.class);
for (InputFile inputPath : inputFileCache.inputFiles()) {
inputFilesByKeys.put(((DefaultInputFile) inputPath).getProjectRelativePath(), inputPath);
}
}
public Component getReportComponent(InputComponent inputComponent) {
return getReportReader().readComponent(((DefaultInputComponent) inputComponent).scannerId());
}
public Component getReportComponent(int scannerId) {
return getReportReader().readComponent(scannerId);
}
public List<ScannerReport.Issue> issuesFor(InputComponent inputComponent) {
return issuesFor(((DefaultInputComponent) inputComponent).scannerId());
}
public List<ScannerReport.ExternalIssue> externalIssuesFor(InputComponent inputComponent) {
return externalIssuesFor(((DefaultInputComponent) inputComponent).scannerId());
}
public List<ScannerReport.Issue> issuesFor(Component reportComponent) {
int ref = reportComponent.getRef();
return issuesFor(ref);
}
private List<ScannerReport.Issue> issuesFor(int ref) {
List<ScannerReport.Issue> result = new ArrayList<>();
try (CloseableIterator<ScannerReport.Issue> it = reader.readComponentIssues(ref)) {
while (it.hasNext()) {
result.add(it.next());
}
}
return result;
}
private List<ScannerReport.ExternalIssue> externalIssuesFor(int ref) {
List<ScannerReport.ExternalIssue> result = new ArrayList<>();
try (CloseableIterator<ScannerReport.ExternalIssue> it = reader.readComponentExternalIssues(ref)) {
while (it.hasNext()) {
result.add(it.next());
}
}
return result;
}
public InputProject project() {
return project;
}
public Collection<InputFile> inputFiles() {
return inputFilesByKeys.values();
}
@CheckForNull
public InputFile inputFile(String relativePath) {
return inputFilesByKeys.get(relativePath);
}
public Map<String, List<ScannerReport.Measure>> allMeasures() {
Map<String, List<ScannerReport.Measure>> result = new HashMap<>();
List<ScannerReport.Measure> projectMeasures = new ArrayList<>();
try (CloseableIterator<ScannerReport.Measure> it = reader.readComponentMeasures(((DefaultInputComponent) project).scannerId())) {
while (it.hasNext()) {
projectMeasures.add(it.next());
}
}
result.put(project.key(), projectMeasures);
for (InputFile inputFile : inputFilesByKeys.values()) {
List<ScannerReport.Measure> measures = new ArrayList<>();
try (CloseableIterator<ScannerReport.Measure> it = reader.readComponentMeasures(((DefaultInputComponent) inputFile).scannerId())) {
while (it.hasNext()) {
measures.add(it.next());
}
}
result.put(inputFile.key(), measures);
}
return result;
}
/**
* Get highlighting types at a given position in an inputfile
*
* @param lineOffset 0-based offset in file
*/
public List<TypeOfText> highlightingTypeFor(InputFile file, int line, int lineOffset) {
int ref = ((DefaultInputComponent) file).scannerId();
if (!reader.hasSyntaxHighlighting(ref)) {
return Collections.emptyList();
}
TextPointer pointer = file.newPointer(line, lineOffset);
List<TypeOfText> result = new ArrayList<>();
try (CloseableIterator<ScannerReport.SyntaxHighlightingRule> it = reader.readComponentSyntaxHighlighting(ref)) {
while (it.hasNext()) {
ScannerReport.SyntaxHighlightingRule rule = it.next();
TextRange ruleRange = toRange(file, rule.getRange());
if (ruleRange.start().compareTo(pointer) <= 0 && ruleRange.end().compareTo(pointer) > 0) {
result.add(ScannerReportUtils.toBatchType(rule.getType()));
}
}
} catch (Exception e) {
throw new IllegalStateException("Can't read syntax highlighting for " + file, e);
}
return result;
}
private static TextRange toRange(InputFile file, ScannerReport.TextRange reportRange) {
return file.newRange(file.newPointer(reportRange.getStartLine(), reportRange.getStartOffset()), file.newPointer(reportRange.getEndLine(), reportRange.getEndOffset()));
}
/**
* Get list of all start positions of a symbol in an inputfile
*
* @param symbolStartLine 0-based start offset for the symbol in file
* @param symbolStartLineOffset 0-based end offset for the symbol in file
*/
@CheckForNull
public List<ScannerReport.TextRange> symbolReferencesFor(InputFile file, int symbolStartLine, int symbolStartLineOffset) {
int ref = ((DefaultInputComponent) file).scannerId();
try (CloseableIterator<Symbol> symbols = getReportReader().readComponentSymbols(ref)) {
while (symbols.hasNext()) {
Symbol symbol = symbols.next();
if (symbol.getDeclaration().getStartLine() == symbolStartLine && symbol.getDeclaration().getStartOffset() == symbolStartLineOffset) {
return symbol.getReferenceList();
}
}
}
return Collections.emptyList();
}
public List<ScannerReport.Duplication> duplicationsFor(InputFile file) {
List<ScannerReport.Duplication> result = new ArrayList<>();
int ref = ((DefaultInputComponent) file).scannerId();
try (CloseableIterator<ScannerReport.Duplication> it = getReportReader().readComponentDuplications(ref)) {
while (it.hasNext()) {
result.add(it.next());
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
return result;
}
public List<ScannerReport.CpdTextBlock> duplicationBlocksFor(InputFile file) {
List<ScannerReport.CpdTextBlock> result = new ArrayList<>();
int ref = ((DefaultInputComponent) file).scannerId();
try (CloseableIterator<ScannerReport.CpdTextBlock> it = getReportReader().readCpdTextBlocks(ref)) {
while (it.hasNext()) {
result.add(it.next());
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
return result;
}
@CheckForNull
public ScannerReport.LineCoverage coverageFor(InputFile file, int line) {
int ref = ((DefaultInputComponent) file).scannerId();
try (CloseableIterator<ScannerReport.LineCoverage> it = getReportReader().readComponentCoverage(ref)) {
while (it.hasNext()) {
ScannerReport.LineCoverage coverage = it.next();
if (coverage.getLine() == line) {
return coverage;
}
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
return null;
}
public List<ScannerReport.AdHocRule> adHocRules() {
List<ScannerReport.AdHocRule> result = new ArrayList<>();
try (CloseableIterator<ScannerReport.AdHocRule> it = getReportReader().readAdHocRules()) {
while (it.hasNext()) {
result.add(it.next());
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
return result;
}
}
| 9,779 | 36.906977 | 171 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/mediumtest/FakePluginInstaller.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.scanner.mediumtest;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Priority;
import org.sonar.api.Plugin;
import org.sonar.core.platform.PluginInfo;
import org.sonar.core.plugin.PluginType;
import org.sonar.scanner.bootstrap.PluginInstaller;
import org.sonar.scanner.bootstrap.ScannerPlugin;
@Priority(1)
public class FakePluginInstaller implements PluginInstaller {
private final Map<String, ScannerPlugin> pluginsByKeys = new HashMap<>();
private final List<Object[]> mediumTestPlugins = new ArrayList<>();
public FakePluginInstaller add(String pluginKey, File jarFile, long lastUpdatedAt) {
pluginsByKeys.put(pluginKey, new ScannerPlugin(pluginKey, lastUpdatedAt, PluginType.BUNDLED, PluginInfo.create(jarFile)));
return this;
}
public FakePluginInstaller add(String pluginKey, Plugin instance, long lastUpdatedAt) {
mediumTestPlugins.add(new Object[] {pluginKey, instance, lastUpdatedAt});
return this;
}
@Override
public Map<String, ScannerPlugin> installRemotes() {
return pluginsByKeys;
}
@Override
public List<Object[]> installLocals() {
return mediumTestPlugins;
}
}
| 2,089 | 33.833333 | 126 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/mediumtest/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.scanner.mediumtest;
import javax.annotation.ParametersAreNonnullByDefault;
| 968 | 39.375 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/notifications/DefaultAnalysisWarnings.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.scanner.notifications;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.notifications.AnalysisWarnings;
import org.sonar.api.utils.System2;
import static org.sonar.api.utils.Preconditions.checkArgument;
public class DefaultAnalysisWarnings implements AnalysisWarnings {
private final System2 system2;
private final List<Message> messages = new ArrayList<>();
private final Set<String> seen = new HashSet<>();
public DefaultAnalysisWarnings(System2 system2) {
this.system2 = system2;
}
@Override
public void addUnique(String text) {
if (this.seen.add(text)) {
this.messages.add(new Message(text, system2.now()));
}
}
public List<Message> warnings() {
return Collections.unmodifiableList(messages);
}
@Immutable
public static class Message {
private final String text;
private final long timestamp;
Message(String text, long timestamp) {
checkArgument(!text.isEmpty(), "Text can't be empty");
this.text = text;
this.timestamp = timestamp;
}
public String getText() {
return text;
}
public long getTimestamp() {
return timestamp;
}
}
}
| 2,162 | 28.22973 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/notifications/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.scanner.notifications;
import javax.annotation.ParametersAreNonnullByDefault;
| 971 | 39.5 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/platform/DefaultServer.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.scanner.platform;
import java.util.Date;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.CoreProperties;
import org.sonar.api.config.Configuration;
import org.sonar.api.platform.Server;
import org.sonar.api.utils.DateUtils;
import org.sonar.core.platform.SonarQubeVersion;
import org.sonar.scanner.bootstrap.DefaultScannerWsClient;
import static org.apache.commons.lang.StringUtils.trimToEmpty;
public class DefaultServer extends Server {
private final Configuration settings;
private final DefaultScannerWsClient client;
private final SonarQubeVersion sonarQubeVersion;
public DefaultServer(Configuration settings, DefaultScannerWsClient client, SonarQubeVersion sonarQubeVersion) {
this.settings = settings;
this.client = client;
this.sonarQubeVersion = sonarQubeVersion;
}
@Override
public String getId() {
return settings.get(CoreProperties.SERVER_ID).orElseThrow(() -> new IllegalStateException("Mandatory"));
}
@Override
public String getVersion() {
return sonarQubeVersion.get().toString();
}
@Override
public Date getStartedAt() {
String dateString = settings.get(CoreProperties.SERVER_STARTTIME).orElseThrow(() -> new IllegalStateException("Mandatory"));
return DateUtils.parseDateTime(dateString);
}
@Override
public String getContextPath() {
return null;
}
@Override
public String getPublicRootUrl() {
String baseUrl = trimToEmpty(settings.get(CoreProperties.SERVER_BASE_URL).orElse(""));
if (baseUrl.isEmpty()) {
// If server base URL was not configured in Sonar server then it is better to take URL configured on batch side
baseUrl = client.baseUrl();
}
return StringUtils.removeEnd(baseUrl, "/");
}
@Override
public boolean isSecured() {
return false;
}
@Override
public String getPermanentServerId() {
return getId();
}
}
| 2,747 | 30.953488 | 128 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/platform/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.scanner.platform;
import javax.annotation.ParametersAreNonnullByDefault;
| 967 | 37.72 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/postjob/DefaultPostJobContext.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.scanner.postjob;
import org.sonar.api.batch.postjob.PostJobContext;
import org.sonar.api.config.Configuration;
public class DefaultPostJobContext implements PostJobContext {
private final Configuration config;
public DefaultPostJobContext(Configuration config) {
this.config = config;
}
@Override
public Configuration config() {
return config;
}
}
| 1,234 | 31.5 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/postjob/PostJobOptimizer.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.scanner.postjob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.config.Configuration;
import org.sonar.api.batch.postjob.internal.DefaultPostJobDescriptor;
public class PostJobOptimizer {
private static final Logger LOG = LoggerFactory.getLogger(PostJobOptimizer.class);
private final Configuration settings;
public PostJobOptimizer(Configuration settings) {
this.settings = settings;
}
/**
* Decide if the given PostJob should be executed.
*/
public boolean shouldExecute(DefaultPostJobDescriptor descriptor) {
if (!settingsCondition(descriptor)) {
LOG.debug("'{}' skipped because one of the required properties is missing", descriptor.name());
return false;
}
return true;
}
private boolean settingsCondition(DefaultPostJobDescriptor descriptor) {
if (!descriptor.properties().isEmpty()) {
for (String propertyKey : descriptor.properties()) {
if (!settings.hasKey(propertyKey)) {
return false;
}
}
}
return true;
}
}
| 1,921 | 31.033333 | 101 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/postjob/PostJobWrapper.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.scanner.postjob;
import org.sonar.api.batch.postjob.PostJob;
import org.sonar.api.batch.postjob.PostJobContext;
import org.sonar.api.batch.postjob.internal.DefaultPostJobDescriptor;
public class PostJobWrapper {
private PostJob wrappedPostJob;
private PostJobContext adaptor;
private DefaultPostJobDescriptor descriptor;
private PostJobOptimizer optimizer;
public PostJobWrapper(PostJob newPostJob, PostJobContext adaptor, PostJobOptimizer optimizer) {
this.wrappedPostJob = newPostJob;
this.optimizer = optimizer;
this.descriptor = new DefaultPostJobDescriptor();
newPostJob.describe(descriptor);
if (descriptor.name() == null) {
descriptor.name(newPostJob.getClass().getName());
}
this.adaptor = adaptor;
}
public boolean shouldExecute() {
return optimizer.shouldExecute(descriptor);
}
public void execute() {
wrappedPostJob.execute(adaptor);
}
@Override
public String toString() {
return descriptor.name();
}
}
| 1,854 | 31.54386 | 97 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/postjob/PostJobsExecutor.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.scanner.postjob;
import java.util.Collection;
import java.util.stream.Collectors;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.scanner.bootstrap.PostJobExtensionDictionary;
public class PostJobsExecutor {
private static final Logger LOG = Loggers.get(PostJobsExecutor.class);
private final PostJobExtensionDictionary selector;
public PostJobsExecutor(PostJobExtensionDictionary selector) {
this.selector = selector;
}
public void execute() {
Collection<PostJobWrapper> postJobs = selector.selectPostJobs();
execute(postJobs);
}
private static void execute(Collection<PostJobWrapper> postJobs) {
logPostJobs(postJobs);
for (PostJobWrapper postJob : postJobs) {
if (postJob.shouldExecute()) {
LOG.info("Executing post-job '{}'", postJob);
postJob.execute();
}
}
}
private static void logPostJobs(Collection<PostJobWrapper> postJobs) {
if (LOG.isDebugEnabled()) {
LOG.debug(() -> "Post-jobs : " + postJobs.stream().map(Object::toString).collect(Collectors.joining(" -> ")));
}
}
}
| 1,984 | 32.644068 | 116 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/postjob/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.scanner.postjob;
| 926 | 41.136364 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/qualitygate/QualityGateCheck.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.scanner.qualitygate;
import java.io.InputStream;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.EnumSet;
import org.sonar.api.Startable;
import org.sonar.api.utils.MessageException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.scanner.bootstrap.DefaultScannerWsClient;
import org.sonar.scanner.bootstrap.GlobalAnalysisMode;
import org.sonar.scanner.report.CeTaskReportDataHolder;
import org.sonar.scanner.scan.ScanProperties;
import org.sonarqube.ws.Ce;
import org.sonarqube.ws.Ce.TaskStatus;
import org.sonarqube.ws.MediaTypes;
import org.sonarqube.ws.Qualitygates;
import org.sonarqube.ws.Qualitygates.ProjectStatusResponse.Status;
import org.sonarqube.ws.client.GetRequest;
import org.sonarqube.ws.client.HttpException;
import org.sonarqube.ws.client.WsResponse;
public class QualityGateCheck implements Startable {
private static final Logger LOG = LoggerFactory.getLogger(QualityGateCheck.class);
private static final EnumSet<TaskStatus> TASK_TERMINAL_STATUSES = EnumSet.of(TaskStatus.SUCCESS, TaskStatus.FAILED, TaskStatus.CANCELED);
private static final int POLLING_INTERVAL_IN_MS = 5000;
private final DefaultScannerWsClient wsClient;
private final GlobalAnalysisMode analysisMode;
private final CeTaskReportDataHolder ceTaskReportDataHolder;
private final ScanProperties properties;
private long qualityGateTimeoutInMs;
private boolean enabled;
public QualityGateCheck(DefaultScannerWsClient wsClient, GlobalAnalysisMode analysisMode, CeTaskReportDataHolder ceTaskReportDataHolder,
ScanProperties properties) {
this.wsClient = wsClient;
this.properties = properties;
this.ceTaskReportDataHolder = ceTaskReportDataHolder;
this.analysisMode = analysisMode;
}
@Override
public void start() {
this.enabled = properties.shouldWaitForQualityGate();
this.qualityGateTimeoutInMs = Duration.of(properties.qualityGateWaitTimeout(), ChronoUnit.SECONDS).toMillis();
}
@Override
public void stop() {
// nothing to do
}
public void await() {
if (!enabled) {
LOG.debug("Quality Gate check disabled - skipping");
return;
}
if (analysisMode.isMediumTest()) {
throw new IllegalStateException("Quality Gate check not available in medium test mode");
}
LOG.info("Waiting for the analysis report to be processed (max {}s)", properties.qualityGateWaitTimeout());
String taskId = ceTaskReportDataHolder.getCeTaskId();
Ce.Task task = waitForCeTaskToFinish(taskId);
if (!TaskStatus.SUCCESS.equals(task.getStatus())) {
throw MessageException.of(String.format("CE Task finished abnormally with status: %s, you can check details here: %s",
task.getStatus().name(), ceTaskReportDataHolder.getCeTaskUrl()));
}
Status qualityGateStatus = getQualityGateStatus(task.getAnalysisId());
if (Status.OK.equals(qualityGateStatus)) {
LOG.info("QUALITY GATE STATUS: PASSED - View details on " + ceTaskReportDataHolder.getDashboardUrl());
} else {
throw MessageException.of("QUALITY GATE STATUS: FAILED - View details on " + ceTaskReportDataHolder.getDashboardUrl());
}
}
private Ce.Task waitForCeTaskToFinish(String taskId) {
GetRequest getTaskResultReq = new GetRequest("api/ce/task")
.setMediaType(MediaTypes.PROTOBUF)
.setParam("id", taskId);
long currentTime = 0;
while (qualityGateTimeoutInMs > currentTime) {
try {
WsResponse getTaskResultResponse = wsClient.call(getTaskResultReq).failIfNotSuccessful();
Ce.Task task = parseCeTaskResponse(getTaskResultResponse);
if (TASK_TERMINAL_STATUSES.contains(task.getStatus())) {
return task;
}
Thread.sleep(POLLING_INTERVAL_IN_MS);
currentTime += POLLING_INTERVAL_IN_MS;
} catch (HttpException e) {
throw MessageException.of(String.format("Failed to get CE Task status - %s", DefaultScannerWsClient.createErrorMessage(e)));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("Quality Gate check has been interrupted", e);
}
}
throw MessageException.of("Quality Gate check timeout exceeded - View details on " + ceTaskReportDataHolder.getDashboardUrl());
}
private static Ce.Task parseCeTaskResponse(WsResponse response) {
try (InputStream protobuf = response.contentStream()) {
return Ce.TaskResponse.parser().parseFrom(protobuf).getTask();
} catch (Exception e) {
throw new IllegalStateException("Failed to parse response from " + response.requestUrl(), e);
}
}
private Status getQualityGateStatus(String analysisId) {
GetRequest getQualityGateReq = new GetRequest("api/qualitygates/project_status")
.setMediaType(MediaTypes.PROTOBUF)
.setParam("analysisId", analysisId);
try {
WsResponse getTaskResultResponse = wsClient.call(getQualityGateReq).failIfNotSuccessful();
Qualitygates.ProjectStatusResponse.ProjectStatus status = parseQualityGateResponse(getTaskResultResponse);
return status.getStatus();
} catch (HttpException e) {
throw MessageException.of(String.format("Failed to get Quality Gate status - %s", DefaultScannerWsClient.createErrorMessage(e)));
}
}
private static Qualitygates.ProjectStatusResponse.ProjectStatus parseQualityGateResponse(WsResponse response) {
try (InputStream protobuf = response.contentStream()) {
return Qualitygates.ProjectStatusResponse.parser().parseFrom(protobuf).getProjectStatus();
} catch (Exception e) {
throw new IllegalStateException("Failed to parse response from " + response.requestUrl(), e);
}
}
}
| 6,583 | 40.15 | 139 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/qualitygate/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.scanner.qualitygate;
import javax.annotation.ParametersAreNonnullByDefault;
| 969 | 39.416667 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/report/ActiveRulesPublisher.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.scanner.report;
import org.sonar.api.batch.rule.ActiveRules;
import org.sonar.api.batch.rule.internal.DefaultActiveRule;
import org.sonar.scanner.protocol.Constants;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.protocol.output.ScannerReportWriter;
import static java.util.stream.Collectors.toList;
public class ActiveRulesPublisher implements ReportPublisherStep {
private final ActiveRules activeRules;
public ActiveRulesPublisher(ActiveRules activeRules) {
this.activeRules = activeRules;
}
@Override
public void publish(ScannerReportWriter writer) {
final ScannerReport.ActiveRule.Builder builder = ScannerReport.ActiveRule.newBuilder();
writer.writeActiveRules(activeRules.findAll().stream()
.map(DefaultActiveRule.class::cast)
.map(input -> {
builder.clear();
builder.setRuleRepository(input.ruleKey().repository());
builder.setRuleKey(input.ruleKey().rule());
builder.setSeverity(Constants.Severity.valueOf(input.severity()));
builder.setCreatedAt(input.createdAt());
builder.setUpdatedAt(input.updatedAt());
builder.setQProfileKey(input.qpKey());
builder.getMutableParamsByKey().putAll(input.params());
return builder.build();
}).collect(toList()));
}
}
| 2,179 | 37.245614 | 91 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/report/AnalysisCachePublisher.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.scanner.report;
import org.sonar.scanner.cache.ScannerWriteCache;
import org.sonar.scanner.protocol.output.ScannerReportWriter;
public class AnalysisCachePublisher implements ReportPublisherStep {
private final ScannerWriteCache cache;
public AnalysisCachePublisher(ScannerWriteCache cache) {
this.cache = cache;
}
@Override
public void publish(ScannerReportWriter writer) {
cache.close();
}
}
| 1,279 | 33.594595 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/report/AnalysisContextReportPublisher.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.scanner.report;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeSet;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.CoreProperties;
import org.sonar.api.batch.fs.internal.AbstractProjectOrModule;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.api.utils.System2;
import org.sonar.core.platform.PluginInfo;
import org.sonar.scanner.bootstrap.GlobalServerSettings;
import org.sonar.scanner.bootstrap.ScannerPluginRepository;
import org.sonar.scanner.fs.InputModuleHierarchy;
import org.sonar.scanner.protocol.output.ScannerReportWriter;
import org.sonar.scanner.scan.ProjectServerSettings;
import org.sonar.scanner.scan.filesystem.InputComponentStore;
import static java.util.stream.Collectors.toList;
public class AnalysisContextReportPublisher {
private static final String KEY_VALUE_FORMAT = " - %s=%s";
private static final String ENV_PROP_PREFIX = "env.";
private static final String SONAR_PROP_PREFIX = "sonar.";
private static final int MAX_WIDTH = 1000;
private final ScannerPluginRepository pluginRepo;
private final ProjectServerSettings projectServerSettings;
private final System2 system;
private final GlobalServerSettings globalServerSettings;
private final InputModuleHierarchy hierarchy;
private final InputComponentStore store;
public AnalysisContextReportPublisher(ProjectServerSettings projectServerSettings, ScannerPluginRepository pluginRepo, System2 system,
GlobalServerSettings globalServerSettings, InputModuleHierarchy hierarchy, InputComponentStore store) {
this.projectServerSettings = projectServerSettings;
this.pluginRepo = pluginRepo;
this.system = system;
this.globalServerSettings = globalServerSettings;
this.hierarchy = hierarchy;
this.store = store;
}
public void init(ScannerReportWriter writer) {
File analysisLog = writer.getFileStructure().analysisLog();
try (BufferedWriter fileWriter = Files.newBufferedWriter(analysisLog.toPath(), StandardCharsets.UTF_8)) {
writePlugins(fileWriter);
writeBundledAnalyzers(fileWriter);
writeGlobalSettings(fileWriter);
writeProjectSettings(fileWriter);
writeModulesSettings(fileWriter);
} catch (IOException e) {
throw new IllegalStateException("Unable to write analysis log", e);
}
}
private void writePlugins(BufferedWriter fileWriter) throws IOException {
fileWriter.write("Plugins:\n");
for (PluginInfo p : pluginRepo.getExternalPluginsInfos()) {
fileWriter.append(String.format(" - %s %s (%s)", p.getName(), p.getVersion(), p.getKey())).append('\n');
}
}
private void writeBundledAnalyzers(BufferedWriter fileWriter) throws IOException {
fileWriter.write("Bundled analyzers:\n");
for (PluginInfo p : pluginRepo.getBundledPluginsInfos()) {
fileWriter.append(String.format(" - %s %s (%s)", p.getName(), p.getVersion(), p.getKey())).append('\n');
}
}
private void writeGlobalSettings(BufferedWriter fileWriter) throws IOException {
fileWriter.append("Global server settings:\n");
Map<String, String> props = globalServerSettings.properties();
for (String prop : new TreeSet<>(props.keySet())) {
dumpPropIfNotSensitive(fileWriter, prop, props.get(prop));
}
}
private void writeProjectSettings(BufferedWriter fileWriter) throws IOException {
fileWriter.append("Project server settings:\n");
Map<String, String> props = projectServerSettings.properties();
for (String prop : new TreeSet<>(props.keySet())) {
dumpPropIfNotSensitive(fileWriter, prop, props.get(prop));
}
fileWriter.append("Project scanner properties:\n");
writeScannerProps(fileWriter, hierarchy.root().properties());
}
private void writeModulesSettings(BufferedWriter fileWriter) throws IOException {
for (DefaultInputModule module : store.allModules()) {
if (module.equals(hierarchy.root())) {
continue;
}
Map<String, String> moduleSpecificProps = collectModuleSpecificProps(module);
fileWriter.append(String.format("Scanner properties of module: %s", module.key())).append('\n');
writeScannerProps(fileWriter, moduleSpecificProps);
}
}
private void writeScannerProps(BufferedWriter fileWriter, Map<String, String> props) throws IOException {
for (Map.Entry<String, String> prop : props.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getKey)).collect(toList())) {
if (isSystemProp(prop.getKey()) || isEnvVariable(prop.getKey()) || !isSqProp(prop.getKey())) {
continue;
}
dumpPropIfNotSensitive(fileWriter, prop.getKey(), prop.getValue());
}
}
private static void dumpPropIfNotSensitive(BufferedWriter fileWriter, String prop, String value) throws IOException {
fileWriter.append(String.format(KEY_VALUE_FORMAT, prop, isSensitiveProperty(prop) ? "******" : StringUtils.abbreviate(value, MAX_WIDTH))).append('\n');
}
/**
* Only keep props that are not in parent
*/
private Map<String, String> collectModuleSpecificProps(DefaultInputModule module) {
Map<String, String> moduleSpecificProps = new HashMap<>();
AbstractProjectOrModule parent = hierarchy.parent(module);
if (parent == null) {
moduleSpecificProps.putAll(module.properties());
} else {
Map<String, String> parentProps = parent.properties();
for (Map.Entry<String, String> entry : module.properties().entrySet()) {
if (!parentProps.containsKey(entry.getKey()) || !parentProps.get(entry.getKey()).equals(entry.getValue())) {
moduleSpecificProps.put(entry.getKey(), entry.getValue());
}
}
}
return moduleSpecificProps;
}
private static boolean isSqProp(String propKey) {
return propKey.startsWith(SONAR_PROP_PREFIX);
}
private boolean isSystemProp(String propKey) {
return system.properties().containsKey(propKey) && !propKey.startsWith(SONAR_PROP_PREFIX);
}
private boolean isEnvVariable(String propKey) {
return propKey.startsWith(ENV_PROP_PREFIX) && system.envVariables().containsKey(propKey.substring(ENV_PROP_PREFIX.length()));
}
private static boolean isSensitiveProperty(String key) {
return key.equals(CoreProperties.LOGIN) || key.contains(".password") || key.contains(".secured") || key.contains(".token");
}
}
| 7,383 | 41.436782 | 155 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/report/AnalysisWarningsPublisher.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.scanner.report;
import java.util.List;
import java.util.stream.Collectors;
import org.sonar.scanner.notifications.DefaultAnalysisWarnings;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.protocol.output.ScannerReportWriter;
public class AnalysisWarningsPublisher implements ReportPublisherStep {
private final DefaultAnalysisWarnings defaultAnalysisWarnings;
public AnalysisWarningsPublisher(DefaultAnalysisWarnings defaultAnalysisWarnings) {
this.defaultAnalysisWarnings = defaultAnalysisWarnings;
}
@Override
public void publish(ScannerReportWriter writer) {
List<DefaultAnalysisWarnings.Message> warnings = defaultAnalysisWarnings.warnings();
if (warnings.isEmpty()) {
return;
}
writer.writeAnalysisWarnings(warnings.stream()
.map(AnalysisWarningsPublisher::toProtobufAnalysisWarning)
.collect(Collectors.toList()));
}
private static ScannerReport.AnalysisWarning toProtobufAnalysisWarning(DefaultAnalysisWarnings.Message message) {
return ScannerReport.AnalysisWarning.newBuilder()
.setText(message.getText())
.setTimestamp(message.getTimestamp())
.build();
}
}
| 2,042 | 36.833333 | 115 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/report/CeTaskReportDataHolder.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.scanner.report;
import static java.util.Objects.requireNonNull;
public class CeTaskReportDataHolder {
private boolean initialized = false;
private String ceTaskId = null;
private String ceTaskUrl = null;
private String dashboardUrl= null;
public void init(String ceTaskId, String ceTaskUrl, String dashboardUrl) {
requireNonNull(ceTaskId, "CE task id must not be null");
requireNonNull(ceTaskUrl, "CE task url must not be null");
requireNonNull(dashboardUrl, "Dashboard url map must not be null");
this.ceTaskId = ceTaskId;
this.ceTaskUrl = ceTaskUrl;
this.dashboardUrl = dashboardUrl;
this.initialized = true;
}
private void verifyInitialized() {
if (!initialized) {
throw new IllegalStateException("Scan report hasn't been published yet");
}
}
public String getCeTaskId() {
verifyInitialized();
return ceTaskId;
}
public String getDashboardUrl() {
verifyInitialized();
return dashboardUrl;
}
public String getCeTaskUrl() {
verifyInitialized();
return ceTaskUrl;
}
}
| 1,932 | 29.68254 | 79 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/report/ChangedLinesPublisher.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.scanner.report;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.StreamSupport;
import javax.annotation.CheckForNull;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.api.batch.scm.ScmProvider;
import org.sonar.api.impl.utils.ScannerUtils;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.api.utils.log.Profiler;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.protocol.output.ScannerReportWriter;
import org.sonar.scanner.repository.ReferenceBranchSupplier;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import org.sonar.scanner.scan.filesystem.InputComponentStore;
import org.sonar.scanner.scm.ScmConfiguration;
import org.sonar.scm.git.ChangedFile;
import org.sonar.scm.git.GitScmProvider;
import static java.util.Optional.empty;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toMap;
public class ChangedLinesPublisher implements ReportPublisherStep {
private static final Logger LOG = Loggers.get(ChangedLinesPublisher.class);
private static final String LOG_MSG = "SCM writing changed lines";
private final ScmConfiguration scmConfiguration;
private final DefaultInputProject project;
private final InputComponentStore inputComponentStore;
private final BranchConfiguration branchConfiguration;
private final ReferenceBranchSupplier referenceBranchSupplier;
public ChangedLinesPublisher(ScmConfiguration scmConfiguration, DefaultInputProject project, InputComponentStore inputComponentStore,
BranchConfiguration branchConfiguration, ReferenceBranchSupplier referenceBranchSupplier) {
this.scmConfiguration = scmConfiguration;
this.project = project;
this.inputComponentStore = inputComponentStore;
this.branchConfiguration = branchConfiguration;
this.referenceBranchSupplier = referenceBranchSupplier;
}
@Override
public void publish(ScannerReportWriter writer) {
Optional<String> targetBranch = getTargetBranch();
if (targetBranch.isPresent()) {
Profiler profiler = Profiler.create(LOG).startInfo(LOG_MSG);
int count = writeChangedLines(scmConfiguration.provider(), writer, targetBranch.get());
LOG.debug("SCM reported changed lines for {} {} in the branch", count, ScannerUtils.pluralize("file", count));
profiler.stopInfo();
}
}
private Optional<String> getTargetBranch() {
if (scmConfiguration.isDisabled() || scmConfiguration.provider() == null) {
return empty();
}
String targetBranchName = branchConfiguration.targetBranchName();
if (branchConfiguration.isPullRequest() && targetBranchName != null) {
return Optional.of(targetBranchName);
}
return Optional.ofNullable(referenceBranchSupplier.get());
}
private int writeChangedLines(ScmProvider provider, ScannerReportWriter writer, String targetScmBranch) {
Path rootBaseDir = project.getBaseDir();
Map<Path, DefaultInputFile> changedFiles = StreamSupport.stream(inputComponentStore.allChangedFilesToPublish().spliterator(), false)
.collect(toMap(DefaultInputFile::path, identity()));
Map<Path, Set<Integer>> pathSetMap = getBranchChangedLinesByScm(provider, targetScmBranch, rootBaseDir, toChangedFilesByPathMap(changedFiles.values()));
int count = 0;
if (pathSetMap == null) {
// no information returned by the SCM, we write nothing in the report and
// the compute engine will use SCM dates to estimate which lines are new
return count;
}
for (Map.Entry<Path, DefaultInputFile> e : changedFiles.entrySet()) {
DefaultInputFile inputFile = e.getValue();
Set<Integer> changedLines = pathSetMap.get(e.getKey());
if (changedLines == null) {
if (branchConfiguration.isPullRequest()) {
LOG.warn("File '{}' was detected as changed but without having changed lines", e.getKey().toAbsolutePath());
}
// assume that no line was changed
writeChangedLines(writer, e.getValue().scannerId(), Collections.emptySet());
} else {
// detect unchanged last empty line
if (changedLines.size() + 1 == inputFile.lines() && inputFile.lineLength(inputFile.lines()) == 0) {
changedLines.add(inputFile.lines());
}
count++;
writeChangedLines(writer, e.getValue().scannerId(), changedLines);
}
}
return count;
}
private static void writeChangedLines(ScannerReportWriter writer, int fileRef, Set<Integer> changedLines) {
ScannerReport.ChangedLines.Builder builder = ScannerReport.ChangedLines.newBuilder();
builder.addAllLine(changedLines);
writer.writeComponentChangedLines(fileRef, builder.build());
}
@CheckForNull
private static Map<Path, Set<Integer>> getBranchChangedLinesByScm(ScmProvider scmProvider, String targetScmBranch, Path rootBaseDir, Map<Path, ChangedFile> changedFiles) {
if (scmProvider instanceof GitScmProvider) {
return ((GitScmProvider) scmProvider).branchChangedLinesWithFileMovementDetection(targetScmBranch, rootBaseDir, changedFiles);
}
return scmProvider.branchChangedLines(targetScmBranch, rootBaseDir, changedFiles.keySet());
}
private static Map<Path, ChangedFile> toChangedFilesByPathMap(Collection<DefaultInputFile> files) {
return files
.stream()
.map(ChangedFile::of)
.collect(toMap(ChangedFile::getAbsolutFilePath, identity()));
}
}
| 6,513 | 42.426667 | 173 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/report/ComponentsPublisher.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.scanner.report;
import java.util.Map;
import javax.annotation.CheckForNull;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.CoreProperties;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.InputFile.Status;
import org.sonar.api.batch.fs.internal.AbstractProjectOrModule;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.DefaultInputProject;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.protocol.output.ScannerReport.Component.ComponentType;
import org.sonar.scanner.protocol.output.ScannerReport.Component.FileStatus;
import org.sonar.scanner.protocol.output.ScannerReport.ComponentLink;
import org.sonar.scanner.protocol.output.ScannerReport.ComponentLink.ComponentLinkType;
import org.sonar.scanner.protocol.output.ScannerReportWriter;
import org.sonar.scanner.scan.filesystem.InputComponentStore;
/**
* Adds components and analysis metadata to output report
*/
public class ComponentsPublisher implements ReportPublisherStep {
private final InputComponentStore inputComponentStore;
private final DefaultInputProject project;
public ComponentsPublisher(DefaultInputProject project, InputComponentStore inputComponentStore) {
this.project = project;
this.inputComponentStore = inputComponentStore;
}
@Override
public void publish(ScannerReportWriter writer) {
ScannerReport.Component.Builder projectBuilder = prepareProjectBuilder();
ScannerReport.Component.Builder fileBuilder = ScannerReport.Component.newBuilder();
for (DefaultInputFile file : inputComponentStore.allFilesToPublish()) {
projectBuilder.addChildRef(file.scannerId());
fileBuilder.clear();
// non-null fields
fileBuilder.setRef(file.scannerId());
fileBuilder.setType(ComponentType.FILE);
fileBuilder.setIsTest(file.type() == InputFile.Type.TEST);
fileBuilder.setLines(file.lines());
fileBuilder.setStatus(convert(file.status()));
fileBuilder.setMarkedAsUnchanged(file.isMarkedAsUnchanged());
String oldRelativePath = file.oldRelativePath();
if (oldRelativePath != null) {
fileBuilder.setOldRelativeFilePath(oldRelativePath);
}
String lang = getLanguageKey(file);
if (lang != null) {
fileBuilder.setLanguage(lang);
}
fileBuilder.setProjectRelativePath(file.getProjectRelativePath());
writer.writeComponent(fileBuilder.build());
}
writer.writeComponent(projectBuilder.build());
}
private ScannerReport.Component.Builder prepareProjectBuilder() {
ScannerReport.Component.Builder projectBuilder = ScannerReport.Component.newBuilder();
projectBuilder.setRef(project.scannerId());
projectBuilder.setType(ComponentType.PROJECT);
// Here we want key without branch
projectBuilder.setKey(project.key());
// protocol buffers does not accept null values
String name = getName(project);
if (name != null) {
projectBuilder.setName(name);
}
String description = getDescription(project);
if (description != null) {
projectBuilder.setDescription(description);
}
writeLinks(project, projectBuilder);
return projectBuilder;
}
private static FileStatus convert(Status status) {
switch (status) {
case ADDED:
return FileStatus.ADDED;
case CHANGED:
return FileStatus.CHANGED;
case SAME:
return FileStatus.SAME;
default:
throw new IllegalArgumentException("Unexpected status: " + status);
}
}
private static void writeLinks(DefaultInputProject project, ScannerReport.Component.Builder builder) {
ComponentLink.Builder linkBuilder = ComponentLink.newBuilder();
writeProjectLink(builder, project.properties(), linkBuilder, CoreProperties.LINKS_HOME_PAGE, ComponentLinkType.HOME);
writeProjectLink(builder, project.properties(), linkBuilder, CoreProperties.LINKS_CI, ComponentLinkType.CI);
writeProjectLink(builder, project.properties(), linkBuilder, CoreProperties.LINKS_ISSUE_TRACKER, ComponentLinkType.ISSUE);
writeProjectLink(builder, project.properties(), linkBuilder, CoreProperties.LINKS_SOURCES, ComponentLinkType.SCM);
}
private static void writeProjectLink(ScannerReport.Component.Builder componentBuilder, Map<String, String> properties, ComponentLink.Builder linkBuilder, String linkProp,
ComponentLinkType linkType) {
String link = properties.get(linkProp);
if (StringUtils.isNotBlank(link)) {
linkBuilder.setType(linkType);
linkBuilder.setHref(link);
componentBuilder.addLink(linkBuilder.build());
linkBuilder.clear();
}
}
@CheckForNull
private static String getLanguageKey(InputFile file) {
return file.language();
}
@CheckForNull
private static String getName(AbstractProjectOrModule module) {
return module.definition().getOriginalName();
}
@CheckForNull
private static String getDescription(AbstractProjectOrModule module) {
return module.definition().getDescription();
}
}
| 5,941 | 36.847134 | 172 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/report/ContextPropertiesPublisher.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.scanner.report;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.sonar.api.batch.scm.ScmProvider;
import org.sonar.core.config.CorePropertyDefinitions;
import org.sonar.scanner.ci.CiConfiguration;
import org.sonar.scanner.config.DefaultConfiguration;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.protocol.output.ScannerReportWriter;
import org.sonar.scanner.repository.ContextPropertiesCache;
import org.sonar.scanner.scm.ScmConfiguration;
import static org.sonar.core.config.CorePropertyDefinitions.SONAR_ANALYSIS_DETECTEDCI;
import static org.sonar.core.config.CorePropertyDefinitions.SONAR_ANALYSIS_DETECTEDSCM;
public class ContextPropertiesPublisher implements ReportPublisherStep {
private final ContextPropertiesCache cache;
private final DefaultConfiguration config;
private final ScmConfiguration scmConfiguration;
private final CiConfiguration ciConfiguration;
public ContextPropertiesPublisher(ContextPropertiesCache cache, DefaultConfiguration config, ScmConfiguration scmConfiguration, CiConfiguration ciConfiguration) {
this.cache = cache;
this.config = config;
this.scmConfiguration = scmConfiguration;
this.ciConfiguration = ciConfiguration;
}
@Override
public void publish(ScannerReportWriter writer) {
List<Map.Entry<String, String>> properties = new ArrayList<>(cache.getAll().entrySet());
properties.add(constructScmInfo());
properties.add(constructCiInfo());
// properties that are automatically included to report so that
// they can be included to webhook payloads
properties.addAll(config.getProperties().entrySet()
.stream()
.filter(e -> e.getKey().startsWith(CorePropertyDefinitions.SONAR_ANALYSIS))
.collect(Collectors.toList()));
writer.writeContextProperties(properties
.stream()
.map(e -> ScannerReport.ContextProperty.newBuilder()
.setKey(e.getKey())
.setValue(e.getValue())
.build())
.collect(Collectors.toList()));
}
private Map.Entry<String, String> constructScmInfo() {
ScmProvider scmProvider = scmConfiguration.provider();
if (scmProvider != null) {
return new AbstractMap.SimpleEntry<>(SONAR_ANALYSIS_DETECTEDSCM, scmProvider.key());
} else {
return new AbstractMap.SimpleEntry<>(SONAR_ANALYSIS_DETECTEDSCM, "undetected");
}
}
private Map.Entry<String, String> constructCiInfo() {
return new AbstractMap.SimpleEntry<>(SONAR_ANALYSIS_DETECTEDCI, ciConfiguration.getCiName());
}
}
| 3,485 | 39.534884 | 164 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/report/JavaArchitectureInformationProvider.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.scanner.report;
import com.sun.jna.Platform;
public class JavaArchitectureInformationProvider {
public boolean is64bitJavaVersion() {
return Platform.is64Bit();
}
}
| 1,038 | 32.516129 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/report/MetadataPublisher.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.scanner.report;
import java.io.File;
import java.nio.file.Path;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import org.sonar.api.batch.fs.internal.AbstractProjectOrModule;
import org.sonar.api.batch.scm.ScmProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.scanner.ProjectInfo;
import org.sonar.scanner.bootstrap.ScannerPlugin;
import org.sonar.scanner.bootstrap.ScannerPluginRepository;
import org.sonar.scanner.cpd.CpdSettings;
import org.sonar.scanner.fs.InputModuleHierarchy;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.protocol.output.ScannerReport.Metadata.BranchType;
import org.sonar.scanner.protocol.output.ScannerReportWriter;
import org.sonar.scanner.repository.ReferenceBranchSupplier;
import org.sonar.scanner.rule.QProfile;
import org.sonar.scanner.rule.QualityProfiles;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import org.sonar.scanner.scan.filesystem.InputComponentStore;
import org.sonar.scanner.scm.ScmConfiguration;
import org.sonar.scanner.scm.ScmRevision;
public class MetadataPublisher implements ReportPublisherStep {
private static final Logger LOG = LoggerFactory.getLogger(MetadataPublisher.class);
private final QualityProfiles qProfiles;
private final ProjectInfo projectInfo;
private final InputModuleHierarchy moduleHierarchy;
private final CpdSettings cpdSettings;
private final ScannerPluginRepository pluginRepository;
private final BranchConfiguration branchConfiguration;
private final ScmRevision scmRevision;
private final InputComponentStore componentStore;
private final ScmConfiguration scmConfiguration;
private final ReferenceBranchSupplier referenceBranchSupplier;
public MetadataPublisher(ProjectInfo projectInfo, InputModuleHierarchy moduleHierarchy, QualityProfiles qProfiles,
CpdSettings cpdSettings, ScannerPluginRepository pluginRepository, BranchConfiguration branchConfiguration,
ScmRevision scmRevision, InputComponentStore componentStore, ScmConfiguration scmConfiguration, ReferenceBranchSupplier referenceBranchSupplier) {
this.projectInfo = projectInfo;
this.moduleHierarchy = moduleHierarchy;
this.qProfiles = qProfiles;
this.cpdSettings = cpdSettings;
this.pluginRepository = pluginRepository;
this.branchConfiguration = branchConfiguration;
this.scmRevision = scmRevision;
this.componentStore = componentStore;
this.scmConfiguration = scmConfiguration;
this.referenceBranchSupplier = referenceBranchSupplier;
}
@Override
public void publish(ScannerReportWriter writer) {
AbstractProjectOrModule rootProject = moduleHierarchy.root();
ScannerReport.Metadata.Builder builder = ScannerReport.Metadata.newBuilder()
.setAnalysisDate(projectInfo.getAnalysisDate().getTime())
// Here we want key without branch
.setProjectKey(rootProject.key())
.setCrossProjectDuplicationActivated(cpdSettings.isCrossProjectDuplicationEnabled())
.setRootComponentRef(rootProject.scannerId());
projectInfo.getProjectVersion().ifPresent(builder::setProjectVersion);
projectInfo.getBuildString().ifPresent(builder::setBuildString);
if (branchConfiguration.branchName() != null) {
addBranchInformation(builder);
}
String newCodeReferenceBranch = referenceBranchSupplier.getFromProperties();
if (newCodeReferenceBranch != null) {
builder.setNewCodeReferenceBranch(newCodeReferenceBranch);
}
addScmInformation(builder);
addNotAnalyzedFileCountsByLanguage(builder);
for (QProfile qp : qProfiles.findAll()) {
builder.putQprofilesPerLanguage(qp.getLanguage(), ScannerReport.Metadata.QProfile.newBuilder()
.setKey(qp.getKey())
.setLanguage(qp.getLanguage())
.setName(qp.getName())
.setRulesUpdatedAt(qp.getRulesUpdatedAt().getTime()).build());
}
for (Entry<String, ScannerPlugin> pluginEntry : pluginRepository.getPluginsByKey().entrySet()) {
builder.putPluginsByKey(pluginEntry.getKey(), ScannerReport.Metadata.Plugin.newBuilder()
.setKey(pluginEntry.getKey())
.setUpdatedAt(pluginEntry.getValue().getUpdatedAt()).build());
}
addRelativePathFromScmRoot(builder);
writer.writeMetadata(builder.build());
}
private void addRelativePathFromScmRoot(ScannerReport.Metadata.Builder builder) {
ScmProvider scmProvider = scmConfiguration.provider();
if (scmProvider == null) {
return;
}
Path projectBasedir = moduleHierarchy.root().getBaseDir();
try {
builder.setRelativePathFromScmRoot(toSonarQubePath(scmProvider.relativePathFromScmRoot(projectBasedir)));
} catch (UnsupportedOperationException e) {
LOG.debug(e.getMessage());
}
}
private void addScmInformation(ScannerReport.Metadata.Builder builder) {
try {
scmRevision.get().ifPresent(revisionId -> {
LOG.debug("SCM revision ID '{}'", revisionId);
builder.setScmRevisionId(revisionId);
});
} catch (UnsupportedOperationException e) {
LOG.debug(e.getMessage());
}
}
private void addNotAnalyzedFileCountsByLanguage(ScannerReport.Metadata.Builder builder) {
builder.putAllNotAnalyzedFilesByLanguage(componentStore.getNotAnalysedFilesByLanguage());
}
private void addBranchInformation(ScannerReport.Metadata.Builder builder) {
builder.setBranchName(branchConfiguration.branchName());
BranchType branchType = toProtobufBranchType(branchConfiguration.branchType());
builder.setBranchType(branchType);
String referenceBranch = branchConfiguration.referenceBranchName();
if (referenceBranch != null) {
builder.setReferenceBranchName(referenceBranch);
}
String targetBranchName = branchConfiguration.targetBranchName();
if (targetBranchName != null) {
builder.setTargetBranchName(targetBranchName);
}
if (branchType == BranchType.PULL_REQUEST) {
builder.setPullRequestKey(branchConfiguration.pullRequestKey());
}
}
private static BranchType toProtobufBranchType(org.sonar.scanner.scan.branch.BranchType branchType) {
if (branchType == org.sonar.scanner.scan.branch.BranchType.PULL_REQUEST) {
return BranchType.PULL_REQUEST;
}
return BranchType.BRANCH;
}
private static String toSonarQubePath(Path path) {
String pathAsString = path.toString();
char sonarQubeSeparatorChar = '/';
if (File.separatorChar != sonarQubeSeparatorChar) {
return pathAsString.replaceAll(Pattern.quote(File.separator), String.valueOf(sonarQubeSeparatorChar));
}
return pathAsString;
}
}
| 7,485 | 40.131868 | 150 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/report/ReportPublisher.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.scanner.report;
import com.google.common.annotations.VisibleForTesting;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.annotation.Nullable;
import okhttp3.HttpUrl;
import org.apache.commons.io.FileUtils;
import org.sonar.api.Startable;
import org.sonar.api.notifications.AnalysisWarnings;
import org.sonar.api.platform.Server;
import org.sonar.api.utils.MessageException;
import org.sonar.api.utils.TempFolder;
import org.sonar.api.utils.ZipUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.scanner.bootstrap.DefaultScannerWsClient;
import org.sonar.scanner.bootstrap.GlobalAnalysisMode;
import org.sonar.scanner.fs.InputModuleHierarchy;
import org.sonar.scanner.protocol.output.FileStructure;
import org.sonar.scanner.protocol.output.ScannerReportReader;
import org.sonar.scanner.protocol.output.ScannerReportWriter;
import org.sonar.scanner.scan.ScanProperties;
import org.sonar.scanner.scan.branch.BranchConfiguration;
import org.sonar.scanner.scan.branch.BranchType;
import org.sonarqube.ws.Ce;
import org.sonarqube.ws.MediaTypes;
import org.sonarqube.ws.client.HttpException;
import org.sonarqube.ws.client.PostRequest;
import org.sonarqube.ws.client.RequestWithPayload.Part;
import org.sonarqube.ws.client.WsResponse;
import static java.net.URLEncoder.encode;
import static org.apache.commons.lang.StringUtils.EMPTY;
import static org.apache.commons.lang.StringUtils.isBlank;
import static org.sonar.core.util.FileUtils.deleteQuietly;
import static org.sonar.core.util.FileUtils.humanReadableByteCountSI;
import static org.sonar.scanner.scan.branch.BranchType.PULL_REQUEST;
public class ReportPublisher implements Startable {
private static final Logger LOG = LoggerFactory.getLogger(ReportPublisher.class);
private static final String CHARACTERISTIC = "characteristic";
private static final String DASHBOARD = "dashboard";
private static final String BRANCH = "branch";
private static final String ID = "id";
@VisibleForTesting
static final String SUPPORT_OF_32_BIT_JRE_IS_DEPRECATED_MESSAGE = "You are using a 32 bits JRE. "
+ "The support of 32 bits JRE is deprecated and a future version of the scanner will remove it completely.";
private final DefaultScannerWsClient wsClient;
private final AnalysisContextReportPublisher contextPublisher;
private final InputModuleHierarchy moduleHierarchy;
private final GlobalAnalysisMode analysisMode;
private final TempFolder temp;
private final ReportPublisherStep[] publishers;
private final Server server;
private final BranchConfiguration branchConfiguration;
private final ScanProperties properties;
private final CeTaskReportDataHolder ceTaskReportDataHolder;
private final Path reportDir;
private final ScannerReportWriter writer;
private final ScannerReportReader reader;
private final AnalysisWarnings analysisWarnings;
private final JavaArchitectureInformationProvider javaArchitectureInformationProvider;
public ReportPublisher(ScanProperties properties, DefaultScannerWsClient wsClient, Server server, AnalysisContextReportPublisher contextPublisher,
InputModuleHierarchy moduleHierarchy, GlobalAnalysisMode analysisMode, TempFolder temp, ReportPublisherStep[] publishers, BranchConfiguration branchConfiguration,
CeTaskReportDataHolder ceTaskReportDataHolder, AnalysisWarnings analysisWarnings,
JavaArchitectureInformationProvider javaArchitectureInformationProvider, FileStructure fileStructure) {
this.wsClient = wsClient;
this.server = server;
this.contextPublisher = contextPublisher;
this.moduleHierarchy = moduleHierarchy;
this.analysisMode = analysisMode;
this.temp = temp;
this.publishers = publishers;
this.branchConfiguration = branchConfiguration;
this.properties = properties;
this.ceTaskReportDataHolder = ceTaskReportDataHolder;
this.reportDir = fileStructure.root().toPath();
this.analysisWarnings = analysisWarnings;
this.javaArchitectureInformationProvider = javaArchitectureInformationProvider;
this.writer = new ScannerReportWriter(fileStructure);
this.reader = new ScannerReportReader(fileStructure);
}
@Override
public void start() {
contextPublisher.init(writer);
if (!analysisMode.isMediumTest()) {
String publicUrl = server.getPublicRootUrl();
if (HttpUrl.parse(publicUrl) == null) {
throw MessageException.of("Failed to parse public URL set in SonarQube server: " + publicUrl);
}
}
}
@Override
public void stop() {
if (!properties.shouldKeepReport()) {
deleteQuietly(reportDir);
}
}
public Path getReportDir() {
return reportDir;
}
public ScannerReportWriter getWriter() {
return writer;
}
public ScannerReportReader getReader() {
return reader;
}
public void execute() {
logDeprecationWarningIf32bitJava();
File report = generateReportFile();
if (properties.shouldKeepReport()) {
LOG.info("Analysis report generated in " + reportDir);
}
if (!analysisMode.isMediumTest()) {
String taskId = upload(report);
prepareAndDumpMetadata(taskId);
}
logSuccess();
}
private void logDeprecationWarningIf32bitJava() {
if (!javaArchitectureInformationProvider.is64bitJavaVersion()) {
analysisWarnings.addUnique(SUPPORT_OF_32_BIT_JRE_IS_DEPRECATED_MESSAGE);
LOG.warn(SUPPORT_OF_32_BIT_JRE_IS_DEPRECATED_MESSAGE);
}
}
private File generateReportFile() {
try {
long startTime = System.currentTimeMillis();
for (ReportPublisherStep publisher : publishers) {
publisher.publish(writer);
}
long stopTime = System.currentTimeMillis();
LOG.info("Analysis report generated in {}ms, dir size={}", stopTime - startTime, humanReadableByteCountSI(FileUtils.sizeOfDirectory(reportDir.toFile())));
startTime = System.currentTimeMillis();
File reportZip = temp.newFile("scanner-report", ".zip");
ZipUtils.zipDir(reportDir.toFile(), reportZip);
stopTime = System.currentTimeMillis();
LOG.info("Analysis report compressed in {}ms, zip size={}", stopTime - startTime, humanReadableByteCountSI(FileUtils.sizeOf(reportZip)));
return reportZip;
} catch (IOException e) {
throw new IllegalStateException("Unable to prepare analysis report", e);
}
}
private void logSuccess() {
if (analysisMode.isMediumTest()) {
LOG.info("ANALYSIS SUCCESSFUL");
} else if (!properties.shouldWaitForQualityGate()) {
LOG.info("ANALYSIS SUCCESSFUL, you can find the results at: {}", ceTaskReportDataHolder.getDashboardUrl());
LOG.info("Note that you will be able to access the updated dashboard once the server has processed the submitted analysis report");
LOG.info("More about the report processing at {}", ceTaskReportDataHolder.getCeTaskUrl());
}
}
/**
* Uploads the report file to server and returns the generated task id
*/
String upload(File report) {
LOG.debug("Upload report");
long startTime = System.currentTimeMillis();
Part filePart = new Part(MediaTypes.ZIP, report);
PostRequest post = new PostRequest("api/ce/submit")
.setMediaType(MediaTypes.PROTOBUF)
.setParam("projectKey", moduleHierarchy.root().key())
.setParam("projectName", moduleHierarchy.root().getOriginalName())
.setPart("report", filePart);
String branchName = branchConfiguration.branchName();
if (branchName != null) {
if (branchConfiguration.branchType() != PULL_REQUEST) {
post.setParam(CHARACTERISTIC, "branch=" + branchName);
post.setParam(CHARACTERISTIC, "branchType=" + branchConfiguration.branchType().name());
} else {
post.setParam(CHARACTERISTIC, "pullRequest=" + branchConfiguration.pullRequestKey());
}
}
WsResponse response;
try {
post.setWriteTimeOutInMs(properties.reportPublishTimeout() * 1000);
response = wsClient.call(post);
} catch (Exception e) {
throw new IllegalStateException("Failed to upload report: " + e.getMessage(), e);
}
try {
response.failIfNotSuccessful();
} catch (HttpException e) {
throw MessageException.of(String.format("Server failed to process report. Please check server logs: %s", DefaultScannerWsClient.createErrorMessage(e)));
}
try (InputStream protobuf = response.contentStream()) {
return Ce.SubmitResponse.parser().parseFrom(protobuf).getTaskId();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
long stopTime = System.currentTimeMillis();
LOG.info("Analysis report uploaded in " + (stopTime - startTime) + "ms");
}
}
void prepareAndDumpMetadata(String taskId) {
Map<String, String> metadata = new LinkedHashMap<>();
metadata.put("projectKey", moduleHierarchy.root().key());
metadata.put("serverUrl", server.getPublicRootUrl());
metadata.put("serverVersion", server.getVersion());
properties.branch().ifPresent(branch -> metadata.put("branch", branch));
URL dashboardUrl = buildDashboardUrl(server.getPublicRootUrl(), moduleHierarchy.root().key());
metadata.put("dashboardUrl", dashboardUrl.toExternalForm());
URL taskUrl = HttpUrl.parse(server.getPublicRootUrl()).newBuilder()
.addPathSegment("api").addPathSegment("ce").addPathSegment("task")
.addQueryParameter(ID, taskId)
.build()
.url();
metadata.put("ceTaskId", taskId);
metadata.put("ceTaskUrl", taskUrl.toExternalForm());
ceTaskReportDataHolder.init(taskId, taskUrl.toExternalForm(), dashboardUrl.toExternalForm());
dumpMetadata(metadata);
}
private URL buildDashboardUrl(String publicUrl, String effectiveKey) {
HttpUrl httpUrl = HttpUrl.parse(publicUrl);
if (onPullRequest(branchConfiguration)) {
return httpUrl.newBuilder()
.addPathSegment(DASHBOARD)
.addEncodedQueryParameter(ID, encoded(effectiveKey))
.addEncodedQueryParameter("pullRequest", encoded(branchConfiguration.pullRequestKey()))
.build()
.url();
}
if (onBranch(branchConfiguration)) {
return httpUrl.newBuilder()
.addPathSegment(DASHBOARD)
.addEncodedQueryParameter(ID, encoded(effectiveKey))
.addEncodedQueryParameter(BRANCH, encoded(branchConfiguration.branchName()))
.build()
.url();
}
if (onMainBranch(branchConfiguration)) {
return httpUrl.newBuilder()
.addPathSegment(DASHBOARD)
.addEncodedQueryParameter(ID, encoded(effectiveKey))
.build()
.url();
}
return httpUrl.newBuilder().build().url();
}
private static boolean onPullRequest(BranchConfiguration branchConfiguration) {
return branchConfiguration.branchName() != null && (branchConfiguration.branchType() == PULL_REQUEST);
}
private static boolean onBranch(BranchConfiguration branchConfiguration) {
return branchConfiguration.branchName() != null && (branchConfiguration.branchType() == BranchType.BRANCH);
}
private static boolean onMainBranch(BranchConfiguration branchConfiguration) {
return branchConfiguration.branchName() == null;
}
private static String encoded(@Nullable String queryParameter) {
if (isBlank(queryParameter)) {
return EMPTY;
}
try {
return encode(queryParameter, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("Unable to urlencode " + queryParameter, e);
}
}
private void dumpMetadata(Map<String, String> metadata) {
Path file = properties.metadataFilePath();
try {
Files.createDirectories(file.getParent());
try (Writer output = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
for (Map.Entry<String, String> entry : metadata.entrySet()) {
output.write(entry.getKey());
output.write("=");
output.write(entry.getValue());
output.write("\n");
}
}
LOG.debug("Report metadata written to {}", file);
} catch (IOException e) {
throw new IllegalStateException("Unable to dump " + file, e);
}
}
}
| 13,302 | 37.897661 | 166 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/report/ReportPublisherStep.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.scanner.report;
import org.sonar.scanner.protocol.output.ScannerReportWriter;
/**
* Adds a sub-part of data to output report
*/
@FunctionalInterface
public interface ReportPublisherStep {
void publish(ScannerReportWriter writer);
}
| 1,101 | 32.393939 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/report/ScannerFileStructureProvider.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.scanner.report;
import java.io.File;
import org.sonar.scanner.fs.InputModuleHierarchy;
import org.sonar.scanner.protocol.output.FileStructure;
import org.springframework.context.annotation.Bean;
public class ScannerFileStructureProvider {
@Bean
public FileStructure fileStructure(InputModuleHierarchy inputModuleHierarchy) {
File reportDir = inputModuleHierarchy.root().getWorkDir().resolve("scanner-report").toFile();
if (!reportDir.exists() && !reportDir.mkdirs()) {
throw new IllegalStateException("Unable to create directory: " + reportDir);
}
return new FileStructure(reportDir);
}
}
| 1,481 | 38 | 97 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/report/ScannerReportUtils.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.scanner.report;
import org.sonar.api.batch.sensor.highlighting.TypeOfText;
import org.sonar.scanner.protocol.output.ScannerReport.SyntaxHighlightingRule.HighlightingType;
public class ScannerReportUtils {
private ScannerReportUtils() {
}
public static HighlightingType toProtocolType(TypeOfText textType) {
switch (textType) {
case ANNOTATION:
return HighlightingType.ANNOTATION;
case COMMENT:
return HighlightingType.COMMENT;
case CONSTANT:
return HighlightingType.CONSTANT;
case KEYWORD:
return HighlightingType.KEYWORD;
case KEYWORD_LIGHT:
return HighlightingType.KEYWORD_LIGHT;
case PREPROCESS_DIRECTIVE:
return HighlightingType.PREPROCESS_DIRECTIVE;
case STRING:
return HighlightingType.HIGHLIGHTING_STRING;
case STRUCTURED_COMMENT:
return HighlightingType.STRUCTURED_COMMENT;
default:
throw new IllegalArgumentException("Unknow highlighting type: " + textType);
}
}
public static TypeOfText toBatchType(HighlightingType type) {
switch (type) {
case ANNOTATION:
return TypeOfText.ANNOTATION;
case COMMENT:
return TypeOfText.COMMENT;
case CONSTANT:
return TypeOfText.CONSTANT;
case HIGHLIGHTING_STRING:
return TypeOfText.STRING;
case KEYWORD:
return TypeOfText.KEYWORD;
case KEYWORD_LIGHT:
return TypeOfText.KEYWORD_LIGHT;
case PREPROCESS_DIRECTIVE:
return TypeOfText.PREPROCESS_DIRECTIVE;
case STRUCTURED_COMMENT:
return TypeOfText.STRUCTURED_COMMENT;
default:
throw new IllegalArgumentException(type + " is not a valid type");
}
}
public static String toCssClass(HighlightingType type) {
return toBatchType(type).cssClass();
}
}
| 2,690 | 32.6375 | 95 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/report/SourcePublisher.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.scanner.report;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.IOUtils;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.scanner.protocol.output.ScannerReportWriter;
import org.sonar.scanner.scan.filesystem.InputComponentStore;
public class SourcePublisher implements ReportPublisherStep {
private final InputComponentStore componentCache;
public SourcePublisher(InputComponentStore componentStore) {
this.componentCache = componentStore;
}
@Override
public void publish(ScannerReportWriter writer) {
for (final DefaultInputFile inputFile : componentCache.allChangedFilesToPublish()) {
File iofile = writer.getSourceFile(inputFile.scannerId());
try (OutputStream output = new BufferedOutputStream(new FileOutputStream(iofile));
InputStream in = inputFile.inputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, inputFile.charset()))) {
writeSource(reader, output, inputFile.lines());
} catch (IOException e) {
throw new IllegalStateException("Unable to store file source in the report", e);
}
}
}
private static void writeSource(BufferedReader reader, OutputStream output, int lines) throws IOException {
int line = 0;
String lineStr = reader.readLine();
while (lineStr != null) {
IOUtils.write(lineStr, output, StandardCharsets.UTF_8);
line++;
if (line < lines) {
IOUtils.write("\n", output, StandardCharsets.UTF_8);
}
lineStr = reader.readLine();
}
}
}
| 2,679 | 36.222222 | 109 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/report/TestExecutionPublisher.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.scanner.report;
import java.util.Objects;
import java.util.stream.StreamSupport;
import org.sonar.api.batch.fs.InputComponent;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.DefaultInputComponent;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.sensor.measure.internal.DefaultMeasure;
import org.sonar.scanner.deprecated.test.DefaultTestCase;
import org.sonar.scanner.deprecated.test.DefaultTestCase.Status;
import org.sonar.scanner.deprecated.test.DefaultTestPlan;
import org.sonar.scanner.deprecated.test.TestPlanBuilder;
import org.sonar.scanner.protocol.output.ScannerReportWriter;
import org.sonar.scanner.scan.filesystem.InputComponentStore;
import static org.sonar.api.measures.CoreMetrics.SKIPPED_TESTS;
import static org.sonar.api.measures.CoreMetrics.TESTS;
import static org.sonar.api.measures.CoreMetrics.TEST_ERRORS;
import static org.sonar.api.measures.CoreMetrics.TEST_EXECUTION_TIME;
import static org.sonar.api.measures.CoreMetrics.TEST_FAILURES;
import static org.sonar.scanner.sensor.DefaultSensorStorage.toReportMeasure;
public class TestExecutionPublisher implements ReportPublisherStep {
private final InputComponentStore componentStore;
private final TestPlanBuilder testPlanBuilder;
public TestExecutionPublisher(InputComponentStore componentStore, TestPlanBuilder testPlanBuilder) {
this.componentStore = componentStore;
this.testPlanBuilder = testPlanBuilder;
}
@Override
public void publish(ScannerReportWriter writer) {
for (final InputComponent c : componentStore.all()) {
DefaultInputComponent component = (DefaultInputComponent) c;
if (component.isFile()) {
DefaultInputFile file = (DefaultInputFile) component;
// Recompute test execution measures from MutableTestPlan to take into account the possible merge of several reports
updateTestExecutionFromTestPlan(file, writer);
}
}
}
private void updateTestExecutionFromTestPlan(final InputFile inputFile, ScannerReportWriter writer) {
final DefaultTestPlan testPlan = testPlanBuilder.getTestPlanByFile(inputFile);
if (testPlan == null || !testPlan.testCases().iterator().hasNext()) {
return;
}
long nonSkippedTests = StreamSupport.stream(testPlan.testCases().spliterator(), false).filter(t -> t.status() != Status.SKIPPED).count();
appendMeasure(inputFile, writer, new DefaultMeasure<Integer>().forMetric(TESTS).withValue((int) nonSkippedTests));
long executionTime = StreamSupport.stream(testPlan.testCases().spliterator(), false).map(DefaultTestCase::durationInMs).filter(Objects::nonNull).mapToLong(Long::longValue)
.sum();
appendMeasure(inputFile, writer, new DefaultMeasure<Long>().forMetric(TEST_EXECUTION_TIME).withValue(executionTime));
long errorTests = StreamSupport.stream(testPlan.testCases().spliterator(), false).filter(t -> t.status() == Status.ERROR).count();
appendMeasure(inputFile, writer, new DefaultMeasure<Integer>().forMetric(TEST_ERRORS).withValue((int) errorTests));
long skippedTests = StreamSupport.stream(testPlan.testCases().spliterator(), false).filter(t -> t.status() == Status.SKIPPED).count();
appendMeasure(inputFile, writer, new DefaultMeasure<Integer>().forMetric(SKIPPED_TESTS).withValue((int) skippedTests));
long failedTests = StreamSupport.stream(testPlan.testCases().spliterator(), false).filter(t -> t.status() == Status.FAILURE).count();
appendMeasure(inputFile, writer, new DefaultMeasure<Integer>().forMetric(TEST_FAILURES).withValue((int) failedTests));
}
private static void appendMeasure(InputFile inputFile, ScannerReportWriter writer, DefaultMeasure measure) {
writer.appendComponentMeasure(((DefaultInputComponent) inputFile).scannerId(), toReportMeasure(measure));
}
}
| 4,689 | 51.696629 | 175 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/report/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.scanner.report;
import javax.annotation.ParametersAreNonnullByDefault;
| 964 | 39.208333 | 75 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/ContextPropertiesCache.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.scanner.repository;
import java.util.HashMap;
import java.util.Map;
import static org.sonar.api.utils.Preconditions.checkArgument;
public class ContextPropertiesCache {
private final Map<String, String> props = new HashMap<>();
/**
* Value is overridden if the key was already stored.
* @throws IllegalArgumentException if key is null
* @throws IllegalArgumentException if value is null
* @since 6.1
*/
public ContextPropertiesCache put(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");
props.put(key, value);
return this;
}
public Map<String, String> getAll() {
return props;
}
}
| 1,621 | 32.791667 | 79 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/DefaultMetricsRepositoryLoader.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.scanner.repository;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import org.sonar.api.measures.Metric;
import org.sonar.api.measures.Metric.ValueType;
import org.sonar.scanner.bootstrap.DefaultScannerWsClient;
import org.sonar.scanner.protocol.GsonHelper;
import org.sonarqube.ws.client.GetRequest;
public class DefaultMetricsRepositoryLoader implements MetricsRepositoryLoader {
private static final String METRICS_SEARCH_URL = "/api/metrics/search?ps=500&p=";
private DefaultScannerWsClient wsClient;
public DefaultMetricsRepositoryLoader(DefaultScannerWsClient wsClient) {
this.wsClient = wsClient;
}
@Override
public MetricsRepository load() {
List<Metric> metrics = new ArrayList<>();
try {
loadFromPaginatedWs(metrics);
} catch (Exception e) {
throw new IllegalStateException("Unable to load metrics", e);
}
return new MetricsRepository(metrics);
}
private void loadFromPaginatedWs(List<Metric> metrics) throws IOException {
int page = 1;
WsMetricsResponse response;
do {
GetRequest getRequest = new GetRequest(METRICS_SEARCH_URL + page);
try (Reader reader = wsClient.call(getRequest).contentReader()) {
response = GsonHelper.create().fromJson(reader, WsMetricsResponse.class);
for (WsMetric metric : response.metrics) {
metrics.add(new Metric.Builder(metric.getKey(), metric.getName(), ValueType.valueOf(metric.getType()))
.create()
.setDirection(metric.getDirection())
.setQualitative(metric.isQualitative())
.setUserManaged(false)
.setDescription(metric.getDescription())
.setUuid(metric.getUuid()));
}
}
page++;
} while (response.getP() < (response.getTotal() / response.getPs() + 1));
}
private static class WsMetric {
private String uuid;
private String key;
private String type;
private String name;
private String description;
private int direction;
private boolean qualitative;
public String getUuid() {
return uuid;
}
public String getKey() {
return key;
}
public String getType() {
return type;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public int getDirection() {
return direction;
}
public boolean isQualitative() {
return qualitative;
}
}
private static class WsMetricsResponse {
private List<WsMetric> metrics = new ArrayList<>();
private int total;
private int p;
private int ps;
public WsMetricsResponse() {
// http://stackoverflow.com/a/18645370/229031
}
public int getTotal() {
return total;
}
public int getP() {
return p;
}
public int getPs() {
return ps;
}
}
}
| 3,795 | 26.114286 | 112 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/DefaultNewCodePeriodLoader.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.scanner.repository;
import java.io.IOException;
import java.io.InputStream;
import org.sonar.scanner.bootstrap.DefaultScannerWsClient;
import org.sonarqube.ws.NewCodePeriods;
import org.sonarqube.ws.client.GetRequest;
import org.sonarqube.ws.client.HttpException;
import static org.sonar.api.impl.utils.ScannerUtils.encodeForUrl;
public class DefaultNewCodePeriodLoader implements NewCodePeriodLoader {
private static final String WS_URL = "/api/new_code_periods/show.protobuf";
private final DefaultScannerWsClient wsClient;
public DefaultNewCodePeriodLoader(DefaultScannerWsClient wsClient) {
this.wsClient = wsClient;
}
@Override public NewCodePeriods.ShowWSResponse load(String projectKey, String branchName) {
String url = WS_URL + "?project=" + encodeForUrl(projectKey) + "&branch=" + encodeForUrl(branchName);
try {
return call(url);
} catch (HttpException | IOException e) {
throw new IllegalStateException("Failed to get the New Code definition: " + e.getMessage(), e);
}
}
private NewCodePeriods.ShowWSResponse call(String url) throws IOException {
GetRequest getRequest = new GetRequest(url);
try (InputStream is = wsClient.call(getRequest).contentStream()) {
return NewCodePeriods.ShowWSResponse.parseFrom(is);
}
}
}
| 2,163 | 37.642857 | 105 | java |
sonarqube | sonarqube-master/sonar-scanner-engine/src/main/java/org/sonar/scanner/repository/DefaultProjectRepositoriesLoader.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.scanner.repository;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.impl.utils.ScannerUtils;
import org.sonar.scanner.bootstrap.DefaultScannerWsClient;
import org.sonarqube.ws.Batch.WsProjectResponse;
import org.sonarqube.ws.client.GetRequest;
import org.sonarqube.ws.client.HttpException;
import org.sonarqube.ws.client.WsResponse;
public class DefaultProjectRepositoriesLoader implements ProjectRepositoriesLoader {
private static final Logger LOG = LoggerFactory.getLogger(DefaultProjectRepositoriesLoader.class);
private static final String BATCH_PROJECT_URL = "/batch/project.protobuf";
private final DefaultScannerWsClient wsClient;
public DefaultProjectRepositoriesLoader(DefaultScannerWsClient wsClient) {
this.wsClient = wsClient;
}
@Override
public ProjectRepositories load(String projectKey, @Nullable String branchBase) {
GetRequest request = new GetRequest(getUrl(projectKey, branchBase));
try (WsResponse response = wsClient.call(request)) {
try (InputStream is = response.contentStream()) {
return processStream(is);
} catch (IOException e) {
throw new IllegalStateException("Couldn't load project repository for " + projectKey, e);
}
} catch (RuntimeException e) {
if (shouldThrow(e)) {
throw e;
}
LOG.debug("Project repository not available - continuing without it");
return new SingleProjectRepository();
}
}
private static String getUrl(String projectKey, @Nullable String branchBase) {
StringBuilder builder = new StringBuilder();
builder.append(BATCH_PROJECT_URL)
.append("?key=").append(ScannerUtils.encodeForUrl(projectKey));
if (branchBase != null) {
builder.append("&branch=").append(branchBase);
}
return builder.toString();
}
private static boolean shouldThrow(Exception e) {
Throwable t = e;
do {
if (t instanceof HttpException && ((HttpException) t).code() == HttpURLConnection.HTTP_NOT_FOUND) {
return false;
}
t = t.getCause();
} while (t != null);
return true;
}
private static ProjectRepositories processStream(InputStream is) throws IOException {
WsProjectResponse response = WsProjectResponse.parseFrom(is);
if (response.getFileDataByModuleAndPathCount() == 0) {
return new SingleProjectRepository(constructFileDataMap(response.getFileDataByPathMap()));
} else {
final Map<String, SingleProjectRepository> repositoriesPerModule = new HashMap<>();
response.getFileDataByModuleAndPathMap().keySet().forEach(moduleKey -> {
WsProjectResponse.FileDataByPath filePaths = response.getFileDataByModuleAndPathMap().get(moduleKey);
repositoriesPerModule.put(moduleKey, new SingleProjectRepository(
constructFileDataMap(filePaths.getFileDataByPathMap())));
});
return new MultiModuleProjectRepository(repositoriesPerModule);
}
}
private static Map<String, FileData> constructFileDataMap(Map<String, WsProjectResponse.FileData> content) {
Map<String, FileData> fileDataMap = new HashMap<>();
content.forEach((key, value) -> {
FileData fd = new FileData(value.getHash(), value.getRevision());
fileDataMap.put(key, fd);
});
return fileDataMap;
}
}
| 4,339 | 36.73913 | 110 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.