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/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/SourceLinesHashRepositoryImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.source;
import java.util.List;
import java.util.Optional;
import org.apache.commons.lang.StringUtils;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.core.hash.LineRange;
import org.sonar.core.hash.SourceLineHashesComputer;
import org.sonar.core.util.CloseableIterator;
import org.sonar.db.source.LineHashVersion;
public class SourceLinesHashRepositoryImpl implements SourceLinesHashRepository {
private final SourceLinesRepository sourceLinesRepository;
private final SignificantCodeRepository significantCodeRepository;
private final SourceLinesHashCache cache;
private final DbLineHashVersion dbLineHashesVersion;
public SourceLinesHashRepositoryImpl(SourceLinesRepository sourceLinesRepository, SignificantCodeRepository significantCodeRepository,
SourceLinesHashCache cache, DbLineHashVersion dbLineHashVersion) {
this.sourceLinesRepository = sourceLinesRepository;
this.significantCodeRepository = significantCodeRepository;
this.cache = cache;
this.dbLineHashesVersion = dbLineHashVersion;
}
@Override
public List<String> getLineHashesMatchingDBVersion(Component component) {
return cache.computeIfAbsent(component, this::createLineHashesMatchingDBVersion);
}
@Override
public int getLineHashesVersion(Component component) {
if (significantCodeRepository.getRangesPerLine(component).isPresent()) {
return LineHashVersion.WITH_SIGNIFICANT_CODE.getDbValue();
} else {
return LineHashVersion.WITHOUT_SIGNIFICANT_CODE.getDbValue();
}
}
@Override
public LineHashesComputer getLineHashesComputerToPersist(Component component) {
boolean cacheHit = cache.contains(component);
// check if line hashes are cached and if we can use it
if (cacheHit && !dbLineHashesVersion.hasLineHashesWithoutSignificantCode(component)) {
return new CachedLineHashesComputer(cache.get(component));
}
Optional<LineRange[]> significantCodePerLine = significantCodeRepository.getRangesPerLine(component);
if (cacheHit && !significantCodePerLine.isPresent()) {
return new CachedLineHashesComputer(cache.get(component));
}
// Generate the line hashes taking into account significant code ranges
return createLineHashesProcessor(component.getFileAttributes().getLines(), significantCodePerLine);
}
private List<String> createLineHashesMatchingDBVersion(Component component) {
if (dbLineHashesVersion.hasLineHashesWithoutSignificantCode(component)) {
return createLineHashes(component, Optional.empty());
}
// if the file is not in the DB, this will be used too
Optional<LineRange[]> significantCodePerLine = significantCodeRepository.getRangesPerLine(component);
return createLineHashes(component, significantCodePerLine);
}
private List<String> createLineHashes(Component component, Optional<LineRange[]> significantCodePerLine) {
LineHashesComputer processor = createLineHashesProcessor(component.getFileAttributes().getLines(), significantCodePerLine);
try (CloseableIterator<String> lines = sourceLinesRepository.readLines(component)) {
while (lines.hasNext()) {
processor.addLine(lines.next());
}
return processor.getResult();
}
}
public interface LineHashesComputer {
void addLine(String line);
List<String> getResult();
}
private static LineHashesComputer createLineHashesProcessor(int numLines, Optional<LineRange[]> significantCodePerLine) {
if (significantCodePerLine.isPresent()) {
return new SignificantCodeLineHashesComputer(new SourceLineHashesComputer(numLines), significantCodePerLine.get());
} else {
return new SimpleLineHashesComputer(numLines);
}
}
static class CachedLineHashesComputer implements LineHashesComputer {
private final List<String> lineHashes;
public CachedLineHashesComputer(List<String> lineHashes) {
this.lineHashes = lineHashes;
}
@Override
public void addLine(String line) {
// no op
}
@Override
public List<String> getResult() {
return lineHashes;
}
}
static class SimpleLineHashesComputer implements LineHashesComputer {
private final SourceLineHashesComputer delegate;
public SimpleLineHashesComputer(int numLines) {
this.delegate = new SourceLineHashesComputer(numLines);
}
@Override
public void addLine(String line) {
delegate.addLine(line);
}
@Override
public List<String> getResult() {
return delegate.getLineHashes();
}
}
static class SignificantCodeLineHashesComputer implements LineHashesComputer {
private final SourceLineHashesComputer delegate;
private final LineRange[] rangesPerLine;
private int i = 0;
public SignificantCodeLineHashesComputer(SourceLineHashesComputer hashComputer, LineRange[] rangesPerLine) {
this.rangesPerLine = rangesPerLine;
this.delegate = hashComputer;
}
@Override
public void addLine(String line) {
LineRange range = null;
if (i < rangesPerLine.length) {
range = rangesPerLine[i];
}
if (range == null) {
delegate.addLine("");
} else {
delegate.addLine(StringUtils.substring(line, range.startOffset(), range.endOffset()));
}
i++;
}
@Override
public List<String> getResult() {
return delegate.getLineHashes();
}
}
}
| 6,299 | 34 | 136 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/SourceLinesRepository.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.source;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.core.util.CloseableIterator;
public interface SourceLinesRepository {
/**
* Creates a iterator over the source lines of a given component from the report.
* <p>
* The returned {@link CloseableIterator} will wrap the {@link CloseableIterator} returned by
* {@link org.sonar.ce.task.projectanalysis.batch.BatchReportReader#readFileSource(int)} but enforces that the number
* of lines specified by {@link org.sonar.scanner.protocol.output.ScannerReport.Component#getLines()} is respected, adding
* an extra empty last line if required.
* </p>
*
* @throws NullPointerException if argument is {@code null}
* @throws IllegalArgumentException if component is not a {@link Component.Type#FILE}
* @throws IllegalStateException if the file has no source code in the report
*/
CloseableIterator<String> readLines(Component component);
}
| 1,841 | 42.857143 | 124 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/SourceLinesRepositoryImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.source;
import java.util.Optional;
import org.sonar.ce.task.projectanalysis.batch.BatchReportReader;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.core.util.CloseableIterator;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.FILE;
public class SourceLinesRepositoryImpl implements SourceLinesRepository {
private final BatchReportReader reportReader;
public SourceLinesRepositoryImpl(BatchReportReader reportReader) {
this.reportReader = reportReader;
}
@Override
public CloseableIterator<String> readLines(Component file) {
requireNonNull(file, "Component should not be null");
checkArgument(file.getType() == FILE, "Component '%s' is not a file", file);
Optional<CloseableIterator<String>> linesIteratorOptional = reportReader.readFileSource(file.getReportAttributes().getRef());
checkState(linesIteratorOptional.isPresent(), "File '%s' has no source code", file);
CloseableIterator<String> lineIterator = linesIteratorOptional.get();
return new ComponentLinesCloseableIterator(file, lineIterator, file.getFileAttributes().getLines());
}
private static class ComponentLinesCloseableIterator extends CloseableIterator<String> {
private static final String EXTRA_END_LINE = "";
private final Component file;
private final CloseableIterator<String> delegate;
private final int numberOfLines;
private int currentLine = 0;
private ComponentLinesCloseableIterator(Component file, CloseableIterator<String> lineIterator, int numberOfLines) {
this.file = file;
this.delegate = lineIterator;
this.numberOfLines = numberOfLines;
}
@Override
public boolean hasNext() {
if (delegate.hasNext()) {
checkState(currentLine < numberOfLines, "Source of file '%s' has at least one more line than the expected number (%s)", file, numberOfLines);
return true;
}
checkState((currentLine + 1) >= numberOfLines, "Source of file '%s' has less lines (%s) than the expected number (%s)", file, currentLine, numberOfLines);
return currentLine < numberOfLines;
}
@Override
public String next() {
if (!hasNext()) {
// will throw NoSuchElementException
return delegate.next();
}
currentLine++;
if (delegate.hasNext()) {
return delegate.next();
}
return EXTRA_END_LINE;
}
@Override
protected String doNext() {
throw new UnsupportedOperationException("Not implemented because hasNext() and next() are overridden");
}
@Override
protected void doClose() {
delegate.close();
}
}
}
| 3,733 | 35.607843 | 160 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/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.ce.task.projectanalysis.source;
import javax.annotation.ParametersAreNonnullByDefault;
| 980 | 39.875 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/linereader/CoverageLineReader.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.source.linereader;
import java.util.Iterator;
import java.util.Optional;
import javax.annotation.CheckForNull;
import org.sonar.db.protobuf.DbFileSources;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.protocol.output.ScannerReport.LineCoverage.HasCoveredConditionsCase;
import org.sonar.scanner.protocol.output.ScannerReport.LineCoverage.HasHitsCase;
public class CoverageLineReader implements LineReader {
private final Iterator<ScannerReport.LineCoverage> coverageIterator;
private ScannerReport.LineCoverage coverage;
public CoverageLineReader(Iterator<ScannerReport.LineCoverage> coverageIterator) {
this.coverageIterator = coverageIterator;
}
@Override
public Optional<ReadError> read(DbFileSources.Line.Builder lineBuilder) {
ScannerReport.LineCoverage reportCoverage = getNextLineCoverageIfMatchLine(lineBuilder.getLine());
if (reportCoverage != null) {
processCoverage(lineBuilder, reportCoverage);
coverage = null;
}
return Optional.empty();
}
private static void processCoverage(DbFileSources.Line.Builder lineBuilder, ScannerReport.LineCoverage reportCoverage) {
if (reportCoverage.getHasHitsCase() == HasHitsCase.HITS) {
lineBuilder.setLineHits(reportCoverage.getHits() ? 1 : 0);
}
if (reportCoverage.getHasCoveredConditionsCase() == HasCoveredConditionsCase.COVERED_CONDITIONS) {
lineBuilder.setConditions(reportCoverage.getConditions());
lineBuilder.setCoveredConditions(reportCoverage.getCoveredConditions());
}
}
@CheckForNull
private ScannerReport.LineCoverage getNextLineCoverageIfMatchLine(int line) {
// Get next element (if exists)
if (coverage == null && coverageIterator.hasNext()) {
coverage = coverageIterator.next();
}
// Return current element if lines match
if (coverage != null && coverage.getLine() == line) {
return coverage;
}
return null;
}
}
| 2,834 | 37.835616 | 122 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/linereader/DuplicationLineReader.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.source.linereader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.sonar.ce.task.projectanalysis.duplication.Duplicate;
import org.sonar.ce.task.projectanalysis.duplication.Duplication;
import org.sonar.ce.task.projectanalysis.duplication.InnerDuplicate;
import org.sonar.ce.task.projectanalysis.duplication.TextBlock;
import org.sonar.db.protobuf.DbFileSources;
import static com.google.common.collect.Iterables.size;
public class DuplicationLineReader implements LineReader {
private final Map<TextBlock, Integer> duplicatedTextBlockIndexByTextBlock;
public DuplicationLineReader(Iterable<Duplication> duplications) {
this.duplicatedTextBlockIndexByTextBlock = createIndexOfDuplicatedTextBlocks(duplications);
}
@Override
public Optional<ReadError> read(DbFileSources.Line.Builder lineBuilder) {
Predicate<Map.Entry<TextBlock, Integer>> containsLine = new TextBlockContainsLine(lineBuilder.getLine());
// list is sorted to cope with the non-guaranteed order of Map entries which would trigger false detection of changes
// in {@link DbFileSources.Line#getDuplicationList()}
duplicatedTextBlockIndexByTextBlock.entrySet().stream()
.filter(containsLine)
.map(Map.Entry::getValue)
.sorted(Comparator.naturalOrder())
.forEach(lineBuilder::addDuplication);
return Optional.empty();
}
/**
* <p>
* This method uses the natural order of TextBlocks to ensure that given the same set of TextBlocks, they get the same
* index. It avoids false detections of changes in {@link DbFileSources.Line#getDuplicationList()}.
* </p>
*/
private static Map<TextBlock, Integer> createIndexOfDuplicatedTextBlocks(Iterable<Duplication> duplications) {
return extractAllDuplicatedTextBlocks(duplications)
.stream().sorted()
.collect(Collectors.toMap(e -> e, new TextBlockIndexGenerator(), (a, b) -> a, LinkedHashMap::new));
}
/**
* Duplicated blocks in the current file are either {@link Duplication#getOriginal()} or {@link Duplication#getDuplicates()}
* when the {@link Duplicate} is a {@link InnerDuplicate}.
* <p>
* The returned list is mutable on purpose because it will be sorted.
* </p>
*
* @see {@link #createIndexOfDuplicatedTextBlocks(Iterable)}
*/
private static List<TextBlock> extractAllDuplicatedTextBlocks(Iterable<Duplication> duplications) {
List<TextBlock> duplicatedBlock = new ArrayList<>(size(duplications));
for (Duplication duplication : duplications) {
duplicatedBlock.add(duplication.getOriginal());
Arrays.stream(duplication.getDuplicates())
.filter(InnerDuplicate.class::isInstance)
.forEach(duplicate -> duplicatedBlock.add(duplicate.getTextBlock()));
}
return duplicatedBlock;
}
private static class TextBlockContainsLine implements Predicate<Map.Entry<TextBlock, Integer>> {
private final int line;
public TextBlockContainsLine(int line) {
this.line = line;
}
@Override
public boolean test(@Nonnull Map.Entry<TextBlock, Integer> input) {
return isLineInBlock(input.getKey(), line);
}
private static boolean isLineInBlock(TextBlock range, int line) {
return line >= range.getStart() && line <= range.getEnd();
}
}
private static class TextBlockIndexGenerator implements Function<TextBlock, Integer> {
int i = 1;
@Nullable
@Override
public Integer apply(TextBlock input) {
return i++;
}
}
}
| 4,675 | 37.01626 | 126 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/linereader/HighlightingLineReader.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.source.linereader;
import com.google.common.collect.ImmutableMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.annotation.CheckForNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.source.linereader.RangeOffsetConverter.RangeOffsetConverterException;
import org.sonar.db.protobuf.DbFileSources;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.protocol.output.ScannerReport.SyntaxHighlightingRule.HighlightingType;
import static com.google.common.collect.Lists.newArrayList;
import static java.lang.String.format;
import static org.sonar.ce.task.projectanalysis.source.linereader.LineReader.Data.HIGHLIGHTING;
import static org.sonar.ce.task.projectanalysis.source.linereader.RangeOffsetConverter.OFFSET_SEPARATOR;
import static org.sonar.ce.task.projectanalysis.source.linereader.RangeOffsetConverter.SYMBOLS_SEPARATOR;
public class HighlightingLineReader implements LineReader {
private static final Logger LOG = LoggerFactory.getLogger(HighlightingLineReader.class);
private static final Map<HighlightingType, String> cssClassByType = ImmutableMap.<HighlightingType, String>builder()
.put(HighlightingType.ANNOTATION, "a")
.put(HighlightingType.CONSTANT, "c")
.put(HighlightingType.COMMENT, "cd")
.put(HighlightingType.STRUCTURED_COMMENT, "j")
.put(HighlightingType.KEYWORD, "k")
.put(HighlightingType.KEYWORD_LIGHT, "h")
.put(HighlightingType.HIGHLIGHTING_STRING, "s")
.put(HighlightingType.PREPROCESS_DIRECTIVE, "p")
.build();
private final Component file;
private final Iterator<ScannerReport.SyntaxHighlightingRule> lineHighlightingIterator;
private final RangeOffsetConverter rangeOffsetConverter;
private final List<ScannerReport.SyntaxHighlightingRule> highlightingList;
private ReadError readError = null;
private ScannerReport.SyntaxHighlightingRule currentItem;
public HighlightingLineReader(Component file, Iterator<ScannerReport.SyntaxHighlightingRule> lineHighlightingIterator, RangeOffsetConverter rangeOffsetConverter) {
this.file = file;
this.lineHighlightingIterator = lineHighlightingIterator;
this.rangeOffsetConverter = rangeOffsetConverter;
this.highlightingList = newArrayList();
}
/**
* Stops reading at first encountered error, which implies the same
* {@link org.sonar.ce.task.projectanalysis.source.linereader.LineReader.ReadError} will be returned once an error
* has been encountered and for any then provided {@link DbFileSources.Line.Builder lineBuilder}.
*/
@Override
public Optional<ReadError> read(DbFileSources.Line.Builder lineBuilder) {
if (readError == null) {
try {
processHighlightings(lineBuilder);
} catch (RangeOffsetConverterException e) {
readError = new ReadError(HIGHLIGHTING, lineBuilder.getLine());
LOG.debug(format("Inconsistency detected in Highlighting data. Highlighting will be ignored for file '%s'", file.getKey()), e);
}
}
return Optional.ofNullable(readError);
}
private void processHighlightings(DbFileSources.Line.Builder lineBuilder) {
int line = lineBuilder.getLine();
StringBuilder highlighting = new StringBuilder();
incrementHighlightingListMatchingLine(line);
for (Iterator<ScannerReport.SyntaxHighlightingRule> syntaxHighlightingIterator = highlightingList.iterator(); syntaxHighlightingIterator.hasNext();) {
processHighlighting(syntaxHighlightingIterator, highlighting, lineBuilder);
}
if (highlighting.length() > 0) {
lineBuilder.setHighlighting(highlighting.toString());
}
}
private void processHighlighting(Iterator<ScannerReport.SyntaxHighlightingRule> syntaxHighlightingIterator, StringBuilder highlighting,
DbFileSources.Line.Builder lineBuilder) {
ScannerReport.SyntaxHighlightingRule syntaxHighlighting = syntaxHighlightingIterator.next();
int line = lineBuilder.getLine();
ScannerReport.TextRange range = syntaxHighlighting.getRange();
if (range.getStartLine() <= line) {
String offsets = rangeOffsetConverter.offsetToString(syntaxHighlighting.getRange(), line, lineBuilder.getSource().length());
if (offsets.isEmpty()) {
if (range.getEndLine() == line) {
syntaxHighlightingIterator.remove();
}
} else {
if (highlighting.length() > 0) {
highlighting.append(SYMBOLS_SEPARATOR);
}
highlighting.append(offsets)
.append(OFFSET_SEPARATOR)
.append(getCssClass(syntaxHighlighting.getType()));
if (range.getEndLine() == line) {
syntaxHighlightingIterator.remove();
}
}
}
}
private static String getCssClass(HighlightingType type) {
String cssClass = cssClassByType.get(type);
if (cssClass != null) {
return cssClass;
} else {
throw new IllegalArgumentException(format("Unknown type %s ", type.toString()));
}
}
private void incrementHighlightingListMatchingLine(int line) {
ScannerReport.SyntaxHighlightingRule syntaxHighlighting = getNextHighlightingMatchingLine(line);
while (syntaxHighlighting != null) {
highlightingList.add(syntaxHighlighting);
this.currentItem = null;
syntaxHighlighting = getNextHighlightingMatchingLine(line);
}
}
@CheckForNull
private ScannerReport.SyntaxHighlightingRule getNextHighlightingMatchingLine(int line) {
// Get next element (if exists)
if (currentItem == null && lineHighlightingIterator.hasNext()) {
currentItem = lineHighlightingIterator.next();
}
// Return current element if lines match
if (currentItem != null && currentItem.getRange().getStartLine() == line) {
return currentItem;
}
return null;
}
}
| 6,790 | 41.710692 | 165 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/linereader/IsNewLineReader.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.source.linereader;
import java.util.Collections;
import java.util.Optional;
import java.util.Set;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.source.NewLinesRepository;
import org.sonar.db.protobuf.DbFileSources;
public class IsNewLineReader implements LineReader {
private final Set<Integer> newLines;
public IsNewLineReader(NewLinesRepository newLinesRepository, Component file) {
this.newLines = newLinesRepository.getNewLines(file).orElse(Collections.emptySet());
}
@Override
public Optional<ReadError> read(DbFileSources.Line.Builder lineBuilder) {
lineBuilder.setIsNewLine(newLines.contains(lineBuilder.getLine()));
return Optional.empty();
}
}
| 1,623 | 37.666667 | 88 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/linereader/LineReader.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.source.linereader;
import java.util.Optional;
import org.sonar.db.protobuf.DbFileSources;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
@FunctionalInterface
public interface LineReader {
Optional<ReadError> read(DbFileSources.Line.Builder lineBuilder);
enum Data {
COVERAGE, DUPLICATION, HIGHLIGHTING, SCM, SYMBOLS
}
record ReadError(Data data, int line) {
public ReadError {
requireNonNull(data);
checkArgument(line >= 0);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ReadError readError = (ReadError) o;
return line == readError.line &&
data == readError.data;
}
@Override
public String toString() {
return "ReadError{" +
"data=" + data +
", line=" + line +
'}';
}
}
}
| 1,876 | 27.876923 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/linereader/RangeOffsetConverter.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.source.linereader;
import org.sonar.scanner.protocol.output.ScannerReport;
import static java.lang.String.format;
public class RangeOffsetConverter {
static final String OFFSET_SEPARATOR = ",";
static final String SYMBOLS_SEPARATOR = ";";
public String offsetToString(ScannerReport.TextRange range, int lineIndex, int lineLength) {
validateOffsetOrder(range, lineIndex);
validateStartOffsetNotGreaterThanLineLength(range, lineLength, lineIndex);
validateEndOffsetNotGreaterThanLineLength(range, lineLength, lineIndex);
int startOffset = range.getStartLine() == lineIndex ? range.getStartOffset() : 0;
int endOffset = range.getEndLine() == lineIndex ? range.getEndOffset() : lineLength;
StringBuilder element = new StringBuilder();
if (startOffset < endOffset) {
element.append(startOffset).append(OFFSET_SEPARATOR);
element.append(endOffset);
}
return element.toString();
}
private static void validateOffsetOrder(ScannerReport.TextRange range, int line) {
checkExpression(range.getStartLine() != range.getEndLine() || range.getStartOffset() <= range.getEndOffset(),
"End offset %s cannot be defined before start offset %s on line %s", range.getEndOffset(), range.getStartOffset(), line);
}
private static void validateStartOffsetNotGreaterThanLineLength(ScannerReport.TextRange range, int lineLength, int line) {
checkExpression(range.getStartLine() != line || range.getStartOffset() <= lineLength,
"Start offset %s is defined outside the length (%s) of the line %s", range.getStartOffset(), lineLength, line);
}
private static void validateEndOffsetNotGreaterThanLineLength(ScannerReport.TextRange range, int lineLength, int line) {
checkExpression(range.getEndLine() != line || range.getEndOffset() <= lineLength,
"End offset %s is defined outside the length (%s) of the line %s", range.getEndOffset(), lineLength, line);
}
private static void checkExpression(boolean expression, String errorMessageTemplate, Object... errorMessageArgs) {
if (!expression) {
throw new RangeOffsetConverterException(format(errorMessageTemplate, errorMessageArgs));
}
}
public static class RangeOffsetConverterException extends RuntimeException {
public RangeOffsetConverterException(String message) {
super(message);
}
}
}
| 3,241 | 41.657895 | 127 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/linereader/ScmLineReader.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.source.linereader;
import java.util.Optional;
import javax.annotation.CheckForNull;
import org.sonar.ce.task.projectanalysis.scm.Changeset;
import org.sonar.ce.task.projectanalysis.scm.ScmInfo;
import org.sonar.db.protobuf.DbFileSources;
public class ScmLineReader implements LineReader {
private final ScmInfo scmReport;
@CheckForNull
private Changeset latestChange;
@CheckForNull
private Changeset latestChangeWithRevision;
public ScmLineReader(ScmInfo scmReport) {
this.scmReport = scmReport;
}
@Override
public Optional<ReadError> read(DbFileSources.Line.Builder lineBuilder) {
if (scmReport.hasChangesetForLine(lineBuilder.getLine())) {
Changeset changeset = scmReport.getChangesetForLine(lineBuilder.getLine());
String author = changeset.getAuthor();
if (author != null) {
lineBuilder.setScmAuthor(author);
}
String revision = changeset.getRevision();
if (revision != null) {
lineBuilder.setScmRevision(revision);
}
lineBuilder.setScmDate(changeset.getDate());
updateLatestChange(changeset);
if (revision != null) {
updateLatestChangeWithRevision(changeset);
}
}
return Optional.empty();
}
private void updateLatestChange(Changeset newChangeSet) {
if (latestChange == null) {
latestChange = newChangeSet;
} else {
long newChangesetDate = newChangeSet.getDate();
long latestChangeDate = latestChange.getDate();
if (newChangesetDate > latestChangeDate) {
latestChange = newChangeSet;
}
}
}
private void updateLatestChangeWithRevision(Changeset newChangeSet) {
if (latestChangeWithRevision == null) {
latestChangeWithRevision = newChangeSet;
} else {
long newChangesetDate = newChangeSet.getDate();
long latestChangeDate = latestChangeWithRevision.getDate();
if (newChangesetDate > latestChangeDate) {
latestChangeWithRevision = newChangeSet;
}
}
}
@CheckForNull
public Changeset getLatestChangeWithRevision() {
return latestChangeWithRevision;
}
@CheckForNull
public Changeset getLatestChange() {
return latestChange;
}
}
| 3,075 | 31.041667 | 81 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/linereader/SymbolsLineReader.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.source.linereader;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.SetMultimap;
import java.util.Comparator;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.db.protobuf.DbFileSources;
import org.sonar.scanner.protocol.output.ScannerReport;
import static java.lang.String.format;
import static org.sonar.ce.task.projectanalysis.source.linereader.RangeOffsetConverter.OFFSET_SEPARATOR;
import static org.sonar.ce.task.projectanalysis.source.linereader.RangeOffsetConverter.SYMBOLS_SEPARATOR;
public class SymbolsLineReader implements LineReader {
private static final Logger LOG = LoggerFactory.getLogger(SymbolsLineReader.class);
private final Component file;
private final RangeOffsetConverter rangeOffsetConverter;
private final Map<ScannerReport.Symbol, Integer> idsBySymbol;
private final SetMultimap<Integer, ScannerReport.Symbol> symbolsPerLine;
private ReadError readError = null;
public SymbolsLineReader(Component file, Iterator<ScannerReport.Symbol> symbolIterator, RangeOffsetConverter rangeOffsetConverter) {
this.file = file;
this.rangeOffsetConverter = rangeOffsetConverter;
List<ScannerReport.Symbol> symbols = Lists.newArrayList(symbolIterator);
// Sort symbols to have deterministic id generation
symbols.sort(SymbolsComparator.INSTANCE);
this.idsBySymbol = createIdsBySymbolMap(symbols);
this.symbolsPerLine = buildSymbolsPerLine(symbols);
}
/**
* Stops reading at first encountered error, which implies the same
* {@link org.sonar.ce.task.projectanalysis.source.linereader.LineReader.ReadError} will be returned once an error
* has been encountered and for any then provided {@link DbFileSources.Line.Builder lineBuilder}.
*/
@Override
public Optional<ReadError> read(DbFileSources.Line.Builder lineBuilder) {
if (readError == null) {
try {
processSymbols(lineBuilder);
} catch (RangeOffsetConverter.RangeOffsetConverterException e) {
readError = new ReadError(Data.SYMBOLS, lineBuilder.getLine());
LOG.warn(format("Inconsistency detected in Symbols data. Symbols will be ignored for file '%s'", file.getKey()), e);
}
}
return Optional.ofNullable(readError);
}
private void processSymbols(DbFileSources.Line.Builder lineBuilder) {
int line = lineBuilder.getLine();
// Sort symbols to have deterministic results and avoid false variation that would lead to an unnecessary update of the source files
// data
StringBuilder symbolString = new StringBuilder();
symbolsPerLine.get(line).stream().sorted(SymbolsComparator.INSTANCE).forEach(lineSymbol -> {
int symbolId = idsBySymbol.get(lineSymbol);
appendSymbol(symbolString, lineSymbol.getDeclaration(), line, symbolId, lineBuilder.getSource());
for (ScannerReport.TextRange range : lineSymbol.getReferenceList()) {
appendSymbol(symbolString, range, line, symbolId, lineBuilder.getSource());
}
});
if (symbolString.length() > 0) {
lineBuilder.setSymbols(symbolString.toString());
}
}
private void appendSymbol(StringBuilder lineSymbol, ScannerReport.TextRange range, int line, int symbolId, String sourceLine) {
if (matchLine(range, line)) {
String offsets = rangeOffsetConverter.offsetToString(range, line, sourceLine.length());
if (!offsets.isEmpty()) {
if (lineSymbol.length() > 0) {
lineSymbol.append(SYMBOLS_SEPARATOR);
}
lineSymbol.append(offsets)
.append(OFFSET_SEPARATOR)
.append(symbolId);
}
}
}
private static boolean matchLine(ScannerReport.TextRange range, int line) {
return range.getStartLine() <= line && range.getEndLine() >= line;
}
private static Map<ScannerReport.Symbol, Integer> createIdsBySymbolMap(List<ScannerReport.Symbol> symbols) {
Map<ScannerReport.Symbol, Integer> map = new IdentityHashMap<>(symbols.size());
int symbolId = 1;
for (ScannerReport.Symbol symbol : symbols) {
map.put(symbol, symbolId);
symbolId++;
}
return map;
}
private static SetMultimap<Integer, ScannerReport.Symbol> buildSymbolsPerLine(List<ScannerReport.Symbol> symbols) {
SetMultimap<Integer, ScannerReport.Symbol> res = HashMultimap.create();
for (ScannerReport.Symbol symbol : symbols) {
putForTextRange(res, symbol, symbol.getDeclaration());
for (ScannerReport.TextRange textRange : symbol.getReferenceList()) {
putForTextRange(res, symbol, textRange);
}
}
return res;
}
private static void putForTextRange(SetMultimap<Integer, ScannerReport.Symbol> res, ScannerReport.Symbol symbol, ScannerReport.TextRange declaration) {
for (int i = declaration.getStartLine(); i <= declaration.getEndLine(); i++) {
res.put(i, symbol);
}
}
private enum SymbolsComparator implements Comparator<ScannerReport.Symbol> {
INSTANCE;
@Override
public int compare(ScannerReport.Symbol o1, ScannerReport.Symbol o2) {
if (o1.getDeclaration().getStartLine() == o2.getDeclaration().getStartLine()) {
return Integer.compare(o1.getDeclaration().getStartOffset(), o2.getDeclaration().getStartOffset());
} else {
return Integer.compare(o1.getDeclaration().getStartLine(), o2.getDeclaration().getStartLine());
}
}
}
}
| 6,490 | 40.082278 | 153 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/linereader/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.ce.task.projectanalysis.source.linereader;
import javax.annotation.ParametersAreNonnullByDefault;
| 991 | 40.333333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/AbstractComputationSteps.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import com.google.common.collect.Iterables;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.ce.task.step.ComputationSteps;
import org.sonar.core.platform.Container;
/**
* Abstract implementation of {@link ComputationStep} which provides the implementation of {@link ComputationSteps#instances()}
* based on a {@link org.sonar.core.platform.Container}.
*/
public abstract class AbstractComputationSteps implements ComputationSteps {
private final Container container;
protected AbstractComputationSteps(Container container) {
this.container = container;
}
@Override
public Iterable<ComputationStep> instances() {
return Iterables.transform(orderedStepClasses(), container::getComponentByType);
}
}
| 1,631 | 36.953488 | 127 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/BuildComponentTreeStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.Optional;
import javax.annotation.Nullable;
import org.sonar.ce.task.projectanalysis.analysis.Analysis;
import org.sonar.ce.task.projectanalysis.analysis.MutableAnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.batch.BatchReportReader;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.ComponentKeyGenerator;
import org.sonar.ce.task.projectanalysis.component.ComponentTreeBuilder;
import org.sonar.ce.task.projectanalysis.component.ComponentUuidFactory;
import org.sonar.ce.task.projectanalysis.component.ComponentUuidFactoryImpl;
import org.sonar.ce.task.projectanalysis.component.MutableTreeRootHolder;
import org.sonar.ce.task.projectanalysis.component.ProjectAttributes;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.SnapshotDto;
import org.sonar.scanner.protocol.output.ScannerReport;
import static com.google.common.base.MoreObjects.firstNonNull;
import static org.apache.commons.lang.StringUtils.trimToNull;
/**
* Populates the {@link MutableTreeRootHolder} and {@link MutableAnalysisMetadataHolder} from the {@link BatchReportReader}
*/
public class BuildComponentTreeStep implements ComputationStep {
private static final String DEFAULT_PROJECT_VERSION = "not provided";
private final DbClient dbClient;
private final BatchReportReader reportReader;
private final MutableTreeRootHolder treeRootHolder;
private final MutableAnalysisMetadataHolder analysisMetadataHolder;
public BuildComponentTreeStep(DbClient dbClient, BatchReportReader reportReader, MutableTreeRootHolder treeRootHolder,
MutableAnalysisMetadataHolder analysisMetadataHolder) {
this.dbClient = dbClient;
this.reportReader = reportReader;
this.treeRootHolder = treeRootHolder;
this.analysisMetadataHolder = analysisMetadataHolder;
}
@Override
public String getDescription() {
return "Build tree of components";
}
@Override
public void execute(ComputationStep.Context context) {
try (DbSession dbSession = dbClient.openSession(false)) {
ScannerReport.Component reportProject = reportReader.readComponent(analysisMetadataHolder.getRootComponentRef());
ComponentKeyGenerator keyGenerator = loadKeyGenerator();
ScannerReport.Metadata metadata = reportReader.readMetadata();
// root key of branch, not necessarily of project
String rootKey = keyGenerator.generateKey(reportProject.getKey(), null);
// loads the UUIDs from database. If they don't exist, then generate new ones
ComponentUuidFactory componentUuidFactory = new ComponentUuidFactoryImpl(dbClient, dbSession, rootKey, analysisMetadataHolder.getBranch());
String rootUuid = componentUuidFactory.getOrCreateForKey(rootKey);
Optional<SnapshotDto> baseAnalysis = dbClient.snapshotDao().selectLastAnalysisByRootComponentUuid(dbSession, rootUuid);
ComponentTreeBuilder builder = new ComponentTreeBuilder(keyGenerator,
componentUuidFactory::getOrCreateForKey,
reportReader::readComponent,
analysisMetadataHolder.getProject(),
analysisMetadataHolder.getBranch(),
createProjectAttributes(metadata, baseAnalysis.orElse(null)));
String relativePathFromScmRoot = metadata.getRelativePathFromScmRoot();
Component reportTreeRoot = builder.buildProject(reportProject, relativePathFromScmRoot);
if (analysisMetadataHolder.isPullRequest()) {
Component changedComponentTreeRoot = builder.buildChangedComponentTreeRoot(reportTreeRoot);
treeRootHolder.setRoots(changedComponentTreeRoot, reportTreeRoot);
} else {
treeRootHolder.setRoots(reportTreeRoot, reportTreeRoot);
}
analysisMetadataHolder.setBaseAnalysis(baseAnalysis.map(BuildComponentTreeStep::toAnalysis).orElse(null));
context.getStatistics().add("components", treeRootHolder.getSize());
}
}
private static ProjectAttributes createProjectAttributes(ScannerReport.Metadata metadata, @Nullable SnapshotDto baseAnalysis) {
String projectVersion = computeProjectVersion(trimToNull(metadata.getProjectVersion()), baseAnalysis);
String buildString = trimToNull(metadata.getBuildString());
String scmRevisionId = trimToNull(metadata.getScmRevisionId());
return new ProjectAttributes(projectVersion, buildString, scmRevisionId);
}
private static String computeProjectVersion(@Nullable String projectVersion, @Nullable SnapshotDto baseAnalysis) {
if (projectVersion != null) {
return projectVersion;
}
if (baseAnalysis != null) {
return firstNonNull(baseAnalysis.getProjectVersion(), DEFAULT_PROJECT_VERSION);
}
return DEFAULT_PROJECT_VERSION;
}
private ComponentKeyGenerator loadKeyGenerator() {
return analysisMetadataHolder.getBranch();
}
private static Analysis toAnalysis(SnapshotDto dto) {
return new Analysis.Builder()
.setUuid(dto.getUuid())
.setCreatedAt(dto.getCreatedAt())
.build();
}
}
| 5,975 | 43.266667 | 145 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/CleanIssueChangesStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.Set;
import org.sonar.ce.task.projectanalysis.issue.IssueChangesToDeleteRepository;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
public class CleanIssueChangesStep implements ComputationStep {
private final IssueChangesToDeleteRepository issueChangesToDeleteRepository;
private final DbClient dbClient;
public CleanIssueChangesStep(IssueChangesToDeleteRepository issueChangesToDeleteRepository, DbClient dbClient) {
this.issueChangesToDeleteRepository = issueChangesToDeleteRepository;
this.dbClient = dbClient;
}
@Override
public void execute(Context context) {
Set<String> uuids = issueChangesToDeleteRepository.getUuids();
context.getStatistics().add("changes", uuids.size());
if (uuids.isEmpty()) {
return;
}
try (DbSession dbSession = dbClient.openSession(false)) {
dbClient.issueChangeDao().deleteByUuids(dbSession, issueChangesToDeleteRepository.getUuids());
dbSession.commit();
}
}
@Override
public String getDescription() {
return "Delete issue changes";
}
}
| 2,021 | 33.862069 | 114 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/CommentMeasuresStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.List;
import java.util.Optional;
import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit;
import org.sonar.ce.task.projectanalysis.component.PathAwareCrawler;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.projectanalysis.formula.Counter;
import org.sonar.ce.task.projectanalysis.formula.CounterInitializationContext;
import org.sonar.ce.task.projectanalysis.formula.CreateMeasureContext;
import org.sonar.ce.task.projectanalysis.formula.Formula;
import org.sonar.ce.task.projectanalysis.formula.FormulaExecutorComponentVisitor;
import org.sonar.ce.task.projectanalysis.formula.counter.IntSumCounter;
import org.sonar.ce.task.projectanalysis.formula.counter.SumCounter;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import org.sonar.ce.task.projectanalysis.measure.MeasureRepository;
import org.sonar.ce.task.projectanalysis.metric.Metric;
import org.sonar.ce.task.projectanalysis.metric.MetricRepository;
import org.sonar.ce.task.step.ComputationStep;
import static org.sonar.api.measures.CoreMetrics.COMMENT_LINES_DENSITY_KEY;
import static org.sonar.api.measures.CoreMetrics.COMMENT_LINES_KEY;
import static org.sonar.api.measures.CoreMetrics.NCLOC_KEY;
import static org.sonar.api.measures.CoreMetrics.PUBLIC_API_KEY;
import static org.sonar.api.measures.CoreMetrics.PUBLIC_DOCUMENTED_API_DENSITY_KEY;
import static org.sonar.api.measures.CoreMetrics.PUBLIC_UNDOCUMENTED_API_KEY;
/**
* Computes comments measures on files and then aggregates them on higher components.
*/
public class CommentMeasuresStep implements ComputationStep {
private final TreeRootHolder treeRootHolder;
private final MetricRepository metricRepository;
private final MeasureRepository measureRepository;
private final List<Formula<?>> formulas;
public CommentMeasuresStep(TreeRootHolder treeRootHolder, MetricRepository metricRepository, MeasureRepository measureRepository) {
this.treeRootHolder = treeRootHolder;
this.metricRepository = metricRepository;
this.measureRepository = measureRepository;
this.formulas = List.of(
new DocumentationFormula(),
new CommentDensityFormula()
);
}
@Override
public void execute(ComputationStep.Context context) {
new PathAwareCrawler<>(
FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository).buildFor(formulas))
.visit(treeRootHolder.getRoot());
}
private class CommentDensityFormula implements Formula<IntSumCounter> {
private final Metric nclocMetric;
public CommentDensityFormula() {
this.nclocMetric = metricRepository.getByKey(NCLOC_KEY);
}
@Override
public IntSumCounter createNewCounter() {
return new IntSumCounter(COMMENT_LINES_KEY);
}
@Override
public Optional<Measure> createMeasure(IntSumCounter counter, CreateMeasureContext context) {
Optional<Measure> measure = createCommentLinesMeasure(counter, context);
return measure.isPresent() ? measure : createCommentLinesDensityMeasure(counter, context);
}
private Optional<Measure> createCommentLinesMeasure(SumCounter counter, CreateMeasureContext context) {
Optional<Integer> commentLines = counter.getValue();
if (COMMENT_LINES_KEY.equals(context.getMetric().getKey())
&& commentLines.isPresent()
&& CrawlerDepthLimit.LEAVES.isDeeperThan(context.getComponent().getType())) {
return Optional.of(Measure.newMeasureBuilder().create(commentLines.get()));
}
return Optional.empty();
}
private Optional<Measure> createCommentLinesDensityMeasure(SumCounter counter, CreateMeasureContext context) {
if (COMMENT_LINES_DENSITY_KEY.equals(context.getMetric().getKey())) {
Optional<Measure> nclocsOpt = measureRepository.getRawMeasure(context.getComponent(), nclocMetric);
Optional<Integer> commentsOpt = counter.getValue();
if (nclocsOpt.isPresent() && commentsOpt.isPresent()) {
double nclocs = nclocsOpt.get().getIntValue();
double comments = commentsOpt.get();
double divisor = nclocs + comments;
if (divisor > 0D) {
double value = 100D * (comments / divisor);
return Optional.of(Measure.newMeasureBuilder().create(value, context.getMetric().getDecimalScale()));
}
}
}
return Optional.empty();
}
@Override
public String[] getOutputMetricKeys() {
return new String[] {COMMENT_LINES_KEY, COMMENT_LINES_DENSITY_KEY};
}
}
private static class DocumentationFormula implements Formula<DocumentationCounter> {
@Override
public DocumentationCounter createNewCounter() {
return new DocumentationCounter();
}
@Override
public Optional<Measure> createMeasure(DocumentationCounter counter, CreateMeasureContext context) {
Optional<Measure> measure = getMeasure(context, counter.getPublicApiValue(), PUBLIC_API_KEY);
if (measure.isPresent()) {
return measure;
}
measure = getMeasure(context, counter.getPublicUndocumentedApiValue(), PUBLIC_UNDOCUMENTED_API_KEY);
return measure.isPresent() ? measure : getDensityMeasure(counter, context);
}
private static Optional<Measure> getMeasure(CreateMeasureContext context, Optional<Integer> metricValue, String metricKey) {
if (context.getMetric().getKey().equals(metricKey) && metricValue.isPresent()
&& CrawlerDepthLimit.LEAVES.isDeeperThan(context.getComponent().getType())) {
return Optional.of(Measure.newMeasureBuilder().create(metricValue.get()));
}
return Optional.empty();
}
private static Optional<Measure> getDensityMeasure(DocumentationCounter counter, CreateMeasureContext context) {
if (context.getMetric().getKey().equals(PUBLIC_DOCUMENTED_API_DENSITY_KEY) && counter.getPublicApiValue().isPresent()
&& counter.getPublicUndocumentedApiValue().isPresent()) {
double publicApis = counter.getPublicApiValue().get();
double publicUndocumentedApis = counter.getPublicUndocumentedApiValue().get();
if (publicApis > 0D) {
double documentedAPI = publicApis - publicUndocumentedApis;
double value = 100D * (documentedAPI / publicApis);
return Optional.of(Measure.newMeasureBuilder().create(value, context.getMetric().getDecimalScale()));
}
}
return Optional.empty();
}
@Override
public String[] getOutputMetricKeys() {
return new String[] {PUBLIC_API_KEY, PUBLIC_UNDOCUMENTED_API_KEY, PUBLIC_DOCUMENTED_API_DENSITY_KEY};
}
}
private static class DocumentationCounter implements Counter<DocumentationCounter> {
private final SumCounter publicApiCounter;
private final SumCounter publicUndocumentedApiCounter;
public DocumentationCounter() {
this.publicApiCounter = new IntSumCounter(PUBLIC_API_KEY);
this.publicUndocumentedApiCounter = new IntSumCounter(PUBLIC_UNDOCUMENTED_API_KEY);
}
@Override
public void aggregate(DocumentationCounter counter) {
publicApiCounter.aggregate(counter.publicApiCounter);
publicUndocumentedApiCounter.aggregate(counter.publicUndocumentedApiCounter);
}
@Override
public void initialize(CounterInitializationContext context) {
publicApiCounter.initialize(context);
publicUndocumentedApiCounter.initialize(context);
}
public Optional<Integer> getPublicApiValue() {
return publicApiCounter.getValue();
}
public Optional<Integer> getPublicUndocumentedApiValue() {
return publicUndocumentedApiCounter.getValue();
}
}
@Override
public String getDescription() {
return "Compute comment measures";
}
}
| 8,646 | 40.772947 | 133 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/ComplexityMeasuresStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.List;
import org.sonar.ce.task.projectanalysis.component.PathAwareCrawler;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.projectanalysis.formula.AverageFormula;
import org.sonar.ce.task.projectanalysis.formula.DistributionFormula;
import org.sonar.ce.task.projectanalysis.formula.Formula;
import org.sonar.ce.task.projectanalysis.formula.FormulaExecutorComponentVisitor;
import org.sonar.ce.task.projectanalysis.measure.MeasureRepository;
import org.sonar.ce.task.projectanalysis.metric.MetricRepository;
import org.sonar.ce.task.step.ComputationStep;
import static org.sonar.api.measures.CoreMetrics.CLASSES_KEY;
import static org.sonar.api.measures.CoreMetrics.CLASS_COMPLEXITY_KEY;
import static org.sonar.api.measures.CoreMetrics.COGNITIVE_COMPLEXITY_KEY;
import static org.sonar.api.measures.CoreMetrics.COMPLEXITY_IN_CLASSES_KEY;
import static org.sonar.api.measures.CoreMetrics.COMPLEXITY_IN_FUNCTIONS_KEY;
import static org.sonar.api.measures.CoreMetrics.COMPLEXITY_KEY;
import static org.sonar.api.measures.CoreMetrics.FILES_KEY;
import static org.sonar.api.measures.CoreMetrics.FILE_COMPLEXITY_DISTRIBUTION_KEY;
import static org.sonar.api.measures.CoreMetrics.FILE_COMPLEXITY_KEY;
import static org.sonar.api.measures.CoreMetrics.FUNCTIONS_KEY;
import static org.sonar.api.measures.CoreMetrics.FUNCTION_COMPLEXITY_DISTRIBUTION_KEY;
import static org.sonar.api.measures.CoreMetrics.FUNCTION_COMPLEXITY_KEY;
import static org.sonar.ce.task.projectanalysis.formula.SumFormula.createIntSumFormula;
/**
* Computes complexity measures on files and then aggregates them on higher components.
*/
public class ComplexityMeasuresStep implements ComputationStep {
private static final List<Formula<?>> FORMULAS = List.of(
createIntSumFormula(COMPLEXITY_KEY),
createIntSumFormula(COMPLEXITY_IN_CLASSES_KEY),
createIntSumFormula(COMPLEXITY_IN_FUNCTIONS_KEY),
createIntSumFormula(COGNITIVE_COMPLEXITY_KEY),
new DistributionFormula(FUNCTION_COMPLEXITY_DISTRIBUTION_KEY),
new DistributionFormula(FILE_COMPLEXITY_DISTRIBUTION_KEY),
AverageFormula.Builder.newBuilder().setOutputMetricKey(FILE_COMPLEXITY_KEY)
.setMainMetricKey(COMPLEXITY_KEY)
.setByMetricKey(FILES_KEY)
.build(),
AverageFormula.Builder.newBuilder().setOutputMetricKey(CLASS_COMPLEXITY_KEY)
.setMainMetricKey(COMPLEXITY_IN_CLASSES_KEY)
.setByMetricKey(CLASSES_KEY)
.build(),
AverageFormula.Builder.newBuilder().setOutputMetricKey(FUNCTION_COMPLEXITY_KEY)
.setMainMetricKey(COMPLEXITY_IN_FUNCTIONS_KEY)
.setByMetricKey(FUNCTIONS_KEY)
.build()
);
private final TreeRootHolder treeRootHolder;
private final MetricRepository metricRepository;
private final MeasureRepository measureRepository;
public ComplexityMeasuresStep(TreeRootHolder treeRootHolder, MetricRepository metricRepository, MeasureRepository measureRepository) {
this.treeRootHolder = treeRootHolder;
this.metricRepository = metricRepository;
this.measureRepository = measureRepository;
}
@Override
public void execute(ComputationStep.Context context) {
new PathAwareCrawler<>(
FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository).buildFor(FORMULAS))
.visit(treeRootHolder.getRoot());
}
@Override
public String getDescription() {
return "Compute complexity measures";
}
}
| 4,331 | 45.085106 | 136 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/ComputeQProfileMeasureStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.HashMap;
import java.util.Map;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit;
import org.sonar.ce.task.projectanalysis.component.PathAwareCrawler;
import org.sonar.ce.task.projectanalysis.component.PathAwareVisitorAdapter;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import org.sonar.ce.task.projectanalysis.measure.MeasureRepository;
import org.sonar.ce.task.projectanalysis.metric.Metric;
import org.sonar.ce.task.projectanalysis.metric.MetricRepository;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.server.qualityprofile.QPMeasureData;
import org.sonar.server.qualityprofile.QualityProfile;
import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.POST_ORDER;
/**
* Compute quality profile measure per module based on present languages
*/
public class ComputeQProfileMeasureStep implements ComputationStep {
private final TreeRootHolder treeRootHolder;
private final MeasureRepository measureRepository;
private final MetricRepository metricRepository;
private final AnalysisMetadataHolder analysisMetadataHolder;
public ComputeQProfileMeasureStep(TreeRootHolder treeRootHolder, MeasureRepository measureRepository, MetricRepository metricRepository,
AnalysisMetadataHolder analysisMetadataHolder) {
this.treeRootHolder = treeRootHolder;
this.measureRepository = measureRepository;
this.metricRepository = metricRepository;
this.analysisMetadataHolder = analysisMetadataHolder;
}
@Override
public void execute(ComputationStep.Context context) {
Metric qProfilesMetric = metricRepository.getByKey(CoreMetrics.QUALITY_PROFILES_KEY);
new PathAwareCrawler<>(new QProfileAggregationComponentVisitor(qProfilesMetric))
.visit(treeRootHolder.getRoot());
}
private class QProfileAggregationComponentVisitor extends PathAwareVisitorAdapter<QProfiles> {
private final Metric qProfilesMetric;
public QProfileAggregationComponentVisitor(Metric qProfilesMetric) {
super(CrawlerDepthLimit.FILE, POST_ORDER, new SimpleStackElementFactory<QProfiles>() {
@Override
public QProfiles createForAny(Component component) {
return new QProfiles();
}
});
this.qProfilesMetric = qProfilesMetric;
}
@Override
public void visitFile(Component file, Path<QProfiles> path) {
String languageKey = file.getFileAttributes().getLanguageKey();
if (languageKey == null) {
// No qprofile for unknown languages
return;
}
if (!analysisMetadataHolder.getQProfilesByLanguage().containsKey(languageKey)) {
throw new IllegalStateException("Report contains a file with language '" + languageKey + "' but no matching quality profile");
}
path.parent().add(analysisMetadataHolder.getQProfilesByLanguage().get(languageKey));
}
@Override
public void visitDirectory(Component directory, Path<QProfiles> path) {
QProfiles qProfiles = path.current();
path.parent().add(qProfiles);
}
@Override
public void visitProject(Component project, Path<QProfiles> path) {
addMeasure(project, path.current());
}
private void addMeasure(Component component, QProfiles qProfiles) {
if (!qProfiles.profilesByKey.isEmpty()) {
measureRepository.add(component, qProfilesMetric, qProfiles.createMeasure());
}
}
}
private static class QProfiles {
private final Map<String, QualityProfile> profilesByKey = new HashMap<>();
public void add(QProfiles qProfiles) {
profilesByKey.putAll(qProfiles.profilesByKey);
}
public void add(QualityProfile qProfile) {
profilesByKey.put(qProfile.getQpKey(), qProfile);
}
public Measure createMeasure() {
return Measure.newMeasureBuilder().create(QPMeasureData.toJson(new QPMeasureData(profilesByKey.values())));
}
}
@Override
public String getDescription() {
return "Compute Quality profile measures";
}
}
| 5,148 | 38.007576 | 138 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/CoverageMeasuresStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.List;
import javax.annotation.Nullable;
import javax.inject.Inject;
import org.sonar.ce.task.projectanalysis.batch.BatchReportReader;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit;
import org.sonar.ce.task.projectanalysis.component.DepthTraversalTypeAwareCrawler;
import org.sonar.ce.task.projectanalysis.component.PathAwareCrawler;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.projectanalysis.component.TypeAwareVisitorAdapter;
import org.sonar.ce.task.projectanalysis.formula.Formula;
import org.sonar.ce.task.projectanalysis.formula.FormulaExecutorComponentVisitor;
import org.sonar.ce.task.projectanalysis.formula.coverage.LinesAndConditionsWithUncoveredFormula;
import org.sonar.ce.task.projectanalysis.formula.coverage.LinesAndConditionsWithUncoveredMetricKeys;
import org.sonar.ce.task.projectanalysis.formula.coverage.SingleWithUncoveredFormula;
import org.sonar.ce.task.projectanalysis.formula.coverage.SingleWithUncoveredMetricKeys;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import org.sonar.ce.task.projectanalysis.measure.MeasureRepository;
import org.sonar.ce.task.projectanalysis.metric.Metric;
import org.sonar.ce.task.projectanalysis.metric.MetricRepository;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.core.util.CloseableIterator;
import org.sonar.scanner.protocol.output.ScannerReport;
import static java.lang.Math.min;
import static org.sonar.api.measures.CoreMetrics.BRANCH_COVERAGE_KEY;
import static org.sonar.api.measures.CoreMetrics.CONDITIONS_TO_COVER_KEY;
import static org.sonar.api.measures.CoreMetrics.COVERAGE_KEY;
import static org.sonar.api.measures.CoreMetrics.LINES_TO_COVER_KEY;
import static org.sonar.api.measures.CoreMetrics.LINE_COVERAGE_KEY;
import static org.sonar.api.measures.CoreMetrics.UNCOVERED_CONDITIONS_KEY;
import static org.sonar.api.measures.CoreMetrics.UNCOVERED_LINES_KEY;
import static org.sonar.ce.task.projectanalysis.formula.SumFormula.createIntSumFormula;
/**
* Computes coverage measures on files and then aggregates them on higher components.
*/
public class CoverageMeasuresStep implements ComputationStep {
private static final List<Formula<?>> COVERAGE_FORMULAS = List.of(
createIntSumFormula(LINES_TO_COVER_KEY),
createIntSumFormula(UNCOVERED_LINES_KEY),
createIntSumFormula(CONDITIONS_TO_COVER_KEY),
createIntSumFormula(UNCOVERED_CONDITIONS_KEY),
new CodeCoverageFormula(),
new BranchCoverageFormula(),
new LineCoverageFormula()
);
private final TreeRootHolder treeRootHolder;
private final MetricRepository metricRepository;
private final MeasureRepository measureRepository;
private final BatchReportReader reportReader;
private final Metric linesToCoverMetric;
private final Metric uncoveredLinesMetric;
private final Metric conditionsToCoverMetric;
private final Metric uncoveredConditionsMetric;
/**
* Constructor used when processing a Report (ie. a {@link BatchReportReader} instance is available in the container)
*/
@Inject
public CoverageMeasuresStep(TreeRootHolder treeRootHolder, MetricRepository metricRepository, MeasureRepository measureRepository, @Nullable BatchReportReader reportReader) {
this.treeRootHolder = treeRootHolder;
this.metricRepository = metricRepository;
this.measureRepository = measureRepository;
this.reportReader = reportReader;
this.linesToCoverMetric = metricRepository.getByKey(LINES_TO_COVER_KEY);
this.uncoveredLinesMetric = metricRepository.getByKey(UNCOVERED_LINES_KEY);
this.conditionsToCoverMetric = metricRepository.getByKey(CONDITIONS_TO_COVER_KEY);
this.uncoveredConditionsMetric = metricRepository.getByKey(UNCOVERED_CONDITIONS_KEY);
}
@Override
public void execute(ComputationStep.Context context) {
if (reportReader != null) {
new DepthTraversalTypeAwareCrawler(new FileCoverageVisitor(reportReader)).visit(treeRootHolder.getReportTreeRoot());
}
new PathAwareCrawler<>(
FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository).buildFor(COVERAGE_FORMULAS))
.visit(treeRootHolder.getReportTreeRoot());
}
private class FileCoverageVisitor extends TypeAwareVisitorAdapter {
private final BatchReportReader reportReader;
private FileCoverageVisitor(BatchReportReader reportReader) {
super(CrawlerDepthLimit.FILE, Order.POST_ORDER);
this.reportReader = reportReader;
}
@Override
public void visitFile(Component file) {
if (file.getFileAttributes().isUnitTest()) {
return;
}
try (CloseableIterator<ScannerReport.LineCoverage> lineCoverage = reportReader.readComponentCoverage(file.getReportAttributes().getRef())) {
int linesToCover = 0;
int coveredLines = 0;
int conditionsToCover = 0;
int coveredConditions = 0;
while (lineCoverage.hasNext()) {
final ScannerReport.LineCoverage line = lineCoverage.next();
if (line.getHasHitsCase() == ScannerReport.LineCoverage.HasHitsCase.HITS) {
linesToCover++;
if (line.getHits()) {
coveredLines++;
}
}
if (line.getHasCoveredConditionsCase() == ScannerReport.LineCoverage.HasCoveredConditionsCase.COVERED_CONDITIONS) {
conditionsToCover += line.getConditions();
coveredConditions += min(line.getCoveredConditions(), line.getConditions());
}
}
if (linesToCover > 0) {
measureRepository.add(file, linesToCoverMetric, Measure.newMeasureBuilder().create(linesToCover));
measureRepository.add(file, uncoveredLinesMetric, Measure.newMeasureBuilder().create(linesToCover - coveredLines));
}
if (conditionsToCover > 0) {
measureRepository.add(file, conditionsToCoverMetric, Measure.newMeasureBuilder().create(conditionsToCover));
measureRepository.add(file, uncoveredConditionsMetric, Measure.newMeasureBuilder().create(conditionsToCover - coveredConditions));
}
}
}
}
private static class CodeCoverageFormula extends LinesAndConditionsWithUncoveredFormula {
public CodeCoverageFormula() {
super(
new LinesAndConditionsWithUncoveredMetricKeys(
LINES_TO_COVER_KEY, CONDITIONS_TO_COVER_KEY,
UNCOVERED_LINES_KEY, UNCOVERED_CONDITIONS_KEY),
COVERAGE_KEY);
}
}
private static class BranchCoverageFormula extends SingleWithUncoveredFormula {
public BranchCoverageFormula() {
super(
new SingleWithUncoveredMetricKeys(
CONDITIONS_TO_COVER_KEY, UNCOVERED_CONDITIONS_KEY),
BRANCH_COVERAGE_KEY);
}
}
private static class LineCoverageFormula extends SingleWithUncoveredFormula {
public LineCoverageFormula() {
super(
new SingleWithUncoveredMetricKeys(LINES_TO_COVER_KEY, UNCOVERED_LINES_KEY),
LINE_COVERAGE_KEY);
}
}
@Override
public String getDescription() {
return "Compute coverage measures";
}
}
| 8,033 | 43.633333 | 176 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/DuplicationMeasuresStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.ce.task.projectanalysis.duplication.DuplicationMeasures;
import org.sonar.ce.task.step.ComputationStep;
/**
* Computes duplication measures on files and then aggregates them on higher components.
*
* This step must be executed after {@link CommentMeasuresStep} as it depends on {@link CoreMetrics#COMMENT_LINES}
*/
public class DuplicationMeasuresStep implements ComputationStep {
private final DuplicationMeasures defaultDuplicationMeasures;
public DuplicationMeasuresStep(DuplicationMeasures defaultDuplicationMeasures) {
this.defaultDuplicationMeasures = defaultDuplicationMeasures;
}
@Override
public String getDescription() {
return "Compute duplication measures";
}
@Override
public void execute(ComputationStep.Context context) {
defaultDuplicationMeasures.execute();
}
}
| 1,770 | 35.895833 | 114 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/EnableAnalysisStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
public class EnableAnalysisStep implements ComputationStep {
private final DbClient dbClient;
private final TreeRootHolder treeRootHolder;
private final AnalysisMetadataHolder analysisMetadataHolder;
public EnableAnalysisStep(DbClient dbClient, TreeRootHolder treeRootHolder, AnalysisMetadataHolder analysisMetadataHolder) {
this.dbClient = dbClient;
this.treeRootHolder = treeRootHolder;
this.analysisMetadataHolder = analysisMetadataHolder;
}
@Override
public void execute(ComputationStep.Context context) {
try (DbSession dbSession = dbClient.openSession(false)) {
Component project = treeRootHolder.getRoot();
dbClient.snapshotDao().switchIsLastFlagAndSetProcessedStatus(dbSession, project.getUuid(), analysisMetadataHolder.getUuid());
dbClient.componentDao().applyBChangesForBranchUuid(dbSession, project.getUuid());
dbSession.commit();
}
}
@Override
public String getDescription() {
return "Enable analysis";
}
}
| 2,198 | 37.578947 | 131 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/ExecuteVisitorsStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.ce.task.projectanalysis.component.ComponentVisitor;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.projectanalysis.component.VisitorsCrawler;
import org.sonar.ce.task.step.ComputationStep;
public class ExecuteVisitorsStep implements ComputationStep {
private static final Logger LOGGER = LoggerFactory.getLogger(ExecuteVisitorsStep.class);
private final TreeRootHolder treeRootHolder;
private final List<ComponentVisitor> visitors;
public ExecuteVisitorsStep(TreeRootHolder treeRootHolder, List<ComponentVisitor> visitors) {
this.treeRootHolder = treeRootHolder;
this.visitors = visitors;
}
@Override
public String getDescription() {
return "Execute component visitors";
}
@Override
public void execute(ComputationStep.Context context) {
VisitorsCrawler visitorsCrawler = new VisitorsCrawler(visitors, LOGGER.isDebugEnabled());
visitorsCrawler.visit(treeRootHolder.getRoot());
logVisitorExecutionDurations(visitors, visitorsCrawler);
}
private static void logVisitorExecutionDurations(List<ComponentVisitor> visitors, VisitorsCrawler visitorsCrawler) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(" Execution time for each component visitor:");
Map<ComponentVisitor, Long> cumulativeDurations = visitorsCrawler.getCumulativeDurations();
for (ComponentVisitor visitor : visitors) {
LOGGER.debug(" - {} | time={}ms", visitor.getClass().getSimpleName(), cumulativeDurations.get(visitor));
}
}
}
}
| 2,549 | 38.230769 | 118 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/ExtractReportStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;
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.ce.task.CeTask;
import org.sonar.ce.task.projectanalysis.batch.MutableBatchReportDirectoryHolder;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.db.DbInputStream;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.process.FileUtils2;
import static org.sonar.core.util.FileUtils.humanReadableByteCountSI;
/**
* Extracts the content zip file of the {@link CeTask} to a temp directory and adds a {@link File}
* representing that temp directory to the {@link MutableBatchReportDirectoryHolder}.
*/
public class ExtractReportStep implements ComputationStep {
static final long REPORT_SIZE_THRESHOLD_IN_BYTES = 4_000_000_000L;
private static final Logger LOGGER = LoggerFactory.getLogger(ExtractReportStep.class);
private final DbClient dbClient;
private final CeTask task;
private final TempFolder tempFolder;
private final MutableBatchReportDirectoryHolder reportDirectoryHolder;
public ExtractReportStep(DbClient dbClient, CeTask task, TempFolder tempFolder,
MutableBatchReportDirectoryHolder reportDirectoryHolder) {
this.dbClient = dbClient;
this.task = task;
this.tempFolder = tempFolder;
this.reportDirectoryHolder = reportDirectoryHolder;
}
@Override
public void execute(ComputationStep.Context context) {
try (DbSession dbSession = dbClient.openSession(false)) {
Optional<DbInputStream> opt = dbClient.ceTaskInputDao().selectData(dbSession, task.getUuid());
if (opt.isPresent()) {
File unzippedDir = tempFolder.newDir();
try (DbInputStream reportStream = opt.get();
InputStream zipStream = new BufferedInputStream(reportStream)) {
ZipUtils.unzip(zipStream, unzippedDir, REPORT_SIZE_THRESHOLD_IN_BYTES);
} catch (IOException e) {
throw new IllegalStateException("Fail to extract report " + task.getUuid() + " from database", e);
}
reportDirectoryHolder.setDirectory(unzippedDir);
if (LOGGER.isDebugEnabled()) {
// size is not added to context statistics because computation
// can take time. It's enabled only if log level is DEBUG.
try {
String dirSize = humanReadableByteCountSI(FileUtils2.sizeOf(unzippedDir.toPath()));
LOGGER.debug("Analysis report is {} uncompressed", dirSize);
} catch (IOException e) {
LOGGER.warn("Fail to compute size of directory " + unzippedDir, e);
}
}
} else {
throw MessageException.of("Analysis report " + task.getUuid() + " is missing in database");
}
}
}
@Override
public String getDescription() {
return "Extract report";
}
}
| 3,913 | 38.14 | 108 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/GenerateAnalysisUuid.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import org.sonar.ce.task.projectanalysis.analysis.MutableAnalysisMetadataHolder;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.core.util.UuidFactory;
public class GenerateAnalysisUuid implements ComputationStep {
private final UuidFactory uuidFactory;
private final MutableAnalysisMetadataHolder analysisMetadataHolder;
public GenerateAnalysisUuid(UuidFactory uuidFactory, MutableAnalysisMetadataHolder analysisMetadataHolder) {
this.uuidFactory = uuidFactory;
this.analysisMetadataHolder = analysisMetadataHolder;
}
@Override
public void execute(ComputationStep.Context context) {
analysisMetadataHolder.setUuid(uuidFactory.create());
}
@Override
public String getDescription() {
return "Generate analysis UUID";
}
}
| 1,669 | 35.304348 | 110 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/IndexAnalysisStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.Set;
import java.util.function.Consumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.ce.task.projectanalysis.component.FileStatuses;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.server.es.AnalysisIndexer;
public class IndexAnalysisStep implements ComputationStep {
private static final Logger LOGGER = LoggerFactory.getLogger(IndexAnalysisStep.class);
private final TreeRootHolder treeRootHolder;
private final FileStatuses fileStatuses;
private final AnalysisIndexer[] indexers;
private final DbClient dbClient;
public IndexAnalysisStep(TreeRootHolder treeRootHolder, FileStatuses fileStatuses, DbClient dbClient, AnalysisIndexer... indexers) {
this.treeRootHolder = treeRootHolder;
this.fileStatuses = fileStatuses;
this.indexers = indexers;
this.dbClient = dbClient;
}
@Override
public void execute(ComputationStep.Context context) {
String branchUuid = treeRootHolder.getRoot().getUuid();
Consumer<AnalysisIndexer> analysisIndexerConsumer = getAnalysisIndexerConsumer(branchUuid);
for (AnalysisIndexer indexer : indexers) {
LOGGER.debug("Call {}", indexer);
analysisIndexerConsumer.accept(indexer);
}
}
private Consumer<AnalysisIndexer> getAnalysisIndexerConsumer(String branchUuid) {
Set<String> fileUuidsMarkedAsUnchanged = fileStatuses.getFileUuidsMarkedAsUnchanged();
return isBranchNeedIssueSync(branchUuid)
? (indexer -> indexer.indexOnAnalysis(branchUuid))
: (indexer -> indexer.indexOnAnalysis(branchUuid, fileUuidsMarkedAsUnchanged));
}
private boolean isBranchNeedIssueSync(String branchUuid) {
try (DbSession dbSession = dbClient.openSession(false)) {
return dbClient.branchDao().isBranchNeedIssueSync(dbSession, branchUuid);
}
}
@Override
public String getDescription() {
return "Index analysis";
}
}
| 2,927 | 37.025974 | 134 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/LanguageDistributionMeasuresStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import com.google.common.base.Function;
import com.google.common.collect.Multiset;
import com.google.common.collect.TreeMultiset;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.utils.KeyValueFormat;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.PathAwareCrawler;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.projectanalysis.formula.Counter;
import org.sonar.ce.task.projectanalysis.formula.CounterInitializationContext;
import org.sonar.ce.task.projectanalysis.formula.CreateMeasureContext;
import org.sonar.ce.task.projectanalysis.formula.Formula;
import org.sonar.ce.task.projectanalysis.formula.FormulaExecutorComponentVisitor;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import org.sonar.ce.task.projectanalysis.measure.MeasureRepository;
import org.sonar.ce.task.projectanalysis.metric.MetricRepository;
import org.sonar.ce.task.step.ComputationStep;
import static com.google.common.collect.Maps.asMap;
import static org.sonar.api.measures.CoreMetrics.NCLOC_LANGUAGE_DISTRIBUTION_KEY;
import static org.sonar.api.utils.KeyValueFormat.format;
import static org.sonar.api.utils.KeyValueFormat.newIntegerConverter;
import static org.sonar.api.utils.KeyValueFormat.newStringConverter;
import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilder;
public class LanguageDistributionMeasuresStep implements ComputationStep {
private static final String UNKNOWN_LANGUAGE_KEY = "<null>";
private static final List<Formula<?>> FORMULAS = List.of(new LanguageDistributionFormula());
private static final String[] LANGUAGE_DISTRIBUTION_FORMULA_METRICS = new String[] {NCLOC_LANGUAGE_DISTRIBUTION_KEY};
private final TreeRootHolder treeRootHolder;
private final MetricRepository metricRepository;
private final MeasureRepository measureRepository;
public LanguageDistributionMeasuresStep(TreeRootHolder treeRootHolder, MetricRepository metricRepository, MeasureRepository measureRepository) {
this.treeRootHolder = treeRootHolder;
this.metricRepository = metricRepository;
this.measureRepository = measureRepository;
}
@Override
public void execute(ComputationStep.Context context) {
new PathAwareCrawler<>(FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository).buildFor(FORMULAS))
.visit(treeRootHolder.getRoot());
}
private static class LanguageDistributionFormula implements Formula<LanguageDistributionCounter> {
@Override
public LanguageDistributionCounter createNewCounter() {
return new LanguageDistributionCounter();
}
@Override
public Optional<Measure> createMeasure(LanguageDistributionCounter counter, CreateMeasureContext context) {
if (counter.multiset.isEmpty()) {
return Optional.empty();
}
return Optional.of(newMeasureBuilder().create(format(asMap(counter.multiset.elementSet(), new LanguageToTotalCount(counter.multiset)))));
}
@Override
public String[] getOutputMetricKeys() {
return LANGUAGE_DISTRIBUTION_FORMULA_METRICS;
}
}
private static class LanguageToTotalCount implements Function<String, Integer> {
private final Multiset<String> multiset;
public LanguageToTotalCount(Multiset<String> multiset) {
this.multiset = multiset;
}
@Nullable
@Override
public Integer apply(@Nonnull String language) {
return multiset.count(language);
}
}
private static class LanguageDistributionCounter implements Counter<LanguageDistributionCounter> {
private final Multiset<String> multiset = TreeMultiset.create();
@Override
public void aggregate(LanguageDistributionCounter counter) {
multiset.addAll(counter.multiset);
}
@Override
public void initialize(CounterInitializationContext context) {
if (context.getLeaf().getType() == Component.Type.FILE) {
initializeForFile(context);
}
initializeForOtherLeaf(context);
}
private void initializeForFile(CounterInitializationContext context) {
String language = context.getLeaf().getFileAttributes().getLanguageKey();
Optional<Measure> ncloc = context.getMeasure(CoreMetrics.NCLOC_KEY);
if (ncloc.isPresent()) {
multiset.add(language == null ? UNKNOWN_LANGUAGE_KEY : language, ncloc.get().getIntValue());
}
}
private void initializeForOtherLeaf(CounterInitializationContext context) {
Optional<Measure> measure = context.getMeasure(NCLOC_LANGUAGE_DISTRIBUTION_KEY);
if (measure.isPresent()) {
Map<String, Integer> parse = KeyValueFormat.parse(measure.get().getData(), newStringConverter(), newIntegerConverter());
for (Map.Entry<String, Integer> entry : parse.entrySet()) {
multiset.add(entry.getKey(), entry.getValue());
}
}
}
}
@Override
public String getDescription() {
return "Compute language distribution";
}
}
| 6,047 | 38.789474 | 146 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/LoadCrossProjectDuplicationsRepositoryStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.Function;
import javax.annotation.Nonnull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.ce.task.projectanalysis.analysis.Analysis;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.batch.BatchReportReader;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit;
import org.sonar.ce.task.projectanalysis.component.DepthTraversalTypeAwareCrawler;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.projectanalysis.component.TypeAwareVisitorAdapter;
import org.sonar.ce.task.projectanalysis.duplication.CrossProjectDuplicationStatusHolder;
import org.sonar.ce.task.projectanalysis.duplication.IntegrateCrossProjectDuplications;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.core.util.CloseableIterator;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.duplication.DuplicationUnitDto;
import org.sonar.duplications.block.Block;
import org.sonar.duplications.block.ByteArray;
import org.sonar.scanner.protocol.output.ScannerReport.CpdTextBlock;
/**
* Feed the duplications repository from the cross project duplication blocks computed with duplications blocks of the analysis report.
* Blocks can be empty if :
* - The file is excluded from the analysis using {@link org.sonar.api.CoreProperties#CPD_EXCLUSIONS}
* - On Java, if the number of statements of the file is too small, nothing will be sent.
*/
public class LoadCrossProjectDuplicationsRepositoryStep implements ComputationStep {
private static final Logger LOGGER = LoggerFactory.getLogger(LoadCrossProjectDuplicationsRepositoryStep.class);
private final TreeRootHolder treeRootHolder;
private final BatchReportReader reportReader;
private final AnalysisMetadataHolder analysisMetadataHolder;
private final IntegrateCrossProjectDuplications integrateCrossProjectDuplications;
private final CrossProjectDuplicationStatusHolder crossProjectDuplicationStatusHolder;
private final DbClient dbClient;
public LoadCrossProjectDuplicationsRepositoryStep(TreeRootHolder treeRootHolder, BatchReportReader reportReader,
AnalysisMetadataHolder analysisMetadataHolder, CrossProjectDuplicationStatusHolder crossProjectDuplicationStatusHolder,
IntegrateCrossProjectDuplications integrateCrossProjectDuplications, DbClient dbClient) {
this.treeRootHolder = treeRootHolder;
this.reportReader = reportReader;
this.analysisMetadataHolder = analysisMetadataHolder;
this.integrateCrossProjectDuplications = integrateCrossProjectDuplications;
this.crossProjectDuplicationStatusHolder = crossProjectDuplicationStatusHolder;
this.dbClient = dbClient;
}
@Override
public void execute(ComputationStep.Context context) {
if (crossProjectDuplicationStatusHolder.isEnabled()) {
new DepthTraversalTypeAwareCrawler(new CrossProjectDuplicationVisitor()).visit(treeRootHolder.getRoot());
}
}
@Override
public String getDescription() {
return "Compute cross project duplications";
}
private class CrossProjectDuplicationVisitor extends TypeAwareVisitorAdapter {
private CrossProjectDuplicationVisitor() {
super(CrawlerDepthLimit.FILE, Order.PRE_ORDER);
}
@Override
public void visitFile(Component file) {
List<CpdTextBlock> cpdTextBlocks = new ArrayList<>();
try (CloseableIterator<CpdTextBlock> blocksIt = reportReader.readCpdTextBlocks(file.getReportAttributes().getRef())) {
while(blocksIt.hasNext()) {
cpdTextBlocks.add(blocksIt.next());
}
}
LOGGER.trace("Found {} cpd blocks on file {}", cpdTextBlocks.size(), file.getKey());
if (cpdTextBlocks.isEmpty()) {
return;
}
Collection<String> hashes = cpdTextBlocks.stream().map(CpdTextBlockToHash.INSTANCE).toList();
List<DuplicationUnitDto> dtos = selectDuplicates(file, hashes);
if (dtos.isEmpty()) {
return;
}
Collection<Block> duplicatedBlocks = dtos.stream().map(DtoToBlock.INSTANCE).toList();
Collection<Block> originBlocks = cpdTextBlocks.stream().map(new CpdTextBlockToBlock(file.getKey())).toList();
LOGGER.trace("Found {} duplicated cpd blocks on file {}", duplicatedBlocks.size(), file.getKey());
integrateCrossProjectDuplications.computeCpd(file, originBlocks, duplicatedBlocks);
}
private List<DuplicationUnitDto> selectDuplicates(Component file, Collection<String> hashes) {
try (DbSession dbSession = dbClient.openSession(false)) {
Analysis projectAnalysis = analysisMetadataHolder.getBaseAnalysis();
String analysisUuid = projectAnalysis == null ? null : projectAnalysis.getUuid();
return dbClient.duplicationDao().selectCandidates(dbSession, analysisUuid, file.getFileAttributes().getLanguageKey(), hashes);
}
}
}
private enum CpdTextBlockToHash implements Function<CpdTextBlock, String> {
INSTANCE;
@Override
public String apply(@Nonnull CpdTextBlock duplicationBlock) {
return duplicationBlock.getHash();
}
}
private enum DtoToBlock implements Function<DuplicationUnitDto, Block> {
INSTANCE;
@Override
public Block apply(@Nonnull DuplicationUnitDto dto) {
// Note that the dto doesn't contains start/end token indexes
return Block.builder()
.setResourceId(dto.getComponentKey())
.setBlockHash(new ByteArray(dto.getHash()))
.setIndexInFile(dto.getIndexInFile())
.setLines(dto.getStartLine(), dto.getEndLine())
.build();
}
}
private static class CpdTextBlockToBlock implements Function<CpdTextBlock, Block> {
private final String fileKey;
private int indexInFile = 0;
CpdTextBlockToBlock(String fileKey) {
this.fileKey = fileKey;
}
@Override
public Block apply(@Nonnull CpdTextBlock duplicationBlock) {
Block block = Block.builder()
.setResourceId(fileKey)
.setBlockHash(new ByteArray(duplicationBlock.getHash()))
.setIndexInFile(indexInFile)
.setLines(duplicationBlock.getStartLine(), duplicationBlock.getEndLine())
.setUnit(duplicationBlock.getStartTokenIndex(), duplicationBlock.getEndTokenIndex())
.build();
indexInFile++;
return block;
}
}
}
| 7,401 | 41.056818 | 135 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/LoadDuplicationsFromReportStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.function.Function;
import javax.annotation.Nonnull;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.batch.BatchReportReader;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit;
import org.sonar.ce.task.projectanalysis.component.DepthTraversalTypeAwareCrawler;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.projectanalysis.component.TypeAwareVisitorAdapter;
import org.sonar.ce.task.projectanalysis.duplication.DetailedTextBlock;
import org.sonar.ce.task.projectanalysis.duplication.Duplicate;
import org.sonar.ce.task.projectanalysis.duplication.Duplication;
import org.sonar.ce.task.projectanalysis.duplication.DuplicationRepository;
import org.sonar.ce.task.projectanalysis.duplication.InExtendedProjectDuplicate;
import org.sonar.ce.task.projectanalysis.duplication.InProjectDuplicate;
import org.sonar.ce.task.projectanalysis.duplication.InnerDuplicate;
import org.sonar.ce.task.projectanalysis.duplication.TextBlock;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.core.util.CloseableIterator;
import org.sonar.scanner.protocol.output.ScannerReport;
import static com.google.common.base.Preconditions.checkArgument;
/**
* Loads duplication information from the report and loads them into the {@link DuplicationRepository}.
*/
public class LoadDuplicationsFromReportStep implements ComputationStep {
private final TreeRootHolder treeRootHolder;
private final AnalysisMetadataHolder analysisMetadataHolder;
private final BatchReportReader batchReportReader;
private final DuplicationRepository duplicationRepository;
public LoadDuplicationsFromReportStep(TreeRootHolder treeRootHolder, AnalysisMetadataHolder analysisMetadataHolder, BatchReportReader batchReportReader,
DuplicationRepository duplicationRepository) {
this.treeRootHolder = treeRootHolder;
this.analysisMetadataHolder = analysisMetadataHolder;
this.batchReportReader = batchReportReader;
this.duplicationRepository = duplicationRepository;
}
@Override
public String getDescription() {
return "Load duplications";
}
@Override
public void execute(ComputationStep.Context context) {
DuplicationVisitor visitor = new DuplicationVisitor();
new DepthTraversalTypeAwareCrawler(visitor).visit(treeRootHolder.getReportTreeRoot());
context.getStatistics().add("duplications", visitor.count);
}
private class BatchDuplicateToCeDuplicate implements Function<ScannerReport.Duplicate, Duplicate> {
private final Component file;
private BatchDuplicateToCeDuplicate(Component file) {
this.file = file;
}
@Override
@Nonnull
public Duplicate apply(@Nonnull ScannerReport.Duplicate input) {
if (input.getOtherFileRef() != 0) {
checkArgument(input.getOtherFileRef() != file.getReportAttributes().getRef(), "file and otherFile references can not be the same");
Component otherComponent = treeRootHolder.getReportTreeComponentByRef(input.getOtherFileRef());
if (analysisMetadataHolder.isPullRequest() && otherComponent.getStatus() == Component.Status.SAME) {
return new InExtendedProjectDuplicate(otherComponent, convert(input.getRange()));
} else {
return new InProjectDuplicate(otherComponent, convert(input.getRange()));
}
}
return new InnerDuplicate(convert(input.getRange()));
}
private TextBlock convert(ScannerReport.TextRange textRange) {
return new TextBlock(textRange.getStartLine(), textRange.getEndLine());
}
}
private class DuplicationVisitor extends TypeAwareVisitorAdapter {
private int count = 0;
private DuplicationVisitor() {
super(CrawlerDepthLimit.FILE, Order.POST_ORDER);
}
@Override
public void visitFile(Component file) {
try (CloseableIterator<ScannerReport.Duplication> duplications = batchReportReader.readComponentDuplications(file.getReportAttributes().getRef())) {
int idGenerator = 1;
while (duplications.hasNext()) {
loadDuplications(file, duplications.next(), idGenerator);
idGenerator++;
count++;
}
}
}
private void loadDuplications(Component file, ScannerReport.Duplication duplication, int id) {
duplicationRepository.add(file,
new Duplication(
convert(duplication.getOriginPosition(), id),
duplication.getDuplicateList().stream()
.map(new BatchDuplicateToCeDuplicate(file)).toList()));
}
private DetailedTextBlock convert(ScannerReport.TextRange textRange, int id) {
return new DetailedTextBlock(id, textRange.getStartLine(), textRange.getEndLine());
}
}
}
| 5,731 | 42.097744 | 154 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/LoadFileHashesAndStatusStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.HashMap;
import java.util.Map;
import org.sonar.ce.task.projectanalysis.component.FileStatusesImpl;
import org.sonar.ce.task.projectanalysis.component.PreviousSourceHashRepositoryImpl;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.source.FileHashesDto;
import org.sonar.db.source.FileSourceDao;
public class LoadFileHashesAndStatusStep implements ComputationStep {
private final DbClient dbClient;
private final PreviousSourceHashRepositoryImpl previousFileHashesRepository;
private final FileStatusesImpl fileStatuses;
private final FileSourceDao fileSourceDao;
private final TreeRootHolder treeRootHolder;
public LoadFileHashesAndStatusStep(DbClient dbClient, PreviousSourceHashRepositoryImpl previousFileHashesRepository,
FileStatusesImpl fileStatuses, FileSourceDao fileSourceDao, TreeRootHolder treeRootHolder) {
this.dbClient = dbClient;
this.previousFileHashesRepository = previousFileHashesRepository;
this.fileStatuses = fileStatuses;
this.fileSourceDao = fileSourceDao;
this.treeRootHolder = treeRootHolder;
}
@Override
public void execute(Context context) {
Map<String, FileHashesDto> previousFileHashesByUuid = new HashMap<>();
String projectUuid = treeRootHolder.getRoot().getUuid();
try (DbSession session = dbClient.openSession(false)) {
fileSourceDao.scrollFileHashesByProjectUuid(session, projectUuid, ctx -> {
FileHashesDto dto = ctx.getResultObject();
previousFileHashesByUuid.put(dto.getFileUuid(), dto);
});
}
previousFileHashesRepository.set(previousFileHashesByUuid);
fileStatuses.initialize();
}
@Override
public String getDescription() {
return "Load file hashes and statuses";
}
}
| 2,776 | 39.246377 | 118 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/LoadMeasureComputersStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import org.sonar.api.ce.measure.MeasureComputer;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.measures.Metric;
import org.sonar.api.measures.Metrics;
import org.sonar.api.utils.dag.DirectAcyclicGraph;
import org.sonar.ce.task.projectanalysis.api.measurecomputer.MeasureComputerDefinitionImpl;
import org.sonar.ce.task.projectanalysis.api.measurecomputer.MeasureComputerWrapper;
import org.sonar.ce.task.projectanalysis.measure.MutableMeasureComputersHolder;
import org.sonar.ce.task.step.ComputationStep;
import org.springframework.beans.factory.annotation.Autowired;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.FluentIterable.from;
import static org.sonar.api.ce.measure.MeasureComputer.MeasureComputerDefinition;
public class LoadMeasureComputersStep implements ComputationStep {
private static final Set<String> CORE_METRIC_KEYS = CoreMetrics.getMetrics().stream().map(Metric::getKey).collect(Collectors.toSet());
private final Set<String> pluginMetricKeys;
private final MutableMeasureComputersHolder measureComputersHolder;
private final MeasureComputer[] measureComputers;
@Autowired(required = false)
public LoadMeasureComputersStep(MutableMeasureComputersHolder measureComputersHolder, Metrics[] metricsRepositories, MeasureComputer[] measureComputers) {
this.measureComputersHolder = measureComputersHolder;
this.measureComputers = measureComputers;
this.pluginMetricKeys = Arrays.stream(metricsRepositories)
.flatMap(m -> m.getMetrics().stream())
.map(Metric::getKey)
.collect(Collectors.toSet());
}
/**
* Constructor override used by the ioc container to instantiate the class when no plugin is defining metrics
*/
@Autowired(required = false)
public LoadMeasureComputersStep(MutableMeasureComputersHolder measureComputersHolder, MeasureComputer[] measureComputers) {
this(measureComputersHolder, new Metrics[] {}, measureComputers);
}
/**
* Constructor override used by the ioc container to instantiate the class when no plugin is defining measure computers
*/
@Autowired(required = false)
public LoadMeasureComputersStep(MutableMeasureComputersHolder measureComputersHolder, Metrics[] metricsRepositories) {
this(measureComputersHolder, metricsRepositories, new MeasureComputer[] {});
}
/**
* Constructor override used by the ioc container to instantiate the class when no plugin is defining metrics neither measure computers
*/
@Autowired(required = false)
public LoadMeasureComputersStep(MutableMeasureComputersHolder measureComputersHolder) {
this(measureComputersHolder, new Metrics[] {}, new MeasureComputer[] {});
}
@Override
public void execute(Context context) {
List<MeasureComputerWrapper> wrappers = Arrays.stream(measureComputers).map(ToMeasureWrapper.INSTANCE).toList();
validateMetrics(wrappers);
measureComputersHolder.setMeasureComputers(sortComputers(wrappers));
}
private static Iterable<MeasureComputerWrapper> sortComputers(List<MeasureComputerWrapper> wrappers) {
Map<String, MeasureComputerWrapper> computersByOutputMetric = new HashMap<>();
Map<String, MeasureComputerWrapper> computersByInputMetric = new HashMap<>();
feedComputersByMetric(wrappers, computersByOutputMetric, computersByInputMetric);
ToComputerByKey toComputerByOutputMetricKey = new ToComputerByKey(computersByOutputMetric);
ToComputerByKey toComputerByInputMetricKey = new ToComputerByKey(computersByInputMetric);
DirectAcyclicGraph dag = new DirectAcyclicGraph();
for (MeasureComputerWrapper computer : wrappers) {
dag.add(computer);
for (MeasureComputerWrapper dependency : getDependencies(computer, toComputerByOutputMetricKey)) {
dag.add(computer, dependency);
}
for (MeasureComputerWrapper generates : getDependents(computer, toComputerByInputMetricKey)) {
dag.add(generates, computer);
}
}
return dag.sort();
}
private static void feedComputersByMetric(List<MeasureComputerWrapper> wrappers, Map<String, MeasureComputerWrapper> computersByOutputMetric,
Map<String, MeasureComputerWrapper> computersByInputMetric) {
for (MeasureComputerWrapper computer : wrappers) {
for (String outputMetric : computer.getDefinition().getOutputMetrics()) {
computersByOutputMetric.put(outputMetric, computer);
}
for (String inputMetric : computer.getDefinition().getInputMetrics()) {
computersByInputMetric.put(inputMetric, computer);
}
}
}
private void validateMetrics(List<MeasureComputerWrapper> wrappers) {
wrappers.stream().flatMap(s -> ToInputMetrics.INSTANCE.apply(s).stream()).forEach(this::validateInputMetric);
wrappers.stream().flatMap(s -> ToOutputMetrics.INSTANCE.apply(s).stream()).forEach(this::validateOutputMetric);
ValidateUniqueOutputMetric validateUniqueOutputMetric = new ValidateUniqueOutputMetric();
wrappers.forEach(validateUniqueOutputMetric::validate);
}
private static Collection<MeasureComputerWrapper> getDependencies(MeasureComputerWrapper measureComputer, ToComputerByKey toComputerByOutputMetricKey) {
// Remove null computer because a computer can depend on a metric that is only generated by a sensor or on a core metrics
return measureComputer.getDefinition().getInputMetrics().stream()
.map(toComputerByOutputMetricKey)
.filter(Objects::nonNull)
.toList();
}
private static Collection<MeasureComputerWrapper> getDependents(MeasureComputerWrapper measureComputer, ToComputerByKey toComputerByInputMetricKey) {
return measureComputer.getDefinition().getInputMetrics().stream()
.map(toComputerByInputMetricKey)
.toList();
}
private static class ToComputerByKey implements Function<String, MeasureComputerWrapper> {
private final Map<String, MeasureComputerWrapper> computersByMetric;
private ToComputerByKey(Map<String, MeasureComputerWrapper> computersByMetric) {
this.computersByMetric = computersByMetric;
}
@Override
public MeasureComputerWrapper apply(@Nonnull String metricKey) {
return computersByMetric.get(metricKey);
}
}
private enum ToMeasureWrapper implements Function<MeasureComputer, MeasureComputerWrapper> {
INSTANCE;
@Override
public MeasureComputerWrapper apply(@Nonnull MeasureComputer measureComputer) {
MeasureComputerDefinition def = measureComputer.define(MeasureComputerDefinitionImpl.BuilderImpl::new);
return new MeasureComputerWrapper(measureComputer, validateDef(def));
}
private static MeasureComputerDefinition validateDef(MeasureComputerDefinition def) {
if (def instanceof MeasureComputerDefinitionImpl) {
return def;
}
// If the computer has not been created by the builder, we recreate it to make sure it's valid
Set<String> inputMetrics = def.getInputMetrics();
Set<String> outputMetrics = def.getOutputMetrics();
return new MeasureComputerDefinitionImpl.BuilderImpl()
.setInputMetrics(from(inputMetrics).toArray(String.class))
.setOutputMetrics(from(outputMetrics).toArray(String.class))
.build();
}
}
private enum ToInputMetrics implements Function<MeasureComputerWrapper, Collection<String>> {
INSTANCE;
@Override
public Collection<String> apply(@Nonnull MeasureComputerWrapper input) {
return input.getDefinition().getInputMetrics();
}
}
private void validateInputMetric(String metric) {
checkState(pluginMetricKeys.contains(metric) || CORE_METRIC_KEYS.contains(metric),
"Metric '%s' cannot be used as an input metric as it's not a core metric and no plugin declare this metric", metric);
}
private enum ToOutputMetrics implements Function<MeasureComputerWrapper, Collection<String>> {
INSTANCE;
@Override
public Collection<String> apply(@Nonnull MeasureComputerWrapper input) {
return input.getDefinition().getOutputMetrics();
}
}
private void validateOutputMetric(String metric) {
checkState(!CORE_METRIC_KEYS.contains(metric), "Metric '%s' cannot be used as an output metric because it's a core metric", metric);
checkState(pluginMetricKeys.contains(metric), "Metric '%s' cannot be used as an output metric because no plugins declare this metric", metric);
}
private static class ValidateUniqueOutputMetric {
private final Set<String> allOutputMetrics = new HashSet<>();
public boolean validate(@Nonnull MeasureComputerWrapper wrapper) {
for (String outputMetric : wrapper.getDefinition().getOutputMetrics()) {
checkState(!allOutputMetrics.contains(outputMetric),
"Output metric '%s' is already defined by another measure computer '%s'", outputMetric, wrapper.getComputer());
allOutputMetrics.add(outputMetric);
}
return true;
}
}
@Override
public String getDescription() {
return "Load measure computers";
}
}
| 10,207 | 43.190476 | 156 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/LoadPeriodsStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.Optional;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.log.CeTaskMessages;
import org.sonar.ce.task.log.CeTaskMessages.Message;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.projectanalysis.period.NewCodePeriodResolver;
import org.sonar.ce.task.projectanalysis.period.Period;
import org.sonar.ce.task.projectanalysis.period.PeriodHolder;
import org.sonar.ce.task.projectanalysis.period.PeriodHolderImpl;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.newcodeperiod.NewCodePeriodDao;
import org.sonar.db.newcodeperiod.NewCodePeriodDto;
import static org.sonar.db.newcodeperiod.NewCodePeriodType.REFERENCE_BRANCH;
/**
* Populates the {@link PeriodHolder}
* <p/>
* Here is how these periods are computed :
* - Read the new code period from DB
* - Try to find the matching snapshots from the setting
* - If a snapshot is found, a period is set to the repository, otherwise fail with MessageException
*/
public class LoadPeriodsStep implements ComputationStep {
private final AnalysisMetadataHolder analysisMetadataHolder;
private final NewCodePeriodDao newCodePeriodDao;
private final TreeRootHolder treeRootHolder;
private final PeriodHolderImpl periodsHolder;
private final DbClient dbClient;
private final NewCodePeriodResolver resolver;
private final CeTaskMessages ceTaskMessages;
private final System2 system2;
public LoadPeriodsStep(AnalysisMetadataHolder analysisMetadataHolder, NewCodePeriodDao newCodePeriodDao, TreeRootHolder treeRootHolder,
PeriodHolderImpl periodsHolder, DbClient dbClient, NewCodePeriodResolver resolver, CeTaskMessages ceTaskMessages, System2 system2) {
this.analysisMetadataHolder = analysisMetadataHolder;
this.newCodePeriodDao = newCodePeriodDao;
this.treeRootHolder = treeRootHolder;
this.periodsHolder = periodsHolder;
this.dbClient = dbClient;
this.resolver = resolver;
this.ceTaskMessages = ceTaskMessages;
this.system2 = system2;
}
@Override
public String getDescription() {
return "Load new code period";
}
@Override
public void execute(ComputationStep.Context context) {
if (!analysisMetadataHolder.isBranch()) {
periodsHolder.setPeriod(null);
return;
}
String projectUuid = getProjectBranchUuid();
String branchUuid = treeRootHolder.getRoot().getUuid();
String projectVersion = treeRootHolder.getRoot().getProjectAttributes().getProjectVersion();
var newCodePeriod = analysisMetadataHolder.getNewCodeReferenceBranch()
.filter(s -> !s.isBlank())
.map(b -> new NewCodePeriodDto().setType(REFERENCE_BRANCH).setValue(b))
.orElse(null);
try (DbSession dbSession = dbClient.openSession(false)) {
Optional<NewCodePeriodDto> branchSpecificSetting = getBranchSetting(dbSession, projectUuid, branchUuid);
if (newCodePeriod == null) {
newCodePeriod = branchSpecificSetting
.or(() -> getProjectSetting(dbSession, projectUuid))
.or(() -> getGlobalSetting(dbSession))
.orElse(NewCodePeriodDto.defaultInstance());
if (analysisMetadataHolder.isFirstAnalysis() && newCodePeriod.getType() != REFERENCE_BRANCH) {
periodsHolder.setPeriod(null);
return;
}
} else if (branchSpecificSetting.isPresent()) {
ceTaskMessages.add(new Message("A scanner parameter is defining a new code reference branch, but this conflicts with the New Code Period"
+ " setting of your branch. Please check your project configuration. You should use either one or the other but not both.", system2.now()));
}
Period period = resolver.resolve(dbSession, branchUuid, newCodePeriod, projectVersion);
periodsHolder.setPeriod(period);
}
}
private Optional<NewCodePeriodDto> getBranchSetting(DbSession dbSession, String projectUuid, String branchUuid) {
return newCodePeriodDao.selectByBranch(dbSession, projectUuid, branchUuid);
}
private Optional<NewCodePeriodDto> getProjectSetting(DbSession dbSession, String projectUuid) {
return newCodePeriodDao.selectByProject(dbSession, projectUuid);
}
private Optional<NewCodePeriodDto> getGlobalSetting(DbSession dbSession) {
return newCodePeriodDao.selectGlobal(dbSession);
}
private String getProjectBranchUuid() {
return analysisMetadataHolder.getProject().getUuid();
}
}
| 5,450 | 40.610687 | 150 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/LoadQualityGateStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.qualitygate.Condition;
import org.sonar.ce.task.projectanalysis.qualitygate.MutableQualityGateHolder;
import org.sonar.ce.task.projectanalysis.qualitygate.QualityGate;
import org.sonar.ce.task.projectanalysis.qualitygate.QualityGateService;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.server.project.Project;
/**
* This step retrieves the QualityGate and stores it in
* {@link MutableQualityGateHolder}.
*/
public class LoadQualityGateStep implements ComputationStep {
private final QualityGateService qualityGateService;
private final MutableQualityGateHolder qualityGateHolder;
private final AnalysisMetadataHolder analysisMetadataHolder;
public LoadQualityGateStep(QualityGateService qualityGateService, MutableQualityGateHolder qualityGateHolder, AnalysisMetadataHolder analysisMetadataHolder) {
this.qualityGateService = qualityGateService;
this.qualityGateHolder = qualityGateHolder;
this.analysisMetadataHolder = analysisMetadataHolder;
}
@Override
public void execute(ComputationStep.Context context) {
QualityGate qualityGate = getProjectQualityGate();
if (analysisMetadataHolder.isPullRequest()) {
qualityGate = filterQGForPR(qualityGate);
}
qualityGateHolder.setQualityGate(qualityGate);
}
private static QualityGate filterQGForPR(QualityGate qg) {
return new QualityGate(qg.getUuid(), qg.getName(), qg.getConditions().stream().filter(Condition::useVariation).toList());
}
private QualityGate getProjectQualityGate() {
Project project = analysisMetadataHolder.getProject();
return qualityGateService.findEffectiveQualityGate(project);
}
@Override
public String getDescription() {
return "Load Quality gate";
}
}
| 2,742 | 37.633803 | 160 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/LoadQualityProfilesStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.RuleStatus;
import org.sonar.ce.task.projectanalysis.batch.BatchReportReader;
import org.sonar.ce.task.projectanalysis.issue.Rule;
import org.sonar.ce.task.projectanalysis.issue.RuleRepository;
import org.sonar.ce.task.projectanalysis.qualityprofile.ActiveRule;
import org.sonar.ce.task.projectanalysis.qualityprofile.ActiveRulesHolderImpl;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.core.util.CloseableIterator;
import org.sonar.scanner.protocol.output.ScannerReport;
public class LoadQualityProfilesStep implements ComputationStep {
private final BatchReportReader batchReportReader;
private final ActiveRulesHolderImpl activeRulesHolder;
private final RuleRepository ruleRepository;
public LoadQualityProfilesStep(BatchReportReader batchReportReader, ActiveRulesHolderImpl activeRulesHolder, RuleRepository ruleRepository) {
this.batchReportReader = batchReportReader;
this.activeRulesHolder = activeRulesHolder;
this.ruleRepository = ruleRepository;
}
@Override
public void execute(ComputationStep.Context context) {
List<ActiveRule> activeRules = new ArrayList<>();
try (CloseableIterator<ScannerReport.ActiveRule> batchActiveRules = batchReportReader.readActiveRules()) {
while (batchActiveRules.hasNext()) {
ScannerReport.ActiveRule scannerReportActiveRule = batchActiveRules.next();
Optional<Rule> rule = ruleRepository.findByKey(RuleKey.of(scannerReportActiveRule.getRuleRepository(), scannerReportActiveRule.getRuleKey()));
if (rule.isPresent() && rule.get().getStatus() != RuleStatus.REMOVED && !rule.get().isExternal()) {
activeRules.add(convert(scannerReportActiveRule, rule.get()));
}
}
}
activeRulesHolder.set(activeRules);
}
@Override
public String getDescription() {
return "Load quality profiles";
}
private static ActiveRule convert(ScannerReport.ActiveRule input, Rule rule) {
RuleKey key = RuleKey.of(input.getRuleRepository(), input.getRuleKey());
Map<String, String> params = new HashMap<>(input.getParamsByKeyMap());
return new ActiveRule(key, input.getSeverity().name(), params, input.getUpdatedAt(), rule.getPluginKey(), input.getQProfileKey());
}
}
| 3,307 | 41.961039 | 150 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/LoadReportAnalysisMetadataHolderStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.Date;
import java.util.Optional;
import javax.annotation.CheckForNull;
import org.sonar.api.utils.MessageException;
import org.sonar.ce.task.CeTask;
import org.sonar.ce.task.projectanalysis.analysis.MutableAnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.analysis.ScannerPlugin;
import org.sonar.ce.task.projectanalysis.batch.BatchReportReader;
import org.sonar.ce.task.projectanalysis.component.BranchLoader;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.core.platform.PluginRepository;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.project.ProjectDto;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.protocol.output.ScannerReport.Metadata.Plugin;
import org.sonar.scanner.protocol.output.ScannerReport.Metadata.QProfile;
import org.sonar.server.project.Project;
import org.sonar.server.qualityprofile.QualityProfile;
import static com.google.common.base.Preconditions.checkState;
import static java.lang.String.format;
import static java.util.stream.Collectors.toMap;
/**
* Feed analysis metadata holder with metadata from the analysis report.
*/
public class LoadReportAnalysisMetadataHolderStep implements ComputationStep {
private final CeTask ceTask;
private final BatchReportReader reportReader;
private final MutableAnalysisMetadataHolder analysisMetadata;
private final DbClient dbClient;
private final BranchLoader branchLoader;
private final PluginRepository pluginRepository;
public LoadReportAnalysisMetadataHolderStep(CeTask ceTask, BatchReportReader reportReader, MutableAnalysisMetadataHolder analysisMetadata,
DbClient dbClient, BranchLoader branchLoader, PluginRepository pluginRepository) {
this.ceTask = ceTask;
this.reportReader = reportReader;
this.analysisMetadata = analysisMetadata;
this.dbClient = dbClient;
this.branchLoader = branchLoader;
this.pluginRepository = pluginRepository;
}
@Override
public void execute(ComputationStep.Context context) {
ScannerReport.Metadata reportMetadata = reportReader.readMetadata();
loadMetadata(reportMetadata);
Runnable projectValidation = loadProject(reportMetadata);
loadQualityProfiles(reportMetadata);
branchLoader.load(reportMetadata);
projectValidation.run();
}
private void loadMetadata(ScannerReport.Metadata reportMetadata) {
analysisMetadata.setAnalysisDate(reportMetadata.getAnalysisDate());
analysisMetadata.setRootComponentRef(reportMetadata.getRootComponentRef());
analysisMetadata.setCrossProjectDuplicationEnabled(reportMetadata.getCrossProjectDuplicationActivated());
analysisMetadata.setScmRevision(reportMetadata.getScmRevisionId());
analysisMetadata.setNewCodeReferenceBranch(reportMetadata.getNewCodeReferenceBranch());
}
/**
* @return a {@link Runnable} to execute some checks on the project at the end of the step
*/
private Runnable loadProject(ScannerReport.Metadata reportMetadata) {
CeTask.Component entity = mandatoryComponent(ceTask.getEntity());
String entityKey = entity.getKey()
.orElseThrow(() -> MessageException.of(format(
"Compute Engine task entity key is null. Project with UUID %s must have been deleted since report was uploaded. Can not proceed.",
entity.getUuid())));
CeTask.Component component = mandatoryComponent(ceTask.getComponent());
if (!component.getKey().isPresent()) {
throw MessageException.of(format(
"Compute Engine task component key is null. Project with UUID %s must have been deleted since report was uploaded. Can not proceed.",
component.getUuid()));
}
ProjectDto dto = toProject(reportMetadata.getProjectKey());
analysisMetadata.setProject(Project.fromProjectDtoWithTags(dto));
return () -> {
if (!entityKey.equals(reportMetadata.getProjectKey())) {
throw MessageException.of(format(
"ProjectKey in report (%s) is not consistent with projectKey under which the report has been submitted (%s)",
reportMetadata.getProjectKey(),
entityKey));
}
};
}
private static CeTask.Component mandatoryComponent(Optional<CeTask.Component> entity) {
return entity.orElseThrow(() -> new IllegalStateException("component missing on ce task"));
}
private void loadQualityProfiles(ScannerReport.Metadata reportMetadata) {
analysisMetadata.setQProfilesByLanguage(reportMetadata.getQprofilesPerLanguageMap().values().stream()
.collect(toMap(
QProfile::getLanguage,
qp -> new QualityProfile(qp.getKey(), qp.getName(), qp.getLanguage(), new Date(qp.getRulesUpdatedAt())))));
analysisMetadata.setScannerPluginsByKey(reportMetadata.getPluginsByKeyMap().values().stream()
.collect(toMap(
Plugin::getKey,
p -> new ScannerPlugin(p.getKey(), getBasePluginKey(p), p.getUpdatedAt()))));
}
@CheckForNull
private String getBasePluginKey(Plugin p) {
if (!pluginRepository.hasPlugin(p.getKey())) {
// May happen if plugin was uninstalled between start of scanner analysis and now.
// But it doesn't matter since all active rules are removed anyway, so no issues will be reported
return null;
}
return pluginRepository.getPluginInfo(p.getKey()).getBasePlugin();
}
private ProjectDto toProject(String projectKey) {
try (DbSession dbSession = dbClient.openSession(false)) {
Optional<ProjectDto> opt = dbClient.projectDao().selectProjectByKey(dbSession, projectKey);
checkState(opt.isPresent(), "Project with key '%s' can't be found", projectKey);
return opt.get();
}
}
@Override
public String getDescription() {
return "Load analysis metadata";
}
}
| 6,643 | 42.710526 | 141 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/NewCoverageMeasuresStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import com.google.common.collect.Iterables;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.ce.task.projectanalysis.batch.BatchReportReader;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.PathAwareCrawler;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.projectanalysis.formula.Counter;
import org.sonar.ce.task.projectanalysis.formula.CounterInitializationContext;
import org.sonar.ce.task.projectanalysis.formula.CreateMeasureContext;
import org.sonar.ce.task.projectanalysis.formula.Formula;
import org.sonar.ce.task.projectanalysis.formula.FormulaExecutorComponentVisitor;
import org.sonar.ce.task.projectanalysis.formula.counter.IntValue;
import org.sonar.ce.task.projectanalysis.formula.coverage.LinesAndConditionsWithUncoveredFormula;
import org.sonar.ce.task.projectanalysis.formula.coverage.LinesAndConditionsWithUncoveredMetricKeys;
import org.sonar.ce.task.projectanalysis.formula.coverage.SingleWithUncoveredFormula;
import org.sonar.ce.task.projectanalysis.formula.coverage.SingleWithUncoveredMetricKeys;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import org.sonar.ce.task.projectanalysis.measure.MeasureRepository;
import org.sonar.ce.task.projectanalysis.metric.Metric;
import org.sonar.ce.task.projectanalysis.metric.MetricRepository;
import org.sonar.ce.task.projectanalysis.source.NewLinesRepository;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.core.util.CloseableIterator;
import org.sonar.scanner.protocol.output.ScannerReport;
import static java.lang.Math.min;
import static org.sonar.api.measures.CoreMetrics.NEW_CONDITIONS_TO_COVER_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_LINES_TO_COVER_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_UNCOVERED_CONDITIONS_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_UNCOVERED_LINES_KEY;
import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilder;
/**
* Computes measures related to the New Coverage.
*/
public class NewCoverageMeasuresStep implements ComputationStep {
private static final List<Formula<?>> FORMULAS = List.of(
// UT coverage
new NewCoverageFormula(),
new NewBranchCoverageFormula(),
new NewLineCoverageFormula()
);
private final TreeRootHolder treeRootHolder;
private final MetricRepository metricRepository;
private final MeasureRepository measureRepository;
private final NewLinesRepository newLinesRepository;
private final BatchReportReader reportReader;
public NewCoverageMeasuresStep(TreeRootHolder treeRootHolder,
MeasureRepository measureRepository, MetricRepository metricRepository, NewLinesRepository newLinesRepository, BatchReportReader reportReader) {
this.treeRootHolder = treeRootHolder;
this.metricRepository = metricRepository;
this.measureRepository = measureRepository;
this.newLinesRepository = newLinesRepository;
this.reportReader = reportReader;
}
@Override
public void execute(ComputationStep.Context context) {
new PathAwareCrawler<>(
FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository)
.buildFor(
Iterables.concat(NewLinesAndConditionsCoverageFormula.from(newLinesRepository, reportReader), FORMULAS)))
.visit(treeRootHolder.getRoot());
}
@Override
public String getDescription() {
return "Compute new coverage";
}
private static class NewCoverageFormula extends LinesAndConditionsWithUncoveredFormula {
NewCoverageFormula() {
super(
new LinesAndConditionsWithUncoveredMetricKeys(
NEW_LINES_TO_COVER_KEY, NEW_CONDITIONS_TO_COVER_KEY,
NEW_UNCOVERED_LINES_KEY, NEW_UNCOVERED_CONDITIONS_KEY),
CoreMetrics.NEW_COVERAGE_KEY);
}
}
private static class NewBranchCoverageFormula extends SingleWithUncoveredFormula {
NewBranchCoverageFormula() {
super(
new SingleWithUncoveredMetricKeys(NEW_CONDITIONS_TO_COVER_KEY, NEW_UNCOVERED_CONDITIONS_KEY),
CoreMetrics.NEW_BRANCH_COVERAGE_KEY);
}
}
private static class NewLineCoverageFormula extends SingleWithUncoveredFormula {
NewLineCoverageFormula() {
super(
new SingleWithUncoveredMetricKeys(NEW_LINES_TO_COVER_KEY, NEW_UNCOVERED_LINES_KEY),
CoreMetrics.NEW_LINE_COVERAGE_KEY);
}
}
public static class NewLinesAndConditionsCoverageFormula implements Formula<NewCoverageCounter> {
private final NewLinesRepository newLinesRepository;
private final BatchReportReader reportReader;
private NewLinesAndConditionsCoverageFormula(NewLinesRepository newLinesRepository, BatchReportReader reportReader) {
this.newLinesRepository = newLinesRepository;
this.reportReader = reportReader;
}
public static Iterable<Formula<NewCoverageCounter>> from(NewLinesRepository newLinesRepository, BatchReportReader reportReader) {
return Collections.singleton(new NewLinesAndConditionsCoverageFormula(newLinesRepository, reportReader));
}
@Override
public NewCoverageCounter createNewCounter() {
return new NewCoverageCounter(newLinesRepository, reportReader);
}
@Override
public Optional<Measure> createMeasure(NewCoverageCounter counter, CreateMeasureContext context) {
if (counter.hasNewCode()) {
int value = computeValueForMetric(counter, context.getMetric());
return Optional.of(newMeasureBuilder().create(value));
}
return Optional.empty();
}
private static int computeValueForMetric(NewCoverageCounter counter, Metric metric) {
if (metric.getKey().equals(NEW_LINES_TO_COVER_KEY)) {
return counter.getNewLines();
}
if (metric.getKey().equals(NEW_UNCOVERED_LINES_KEY)) {
return counter.getNewLines() - counter.getNewCoveredLines();
}
if (metric.getKey().equals(NEW_CONDITIONS_TO_COVER_KEY)) {
return counter.getNewConditions();
}
if (metric.getKey().equals(NEW_UNCOVERED_CONDITIONS_KEY)) {
return counter.getNewConditions() - counter.getNewCoveredConditions();
}
throw new IllegalArgumentException("Unsupported metric " + metric.getKey());
}
@Override
public String[] getOutputMetricKeys() {
return new String[] {
NEW_LINES_TO_COVER_KEY,
NEW_UNCOVERED_LINES_KEY,
NEW_CONDITIONS_TO_COVER_KEY,
NEW_UNCOVERED_CONDITIONS_KEY
};
}
}
public static final class NewCoverageCounter implements Counter<NewCoverageCounter> {
private final IntValue newLines = new IntValue();
private final IntValue newCoveredLines = new IntValue();
private final IntValue newConditions = new IntValue();
private final IntValue newCoveredConditions = new IntValue();
private final NewLinesRepository newLinesRepository;
private final BatchReportReader reportReader;
NewCoverageCounter(NewLinesRepository newLinesRepository, BatchReportReader reportReader) {
this.newLinesRepository = newLinesRepository;
this.reportReader = reportReader;
}
@Override
public void aggregate(NewCoverageCounter counter) {
newLines.increment(counter.newLines);
newCoveredLines.increment(counter.newCoveredLines);
newConditions.increment(counter.newConditions);
newCoveredConditions.increment(counter.newCoveredConditions);
}
@Override
public void initialize(CounterInitializationContext context) {
Component component = context.getLeaf();
if (component.getType() != Component.Type.FILE || component.getFileAttributes().isUnitTest()) {
return;
}
Optional<Set<Integer>> newLinesSet = newLinesRepository.getNewLines(component);
if (!newLinesSet.isPresent()) {
return;
}
newLines.increment(0);
newCoveredLines.increment(0);
newConditions.increment(0);
newCoveredConditions.increment(0);
try (CloseableIterator<ScannerReport.LineCoverage> lineCoverage = reportReader.readComponentCoverage(component.getReportAttributes().getRef())) {
while (lineCoverage.hasNext()) {
final ScannerReport.LineCoverage line = lineCoverage.next();
int lineId = line.getLine();
if (newLinesSet.get().contains(lineId)) {
if (line.getHasHitsCase() == ScannerReport.LineCoverage.HasHitsCase.HITS) {
newLines.increment(1);
if (line.getHits()) {
newCoveredLines.increment(1);
}
}
if (line.getHasCoveredConditionsCase() == ScannerReport.LineCoverage.HasCoveredConditionsCase.COVERED_CONDITIONS) {
newConditions.increment(line.getConditions());
newCoveredConditions.increment(min(line.getCoveredConditions(), line.getConditions()));
}
}
}
}
}
boolean hasNewCode() {
return newLines.isSet();
}
int getNewLines() {
return newLines.getValue();
}
int getNewCoveredLines() {
return newCoveredLines.getValue();
}
int getNewConditions() {
return newConditions.getValue();
}
int getNewCoveredConditions() {
return newCoveredConditions.getValue();
}
}
}
| 10,298 | 38.918605 | 151 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/NewSizeMeasuresStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.IntStream;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.PathAwareCrawler;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.projectanalysis.duplication.Duplication;
import org.sonar.ce.task.projectanalysis.duplication.DuplicationRepository;
import org.sonar.ce.task.projectanalysis.duplication.InnerDuplicate;
import org.sonar.ce.task.projectanalysis.duplication.TextBlock;
import org.sonar.ce.task.projectanalysis.formula.Counter;
import org.sonar.ce.task.projectanalysis.formula.CounterInitializationContext;
import org.sonar.ce.task.projectanalysis.formula.CreateMeasureContext;
import org.sonar.ce.task.projectanalysis.formula.Formula;
import org.sonar.ce.task.projectanalysis.formula.FormulaExecutorComponentVisitor;
import org.sonar.ce.task.projectanalysis.formula.counter.IntValue;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import org.sonar.ce.task.projectanalysis.measure.MeasureRepository;
import org.sonar.ce.task.projectanalysis.metric.MetricRepository;
import org.sonar.ce.task.projectanalysis.source.NewLinesRepository;
import org.sonar.ce.task.step.ComputationStep;
import static org.sonar.api.measures.CoreMetrics.NEW_BLOCKS_DUPLICATED_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_DUPLICATED_LINES_DENSITY_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_DUPLICATED_LINES_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_LINES_KEY;
/**
* Computes measures on new code related to the size
*/
public class NewSizeMeasuresStep implements ComputationStep {
private final TreeRootHolder treeRootHolder;
private final MetricRepository metricRepository;
private final MeasureRepository measureRepository;
private final NewDuplicationFormula duplicationFormula;
public NewSizeMeasuresStep(TreeRootHolder treeRootHolder, MetricRepository metricRepository, MeasureRepository measureRepository,
NewLinesRepository newLinesRepository, DuplicationRepository duplicationRepository) {
this.treeRootHolder = treeRootHolder;
this.metricRepository = metricRepository;
this.measureRepository = measureRepository;
this.duplicationFormula = new NewDuplicationFormula(newLinesRepository, duplicationRepository);
}
@Override
public String getDescription() {
return "Compute size measures on new code";
}
@Override
public void execute(ComputationStep.Context context) {
new PathAwareCrawler<>(
FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository)
.buildFor(List.of(duplicationFormula)))
.visit(treeRootHolder.getRoot());
}
private static class NewSizeCounter implements Counter<NewSizeCounter> {
private final DuplicationRepository duplicationRepository;
private final NewLinesRepository newLinesRepository;
private final IntValue newLines = new IntValue();
private final IntValue newDuplicatedLines = new IntValue();
private final IntValue newDuplicatedBlocks = new IntValue();
private NewSizeCounter(DuplicationRepository duplicationRepository, NewLinesRepository newLinesRepository) {
this.duplicationRepository = duplicationRepository;
this.newLinesRepository = newLinesRepository;
}
@Override
public void aggregate(NewSizeCounter counter) {
this.newDuplicatedLines.increment(counter.newDuplicatedLines);
this.newDuplicatedBlocks.increment(counter.newDuplicatedBlocks);
this.newLines.increment(counter.newLines);
}
@Override
public void initialize(CounterInitializationContext context) {
Component leaf = context.getLeaf();
if (leaf.getType() != Component.Type.FILE) {
return;
}
Optional<Set<Integer>> changedLines = newLinesRepository.getNewLines(leaf);
if (changedLines.isEmpty()) {
return;
}
newLines.increment(0);
if (leaf.getType() != Component.Type.FILE) {
newDuplicatedLines.increment(0);
newDuplicatedBlocks.increment(0);
} else {
initNewLines(changedLines.get());
initNewDuplicated(leaf, changedLines.get());
}
}
private void initNewLines(Set<Integer> changedLines) {
newLines.increment(changedLines.size());
}
private void initNewDuplicated(Component component, Set<Integer> changedLines) {
DuplicationCounters duplicationCounters = new DuplicationCounters(changedLines);
Iterable<Duplication> duplications = duplicationRepository.getDuplications(component);
for (Duplication duplication : duplications) {
duplicationCounters.addBlock(duplication.getOriginal());
Arrays.stream(duplication.getDuplicates())
.filter(InnerDuplicate.class::isInstance)
.map(duplicate -> (InnerDuplicate) duplicate)
.forEach(duplicate -> duplicationCounters.addBlock(duplicate.getTextBlock()));
}
newDuplicatedLines.increment(duplicationCounters.getNewLinesDuplicated());
newDuplicatedBlocks.increment(duplicationCounters.getNewBlocksDuplicated());
}
}
private static class DuplicationCounters {
private final Set<Integer> changedLines;
private final Set<Integer> lineCounts;
private int blockCounts;
private DuplicationCounters(Set<Integer> changedLines) {
this.changedLines = changedLines;
this.lineCounts = new HashSet<>(changedLines.size());
}
void addBlock(TextBlock textBlock) {
Boolean[] newBlock = new Boolean[] {false};
IntStream.rangeClosed(textBlock.getStart(), textBlock.getEnd())
.filter(changedLines::contains)
.forEach(line -> {
lineCounts.add(line);
newBlock[0] = true;
});
if (newBlock[0]) {
blockCounts++;
}
}
int getNewLinesDuplicated() {
return lineCounts.size();
}
int getNewBlocksDuplicated() {
return blockCounts;
}
}
private static final class NewDuplicationFormula implements Formula<NewSizeCounter> {
private final DuplicationRepository duplicationRepository;
private final NewLinesRepository newLinesRepository;
private NewDuplicationFormula(NewLinesRepository newLinesRepository, DuplicationRepository duplicationRepository) {
this.duplicationRepository = duplicationRepository;
this.newLinesRepository = newLinesRepository;
}
@Override
public NewSizeCounter createNewCounter() {
return new NewSizeCounter(duplicationRepository, newLinesRepository);
}
@Override
public Optional<Measure> createMeasure(NewSizeCounter counter, CreateMeasureContext context) {
String metricKey = context.getMetric().getKey();
switch (metricKey) {
case NEW_LINES_KEY:
return createMeasure(counter.newLines);
case NEW_DUPLICATED_LINES_KEY:
return createMeasure(counter.newDuplicatedLines);
case NEW_DUPLICATED_LINES_DENSITY_KEY:
return createNewDuplicatedLinesDensityMeasure(counter);
case NEW_BLOCKS_DUPLICATED_KEY:
return createMeasure(counter.newDuplicatedBlocks);
default:
throw new IllegalArgumentException("Unsupported metric " + context.getMetric());
}
}
private static Optional<Measure> createMeasure(IntValue intValue) {
return intValue.isSet()
? Optional.of(Measure.newMeasureBuilder().create(intValue.getValue()))
: Optional.empty();
}
private static Optional<Measure> createNewDuplicatedLinesDensityMeasure(NewSizeCounter counter) {
IntValue newLines = counter.newLines;
IntValue newDuplicatedLines = counter.newDuplicatedLines;
if (newLines.isSet() && newDuplicatedLines.isSet()) {
int newLinesValue = newLines.getValue();
int newDuplicatedLinesValue = newDuplicatedLines.getValue();
if (newLinesValue > 0D) {
double density = Math.min(100D, 100D * newDuplicatedLinesValue / newLinesValue);
return Optional.of(Measure.newMeasureBuilder().create(density));
}
}
return Optional.empty();
}
@Override
public String[] getOutputMetricKeys() {
return new String[] {NEW_LINES_KEY, NEW_DUPLICATED_LINES_KEY, NEW_DUPLICATED_LINES_DENSITY_KEY, NEW_BLOCKS_DUPLICATED_KEY};
}
}
}
| 9,346 | 39.288793 | 131 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/PersistAdHocRulesStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import org.sonar.ce.task.projectanalysis.issue.RuleRepository;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
public class PersistAdHocRulesStep implements ComputationStep {
private final DbClient dbClient;
private final RuleRepository ruleRepository;
public PersistAdHocRulesStep(DbClient dbClient, RuleRepository ruleRepository) {
this.dbClient = dbClient;
this.ruleRepository = ruleRepository;
}
@Override
public void execute(ComputationStep.Context context) {
try (DbSession dbSession = dbClient.openSession(false)) {
ruleRepository.saveOrUpdateAddHocRules(dbSession);
}
}
@Override
public String getDescription() {
return "Persist new ad hoc Rules";
}
}
| 1,665 | 31.666667 | 82 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/PersistAnalysisPropertiesStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.batch.BatchReportReader;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.core.util.CloseableIterator;
import org.sonar.core.util.UuidFactory;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.AnalysisPropertyDto;
import org.sonar.scanner.protocol.output.ScannerReport;
import static org.sonar.core.config.CorePropertyDefinitions.SONAR_ANALYSIS;
import static org.sonar.core.config.CorePropertyDefinitions.SONAR_ANALYSIS_DETECTEDCI;
import static org.sonar.core.config.CorePropertyDefinitions.SONAR_ANALYSIS_DETECTEDSCM;
/**
* Persist analysis properties
*/
public class PersistAnalysisPropertiesStep implements ComputationStep {
private static final String SONAR_PULL_REQUEST = "sonar.pullrequest.";
private static final Set<String> ANALYSIS_PROPERTIES_TO_PERSIST = Set.of(SONAR_ANALYSIS_DETECTEDSCM, SONAR_ANALYSIS_DETECTEDCI);
private final DbClient dbClient;
private final AnalysisMetadataHolder analysisMetadataHolder;
private final BatchReportReader reportReader;
private final UuidFactory uuidFactory;
public PersistAnalysisPropertiesStep(DbClient dbClient, AnalysisMetadataHolder analysisMetadataHolder,
BatchReportReader reportReader, UuidFactory uuidFactory) {
this.dbClient = dbClient;
this.analysisMetadataHolder = analysisMetadataHolder;
this.reportReader = reportReader;
this.uuidFactory = uuidFactory;
}
@Override
public void execute(ComputationStep.Context context) {
List<AnalysisPropertyDto> analysisPropertyDtos = new ArrayList<>();
try (CloseableIterator<ScannerReport.ContextProperty> it = reportReader.readContextProperties()) {
it.forEachRemaining(
contextProperty -> {
String propertyKey = contextProperty.getKey();
if (propertyKey.startsWith(SONAR_ANALYSIS) || propertyKey.startsWith(SONAR_PULL_REQUEST) ||
ANALYSIS_PROPERTIES_TO_PERSIST.contains(propertyKey)) {
analysisPropertyDtos.add(new AnalysisPropertyDto()
.setUuid(uuidFactory.create())
.setKey(propertyKey)
.setValue(contextProperty.getValue())
.setAnalysisUuid(analysisMetadataHolder.getUuid()));
}
});
}
if (analysisPropertyDtos.isEmpty()) {
return;
}
try (DbSession dbSession = dbClient.openSession(false)) {
dbClient.analysisPropertiesDao().insert(dbSession, analysisPropertyDtos);
dbSession.commit();
}
}
@Override
public String getDescription() {
return "Persist analysis properties";
}
}
| 3,691 | 38.698925 | 130 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/PersistAnalysisStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit;
import org.sonar.ce.task.projectanalysis.component.DepthTraversalTypeAwareCrawler;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.projectanalysis.component.TypeAwareVisitorAdapter;
import org.sonar.ce.task.projectanalysis.period.Period;
import org.sonar.ce.task.projectanalysis.period.PeriodHolder;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.SnapshotDto;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT;
/**
* Persist analysis
*/
public class PersistAnalysisStep implements ComputationStep {
private final System2 system2;
private final DbClient dbClient;
private final TreeRootHolder treeRootHolder;
private final AnalysisMetadataHolder analysisMetadataHolder;
private final PeriodHolder periodHolder;
public PersistAnalysisStep(System2 system2, DbClient dbClient, TreeRootHolder treeRootHolder, AnalysisMetadataHolder analysisMetadataHolder, PeriodHolder periodHolder) {
this.system2 = system2;
this.dbClient = dbClient;
this.treeRootHolder = treeRootHolder;
this.analysisMetadataHolder = analysisMetadataHolder;
this.periodHolder = periodHolder;
}
@Override
public void execute(ComputationStep.Context context) {
try (DbSession dbSession = dbClient.openSession(false)) {
new DepthTraversalTypeAwareCrawler(
new PersistSnapshotsPathAwareVisitor(dbSession, analysisMetadataHolder.getAnalysisDate()))
.visit(treeRootHolder.getRoot());
dbSession.commit();
}
}
private class PersistSnapshotsPathAwareVisitor extends TypeAwareVisitorAdapter {
private final DbSession dbSession;
private final long analysisDate;
public PersistSnapshotsPathAwareVisitor(DbSession dbSession, long analysisDate) {
super(CrawlerDepthLimit.ROOTS, Order.PRE_ORDER);
this.dbSession = dbSession;
this.analysisDate = analysisDate;
}
@Override
public void visitProject(Component project) {
SnapshotDto snapshot = createAnalysis(analysisMetadataHolder.getUuid(), project);
updateSnapshotPeriods(snapshot);
persist(snapshot, dbSession);
}
@Override
public void visitView(Component view) {
SnapshotDto snapshot = createAnalysis(analysisMetadataHolder.getUuid(), view);
updateSnapshotPeriods(snapshot);
persist(snapshot, dbSession);
}
private void updateSnapshotPeriods(SnapshotDto snapshotDto) {
if (!periodHolder.hasPeriod()) {
return;
}
Period period = periodHolder.getPeriod();
snapshotDto.setPeriodMode(period.getMode());
snapshotDto.setPeriodParam(period.getModeParameter());
snapshotDto.setPeriodDate(period.getDate());
}
private SnapshotDto createAnalysis(String snapshotUuid, Component component) {
String componentUuid = component.getUuid();
String projectVersion = component.getType() == PROJECT ? component.getProjectAttributes().getProjectVersion() : null;
String buildString = component.getType() == PROJECT ? component.getProjectAttributes().getBuildString().orElse(null) : null;
SnapshotDto dto = new SnapshotDto()
.setUuid(snapshotUuid)
.setProjectVersion(projectVersion)
.setBuildString(buildString)
.setRootComponentUuid(componentUuid)
.setLast(false)
.setStatus(SnapshotDto.STATUS_UNPROCESSED)
.setCreatedAt(analysisDate)
.setBuildDate(system2.now());
if (component.getType() == PROJECT) {
component.getProjectAttributes().getScmRevisionId().ifPresent(dto::setRevision);
}
return dto;
}
private void persist(SnapshotDto snapshotDto, DbSession dbSession) {
dbClient.snapshotDao().insert(dbSession, snapshotDto);
}
}
@Override
public String getDescription() {
return "Persist analysis";
}
}
| 5,073 | 37.150376 | 171 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/PersistAnalysisWarningsStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.ArrayList;
import java.util.Collection;
import org.sonar.ce.task.log.CeTaskMessages;
import org.sonar.ce.task.projectanalysis.batch.BatchReportReader;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.core.util.CloseableIterator;
import org.sonar.scanner.protocol.output.ScannerReport;
/**
* Propagate analysis warnings from scanner report.
*/
public class PersistAnalysisWarningsStep implements ComputationStep {
static final String DESCRIPTION = "Propagate analysis warnings from scanner report";
private final BatchReportReader reportReader;
private final CeTaskMessages ceTaskMessages;
public PersistAnalysisWarningsStep(BatchReportReader reportReader, CeTaskMessages ceTaskMessages) {
this.reportReader = reportReader;
this.ceTaskMessages = ceTaskMessages;
}
@Override
public void execute(Context context) {
Collection<CeTaskMessages.Message> warnings = new ArrayList<>();
try (CloseableIterator<ScannerReport.AnalysisWarning> it = reportReader.readAnalysisWarnings()) {
it.forEachRemaining(w -> warnings.add(new CeTaskMessages.Message(w.getText(), w.getTimestamp())));
}
if (!warnings.isEmpty()) {
ceTaskMessages.addAll(warnings);
}
}
@Override
public String getDescription() {
return DESCRIPTION;
}
}
| 2,205 | 35.163934 | 104 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/PersistComponentsStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.resources.Scopes;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.component.BranchPersister;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit;
import org.sonar.ce.task.projectanalysis.component.MutableDisabledComponentsHolder;
import org.sonar.ce.task.projectanalysis.component.PathAwareCrawler;
import org.sonar.ce.task.projectanalysis.component.PathAwareVisitor;
import org.sonar.ce.task.projectanalysis.component.PathAwareVisitorAdapter;
import org.sonar.ce.task.projectanalysis.component.ProjectPersister;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ComponentUpdateDto;
import static java.util.Optional.ofNullable;
import static org.sonar.api.resources.Qualifiers.PROJECT;
import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.PRE_ORDER;
import static org.sonar.db.component.ComponentDto.UUID_PATH_OF_ROOT;
import static org.sonar.db.component.ComponentDto.formatUuidPathFromParent;
/**
* Persist report components
*/
public class PersistComponentsStep implements ComputationStep {
private final DbClient dbClient;
private final TreeRootHolder treeRootHolder;
private final System2 system2;
private final MutableDisabledComponentsHolder disabledComponentsHolder;
private final AnalysisMetadataHolder analysisMetadataHolder;
private final BranchPersister branchPersister;
private final ProjectPersister projectPersister;
public PersistComponentsStep(DbClient dbClient, TreeRootHolder treeRootHolder, System2 system2,
MutableDisabledComponentsHolder disabledComponentsHolder, AnalysisMetadataHolder analysisMetadataHolder,
BranchPersister branchPersister, ProjectPersister projectPersister) {
this.dbClient = dbClient;
this.treeRootHolder = treeRootHolder;
this.system2 = system2;
this.disabledComponentsHolder = disabledComponentsHolder;
this.analysisMetadataHolder = analysisMetadataHolder;
this.branchPersister = branchPersister;
this.projectPersister = projectPersister;
}
@Override
public String getDescription() {
return "Persist components";
}
@Override
public void execute(ComputationStep.Context context) {
try (DbSession dbSession = dbClient.openSession(false)) {
branchPersister.persist(dbSession);
projectPersister.persist(dbSession);
String projectUuid = treeRootHolder.getRoot().getUuid();
// safeguard, reset all rows to b-changed=false
dbClient.componentDao().resetBChangedForBranchUuid(dbSession, projectUuid);
Map<String, ComponentDto> existingDtosByUuids = indexExistingDtosByUuids(dbSession);
boolean isRootPrivate = isRootPrivate(treeRootHolder.getRoot(), existingDtosByUuids);
// Insert or update the components in database. They are removed from existingDtosByUuids
// at the same time.
new PathAwareCrawler<>(new PersistComponentStepsVisitor(existingDtosByUuids, dbSession))
.visit(treeRootHolder.getRoot());
disableRemainingComponents(dbSession, existingDtosByUuids.values());
dbClient.componentDao().setPrivateForBranchUuidWithoutAudit(dbSession, projectUuid, isRootPrivate);
dbSession.commit();
}
}
private void disableRemainingComponents(DbSession dbSession, Collection<ComponentDto> dtos) {
Set<String> uuids = dtos.stream()
.filter(ComponentDto::isEnabled)
.map(ComponentDto::uuid)
.collect(Collectors.toSet());
dbClient.componentDao().updateBEnabledToFalse(dbSession, uuids);
disabledComponentsHolder.setUuids(uuids);
}
private static boolean isRootPrivate(Component root, Map<String, ComponentDto> existingDtosByUuids) {
ComponentDto rootDto = existingDtosByUuids.get(root.getUuid());
if (rootDto == null) {
if (Component.Type.VIEW == root.getType()) {
return false;
}
throw new IllegalStateException(String.format("The project '%s' is not stored in the database, during a project analysis.", root.getKey()));
}
return rootDto.isPrivate();
}
/**
* Returns a mutable map of the components currently persisted in database for the project, including
* disabled components.
*/
private Map<String, ComponentDto> indexExistingDtosByUuids(DbSession session) {
return dbClient.componentDao().selectByBranchUuid(treeRootHolder.getRoot().getUuid(), session)
.stream()
.collect(Collectors.toMap(ComponentDto::uuid, Function.identity()));
}
private class PersistComponentStepsVisitor extends PathAwareVisitorAdapter<ComponentDtoHolder> {
private final Map<String, ComponentDto> existingComponentDtosByUuids;
private final DbSession dbSession;
PersistComponentStepsVisitor(Map<String, ComponentDto> existingComponentDtosByUuids, DbSession dbSession) {
super(
CrawlerDepthLimit.LEAVES,
PRE_ORDER,
new SimpleStackElementFactory<>() {
@Override
public ComponentDtoHolder createForAny(Component component) {
return new ComponentDtoHolder();
}
@Override
public ComponentDtoHolder createForFile(Component file) {
// no need to create holder for file since they are always leaves of the Component tree
return null;
}
@Override
public ComponentDtoHolder createForProjectView(Component projectView) {
// no need to create holder for file since they are always leaves of the Component tree
return null;
}
});
this.existingComponentDtosByUuids = existingComponentDtosByUuids;
this.dbSession = dbSession;
}
@Override
public void visitProject(Component project, Path<ComponentDtoHolder> path) {
ComponentDto dto = createForProject(project);
path.current().setDto(persistComponent(dto));
}
@Override
public void visitDirectory(Component directory, Path<ComponentDtoHolder> path) {
ComponentDto dto = createForDirectory(directory, path);
path.current().setDto(persistComponent(dto));
}
@Override
public void visitFile(Component file, Path<ComponentDtoHolder> path) {
ComponentDto dto = createForFile(file, path);
persistComponent(dto);
}
@Override
public void visitView(Component view, Path<ComponentDtoHolder> path) {
ComponentDto dto = createForView(view);
path.current().setDto(persistComponent(dto));
}
@Override
public void visitSubView(Component subView, Path<ComponentDtoHolder> path) {
ComponentDto dto = createForSubView(subView, path);
path.current().setDto(persistComponent(dto));
}
@Override
public void visitProjectView(Component projectView, Path<ComponentDtoHolder> path) {
ComponentDto dto = createForProjectView(projectView, path);
persistComponent(dto);
}
private ComponentDto persistComponent(ComponentDto componentDto) {
ComponentDto existingComponent = existingComponentDtosByUuids.remove(componentDto.uuid());
if (existingComponent == null) {
if (componentDto.qualifier().equals("APP") && componentDto.scope().equals("PRJ")) {
throw new IllegalStateException("Application should already exists: " + componentDto);
}
dbClient.componentDao().insert(dbSession, componentDto, analysisMetadataHolder.getBranch().isMain());
return componentDto;
}
Optional<ComponentUpdateDto> update = compareForUpdate(existingComponent, componentDto);
if (update.isPresent()) {
ComponentUpdateDto updateDto = update.get();
dbClient.componentDao().update(dbSession, updateDto, componentDto.qualifier());
// update the fields in memory in order the PathAwareVisitor.Path
// to be up-to-date
existingComponent.setKey(updateDto.getBKey());
existingComponent.setCopyComponentUuid(updateDto.getBCopyComponentUuid());
existingComponent.setDescription(updateDto.getBDescription());
existingComponent.setEnabled(updateDto.isBEnabled());
existingComponent.setUuidPath(updateDto.getBUuidPath());
existingComponent.setLanguage(updateDto.getBLanguage());
existingComponent.setLongName(updateDto.getBLongName());
existingComponent.setName(updateDto.getBName());
existingComponent.setPath(updateDto.getBPath());
// We don't have a b_scope. The applyBChangesForRootComponentUuid query is using a case ... when to infer scope from the qualifier
existingComponent.setScope(componentDto.scope());
existingComponent.setQualifier(updateDto.getBQualifier());
}
return existingComponent;
}
public ComponentDto createForProject(Component project) {
ComponentDto res = createBase(project);
res.setScope(Scopes.PROJECT);
res.setQualifier(PROJECT);
res.setName(project.getName());
res.setLongName(res.name());
res.setDescription(project.getDescription());
res.setBranchUuid(res.uuid());
res.setUuidPath(UUID_PATH_OF_ROOT);
return res;
}
public ComponentDto createForDirectory(Component directory, PathAwareVisitor.Path<ComponentDtoHolder> path) {
ComponentDto res = createBase(directory);
res.setScope(Scopes.DIRECTORY);
res.setQualifier(Qualifiers.DIRECTORY);
res.setName(directory.getShortName());
res.setLongName(directory.getName());
res.setPath(directory.getName());
setUuids(res, path);
return res;
}
public ComponentDto createForFile(Component file, PathAwareVisitor.Path<ComponentDtoHolder> path) {
ComponentDto res = createBase(file);
res.setScope(Scopes.FILE);
res.setQualifier(getFileQualifier(file));
res.setName(file.getShortName());
res.setLongName(file.getName());
res.setPath(file.getName());
res.setLanguage(file.getFileAttributes().getLanguageKey());
setUuids(res, path);
return res;
}
private ComponentDto createForView(Component view) {
ComponentDto res = createBase(view);
res.setScope(Scopes.PROJECT);
res.setQualifier(view.getViewAttributes().getType().getQualifier());
res.setName(view.getName());
res.setDescription(view.getDescription());
res.setLongName(res.name());
res.setBranchUuid(res.uuid());
res.setUuidPath(UUID_PATH_OF_ROOT);
return res;
}
private ComponentDto createForSubView(Component subView, PathAwareVisitor.Path<ComponentDtoHolder> path) {
ComponentDto res = createBase(subView);
res.setScope(Scopes.PROJECT);
res.setQualifier(Qualifiers.SUBVIEW);
res.setName(subView.getName());
res.setDescription(subView.getDescription());
res.setLongName(res.name());
res.setCopyComponentUuid(subView.getSubViewAttributes().getOriginalViewUuid());
setRootAndParentModule(res, path);
return res;
}
private ComponentDto createForProjectView(Component projectView, PathAwareVisitor.Path<ComponentDtoHolder> path) {
ComponentDto res = createBase(projectView);
res.setScope(Scopes.FILE);
res.setQualifier(PROJECT);
res.setName(projectView.getName());
res.setLongName(res.name());
res.setCopyComponentUuid(projectView.getProjectViewAttributes().getUuid());
setRootAndParentModule(res, path);
return res;
}
private ComponentDto createBase(Component component) {
String componentKey = component.getKey();
String componentUuid = component.getUuid();
ComponentDto componentDto = new ComponentDto();
componentDto.setUuid(componentUuid);
componentDto.setKey(componentKey);
componentDto.setEnabled(true);
componentDto.setCreatedAt(new Date(system2.now()));
return componentDto;
}
/**
* Applies to a node of type either SUBVIEW or PROJECT_VIEW
*/
private void setRootAndParentModule(ComponentDto res, PathAwareVisitor.Path<ComponentDtoHolder> path) {
ComponentDto rootDto = path.root().getDto();
res.setBranchUuid(rootDto.uuid());
ComponentDto parent = path.parent().getDto();
res.setUuidPath(formatUuidPathFromParent(parent));
}
}
/**
* Applies to a node of type either DIRECTORY or FILE
*/
private static void setUuids(ComponentDto componentDto, PathAwareVisitor.Path<ComponentDtoHolder> path) {
componentDto.setBranchUuid(path.root().getDto().uuid());
componentDto.setUuidPath(formatUuidPathFromParent(path.parent().getDto()));
}
private static Optional<ComponentUpdateDto> compareForUpdate(ComponentDto existing, ComponentDto target) {
boolean hasDifferences = !StringUtils.equals(existing.getCopyComponentUuid(), target.getCopyComponentUuid()) ||
!StringUtils.equals(existing.description(), target.description()) ||
!StringUtils.equals(existing.getKey(), target.getKey()) ||
!existing.isEnabled() ||
!StringUtils.equals(existing.getUuidPath(), target.getUuidPath()) ||
!StringUtils.equals(existing.language(), target.language()) ||
!StringUtils.equals(existing.longName(), target.longName()) ||
!StringUtils.equals(existing.name(), target.name()) ||
!StringUtils.equals(existing.path(), target.path()) ||
!StringUtils.equals(existing.scope(), target.scope()) ||
!StringUtils.equals(existing.qualifier(), target.qualifier());
ComponentUpdateDto update = null;
if (hasDifferences) {
update = ComponentUpdateDto
.copyFrom(target)
.setBChanged(true);
}
return ofNullable(update);
}
private static String getFileQualifier(Component component) {
return component.getFileAttributes().isUnitTest() ? Qualifiers.UNIT_TEST_FILE : Qualifiers.FILE;
}
private static class ComponentDtoHolder {
private ComponentDto dto;
public ComponentDto getDto() {
return dto;
}
public void setDto(ComponentDto dto) {
this.dto = dto;
}
}
}
| 15,479 | 37.992443 | 146 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/PersistCrossProjectDuplicationIndexStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.batch.BatchReportReader;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit;
import org.sonar.ce.task.projectanalysis.component.DepthTraversalTypeAwareCrawler;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.projectanalysis.component.TypeAwareVisitorAdapter;
import org.sonar.ce.task.projectanalysis.duplication.CrossProjectDuplicationStatusHolder;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.core.util.CloseableIterator;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.duplication.DuplicationUnitDto;
import org.sonar.scanner.protocol.output.ScannerReport;
import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.PRE_ORDER;
/**
* Persist cross project duplications text blocks into DUPLICATIONS_INDEX table
*/
public class PersistCrossProjectDuplicationIndexStep implements ComputationStep {
private final DbClient dbClient;
private final TreeRootHolder treeRootHolder;
private final AnalysisMetadataHolder analysisMetadataHolder;
private final BatchReportReader reportReader;
private final CrossProjectDuplicationStatusHolder crossProjectDuplicationStatusHolder;
public PersistCrossProjectDuplicationIndexStep(CrossProjectDuplicationStatusHolder crossProjectDuplicationStatusHolder, DbClient dbClient,
TreeRootHolder treeRootHolder, AnalysisMetadataHolder analysisMetadataHolder,
BatchReportReader reportReader) {
this.dbClient = dbClient;
this.treeRootHolder = treeRootHolder;
this.analysisMetadataHolder = analysisMetadataHolder;
this.reportReader = reportReader;
this.crossProjectDuplicationStatusHolder = crossProjectDuplicationStatusHolder;
}
@Override
public void execute(ComputationStep.Context context) {
if (!crossProjectDuplicationStatusHolder.isEnabled()) {
return;
}
try (DbSession dbSession = dbClient.openSession(true)) {
Component project = treeRootHolder.getRoot();
DuplicationVisitor visitor = new DuplicationVisitor(dbSession, analysisMetadataHolder.getUuid());
new DepthTraversalTypeAwareCrawler(visitor).visit(project);
dbSession.commit();
context.getStatistics().add("inserts", visitor.count);
}
}
private class DuplicationVisitor extends TypeAwareVisitorAdapter {
private final DbSession session;
private final String analysisUuid;
private int count = 0;
private DuplicationVisitor(DbSession session, String analysisUuid) {
super(CrawlerDepthLimit.FILE, PRE_ORDER);
this.session = session;
this.analysisUuid = analysisUuid;
}
@Override
public void visitFile(Component file) {
visitComponent(file);
}
private void visitComponent(Component component) {
readFromReport(component);
}
private void readFromReport(Component component) {
int indexInFile = 0;
try (CloseableIterator<ScannerReport.CpdTextBlock> blocks = reportReader.readCpdTextBlocks(component.getReportAttributes().getRef())) {
while (blocks.hasNext()) {
ScannerReport.CpdTextBlock block = blocks.next();
dbClient.duplicationDao().insert(
session,
new DuplicationUnitDto()
.setHash(block.getHash())
.setStartLine(block.getStartLine())
.setEndLine(block.getEndLine())
.setIndexInFile(indexInFile)
.setAnalysisUuid(analysisUuid)
.setComponentUuid(component.getUuid()));
indexInFile++;
}
}
count += indexInFile;
}
}
@Override
public String getDescription() {
return "Persist cross project duplications";
}
}
| 4,785 | 37.596774 | 141 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/PersistDuplicationDataStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringEscapeUtils;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit;
import org.sonar.ce.task.projectanalysis.component.DepthTraversalTypeAwareCrawler;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.projectanalysis.component.TypeAwareVisitorAdapter;
import org.sonar.ce.task.projectanalysis.duplication.CrossProjectDuplicate;
import org.sonar.ce.task.projectanalysis.duplication.Duplicate;
import org.sonar.ce.task.projectanalysis.duplication.Duplication;
import org.sonar.ce.task.projectanalysis.duplication.DuplicationRepository;
import org.sonar.ce.task.projectanalysis.duplication.InExtendedProjectDuplicate;
import org.sonar.ce.task.projectanalysis.duplication.InProjectDuplicate;
import org.sonar.ce.task.projectanalysis.duplication.InnerDuplicate;
import org.sonar.ce.task.projectanalysis.duplication.TextBlock;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import org.sonar.ce.task.projectanalysis.measure.MeasureToMeasureDto;
import org.sonar.ce.task.projectanalysis.metric.Metric;
import org.sonar.ce.task.projectanalysis.metric.MetricRepository;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.measure.LiveMeasureDto;
import static com.google.common.collect.Iterables.isEmpty;
import static org.sonar.api.measures.CoreMetrics.DUPLICATIONS_DATA_KEY;
import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.PRE_ORDER;
/**
* Compute duplication data measures on files, based on the {@link DuplicationRepository}
*/
public class PersistDuplicationDataStep implements ComputationStep {
private final DbClient dbClient;
private final TreeRootHolder treeRootHolder;
private final DuplicationRepository duplicationRepository;
private final MeasureToMeasureDto measureToMeasureDto;
private final Metric duplicationDataMetric;
public PersistDuplicationDataStep(DbClient dbClient, TreeRootHolder treeRootHolder, MetricRepository metricRepository,
DuplicationRepository duplicationRepository, MeasureToMeasureDto measureToMeasureDto) {
this.dbClient = dbClient;
this.treeRootHolder = treeRootHolder;
this.duplicationRepository = duplicationRepository;
this.measureToMeasureDto = measureToMeasureDto;
this.duplicationDataMetric = metricRepository.getByKey(DUPLICATIONS_DATA_KEY);
}
@Override
public void execute(ComputationStep.Context context) {
boolean supportUpsert = dbClient.getDatabase().getDialect().supportsUpsert();
// batch mode of DB session does not have benefits:
// - on postgres the multi-row upserts are the major optimization and have exactly the same
// performance between batch and non-batch sessions
// - on other dbs the sequence of inserts and updates, in order to emulate upserts,
// breaks the constraint of batch sessions (consecutive requests should have the same
// structure (same PreparedStatement))
try (DbSession dbSession = dbClient.openSession(false);
DuplicationVisitor visitor = new DuplicationVisitor(dbSession, supportUpsert)) {
new DepthTraversalTypeAwareCrawler(visitor).visit(treeRootHolder.getRoot());
context.getStatistics().add("insertsOrUpdates", visitor.insertsOrUpdates);
}
}
private class DuplicationVisitor extends TypeAwareVisitorAdapter implements AutoCloseable {
private final DbSession dbSession;
private final boolean supportUpsert;
private final List<LiveMeasureDto> nonPersistedBuffer = new ArrayList<>();
private int insertsOrUpdates = 0;
private DuplicationVisitor(DbSession dbSession, boolean supportUpsert) {
super(CrawlerDepthLimit.FILE, PRE_ORDER);
this.dbSession = dbSession;
this.supportUpsert = supportUpsert;
}
@Override
public void visitFile(Component file) {
Iterable<Duplication> duplications = duplicationRepository.getDuplications(file);
if (!isEmpty(duplications)) {
computeDuplications(file, duplications);
}
}
private void computeDuplications(Component component, Iterable<Duplication> duplications) {
Measure measure = generateMeasure(component.getKey(), duplications);
LiveMeasureDto dto = measureToMeasureDto.toLiveMeasureDto(measure, duplicationDataMetric, component);
nonPersistedBuffer.add(dto);
persist(false);
}
private void persist(boolean force) {
// Persist a bunch of 100 or less measures. That prevents from having more than 100 XML documents
// in memory. Consumption of memory does not explode with the number of duplications and is kept
// under control.
// Measures are upserted and transactions are committed every 100 rows (arbitrary number to
// maximize the performance of a multi-rows request on PostgreSQL).
// On PostgreSQL, a bunch of 100 measures is persisted into a single request (multi-rows upsert).
// On other DBs, measures are persisted one by one, with update-or-insert requests.
boolean shouldPersist = !nonPersistedBuffer.isEmpty() && (force || nonPersistedBuffer.size() > 100);
if (!shouldPersist) {
return;
}
if (supportUpsert) {
nonPersistedBuffer.forEach(d -> dbClient.liveMeasureDao().upsert(dbSession, d));
} else {
nonPersistedBuffer.forEach(d -> dbClient.liveMeasureDao().insertOrUpdate(dbSession, d));
}
insertsOrUpdates += nonPersistedBuffer.size();
nonPersistedBuffer.clear();
dbSession.commit();
}
@Override
public void close() {
// persist the measures remaining in the buffer
persist(true);
}
private Measure generateMeasure(String componentDbKey, Iterable<Duplication> duplications) {
StringBuilder xml = new StringBuilder();
xml.append("<duplications>");
for (Duplication duplication : duplications) {
xml.append("<g>");
appendDuplication(xml, componentDbKey, duplication.getOriginal(), false);
for (Duplicate duplicate : duplication.getDuplicates()) {
processDuplicationBlock(xml, duplicate, componentDbKey);
}
xml.append("</g>");
}
xml.append("</duplications>");
return Measure.newMeasureBuilder().create(xml.toString());
}
private void processDuplicationBlock(StringBuilder xml, Duplicate duplicate, String componentDbKey) {
if (duplicate instanceof InnerDuplicate) {
// Duplication is on the same file
appendDuplication(xml, componentDbKey, duplicate);
} else if (duplicate instanceof InExtendedProjectDuplicate inExtendedProjectDuplicate) {
// Duplication is on a different file that is not saved in the DB
appendDuplication(xml, inExtendedProjectDuplicate.getFile().getKey(), duplicate.getTextBlock(), true);
} else if (duplicate instanceof InProjectDuplicate inProjectDuplicate) {
// Duplication is on a different file
appendDuplication(xml, inProjectDuplicate.getFile().getKey(), duplicate);
} else if (duplicate instanceof CrossProjectDuplicate crossProjectDuplicate) {
// Only componentKey is set for cross project duplications
String crossProjectComponentKey = crossProjectDuplicate.getFileKey();
appendDuplication(xml, crossProjectComponentKey, duplicate);
} else {
throw new IllegalArgumentException("Unsupported type of Duplicate " + duplicate.getClass().getName());
}
}
private void appendDuplication(StringBuilder xml, String componentDbKey, Duplicate duplicate) {
appendDuplication(xml, componentDbKey, duplicate.getTextBlock(), false);
}
private void appendDuplication(StringBuilder xml, String componentDbKey, TextBlock textBlock, boolean disableLink) {
int length = textBlock.getEnd() - textBlock.getStart() + 1;
xml.append("<b s=\"").append(textBlock.getStart())
.append("\" l=\"").append(length)
.append("\" t=\"").append(disableLink)
.append("\" r=\"").append(StringEscapeUtils.escapeXml(componentDbKey))
.append("\"/>");
}
}
@Override
public String getDescription() {
return "Persist duplication data";
}
}
| 9,258 | 46 | 120 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/PersistEventsStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.StreamSupport;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.projectanalysis.event.Event;
import org.sonar.ce.task.projectanalysis.event.EventRepository;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.core.util.UuidFactory;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.event.EventDto;
public class PersistEventsStep implements ComputationStep {
private final DbClient dbClient;
private final System2 system2;
private final AnalysisMetadataHolder analysisMetadataHolder;
private final TreeRootHolder treeRootHolder;
private final EventRepository eventRepository;
private final UuidFactory uuidFactory;
public PersistEventsStep(DbClient dbClient, System2 system2, TreeRootHolder treeRootHolder, AnalysisMetadataHolder analysisMetadataHolder,
EventRepository eventRepository, UuidFactory uuidFactory) {
this.dbClient = dbClient;
this.system2 = system2;
this.treeRootHolder = treeRootHolder;
this.analysisMetadataHolder = analysisMetadataHolder;
this.eventRepository = eventRepository;
this.uuidFactory = uuidFactory;
}
@Override
public void execute(ComputationStep.Context context) {
try (DbSession dbSession = dbClient.openSession(false)) {
long analysisDate = analysisMetadataHolder.getAnalysisDate();
new PersistEvent(dbSession, analysisDate).process(treeRootHolder.getRoot());
dbSession.commit();
}
}
@Override
public String getDescription() {
return "Persist events";
}
private class PersistEvent {
private final DbSession session;
private final long analysisDate;
PersistEvent(DbSession session, long analysisDate) {
this.session = session;
this.analysisDate = analysisDate;
}
public void process(Component project) {
processEvents(session, project, analysisDate);
saveVersionEvent(session, project, analysisDate);
}
private void processEvents(DbSession session, Component component, Long analysisDate) {
Function<Event, EventDto> eventToEventDto = event -> newBaseEvent(component, analysisDate)
.setName(event.getName())
.setCategory(convertCategory(event.getCategory()))
.setDescription(event.getDescription())
.setData(event.getData());
// FIXME bulk insert
for (EventDto batchEventDto : StreamSupport.stream(eventRepository.getEvents().spliterator(), false).map(eventToEventDto).toList()) {
dbClient.eventDao().insert(session, batchEventDto);
}
}
private void saveVersionEvent(DbSession session, Component component, Long analysisDate) {
String projectVersion = component.getProjectAttributes().getProjectVersion();
deletePreviousEventsHavingSameVersion(session, projectVersion, component);
dbClient.eventDao().insert(session, newBaseEvent(component, analysisDate)
.setName(projectVersion)
.setCategory(EventDto.CATEGORY_VERSION));
}
private void deletePreviousEventsHavingSameVersion(DbSession session, String version, Component component) {
for (EventDto dto : dbClient.eventDao().selectByComponentUuid(session, component.getUuid())) {
if (Objects.equals(dto.getCategory(), EventDto.CATEGORY_VERSION) && Objects.equals(dto.getName(), version)) {
dbClient.eventDao().delete(session, dto.getUuid());
}
}
}
private EventDto newBaseEvent(Component component, Long analysisDate) {
return new EventDto()
.setUuid(uuidFactory.create())
.setAnalysisUuid(analysisMetadataHolder.getUuid())
.setComponentUuid(component.getUuid())
.setCreatedAt(system2.now())
.setDate(analysisDate);
}
private String convertCategory(Event.Category category) {
switch (category) {
case ALERT:
return EventDto.CATEGORY_ALERT;
case PROFILE:
return EventDto.CATEGORY_PROFILE;
default:
throw new IllegalArgumentException(String.format("Unsupported category %s", category.name()));
}
}
}
}
| 5,254 | 38.216418 | 140 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/PersistIssuesStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectanalysis.issue.ProtoIssueCache;
import org.sonar.ce.task.projectanalysis.issue.RuleRepository;
import org.sonar.ce.task.projectanalysis.issue.UpdateConflictResolver;
import org.sonar.ce.task.projectanalysis.period.PeriodHolder;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.util.CloseableIterator;
import org.sonar.core.util.UuidFactory;
import org.sonar.db.BatchSession;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.issue.IssueChangeMapper;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.issue.IssueMapper;
import org.sonar.db.issue.NewCodeReferenceIssueDto;
import org.sonar.db.newcodeperiod.NewCodePeriodType;
import org.sonar.server.issue.IssueStorage;
import static org.sonar.core.util.FileUtils.humanReadableByteCountSI;
public class PersistIssuesStep implements ComputationStep {
// holding up to 1000 DefaultIssue (max size of addedIssues and updatedIssues at any given time) in memory should not
// be a problem while making sure we leverage extensively the batch feature to speed up persistence
private static final int ISSUE_BATCHING_SIZE = BatchSession.MAX_BATCH_SIZE * 2;
private final DbClient dbClient;
private final System2 system2;
private final UpdateConflictResolver conflictResolver;
private final RuleRepository ruleRepository;
private final PeriodHolder periodHolder;
private final ProtoIssueCache protoIssueCache;
private final IssueStorage issueStorage;
private final UuidFactory uuidFactory;
public PersistIssuesStep(DbClient dbClient, System2 system2, UpdateConflictResolver conflictResolver,
RuleRepository ruleRepository, PeriodHolder periodHolder, ProtoIssueCache protoIssueCache, IssueStorage issueStorage,
UuidFactory uuidFactory) {
this.dbClient = dbClient;
this.system2 = system2;
this.conflictResolver = conflictResolver;
this.ruleRepository = ruleRepository;
this.periodHolder = periodHolder;
this.protoIssueCache = protoIssueCache;
this.issueStorage = issueStorage;
this.uuidFactory = uuidFactory;
}
@Override
public void execute(ComputationStep.Context context) {
context.getStatistics().add("cacheSize", humanReadableByteCountSI(protoIssueCache.fileSize()));
IssueStatistics statistics = new IssueStatistics();
try (DbSession dbSession = dbClient.openSession(true);
CloseableIterator<DefaultIssue> issues = protoIssueCache.traverse()) {
List<DefaultIssue> addedIssues = new ArrayList<>(ISSUE_BATCHING_SIZE);
List<DefaultIssue> updatedIssues = new ArrayList<>(ISSUE_BATCHING_SIZE);
List<DefaultIssue> noLongerNewIssues = new ArrayList<>(ISSUE_BATCHING_SIZE);
List<DefaultIssue> newCodeIssuesToMigrate = new ArrayList<>(ISSUE_BATCHING_SIZE);
IssueMapper mapper = dbSession.getMapper(IssueMapper.class);
IssueChangeMapper changeMapper = dbSession.getMapper(IssueChangeMapper.class);
while (issues.hasNext()) {
DefaultIssue issue = issues.next();
if (issue.isNew() || issue.isCopied()) {
addedIssues.add(issue);
if (addedIssues.size() >= ISSUE_BATCHING_SIZE) {
persistNewIssues(statistics, addedIssues, mapper, changeMapper);
addedIssues.clear();
}
} else if (issue.isChanged()) {
updatedIssues.add(issue);
if (updatedIssues.size() >= ISSUE_BATCHING_SIZE) {
persistUpdatedIssues(statistics, updatedIssues, mapper, changeMapper);
updatedIssues.clear();
}
} else if (isOnBranchUsingReferenceBranch() && issue.isNoLongerNewCodeReferenceIssue()) {
noLongerNewIssues.add(issue);
if (noLongerNewIssues.size() >= ISSUE_BATCHING_SIZE) {
persistNoLongerNewIssues(statistics, noLongerNewIssues, mapper);
noLongerNewIssues.clear();
}
} else if (isOnBranchUsingReferenceBranch() && issue.isToBeMigratedAsNewCodeReferenceIssue()) {
newCodeIssuesToMigrate.add(issue);
if (newCodeIssuesToMigrate.size() >= ISSUE_BATCHING_SIZE) {
persistNewCodeIssuesToMigrate(statistics, newCodeIssuesToMigrate, mapper);
newCodeIssuesToMigrate.clear();
}
}
}
persistNewIssues(statistics, addedIssues, mapper, changeMapper);
persistUpdatedIssues(statistics, updatedIssues, mapper, changeMapper);
persistNoLongerNewIssues(statistics, noLongerNewIssues, mapper);
persistNewCodeIssuesToMigrate(statistics, newCodeIssuesToMigrate, mapper);
flushSession(dbSession);
} finally {
statistics.dumpTo(context);
}
}
private void persistNewIssues(IssueStatistics statistics, List<DefaultIssue> addedIssues, IssueMapper mapper, IssueChangeMapper changeMapper) {
if (addedIssues.isEmpty()) {
return;
}
long now = system2.now();
addedIssues.forEach(i -> {
String ruleUuid = ruleRepository.getByKey(i.ruleKey()).getUuid();
IssueDto dto = IssueDto.toDtoForComputationInsert(i, ruleUuid, now);
mapper.insert(dto);
if (isOnBranchUsingReferenceBranch() && i.isOnChangedLine()) {
mapper.insertAsNewCodeOnReferenceBranch(NewCodeReferenceIssueDto.fromIssueDto(dto, now, uuidFactory));
}
statistics.inserts++;
});
addedIssues.forEach(i -> issueStorage.insertChanges(changeMapper, i, uuidFactory));
}
private void persistUpdatedIssues(IssueStatistics statistics, List<DefaultIssue> updatedIssues, IssueMapper mapper, IssueChangeMapper changeMapper) {
if (updatedIssues.isEmpty()) {
return;
}
long now = system2.now();
updatedIssues.forEach(i -> {
IssueDto dto = IssueDto.toDtoForUpdate(i, now);
mapper.updateIfBeforeSelectedDate(dto);
statistics.updates++;
});
// retrieve those of the updatedIssues which have not been updated and apply conflictResolver on them
List<String> updatedIssueKeys = updatedIssues.stream().map(DefaultIssue::key).toList();
List<IssueDto> conflictIssueKeys = mapper.selectByKeysIfNotUpdatedAt(updatedIssueKeys, now);
if (!conflictIssueKeys.isEmpty()) {
Map<String, DefaultIssue> issuesByKeys = updatedIssues.stream().collect(Collectors.toMap(DefaultIssue::key, Function.identity()));
conflictIssueKeys
.forEach(dbIssue -> {
DefaultIssue updatedIssue = issuesByKeys.get(dbIssue.getKey());
conflictResolver.resolve(updatedIssue, dbIssue, mapper);
statistics.merged++;
});
}
updatedIssues.forEach(i -> issueStorage.insertChanges(changeMapper, i, uuidFactory));
}
private static void persistNoLongerNewIssues(IssueStatistics statistics, List<DefaultIssue> noLongerNewIssues, IssueMapper mapper) {
if (noLongerNewIssues.isEmpty()) {
return;
}
noLongerNewIssues.forEach(i -> {
mapper.deleteAsNewCodeOnReferenceBranch(i.key());
statistics.updates++;
});
}
private void persistNewCodeIssuesToMigrate(IssueStatistics statistics, List<DefaultIssue> newCodeIssuesToMigrate, IssueMapper mapper) {
if (newCodeIssuesToMigrate.isEmpty()) {
return;
}
long now = system2.now();
newCodeIssuesToMigrate.forEach(i -> {
mapper.insertAsNewCodeOnReferenceBranch(NewCodeReferenceIssueDto.fromIssueKey(i.key(), now, uuidFactory));
statistics.updates++;
});
}
private static void flushSession(DbSession dbSession) {
dbSession.flushStatements();
dbSession.commit();
}
private boolean isOnBranchUsingReferenceBranch() {
if (periodHolder.hasPeriod()) {
return periodHolder.getPeriod().getMode().equals(NewCodePeriodType.REFERENCE_BRANCH.name());
}
return false;
}
@Override
public String getDescription() {
return "Persist issues";
}
private static class IssueStatistics {
private int inserts = 0;
private int updates = 0;
private int merged = 0;
private void dumpTo(ComputationStep.Context context) {
context.getStatistics()
.add("inserts", String.valueOf(inserts))
.add("updates", String.valueOf(updates))
.add("merged", String.valueOf(merged));
}
}
}
| 9,301 | 39.977974 | 151 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/PersistLiveMeasuresStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import javax.annotation.Nonnull;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit;
import org.sonar.ce.task.projectanalysis.component.DepthTraversalTypeAwareCrawler;
import org.sonar.ce.task.projectanalysis.component.FileStatuses;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.projectanalysis.component.TypeAwareVisitorAdapter;
import org.sonar.ce.task.projectanalysis.measure.BestValueOptimization;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import org.sonar.ce.task.projectanalysis.measure.MeasureRepository;
import org.sonar.ce.task.projectanalysis.measure.MeasureToMeasureDto;
import org.sonar.ce.task.projectanalysis.metric.Metric;
import org.sonar.ce.task.projectanalysis.metric.MetricRepository;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.measure.LiveMeasureDto;
import static org.sonar.api.measures.CoreMetrics.BLOCKER_VIOLATIONS_KEY;
import static org.sonar.api.measures.CoreMetrics.BUGS_KEY;
import static org.sonar.api.measures.CoreMetrics.CLASSES_KEY;
import static org.sonar.api.measures.CoreMetrics.CLASS_COMPLEXITY_KEY;
import static org.sonar.api.measures.CoreMetrics.CODE_SMELLS_KEY;
import static org.sonar.api.measures.CoreMetrics.COGNITIVE_COMPLEXITY_KEY;
import static org.sonar.api.measures.CoreMetrics.COMMENT_LINES_DENSITY_KEY;
import static org.sonar.api.measures.CoreMetrics.COMMENT_LINES_KEY;
import static org.sonar.api.measures.CoreMetrics.COMPLEXITY_IN_CLASSES_KEY;
import static org.sonar.api.measures.CoreMetrics.COMPLEXITY_IN_FUNCTIONS_KEY;
import static org.sonar.api.measures.CoreMetrics.COMPLEXITY_KEY;
import static org.sonar.api.measures.CoreMetrics.CONFIRMED_ISSUES_KEY;
import static org.sonar.api.measures.CoreMetrics.CRITICAL_VIOLATIONS_KEY;
import static org.sonar.api.measures.CoreMetrics.DEVELOPMENT_COST_KEY;
import static org.sonar.api.measures.CoreMetrics.EFFORT_TO_REACH_MAINTAINABILITY_RATING_A_KEY;
import static org.sonar.api.measures.CoreMetrics.FALSE_POSITIVE_ISSUES_KEY;
import static org.sonar.api.measures.CoreMetrics.FILES_KEY;
import static org.sonar.api.measures.CoreMetrics.FILE_COMPLEXITY_DISTRIBUTION_KEY;
import static org.sonar.api.measures.CoreMetrics.FILE_COMPLEXITY_KEY;
import static org.sonar.api.measures.CoreMetrics.FUNCTIONS_KEY;
import static org.sonar.api.measures.CoreMetrics.FUNCTION_COMPLEXITY_DISTRIBUTION_KEY;
import static org.sonar.api.measures.CoreMetrics.FUNCTION_COMPLEXITY_KEY;
import static org.sonar.api.measures.CoreMetrics.GENERATED_LINES_KEY;
import static org.sonar.api.measures.CoreMetrics.GENERATED_NCLOC_KEY;
import static org.sonar.api.measures.CoreMetrics.INFO_VIOLATIONS_KEY;
import static org.sonar.api.measures.CoreMetrics.LINES_KEY;
import static org.sonar.api.measures.CoreMetrics.MAJOR_VIOLATIONS_KEY;
import static org.sonar.api.measures.CoreMetrics.MINOR_VIOLATIONS_KEY;
import static org.sonar.api.measures.CoreMetrics.NCLOC_DATA_KEY;
import static org.sonar.api.measures.CoreMetrics.NCLOC_KEY;
import static org.sonar.api.measures.CoreMetrics.NCLOC_LANGUAGE_DISTRIBUTION_KEY;
import static org.sonar.api.measures.CoreMetrics.OPEN_ISSUES_KEY;
import static org.sonar.api.measures.CoreMetrics.RELIABILITY_RATING_KEY;
import static org.sonar.api.measures.CoreMetrics.RELIABILITY_REMEDIATION_EFFORT_KEY;
import static org.sonar.api.measures.CoreMetrics.REOPENED_ISSUES_KEY;
import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_KEY;
import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_REVIEWED_KEY;
import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_REVIEWED_STATUS_KEY;
import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_TO_REVIEW_STATUS_KEY;
import static org.sonar.api.measures.CoreMetrics.SECURITY_RATING_KEY;
import static org.sonar.api.measures.CoreMetrics.SECURITY_REMEDIATION_EFFORT_KEY;
import static org.sonar.api.measures.CoreMetrics.SECURITY_REVIEW_RATING_KEY;
import static org.sonar.api.measures.CoreMetrics.SQALE_DEBT_RATIO_KEY;
import static org.sonar.api.measures.CoreMetrics.SQALE_RATING_KEY;
import static org.sonar.api.measures.CoreMetrics.STATEMENTS_KEY;
import static org.sonar.api.measures.CoreMetrics.TECHNICAL_DEBT_KEY;
import static org.sonar.api.measures.CoreMetrics.VIOLATIONS_KEY;
import static org.sonar.api.measures.CoreMetrics.VULNERABILITIES_KEY;
import static org.sonar.api.measures.CoreMetrics.WONT_FIX_ISSUES_KEY;
import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.PRE_ORDER;
public class PersistLiveMeasuresStep implements ComputationStep {
/**
* List of metrics that should not be persisted on file measure.
*/
private static final Set<String> NOT_TO_PERSIST_ON_FILE_METRIC_KEYS = Set.of(FILE_COMPLEXITY_DISTRIBUTION_KEY, FUNCTION_COMPLEXITY_DISTRIBUTION_KEY);
private static final Set<String> NOT_TO_PERSIST_ON_UNCHANGED_FILES = Set.of(
BLOCKER_VIOLATIONS_KEY, BUGS_KEY, CLASS_COMPLEXITY_KEY, CLASSES_KEY, CODE_SMELLS_KEY, COGNITIVE_COMPLEXITY_KEY, COMMENT_LINES_KEY, COMMENT_LINES_DENSITY_KEY,
COMPLEXITY_KEY, COMPLEXITY_IN_CLASSES_KEY, COMPLEXITY_IN_FUNCTIONS_KEY, CONFIRMED_ISSUES_KEY, CRITICAL_VIOLATIONS_KEY, DEVELOPMENT_COST_KEY,
EFFORT_TO_REACH_MAINTAINABILITY_RATING_A_KEY, FALSE_POSITIVE_ISSUES_KEY, FILE_COMPLEXITY_KEY, FILE_COMPLEXITY_DISTRIBUTION_KEY, FILES_KEY, FUNCTION_COMPLEXITY_KEY,
FUNCTION_COMPLEXITY_DISTRIBUTION_KEY, FUNCTIONS_KEY, GENERATED_LINES_KEY, GENERATED_NCLOC_KEY, INFO_VIOLATIONS_KEY, LINES_KEY,
MAJOR_VIOLATIONS_KEY, MINOR_VIOLATIONS_KEY, NCLOC_KEY, NCLOC_DATA_KEY, NCLOC_LANGUAGE_DISTRIBUTION_KEY, OPEN_ISSUES_KEY, RELIABILITY_RATING_KEY,
RELIABILITY_REMEDIATION_EFFORT_KEY, REOPENED_ISSUES_KEY, SECURITY_HOTSPOTS_KEY, SECURITY_HOTSPOTS_REVIEWED_KEY, SECURITY_HOTSPOTS_REVIEWED_STATUS_KEY,
SECURITY_HOTSPOTS_TO_REVIEW_STATUS_KEY, SECURITY_RATING_KEY, SECURITY_REMEDIATION_EFFORT_KEY, SECURITY_REVIEW_RATING_KEY, SQALE_DEBT_RATIO_KEY, TECHNICAL_DEBT_KEY,
SQALE_RATING_KEY, STATEMENTS_KEY, VIOLATIONS_KEY, VULNERABILITIES_KEY, WONT_FIX_ISSUES_KEY
);
private final DbClient dbClient;
private final MetricRepository metricRepository;
private final MeasureToMeasureDto measureToMeasureDto;
private final TreeRootHolder treeRootHolder;
private final MeasureRepository measureRepository;
private final Optional<FileStatuses> fileStatuses;
public PersistLiveMeasuresStep(DbClient dbClient, MetricRepository metricRepository, MeasureToMeasureDto measureToMeasureDto,
TreeRootHolder treeRootHolder, MeasureRepository measureRepository, Optional<FileStatuses> fileStatuses) {
this.dbClient = dbClient;
this.metricRepository = metricRepository;
this.measureToMeasureDto = measureToMeasureDto;
this.treeRootHolder = treeRootHolder;
this.measureRepository = measureRepository;
this.fileStatuses = fileStatuses;
}
@Override
public String getDescription() {
return "Persist live measures";
}
@Override
public void execute(ComputationStep.Context context) {
boolean supportUpsert = dbClient.getDatabase().getDialect().supportsUpsert();
try (DbSession dbSession = dbClient.openSession(true)) {
Component root = treeRootHolder.getRoot();
MeasureVisitor visitor = new MeasureVisitor(dbSession, supportUpsert);
new DepthTraversalTypeAwareCrawler(visitor).visit(root);
dbSession.commit();
context.getStatistics()
.add("insertsOrUpdates", visitor.insertsOrUpdates);
}
}
private class MeasureVisitor extends TypeAwareVisitorAdapter {
private final DbSession dbSession;
private final boolean supportUpsert;
private int insertsOrUpdates = 0;
private MeasureVisitor(DbSession dbSession, boolean supportUpsert) {
super(CrawlerDepthLimit.LEAVES, PRE_ORDER);
this.supportUpsert = supportUpsert;
this.dbSession = dbSession;
}
@Override
public void visitAny(Component component) {
List<String> metricUuids = new ArrayList<>();
List<String> keptMetricUuids = new ArrayList<>();
Map<String, Measure> measures = measureRepository.getRawMeasures(component);
List<LiveMeasureDto> dtos = new ArrayList<>();
for (Map.Entry<String, Measure> measuresByMetricKey : measures.entrySet()) {
String metricKey = measuresByMetricKey.getKey();
if (NOT_TO_PERSIST_ON_FILE_METRIC_KEYS.contains(metricKey) ) {
continue;
}
Metric metric = metricRepository.getByKey(metricKey);
Predicate<Measure> notBestValueOptimized = BestValueOptimization.from(metric, component).negate();
Measure m = measuresByMetricKey.getValue();
if (!NonEmptyMeasure.INSTANCE.test(m) || !notBestValueOptimized.test(m)) {
continue;
}
metricUuids.add(metric.getUuid());
if (shouldSkipMetricOnUnchangedFile(component, metricKey)) {
keptMetricUuids.add(metric.getUuid());
continue;
}
LiveMeasureDto lm = measureToMeasureDto.toLiveMeasureDto(m, metric, component);
dtos.add(lm);
}
List<String> excludedMetricUuids = supportUpsert ? metricUuids : keptMetricUuids;
deleteNonexistentMeasures(dbSession, component.getUuid(), excludedMetricUuids);
dtos.forEach(dto -> insertMeasureOptimally(dbSession, dto));
dbSession.commit();
insertsOrUpdates += dtos.size();
}
private void deleteNonexistentMeasures(DbSession dbSession, String componentUuid, List<String> excludedMetricUuids) {
// The measures that no longer exist on the component must be deleted, for example
// when the coverage on a file goes to the "best value" 100%.
// The measures on deleted components are deleted by the step PurgeDatastoresStep
dbClient.liveMeasureDao().deleteByComponentUuidExcludingMetricUuids(dbSession, componentUuid, excludedMetricUuids);
}
private void insertMeasureOptimally(DbSession dbSession, LiveMeasureDto dto) {
if (supportUpsert) {
dbClient.liveMeasureDao().upsert(dbSession, dto);
} else {
dbClient.liveMeasureDao().insert(dbSession, dto);
}
}
private boolean shouldSkipMetricOnUnchangedFile(Component component, String metricKey) {
return component.getType() == Component.Type.FILE && fileStatuses.isPresent() &&
fileStatuses.get().isDataUnchanged(component) && NOT_TO_PERSIST_ON_UNCHANGED_FILES.contains(metricKey);
}
}
private enum NonEmptyMeasure implements Predicate<Measure> {
INSTANCE;
@Override
public boolean test(@Nonnull Measure input) {
return input.getValueType() != Measure.ValueType.NO_VALUE || input.getData() != null;
}
}
}
| 11,851 | 51.910714 | 167 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/PersistMeasuresStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.Map;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit;
import org.sonar.ce.task.projectanalysis.component.DepthTraversalTypeAwareCrawler;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.projectanalysis.component.TypeAwareVisitorAdapter;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import org.sonar.ce.task.projectanalysis.measure.MeasureRepository;
import org.sonar.ce.task.projectanalysis.measure.MeasureToMeasureDto;
import org.sonar.ce.task.projectanalysis.metric.Metric;
import org.sonar.ce.task.projectanalysis.metric.MetricRepository;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.measure.MeasureDao;
import org.sonar.db.measure.MeasureDto;
import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.PRE_ORDER;
public class PersistMeasuresStep implements ComputationStep {
private final DbClient dbClient;
private final MetricRepository metricRepository;
private final MeasureToMeasureDto measureToMeasureDto;
private final TreeRootHolder treeRootHolder;
private final MeasureRepository measureRepository;
public PersistMeasuresStep(DbClient dbClient, MetricRepository metricRepository, MeasureToMeasureDto measureToMeasureDto, TreeRootHolder treeRootHolder,
MeasureRepository measureRepository) {
this.dbClient = dbClient;
this.metricRepository = metricRepository;
this.measureToMeasureDto = measureToMeasureDto;
this.treeRootHolder = treeRootHolder;
this.measureRepository = measureRepository;
}
@Override
public String getDescription() {
return "Persist measures";
}
@Override
public void execute(ComputationStep.Context context) {
try (DbSession dbSession = dbClient.openSession(true)) {
MeasureVisitor visitor = new MeasureVisitor(dbSession);
new DepthTraversalTypeAwareCrawler(visitor).visit(treeRootHolder.getRoot());
dbSession.commit();
context.getStatistics().add("inserts", visitor.inserts);
}
}
private class MeasureVisitor extends TypeAwareVisitorAdapter {
private final DbSession session;
private int inserts = 0;
private MeasureVisitor(DbSession session) {
super(CrawlerDepthLimit.LEAVES, PRE_ORDER);
this.session = session;
}
@Override
public void visitProject(Component project) {
persistMeasures(project);
}
@Override
public void visitView(Component view) {
persistMeasures(view);
}
@Override
public void visitSubView(Component subView) {
persistMeasures(subView);
}
@Override
public void visitProjectView(Component projectView) {
// measures of project copies are never read. No need to persist them.
}
private void persistMeasures(Component component) {
Map<String, Measure> measures = measureRepository.getRawMeasures(component);
MeasureDao measureDao = dbClient.measureDao();
for (Map.Entry<String, Measure> e : measures.entrySet()) {
Measure measure = e.getValue();
if (measure.isEmpty()) {
continue;
}
String metricKey = e.getKey();
Metric metric = metricRepository.getByKey(metricKey);
if (!metric.isDeleteHistoricalData()) {
MeasureDto measureDto = measureToMeasureDto.toMeasureDto(measure, metric, component);
measureDao.insert(session, measureDto);
inserts++;
}
}
}
}
}
| 4,488 | 35.795082 | 154 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/PersistProjectLinksStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.batch.BatchReportReader;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.core.util.UuidFactory;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ProjectLinkDto;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.protocol.output.ScannerReport.ComponentLink.ComponentLinkType;
import static com.google.common.base.Preconditions.checkArgument;
public class PersistProjectLinksStep implements ComputationStep {
private static final Map<ComponentLinkType, String> typesConverter = Map.of(
ComponentLinkType.HOME, ProjectLinkDto.TYPE_HOME_PAGE,
ComponentLinkType.SCM, ProjectLinkDto.TYPE_SOURCES,
ComponentLinkType.CI, ProjectLinkDto.TYPE_CI,
ComponentLinkType.ISSUE, ProjectLinkDto.TYPE_ISSUE_TRACKER);
private final AnalysisMetadataHolder analysisMetadataHolder;
private final DbClient dbClient;
private final TreeRootHolder treeRootHolder;
private final BatchReportReader reportReader;
private final UuidFactory uuidFactory;
public PersistProjectLinksStep(AnalysisMetadataHolder analysisMetadataHolder, DbClient dbClient, TreeRootHolder treeRootHolder,
BatchReportReader reportReader, UuidFactory uuidFactory) {
this.analysisMetadataHolder = analysisMetadataHolder;
this.dbClient = dbClient;
this.treeRootHolder = treeRootHolder;
this.reportReader = reportReader;
this.uuidFactory = uuidFactory;
}
@Override
public void execute(ComputationStep.Context context) {
if (!analysisMetadataHolder.getBranch().isMain()) {
return;
}
try (DbSession session = dbClient.openSession(false)) {
Component rootComponent = treeRootHolder.getRoot();
ScannerReport.Component batchComponent = reportReader.readComponent(rootComponent.getReportAttributes().getRef());
List<ProjectLinkDto> previousLinks = dbClient.projectLinkDao().selectByProjectUuid(session, analysisMetadataHolder.getProject().getUuid());
mergeLinks(session, analysisMetadataHolder.getProject().getUuid(), batchComponent.getLinkList(), previousLinks);
session.commit();
}
}
private void mergeLinks(DbSession session, String projectUuid, List<ScannerReport.ComponentLink> links, List<ProjectLinkDto> previousLinks) {
Set<String> linkType = new HashSet<>();
links.forEach(
link -> {
String type = convertType(link.getType());
checkArgument(!linkType.contains(type), "Link of type '%s' has already been declared on component '%s'", type, projectUuid);
linkType.add(type);
Optional<ProjectLinkDto> previousLink = previousLinks.stream()
.filter(input -> input != null && input.getType().equals(convertType(link.getType())))
.findFirst();
if (previousLink.isPresent()) {
previousLink.get().setHref(link.getHref());
dbClient.projectLinkDao().update(session, previousLink.get());
} else {
dbClient.projectLinkDao().insert(session,
new ProjectLinkDto()
.setUuid(uuidFactory.create())
.setProjectUuid(projectUuid)
.setType(type)
.setHref(link.getHref()));
}
});
previousLinks.stream()
.filter(dto -> !linkType.contains(dto.getType()))
.filter(dto -> ProjectLinkDto.PROVIDED_TYPES.contains(dto.getType()))
.forEach(dto -> dbClient.projectLinkDao().delete(session, dto.getUuid()));
}
private static String convertType(ComponentLinkType reportType) {
String type = typesConverter.get(reportType);
checkArgument(type != null, "Unsupported type %s", reportType.name());
return type;
}
@Override
public String getDescription() {
return "Persist project links";
}
}
| 5,009 | 41.457627 | 145 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/PersistPushEventsStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.projectanalysis.issue.ProtoIssueCache;
import org.sonar.ce.task.projectanalysis.pushevent.PushEventFactory;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.util.CloseableIterator;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.pushevent.PushEventDto;
public class PersistPushEventsStep implements ComputationStep {
private static final int MAX_BATCH_SIZE = 250;
private static final Logger LOGGER = LoggerFactory.getLogger(PersistPushEventsStep.class);
private final DbClient dbClient;
private final ProtoIssueCache protoIssueCache;
private final PushEventFactory pushEventFactory;
private final TreeRootHolder treeRootHolder;
public PersistPushEventsStep(DbClient dbClient,
ProtoIssueCache protoIssueCache,
PushEventFactory pushEventFactory,
TreeRootHolder treeRootHolder) {
this.dbClient = dbClient;
this.protoIssueCache = protoIssueCache;
this.pushEventFactory = pushEventFactory;
this.treeRootHolder = treeRootHolder;
}
@Override
public void execute(Context context) {
try (DbSession dbSession = dbClient.openSession(true);
CloseableIterator<DefaultIssue> issues = protoIssueCache.traverse()) {
int batchCounter = 0;
var projectUuid = getProjectUuid(dbSession);
while (issues.hasNext()) {
DefaultIssue currentIssue = issues.next();
Optional<PushEventDto> raisedEvent = pushEventFactory.raiseEventOnIssue(projectUuid, currentIssue);
if (raisedEvent.isEmpty()) {
continue;
}
dbClient.pushEventDao().insert(dbSession, raisedEvent.get());
batchCounter++;
batchCounter = flushIfNeeded(dbSession, batchCounter);
}
flushSession(dbSession);
} catch (Exception ex) {
LOGGER.warn("Error during publishing push event", ex);
}
}
private String getProjectUuid(DbSession dbSession) {
var branch = dbClient.branchDao().selectByUuid(dbSession, treeRootHolder.getRoot().getUuid());
if (branch.isEmpty()) {
return treeRootHolder.getRoot().getUuid();
}
return branch.get().getProjectUuid();
}
private static int flushIfNeeded(DbSession dbSession, int batchCounter) {
if (batchCounter > MAX_BATCH_SIZE) {
flushSession(dbSession);
batchCounter = 0;
}
return batchCounter;
}
private static void flushSession(DbSession dbSession) {
dbSession.flushStatements();
dbSession.commit();
}
@Override
public String getDescription() {
return "Publishing taint vulnerabilities and security hotspots events";
}
}
| 3,707 | 33.654206 | 107 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/PersistScannerAnalysisCacheStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.io.IOException;
import java.io.InputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.ce.task.projectanalysis.batch.BatchReportReader;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.db.DbClient;
public class PersistScannerAnalysisCacheStep implements ComputationStep {
private static final Logger LOGGER = LoggerFactory.getLogger(PersistScannerAnalysisCacheStep.class);
private final BatchReportReader reportReader;
private final DbClient dbClient;
private final TreeRootHolder treeRootHolder;
public PersistScannerAnalysisCacheStep(BatchReportReader reportReader, DbClient dbClient, TreeRootHolder treeRootHolder) {
this.reportReader = reportReader;
this.dbClient = dbClient;
this.treeRootHolder = treeRootHolder;
}
@Override
public String getDescription() {
return "Persist scanner analysis cache";
}
@Override
public void execute(ComputationStep.Context context) {
InputStream scannerAnalysisCacheStream = reportReader.getAnalysisCache();
if (scannerAnalysisCacheStream != null) {
try (var dataStream = scannerAnalysisCacheStream;
var dbSession = dbClient.openSession(false)) {
String branchUuid = treeRootHolder.getRoot().getUuid();
dbClient.scannerAnalysisCacheDao().remove(dbSession, branchUuid);
dbClient.scannerAnalysisCacheDao().insert(dbSession, branchUuid, dataStream);
dbSession.commit();
} catch (IOException e) {
LOGGER.error("Error in reading plugin cache", e);
}
}
}
}
| 2,528 | 37.907692 | 124 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/PersistScannerContextStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import org.sonar.ce.task.CeTask;
import org.sonar.ce.task.projectanalysis.batch.BatchReportReader;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.core.util.CloseableIterator;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import static java.util.Collections.singleton;
public class PersistScannerContextStep implements ComputationStep {
private final BatchReportReader reportReader;
private final DbClient dbClient;
private final CeTask ceTask;
public PersistScannerContextStep(BatchReportReader reportReader, DbClient dbClient, CeTask ceTask) {
this.reportReader = reportReader;
this.dbClient = dbClient;
this.ceTask = ceTask;
}
@Override
public String getDescription() {
return "Persist scanner context";
}
@Override
public void execute(ComputationStep.Context context) {
try (CloseableIterator<String> logsIterator = reportReader.readScannerLogs()) {
if (logsIterator.hasNext()) {
try (DbSession dbSession = dbClient.openSession(false)) {
// in case the task was restarted, the context might have been already persisted
// for total reliability, we rather delete the existing row as we don't want to assume the content
// consistent with the report
dbClient.ceScannerContextDao().deleteByUuids(dbSession, singleton(ceTask.getUuid()));
dbSession.commit();
dbClient.ceScannerContextDao().insert(dbSession, ceTask.getUuid(), logsIterator);
dbSession.commit();
}
}
}
}
}
| 2,442 | 37.171875 | 108 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/ProjectNclocComputationStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
public class ProjectNclocComputationStep implements ComputationStep {
private final AnalysisMetadataHolder analysisMetadataHolder;
private final DbClient dbClient;
public ProjectNclocComputationStep(AnalysisMetadataHolder analysisMetadataHolder, DbClient dbClient) {
this.analysisMetadataHolder = analysisMetadataHolder;
this.dbClient = dbClient;
}
@Override
public void execute(Context context) {
try (DbSession dbSession = dbClient.openSession(false)) {
String projectUuid = analysisMetadataHolder.getProject().getUuid();
long maxncloc = dbClient.liveMeasureDao().sumNclocOfBiggestBranchForProject(dbSession, projectUuid);
dbClient.projectDao().updateNcloc(dbSession, projectUuid, maxncloc);
dbSession.commit();
}
}
@Override
public String getDescription() {
return "Compute total Project ncloc";
}
}
| 1,946 | 36.442308 | 106 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/PublishTaskResultStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.Optional;
import javax.annotation.concurrent.Immutable;
import org.sonar.ce.task.CeTaskResult;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.ce.task.taskprocessor.MutableTaskResultHolder;
public class PublishTaskResultStep implements ComputationStep {
private final MutableTaskResultHolder taskResultHolder;
private final AnalysisMetadataHolder analysisMetadataHolder;
public PublishTaskResultStep(MutableTaskResultHolder taskResultHolder, AnalysisMetadataHolder analysisMetadataHolder) {
this.taskResultHolder = taskResultHolder;
this.analysisMetadataHolder = analysisMetadataHolder;
}
@Override
public String getDescription() {
return "Publish task results";
}
@Override
public void execute(ComputationStep.Context context) {
taskResultHolder.setResult(new CeTaskResultImpl(analysisMetadataHolder.getUuid()));
}
@Immutable
private static class CeTaskResultImpl implements CeTaskResult {
private final String analysisUuid;
public CeTaskResultImpl(String analysisUuid) {
this.analysisUuid = analysisUuid;
}
@Override
public Optional<String> getAnalysisUuid() {
return Optional.of(analysisUuid);
}
}
}
| 2,187 | 34.290323 | 121 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/QualityGateEventsStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.sonar.api.measures.CoreMetrics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.analysis.Branch;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.projectanalysis.event.Event;
import org.sonar.ce.task.projectanalysis.event.EventRepository;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import org.sonar.ce.task.projectanalysis.measure.MeasureRepository;
import org.sonar.ce.task.projectanalysis.measure.QualityGateStatus;
import org.sonar.ce.task.projectanalysis.metric.Metric;
import org.sonar.ce.task.projectanalysis.metric.Metric.MetricType;
import org.sonar.ce.task.projectanalysis.metric.MetricRepository;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.server.notification.NotificationService;
import org.sonar.server.qualitygate.notification.QGChangeNotification;
import static java.util.Collections.singleton;
/**
* This step must be executed after computation of quality gate measure {@link QualityGateMeasuresStep}
*/
public class QualityGateEventsStep implements ComputationStep {
private static final Logger LOGGER = LoggerFactory.getLogger(QualityGateEventsStep.class);
private final TreeRootHolder treeRootHolder;
private final MetricRepository metricRepository;
private final MeasureRepository measureRepository;
private final EventRepository eventRepository;
private final NotificationService notificationService;
private final AnalysisMetadataHolder analysisMetadataHolder;
public QualityGateEventsStep(TreeRootHolder treeRootHolder,
MetricRepository metricRepository, MeasureRepository measureRepository, EventRepository eventRepository,
NotificationService notificationService, AnalysisMetadataHolder analysisMetadataHolder) {
this.treeRootHolder = treeRootHolder;
this.metricRepository = metricRepository;
this.measureRepository = measureRepository;
this.eventRepository = eventRepository;
this.notificationService = notificationService;
this.analysisMetadataHolder = analysisMetadataHolder;
}
@Override
public void execute(ComputationStep.Context context) {
// no notification on pull requests as there is no real Quality Gate on those
if (analysisMetadataHolder.isPullRequest()) {
return;
}
executeForProject(treeRootHolder.getRoot());
}
private void executeForProject(Component project) {
Metric metric = metricRepository.getByKey(CoreMetrics.ALERT_STATUS_KEY);
Optional<Measure> rawStatus = measureRepository.getRawMeasure(project, metric);
if (!rawStatus.isPresent() || !rawStatus.get().hasQualityGateStatus()) {
return;
}
checkQualityGateStatusChange(project, metric, rawStatus.get().getQualityGateStatus());
}
private void checkQualityGateStatusChange(Component project, Metric metric, QualityGateStatus rawStatus) {
Optional<Measure> baseMeasure = measureRepository.getBaseMeasure(project, metric);
if (!baseMeasure.isPresent()) {
checkNewQualityGate(project, rawStatus);
return;
}
if (!baseMeasure.get().hasQualityGateStatus()) {
LOGGER.warn(String.format("Previous Quality gate status for project %s is not a supported value. Can not compute Quality Gate event", project.getKey()));
checkNewQualityGate(project, rawStatus);
return;
}
QualityGateStatus baseStatus = baseMeasure.get().getQualityGateStatus();
if (baseStatus.getStatus() != rawStatus.getStatus()) {
// The QualityGate status has changed
createEvent(rawStatus.getStatus().getLabel(), rawStatus.getText());
boolean isNewKo = rawStatus.getStatus() == Measure.Level.OK;
notifyUsers(project, rawStatus, isNewKo);
}
}
private void checkNewQualityGate(Component project, QualityGateStatus rawStatus) {
if (rawStatus.getStatus() != Measure.Level.OK) {
// There were no defined alerts before, so this one is a new one
createEvent(rawStatus.getStatus().getLabel(), rawStatus.getText());
notifyUsers(project, rawStatus, true);
}
}
/**
* @param rawStatus OK or ERROR + optional text
*/
private void notifyUsers(Component project, QualityGateStatus rawStatus, boolean isNewAlert) {
QGChangeNotification notification = new QGChangeNotification();
notification
.setDefaultMessage(String.format("Alert on %s: %s", project.getName(), rawStatus.getStatus().getLabel()))
.setFieldValue("projectName", project.getName())
.setFieldValue("projectKey", project.getKey())
.setFieldValue("projectVersion", project.getProjectAttributes().getProjectVersion())
.setFieldValue("alertName", rawStatus.getStatus().getLabel())
.setFieldValue("alertText", rawStatus.getText())
.setFieldValue("alertLevel", rawStatus.getStatus().toString())
.setFieldValue("isNewAlert", Boolean.toString(isNewAlert));
Branch branch = analysisMetadataHolder.getBranch();
if (!branch.isMain()) {
notification.setFieldValue("branch", branch.getName());
}
List<Metric> ratingMetrics = metricRepository.getMetricsByType(MetricType.RATING);
String ratingMetricsInOneString = ratingMetrics.stream().map(Metric::getName).collect(Collectors.joining(","));
notification.setFieldValue("ratingMetrics", ratingMetricsInOneString);
notificationService.deliverEmails(singleton(notification));
// compatibility with old API
notificationService.deliver(notification);
}
private void createEvent(String name, @Nullable String description) {
eventRepository.add(Event.createAlert(name, null, description));
}
@Override
public String getDescription() {
return "Generate Quality gate events";
}
}
| 6,872 | 42.5 | 159 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/QualityGateMeasuresStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Multimap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit;
import org.sonar.ce.task.projectanalysis.component.DepthTraversalTypeAwareCrawler;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.projectanalysis.component.TypeAwareVisitorAdapter;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import org.sonar.ce.task.projectanalysis.measure.MeasureRepository;
import org.sonar.ce.task.projectanalysis.measure.QualityGateStatus;
import org.sonar.ce.task.projectanalysis.measure.qualitygatedetails.EvaluatedCondition;
import org.sonar.ce.task.projectanalysis.measure.qualitygatedetails.QualityGateDetailsData;
import org.sonar.ce.task.projectanalysis.metric.Metric;
import org.sonar.ce.task.projectanalysis.metric.MetricRepository;
import org.sonar.ce.task.projectanalysis.qualitygate.Condition;
import org.sonar.ce.task.projectanalysis.qualitygate.ConditionEvaluator;
import org.sonar.ce.task.projectanalysis.qualitygate.ConditionStatus;
import org.sonar.ce.task.projectanalysis.qualitygate.EvaluationResult;
import org.sonar.ce.task.projectanalysis.qualitygate.EvaluationResultTextConverter;
import org.sonar.ce.task.projectanalysis.qualitygate.MutableQualityGateStatusHolder;
import org.sonar.ce.task.projectanalysis.qualitygate.QualityGate;
import org.sonar.ce.task.projectanalysis.qualitygate.QualityGateHolder;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.core.util.stream.MoreCollectors;
import static java.lang.String.format;
import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.PRE_ORDER;
import static org.sonar.ce.task.projectanalysis.qualitygate.ConditionStatus.NO_VALUE_STATUS;
import static org.sonar.ce.task.projectanalysis.qualitygate.ConditionStatus.create;
/**
* This step:
* <ul>
* <li>updates the QualityGateStatus of all the project's measures for the metrics of the conditions of the current
* QualityGate (retrieved from {@link QualityGateHolder})</li>
* <li>computes the measures on the project for metrics {@link CoreMetrics#QUALITY_GATE_DETAILS_KEY} and
* {@link CoreMetrics#ALERT_STATUS_KEY}</li>
* </ul>
*
*/
public class QualityGateMeasuresStep implements ComputationStep {
private final TreeRootHolder treeRootHolder;
private final QualityGateHolder qualityGateHolder;
private final MutableQualityGateStatusHolder qualityGateStatusHolder;
private final MeasureRepository measureRepository;
private final MetricRepository metricRepository;
private final EvaluationResultTextConverter evaluationResultTextConverter;
private final SmallChangesetQualityGateSpecialCase smallChangesetQualityGateSpecialCase;
public QualityGateMeasuresStep(TreeRootHolder treeRootHolder,
QualityGateHolder qualityGateHolder, MutableQualityGateStatusHolder qualityGateStatusHolder,
MeasureRepository measureRepository, MetricRepository metricRepository,
EvaluationResultTextConverter evaluationResultTextConverter, SmallChangesetQualityGateSpecialCase smallChangesetQualityGateSpecialCase) {
this.treeRootHolder = treeRootHolder;
this.qualityGateHolder = qualityGateHolder;
this.qualityGateStatusHolder = qualityGateStatusHolder;
this.evaluationResultTextConverter = evaluationResultTextConverter;
this.measureRepository = measureRepository;
this.metricRepository = metricRepository;
this.smallChangesetQualityGateSpecialCase = smallChangesetQualityGateSpecialCase;
}
@Override
public void execute(ComputationStep.Context context) {
new DepthTraversalTypeAwareCrawler(
new TypeAwareVisitorAdapter(CrawlerDepthLimit.PROJECT, PRE_ORDER) {
@Override
public void visitProject(Component project) {
executeForProject(project);
}
}).visit(treeRootHolder.getRoot());
}
private void executeForProject(Component project) {
Optional<QualityGate> qualityGate = qualityGateHolder.getQualityGate();
if (qualityGate.isPresent()) {
QualityGateDetailsDataBuilder builder = new QualityGateDetailsDataBuilder();
updateMeasures(project, qualityGate.get().getConditions(), builder);
addProjectMeasure(project, builder);
updateQualityGateStatusHolder(qualityGate.get(), builder);
}
}
private void updateQualityGateStatusHolder(QualityGate qualityGate, QualityGateDetailsDataBuilder builder) {
qualityGateStatusHolder.setStatus(convert(builder.getGlobalLevel()), createStatusPerCondition(qualityGate.getConditions(), builder.getEvaluatedConditions()));
}
private static ConditionStatus.EvaluationStatus toEvaluationStatus(Measure.Level globalLevel) {
switch (globalLevel) {
case OK:
return ConditionStatus.EvaluationStatus.OK;
case ERROR:
return ConditionStatus.EvaluationStatus.ERROR;
default:
throw new IllegalArgumentException(format(
"Unsupported value '%s' of Measure.Level can not be converted to EvaluationStatus",
globalLevel));
}
}
private static org.sonar.ce.task.projectanalysis.qualitygate.QualityGateStatus convert(Measure.Level globalLevel) {
switch (globalLevel) {
case OK:
return org.sonar.ce.task.projectanalysis.qualitygate.QualityGateStatus.OK;
case ERROR:
return org.sonar.ce.task.projectanalysis.qualitygate.QualityGateStatus.ERROR;
default:
throw new IllegalArgumentException(format(
"Unsupported value '%s' of Measure.Level can not be converted to QualityGateStatus",
globalLevel));
}
}
private static Map<Condition, ConditionStatus> createStatusPerCondition(Collection<Condition> conditions, Collection<EvaluatedCondition> evaluatedConditions) {
Map<Condition, EvaluatedCondition> evaluatedConditionPerCondition = evaluatedConditions.stream()
.collect(Collectors.toMap(EvaluatedCondition::getCondition, Function.identity()));
ImmutableMap.Builder<Condition, ConditionStatus> builder = ImmutableMap.builder();
for (Condition condition : conditions) {
EvaluatedCondition evaluatedCondition = evaluatedConditionPerCondition.get(condition);
if (evaluatedCondition == null) {
builder.put(condition, NO_VALUE_STATUS);
} else {
builder.put(condition, create(toEvaluationStatus(evaluatedCondition.getLevel()), evaluatedCondition.getActualValue()));
}
}
return builder.build();
}
private void updateMeasures(Component project, Set<Condition> conditions, QualityGateDetailsDataBuilder builder) {
Multimap<Metric, Condition> conditionsPerMetric = conditions.stream().collect(MoreCollectors.index(Condition::getMetric, Function.identity()));
boolean ignoredConditions = false;
for (Map.Entry<Metric, Collection<Condition>> entry : conditionsPerMetric.asMap().entrySet()) {
Metric metric = entry.getKey();
Optional<Measure> measure = measureRepository.getRawMeasure(project, metric);
if (!measure.isPresent()) {
continue;
}
final MetricEvaluationResult metricEvaluationResult = evaluateQualityGate(measure.get(), entry.getValue());
final MetricEvaluationResult finalMetricEvaluationResult;
if (smallChangesetQualityGateSpecialCase.appliesTo(project, metricEvaluationResult)) {
finalMetricEvaluationResult = smallChangesetQualityGateSpecialCase.apply(metricEvaluationResult);
ignoredConditions = true;
} else {
finalMetricEvaluationResult = metricEvaluationResult;
}
String text = evaluationResultTextConverter.asText(finalMetricEvaluationResult.condition, finalMetricEvaluationResult.evaluationResult);
builder.addLabel(text);
Measure updatedMeasure = Measure.updatedMeasureBuilder(measure.get())
.setQualityGateStatus(new QualityGateStatus(finalMetricEvaluationResult.evaluationResult.level(), text))
.create();
measureRepository.update(project, metric, updatedMeasure);
builder.addEvaluatedCondition(finalMetricEvaluationResult);
}
builder.setIgnoredConditions(ignoredConditions);
}
private static MetricEvaluationResult evaluateQualityGate(Measure measure, Collection<Condition> conditions) {
ConditionEvaluator conditionEvaluator = new ConditionEvaluator();
MetricEvaluationResult metricEvaluationResult = null;
for (Condition newCondition : conditions) {
EvaluationResult newEvaluationResult = conditionEvaluator.evaluate(newCondition, measure);
if (metricEvaluationResult == null || newEvaluationResult.level().ordinal() > metricEvaluationResult.evaluationResult.level().ordinal()) {
metricEvaluationResult = new MetricEvaluationResult(newEvaluationResult, newCondition);
}
}
return metricEvaluationResult;
}
private void addProjectMeasure(Component project, QualityGateDetailsDataBuilder builder) {
Measure globalMeasure = Measure.newMeasureBuilder()
.setQualityGateStatus(new QualityGateStatus(builder.getGlobalLevel(), StringUtils.join(builder.getLabels(), ", ")))
.create(builder.getGlobalLevel());
Metric metric = metricRepository.getByKey(CoreMetrics.ALERT_STATUS_KEY);
measureRepository.add(project, metric, globalMeasure);
String detailMeasureValue = new QualityGateDetailsData(builder.getGlobalLevel(), builder.getEvaluatedConditions(), builder.isIgnoredConditions()).toJson();
Measure detailsMeasure = Measure.newMeasureBuilder().create(detailMeasureValue);
Metric qgDetailsMetric = metricRepository.getByKey(CoreMetrics.QUALITY_GATE_DETAILS_KEY);
measureRepository.add(project, qgDetailsMetric, detailsMeasure);
}
@Override
public String getDescription() {
return "Compute Quality Gate measures";
}
private static final class QualityGateDetailsDataBuilder {
private Measure.Level globalLevel = Measure.Level.OK;
private List<String> labels = new ArrayList<>();
private List<EvaluatedCondition> evaluatedConditions = new ArrayList<>();
private boolean ignoredConditions;
public Measure.Level getGlobalLevel() {
return globalLevel;
}
public void addLabel(@Nullable String label) {
if (StringUtils.isNotBlank(label)) {
labels.add(label);
}
}
public List<String> getLabels() {
return labels;
}
public void addEvaluatedCondition(MetricEvaluationResult metricEvaluationResult) {
Measure.Level level = metricEvaluationResult.evaluationResult.level();
if (Measure.Level.ERROR == level) {
globalLevel = Measure.Level.ERROR;
}
evaluatedConditions.add(
new EvaluatedCondition(metricEvaluationResult.condition, level, metricEvaluationResult.evaluationResult.value()));
}
public List<EvaluatedCondition> getEvaluatedConditions() {
return evaluatedConditions;
}
public boolean isIgnoredConditions() {
return ignoredConditions;
}
public QualityGateDetailsDataBuilder setIgnoredConditions(boolean ignoredConditions) {
this.ignoredConditions = ignoredConditions;
return this;
}
}
static class MetricEvaluationResult {
final EvaluationResult evaluationResult;
final Condition condition;
MetricEvaluationResult(EvaluationResult evaluationResult, Condition condition) {
this.evaluationResult = evaluationResult;
this.condition = condition;
}
}
}
| 12,717 | 44.421429 | 162 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/QualityProfileEventsStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import com.google.common.collect.ImmutableSortedMap;
import java.util.Collections;
import java.util.Date;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nullable;
import org.apache.commons.lang.time.DateUtils;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.resources.Language;
import org.sonar.api.utils.KeyValueFormat;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.projectanalysis.event.Event;
import org.sonar.ce.task.projectanalysis.event.EventRepository;
import org.sonar.ce.task.projectanalysis.language.LanguageRepository;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import org.sonar.ce.task.projectanalysis.measure.MeasureRepository;
import org.sonar.ce.task.projectanalysis.metric.MetricRepository;
import org.sonar.ce.task.projectanalysis.qualityprofile.QProfileStatusRepository;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.core.util.UtcDateUtils;
import org.sonar.server.qualityprofile.QPMeasureData;
import org.sonar.server.qualityprofile.QualityProfile;
import static org.sonar.ce.task.projectanalysis.qualityprofile.QProfileStatusRepository.Status.ADDED;
import static org.sonar.ce.task.projectanalysis.qualityprofile.QProfileStatusRepository.Status.REMOVED;
import static org.sonar.ce.task.projectanalysis.qualityprofile.QProfileStatusRepository.Status.UPDATED;
/**
* Computation of quality profile events
* As it depends upon {@link CoreMetrics#QUALITY_PROFILES_KEY}, it must be executed after {@link ComputeQProfileMeasureStep}
*/
public class QualityProfileEventsStep implements ComputationStep {
private final TreeRootHolder treeRootHolder;
private final MetricRepository metricRepository;
private final MeasureRepository measureRepository;
private final EventRepository eventRepository;
private final LanguageRepository languageRepository;
private final QProfileStatusRepository qProfileStatusRepository;
public QualityProfileEventsStep(TreeRootHolder treeRootHolder,
MetricRepository metricRepository, MeasureRepository measureRepository, LanguageRepository languageRepository,
EventRepository eventRepository, QProfileStatusRepository qProfileStatusRepository) {
this.treeRootHolder = treeRootHolder;
this.metricRepository = metricRepository;
this.measureRepository = measureRepository;
this.eventRepository = eventRepository;
this.languageRepository = languageRepository;
this.qProfileStatusRepository = qProfileStatusRepository;
}
@Override
public void execute(ComputationStep.Context context) {
executeForBranch(treeRootHolder.getRoot());
}
private void executeForBranch(Component branchComponent) {
Optional<Measure> baseMeasure = measureRepository.getBaseMeasure(branchComponent, metricRepository.getByKey(CoreMetrics.QUALITY_PROFILES_KEY));
if (!baseMeasure.isPresent()) {
// first analysis -> do not generate events
return;
}
// Load profiles used in current analysis for which at least one file of the corresponding language exists
Optional<Measure> rawMeasure = measureRepository.getRawMeasure(branchComponent, metricRepository.getByKey(CoreMetrics.QUALITY_PROFILES_KEY));
if (!rawMeasure.isPresent()) {
// No qualify profile computed on the project
return;
}
Map<String, QualityProfile> rawProfiles = QPMeasureData.fromJson(rawMeasure.get().getStringValue()).getProfilesByKey();
Map<String, QualityProfile> baseProfiles = parseJsonData(baseMeasure.get());
detectNewOrUpdatedProfiles(baseProfiles, rawProfiles);
detectNoMoreUsedProfiles(baseProfiles);
}
private static Map<String, QualityProfile> parseJsonData(Measure measure) {
String data = measure.getStringValue();
if (data == null) {
return Collections.emptyMap();
}
return QPMeasureData.fromJson(data).getProfilesByKey();
}
private void detectNoMoreUsedProfiles(Map<String, QualityProfile> baseProfiles) {
for (QualityProfile baseProfile : baseProfiles.values()) {
if (qProfileStatusRepository.get(baseProfile.getQpKey()).filter(REMOVED::equals).isPresent()) {
markAsRemoved(baseProfile);
}
}
}
private void detectNewOrUpdatedProfiles(Map<String, QualityProfile> baseProfiles, Map<String, QualityProfile> rawProfiles) {
for (QualityProfile profile : rawProfiles.values()) {
qProfileStatusRepository.get(profile.getQpKey()).ifPresent(status -> {
if (status.equals(ADDED)) {
markAsAdded(profile);
} else if (status.equals(UPDATED)) {
markAsChanged(baseProfiles.get(profile.getQpKey()), profile);
}
});
}
}
private void markAsChanged(QualityProfile baseProfile, QualityProfile profile) {
Date from = baseProfile.getRulesUpdatedAt();
String data = KeyValueFormat.format(ImmutableSortedMap.of(
"key", profile.getQpKey(),
"from", UtcDateUtils.formatDateTime(fixDate(from)),
"to", UtcDateUtils.formatDateTime(fixDate(profile.getRulesUpdatedAt()))));
eventRepository.add(createQProfileEvent(profile, "Changes in %s", data));
}
private void markAsRemoved(QualityProfile profile) {
eventRepository.add(createQProfileEvent(profile, "Stop using %s"));
}
private void markAsAdded(QualityProfile profile) {
eventRepository.add(createQProfileEvent(profile, "Use %s"));
}
private Event createQProfileEvent(QualityProfile profile, String namePattern) {
return createQProfileEvent(profile, namePattern, null);
}
private Event createQProfileEvent(QualityProfile profile, String namePattern, @Nullable String data) {
return Event.createProfile(String.format(namePattern, profileLabel(profile)), data, null);
}
private String profileLabel(QualityProfile profile) {
Optional<Language> language = languageRepository.find(profile.getLanguageKey());
String languageName = language.isPresent() ? language.get().getName() : profile.getLanguageKey();
return String.format("'%s' (%s)", profile.getQpName(), languageName);
}
/**
* This hack must be done because date precision is millisecond in db/es and date format is select only
*/
private static Date fixDate(Date date) {
return DateUtils.addSeconds(date, 1);
}
@Override
public String getDescription() {
return "Generate Quality profile events";
}
}
| 7,325 | 42.094118 | 147 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/ReportComputationSteps.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.Arrays;
import java.util.List;
import org.sonar.ce.task.container.TaskContainer;
import org.sonar.ce.task.projectanalysis.filemove.FileMoveDetectionStep;
import org.sonar.ce.task.projectanalysis.filemove.PullRequestFileMoveDetectionStep;
import org.sonar.ce.task.projectanalysis.language.HandleUnanalyzedLanguagesStep;
import org.sonar.ce.task.projectanalysis.measure.PostMeasuresComputationChecksStep;
import org.sonar.ce.task.projectanalysis.purge.PurgeDatastoresStep;
import org.sonar.ce.task.projectanalysis.qualityprofile.RegisterQualityProfileStatusStep;
import org.sonar.ce.task.projectanalysis.source.PersistFileSourcesStep;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.ce.task.step.ExecuteStatelessInitExtensionsStep;
/**
* Ordered list of steps classes and instances to be executed for batch processing
*/
public class ReportComputationSteps extends AbstractComputationSteps {
private static final List<Class<? extends ComputationStep>> STEPS = Arrays.asList(
ExtractReportStep.class,
PersistScannerContextStep.class,
PersistAnalysisWarningsStep.class,
GenerateAnalysisUuid.class,
// Builds Component tree
LoadReportAnalysisMetadataHolderStep.class,
ExecuteStatelessInitExtensionsStep.class,
BuildComponentTreeStep.class,
ValidateProjectStep.class,
LoadQualityProfilesStep.class,
// load project related stuffs
LoadFileHashesAndStatusStep.class,
LoadQualityGateStep.class,
LoadPeriodsStep.class,
FileMoveDetectionStep.class,
PullRequestFileMoveDetectionStep.class,
// load duplications related stuff
LoadDuplicationsFromReportStep.class,
LoadCrossProjectDuplicationsRepositoryStep.class,
// data computation
SizeMeasuresStep.class,
NewCoverageMeasuresStep.class,
CoverageMeasuresStep.class,
CommentMeasuresStep.class,
DuplicationMeasuresStep.class,
NewSizeMeasuresStep.class,
LanguageDistributionMeasuresStep.class,
UnitTestMeasuresStep.class,
ComplexityMeasuresStep.class,
LoadMeasureComputersStep.class,
RegisterQualityProfileStatusStep.class,
ExecuteVisitorsStep.class,
PostMeasuresComputationChecksStep.class,
QualityGateMeasuresStep.class,
// Must be executed after computation of language distribution
ComputeQProfileMeasureStep.class,
// Must be executed after computation of quality profile measure
QualityProfileEventsStep.class,
// Must be executed after computation of quality gate measure
QualityGateEventsStep.class,
HandleUnanalyzedLanguagesStep.class,
// Persist data
PersistScannerAnalysisCacheStep.class,
PersistComponentsStep.class,
PersistAnalysisStep.class,
PersistAnalysisPropertiesStep.class,
PersistMeasuresStep.class,
PersistLiveMeasuresStep.class,
PersistDuplicationDataStep.class,
PersistAdHocRulesStep.class,
PersistIssuesStep.class,
CleanIssueChangesStep.class,
PersistProjectLinksStep.class,
PersistEventsStep.class,
PersistFileSourcesStep.class,
PersistCrossProjectDuplicationIndexStep.class,
EnableAnalysisStep.class,
UpdateQualityProfilesLastUsedDateStep.class,
PurgeDatastoresStep.class,
IndexAnalysisStep.class,
UpdateNeedIssueSyncStep.class,
ProjectNclocComputationStep.class,
PersistPushEventsStep.class,
// notifications are sent at the end, so that webapp displays up-to-date information
SendIssueNotificationsStep.class,
PublishTaskResultStep.class,
TriggerViewRefreshStep.class);
public ReportComputationSteps(TaskContainer taskContainer) {
super(taskContainer);
}
/**
* List of all {@link ComputationStep},
* ordered by execution sequence.
*/
@Override
public List<Class<? extends ComputationStep>> orderedStepClasses() {
return STEPS;
}
}
| 4,738 | 33.845588 | 89 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/SendIssueNotificationsStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import com.google.common.collect.ImmutableSet;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.annotation.CheckForNull;
import org.sonar.api.issue.Issue;
import org.sonar.api.notifications.Notification;
import org.sonar.api.rules.RuleType;
import org.sonar.api.utils.Duration;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.analysis.Branch;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.projectanalysis.issue.ProtoIssueCache;
import org.sonar.ce.task.projectanalysis.notification.NotificationFactory;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.util.CloseableIterator;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchType;
import org.sonar.db.user.UserDto;
import org.sonar.server.issue.notification.IssuesChangesNotification;
import org.sonar.server.issue.notification.MyNewIssuesNotification;
import org.sonar.server.issue.notification.NewIssuesNotification;
import org.sonar.server.issue.notification.NewIssuesStatistics;
import org.sonar.server.notification.NotificationService;
import static java.util.Collections.singleton;
import static java.util.stream.Collectors.toMap;
import static java.util.stream.StreamSupport.stream;
import static org.sonar.db.component.BranchType.PULL_REQUEST;
/**
* Reads issues from disk cache and send related notifications. For performance reasons,
* the standard notification DB queue is not used as a temporary storage. Notifications
* are directly processed by {@link NotificationService}.
*/
public class SendIssueNotificationsStep implements ComputationStep {
/**
* Types of the notifications sent by this step
*/
static final Set<Class<? extends Notification>> NOTIF_TYPES = ImmutableSet.of(NewIssuesNotification.class, MyNewIssuesNotification.class, IssuesChangesNotification.class);
private final ProtoIssueCache protoIssueCache;
private final TreeRootHolder treeRootHolder;
private final NotificationService service;
private final AnalysisMetadataHolder analysisMetadataHolder;
private final NotificationFactory notificationFactory;
private final DbClient dbClient;
public SendIssueNotificationsStep(ProtoIssueCache protoIssueCache, TreeRootHolder treeRootHolder,
NotificationService service, AnalysisMetadataHolder analysisMetadataHolder,
NotificationFactory notificationFactory, DbClient dbClient) {
this.protoIssueCache = protoIssueCache;
this.treeRootHolder = treeRootHolder;
this.service = service;
this.analysisMetadataHolder = analysisMetadataHolder;
this.notificationFactory = notificationFactory;
this.dbClient = dbClient;
}
@Override
public void execute(ComputationStep.Context context) {
BranchType branchType = analysisMetadataHolder.getBranch().getType();
if (branchType == PULL_REQUEST) {
return;
}
Component project = treeRootHolder.getRoot();
NotificationStatistics notificationStatistics = new NotificationStatistics();
if (service.hasProjectSubscribersForTypes(analysisMetadataHolder.getProject().getUuid(), NOTIF_TYPES)) {
doExecute(notificationStatistics, project);
}
notificationStatistics.dumpTo(context);
}
private void doExecute(NotificationStatistics notificationStatistics, Component project) {
long analysisDate = analysisMetadataHolder.getAnalysisDate();
Predicate<DefaultIssue> onCurrentAnalysis = i -> i.isNew() && i.creationDate().getTime() >= truncateToSeconds(analysisDate);
NewIssuesStatistics newIssuesStats = new NewIssuesStatistics(onCurrentAnalysis);
Map<String, UserDto> assigneesByUuid;
try (DbSession dbSession = dbClient.openSession(false)) {
Iterable<DefaultIssue> iterable = protoIssueCache::traverse;
Set<String> assigneeUuids = stream(iterable.spliterator(), false).map(DefaultIssue::assignee).filter(Objects::nonNull).collect(Collectors.toSet());
assigneesByUuid = dbClient.userDao().selectByUuids(dbSession, assigneeUuids).stream().collect(toMap(UserDto::getUuid, dto -> dto));
}
try (CloseableIterator<DefaultIssue> issues = protoIssueCache.traverse()) {
processIssues(newIssuesStats, issues, assigneesByUuid, notificationStatistics);
}
if (newIssuesStats.hasIssuesOnCurrentAnalysis()) {
sendNewIssuesNotification(newIssuesStats, project, assigneesByUuid, analysisDate, notificationStatistics);
sendMyNewIssuesNotification(newIssuesStats, project, assigneesByUuid, analysisDate, notificationStatistics);
}
}
/**
* Truncated the analysis date to seconds before comparing it to {@link Issue#creationDate()} is required because
* {@link DefaultIssue#setCreationDate(Date)} does it.
*/
private static long truncateToSeconds(long analysisDate) {
Instant instant = new Date(analysisDate).toInstant();
instant = instant.truncatedTo(ChronoUnit.SECONDS);
return Date.from(instant).getTime();
}
private void processIssues(NewIssuesStatistics newIssuesStats, CloseableIterator<DefaultIssue> issues,
Map<String, UserDto> assigneesByUuid, NotificationStatistics notificationStatistics) {
int batchSize = 1000;
Set<DefaultIssue> changedIssuesToNotify = new HashSet<>(batchSize);
while (issues.hasNext()) {
DefaultIssue issue = issues.next();
if (issue.type() != RuleType.SECURITY_HOTSPOT) {
if (issue.isNew() && issue.resolution() == null) {
newIssuesStats.add(issue);
} else if (issue.isChanged() && issue.mustSendNotifications()) {
changedIssuesToNotify.add(issue);
}
}
if (changedIssuesToNotify.size() >= batchSize) {
sendIssuesChangesNotification(changedIssuesToNotify, assigneesByUuid, notificationStatistics);
changedIssuesToNotify.clear();
}
}
if (!changedIssuesToNotify.isEmpty()) {
sendIssuesChangesNotification(changedIssuesToNotify, assigneesByUuid, notificationStatistics);
}
}
private void sendIssuesChangesNotification(Set<DefaultIssue> issues, Map<String, UserDto> assigneesByUuid, NotificationStatistics notificationStatistics) {
IssuesChangesNotification notification = notificationFactory.newIssuesChangesNotification(issues, assigneesByUuid);
notificationStatistics.issueChangesDeliveries += service.deliverEmails(singleton(notification));
notificationStatistics.issueChanges++;
// compatibility with old API
notificationStatistics.issueChangesDeliveries += service.deliver(notification);
}
private void sendNewIssuesNotification(NewIssuesStatistics statistics, Component project, Map<String, UserDto> assigneesByUuid,
long analysisDate, NotificationStatistics notificationStatistics) {
NewIssuesStatistics.Stats globalStatistics = statistics.globalStatistics();
NewIssuesNotification notification = notificationFactory
.newNewIssuesNotification(assigneesByUuid)
.setProject(project.getKey(), project.getName(), getBranchName(), getPullRequest())
.setProjectVersion(project.getProjectAttributes().getProjectVersion())
.setAnalysisDate(new Date(analysisDate))
.setStatistics(project.getName(), globalStatistics)
.setDebt(Duration.create(globalStatistics.effort().getOnCurrentAnalysis()));
notificationStatistics.newIssuesDeliveries += service.deliverEmails(singleton(notification));
notificationStatistics.newIssues++;
// compatibility with old API
notificationStatistics.newIssuesDeliveries += service.deliver(notification);
}
private void sendMyNewIssuesNotification(NewIssuesStatistics statistics, Component project, Map<String, UserDto> assigneesByUuid, long analysisDate,
NotificationStatistics notificationStatistics) {
Map<String, UserDto> userDtoByUuid = loadUserDtoByUuid(statistics);
Set<MyNewIssuesNotification> myNewIssuesNotifications = statistics.getAssigneesStatistics().entrySet()
.stream()
.filter(e -> e.getValue().hasIssuesOnCurrentAnalysis())
.map(e -> {
String assigneeUuid = e.getKey();
NewIssuesStatistics.Stats assigneeStatistics = e.getValue();
MyNewIssuesNotification myNewIssuesNotification = notificationFactory
.newMyNewIssuesNotification(assigneesByUuid)
.setAssignee(userDtoByUuid.get(assigneeUuid));
myNewIssuesNotification
.setProject(project.getKey(), project.getName(), getBranchName(), getPullRequest())
.setProjectVersion(project.getProjectAttributes().getProjectVersion())
.setAnalysisDate(new Date(analysisDate))
.setStatistics(project.getName(), assigneeStatistics)
.setDebt(Duration.create(assigneeStatistics.effort().getOnCurrentAnalysis()));
return myNewIssuesNotification;
})
.collect(Collectors.toSet());
notificationStatistics.myNewIssuesDeliveries += service.deliverEmails(myNewIssuesNotifications);
notificationStatistics.myNewIssues += myNewIssuesNotifications.size();
// compatibility with old API
myNewIssuesNotifications
.forEach(e -> notificationStatistics.myNewIssuesDeliveries += service.deliver(e));
}
private Map<String, UserDto> loadUserDtoByUuid(NewIssuesStatistics statistics) {
List<Map.Entry<String, NewIssuesStatistics.Stats>> entriesWithIssuesOnLeak = statistics.getAssigneesStatistics().entrySet()
.stream().filter(e -> e.getValue().hasIssuesOnCurrentAnalysis()).toList();
List<String> assigneeUuids = entriesWithIssuesOnLeak.stream().map(Map.Entry::getKey).toList();
try (DbSession dbSession = dbClient.openSession(false)) {
return dbClient.userDao().selectByUuids(dbSession, assigneeUuids).stream().collect(toMap(UserDto::getUuid, u -> u));
}
}
@Override
public String getDescription() {
return "Send issue notifications";
}
@CheckForNull
private String getBranchName() {
Branch branch = analysisMetadataHolder.getBranch();
return branch.isMain() || branch.getType() == PULL_REQUEST ? null : branch.getName();
}
@CheckForNull
private String getPullRequest() {
Branch branch = analysisMetadataHolder.getBranch();
return branch.getType() == PULL_REQUEST ? analysisMetadataHolder.getPullRequestKey() : null;
}
private static class NotificationStatistics {
private int issueChanges = 0;
private int issueChangesDeliveries = 0;
private int newIssues = 0;
private int newIssuesDeliveries = 0;
private int myNewIssues = 0;
private int myNewIssuesDeliveries = 0;
private void dumpTo(ComputationStep.Context context) {
context.getStatistics()
.add("newIssuesNotifs", newIssues)
.add("newIssuesDeliveries", newIssuesDeliveries)
.add("myNewIssuesNotifs", myNewIssues)
.add("myNewIssuesDeliveries", myNewIssuesDeliveries)
.add("changesNotifs", issueChanges)
.add("changesDeliveries", issueChangesDeliveries);
}
}
}
| 12,201 | 45.219697 | 173 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/SizeMeasuresStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.List;
import java.util.Optional;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit;
import org.sonar.ce.task.projectanalysis.component.PathAwareCrawler;
import org.sonar.ce.task.projectanalysis.component.PathAwareVisitorAdapter;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.projectanalysis.formula.Formula;
import org.sonar.ce.task.projectanalysis.formula.FormulaExecutorComponentVisitor;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import org.sonar.ce.task.projectanalysis.measure.MeasureRepository;
import org.sonar.ce.task.projectanalysis.metric.Metric;
import org.sonar.ce.task.projectanalysis.metric.MetricRepository;
import org.sonar.ce.task.step.ComputationStep;
import static org.sonar.api.measures.CoreMetrics.CLASSES_KEY;
import static org.sonar.api.measures.CoreMetrics.FILES_KEY;
import static org.sonar.api.measures.CoreMetrics.FUNCTIONS_KEY;
import static org.sonar.api.measures.CoreMetrics.GENERATED_LINES_KEY;
import static org.sonar.api.measures.CoreMetrics.GENERATED_NCLOC_KEY;
import static org.sonar.api.measures.CoreMetrics.LINES_KEY;
import static org.sonar.api.measures.CoreMetrics.NCLOC_KEY;
import static org.sonar.api.measures.CoreMetrics.STATEMENTS_KEY;
import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.POST_ORDER;
import static org.sonar.ce.task.projectanalysis.formula.SumFormula.createIntSumFormula;
import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilder;
/**
* Compute size measures
*/
public class SizeMeasuresStep implements ComputationStep {
private static final CounterStackElementFactory COUNTER_STACK_ELEMENT_FACTORY = new CounterStackElementFactory();
private static final List<Formula<?>> AGGREGATED_SIZE_MEASURE_FORMULAS = List.of(
createIntSumFormula(GENERATED_LINES_KEY),
createIntSumFormula(NCLOC_KEY),
createIntSumFormula(GENERATED_NCLOC_KEY),
createIntSumFormula(FUNCTIONS_KEY),
createIntSumFormula(STATEMENTS_KEY),
createIntSumFormula(CLASSES_KEY));
private final TreeRootHolder treeRootHolder;
private final MetricRepository metricRepository;
private final MeasureRepository measureRepository;
public SizeMeasuresStep(TreeRootHolder treeRootHolder, MetricRepository metricRepository, MeasureRepository measureRepository) {
this.treeRootHolder = treeRootHolder;
this.metricRepository = metricRepository;
this.measureRepository = measureRepository;
}
@Override
public void execute(ComputationStep.Context context) {
new PathAwareCrawler<>(new FileAndDirectoryMeasureVisitor(
metricRepository.getByKey(FILES_KEY),
metricRepository.getByKey(LINES_KEY)))
.visit(treeRootHolder.getRoot());
new PathAwareCrawler<>(FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository)
.buildFor(AGGREGATED_SIZE_MEASURE_FORMULAS))
.visit(treeRootHolder.getRoot());
}
@Override
public String getDescription() {
return "Compute size measures";
}
private class FileAndDirectoryMeasureVisitor extends PathAwareVisitorAdapter<Counter> {
private final Metric fileMetric;
private final Metric linesMetric;
public FileAndDirectoryMeasureVisitor(Metric fileMetric, Metric linesMetric) {
super(CrawlerDepthLimit.LEAVES, POST_ORDER, COUNTER_STACK_ELEMENT_FACTORY);
this.fileMetric = fileMetric;
this.linesMetric = linesMetric;
}
@Override
public void visitProject(Component project, Path<Counter> path) {
createMeasures(project, path.current());
}
@Override
public void visitDirectory(Component directory, Path<Counter> path) {
int mainfileCount = path.current().files;
if (mainfileCount > 0) {
measureRepository.add(directory, fileMetric, newMeasureBuilder().create(mainfileCount));
measureRepository.add(directory, linesMetric, newMeasureBuilder().create(path.current().lines));
path.parent().files += mainfileCount;
path.parent().lines += path.current().lines;
}
}
private void createMeasures(Component directory, Counter counter) {
if (counter.files > 0) {
measureRepository.add(directory, fileMetric, newMeasureBuilder().create(counter.files));
measureRepository.add(directory, linesMetric, newMeasureBuilder().create(counter.lines));
}
}
@Override
public void visitFile(Component file, Path<Counter> path) {
if (file.getFileAttributes().isUnitTest()) {
return;
}
int lines = file.getFileAttributes().getLines();
measureRepository.add(file, fileMetric, newMeasureBuilder().create(1));
measureRepository.add(file, linesMetric, newMeasureBuilder().create(lines));
path.parent().lines += lines;
path.parent().files += 1;
}
@Override
public void visitView(Component view, Path<Counter> path) {
createMeasures(view, path.current());
}
@Override
public void visitSubView(Component subView, Path<Counter> path) {
createMeasures(subView, path.current());
path.parent().aggregate(path.current());
}
@Override
public void visitProjectView(Component projectView, Path<Counter> path) {
path.parent().files += getIntValue(projectView, this.fileMetric);
path.parent().lines += getIntValue(projectView, this.linesMetric);
}
private int getIntValue(Component component, Metric metric) {
Optional<Measure> fileMeasure = measureRepository.getRawMeasure(component, metric);
return fileMeasure.map(Measure::getIntValue).orElse(0);
}
}
private static class Counter {
private int lines = 0;
private int files = 0;
void aggregate(Counter counter) {
files += counter.files;
lines += counter.lines;
}
}
private static class CounterStackElementFactory extends PathAwareVisitorAdapter.SimpleStackElementFactory<Counter> {
@Override
public Counter createForAny(Component component) {
return new Counter();
}
@Override
public Counter createForFile(Component file) {
return null;
}
@Override
public Counter createForProjectView(Component projectView) {
return null;
}
}
}
| 7,214 | 38.211957 | 130 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/SmallChangesetQualityGateSpecialCase.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import javax.annotation.Nullable;
import org.sonar.api.CoreProperties;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.ConfigurationRepository;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import org.sonar.ce.task.projectanalysis.measure.MeasureRepository;
import org.sonar.ce.task.projectanalysis.metric.MetricRepository;
import org.sonar.ce.task.projectanalysis.qualitygate.EvaluationResult;
import org.sonar.ce.task.projectanalysis.step.QualityGateMeasuresStep.MetricEvaluationResult;
import static org.sonar.server.qualitygate.QualityGateEvaluatorImpl.MAXIMUM_NEW_LINES_FOR_SMALL_CHANGESETS;
import static org.sonar.server.qualitygate.QualityGateEvaluatorImpl.METRICS_TO_IGNORE_ON_SMALL_CHANGESETS;
public class SmallChangesetQualityGateSpecialCase {
private final MeasureRepository measureRepository;
private final MetricRepository metricRepository;
private final ConfigurationRepository config;
public SmallChangesetQualityGateSpecialCase(MeasureRepository measureRepository, MetricRepository metricRepository, ConfigurationRepository config) {
this.measureRepository = measureRepository;
this.metricRepository = metricRepository;
this.config = config;
}
public boolean appliesTo(Component project, @Nullable MetricEvaluationResult metricEvaluationResult) {
return metricEvaluationResult != null
&& metricEvaluationResult.evaluationResult.level() != Measure.Level.OK
&& METRICS_TO_IGNORE_ON_SMALL_CHANGESETS.contains(metricEvaluationResult.condition.getMetric().getKey())
&& config.getConfiguration().getBoolean(CoreProperties.QUALITY_GATE_IGNORE_SMALL_CHANGES).orElse(true)
&& isSmallChangeset(project);
}
MetricEvaluationResult apply(MetricEvaluationResult metricEvaluationResult) {
return new MetricEvaluationResult(
new EvaluationResult(Measure.Level.OK, metricEvaluationResult.evaluationResult.value()), metricEvaluationResult.condition);
}
private boolean isSmallChangeset(Component project) {
return measureRepository.getRawMeasure(project, metricRepository.getByKey(CoreMetrics.NEW_LINES_KEY))
.map(newLines -> newLines.getIntValue() < MAXIMUM_NEW_LINES_FOR_SMALL_CHANGESETS)
.orElse(false);
}
}
| 3,217 | 47.757576 | 151 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/TriggerViewRefreshStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.OptionalInt;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.view.TriggerViewRefreshDelegate;
import org.sonar.ce.task.step.ComputationStep;
import org.springframework.beans.factory.annotation.Autowired;
/**
* This step will trigger refresh of Portfolios and Applications that include the current project.
*/
public class TriggerViewRefreshStep implements ComputationStep {
private final TriggerViewRefreshDelegate[] triggerViewRefreshDelegates;
private final AnalysisMetadataHolder analysisMetadata;
/**
* Constructor used by the ioc container when no implementation of {@link TriggerViewRefreshDelegate} is available
*/
@Autowired(required = false)
public TriggerViewRefreshStep(AnalysisMetadataHolder analysisMetadata) {
this.analysisMetadata = analysisMetadata;
this.triggerViewRefreshDelegates = new TriggerViewRefreshDelegate[0];
}
/**
* Constructor used by the ioc container when an implementation of {@link TriggerViewRefreshDelegate} is available
*/
@Autowired(required = false)
public TriggerViewRefreshStep(AnalysisMetadataHolder analysisMetadata, TriggerViewRefreshDelegate[] triggerViewRefreshDelegates) {
this.analysisMetadata = analysisMetadata;
this.triggerViewRefreshDelegates = triggerViewRefreshDelegates;
}
@Override
public String getDescription() {
return "Trigger refresh of Portfolios and Applications";
}
@Override
public void execute(ComputationStep.Context context) {
for (TriggerViewRefreshDelegate triggerViewRefreshDelegate : this.triggerViewRefreshDelegates) {
OptionalInt count = triggerViewRefreshDelegate.triggerFrom(analysisMetadata.getProject());
count.ifPresent(i -> context.getStatistics().add("refreshes" + triggerViewRefreshDelegate.getQualifier(), i));
}
}
}
| 2,768 | 39.720588 | 132 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/UnitTestMeasuresStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.List;
import java.util.Optional;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.PathAwareCrawler;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.projectanalysis.formula.Counter;
import org.sonar.ce.task.projectanalysis.formula.CounterInitializationContext;
import org.sonar.ce.task.projectanalysis.formula.CreateMeasureContext;
import org.sonar.ce.task.projectanalysis.formula.Formula;
import org.sonar.ce.task.projectanalysis.formula.FormulaExecutorComponentVisitor;
import org.sonar.ce.task.projectanalysis.formula.counter.IntSumCounter;
import org.sonar.ce.task.projectanalysis.formula.counter.LongSumCounter;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import org.sonar.ce.task.projectanalysis.measure.MeasureRepository;
import org.sonar.ce.task.projectanalysis.metric.MetricRepository;
import org.sonar.ce.task.step.ComputationStep;
import static org.sonar.api.measures.CoreMetrics.SKIPPED_TESTS_KEY;
import static org.sonar.api.measures.CoreMetrics.TESTS_KEY;
import static org.sonar.api.measures.CoreMetrics.TEST_ERRORS_KEY;
import static org.sonar.api.measures.CoreMetrics.TEST_EXECUTION_TIME_KEY;
import static org.sonar.api.measures.CoreMetrics.TEST_FAILURES_KEY;
import static org.sonar.api.measures.CoreMetrics.TEST_SUCCESS_DENSITY_KEY;
/**
* Computes unit test measures on files and then aggregates them on higher components.
*/
public class UnitTestMeasuresStep implements ComputationStep {
private static final String[] METRICS = new String[] {TESTS_KEY, TEST_ERRORS_KEY, TEST_FAILURES_KEY, SKIPPED_TESTS_KEY, TEST_SUCCESS_DENSITY_KEY, TEST_EXECUTION_TIME_KEY};
private static final List<Formula<?>> FORMULAS = List.of(new UnitTestsFormula());
private final TreeRootHolder treeRootHolder;
private final MetricRepository metricRepository;
private final MeasureRepository measureRepository;
public UnitTestMeasuresStep(TreeRootHolder treeRootHolder, MetricRepository metricRepository, MeasureRepository measureRepository) {
this.treeRootHolder = treeRootHolder;
this.metricRepository = metricRepository;
this.measureRepository = measureRepository;
}
@Override
public void execute(ComputationStep.Context context) {
new PathAwareCrawler<>(
FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository).buildFor(FORMULAS))
.visit(treeRootHolder.getRoot());
}
private static class UnitTestsFormula implements Formula<UnitTestsCounter> {
@Override
public UnitTestsCounter createNewCounter() {
return new UnitTestsCounter();
}
@Override
public Optional<Measure> createMeasure(UnitTestsCounter counter, CreateMeasureContext context) {
String metricKey = context.getMetric().getKey();
Component leaf = counter.getLeaf();
switch (metricKey) {
case TESTS_KEY:
return createIntMeasure(context.getComponent(), leaf, counter.testsCounter.getValue());
case TEST_ERRORS_KEY:
return createIntMeasure(context.getComponent(), leaf, counter.testsErrorsCounter.getValue());
case TEST_FAILURES_KEY:
return createIntMeasure(context.getComponent(), leaf, counter.testsFailuresCounter.getValue());
case SKIPPED_TESTS_KEY:
return createIntMeasure(context.getComponent(), leaf, counter.skippedTestsCounter.getValue());
case TEST_EXECUTION_TIME_KEY:
return createLongMeasure(context.getComponent(), leaf, counter.testExecutionTimeCounter.getValue());
case TEST_SUCCESS_DENSITY_KEY:
return createDensityMeasure(counter, context.getMetric().getDecimalScale());
default:
throw new IllegalStateException(String.format("Metric '%s' is not supported", metricKey));
}
}
private static Optional<Measure> createIntMeasure(Component currentComponent, Component leafComponent, Optional<Integer> metricValue) {
if (metricValue.isPresent() && leafComponent.getType().isDeeperThan(currentComponent.getType())) {
return Optional.of(Measure.newMeasureBuilder().create(metricValue.get()));
}
return Optional.empty();
}
private static Optional<Measure> createLongMeasure(Component currentComponent, Component leafComponent, Optional<Long> metricValue) {
if (metricValue.isPresent() && leafComponent.getType().isDeeperThan(currentComponent.getType())) {
return Optional.of(Measure.newMeasureBuilder().create(metricValue.get()));
}
return Optional.empty();
}
private static Optional<Measure> createDensityMeasure(UnitTestsCounter counter, int decimalScale) {
if (isPositive(counter.testsCounter.getValue(), true)
&& isPositive(counter.testsErrorsCounter.getValue(), false)
&& isPositive(counter.testsFailuresCounter.getValue(), false)) {
int tests = counter.testsCounter.getValue().get();
int errors = counter.testsErrorsCounter.getValue().get();
int failures = counter.testsFailuresCounter.getValue().get();
double density = (errors + failures) * 100D / tests;
return Optional.of(Measure.newMeasureBuilder().create(100D - density, decimalScale));
}
return Optional.empty();
}
private static boolean isPositive(Optional<Integer> value, boolean isStrictComparison) {
return value.isPresent() && (isStrictComparison ? (value.get() > 0) : (value.get() >= 0));
}
@Override
public String[] getOutputMetricKeys() {
return METRICS;
}
}
private static class UnitTestsCounter implements Counter<UnitTestsCounter> {
private final IntSumCounter testsCounter = new IntSumCounter(TESTS_KEY);
private final IntSumCounter testsErrorsCounter = new IntSumCounter(TEST_ERRORS_KEY);
private final IntSumCounter testsFailuresCounter = new IntSumCounter(TEST_FAILURES_KEY);
private final IntSumCounter skippedTestsCounter = new IntSumCounter(SKIPPED_TESTS_KEY);
private final LongSumCounter testExecutionTimeCounter = new LongSumCounter(TEST_EXECUTION_TIME_KEY);
private Component leaf;
@Override
public void aggregate(UnitTestsCounter counter) {
testsCounter.aggregate(counter.testsCounter);
testsErrorsCounter.aggregate(counter.testsErrorsCounter);
testsFailuresCounter.aggregate(counter.testsFailuresCounter);
skippedTestsCounter.aggregate(counter.skippedTestsCounter);
testExecutionTimeCounter.aggregate(counter.testExecutionTimeCounter);
}
@Override
public void initialize(CounterInitializationContext context) {
this.leaf = context.getLeaf();
testsCounter.initialize(context);
testsErrorsCounter.initialize(context);
testsFailuresCounter.initialize(context);
skippedTestsCounter.initialize(context);
testExecutionTimeCounter.initialize(context);
}
Component getLeaf() {
return leaf;
}
}
@Override
public String getDescription() {
return "Compute test measures";
}
}
| 7,951 | 44.181818 | 173 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/UpdateNeedIssueSyncStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
/**
* Updates need_issue_sync flag of project_branches so that tasks which are in progress, won't reindex again.
*/
public class UpdateNeedIssueSyncStep implements ComputationStep {
private final DbClient dbClient;
private final TreeRootHolder treeRootHolder;
public UpdateNeedIssueSyncStep(DbClient dbClient, TreeRootHolder treeRootHolder) {
this.dbClient = dbClient;
this.treeRootHolder = treeRootHolder;
}
@Override
public void execute(ComputationStep.Context context) {
try (DbSession dbSession = dbClient.openSession(false)) {
Component project = treeRootHolder.getRoot();
dbClient.branchDao().updateNeedIssueSync(dbSession, project.getUuid(), false);
dbSession.commit();
}
}
@Override
public String getDescription() {
return "Update need issue sync for branch";
}
}
| 1,967 | 34.142857 | 109 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/UpdateQualityProfilesLastUsedDateStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.Optional;
import java.util.Set;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import org.sonar.ce.task.projectanalysis.measure.MeasureRepository;
import org.sonar.ce.task.projectanalysis.metric.Metric;
import org.sonar.ce.task.projectanalysis.metric.MetricRepository;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.server.qualityprofile.QPMeasureData;
import org.sonar.server.qualityprofile.QualityProfile;
import static java.util.Collections.emptySet;
import static org.sonar.api.measures.CoreMetrics.QUALITY_PROFILES_KEY;
public class UpdateQualityProfilesLastUsedDateStep implements ComputationStep {
private final DbClient dbClient;
private final AnalysisMetadataHolder analysisMetadataHolder;
private final TreeRootHolder treeRootHolder;
private final MetricRepository metricRepository;
private final MeasureRepository measureRepository;
public UpdateQualityProfilesLastUsedDateStep(DbClient dbClient, AnalysisMetadataHolder analysisMetadataHolder, TreeRootHolder treeRootHolder, MetricRepository metricRepository,
MeasureRepository measureRepository) {
this.dbClient = dbClient;
this.analysisMetadataHolder = analysisMetadataHolder;
this.treeRootHolder = treeRootHolder;
this.metricRepository = metricRepository;
this.measureRepository = measureRepository;
}
@Override
public void execute(ComputationStep.Context context) {
Component root = treeRootHolder.getRoot();
Metric metric = metricRepository.getByKey(QUALITY_PROFILES_KEY);
Set<QualityProfile> qualityProfiles = parseQualityProfiles(measureRepository.getRawMeasure(root, metric));
try (DbSession dbSession = dbClient.openSession(true)) {
for (QualityProfile qualityProfile : qualityProfiles) {
updateDate(dbSession, qualityProfile.getQpKey(), analysisMetadataHolder.getAnalysisDate());
}
dbSession.commit();
}
}
private void updateDate(DbSession dbSession, String qProfileUuid, long lastUsedDate) {
// Traverse profiles from bottom to up in order to avoid DB deadlocks between multiple transactions.
// Example of hierarchy of profiles:
// A
// |- B
// |- C1
// |- C2
// Transaction #1 updates C1 then B then A
// Transaction #2 updates C2 then B then A
// Transaction #3 updates B then A
// No cross-dependencies are possible.
QProfileDto dto = dbClient.qualityProfileDao().selectOrFailByUuid(dbSession, qProfileUuid);
dbClient.qualityProfileDao().updateLastUsedDate(dbSession, dto, lastUsedDate);
String parentUuid = dto.getParentKee();
if (parentUuid != null) {
updateDate(dbSession, parentUuid, lastUsedDate);
}
}
@Override
public String getDescription() {
return "Update last usage date of quality profiles";
}
private static Set<QualityProfile> parseQualityProfiles(Optional<Measure> measure) {
if (!measure.isPresent()) {
return emptySet();
}
String data = measure.get().getStringValue();
return data == null ? emptySet() : QPMeasureData.fromJson(data).getProfiles();
}
}
| 4,304 | 40.394231 | 178 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/ValidateProjectStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import com.google.common.base.Joiner;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import org.sonar.api.utils.MessageException;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.ComponentVisitor;
import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit;
import org.sonar.ce.task.projectanalysis.component.DepthTraversalTypeAwareCrawler;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.projectanalysis.component.TypeAwareVisitorAdapter;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDao;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.SnapshotDto;
import static java.lang.String.format;
import static org.sonar.api.utils.DateUtils.formatDateTime;
import static org.sonar.core.component.ComponentKeys.ALLOWED_CHARACTERS_MESSAGE;
import static org.sonar.core.component.ComponentKeys.isValidProjectKey;
public class ValidateProjectStep implements ComputationStep {
private static final Joiner MESSAGES_JOINER = Joiner.on("\n o ");
private final DbClient dbClient;
private final TreeRootHolder treeRootHolder;
private final AnalysisMetadataHolder analysisMetadataHolder;
public ValidateProjectStep(DbClient dbClient, TreeRootHolder treeRootHolder, AnalysisMetadataHolder analysisMetadataHolder) {
this.dbClient = dbClient;
this.treeRootHolder = treeRootHolder;
this.analysisMetadataHolder = analysisMetadataHolder;
}
@Override
public void execute(ComputationStep.Context context) {
try (DbSession dbSession = dbClient.openSession(false)) {
Component root = treeRootHolder.getRoot();
ValidateProjectsVisitor visitor = new ValidateProjectsVisitor(dbSession, dbClient.componentDao());
new DepthTraversalTypeAwareCrawler(visitor).visit(root);
if (!visitor.validationMessages.isEmpty()) {
throw MessageException.of("Validation of project failed:\n o " + MESSAGES_JOINER.join(visitor.validationMessages));
}
}
}
@Override
public String getDescription() {
return "Validate project";
}
private class ValidateProjectsVisitor extends TypeAwareVisitorAdapter {
private final DbSession session;
private final ComponentDao componentDao;
private final List<String> validationMessages = new ArrayList<>();
public ValidateProjectsVisitor(DbSession session, ComponentDao componentDao) {
super(CrawlerDepthLimit.PROJECT, ComponentVisitor.Order.PRE_ORDER);
this.session = session;
this.componentDao = componentDao;
}
@Override
public void visitProject(Component rawProject) {
String rawProjectKey = rawProject.getKey();
Optional<ComponentDto> baseProjectOpt = loadBaseComponent(rawProjectKey);
if (baseProjectOpt.isPresent()) {
ComponentDto baseProject = baseProjectOpt.get();
validateAnalysisDate(baseProject);
validateProjectKey(baseProject);
}
}
private void validateProjectKey(ComponentDto baseProject) {
if (!isValidProjectKey(baseProject.getKey())) {
validationMessages.add(format("The project key ‘%s’ contains invalid characters. %s. You should update the project key with the expected format.", baseProject.getKey(),
ALLOWED_CHARACTERS_MESSAGE));
}
}
private void validateAnalysisDate(ComponentDto baseProject) {
Optional<SnapshotDto> snapshotDto = dbClient.snapshotDao().selectLastAnalysisByRootComponentUuid(session, baseProject.uuid());
long currentAnalysisDate = analysisMetadataHolder.getAnalysisDate();
Long lastAnalysisDate = snapshotDto.map(SnapshotDto::getCreatedAt).orElse(null);
if (lastAnalysisDate != null && currentAnalysisDate <= lastAnalysisDate) {
validationMessages.add(format("Date of analysis cannot be older than the date of the last known analysis on this project. Value: \"%s\". " +
"Latest analysis: \"%s\". It's only possible to rebuild the past in a chronological order.",
formatDateTime(new Date(currentAnalysisDate)), formatDateTime(new Date(lastAnalysisDate))));
}
}
private Optional<ComponentDto> loadBaseComponent(String rawComponentKey) {
// Load component from key to be able to detect issue (try to analyze a module, etc.)
if (analysisMetadataHolder.isBranch()) {
return componentDao.selectByKeyAndBranch(session, rawComponentKey, analysisMetadataHolder.getBranch().getName());
} else {
return componentDao.selectByKeyAndPullRequest(session, rawComponentKey, analysisMetadataHolder.getBranch().getPullRequestKey());
}
}
}
}
| 5,769 | 44.078125 | 176 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/step/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.ce.task.projectanalysis.step;
import javax.annotation.ParametersAreNonnullByDefault;
| 978 | 39.791667 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/taskprocessor/AuditHousekeepingFrequencyHelper.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.taskprocessor;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Optional;
import org.sonar.api.utils.System2;
import org.sonar.core.config.Frequency;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.property.PropertyDto;
import static org.sonar.core.config.PurgeConstants.AUDIT_HOUSEKEEPING_FREQUENCY;
import static org.sonar.core.config.PurgeProperties.DEFAULT_FREQUENCY;
public class AuditHousekeepingFrequencyHelper {
private final System2 system2;
public AuditHousekeepingFrequencyHelper(System2 system2) {
this.system2 = system2;
}
public PropertyDto getHouseKeepingFrequency(DbClient dbClient, DbSession dbSession) {
return Optional.ofNullable(dbClient.propertiesDao()
.selectGlobalProperty(dbSession, AUDIT_HOUSEKEEPING_FREQUENCY))
.orElse(defaultAuditHouseKeepingProperty());
}
public long getThresholdDate(String frequency) {
Optional<Frequency> housekeepingFrequency = Arrays.stream(Frequency.values())
.filter(f -> f.name().equalsIgnoreCase(frequency)).findFirst();
if (housekeepingFrequency.isEmpty()) {
throw new IllegalArgumentException("Unsupported frequency: " + frequency);
}
return Instant.ofEpochMilli(system2.now())
.minus(housekeepingFrequency.get().getDays(), ChronoUnit.DAYS)
.toEpochMilli();
}
private static PropertyDto defaultAuditHouseKeepingProperty() {
PropertyDto property = new PropertyDto();
property.setKey(AUDIT_HOUSEKEEPING_FREQUENCY);
property.setValue(DEFAULT_FREQUENCY);
return property;
}
}
| 2,506 | 36.41791 | 87 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/taskprocessor/AuditPurgeStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.taskprocessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.core.util.logs.Profiler;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.property.PropertyDto;
import static java.lang.String.format;
public final class AuditPurgeStep implements ComputationStep {
private static final Logger LOG = LoggerFactory.getLogger(AuditPurgeStep.class);
private final AuditHousekeepingFrequencyHelper auditHousekeepingFrequencyHelper;
private final DbClient dbClient;
public AuditPurgeStep(AuditHousekeepingFrequencyHelper auditHousekeepingFrequencyHelper, DbClient dbClient) {
this.auditHousekeepingFrequencyHelper = auditHousekeepingFrequencyHelper;
this.dbClient = dbClient;
}
@Override
public void execute(Context context) {
try (DbSession dbSession = dbClient.openSession(false)) {
PropertyDto property = auditHousekeepingFrequencyHelper.getHouseKeepingFrequency(dbClient, dbSession);
long threshold = auditHousekeepingFrequencyHelper.getThresholdDate(property.getValue());
Profiler profiler = Profiler.create(LOG).logTimeLast(true);
profiler.startInfo("Purge audit logs");
long deleted = dbClient.auditDao().deleteBefore(dbSession, threshold);
dbSession.commit();
profiler.stopInfo(format("Purged %d audit logs", deleted));
}
}
@Override
public String getDescription() {
return "Purge Audit Logs";
}
}
| 2,377 | 37.983607 | 111 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/taskprocessor/AuditPurgeTaskModule.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.taskprocessor;
import org.sonar.core.platform.Module;
public class AuditPurgeTaskModule extends Module {
@Override
protected void configureModule() {
add(AuditPurgeTaskProcessor.class);
}
}
| 1,088 | 34.129032 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/taskprocessor/AuditPurgeTaskProcessor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.taskprocessor;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import javax.annotation.CheckForNull;
import org.sonar.ce.task.CeTask;
import org.sonar.ce.task.CeTaskResult;
import org.sonar.ce.task.container.TaskContainer;
import org.sonar.ce.task.container.TaskContainerImpl;
import org.sonar.ce.task.projectanalysis.step.AbstractComputationSteps;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.ce.task.step.ComputationStepExecutor;
import org.sonar.ce.task.taskprocessor.CeTaskProcessor;
import org.sonar.core.platform.Container;
import org.sonar.core.platform.ContainerPopulator;
import org.sonar.core.platform.SpringComponentContainer;
import static org.sonar.db.ce.CeTaskTypes.AUDIT_PURGE;
public class AuditPurgeTaskProcessor implements CeTaskProcessor {
private static final Set<String> HANDLED_TYPES = Set.of(AUDIT_PURGE);
private final SpringComponentContainer ceEngineContainer;
public AuditPurgeTaskProcessor(SpringComponentContainer ceEngineContainer) {
this.ceEngineContainer = ceEngineContainer;
}
@Override
public Set<String> getHandledCeTaskTypes() {
return HANDLED_TYPES;
}
@CheckForNull
@Override
public CeTaskResult process(CeTask task) {
try (TaskContainer container = new TaskContainerImpl(ceEngineContainer, newContainerPopulator(task))) {
container.bootup();
container.getComponentByType(ComputationStepExecutor.class).execute();
}
return null;
}
static ContainerPopulator<TaskContainer> newContainerPopulator(CeTask task) {
return taskContainer -> {
taskContainer.add(task);
taskContainer.add(AuditHousekeepingFrequencyHelper.class);
taskContainer.add(AuditPurgeStep.class);
taskContainer.add(new AuditPurgeComputationSteps(taskContainer));
taskContainer.add(ComputationStepExecutor.class);
};
}
public static final class AuditPurgeComputationSteps extends AbstractComputationSteps {
public AuditPurgeComputationSteps(Container container) {
super(container);
}
@Override
public List<Class<? extends ComputationStep>> orderedStepClasses() {
return Arrays.asList(AuditPurgeStep.class);
}
}
}
| 3,081 | 34.837209 | 107 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/taskprocessor/IgnoreOrphanBranchStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.taskprocessor;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.ce.task.CeTask;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
public final class IgnoreOrphanBranchStep implements ComputationStep {
private static final Logger LOG = LoggerFactory.getLogger(IgnoreOrphanBranchStep.class);
private final CeTask ceTask;
private final DbClient dbClient;
public IgnoreOrphanBranchStep(CeTask ceTask, DbClient dbClient) {
this.ceTask = ceTask;
this.dbClient = dbClient;
}
@Override
public void execute(Context context) {
String entityUuid = ceTask.getEntity().orElseThrow(() -> new UnsupportedOperationException("entity not found in task")).getUuid();
String componentUuid = ceTask.getComponent().orElseThrow(() -> new UnsupportedOperationException("component not found in task")).getUuid();
try (DbSession dbSession = dbClient.openSession(false)) {
Optional<ComponentDto> componentDto = dbClient.componentDao().selectByUuid(dbSession, entityUuid);
if(!componentDto.isPresent()){
LOG.info("reindexation task has been trigger on an orphan branch. removing any exclude_from_purge flag, and skip the indexation");
dbClient.branchDao().updateExcludeFromPurge(dbSession, componentUuid, false);
dbClient.branchDao().updateNeedIssueSync(dbSession, componentUuid, false);
dbSession.commit();
}
}
}
@Override
public String getDescription() {
return "Ignore orphan component";
}
}
| 2,512 | 39.532258 | 143 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/taskprocessor/IndexIssuesStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.taskprocessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.ce.task.CeTask;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.server.issue.index.IssueIndexer;
public final class IndexIssuesStep implements ComputationStep {
private static final Logger LOG = LoggerFactory.getLogger(IndexIssuesStep.class);
private final CeTask ceTask;
private final DbClient dbClient;
private final IssueIndexer issueIndexer;
public IndexIssuesStep(CeTask ceTask, DbClient dbClient, IssueIndexer issueIndexer) {
this.ceTask = ceTask;
this.dbClient = dbClient;
this.issueIndexer = issueIndexer;
}
@Override
public void execute(Context context) {
String branchUuid = ceTask.getComponent().orElseThrow(() -> new UnsupportedOperationException("component not found in task")).getUuid();
try (DbSession dbSession = dbClient.openSession(false)) {
dbClient.branchDao().selectByUuid(dbSession, branchUuid)
.ifPresent(branchDto -> {
if (branchDto.isNeedIssueSync()) {
LOG.info("indexing issues of branch {}", branchUuid);
issueIndexer.indexOnAnalysis(branchUuid);
dbClient.branchDao().updateNeedIssueSync(dbSession, branchUuid, false);
dbSession.commit();
} else {
// branch has been analyzed since task was created, do not index issues twice
LOG.debug("issues of branch {} are already in sync", branchUuid);
}
});
}
}
@Override
public String getDescription() {
return "index issues";
}
}
| 2,533 | 36.264706 | 140 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/taskprocessor/IssueSyncTaskModule.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.taskprocessor;
import org.sonar.core.platform.Module;
public class IssueSyncTaskModule extends Module {
@Override
protected void configureModule() {
add(
IgnoreOrphanBranchStep.class,
IssueSyncTaskProcessor.class);
}
}
| 1,129 | 33.242424 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/taskprocessor/IssueSyncTaskProcessor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.taskprocessor;
import com.google.common.collect.ImmutableSet;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import javax.annotation.CheckForNull;
import org.sonar.ce.task.CeTask;
import org.sonar.ce.task.CeTaskResult;
import org.sonar.ce.task.container.TaskContainer;
import org.sonar.ce.task.container.TaskContainerImpl;
import org.sonar.ce.task.projectanalysis.step.AbstractComputationSteps;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.ce.task.step.ComputationStepExecutor;
import org.sonar.ce.task.taskprocessor.CeTaskProcessor;
import org.sonar.core.platform.Container;
import org.sonar.core.platform.ContainerPopulator;
import org.sonar.core.platform.SpringComponentContainer;
import static org.sonar.db.ce.CeTaskTypes.BRANCH_ISSUE_SYNC;
public class IssueSyncTaskProcessor implements CeTaskProcessor {
private static final Set<String> HANDLED_TYPES = ImmutableSet.of(BRANCH_ISSUE_SYNC);
private final SpringComponentContainer ceEngineContainer;
public IssueSyncTaskProcessor(SpringComponentContainer ceEngineContainer) {
this.ceEngineContainer = ceEngineContainer;
}
@Override
public Set<String> getHandledCeTaskTypes() {
return HANDLED_TYPES;
}
@CheckForNull
@Override
public CeTaskResult process(CeTask task) {
try (TaskContainer container = new TaskContainerImpl(ceEngineContainer, newContainerPopulator(task))) {
container.bootup();
container.getComponentByType(ComputationStepExecutor.class).execute();
}
return null;
}
static ContainerPopulator<TaskContainer> newContainerPopulator(CeTask task) {
return taskContainer -> {
taskContainer.add(task);
taskContainer.add(IgnoreOrphanBranchStep.class);
taskContainer.add(IndexIssuesStep.class);
taskContainer.add(new SyncComputationSteps(taskContainer));
taskContainer.add(ComputationStepExecutor.class);
};
}
public static final class SyncComputationSteps extends AbstractComputationSteps {
public SyncComputationSteps(Container container) {
super(container);
}
@Override
public List<Class<? extends ComputationStep>> orderedStepClasses() {
return Arrays.asList(IgnoreOrphanBranchStep.class, IndexIssuesStep.class);
}
}
}
| 3,153 | 34.438202 | 107 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/taskprocessor/ReportTaskProcessor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.taskprocessor;
import java.util.Collections;
import java.util.Set;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.ce.task.CeTask;
import org.sonar.ce.task.CeTaskResult;
import org.sonar.ce.task.container.TaskContainer;
import org.sonar.ce.task.projectanalysis.container.ContainerFactory;
import org.sonar.ce.task.step.ComputationStepExecutor;
import org.sonar.ce.task.taskprocessor.CeTaskProcessor;
import org.sonar.ce.task.taskprocessor.TaskResultHolder;
import org.sonar.core.platform.SpringComponentContainer;
import org.sonar.db.ce.CeTaskTypes;
import org.sonar.ce.task.projectanalysis.container.ReportAnalysisComponentProvider;
import org.springframework.beans.factory.annotation.Autowired;
public class ReportTaskProcessor implements CeTaskProcessor {
private static final Set<String> HANDLED_TYPES = Collections.singleton(CeTaskTypes.REPORT);
private final ContainerFactory containerFactory;
private final SpringComponentContainer serverContainer;
@CheckForNull
private final ReportAnalysisComponentProvider[] componentProviders;
@Autowired(required = false)
public ReportTaskProcessor(ContainerFactory containerFactory, SpringComponentContainer serverContainer, @Nullable ReportAnalysisComponentProvider[] componentProviders) {
this.containerFactory = containerFactory;
this.serverContainer = serverContainer;
this.componentProviders = componentProviders;
}
/**
* Used when loaded in WebServer where none of the dependencies are available and where only
* {@link #getHandledCeTaskTypes()} will be called.
*/
@Autowired(required = false)
public ReportTaskProcessor() {
this.containerFactory = null;
this.serverContainer = null;
this.componentProviders = null;
}
@Override
public Set<String> getHandledCeTaskTypes() {
return HANDLED_TYPES;
}
@Override
public CeTaskResult process(CeTask task) {
try (TaskContainer ceContainer = containerFactory.create(serverContainer, task, componentProviders)) {
ceContainer.bootup();
ceContainer.getComponentByType(ComputationStepExecutor.class).execute();
return ceContainer.getComponentByType(TaskResultHolder.class).getResult();
}
}
}
| 3,115 | 37.95 | 171 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/taskprocessor/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.ce.task.projectanalysis.taskprocessor;
import javax.annotation.ParametersAreNonnullByDefault;
| 987 | 40.166667 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/util/cache/CacheLoader.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.util.cache;
import javax.annotation.CheckForNull;
import java.util.Collection;
import java.util.Map;
public interface CacheLoader<K, V> {
/**
* Value associated with the requested key. Null if key is not found.
*/
@CheckForNull
V load(K key);
/**
* All the requested keys must be included in the map result. Value in map is null when
* the key is not found.
*/
Map<K, V> loadAll(Collection<? extends K> keys);
}
| 1,327 | 31.390244 | 89 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/util/cache/DiskCache.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.util.cache;
import java.io.Serializable;
import org.sonar.core.util.CloseableIterator;
public interface DiskCache<O extends Serializable> {
long fileSize();
CacheAppender<O> newAppender();
CloseableIterator<O> traverse();
interface CacheAppender<I extends Serializable> extends AutoCloseable {
CacheAppender<I> append(I object);
@Override
void close();
}
}
| 1,270 | 31.589744 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/util/cache/DoubleCache.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.util.cache;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
public class DoubleCache {
private static final Double ONE = 1.0;
private static final Double HUNDRED = 100.0;
private static final Double ZERO = 0.0;
private DoubleCache() {
// static only
}
@CheckForNull
public static Double intern(@Nullable Double num) {
if (ZERO.equals(num)) {
return ZERO;
}
if (ONE.equals(num)) {
return ONE;
}
if (HUNDRED.equals(num)) {
return HUNDRED;
}
return num;
}
}
| 1,434 | 28.895833 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/util/cache/JavaSerializationDiskCache.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.util.cache;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.sonar.api.utils.System2;
import org.sonar.core.util.CloseableIterator;
/**
* Serialize and deserialize objects on disk. No search capabilities, only traversal (full scan).
*/
public class JavaSerializationDiskCache<O extends Serializable> implements DiskCache<O> {
private final File file;
private final System2 system2;
public JavaSerializationDiskCache(File file, System2 system2) {
this.system2 = system2;
this.file = file;
OutputStream output = null;
boolean threw = true;
try {
// writes the serialization stream header required when calling "traverse()"
// on empty stream. Moreover it allows to call multiple times "newAppender()"
output = new ObjectOutputStream(new FileOutputStream(file));
output.flush();
threw = false;
} catch (IOException e) {
throw new IllegalStateException("Fail to write into file: " + file, e);
} finally {
if (threw) {
// do not hide initial exception
IOUtils.closeQuietly(output);
} else {
// raise an exception if can't close
system2.close(output);
}
}
}
@Override
public long fileSize() {
return file.length();
}
@Override
public CacheAppender<O> newAppender() {
return new JavaSerializationCacheAppender();
}
@Override
public CloseableIterator<O> traverse() {
try {
return new ObjectInputStreamIterator<>(FileUtils.openInputStream(file));
} catch (IOException e) {
throw new IllegalStateException("Fail to traverse file: " + file, e);
}
}
public class JavaSerializationCacheAppender<O extends Serializable> implements CacheAppender<O> {
private final ObjectOutputStream output;
private JavaSerializationCacheAppender() {
try {
this.output = new ObjectOutputStream(new FileOutputStream(file, true)) {
@Override
protected void writeStreamHeader() {
// do not write stream headers as it's already done in constructor of DiskCache
}
};
} catch (IOException e) {
throw new IllegalStateException("Fail to open file " + file, e);
}
}
@Override
public CacheAppender append(O object) {
try {
output.writeObject(object);
output.reset();
return this;
} catch (IOException e) {
throw new IllegalStateException("Fail to write into file " + file, e);
}
}
@Override
public void close() {
system2.close(output);
}
}
}
| 3,670 | 30.376068 | 99 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/util/cache/MemoryCache.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.util.cache;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.CheckForNull;
/**
* This in-memory cache relies on {@link CacheLoader} to
* load missing elements.
* Warning - all searches are kept in memory, even when elements are not found.
*/
public class MemoryCache<K, V> {
private final CacheLoader<K, V> loader;
private final Map<K, V> map = new HashMap<>();
public MemoryCache(CacheLoader<K, V> loader) {
this.loader = loader;
}
@CheckForNull
public V getNullable(K key) {
V value = map.get(key);
if (value == null && !map.containsKey(key)) {
value = loader.load(key);
map.put(key, value);
}
return value;
}
public V get(K key) {
V value = getNullable(key);
if (value == null) {
throw new IllegalStateException("No cache entry found for key: " + key);
}
return value;
}
/**
* Get values associated with keys. All the requested keys are included
* in the Map result. Value is null if the key is not found in cache.
*/
public Map<K, V> getAll(Iterable<K> keys) {
List<K> missingKeys = new ArrayList<>();
Map<K, V> result = new HashMap<>();
for (K key : keys) {
V value = map.get(key);
if (value == null && !map.containsKey(key)) {
missingKeys.add(key);
} else {
result.put(key, value);
}
}
if (!missingKeys.isEmpty()) {
Map<K, V> missingValues = loader.loadAll(missingKeys);
map.putAll(missingValues);
result.putAll(missingValues);
for (K missingKey : missingKeys) {
if (!map.containsKey(missingKey)) {
map.put(missingKey, null);
result.put(missingKey, null);
}
}
}
return result;
}
public void clear() {
map.clear();
}
}
| 2,724 | 28.301075 | 79 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/util/cache/ObjectInputStreamIterator.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.util.cache;
import com.google.common.base.Throwables;
import org.apache.commons.io.IOUtils;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import org.sonar.core.util.CloseableIterator;
public class ObjectInputStreamIterator<E> extends CloseableIterator<E> {
private ObjectInputStream stream;
public ObjectInputStreamIterator(InputStream stream) throws IOException {
this.stream = new ObjectInputStream(stream);
}
@Override
protected E doNext() {
try {
return (E) stream.readObject();
} catch (EOFException e) {
return null;
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
@Override
protected void doClose() {
IOUtils.closeQuietly(stream);
}
}
| 1,678 | 29.527273 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/util/cache/ProtobufIssueDiskCache.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.util.cache;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableSet;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.Collections;
import java.util.Date;
import java.util.Map;
import javax.annotation.CheckForNull;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rules.RuleType;
import org.sonar.api.utils.Duration;
import org.sonar.api.utils.System2;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.DefaultIssueComment;
import org.sonar.core.issue.FieldDiffs;
import org.sonar.core.util.CloseableIterator;
import org.sonar.core.util.Protobuf;
import org.sonar.db.protobuf.DbIssues;
import static java.util.Optional.ofNullable;
public class ProtobufIssueDiskCache implements DiskCache<DefaultIssue> {
private static final String TAGS_SEPARATOR = ",";
private static final Splitter STRING_LIST_SPLITTER = Splitter.on(',').trimResults().omitEmptyStrings();
private final File file;
private final System2 system2;
public ProtobufIssueDiskCache(File file, System2 system2) {
this.file = file;
this.system2 = system2;
}
@Override
public long fileSize() {
return file.length();
}
@Override
public CacheAppender<DefaultIssue> newAppender() {
try {
return new ProtoCacheAppender();
} catch (FileNotFoundException e) {
throw new IllegalStateException(e);
}
}
@Override
public CloseableIterator<DefaultIssue> traverse() {
CloseableIterator<IssueCache.Issue> protoIterator = Protobuf.readStream(file, IssueCache.Issue.parser());
return new CloseableIterator<>() {
@CheckForNull
@Override
protected DefaultIssue doNext() {
if (protoIterator.hasNext()) {
return toDefaultIssue(protoIterator.next());
}
return null;
}
@Override
protected void doClose() {
protoIterator.close();
}
};
}
@VisibleForTesting
static DefaultIssue toDefaultIssue(IssueCache.Issue next) {
DefaultIssue defaultIssue = new DefaultIssue();
defaultIssue.setKey(next.getKey());
defaultIssue.setType(RuleType.valueOf(next.getRuleType()));
defaultIssue.setComponentUuid(next.hasComponentUuid() ? next.getComponentUuid() : null);
defaultIssue.setComponentKey(next.getComponentKey());
defaultIssue.setProjectUuid(next.getProjectUuid());
defaultIssue.setProjectKey(next.getProjectKey());
defaultIssue.setRuleKey(RuleKey.parse(next.getRuleKey()));
defaultIssue.setLanguage(next.hasLanguage() ? next.getLanguage() : null);
defaultIssue.setSeverity(next.hasSeverity() ? next.getSeverity() : null);
defaultIssue.setManualSeverity(next.getManualSeverity());
defaultIssue.setMessage(next.hasMessage() ? next.getMessage() : null);
defaultIssue.setMessageFormattings(next.hasMessageFormattings() ? next.getMessageFormattings() : null);
defaultIssue.setLine(next.hasLine() ? next.getLine() : null);
defaultIssue.setGap(next.hasGap() ? next.getGap() : null);
defaultIssue.setEffort(next.hasEffort() ? Duration.create(next.getEffort()) : null);
defaultIssue.setStatus(next.getStatus());
defaultIssue.setResolution(next.hasResolution() ? next.getResolution() : null);
defaultIssue.setAssigneeUuid(next.hasAssigneeUuid() ? next.getAssigneeUuid() : null);
defaultIssue.setAssigneeLogin(next.hasAssigneeLogin() ? next.getAssigneeLogin() : null);
defaultIssue.setChecksum(next.hasChecksum() ? next.getChecksum() : null);
defaultIssue.setAuthorLogin(next.hasAuthorLogin() ? next.getAuthorLogin() : null);
next.getCommentsList().forEach(c -> defaultIssue.addComment(toDefaultIssueComment(c)));
defaultIssue.setTags(ImmutableSet.copyOf(STRING_LIST_SPLITTER.split(next.getTags())));
defaultIssue.setCodeVariants(ImmutableSet.copyOf(STRING_LIST_SPLITTER.split(next.getCodeVariants())));
defaultIssue.setRuleDescriptionContextKey(next.hasRuleDescriptionContextKey() ? next.getRuleDescriptionContextKey() : null);
defaultIssue.setLocations(next.hasLocations() ? next.getLocations() : null);
defaultIssue.setIsFromExternalRuleEngine(next.getIsFromExternalRuleEngine());
defaultIssue.setCreationDate(new Date(next.getCreationDate()));
defaultIssue.setUpdateDate(next.hasUpdateDate() ? new Date(next.getUpdateDate()) : null);
defaultIssue.setCloseDate(next.hasCloseDate() ? new Date(next.getCloseDate()) : null);
defaultIssue.setCurrentChangeWithoutAddChange(next.hasCurrentChanges() ? toDefaultIssueChanges(next.getCurrentChanges()) : null);
defaultIssue.setNew(next.getIsNew());
defaultIssue.setIsOnChangedLine(next.getIsOnChangedLine());
defaultIssue.setIsNewCodeReferenceIssue(next.getIsNewCodeReferenceIssue());
defaultIssue.setCopied(next.getIsCopied());
defaultIssue.setBeingClosed(next.getBeingClosed());
defaultIssue.setOnDisabledRule(next.getOnDisabledRule());
defaultIssue.setChanged(next.getIsChanged());
defaultIssue.setSendNotifications(next.getSendNotifications());
defaultIssue.setSelectedAt(next.hasSelectedAt() ? next.getSelectedAt() : null);
defaultIssue.setQuickFixAvailable(next.getQuickFixAvailable());
defaultIssue.setIsNoLongerNewCodeReferenceIssue(next.getIsNoLongerNewCodeReferenceIssue());
for (IssueCache.FieldDiffs protoFieldDiffs : next.getChangesList()) {
defaultIssue.addChange(toDefaultIssueChanges(protoFieldDiffs));
}
return defaultIssue;
}
@VisibleForTesting
static IssueCache.Issue toProto(IssueCache.Issue.Builder builder, DefaultIssue defaultIssue) {
builder.clear();
builder.setKey(defaultIssue.key());
builder.setRuleType(defaultIssue.type().getDbConstant());
ofNullable(defaultIssue.componentUuid()).ifPresent(builder::setComponentUuid);
builder.setComponentKey(defaultIssue.componentKey());
builder.setProjectUuid(defaultIssue.projectUuid());
builder.setProjectKey(defaultIssue.projectKey());
builder.setRuleKey(defaultIssue.ruleKey().toString());
ofNullable(defaultIssue.language()).ifPresent(builder::setLanguage);
ofNullable(defaultIssue.severity()).ifPresent(builder::setSeverity);
builder.setManualSeverity(defaultIssue.manualSeverity());
ofNullable(defaultIssue.message()).ifPresent(builder::setMessage);
ofNullable(defaultIssue.getMessageFormattings()).ifPresent(m -> builder.setMessageFormattings((DbIssues.MessageFormattings) m));
ofNullable(defaultIssue.line()).ifPresent(builder::setLine);
ofNullable(defaultIssue.gap()).ifPresent(builder::setGap);
ofNullable(defaultIssue.effort()).map(Duration::toMinutes).ifPresent(builder::setEffort);
builder.setStatus(defaultIssue.status());
ofNullable(defaultIssue.resolution()).ifPresent(builder::setResolution);
ofNullable(defaultIssue.assignee()).ifPresent(builder::setAssigneeUuid);
ofNullable(defaultIssue.assigneeLogin()).ifPresent(builder::setAssigneeLogin);
ofNullable(defaultIssue.checksum()).ifPresent(builder::setChecksum);
ofNullable(defaultIssue.authorLogin()).ifPresent(builder::setAuthorLogin);
defaultIssue.defaultIssueComments().forEach(c -> builder.addComments(toProtoComment(c)));
ofNullable(defaultIssue.tags()).ifPresent(t -> builder.setTags(String.join(TAGS_SEPARATOR, t)));
ofNullable(defaultIssue.codeVariants()).ifPresent(codeVariant -> builder.setCodeVariants(String.join(TAGS_SEPARATOR, codeVariant)));
ofNullable(defaultIssue.getLocations()).ifPresent(l -> builder.setLocations((DbIssues.Locations) l));
defaultIssue.getRuleDescriptionContextKey().ifPresent(builder::setRuleDescriptionContextKey);
builder.setIsFromExternalRuleEngine(defaultIssue.isFromExternalRuleEngine());
builder.setCreationDate(defaultIssue.creationDate().getTime());
ofNullable(defaultIssue.updateDate()).map(Date::getTime).ifPresent(builder::setUpdateDate);
ofNullable(defaultIssue.closeDate()).map(Date::getTime).ifPresent(builder::setCloseDate);
ofNullable(defaultIssue.currentChange()).ifPresent(c -> builder.setCurrentChanges(toProtoIssueChanges(c)));
builder.setIsNew(defaultIssue.isNew());
builder.setIsOnChangedLine(defaultIssue.isOnChangedLine());
builder.setIsNewCodeReferenceIssue(defaultIssue.isNewCodeReferenceIssue());
builder.setIsCopied(defaultIssue.isCopied());
builder.setBeingClosed(defaultIssue.isBeingClosed());
builder.setOnDisabledRule(defaultIssue.isOnDisabledRule());
builder.setIsChanged(defaultIssue.isChanged());
builder.setSendNotifications(defaultIssue.mustSendNotifications());
ofNullable(defaultIssue.selectedAt()).ifPresent(builder::setSelectedAt);
builder.setQuickFixAvailable(defaultIssue.isQuickFixAvailable());
builder.setIsNoLongerNewCodeReferenceIssue(defaultIssue.isNoLongerNewCodeReferenceIssue());
for (FieldDiffs fieldDiffs : defaultIssue.changes()) {
builder.addChanges(toProtoIssueChanges(fieldDiffs));
}
return builder.build();
}
private static DefaultIssueComment toDefaultIssueComment(IssueCache.Comment comment) {
DefaultIssueComment issueComment = new DefaultIssueComment()
.setCreatedAt(new Date(comment.getCreatedAt()))
.setUpdatedAt(new Date(comment.getUpdatedAt()))
.setNew(comment.getIsNew())
.setKey(comment.getKey())
.setIssueKey(comment.getIssueKey())
.setMarkdownText(comment.getMarkdownText());
if (comment.hasUserUuid()) {
issueComment.setUserUuid(comment.getUserUuid());
}
return issueComment;
}
private static IssueCache.Comment toProtoComment(DefaultIssueComment comment) {
IssueCache.Comment.Builder builder = IssueCache.Comment.newBuilder()
.setCreatedAt(comment.createdAt().getTime())
.setUpdatedAt(comment.updatedAt().getTime())
.setIsNew(comment.isNew())
.setKey(comment.key())
.setIssueKey(comment.issueKey())
.setMarkdownText(comment.markdownText());
if (comment.userUuid() != null) {
builder.setUserUuid(comment.userUuid());
}
return builder.build();
}
private static FieldDiffs toDefaultIssueChanges(IssueCache.FieldDiffs fieldDiffs) {
FieldDiffs defaultIssueFieldDiffs = new FieldDiffs()
.setUserUuid(fieldDiffs.getUserUuid())
.setCreationDate(new Date(fieldDiffs.getCreationDate()));
if (fieldDiffs.hasIssueKey()) {
defaultIssueFieldDiffs.setIssueKey(fieldDiffs.getIssueKey());
}
for (Map.Entry<String, IssueCache.Diff> e : fieldDiffs.getDiffsMap().entrySet()) {
defaultIssueFieldDiffs.setDiff(e.getKey(),
e.getValue().hasOldValue() ? e.getValue().getOldValue() : null,
e.getValue().hasNewValue() ? e.getValue().getNewValue() : null);
}
return defaultIssueFieldDiffs;
}
private static IssueCache.FieldDiffs toProtoIssueChanges(FieldDiffs fieldDiffs) {
IssueCache.FieldDiffs.Builder builder = IssueCache.FieldDiffs.newBuilder()
.setCreationDate(fieldDiffs.creationDate().getTime());
fieldDiffs.issueKey().ifPresent(builder::setIssueKey);
fieldDiffs.userUuid().ifPresent(builder::setUserUuid);
for (Map.Entry<String, FieldDiffs.Diff> e : fieldDiffs.diffs().entrySet()) {
IssueCache.Diff.Builder diffBuilder = IssueCache.Diff.newBuilder();
Serializable oldValue = e.getValue().oldValue();
if (oldValue != null) {
diffBuilder.setOldValue(oldValue.toString());
}
Serializable newValue = e.getValue().newValue();
if (newValue != null) {
diffBuilder.setNewValue(newValue.toString());
}
builder.putDiffs(e.getKey(), diffBuilder.build());
}
return builder.build();
}
private class ProtoCacheAppender implements CacheAppender<DefaultIssue> {
private final OutputStream out;
private final IssueCache.Issue.Builder builder;
private ProtoCacheAppender() throws FileNotFoundException {
this.out = new BufferedOutputStream(new FileOutputStream(file, true));
this.builder = IssueCache.Issue.newBuilder();
}
@Override
public CacheAppender append(DefaultIssue object) {
Protobuf.writeStream(Collections.singleton(toProto(builder, object)), out);
return this;
}
@Override
public void close() {
system2.close(out);
}
}
}
| 13,301 | 44.399317 | 136 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/util/cache/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.ce.task.projectanalysis.util.cache;
import javax.annotation.ParametersAreNonnullByDefault;
| 984 | 40.041667 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/view/TriggerViewRefreshDelegate.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.view;
import java.util.OptionalInt;
import org.sonar.server.project.Project;
public interface TriggerViewRefreshDelegate {
/**
* Triggers the refresh of portfolios and applications
* associated to the project.
*
* @return the number of portfolios and applications being refreshed,
* or {@link OptionalInt#empty()} if not applicable.
*/
OptionalInt triggerFrom(Project project);
String getQualifier();
}
| 1,317 | 32.794872 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/view/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.ce.task.projectanalysis.view;
import javax.annotation.ParametersAreNonnullByDefault;
| 978 | 39.791667 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/webhook/WebhookPostTask.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.webhook;
import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;
import org.sonar.api.ce.posttask.PostProjectAnalysisTask;
import org.sonar.ce.task.projectanalysis.api.posttask.QGToEvaluatedQG;
import org.sonar.server.qualitygate.EvaluatedQualityGate;
import org.sonar.server.webhook.Analysis;
import org.sonar.server.webhook.Branch;
import org.sonar.server.webhook.CeTask;
import org.sonar.server.webhook.Project;
import org.sonar.server.webhook.WebHooks;
import org.sonar.server.webhook.WebhookPayload;
import org.sonar.server.webhook.WebhookPayloadFactory;
public class WebhookPostTask implements PostProjectAnalysisTask {
private final WebhookPayloadFactory payloadFactory;
private final WebHooks webHooks;
public WebhookPostTask(WebhookPayloadFactory payloadFactory, WebHooks webHooks) {
this.payloadFactory = payloadFactory;
this.webHooks = webHooks;
}
@Override
public String getDescription() {
return "Webhooks";
}
@Override
public void finished(Context context) {
ProjectAnalysis projectAnalysis = context.getProjectAnalysis();
WebHooks.Analysis analysis = new WebHooks.Analysis(
projectAnalysis.getProject().getUuid(),
projectAnalysis.getAnalysis().map(org.sonar.api.ce.posttask.Analysis::getAnalysisUuid).orElse(null),
projectAnalysis.getCeTask().getId());
Supplier<WebhookPayload> payloadSupplier = () -> payloadFactory.create(convert(projectAnalysis));
webHooks.sendProjectAnalysisUpdate(analysis, payloadSupplier, context.getLogStatistics());
}
private static org.sonar.server.webhook.ProjectAnalysis convert(ProjectAnalysis projectAnalysis) {
CeTask ceTask = new CeTask(projectAnalysis.getCeTask().getId(), CeTask.Status.valueOf(projectAnalysis.getCeTask().getStatus().name()));
Analysis analysis = projectAnalysis.getAnalysis().map(a -> new Analysis(a.getAnalysisUuid(), a.getDate().getTime(), a.getRevision().orElse(null))).orElse(null);
Branch branch = projectAnalysis.getBranch().map(b -> new Branch(b.isMain(), b.getName().orElse(null), Branch.Type.valueOf(b.getType().name()))).orElse(null);
EvaluatedQualityGate qualityGate = Optional.ofNullable(projectAnalysis.getQualityGate())
.map(QGToEvaluatedQG.INSTANCE)
.orElse(null);
Long date = projectAnalysis.getAnalysis().map(a -> a.getDate().getTime()).orElse(null);
Map<String, String> properties = projectAnalysis.getScannerContext().getProperties();
Project project = new Project(projectAnalysis.getProject().getUuid(), projectAnalysis.getProject().getKey(), projectAnalysis.getProject().getName());
return new org.sonar.server.webhook.ProjectAnalysis(project, ceTask, analysis, branch, qualityGate, date, properties);
}
}
| 3,631 | 46.789474 | 164 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/webhook/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.ce.task.projectanalysis.webhook;
import javax.annotation.ParametersAreNonnullByDefault;
| 981 | 39.916667 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/ProjectExportComputationSteps.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectexport;
import java.util.Arrays;
import java.util.List;
import org.sonar.ce.task.container.TaskContainer;
import org.sonar.ce.task.projectanalysis.step.AbstractComputationSteps;
import org.sonar.ce.task.projectexport.analysis.ExportAnalysesStep;
import org.sonar.ce.task.projectexport.branches.ExportBranchesStep;
import org.sonar.ce.task.projectexport.component.ExportComponentsStep;
import org.sonar.ce.task.projectexport.file.ExportLineHashesStep;
import org.sonar.ce.task.projectexport.issue.ExportIssuesChangelogStep;
import org.sonar.ce.task.projectexport.issue.ExportIssuesStep;
import org.sonar.ce.task.projectexport.rule.ExportAdHocRulesStep;
import org.sonar.ce.task.projectexport.rule.ExportRuleStep;
import org.sonar.ce.task.projectexport.steps.ExportEventsStep;
import org.sonar.ce.task.projectexport.steps.ExportLinksStep;
import org.sonar.ce.task.projectexport.steps.ExportLiveMeasuresStep;
import org.sonar.ce.task.projectexport.steps.ExportMeasuresStep;
import org.sonar.ce.task.projectexport.steps.ExportMetricsStep;
import org.sonar.ce.task.projectexport.steps.ExportNewCodePeriodsStep;
import org.sonar.ce.task.projectexport.steps.ExportPluginsStep;
import org.sonar.ce.task.projectexport.steps.ExportSettingsStep;
import org.sonar.ce.task.projectexport.steps.LoadProjectStep;
import org.sonar.ce.task.projectexport.steps.PublishDumpStep;
import org.sonar.ce.task.projectexport.steps.WriteMetadataStep;
import org.sonar.ce.task.step.ComputationStep;
public class ProjectExportComputationSteps extends AbstractComputationSteps {
private static final List<Class<? extends ComputationStep>> STEPS_CLASSES = Arrays.asList(
LoadProjectStep.class,
WriteMetadataStep.class,
ExportComponentsStep.class,
ExportSettingsStep.class,
ExportPluginsStep.class,
ExportBranchesStep.class,
ExportAnalysesStep.class,
ExportMeasuresStep.class,
ExportLiveMeasuresStep.class,
ExportMetricsStep.class,
ExportIssuesStep.class,
ExportIssuesChangelogStep.class,
ExportRuleStep.class,
ExportAdHocRulesStep.class,
ExportLinksStep.class,
ExportEventsStep.class,
ExportLineHashesStep.class,
ExportNewCodePeriodsStep.class,
PublishDumpStep.class);
public ProjectExportComputationSteps(TaskContainer container) {
super(container);
}
@Override
public List<Class<? extends ComputationStep>> orderedStepClasses() {
return STEPS_CLASSES;
}
}
| 3,303 | 40.822785 | 92 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/ProjectExportContainerPopulator.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectexport;
import java.util.List;
import org.sonar.ce.task.container.TaskContainer;
import org.sonar.ce.task.projectexport.component.ComponentRepositoryImpl;
import org.sonar.ce.task.projectexport.rule.RuleRepositoryImpl;
import org.sonar.ce.task.projectexport.steps.DumpWriterImpl;
import org.sonar.ce.task.projectexport.steps.MutableMetricRepositoryImpl;
import org.sonar.ce.task.projectexport.steps.MutableProjectHolderImpl;
import org.sonar.ce.task.projectexport.taskprocessor.ProjectDescriptor;
import org.sonar.ce.task.projectexport.util.ProjectExportDumpFSImpl;
import org.sonar.ce.task.setting.SettingsLoader;
import org.sonar.core.platform.ContainerPopulator;
public class ProjectExportContainerPopulator implements ContainerPopulator<TaskContainer> {
private static final List<Class<?>> COMPONENT_CLASSES = List.of(
SettingsLoader.class,
ProjectExportProcessor.class,
MutableMetricRepositoryImpl.class,
MutableProjectHolderImpl.class,
ProjectExportDumpFSImpl.class,
DumpWriterImpl.class,
RuleRepositoryImpl.class,
ComponentRepositoryImpl.class);
private final ProjectDescriptor projectDescriptor;
public ProjectExportContainerPopulator(ProjectDescriptor descriptor) {
this.projectDescriptor = descriptor;
}
@Override
public void populateContainer(TaskContainer container) {
ProjectExportComputationSteps steps = new ProjectExportComputationSteps(container);
container.add(projectDescriptor);
container.add(steps);
container.add(COMPONENT_CLASSES);
container.add(steps.orderedStepClasses());
}
}
| 2,455 | 38.612903 | 91 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/ProjectExportProcessor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectexport;
import org.sonar.ce.task.CeTaskInterrupter;
import org.sonar.ce.task.step.ComputationStepExecutor;
public class ProjectExportProcessor {
private final ProjectExportComputationSteps steps;
private final CeTaskInterrupter taskInterrupter;
public ProjectExportProcessor(ProjectExportComputationSteps steps, CeTaskInterrupter taskInterrupter) {
this.steps = steps;
this.taskInterrupter = taskInterrupter;
}
public void process() {
new ComputationStepExecutor(this.steps, taskInterrupter).execute();
}
}
| 1,412 | 35.230769 | 105 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/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.ce.task.projectexport;
import javax.annotation.ParametersAreNonnullByDefault;
| 971 | 39.5 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/analysis/ExportAnalysesStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectexport.analysis;
import com.sonarsource.governance.projectdump.protobuf.ProjectDump;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.slf4j.LoggerFactory;
import org.sonar.ce.task.projectexport.component.ComponentRepository;
import org.sonar.ce.task.projectexport.steps.DumpElement;
import org.sonar.ce.task.projectexport.steps.DumpWriter;
import org.sonar.ce.task.projectexport.steps.ProjectHolder;
import org.sonar.ce.task.projectexport.steps.StreamWriter;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.db.DatabaseUtils;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import static java.lang.String.format;
import static org.apache.commons.lang.StringUtils.defaultString;
import static org.sonar.db.DatabaseUtils.getString;
import static org.sonar.db.component.SnapshotDto.STATUS_PROCESSED;
public class ExportAnalysesStep implements ComputationStep {
// contrary to naming convention used in other tables, the column snapshots.created_at is
// the functional date (for instance when using property sonar.projectDate=2010-01-01). The
// column "build_date" is the technical date of scanner execution. It must not be exported.
private static final String QUERY = "select" +
" p.uuid, s.version, s.created_at," +
" s.period1_mode, s.period1_param, s.period1_date," +
" s.uuid, s.build_string" +
" from snapshots s" +
" inner join components p on s.root_component_uuid=p.uuid" +
" inner join project_branches pb on pb.uuid=p.uuid" +
" where pb.project_uuid=? and pb.branch_type = 'BRANCH' and pb.exclude_from_purge=? and s.status=? and p.enabled=?" +
" order by s.build_date asc";
private final DbClient dbClient;
private final ProjectHolder projectHolder;
private final ComponentRepository componentRepository;
private final DumpWriter dumpWriter;
public ExportAnalysesStep(DbClient dbClient, ProjectHolder projectHolder, ComponentRepository componentRepository, DumpWriter dumpWriter) {
this.dbClient = dbClient;
this.projectHolder = projectHolder;
this.componentRepository = componentRepository;
this.dumpWriter = dumpWriter;
}
@Override
public void execute(Context context) {
long count = 0L;
try (
StreamWriter<ProjectDump.Analysis> output = dumpWriter.newStreamWriter(DumpElement.ANALYSES);
DbSession dbSession = dbClient.openSession(false);
PreparedStatement stmt = buildSelectStatement(dbSession);
ResultSet rs = stmt.executeQuery()) {
ProjectDump.Analysis.Builder builder = ProjectDump.Analysis.newBuilder();
while (rs.next()) {
// Results are ordered by ascending id so that any parent is located
// before its children.
ProjectDump.Analysis analysis = convertToAnalysis(rs, builder);
output.write(analysis);
count++;
}
LoggerFactory.getLogger(getClass()).debug("{} analyses exported", count);
} catch (Exception e) {
throw new IllegalStateException(format("Analysis Export failed after processing %d analyses successfully", count), e);
}
}
private PreparedStatement buildSelectStatement(DbSession dbSession) throws SQLException {
PreparedStatement stmt = dbClient.getMyBatis().newScrollingSelectStatement(dbSession, QUERY);
try {
stmt.setString(1, projectHolder.projectDto().getUuid());
stmt.setBoolean(2, true);
stmt.setString(3, STATUS_PROCESSED);
stmt.setBoolean(4, true);
return stmt;
} catch (Exception t) {
DatabaseUtils.closeQuietly(stmt);
throw t;
}
}
private ProjectDump.Analysis convertToAnalysis(ResultSet rs, ProjectDump.Analysis.Builder builder) throws SQLException {
builder.clear();
long componentRef = componentRepository.getRef(rs.getString(1));
return builder
.setComponentRef(componentRef)
.setProjectVersion(defaultString(getString(rs, 2)))
.setDate(rs.getLong(3))
.setPeriod1Mode(defaultString(getString(rs, 4)))
.setPeriod1Param(defaultString(getString(rs, 5)))
.setPeriod1Date(rs.getLong(6))
.setUuid(rs.getString(7))
.setBuildString(defaultString(getString(rs, 8)))
.build();
}
@Override
public String getDescription() {
return "Export analyses";
}
}
| 5,186 | 39.523438 | 141 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/analysis/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.ce.task.projectexport.analysis;
import javax.annotation.ParametersAreNonnullByDefault;
| 980 | 39.875 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/branches/ExportBranchesStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectexport.branches;
import com.sonarsource.governance.projectdump.protobuf.ProjectDump;
import java.util.List;
import org.slf4j.LoggerFactory;
import org.sonar.ce.task.projectexport.steps.DumpElement;
import org.sonar.ce.task.projectexport.steps.DumpWriter;
import org.sonar.ce.task.projectexport.steps.ProjectHolder;
import org.sonar.ce.task.projectexport.steps.StreamWriter;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.project.ProjectExportMapper;
import static java.lang.String.format;
import static org.apache.commons.lang.StringUtils.defaultString;
public class ExportBranchesStep implements ComputationStep {
private final DumpWriter dumpWriter;
private final DbClient dbClient;
private final ProjectHolder projectHolder;
public ExportBranchesStep(DumpWriter dumpWriter, DbClient dbClient, ProjectHolder projectHolder) {
this.dumpWriter = dumpWriter;
this.dbClient = dbClient;
this.projectHolder = projectHolder;
}
@Override
public void execute(Context context) {
long count = 0L;
try {
try (DbSession dbSession = dbClient.openSession(false);
StreamWriter<ProjectDump.Branch> output = dumpWriter.newStreamWriter(DumpElement.BRANCHES)) {
ProjectDump.Branch.Builder builder = ProjectDump.Branch.newBuilder();
List<BranchDto> branches = dbSession.getMapper(ProjectExportMapper.class).selectBranchesForExport(projectHolder.projectDto().getUuid());
for (BranchDto branch : branches) {
builder
.clear()
.setUuid(branch.getUuid())
.setProjectUuid(branch.getProjectUuid())
.setKee(branch.getKey())
.setIsMain(branch.isMain())
.setBranchType(branch.getBranchType().name())
.setMergeBranchUuid(defaultString(branch.getMergeBranchUuid()));
output.write(builder.build());
++count;
}
LoggerFactory.getLogger(getClass()).debug("{} branches exported", count);
}
} catch (Exception e) {
throw new IllegalStateException(format("Branch export failed after processing %d branch(es) successfully", count), e);
}
}
@Override
public String getDescription() {
return "Export branches";
}
}
| 3,212 | 38.182927 | 144 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/branches/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.ce.task.projectexport.branches;
import javax.annotation.ParametersAreNonnullByDefault;
| 980 | 39.875 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/component/ComponentRepository.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectexport.component;
import java.util.Set;
/**
* Holds the references of components which are present in the dump.
*/
public interface ComponentRepository {
/**
* @throws IllegalStateException if there is no ref for the specified Uuid in the repository
*/
long getRef(String uuid);
/**
* Uuids of the components of type FILE (ie. Qualifiers = {@link org.sonar.api.resources.Qualifiers#FILE}) known to
* the repository.
*/
Set<String> getFileUuids();
}
| 1,354 | 32.875 | 117 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/component/ComponentRepositoryImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectexport.component;
import com.google.common.collect.ImmutableSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
public class ComponentRepositoryImpl implements MutableComponentRepository {
private final Map<String, Long> refsByUuid = new HashMap<>();
private final Set<String> fileUuids = new HashSet<>();
@Override
public void register(long ref, String uuid, boolean file) {
requireNonNull(uuid, "uuid can not be null");
Long existingRef = refsByUuid.get(uuid);
if (existingRef != null) {
checkArgument(ref == existingRef, "Uuid '%s' already registered under ref '%s' in repository", uuid, existingRef);
boolean existingIsFile = fileUuids.contains(uuid);
checkArgument(file == existingIsFile, "Uuid '%s' already registered but %sas a File", uuid, existingIsFile ? "" : "not ");
} else {
refsByUuid.put(uuid, ref);
if (file) {
fileUuids.add(uuid);
}
}
}
@Override
public long getRef(String uuid) {
Long ref = refsByUuid.get(requireNonNull(uuid, "uuid can not be null"));
checkState(ref != null, "No reference registered in the repository for uuid '%s'", uuid);
return ref;
}
@Override
public Set<String> getFileUuids() {
return ImmutableSet.copyOf(fileUuids);
}
}
| 2,375 | 35.553846 | 128 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/component/ExportComponentsStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectexport.component;
import com.sonarsource.governance.projectdump.protobuf.ProjectDump;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.sonar.api.resources.Qualifiers;
import org.slf4j.LoggerFactory;
import org.sonar.ce.task.projectexport.steps.DumpElement;
import org.sonar.ce.task.projectexport.steps.DumpWriter;
import org.sonar.ce.task.projectexport.steps.ProjectHolder;
import org.sonar.ce.task.projectexport.steps.StreamWriter;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.db.DatabaseUtils;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import static java.lang.String.format;
import static org.apache.commons.lang.StringUtils.defaultString;
import static org.sonar.db.DatabaseUtils.getString;
public class ExportComponentsStep implements ComputationStep {
// Results are ordered by ascending id so that any parent is located
// before its children.
private static final String QUERY = "select" +
" p.uuid, p.qualifier, p.uuid_path, p.kee, p.name," +
" p.description, p.scope, p.language, p.long_name, p.path," +
" p.deprecated_kee, p.branch_uuid" +
" from components p" +
" join components pp on pp.uuid = p.branch_uuid" +
" join project_branches pb on pb.uuid = pp.uuid" +
" where pb.project_uuid=? and pb.branch_type = 'BRANCH' and pb.exclude_from_purge=? and p.enabled=?";
private final DbClient dbClient;
private final ProjectHolder projectHolder;
private final MutableComponentRepository componentRepository;
private final DumpWriter dumpWriter;
public ExportComponentsStep(DbClient dbClient, ProjectHolder projectHolder, MutableComponentRepository componentRepository, DumpWriter dumpWriter) {
this.dbClient = dbClient;
this.projectHolder = projectHolder;
this.componentRepository = componentRepository;
this.dumpWriter = dumpWriter;
}
@Override
public void execute(Context context) {
long ref = 1;
long count = 0L;
try (
StreamWriter<ProjectDump.Component> output = dumpWriter.newStreamWriter(DumpElement.COMPONENTS);
DbSession dbSession = dbClient.openSession(false);
PreparedStatement stmt = createSelectStatement(dbSession);
ResultSet rs = stmt.executeQuery()) {
ProjectDump.Component.Builder componentBuilder = ProjectDump.Component.newBuilder();
while (rs.next()) {
String uuid = getString(rs, 1);
String qualifier = getString(rs, 2);
String uuidPath = getString(rs, 3);
componentBuilder.clear();
componentRepository.register(ref, uuid, Qualifiers.FILE.equals(qualifier));
ProjectDump.Component component = componentBuilder
.setRef(ref)
.setUuid(uuid)
.setUuidPath(uuidPath)
.setKey(getString(rs, 4))
.setName(defaultString(getString(rs, 5)))
.setDescription(defaultString(getString(rs, 6)))
.setScope(getString(rs, 7))
.setQualifier(qualifier)
.setLanguage(defaultString(getString(rs, 8)))
.setLongName(defaultString(getString(rs, 9)))
.setPath(defaultString(getString(rs, 10)))
.setDeprecatedKey(defaultString(getString(rs, 11)))
.setProjectUuid(getString(rs, 12))
.build();
output.write(component);
ref++;
count++;
}
LoggerFactory.getLogger(getClass()).debug("{} components exported", count);
} catch (Exception e) {
throw new IllegalStateException(format("Component Export failed after processing %d components successfully", count), e);
}
}
private PreparedStatement createSelectStatement(DbSession dbSession) throws SQLException {
PreparedStatement stmt = dbClient.getMyBatis().newScrollingSelectStatement(dbSession, QUERY);
try {
stmt.setString(1, projectHolder.projectDto().getUuid());
stmt.setBoolean(2, true);
stmt.setBoolean(3, true);
return stmt;
} catch (Exception t) {
DatabaseUtils.closeQuietly(stmt);
throw t;
}
}
@Override
public String getDescription() {
return "Export components";
}
}
| 5,014 | 39.443548 | 150 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.