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/formula/counter/RatingValue.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.formula.counter;
import javax.annotation.Nullable;
import org.sonar.server.measure.Rating;
/**
* Convenience class wrapping a rating to compute the value and know it is has ever been set.
*/
public class RatingValue {
private boolean set = false;
private Rating value = Rating.A;
/**
* @return the current {@link RatingValue} so that chained calls on a specific {@link RatingValue} instance can be done
*/
public RatingValue increment(Rating rating) {
if (value.compareTo(rating) > 0) {
value = rating;
}
this.set = true;
return this;
}
/**
* @return the current {@link RatingValue} so that chained calls on a specific {@link RatingValue} instance can be done
*/
public RatingValue increment(@Nullable RatingValue value) {
if (value != null && value.isSet()) {
increment(value.value);
}
return this;
}
public boolean isSet() {
return set;
}
public Rating getValue() {
return value;
}
}
| 1,865 | 29.096774 | 122 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/formula/counter/SumCounter.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.formula.counter;
import java.util.Optional;
import org.sonar.ce.task.projectanalysis.formula.Counter;
public interface SumCounter<T extends Number, COUNTER extends SumCounter<T, COUNTER>> extends Counter<COUNTER> {
Optional<T> getValue();
}
| 1,131 | 38.034483 | 112 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/formula/counter/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.formula.counter;
import javax.annotation.ParametersAreNonnullByDefault;
| 989 | 40.25 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/formula/coverage/CoverageFormula.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.formula.coverage;
import java.util.Optional;
import org.sonar.ce.task.projectanalysis.formula.Counter;
import org.sonar.ce.task.projectanalysis.formula.CreateMeasureContext;
import org.sonar.ce.task.projectanalysis.formula.Formula;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import static org.sonar.ce.task.projectanalysis.formula.coverage.CoverageUtils.calculateCoverage;
import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilder;
/**
* An abstract {@link Formula} which implements the aggregation of a {@link Counter} of
* type {@link ElementsAndCoveredElementsCounter} with another counter.
*/
public abstract class CoverageFormula<T extends ElementsAndCoveredElementsCounter> implements Formula<T> {
@Override
public Optional<Measure> createMeasure(T counter, CreateMeasureContext context) {
long elements = counter.elements;
long coveredElements = counter.coveredElements;
if (elements > 0L) {
return Optional.of(newMeasureBuilder().create(calculateCoverage(coveredElements, elements), context.getMetric().getDecimalScale()));
}
return Optional.empty();
}
}
| 2,028 | 41.270833 | 138 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/formula/coverage/CoverageUtils.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.formula.coverage;
import org.sonar.ce.task.projectanalysis.formula.CounterInitializationContext;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilder;
public final class CoverageUtils {
private static final Measure DEFAULT_MEASURE_LONG = newMeasureBuilder().create(0L);
private static final Measure DEFAULT_MEASURE_INT = newMeasureBuilder().create(0);
private CoverageUtils() {
// prevents instantiation
}
static double calculateCoverage(long coveredLines, long lines) {
return (100.0 * coveredLines) / lines;
}
static long getLongMeasureValue(CounterInitializationContext counterContext, String metricKey) {
Measure measure = counterContext.getMeasure(metricKey).orElse(DEFAULT_MEASURE_LONG);
if (measure.getValueType() == Measure.ValueType.NO_VALUE) {
return 0L;
}
if (measure.getValueType() == Measure.ValueType.INT) {
return measure.getIntValue();
}
return measure.getLongValue();
}
static int getIntMeasureValue(CounterInitializationContext counterContext, String metricKey) {
Measure measure = counterContext.getMeasure(metricKey).orElse(DEFAULT_MEASURE_INT);
if (measure.getValueType() == Measure.ValueType.NO_VALUE) {
return 0;
}
return measure.getIntValue();
}
}
| 2,237 | 37.586207 | 98 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/formula/coverage/ElementsAndCoveredElementsCounter.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.formula.coverage;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.formula.Counter;
import org.sonar.ce.task.projectanalysis.formula.CounterInitializationContext;
/**
* A counter used to create a measure which are based on a count of elements and coveredElements.
*/
public abstract class ElementsAndCoveredElementsCounter implements Counter<ElementsAndCoveredElementsCounter> {
protected long elements = 0L;
protected long coveredElements = 0L;
@Override
public void aggregate(ElementsAndCoveredElementsCounter counter) {
this.elements += counter.elements;
this.coveredElements += counter.coveredElements;
}
@Override
public void initialize(CounterInitializationContext context) {
Component component = context.getLeaf();
if (component.getType() == Component.Type.FILE && component.getFileAttributes().isUnitTest()) {
return;
}
initializeForSupportedLeaf(context);
}
protected abstract void initializeForSupportedLeaf(CounterInitializationContext counterContext);
}
| 1,961 | 38.24 | 111 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/formula/coverage/LinesAndConditionsWithUncoveredCounter.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.formula.coverage;
import org.sonar.ce.task.projectanalysis.formula.CounterInitializationContext;
import static org.sonar.ce.task.projectanalysis.formula.coverage.CoverageUtils.getLongMeasureValue;
public final class LinesAndConditionsWithUncoveredCounter extends ElementsAndCoveredElementsCounter {
private final LinesAndConditionsWithUncoveredMetricKeys metricKeys;
public LinesAndConditionsWithUncoveredCounter(LinesAndConditionsWithUncoveredMetricKeys metricKeys) {
this.metricKeys = metricKeys;
}
@Override
protected void initializeForSupportedLeaf(CounterInitializationContext counterContext) {
this.elements = getLongMeasureValue(counterContext, metricKeys.lines())
+ getLongMeasureValue(counterContext, metricKeys.conditions());
this.coveredElements = this.elements
- getLongMeasureValue(counterContext, metricKeys.uncoveredLines())
- getLongMeasureValue(counterContext, metricKeys.uncoveredConditions());
}
}
| 1,849 | 43.047619 | 103 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/formula/coverage/LinesAndConditionsWithUncoveredFormula.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.formula.coverage;
import static java.util.Objects.requireNonNull;
/**
* A Formula which implements the aggregation of lines and conditions measures (and their associated "uncovered" measures)
* into a fifth measure.
*/
public class LinesAndConditionsWithUncoveredFormula extends CoverageFormula<LinesAndConditionsWithUncoveredCounter> {
private final LinesAndConditionsWithUncoveredMetricKeys inputKeys;
private final String outputKey;
public LinesAndConditionsWithUncoveredFormula(LinesAndConditionsWithUncoveredMetricKeys inputKeys, String outputKey) {
this.inputKeys = requireNonNull(inputKeys);
this.outputKey = requireNonNull(outputKey);
}
@Override
public LinesAndConditionsWithUncoveredCounter createNewCounter() {
return new LinesAndConditionsWithUncoveredCounter(inputKeys);
}
@Override
public String[] getOutputMetricKeys() {
return new String[] {outputKey};
}
}
| 1,802 | 37.361702 | 122 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/formula/coverage/LinesAndConditionsWithUncoveredMetricKeys.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.formula.coverage;
import static java.util.Objects.requireNonNull;
public record LinesAndConditionsWithUncoveredMetricKeys(String lines, String conditions, String uncoveredLines, String uncoveredConditions) {
public LinesAndConditionsWithUncoveredMetricKeys(String lines, String conditions, String uncoveredLines, String uncoveredConditions) {
this.lines = requireNonNull(lines);
this.conditions = requireNonNull(conditions);
this.uncoveredLines = requireNonNull(uncoveredLines);
this.uncoveredConditions = requireNonNull(uncoveredConditions);
}
}
| 1,454 | 44.46875 | 141 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/formula/coverage/SingleWithUncoveredCounter.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.formula.coverage;
import org.sonar.ce.task.projectanalysis.formula.CounterInitializationContext;
import static org.sonar.ce.task.projectanalysis.formula.coverage.CoverageUtils.getLongMeasureValue;
public final class SingleWithUncoveredCounter extends ElementsAndCoveredElementsCounter {
private final SingleWithUncoveredMetricKeys metricKeys;
public SingleWithUncoveredCounter(SingleWithUncoveredMetricKeys metricKeys) {
this.metricKeys = metricKeys;
}
@Override
protected void initializeForSupportedLeaf(CounterInitializationContext counterContext) {
this.elements = getLongMeasureValue(counterContext, metricKeys.covered());
this.coveredElements = this.elements - getLongMeasureValue(counterContext, metricKeys.uncovered());
}
}
| 1,645 | 41.205128 | 103 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/formula/coverage/SingleWithUncoveredFormula.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.formula.coverage;
import static java.util.Objects.requireNonNull;
/**
* A Formula which implements the aggregation of a specific measure and its associated "uncovered" measure into a third
* measure.
*/
public class SingleWithUncoveredFormula extends CoverageFormula<SingleWithUncoveredCounter> {
private final SingleWithUncoveredMetricKeys inputKeys;
private final String outputKeys;
protected SingleWithUncoveredFormula(SingleWithUncoveredMetricKeys inputKeys, String outputKeys) {
this.inputKeys = requireNonNull(inputKeys);
this.outputKeys = requireNonNull(outputKeys);
}
@Override
public SingleWithUncoveredCounter createNewCounter() {
return new SingleWithUncoveredCounter(inputKeys);
}
@Override
public String[] getOutputMetricKeys() {
return new String[] {outputKeys};
}
}
| 1,710 | 35.404255 | 119 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/formula/coverage/SingleWithUncoveredMetricKeys.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.formula.coverage;
import static java.util.Objects.requireNonNull;
public record SingleWithUncoveredMetricKeys(String covered, String uncovered) {
public SingleWithUncoveredMetricKeys(String covered, String uncovered) {
this.covered = requireNonNull(covered);
this.uncovered = requireNonNull(uncovered);
}
}
| 1,206 | 39.233333 | 79 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/formula/coverage/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.formula.coverage;
import javax.annotation.ParametersAreNonnullByDefault;
| 990 | 40.291667 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/AdHocRuleCreator.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import com.google.common.base.Preconditions;
import java.util.Objects;
import java.util.Optional;
import org.sonar.api.rules.RuleType;
import org.sonar.api.utils.System2;
import org.sonar.core.util.UuidFactory;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.rule.RuleDao;
import org.sonar.db.rule.RuleDto;
import org.sonar.server.rule.index.RuleIndexer;
import static java.util.Objects.requireNonNull;
import static org.apache.commons.lang.StringUtils.substring;
import static org.sonar.api.rule.RuleStatus.READY;
import static org.sonar.db.rule.RuleDto.Scope.ALL;
public class AdHocRuleCreator {
private static final int MAX_LENGTH_AD_HOC_NAME = 200;
private static final int MAX_LENGTH_AD_HOC_DESC = 16_777_215;
private final DbClient dbClient;
private final System2 system2;
private final RuleIndexer ruleIndexer;
private final UuidFactory uuidFactory;
public AdHocRuleCreator(DbClient dbClient, System2 system2, RuleIndexer ruleIndexer, UuidFactory uuidFactory) {
this.dbClient = dbClient;
this.system2 = system2;
this.ruleIndexer = ruleIndexer;
this.uuidFactory = uuidFactory;
}
/**
* Persists a new add hoc rule in the DB and indexes it.
* @return the rule that was inserted in the DB, which <b>includes the generated ID</b>.
*/
public RuleDto persistAndIndex(DbSession dbSession, NewAdHocRule adHoc) {
RuleDao dao = dbClient.ruleDao();
long now = system2.now();
RuleDto ruleDtoToUpdate = findOrCreateRuleDto(dbSession, adHoc, dao, now);
if (adHoc.hasDetails()) {
boolean changed = false;
if (!Objects.equals(ruleDtoToUpdate.getAdHocName(), adHoc.getName())) {
ruleDtoToUpdate.setAdHocName(substring(adHoc.getName(), 0, MAX_LENGTH_AD_HOC_NAME));
changed = true;
}
if (!Objects.equals(ruleDtoToUpdate.getAdHocDescription(), adHoc.getDescription())) {
ruleDtoToUpdate.setAdHocDescription(substring(adHoc.getDescription(), 0, MAX_LENGTH_AD_HOC_DESC));
changed = true;
}
if (!Objects.equals(ruleDtoToUpdate.getAdHocSeverity(), adHoc.getSeverity())) {
ruleDtoToUpdate.setAdHocSeverity(adHoc.getSeverity());
changed = true;
}
RuleType ruleType = requireNonNull(adHoc.getRuleType(), "Rule type should not be null");
if (!Objects.equals(ruleDtoToUpdate.getAdHocType(), ruleType.getDbConstant())) {
ruleDtoToUpdate.setAdHocType(ruleType);
changed = true;
}
if (changed) {
ruleDtoToUpdate.setUpdatedAt(now);
dao.update(dbSession, ruleDtoToUpdate);
}
}
RuleDto ruleDto = dao.selectOrFailByKey(dbSession, adHoc.getKey());
ruleIndexer.commitAndIndex(dbSession, ruleDto.getUuid());
return ruleDto;
}
private RuleDto findOrCreateRuleDto(DbSession dbSession, NewAdHocRule adHoc, RuleDao dao, long now) {
Optional<RuleDto> existingRuleDtoOpt = dbClient.ruleDao().selectByKey(dbSession, adHoc.getKey());
if (existingRuleDtoOpt.isEmpty()) {
RuleDto ruleDto = new RuleDto()
.setUuid(uuidFactory.create())
.setRuleKey(adHoc.getKey())
.setIsExternal(true)
.setIsAdHoc(true)
.setName(adHoc.getEngineId() + ":" + adHoc.getRuleId())
.setScope(ALL)
.setStatus(READY)
.setCreatedAt(now)
.setUpdatedAt(now);
dao.insert(dbSession, ruleDto);
return ruleDto;
} else {
RuleDto ruleDto = existingRuleDtoOpt.get();
Preconditions.checkState(ruleDto.isExternal() && ruleDto.isAdHoc());
return ruleDto;
}
}
}
| 4,476 | 36.621849 | 113 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/BaseInputFactory.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nullable;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.filemove.MovedFilesRepository;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.tracking.Input;
import org.sonar.core.issue.tracking.LazyInput;
import org.sonar.core.issue.tracking.LineHashSequence;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
public abstract class BaseInputFactory {
private static final LineHashSequence EMPTY_LINE_HASH_SEQUENCE = new LineHashSequence(Collections.emptyList());
abstract Input<DefaultIssue> create(Component component);
abstract static class BaseLazyInput extends LazyInput<DefaultIssue> {
private final DbClient dbClient;
final Component component;
final String effectiveUuid;
BaseLazyInput(DbClient dbClient, Component component, @Nullable MovedFilesRepository.OriginalFile originalFile) {
this.dbClient = dbClient;
this.component = component;
this.effectiveUuid = originalFile == null ? component.getUuid() : originalFile.uuid();
}
@Override
protected LineHashSequence loadLineHashSequence() {
if (component.getType() != Component.Type.FILE) {
return EMPTY_LINE_HASH_SEQUENCE;
}
try (DbSession session = dbClient.openSession(false)) {
List<String> hashes = dbClient.fileSourceDao().selectLineHashes(session, effectiveUuid);
if (hashes == null || hashes.isEmpty()) {
return EMPTY_LINE_HASH_SEQUENCE;
}
return new LineHashSequence(hashes);
}
}
}
}
| 2,543 | 36.970149 | 117 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/BaseIssuesLoader.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.util.Set;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
/**
* Loads all the project open issues from database, including manual issues.
*/
public class BaseIssuesLoader {
private final TreeRootHolder treeRootHolder;
private final DbClient dbClient;
public BaseIssuesLoader(TreeRootHolder treeRootHolder, DbClient dbClient) {
this.treeRootHolder = treeRootHolder;
this.dbClient = dbClient;
}
/**
* Uuids of all the components that have open issues on this project.
*/
public Set<String> loadUuidsOfComponentsWithOpenIssues() {
try (DbSession dbSession = dbClient.openSession(false)) {
return dbClient.issueDao().selectComponentUuidsOfOpenIssuesForProjectUuid(dbSession, treeRootHolder.getRoot().getUuid());
}
}
}
| 1,747 | 34.673469 | 127 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/CloseIssuesOnRemovedComponentsVisitor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.util.List;
import java.util.Set;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit;
import org.sonar.ce.task.projectanalysis.component.TypeAwareVisitorAdapter;
import org.sonar.ce.task.projectanalysis.util.cache.DiskCache.CacheAppender;
import org.sonar.core.issue.DefaultIssue;
import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.POST_ORDER;
/**
* Close issues on removed components
*/
public class CloseIssuesOnRemovedComponentsVisitor extends TypeAwareVisitorAdapter {
private final ComponentIssuesLoader issuesLoader;
private final ComponentsWithUnprocessedIssues componentsWithUnprocessedIssues;
private final ProtoIssueCache protoIssueCache;
private final IssueLifecycle issueLifecycle;
public CloseIssuesOnRemovedComponentsVisitor(ComponentIssuesLoader issuesLoader, ComponentsWithUnprocessedIssues componentsWithUnprocessedIssues, ProtoIssueCache protoIssueCache,
IssueLifecycle issueLifecycle) {
super(CrawlerDepthLimit.PROJECT, POST_ORDER);
this.issuesLoader = issuesLoader;
this.componentsWithUnprocessedIssues = componentsWithUnprocessedIssues;
this.protoIssueCache = protoIssueCache;
this.issueLifecycle = issueLifecycle;
}
@Override
public void visitProject(Component project) {
closeIssuesForDeletedComponentUuids(componentsWithUnprocessedIssues.getUuids());
}
private void closeIssuesForDeletedComponentUuids(Set<String> deletedComponentUuids) {
try (CacheAppender<DefaultIssue> cacheAppender = protoIssueCache.newAppender()) {
for (String deletedComponentUuid : deletedComponentUuids) {
List<DefaultIssue> issues = issuesLoader.loadOpenIssues(deletedComponentUuid);
for (DefaultIssue issue : issues) {
issue.setBeingClosed(true);
// TODO should be renamed
issue.setOnDisabledRule(false);
issueLifecycle.doAutomaticTransition(issue);
cacheAppender.append(issue);
}
}
}
}
}
| 2,956 | 40.647887 | 180 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/ClosedIssuesInputFactory.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.util.List;
import javax.annotation.Nullable;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.filemove.MovedFilesRepository;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.tracking.Input;
import org.sonar.db.DbClient;
public class ClosedIssuesInputFactory extends BaseInputFactory {
private final ComponentIssuesLoader issuesLoader;
private final DbClient dbClient;
private final MovedFilesRepository movedFilesRepository;
public ClosedIssuesInputFactory(ComponentIssuesLoader issuesLoader, DbClient dbClient, MovedFilesRepository movedFilesRepository) {
this.issuesLoader = issuesLoader;
this.dbClient = dbClient;
this.movedFilesRepository = movedFilesRepository;
}
public Input<DefaultIssue> create(Component component) {
return new ClosedIssuesLazyInput(dbClient, component, movedFilesRepository.getOriginalFile(component).orElse(null));
}
private class ClosedIssuesLazyInput extends BaseLazyInput {
ClosedIssuesLazyInput(DbClient dbClient, Component component, @Nullable MovedFilesRepository.OriginalFile originalFile) {
super(dbClient, component, originalFile);
}
@Override
protected List<DefaultIssue> loadIssues() {
return issuesLoader.loadClosedIssues(effectiveUuid);
}
}
}
| 2,236 | 38.245614 | 133 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/ComponentIssuesLoader.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.ibatis.session.ResultContext;
import org.apache.ibatis.session.ResultHandler;
import org.slf4j.LoggerFactory;
import org.sonar.api.config.Configuration;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectanalysis.qualityprofile.ActiveRulesHolder;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.FieldDiffs;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.issue.IssueChangeDto;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.issue.IssueMapper;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Collections.emptyList;
import static java.util.Collections.unmodifiableList;
import static java.util.stream.Collectors.groupingBy;
import static org.sonar.api.issue.Issue.STATUS_CLOSED;
import static org.sonar.server.issue.IssueFieldsSetter.FROM_BRANCH;
import static org.sonar.server.issue.IssueFieldsSetter.STATUS;
public class ComponentIssuesLoader {
private static final int DEFAULT_CLOSED_ISSUES_MAX_AGE = 30;
static final int NUMBER_STATUS_AND_BRANCH_CHANGES_TO_KEEP = 15;
private static final String PROPERTY_CLOSED_ISSUE_MAX_AGE = "sonar.issuetracking.closedissues.maxage";
private final DbClient dbClient;
private final RuleRepository ruleRepository;
private final ActiveRulesHolder activeRulesHolder;
private final System2 system2;
private final int closedIssueMaxAge;
private final IssueChangesToDeleteRepository issueChangesToDeleteRepository;
public ComponentIssuesLoader(DbClient dbClient, RuleRepository ruleRepository, ActiveRulesHolder activeRulesHolder,
Configuration configuration, System2 system2, IssueChangesToDeleteRepository issueChangesToDeleteRepository) {
this.dbClient = dbClient;
this.activeRulesHolder = activeRulesHolder;
this.ruleRepository = ruleRepository;
this.system2 = system2;
this.closedIssueMaxAge = configuration.get(PROPERTY_CLOSED_ISSUE_MAX_AGE)
.map(ComponentIssuesLoader::safelyParseClosedIssueMaxAge)
.filter(i -> i >= 0)
.orElse(DEFAULT_CLOSED_ISSUES_MAX_AGE);
this.issueChangesToDeleteRepository = issueChangesToDeleteRepository;
}
public List<DefaultIssue> loadOpenIssues(String componentUuid) {
try (DbSession dbSession = dbClient.openSession(false)) {
return loadOpenIssues(componentUuid, dbSession);
}
}
public List<DefaultIssue> loadOpenIssuesWithChanges(String componentUuid) {
try (DbSession dbSession = dbClient.openSession(false)) {
List<DefaultIssue> result = loadOpenIssues(componentUuid, dbSession);
return loadChanges(dbSession, result);
}
}
/**
* Loads all comments and changes EXCEPT old changes involving a status change or a move between branches.
*/
public List<DefaultIssue> loadChanges(DbSession dbSession, Collection<DefaultIssue> issues) {
Map<String, List<IssueChangeDto>> changeDtoByIssueKey = dbClient.issueChangeDao()
.selectByIssueKeys(dbSession, issues.stream().map(DefaultIssue::key).toList())
.stream()
.collect(groupingBy(IssueChangeDto::getIssueKey));
issues.forEach(i -> setFilteredChanges(changeDtoByIssueKey, i));
return new ArrayList<>(issues);
}
/**
* Loads the most recent diff changes of the specified issues which contain the latest status and resolution of the issue.
*/
public void loadLatestDiffChangesForReopeningOfClosedIssues(Collection<DefaultIssue> issues) {
if (issues.isEmpty()) {
return;
}
try (DbSession dbSession = dbClient.openSession(false)) {
loadLatestDiffChangesForReopeningOfClosedIssues(dbSession, issues);
}
}
/**
* Load closed issues for the specified Component, which have at least one line diff in changelog AND are
* not manual vulnerabilities.
* <p>
* Closed issues do not have a line number in DB (it is unset when the issue is closed), this method
* returns {@link DefaultIssue} objects which line number is populated from the most recent diff logging
* the removal of the line. Closed issues which do not have such diff are not loaded.
* <p>
* To not depend on purge configuration of closed issues, only issues which close date is less than 30 days ago at
* 00H00 are returned.
*/
public List<DefaultIssue> loadClosedIssues(String componentUuid) {
if (closedIssueMaxAge == 0) {
return emptyList();
}
Date date = new Date(system2.now());
long closeDateAfter = date.toInstant()
.minus(closedIssueMaxAge, ChronoUnit.DAYS)
.truncatedTo(ChronoUnit.DAYS)
.toEpochMilli();
try (DbSession dbSession = dbClient.openSession(false)) {
return loadClosedIssues(dbSession, componentUuid, closeDateAfter);
}
}
private static Integer safelyParseClosedIssueMaxAge(String str) {
try {
return Integer.parseInt(str);
} catch (NumberFormatException e) {
LoggerFactory.getLogger(ComponentIssuesLoader.class)
.warn("Value of property {} should be an integer >= 0: {}", PROPERTY_CLOSED_ISSUE_MAX_AGE, str);
return null;
}
}
/**
* To be efficient both in term of memory and speed:
* <ul>
* <li>only diff changes are loaded from DB, sorted by issue and then change creation date</li>
* <li>data from DB is streamed</li>
* <li>only the latest change(s) with status and resolution are added to the {@link DefaultIssue} objects</li>
* </ul>
*
* While loading the changes for the issues, this class will also collect old status changes that should be deleted.
*/
private void loadLatestDiffChangesForReopeningOfClosedIssues(DbSession dbSession, Collection<DefaultIssue> issues) {
Map<String, DefaultIssue> issuesByKey = issues.stream().collect(Collectors.toMap(DefaultIssue::key, Function.identity()));
CollectIssueChangesToDeleteResultHandler collectChangesToDelete = new CollectIssueChangesToDeleteResultHandler(issueChangesToDeleteRepository);
CollectLastStatusAndResolution collectLastStatusAndResolution = new CollectLastStatusAndResolution(issuesByKey);
dbClient.issueChangeDao().scrollDiffChangesOfIssues(dbSession, issuesByKey.keySet(), resultContext -> {
IssueChangeDto issueChangeDto = resultContext.getResultObject();
FieldDiffs fieldDiffs = issueChangeDto.toFieldDiffs();
collectChangesToDelete.handle(issueChangeDto, fieldDiffs);
collectLastStatusAndResolution.handle(issueChangeDto, fieldDiffs);
});
}
private List<DefaultIssue> loadOpenIssues(String componentUuid, DbSession dbSession) {
List<DefaultIssue> result = new ArrayList<>();
dbSession.getMapper(IssueMapper.class).scrollNonClosedByComponentUuid(componentUuid, resultContext -> {
DefaultIssue issue = (resultContext.getResultObject()).toDefaultIssue();
Rule rule = ruleRepository.getByKey(issue.ruleKey());
// TODO this field should be set outside this class
if ((!rule.isExternal() && !isActive(issue.ruleKey())) || rule.getStatus() == RuleStatus.REMOVED) {
issue.setOnDisabledRule(true);
// TODO to be improved, why setOnDisabledRule(true) is not enough ?
issue.setBeingClosed(true);
}
issue.setSelectedAt(System.currentTimeMillis());
result.add(issue);
});
return unmodifiableList(result);
}
private void setFilteredChanges(Map<String, List<IssueChangeDto>> changeDtoByIssueKey, DefaultIssue i) {
List<IssueChangeDto> sortedIssueChanges = changeDtoByIssueKey.computeIfAbsent(i.key(), k -> emptyList()).stream()
.sorted(Comparator.comparing(IssueChangeDto::getIssueChangeCreationDate).reversed())
.toList();
int statusCount = 0;
int branchCount = 0;
for (IssueChangeDto c : sortedIssueChanges) {
switch (c.getChangeType()) {
case IssueChangeDto.TYPE_FIELD_CHANGE:
FieldDiffs fieldDiffs = c.toFieldDiffs();
// To limit the amount of changes that copied issues carry over, we only keep the 15 most recent changes that involve a status change or a move between branches.
if (fieldDiffs.get(STATUS) != null) {
statusCount++;
if (statusCount > NUMBER_STATUS_AND_BRANCH_CHANGES_TO_KEEP) {
issueChangesToDeleteRepository.add(c.getUuid());
break;
}
}
if (fieldDiffs.get(FROM_BRANCH) != null) {
branchCount++;
if (branchCount > NUMBER_STATUS_AND_BRANCH_CHANGES_TO_KEEP) {
issueChangesToDeleteRepository.add(c.getUuid());
break;
}
}
i.addChange(c.toFieldDiffs());
break;
case IssueChangeDto.TYPE_COMMENT:
i.addComment(c.toComment());
break;
default:
throw new IllegalStateException("Unknown change type: " + c.getChangeType());
}
}
}
private boolean isActive(RuleKey ruleKey) {
return activeRulesHolder.get(ruleKey).isPresent();
}
private static List<DefaultIssue> loadClosedIssues(DbSession dbSession, String componentUuid, long closeDateAfter) {
ClosedIssuesResultHandler handler = new ClosedIssuesResultHandler();
dbSession.getMapper(IssueMapper.class).scrollClosedByComponentUuid(componentUuid, closeDateAfter, handler);
return unmodifiableList(handler.issues);
}
private static class ClosedIssuesResultHandler implements ResultHandler<IssueDto> {
private final List<DefaultIssue> issues = new ArrayList<>();
private String previousIssueKey = null;
@Override
public void handleResult(ResultContext<? extends IssueDto> resultContext) {
IssueDto resultObject = resultContext.getResultObject();
// issue are ordered by most recent change first, only the first row for a given issue is of interest
if (previousIssueKey != null && previousIssueKey.equals(resultObject.getKey())) {
return;
}
FieldDiffs fieldDiffs = FieldDiffs.parse(resultObject.getClosedChangeData()
.orElseThrow(() -> new IllegalStateException("Close change data should be populated")));
checkState(Optional.ofNullable(fieldDiffs.get("status"))
.map(FieldDiffs.Diff::newValue)
.filter(STATUS_CLOSED::equals)
.isPresent(), "Close change data should have a status diff with new value %s", STATUS_CLOSED);
Integer line = Optional.ofNullable(fieldDiffs.get("line"))
.map(diff -> (String) diff.oldValue())
.filter(str -> !str.isEmpty())
.map(Integer::parseInt)
.orElse(null);
previousIssueKey = resultObject.getKey();
DefaultIssue issue = resultObject.toDefaultIssue();
issue.setLine(line);
issue.setSelectedAt(System.currentTimeMillis());
issues.add(issue);
}
}
private static class CollectLastStatusAndResolution {
private final Map<String, DefaultIssue> issuesByKey;
private DefaultIssue currentIssue = null;
private boolean previousStatusFound = false;
private boolean previousResolutionFound = false;
private CollectLastStatusAndResolution(Map<String, DefaultIssue> issuesByKey) {
this.issuesByKey = issuesByKey;
}
/**
* Assumes that changes are sorted by issue key and date desc
*/
public void handle(IssueChangeDto issueChangeDto, FieldDiffs fieldDiffs) {
if (currentIssue == null || !currentIssue.key().equals(issueChangeDto.getIssueKey())) {
currentIssue = issuesByKey.get(issueChangeDto.getIssueKey());
previousStatusFound = false;
previousResolutionFound = false;
}
if (currentIssue != null) {
boolean hasPreviousStatus = fieldDiffs.get("status") != null;
boolean hasPreviousResolution = fieldDiffs.get("resolution") != null;
if ((!previousStatusFound && hasPreviousStatus) || (!previousResolutionFound && hasPreviousResolution)) {
currentIssue.addChange(fieldDiffs);
}
previousStatusFound |= hasPreviousStatus;
previousResolutionFound |= hasPreviousResolution;
}
}
}
/**
* Collects issue changes related to status changes that should be cleaned up.
* If we have more than 15 status changes recorded for an issue, only the 15 most recent ones should be kept.
*/
private static class CollectIssueChangesToDeleteResultHandler {
private final IssueChangesToDeleteRepository issueChangesToDeleteRepository;
private String currentIssueKey;
private int statusChangeCount;
public CollectIssueChangesToDeleteResultHandler(IssueChangesToDeleteRepository issueChangesToDeleteRepository) {
this.issueChangesToDeleteRepository = issueChangesToDeleteRepository;
}
/**
* Assumes that changes are sorted by issue key and date desc
*/
public void handle(IssueChangeDto dto, FieldDiffs fieldDiffs) {
if (currentIssueKey == null || !currentIssueKey.equals(dto.getIssueKey())) {
currentIssueKey = dto.getIssueKey();
statusChangeCount = 0;
}
if (fieldDiffs.get(STATUS) != null) {
statusChangeCount++;
if (statusChangeCount > NUMBER_STATUS_AND_BRANCH_CHANGES_TO_KEEP) {
issueChangesToDeleteRepository.add(dto.getUuid());
}
}
}
}
}
| 14,463 | 41.169096 | 171 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/ComponentIssuesRepository.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.util.List;
import org.sonar.api.ce.measure.MeasureComputer;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.core.issue.DefaultIssue;
/**
* This repository contains issues for only one component at a time. It's populated by {@link IntegrateIssuesVisitor} and
* it's mainly used by {@link org.sonar.api.ce.measure.MeasureComputer.MeasureComputerContext} in order for a {@link MeasureComputer}
* to access to the issues of a component.
*
* This repository must NEVER contains more issues than in issues from one component order to not consume to much memory.
*/
public interface ComponentIssuesRepository {
/**
* Return issues from the component
*
* @throws IllegalStateException if no issues have been set
* @throws IllegalArgumentException if the component is not the component that contains current issues.
*/
List<DefaultIssue> getIssues(Component component);
}
| 1,827 | 39.622222 | 133 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/ComponentIssuesRepositoryImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.util.Collections;
import java.util.List;
import javax.annotation.CheckForNull;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.core.issue.DefaultIssue;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
public class ComponentIssuesRepositoryImpl implements MutableComponentIssuesRepository {
@CheckForNull
private List<DefaultIssue> issues;
@CheckForNull
private Component component;
@Override
public void setIssues(Component component, List<DefaultIssue> issues) {
this.issues = requireNonNull(issues, "issues cannot be null");
this.component = requireNonNull(component, "component cannot be null");
}
@Override
public List<DefaultIssue> getIssues(Component component) {
if (component.getType() == Component.Type.DIRECTORY) {
// No issues on directories
return Collections.emptyList();
}
checkState(this.component != null && this.issues != null, "Issues have not been initialized");
checkArgument(component.equals(this.component),
"Only issues from component '%s' are available, but wanted component is '%s'.",
this.component.getReportAttributes().getRef(), component.getReportAttributes().getRef());
return issues;
}
}
| 2,261 | 37.338983 | 98 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/ComponentsWithUnprocessedIssues.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.util.HashSet;
import java.util.Set;
import javax.annotation.CheckForNull;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
public class ComponentsWithUnprocessedIssues {
@CheckForNull
private Set<String> uuids;
public void setUuids(Set<String> uuids) {
requireNonNull(uuids, "Uuids cannot be null");
checkState(this.uuids == null, "Uuids have already been initialized");
this.uuids = new HashSet<>(uuids);
}
public void remove(String uuid) {
checkIssuesAreInitialized();
uuids.remove(uuid);
}
public Set<String> getUuids() {
checkIssuesAreInitialized();
return uuids;
}
private void checkIssuesAreInitialized() {
checkState(this.uuids != null, "Uuids have not been initialized yet");
}
}
| 1,715 | 30.2 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/ComputeLocationHashesVisitor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.apache.commons.codec.digest.DigestUtils;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.projectanalysis.source.SourceLinesRepository;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.util.CloseableIterator;
import org.sonar.db.protobuf.DbCommons;
import org.sonar.db.protobuf.DbIssues;
import org.sonar.server.issue.TaintChecker;
import static org.apache.commons.lang.StringUtils.defaultIfEmpty;
import static org.sonar.api.rules.RuleType.SECURITY_HOTSPOT;
/**
* This visitor will update the locations field of issues, by filling the hashes for all locations.
* It only applies to issues that are taint vulnerabilities or security hotspots, and that are new or were changed.
* For performance reasons, it will read each source code file once and feed the lines to all locations in that file.
*/
public class ComputeLocationHashesVisitor extends IssueVisitor {
private static final Pattern MATCH_ALL_WHITESPACES = Pattern.compile("\\s");
private final List<DefaultIssue> issues = new LinkedList<>();
private final SourceLinesRepository sourceLinesRepository;
private final TreeRootHolder treeRootHolder;
private final TaintChecker taintChecker;
public ComputeLocationHashesVisitor(TaintChecker taintChecker, SourceLinesRepository sourceLinesRepository, TreeRootHolder treeRootHolder) {
this.taintChecker = taintChecker;
this.sourceLinesRepository = sourceLinesRepository;
this.treeRootHolder = treeRootHolder;
}
@Override
public void beforeComponent(Component component) {
issues.clear();
}
@Override
public void onIssue(Component component, DefaultIssue issue) {
if (shouldComputeLocation(issue)) {
issues.add(issue);
}
}
private boolean shouldComputeLocation(DefaultIssue issue) {
return (taintChecker.isTaintVulnerability(issue) || SECURITY_HOTSPOT.equals(issue.type()))
&& !issue.isFromExternalRuleEngine()
&& (issue.isNew() || issue.locationsChanged());
}
@Override
public void beforeCaching(Component component) {
Map<Component, List<Location>> locationsByComponent = new HashMap<>();
List<LocationToSet> locationsToSet = new LinkedList<>();
for (DefaultIssue issue : issues) {
DbIssues.Locations locations = issue.getLocations();
if (locations == null) {
continue;
}
DbIssues.Locations.Builder primaryLocationBuilder = locations.toBuilder();
boolean hasTextRange = addLocations(component, issue, locationsByComponent, primaryLocationBuilder);
// If any location was added (because it had a text range), we'll need to update the issue at the end with the new object containing the hashes
if (hasTextRange) {
locationsToSet.add(new LocationToSet(issue, primaryLocationBuilder));
}
}
// Feed lines to locations, component by component
locationsByComponent.forEach(this::updateLocationsInComponent);
// Finalize by setting hashes
locationsByComponent.values().forEach(list -> list.forEach(Location::afterAllLines));
// set new locations to issues
locationsToSet.forEach(LocationToSet::set);
issues.clear();
}
private boolean addLocations(Component component, DefaultIssue issue, Map<Component, List<Location>> locationsByComponent, DbIssues.Locations.Builder primaryLocationBuilder) {
boolean hasPrimaryLocation = addPrimaryLocation(component, locationsByComponent, primaryLocationBuilder);
boolean hasSecondaryLocations = addSecondaryLocations(issue, locationsByComponent, primaryLocationBuilder);
return hasPrimaryLocation || hasSecondaryLocations;
}
private static boolean addPrimaryLocation(Component component, Map<Component, List<Location>> locationsByComponent, DbIssues.Locations.Builder primaryLocationBuilder) {
if (!primaryLocationBuilder.hasTextRange()) {
return false;
}
PrimaryLocation primaryLocation = new PrimaryLocation(primaryLocationBuilder);
locationsByComponent.computeIfAbsent(component, c -> new LinkedList<>()).add(primaryLocation);
return true;
}
private boolean addSecondaryLocations(DefaultIssue issue, Map<Component, List<Location>> locationsByComponent, DbIssues.Locations.Builder primaryLocationBuilder) {
if (SECURITY_HOTSPOT.equals(issue.type())) {
return false;
}
List<DbIssues.Location.Builder> locationBuilders = primaryLocationBuilder.getFlowBuilderList().stream()
.flatMap(flowBuilder -> flowBuilder.getLocationBuilderList().stream())
.filter(DbIssues.Location.Builder::hasTextRange)
.toList();
locationBuilders.forEach(locationBuilder -> addSecondaryLocation(locationBuilder, issue, locationsByComponent));
return !locationBuilders.isEmpty();
}
private void addSecondaryLocation(DbIssues.Location.Builder locationBuilder, DefaultIssue issue, Map<Component, List<Location>> locationsByComponent) {
String componentUuid = defaultIfEmpty(locationBuilder.getComponentId(), issue.componentUuid());
Component locationComponent = treeRootHolder.getComponentByUuid(componentUuid);
locationsByComponent.computeIfAbsent(locationComponent, c -> new LinkedList<>()).add(new SecondaryLocation(locationBuilder));
}
private void updateLocationsInComponent(Component component, List<Location> locations) {
try (CloseableIterator<String> linesIterator = sourceLinesRepository.readLines(component)) {
int lineNumber = 1;
while (linesIterator.hasNext()) {
String line = linesIterator.next();
for (Location location : locations) {
location.processLine(lineNumber, line);
}
lineNumber++;
}
}
}
private static class LocationToSet {
private final DefaultIssue issue;
private final DbIssues.Locations.Builder locationsBuilder;
public LocationToSet(DefaultIssue issue, DbIssues.Locations.Builder locationsBuilder) {
this.issue = issue;
this.locationsBuilder = locationsBuilder;
}
void set() {
issue.setLocations(locationsBuilder.build());
}
}
private static class PrimaryLocation extends Location {
private final DbIssues.Locations.Builder locationsBuilder;
public PrimaryLocation(DbIssues.Locations.Builder locationsBuilder) {
this.locationsBuilder = locationsBuilder;
}
@Override
DbCommons.TextRange getTextRange() {
return locationsBuilder.getTextRange();
}
@Override
void setHash(String hash) {
locationsBuilder.setChecksum(hash);
}
}
private static class SecondaryLocation extends Location {
private final DbIssues.Location.Builder locationBuilder;
public SecondaryLocation(DbIssues.Location.Builder locationBuilder) {
this.locationBuilder = locationBuilder;
}
@Override
DbCommons.TextRange getTextRange() {
return locationBuilder.getTextRange();
}
@Override
void setHash(String hash) {
locationBuilder.setChecksum(hash);
}
}
private abstract static class Location {
private final StringBuilder hashBuilder = new StringBuilder();
abstract DbCommons.TextRange getTextRange();
abstract void setHash(String hash);
public void processLine(int lineNumber, String line) {
DbCommons.TextRange textRange = getTextRange();
if (lineNumber > textRange.getEndLine() || lineNumber < textRange.getStartLine()) {
return;
}
if (lineNumber == textRange.getStartLine() && lineNumber == textRange.getEndLine()) {
hashBuilder.append(line, textRange.getStartOffset(), textRange.getEndOffset());
} else if (lineNumber == textRange.getStartLine()) {
hashBuilder.append(line, textRange.getStartOffset(), line.length());
} else if (lineNumber < textRange.getEndLine()) {
hashBuilder.append(line);
} else {
hashBuilder.append(line, 0, textRange.getEndOffset());
}
}
void afterAllLines() {
String issueContentWithoutWhitespaces = MATCH_ALL_WHITESPACES.matcher(hashBuilder.toString()).replaceAll("");
String hash = DigestUtils.md5Hex(issueContentWithoutWhitespaces);
setHash(hash);
}
}
}
| 9,255 | 37.890756 | 177 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/DebtCalculator.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import com.google.common.base.MoreObjects;
import com.google.common.base.Strings;
import javax.annotation.CheckForNull;
import org.sonar.api.server.debt.DebtRemediationFunction;
import org.sonar.api.server.debt.DebtRemediationFunction.Type;
import org.sonar.api.utils.Duration;
import org.sonar.api.utils.Durations;
import org.sonar.core.issue.DefaultIssue;
public class DebtCalculator {
private final RuleRepository ruleRepository;
private final Durations durations;
public DebtCalculator(RuleRepository ruleRepository, Durations durations) {
this.ruleRepository = ruleRepository;
this.durations = durations;
}
@CheckForNull
public Duration calculate(DefaultIssue issue) {
if (issue.isFromExternalRuleEngine()) {
return issue.effort();
}
Rule rule = ruleRepository.getByKey(issue.ruleKey());
DebtRemediationFunction fn = rule.getRemediationFunction();
if (fn != null) {
verifyEffortToFix(issue, fn);
Duration debt = Duration.create(0);
String gapMultiplier = fn.gapMultiplier();
if (fn.type().usesGapMultiplier() && !Strings.isNullOrEmpty(gapMultiplier)) {
int effortToFixValue = MoreObjects.firstNonNull(issue.gap(), 1).intValue();
// TODO convert to Duration directly in Rule#remediationFunction -> better performance + error handling
debt = durations.decode(gapMultiplier).multiply(effortToFixValue);
}
String baseEffort = fn.baseEffort();
if (fn.type().usesBaseEffort() && !Strings.isNullOrEmpty(baseEffort)) {
// TODO convert to Duration directly in Rule#remediationFunction -> better performance + error handling
debt = debt.add(durations.decode(baseEffort));
}
return debt;
}
return null;
}
private static void verifyEffortToFix(DefaultIssue issue, DebtRemediationFunction fn) {
if (Type.CONSTANT_ISSUE.equals(fn.type()) && issue.gap() != null) {
throw new IllegalArgumentException("Rule '" + issue.getRuleKey() + "' can not use 'Constant/issue' remediation function " +
"because this rule does not have a fixed remediation cost.");
}
}
}
| 3,022 | 39.306667 | 129 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/DefaultAssignee.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import javax.annotation.CheckForNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.ce.task.projectanalysis.component.ConfigurationRepository;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.user.UserDto;
import org.sonar.db.user.UserIdDto;
import static com.google.common.base.Strings.isNullOrEmpty;
import static org.sonar.api.CoreProperties.DEFAULT_ISSUE_ASSIGNEE;
/**
* The user who is optionally declared as being the assignee
* of all the issues which SCM author is not associated with any SonarQube user.
*/
public class DefaultAssignee {
private static final Logger LOG = LoggerFactory.getLogger(DefaultAssignee.class);
private final DbClient dbClient;
private final ConfigurationRepository configRepository;
private boolean loaded = false;
private UserIdDto userId = null;
public DefaultAssignee(DbClient dbClient, ConfigurationRepository configRepository) {
this.dbClient = dbClient;
this.configRepository = configRepository;
}
@CheckForNull
public UserIdDto loadDefaultAssigneeUserId() {
if (loaded) {
return userId;
}
String login = configRepository.getConfiguration().get(DEFAULT_ISSUE_ASSIGNEE).orElse(null);
if (!isNullOrEmpty(login)) {
userId = findValidUserUuidFromLogin(login);
}
loaded = true;
return userId;
}
private UserIdDto findValidUserUuidFromLogin(String login) {
try (DbSession dbSession = dbClient.openSession(false)) {
UserDto user = dbClient.userDao().selectActiveUserByLogin(dbSession, login);
if (user == null) {
LOG.info("Property {} is set with an unknown login: {}", DEFAULT_ISSUE_ASSIGNEE, login);
return null;
}
return new UserIdDto(user.getUuid(), user.getLogin());
}
}
}
| 2,697 | 33.589744 | 96 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/DefaultTrackingInput.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.util.Collection;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.tracking.BlockHashSequence;
import org.sonar.core.issue.tracking.Input;
import org.sonar.core.issue.tracking.LineHashSequence;
public class DefaultTrackingInput implements Input<DefaultIssue> {
private final Collection<DefaultIssue> issues;
private final LineHashSequence lineHashes;
private final BlockHashSequence blockHashes;
public DefaultTrackingInput(Collection<DefaultIssue> issues, LineHashSequence lineHashes, BlockHashSequence blockHashes) {
this.issues = issues;
this.lineHashes = lineHashes;
this.blockHashes = blockHashes;
}
@Override
public LineHashSequence getLineHashSequence() {
return lineHashes;
}
@Override
public BlockHashSequence getBlockHashSequence() {
return blockHashes;
}
@Override
public Collection<DefaultIssue> getIssues() {
return issues;
}
}
| 1,824 | 32.181818 | 124 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/EffortAggregator.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.util.HashMap;
import java.util.Map;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.ce.task.projectanalysis.component.Component;
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.core.issue.DefaultIssue;
import static org.sonar.api.measures.CoreMetrics.RELIABILITY_REMEDIATION_EFFORT_KEY;
import static org.sonar.api.measures.CoreMetrics.SECURITY_REMEDIATION_EFFORT_KEY;
import static org.sonar.api.measures.CoreMetrics.TECHNICAL_DEBT_KEY;
/**
* Compute effort related measures :
* {@link CoreMetrics#TECHNICAL_DEBT_KEY}
* {@link CoreMetrics#RELIABILITY_REMEDIATION_EFFORT_KEY}
* {@link CoreMetrics#SECURITY_REMEDIATION_EFFORT_KEY}
*/
public class EffortAggregator extends IssueVisitor {
private final MeasureRepository measureRepository;
private final Map<String, EffortCounter> effortsByComponentUuid = new HashMap<>();
private final Metric maintainabilityEffortMetric;
private final Metric reliabilityEffortMetric;
private final Metric securityEffortMetric;
private EffortCounter effortCounter;
public EffortAggregator(MetricRepository metricRepository, MeasureRepository measureRepository) {
this.measureRepository = measureRepository;
this.maintainabilityEffortMetric = metricRepository.getByKey(TECHNICAL_DEBT_KEY);
this.reliabilityEffortMetric = metricRepository.getByKey(RELIABILITY_REMEDIATION_EFFORT_KEY);
this.securityEffortMetric = metricRepository.getByKey(SECURITY_REMEDIATION_EFFORT_KEY);
}
@Override
public void beforeComponent(Component component) {
effortCounter = new EffortCounter();
effortsByComponentUuid.put(component.getUuid(), effortCounter);
// aggregate children counters
for (Component child : component.getChildren()) {
// no need to keep the children in memory. They can be garbage-collected.
EffortCounter childEffortCounter = effortsByComponentUuid.remove(child.getUuid());
if (childEffortCounter != null) {
effortCounter.add(childEffortCounter);
}
}
}
@Override
public void onIssue(Component component, DefaultIssue issue) {
if (issue.resolution() == null) {
effortCounter.add(issue);
}
}
@Override
public void afterComponent(Component component) {
computeMaintainabilityEffortMeasure(component);
computeReliabilityEffortMeasure(component);
computeSecurityEffortMeasure(component);
this.effortCounter = null;
}
private void computeMaintainabilityEffortMeasure(Component component) {
measureRepository.add(component, maintainabilityEffortMetric, Measure.newMeasureBuilder().create(effortCounter.maintainabilityEffort));
}
private void computeReliabilityEffortMeasure(Component component) {
measureRepository.add(component, reliabilityEffortMetric, Measure.newMeasureBuilder().create(effortCounter.reliabilityEffort));
}
private void computeSecurityEffortMeasure(Component component) {
measureRepository.add(component, securityEffortMetric, Measure.newMeasureBuilder().create(effortCounter.securityEffort));
}
private static class EffortCounter {
private long maintainabilityEffort = 0L;
private long reliabilityEffort = 0L;
private long securityEffort = 0L;
void add(DefaultIssue issue) {
Long issueEffort = issue.effortInMinutes();
if (issueEffort != null && issueEffort != 0L) {
switch (issue.type()) {
case CODE_SMELL:
maintainabilityEffort += issueEffort;
break;
case BUG:
reliabilityEffort += issueEffort;
break;
case VULNERABILITY:
securityEffort += issueEffort;
break;
case SECURITY_HOTSPOT:
// Not counted
break;
default:
throw new IllegalStateException(String.format("Unknown type '%s'", issue.type()));
}
}
}
public void add(EffortCounter effortCounter) {
maintainabilityEffort += effortCounter.maintainabilityEffort;
reliabilityEffort += effortCounter.reliabilityEffort;
securityEffort += effortCounter.securityEffort;
}
}
}
| 5,220 | 37.109489 | 139 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/IntegrateIssuesVisitor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit;
import org.sonar.ce.task.projectanalysis.component.FileStatuses;
import org.sonar.ce.task.projectanalysis.component.ReferenceBranchComponentUuids;
import org.sonar.ce.task.projectanalysis.component.TypeAwareVisitorAdapter;
import org.sonar.ce.task.projectanalysis.util.cache.DiskCache.CacheAppender;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.tracking.Input;
import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.POST_ORDER;
public class IntegrateIssuesVisitor extends TypeAwareVisitorAdapter {
private final ProtoIssueCache protoIssueCache;
private final TrackerRawInputFactory rawInputFactory;
private final TrackerBaseInputFactory baseInputFactory;
private final IssueLifecycle issueLifecycle;
private final IssueVisitors issueVisitors;
private final IssueTrackingDelegator issueTracking;
private final SiblingsIssueMerger issueStatusCopier;
private final ReferenceBranchComponentUuids referenceBranchComponentUuids;
private final PullRequestSourceBranchMerger pullRequestSourceBranchMerger;
private final FileStatuses fileStatuses;
public IntegrateIssuesVisitor(
ProtoIssueCache protoIssueCache,
TrackerRawInputFactory rawInputFactory,
TrackerBaseInputFactory baseInputFactory,
IssueLifecycle issueLifecycle,
IssueVisitors issueVisitors,
IssueTrackingDelegator issueTracking,
SiblingsIssueMerger issueStatusCopier,
ReferenceBranchComponentUuids referenceBranchComponentUuids,
PullRequestSourceBranchMerger pullRequestSourceBranchMerger,
FileStatuses fileStatuses) {
super(CrawlerDepthLimit.FILE, POST_ORDER);
this.protoIssueCache = protoIssueCache;
this.rawInputFactory = rawInputFactory;
this.baseInputFactory = baseInputFactory;
this.issueLifecycle = issueLifecycle;
this.issueVisitors = issueVisitors;
this.issueTracking = issueTracking;
this.issueStatusCopier = issueStatusCopier;
this.referenceBranchComponentUuids = referenceBranchComponentUuids;
this.pullRequestSourceBranchMerger = pullRequestSourceBranchMerger;
this.fileStatuses = fileStatuses;
}
@Override
public void visitAny(Component component) {
try (CacheAppender<DefaultIssue> cacheAppender = protoIssueCache.newAppender()) {
issueVisitors.beforeComponent(component);
if (fileStatuses.isDataUnchanged(component)) {
// we assume there's a previous analysis of the same branch
Input<DefaultIssue> baseIssues = baseInputFactory.create(component);
var issues = new LinkedList<>(baseIssues.getIssues());
processIssues(component, issues);
issueVisitors.beforeCaching(component);
appendIssuesToCache(cacheAppender, issues);
} else {
Input<DefaultIssue> rawInput = rawInputFactory.create(component);
TrackingResult tracking = issueTracking.track(component, rawInput);
var newOpenIssues = fillNewOpenIssues(component, tracking.newIssues(), rawInput);
var existingOpenIssues = fillExistingOpenIssues(tracking.issuesToMerge());
var closedIssues = closeIssues(tracking.issuesToClose());
var copiedIssues = copyIssues(tracking.issuesToCopy());
var issues = Stream.of(newOpenIssues, existingOpenIssues, closedIssues, copiedIssues)
.flatMap(Collection::stream)
.toList();
processIssues(component, issues);
issueVisitors.beforeCaching(component);
appendIssuesToCache(cacheAppender, issues);
}
issueVisitors.afterComponent(component);
} catch (Exception e) {
throw new IllegalStateException(String.format("Fail to process issues of component '%s'", component.getKey()), e);
}
}
private void processIssues(Component component, Collection<DefaultIssue> issues) {
issues.forEach(issue -> processIssue(component, issue));
}
private List<DefaultIssue> fillNewOpenIssues(Component component, Stream<DefaultIssue> newIssues, Input<DefaultIssue> rawInput) {
List<DefaultIssue> newIssuesList = newIssues
.peek(issueLifecycle::initNewOpenIssue)
.toList();
if (newIssuesList.isEmpty()) {
return newIssuesList;
}
pullRequestSourceBranchMerger.tryMergeIssuesFromSourceBranchOfPullRequest(component, newIssuesList, rawInput);
issueStatusCopier.tryMerge(component, newIssuesList);
return newIssuesList;
}
private List<DefaultIssue> fillExistingOpenIssues(Map<DefaultIssue, DefaultIssue> matched) {
List<DefaultIssue> newIssuesList = new LinkedList<>();
for (Map.Entry<DefaultIssue, DefaultIssue> entry : matched.entrySet()) {
DefaultIssue raw = entry.getKey();
DefaultIssue base = entry.getValue();
issueLifecycle.mergeExistingOpenIssue(raw, base);
newIssuesList.add(raw);
}
return newIssuesList;
}
private static List<DefaultIssue> closeIssues(Stream<DefaultIssue> issues) {
return issues.map(issue ->
// TODO should replace flag "beingClosed" by express call to transition "automaticClose"
issue.setBeingClosed(true)
// TODO manual issues -> was updater.setResolution(newIssue, Issue.RESOLUTION_REMOVED, changeContext);. Is it a problem ?
).toList();
}
private List<DefaultIssue> copyIssues(Map<DefaultIssue, DefaultIssue> matched) {
List<DefaultIssue> newIssuesList = new LinkedList<>();
for (Map.Entry<DefaultIssue, DefaultIssue> entry : matched.entrySet()) {
DefaultIssue raw = entry.getKey();
DefaultIssue base = entry.getValue();
issueLifecycle.copyExistingOpenIssueFromBranch(raw, base, referenceBranchComponentUuids.getReferenceBranchName());
newIssuesList.add(raw);
}
return newIssuesList;
}
private void processIssue(Component component, DefaultIssue issue) {
issueLifecycle.doAutomaticTransition(issue);
issueVisitors.onIssue(component, issue);
}
private static void appendIssuesToCache(CacheAppender<DefaultIssue> cacheAppender, Collection<DefaultIssue> issues) {
issues.forEach(issue -> appendIssue(issue, cacheAppender));
}
private static void appendIssue(DefaultIssue issue, CacheAppender<DefaultIssue> cacheAppender) {
if (issue.isNew() || issue.isChanged() || issue.isCopied() || issue.isNoLongerNewCodeReferenceIssue() || issue.isToBeMigratedAsNewCodeReferenceIssue()) {
cacheAppender.append(issue);
}
}
}
| 7,510 | 42.668605 | 157 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/IssueAssigner.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.util.Comparator;
import java.util.Date;
import java.util.Optional;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.scm.Changeset;
import org.sonar.ce.task.projectanalysis.scm.ScmInfo;
import org.sonar.ce.task.projectanalysis.scm.ScmInfoRepository;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.IssueChangeContext;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.user.UserIdDto;
import org.sonar.server.issue.IssueFieldsSetter;
import static org.apache.commons.lang.StringUtils.defaultIfEmpty;
import static org.sonar.core.issue.IssueChangeContext.issueChangeContextByScanBuilder;
/**
* Detect the SCM author and SQ assignee.
* <p/>
* It relies on SCM information which comes from both the report and database.
*/
public class IssueAssigner extends IssueVisitor {
private static final Logger LOGGER = LoggerFactory.getLogger(IssueAssigner.class);
private final ScmInfoRepository scmInfoRepository;
private final DefaultAssignee defaultAssignee;
private final IssueFieldsSetter issueUpdater;
private final ScmAccountToUser scmAccountToUser;
private final IssueChangeContext changeContext;
private String lastCommitAuthor = null;
private ScmInfo scmChangesets = null;
public IssueAssigner(AnalysisMetadataHolder analysisMetadataHolder, ScmInfoRepository scmInfoRepository, ScmAccountToUser scmAccountToUser, DefaultAssignee defaultAssignee,
IssueFieldsSetter issueUpdater) {
this.scmInfoRepository = scmInfoRepository;
this.scmAccountToUser = scmAccountToUser;
this.defaultAssignee = defaultAssignee;
this.issueUpdater = issueUpdater;
this.changeContext = issueChangeContextByScanBuilder(new Date(analysisMetadataHolder.getAnalysisDate())).build();
}
@Override
public void onIssue(Component component, DefaultIssue issue) {
if (issue.authorLogin() != null) {
return;
}
loadScmChangesets(component);
Optional<String> scmAuthor = guessScmAuthor(issue, component);
if (scmAuthor.isPresent()) {
if (scmAuthor.get().length() <= IssueDto.AUTHOR_MAX_SIZE) {
issueUpdater.setNewAuthor(issue, scmAuthor.get(), changeContext);
} else {
LOGGER.debug("SCM account '{}' is too long to be stored as issue author", scmAuthor.get());
}
}
if (issue.assignee() == null) {
UserIdDto userId = scmAuthor.map(scmAccountToUser::getNullable).orElse(defaultAssignee.loadDefaultAssigneeUserId());
issueUpdater.setNewAssignee(issue, userId, changeContext);
}
}
private void loadScmChangesets(Component component) {
if (scmChangesets == null) {
Optional<ScmInfo> scmInfoOptional = scmInfoRepository.getScmInfo(component);
if (scmInfoOptional.isPresent()) {
scmChangesets = scmInfoOptional.get();
lastCommitAuthor = scmChangesets.getLatestChangeset().getAuthor();
}
}
}
@Override
public void afterComponent(Component component) {
lastCommitAuthor = null;
scmChangesets = null;
}
/**
* Author of the latest change on the lines involved by the issue.
* If no authors are set on the lines, then the author of the latest change on the file
* is returned.
*/
private Optional<String> guessScmAuthor(DefaultIssue issue, Component component) {
String author = null;
if (scmChangesets != null) {
author = IssueLocations.allLinesFor(issue, component.getUuid())
.filter(scmChangesets::hasChangesetForLine)
.mapToObj(scmChangesets::getChangesetForLine)
.filter(c -> StringUtils.isNotEmpty(c.getAuthor()))
.max(Comparator.comparingLong(Changeset::getDate))
.map(Changeset::getAuthor)
.orElse(null);
}
return Optional.ofNullable(defaultIfEmpty(author, lastCommitAuthor));
}
}
| 4,896 | 37.865079 | 174 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/IssueChangesToDeleteRepository.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.util.HashSet;
import java.util.Set;
import static java.util.Collections.unmodifiableSet;
public class IssueChangesToDeleteRepository {
private final Set<String> uuids = new HashSet<>();
public void add(String uuid) {
uuids.add(uuid);
}
public Set<String> getUuids() {
return unmodifiableSet(uuids);
}
}
| 1,230 | 31.394737 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/IssueCounter.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import com.google.common.collect.EnumMultiset;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Multiset;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
import org.sonar.api.rules.RuleType;
import org.sonar.ce.task.projectanalysis.component.Component;
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.core.issue.DefaultIssue;
import static org.sonar.api.issue.Issue.RESOLUTION_FALSE_POSITIVE;
import static org.sonar.api.issue.Issue.RESOLUTION_WONT_FIX;
import static org.sonar.api.issue.Issue.STATUS_CONFIRMED;
import static org.sonar.api.issue.Issue.STATUS_OPEN;
import static org.sonar.api.issue.Issue.STATUS_REOPENED;
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.CODE_SMELLS_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.FALSE_POSITIVE_ISSUES_KEY;
import static org.sonar.api.measures.CoreMetrics.INFO_VIOLATIONS_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.NEW_BLOCKER_VIOLATIONS_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_BUGS_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_CODE_SMELLS_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_CRITICAL_VIOLATIONS_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_INFO_VIOLATIONS_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_MAJOR_VIOLATIONS_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_MINOR_VIOLATIONS_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_VIOLATIONS_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_VULNERABILITIES_KEY;
import static org.sonar.api.measures.CoreMetrics.OPEN_ISSUES_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.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.api.rule.Severity.BLOCKER;
import static org.sonar.api.rule.Severity.CRITICAL;
import static org.sonar.api.rule.Severity.INFO;
import static org.sonar.api.rule.Severity.MAJOR;
import static org.sonar.api.rule.Severity.MINOR;
import static org.sonar.api.rules.RuleType.BUG;
import static org.sonar.api.rules.RuleType.CODE_SMELL;
import static org.sonar.api.rules.RuleType.SECURITY_HOTSPOT;
import static org.sonar.api.rules.RuleType.VULNERABILITY;
/**
* For each component, computes the measures related to number of issues:
* <ul>
* <li>issues per status (open, reopen, confirmed)</li>
* <li>issues per resolution (unresolved, false-positives, won't fix)</li>
* <li>issues per severity (from info to blocker)</li>
* <li>issues per type (code smell, bug, vulnerability, security hotspots)</li>
* </ul>
* For each value, the variation on configured periods is also computed.
*/
public class IssueCounter extends IssueVisitor {
private static final Map<String, String> SEVERITY_TO_METRIC_KEY = ImmutableMap.of(
BLOCKER, BLOCKER_VIOLATIONS_KEY,
CRITICAL, CRITICAL_VIOLATIONS_KEY,
MAJOR, MAJOR_VIOLATIONS_KEY,
MINOR, MINOR_VIOLATIONS_KEY,
INFO, INFO_VIOLATIONS_KEY);
private static final Map<String, String> SEVERITY_TO_NEW_METRIC_KEY = ImmutableMap.of(
BLOCKER, NEW_BLOCKER_VIOLATIONS_KEY,
CRITICAL, NEW_CRITICAL_VIOLATIONS_KEY,
MAJOR, NEW_MAJOR_VIOLATIONS_KEY,
MINOR, NEW_MINOR_VIOLATIONS_KEY,
INFO, NEW_INFO_VIOLATIONS_KEY);
private static final Map<RuleType, String> TYPE_TO_METRIC_KEY = ImmutableMap.<RuleType, String>builder()
.put(CODE_SMELL, CODE_SMELLS_KEY)
.put(BUG, BUGS_KEY)
.put(VULNERABILITY, VULNERABILITIES_KEY)
.put(SECURITY_HOTSPOT, SECURITY_HOTSPOTS_KEY)
.build();
private static final Map<RuleType, String> TYPE_TO_NEW_METRIC_KEY = ImmutableMap.<RuleType, String>builder()
.put(CODE_SMELL, NEW_CODE_SMELLS_KEY)
.put(BUG, NEW_BUGS_KEY)
.put(VULNERABILITY, NEW_VULNERABILITIES_KEY)
.put(SECURITY_HOTSPOT, NEW_SECURITY_HOTSPOTS_KEY)
.build();
private final MetricRepository metricRepository;
private final MeasureRepository measureRepository;
private final NewIssueClassifier newIssueClassifier;
private final Map<String, Counters> countersByComponentUuid = new HashMap<>();
private Counters currentCounters;
public IssueCounter(MetricRepository metricRepository, MeasureRepository measureRepository, NewIssueClassifier newIssueClassifier) {
this.metricRepository = metricRepository;
this.measureRepository = measureRepository;
this.newIssueClassifier = newIssueClassifier;
}
@Override
public void beforeComponent(Component component) {
currentCounters = new Counters();
countersByComponentUuid.put(component.getUuid(), currentCounters);
// aggregate children counters
for (Component child : component.getChildren()) {
Counters childCounters = countersByComponentUuid.remove(child.getUuid());
currentCounters.add(childCounters);
}
}
@Override
public void onIssue(Component component, DefaultIssue issue) {
currentCounters.add(issue);
if (newIssueClassifier.isNew(component, issue)) {
currentCounters.addOnPeriod(issue);
}
}
@Override
public void afterComponent(Component component) {
addMeasuresBySeverity(component);
addMeasuresByStatus(component);
addMeasuresByType(component);
addNewMeasures(component);
currentCounters = null;
}
private void addMeasuresBySeverity(Component component) {
for (Map.Entry<String, String> entry : SEVERITY_TO_METRIC_KEY.entrySet()) {
String severity = entry.getKey();
String metricKey = entry.getValue();
addMeasure(component, metricKey, currentCounters.counter().severityBag.count(severity));
}
}
private void addMeasuresByStatus(Component component) {
addMeasure(component, VIOLATIONS_KEY, currentCounters.counter().unresolved);
addMeasure(component, OPEN_ISSUES_KEY, currentCounters.counter().open);
addMeasure(component, REOPENED_ISSUES_KEY, currentCounters.counter().reopened);
addMeasure(component, CONFIRMED_ISSUES_KEY, currentCounters.counter().confirmed);
addMeasure(component, FALSE_POSITIVE_ISSUES_KEY, currentCounters.counter().falsePositives);
addMeasure(component, WONT_FIX_ISSUES_KEY, currentCounters.counter().wontFix);
}
private void addMeasuresByType(Component component) {
for (Map.Entry<RuleType, String> entry : TYPE_TO_METRIC_KEY.entrySet()) {
addMeasure(component, entry.getValue(), currentCounters.counter().typeBag.count(entry.getKey()));
}
}
private void addMeasure(Component component, String metricKey, int value) {
Metric metric = metricRepository.getByKey(metricKey);
measureRepository.add(component, metric, Measure.newMeasureBuilder().create(value));
}
private void addNewMeasures(Component component) {
if (!newIssueClassifier.isEnabled()) {
return;
}
int unresolved = currentCounters.counterForPeriod().unresolved;
measureRepository.add(component, metricRepository.getByKey(NEW_VIOLATIONS_KEY), Measure.newMeasureBuilder()
.create(unresolved));
for (Map.Entry<String, String> entry : SEVERITY_TO_NEW_METRIC_KEY.entrySet()) {
String severity = entry.getKey();
String metricKey = entry.getValue();
Multiset<String> bag = currentCounters.counterForPeriod().severityBag;
Metric metric = metricRepository.getByKey(metricKey);
measureRepository.add(component, metric, Measure.newMeasureBuilder()
.create(bag.count(severity)));
}
// waiting for Java 8 lambda in order to factor this loop with the previous one
// (see call currentCounters.counterForPeriod(period.getIndex()).xxx with xxx as severityBag or typeBag)
for (Map.Entry<RuleType, String> entry : TYPE_TO_NEW_METRIC_KEY.entrySet()) {
RuleType type = entry.getKey();
String metricKey = entry.getValue();
Multiset<RuleType> bag = currentCounters.counterForPeriod().typeBag;
Metric metric = metricRepository.getByKey(metricKey);
measureRepository.add(component, metric, Measure.newMeasureBuilder()
.create(bag.count(type)));
}
}
/**
* Count issues by status, resolutions, rules and severities
*/
private static class Counter {
private int unresolved = 0;
private int open = 0;
private int reopened = 0;
private int confirmed = 0;
private int falsePositives = 0;
private int wontFix = 0;
private final Multiset<String> severityBag = HashMultiset.create();
private final EnumMultiset<RuleType> typeBag = EnumMultiset.create(RuleType.class);
void add(Counter counter) {
unresolved += counter.unresolved;
open += counter.open;
reopened += counter.reopened;
confirmed += counter.confirmed;
falsePositives += counter.falsePositives;
wontFix += counter.wontFix;
severityBag.addAll(counter.severityBag);
typeBag.addAll(counter.typeBag);
}
void add(DefaultIssue issue) {
if (issue.type() == SECURITY_HOTSPOT) {
if (issue.resolution() == null) {
typeBag.add(SECURITY_HOTSPOT);
}
return;
}
if (issue.resolution() == null) {
unresolved++;
typeBag.add(issue.type());
severityBag.add(issue.severity());
} else if (RESOLUTION_FALSE_POSITIVE.equals(issue.resolution())) {
falsePositives++;
} else if (RESOLUTION_WONT_FIX.equals(issue.resolution())) {
wontFix++;
}
switch (issue.status()) {
case STATUS_OPEN:
open++;
break;
case STATUS_REOPENED:
reopened++;
break;
case STATUS_CONFIRMED:
confirmed++;
break;
default:
// Other statuses are ignored
}
}
}
/**
* List of {@link Counter} for regular value and period.
*/
private static class Counters {
private final Counter counter = new Counter();
private final Counter counterForPeriod = new Counter();
void add(@Nullable Counters other) {
if (other != null) {
counter.add(other.counter);
counterForPeriod.add(other.counterForPeriod);
}
}
void addOnPeriod(DefaultIssue issue) {
counterForPeriod.add(issue);
}
void add(DefaultIssue issue) {
counter.add(issue);
}
Counter counter() {
return counter;
}
Counter counterForPeriod() {
return counterForPeriod;
}
}
}
| 12,165 | 39.284768 | 134 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/IssueCreationDateCalculator.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.util.Comparator;
import java.util.Date;
import java.util.Optional;
import java.util.function.Supplier;
import javax.annotation.Nullable;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.utils.DateUtils;
import org.sonar.ce.task.projectanalysis.analysis.Analysis;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.analysis.ScannerPlugin;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.filemove.AddedFileRepository;
import org.sonar.ce.task.projectanalysis.qualityprofile.ActiveRule;
import org.sonar.ce.task.projectanalysis.qualityprofile.ActiveRulesHolder;
import org.sonar.ce.task.projectanalysis.qualityprofile.QProfileStatusRepository;
import org.sonar.ce.task.projectanalysis.scm.Changeset;
import org.sonar.ce.task.projectanalysis.scm.ScmInfo;
import org.sonar.ce.task.projectanalysis.scm.ScmInfoRepository;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.IssueChangeContext;
import org.sonar.server.issue.IssueFieldsSetter;
import static org.sonar.ce.task.projectanalysis.qualityprofile.QProfileStatusRepository.Status.UNCHANGED;
import static org.sonar.core.issue.IssueChangeContext.issueChangeContextByScanBuilder;
/**
* Calculates the creation date of an issue. Takes into account, that the issue
* might be raised by adding a rule to a quality profile.
*/
public class IssueCreationDateCalculator extends IssueVisitor {
private final ScmInfoRepository scmInfoRepository;
private final IssueFieldsSetter issueUpdater;
private final AnalysisMetadataHolder analysisMetadataHolder;
private final IssueChangeContext changeContext;
private final ActiveRulesHolder activeRulesHolder;
private final RuleRepository ruleRepository;
private final AddedFileRepository addedFileRepository;
private QProfileStatusRepository qProfileStatusRepository;
public IssueCreationDateCalculator(AnalysisMetadataHolder analysisMetadataHolder, ScmInfoRepository scmInfoRepository,
IssueFieldsSetter issueUpdater, ActiveRulesHolder activeRulesHolder, RuleRepository ruleRepository,
AddedFileRepository addedFileRepository, QProfileStatusRepository qProfileStatusRepository) {
this.scmInfoRepository = scmInfoRepository;
this.issueUpdater = issueUpdater;
this.analysisMetadataHolder = analysisMetadataHolder;
this.ruleRepository = ruleRepository;
this.changeContext = issueChangeContextByScanBuilder(new Date(analysisMetadataHolder.getAnalysisDate())).build();
this.activeRulesHolder = activeRulesHolder;
this.addedFileRepository = addedFileRepository;
this.qProfileStatusRepository = qProfileStatusRepository;
}
@Override
public void onIssue(Component component, DefaultIssue issue) {
if (!issue.isNew()) {
return;
}
Optional<Long> lastAnalysisOptional = lastAnalysis();
boolean firstAnalysis = !lastAnalysisOptional.isPresent();
if (firstAnalysis || isNewFile(component)) {
backdateIssue(component, issue);
return;
}
Rule rule = ruleRepository.findByKey(issue.getRuleKey())
.orElseThrow(illegalStateException("The rule with key '%s' raised an issue, but no rule with that key was found", issue.getRuleKey()));
if (rule.isExternal()) {
backdateIssue(component, issue);
} else {
// Rule can't be inactive (see contract of IssueVisitor)
ActiveRule activeRule = activeRulesHolder.get(issue.getRuleKey()).get();
if (activeRuleIsNewOrChanged(activeRule, lastAnalysisOptional.get())
|| ruleImplementationChanged(activeRule.getRuleKey(), activeRule.getPluginKey(), lastAnalysisOptional.get())
|| qualityProfileChanged(activeRule.getQProfileKey())) {
backdateIssue(component, issue);
}
}
}
private boolean qualityProfileChanged(String qpKey) {
return qProfileStatusRepository.get(qpKey).filter(s -> !s.equals(UNCHANGED)).isPresent();
}
private boolean isNewFile(Component component) {
return component.getType() == Component.Type.FILE && addedFileRepository.isAdded(component);
}
private void backdateIssue(Component component, DefaultIssue issue) {
getDateOfLatestChange(component, issue).ifPresent(changeDate -> updateDate(issue, changeDate));
}
private boolean ruleImplementationChanged(RuleKey ruleKey, @Nullable String pluginKey, long lastAnalysisDate) {
if (pluginKey == null) {
return false;
}
ScannerPlugin scannerPlugin = Optional.ofNullable(analysisMetadataHolder.getScannerPluginsByKey().get(pluginKey))
.orElseThrow(illegalStateException("The rule %s is declared to come from plugin %s, but this plugin was not used by scanner.", ruleKey, pluginKey));
return pluginIsNew(scannerPlugin, lastAnalysisDate)
|| basePluginIsNew(scannerPlugin, lastAnalysisDate);
}
private boolean basePluginIsNew(ScannerPlugin scannerPlugin, long lastAnalysisDate) {
String basePluginKey = scannerPlugin.getBasePluginKey();
if (basePluginKey == null) {
return false;
}
ScannerPlugin basePlugin = analysisMetadataHolder.getScannerPluginsByKey().get(basePluginKey);
return lastAnalysisDate < basePlugin.getUpdatedAt();
}
private static boolean pluginIsNew(ScannerPlugin scannerPlugin, long lastAnalysisDate) {
return lastAnalysisDate < scannerPlugin.getUpdatedAt();
}
private static boolean activeRuleIsNewOrChanged(ActiveRule activeRule, Long lastAnalysisDate) {
return lastAnalysisDate < activeRule.getUpdatedAt();
}
private Optional<Date> getDateOfLatestChange(Component component, DefaultIssue issue) {
return getScmInfo(component)
.flatMap(scmInfo -> getLatestChangeset(component, scmInfo, issue))
.map(IssueCreationDateCalculator::getChangeDate);
}
private Optional<Long> lastAnalysis() {
return Optional.ofNullable(analysisMetadataHolder.getBaseAnalysis()).map(Analysis::getCreatedAt);
}
private Optional<ScmInfo> getScmInfo(Component component) {
return scmInfoRepository.getScmInfo(component);
}
private static Optional<Changeset> getLatestChangeset(Component component, ScmInfo scmInfo, DefaultIssue issue) {
Optional<Changeset> mostRecentChangeset = IssueLocations.allLinesFor(issue, component.getUuid())
.filter(scmInfo::hasChangesetForLine)
.mapToObj(scmInfo::getChangesetForLine)
.max(Comparator.comparingLong(Changeset::getDate));
if (mostRecentChangeset.isPresent()) {
return mostRecentChangeset;
}
return Optional.of(scmInfo.getLatestChangeset());
}
private static Date getChangeDate(Changeset changesetForLine) {
return DateUtils.longToDate(changesetForLine.getDate());
}
private void updateDate(DefaultIssue issue, Date scmDate) {
issueUpdater.setCreationDate(issue, scmDate, changeContext);
}
private static Supplier<? extends IllegalStateException> illegalStateException(String str, Object... args) {
return () -> new IllegalStateException(String.format(str, args));
}
}
| 7,931 | 43.066667 | 154 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/IssueLifecycle.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import java.util.Date;
import java.util.Optional;
import javax.inject.Inject;
import org.sonar.api.issue.Issue;
import org.sonar.api.rules.RuleType;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.DefaultIssueComment;
import org.sonar.core.issue.FieldDiffs;
import org.sonar.core.issue.IssueChangeContext;
import org.sonar.core.util.Uuids;
import org.sonar.db.component.BranchType;
import org.sonar.server.issue.IssueFieldsSetter;
import org.sonar.server.issue.workflow.IssueWorkflow;
import static java.util.Objects.requireNonNull;
import static org.sonar.core.issue.IssueChangeContext.issueChangeContextByScanBuilder;
/**
* Sets the appropriate fields when an issue is :
* <ul>
* <li>newly created</li>
* <li>merged the related base issue</li>
* <li>relocated (only manual issues)</li>
* </ul>
*/
public class IssueLifecycle {
private final IssueWorkflow workflow;
private final IssueChangeContext changeContext;
private final RuleRepository ruleRepository;
private final IssueFieldsSetter updater;
private final DebtCalculator debtCalculator;
private final AnalysisMetadataHolder analysisMetadataHolder;
@Inject
public IssueLifecycle(AnalysisMetadataHolder analysisMetadataHolder, IssueWorkflow workflow, IssueFieldsSetter updater, DebtCalculator debtCalculator,
RuleRepository ruleRepository) {
this(analysisMetadataHolder, issueChangeContextByScanBuilder(new Date(analysisMetadataHolder.getAnalysisDate())).build(), workflow, updater, debtCalculator, ruleRepository);
}
@VisibleForTesting
IssueLifecycle(AnalysisMetadataHolder analysisMetadataHolder, IssueChangeContext changeContext, IssueWorkflow workflow, IssueFieldsSetter updater,
DebtCalculator debtCalculator, RuleRepository ruleRepository) {
this.analysisMetadataHolder = analysisMetadataHolder;
this.workflow = workflow;
this.updater = updater;
this.debtCalculator = debtCalculator;
this.changeContext = changeContext;
this.ruleRepository = ruleRepository;
}
public void initNewOpenIssue(DefaultIssue issue) {
Preconditions.checkArgument(issue.isFromExternalRuleEngine() != (issue.type() == null), "At this stage issue type should be set for and only for external issues");
Rule rule = ruleRepository.getByKey(issue.ruleKey());
issue.setKey(Uuids.create());
issue.setCreationDate(changeContext.date());
issue.setUpdateDate(changeContext.date());
issue.setEffort(debtCalculator.calculate(issue));
setType(issue, rule);
setStatus(issue, rule);
}
private static void setType(DefaultIssue issue, Rule rule) {
if (issue.isFromExternalRuleEngine()) {
return;
}
issue.setType(requireNonNull(rule.getType(), "No rule type"));
}
private static void setStatus(DefaultIssue issue, Rule rule) {
if (rule.getType() == RuleType.SECURITY_HOTSPOT || issue.type() == RuleType.SECURITY_HOTSPOT) {
issue.setStatus(Issue.STATUS_TO_REVIEW);
} else {
issue.setStatus(Issue.STATUS_OPEN);
}
}
public void copyExistingOpenIssueFromBranch(DefaultIssue raw, DefaultIssue base, String branchName) {
raw.setKey(Uuids.create());
raw.setNew(false);
copyAttributesOfIssueFromAnotherBranch(raw, base);
raw.setFieldChange(changeContext, IssueFieldsSetter.FROM_BRANCH, branchName, analysisMetadataHolder.getBranch().getName());
}
public void mergeConfirmedOrResolvedFromPrOrBranch(DefaultIssue raw, DefaultIssue base, BranchType branchType, String prOrBranchKey) {
copyAttributesOfIssueFromAnotherBranch(raw, base);
String from = (branchType == BranchType.PULL_REQUEST) ? "#" + prOrBranchKey : prOrBranchKey;
String to = analysisMetadataHolder.isPullRequest() ? ("#" + analysisMetadataHolder.getPullRequestKey()) : analysisMetadataHolder.getBranch().getName();
raw.setFieldChange(changeContext, IssueFieldsSetter.FROM_BRANCH, from, to);
}
public void copyExistingIssueFromSourceBranchToPullRequest(DefaultIssue raw, DefaultIssue base) {
Preconditions.checkState(analysisMetadataHolder.isPullRequest(), "This operation should be done only on pull request analysis");
copyAttributesOfIssueFromAnotherBranch(raw, base);
String from = analysisMetadataHolder.getBranch().getName();
String to = "#" + analysisMetadataHolder.getPullRequestKey();
raw.setFieldChange(changeContext, IssueFieldsSetter.FROM_BRANCH, from, to);
}
public void copyAttributesOfIssueFromAnotherBranch(DefaultIssue to, DefaultIssue from) {
to.setCopied(true);
copyFields(to, from);
if (from.manualSeverity()) {
to.setManualSeverity(true);
to.setSeverity(from.severity());
}
copyChangesOfIssueFromOtherBranch(to, from);
}
private static void copyChangesOfIssueFromOtherBranch(DefaultIssue raw, DefaultIssue base) {
base.defaultIssueComments().forEach(c -> raw.addComment(copyComment(raw.key(), c)));
base.changes().forEach(c -> copyFieldDiffOfIssueFromOtherBranch(raw.key(), c).ifPresent(raw::addChange));
}
/**
* Copy a comment from another issue
*/
private static DefaultIssueComment copyComment(String issueKey, DefaultIssueComment c) {
DefaultIssueComment comment = new DefaultIssueComment();
comment.setIssueKey(issueKey);
comment.setKey(Uuids.create());
comment.setUserUuid(c.userUuid());
comment.setMarkdownText(c.markdownText());
comment.setCreatedAt(c.createdAt()).setUpdatedAt(c.updatedAt());
comment.setNew(true);
return comment;
}
/**
* Copy a diff from another issue
*/
private static Optional<FieldDiffs> copyFieldDiffOfIssueFromOtherBranch(String issueKey, FieldDiffs source) {
FieldDiffs result = new FieldDiffs();
result.setIssueKey(issueKey);
source.userUuid().ifPresent(result::setUserUuid);
source.webhookSource().ifPresent(result::setWebhookSource);
source.externalUser().ifPresent(result::setExternalUser);
result.setCreationDate(source.creationDate());
// Don't copy "file" changelogs as they refer to file uuids that might later be purged
source.diffs().entrySet().stream()
.filter(e -> !e.getKey().equals(IssueFieldsSetter.FILE))
.forEach(e -> result.setDiff(e.getKey(), e.getValue().oldValue(), e.getValue().newValue()));
if (result.diffs().isEmpty()) {
return Optional.empty();
}
return Optional.of(result);
}
public void mergeExistingOpenIssue(DefaultIssue raw, DefaultIssue base) {
Preconditions.checkArgument(raw.isFromExternalRuleEngine() != (raw.type() == null), "At this stage issue type should be set for and only for external issues");
Rule rule = ruleRepository.getByKey(raw.ruleKey());
raw.setKey(base.key());
raw.setNew(false);
if (base.isChanged()) {
// In case issue was moved from module or folder to the root project
raw.setChanged(true);
}
setType(raw, rule);
copyFields(raw, base);
base.changes().forEach(raw::addChange);
if (base.manualSeverity()) {
raw.setManualSeverity(true);
raw.setSeverity(base.severity());
} else {
updater.setPastSeverity(raw, base.severity(), changeContext);
}
// set component/module related fields from base in case current component has been moved
// (in which case base issue belongs to original file and raw issue to component)
raw.setComponentUuid(base.componentUuid());
raw.setComponentKey(base.componentKey());
// fields coming from raw
updater.setPastLine(raw, base.getLine());
updater.setPastLocations(raw, base.getLocations());
updater.setRuleDescriptionContextKey(raw, base.getRuleDescriptionContextKey().orElse(null));
updater.setPastMessage(raw, base.getMessage(), base.getMessageFormattings(), changeContext);
updater.setPastGap(raw, base.gap(), changeContext);
updater.setPastEffort(raw, base.effort(), changeContext);
updater.setCodeVariants(raw, requireNonNull(base.codeVariants()), changeContext);
}
public void doAutomaticTransition(DefaultIssue issue) {
workflow.doAutomaticTransition(issue, changeContext);
}
private void copyFields(DefaultIssue toIssue, DefaultIssue fromIssue) {
toIssue.setType(fromIssue.type());
toIssue.setCreationDate(fromIssue.creationDate());
toIssue.setUpdateDate(fromIssue.updateDate());
toIssue.setCloseDate(fromIssue.closeDate());
toIssue.setResolution(fromIssue.resolution());
toIssue.setStatus(fromIssue.status());
toIssue.setAssigneeUuid(fromIssue.assignee());
toIssue.setAssigneeLogin(fromIssue.assigneeLogin());
toIssue.setAuthorLogin(fromIssue.authorLogin());
toIssue.setTags(fromIssue.tags());
toIssue.setEffort(debtCalculator.calculate(toIssue));
toIssue.setOnDisabledRule(fromIssue.isOnDisabledRule());
toIssue.setSelectedAt(fromIssue.selectedAt());
toIssue.setIsNewCodeReferenceIssue(fromIssue.isNewCodeReferenceIssue());
}
}
| 9,941 | 42.605263 | 177 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/IssueLocations.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.util.Objects;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.apache.commons.lang.StringUtils;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.db.protobuf.DbCommons;
import org.sonar.db.protobuf.DbIssues;
public class IssueLocations {
private IssueLocations() {
// do not instantiate
}
/**
* Extract the lines of all the locations in the specified component. All the flows and secondary locations
* are taken into account. The lines present in multiple flows and locations are kept
* duplicated. Ordering of results is not guaranteed.
* <p>
* TODO should be a method of DefaultIssue, as soon as it's no
* longer in sonar-core and can access sonar-db-dao.
*/
public static IntStream allLinesFor(DefaultIssue issue, String componentUuid) {
DbIssues.Locations locations = issue.getLocations();
if (locations == null) {
return IntStream.empty();
}
Stream<DbCommons.TextRange> textRanges = Stream.concat(
locations.hasTextRange() ? Stream.of(locations.getTextRange()) : Stream.empty(),
locations.getFlowList().stream()
.flatMap(f -> f.getLocationList().stream())
.filter(l -> Objects.equals(componentIdOf(issue, l), componentUuid))
.map(DbIssues.Location::getTextRange));
return textRanges.flatMapToInt(range -> IntStream.rangeClosed(range.getStartLine(), range.getEndLine()));
}
private static String componentIdOf(DefaultIssue issue, DbIssues.Location location) {
if (location.hasComponentId()) {
return StringUtils.defaultIfEmpty(location.getComponentId(), issue.componentUuid());
}
return issue.componentUuid();
}
}
| 2,585 | 38.181818 | 109 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/IssueOnReferenceBranchVisitor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.core.issue.DefaultIssue;
public class IssueOnReferenceBranchVisitor extends IssueVisitor {
private final NewIssueClassifier newIssueClassifier;
public IssueOnReferenceBranchVisitor(NewIssueClassifier newIssueClassifier) {
this.newIssueClassifier = newIssueClassifier;
}
@Override
public void onIssue(Component component, DefaultIssue issue) {
if (!newIssueClassifier.isEnabled()) {
return;
}
if (newIssueClassifier.isOnBranchUsingReferenceBranch()) {
issue.setIsOnChangedLine(newIssueClassifier.hasAtLeastOneLocationOnChangedLines(component, issue));
if (issue.isNewCodeReferenceIssue() && !issue.isOnChangedLine()) {
issue.setIsNoLongerNewCodeReferenceIssue(true);
issue.setIsNewCodeReferenceIssue(false);
}
}
}
}
| 1,766 | 34.34 | 105 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/IssueTrackingDelegator.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.tracking.Input;
import org.sonar.core.issue.tracking.Tracking;
import static java.util.Collections.emptyMap;
import static java.util.stream.Stream.empty;
public class IssueTrackingDelegator {
private final PullRequestTrackerExecution pullRequestTracker;
private final TrackerExecution tracker;
private final AnalysisMetadataHolder analysisMetadataHolder;
private final ReferenceBranchTrackerExecution referenceBranchTracker;
public IssueTrackingDelegator(PullRequestTrackerExecution pullRequestTracker, ReferenceBranchTrackerExecution referenceBranchTracker,
TrackerExecution tracker, AnalysisMetadataHolder analysisMetadataHolder) {
this.pullRequestTracker = pullRequestTracker;
this.referenceBranchTracker = referenceBranchTracker;
this.tracker = tracker;
this.analysisMetadataHolder = analysisMetadataHolder;
}
public TrackingResult track(Component component, Input<DefaultIssue> rawInput) {
if (analysisMetadataHolder.isPullRequest()) {
return standardResult(pullRequestTracker.track(component, rawInput));
}
if (isFirstAnalysisSecondaryBranch()) {
Tracking<DefaultIssue, DefaultIssue> tracking = referenceBranchTracker.track(component, rawInput);
return new TrackingResult(tracking.getMatchedRaws(), emptyMap(), empty(), tracking.getUnmatchedRaws());
}
return standardResult(tracker.track(component, rawInput));
}
private static TrackingResult standardResult(Tracking<DefaultIssue, DefaultIssue> tracking) {
return new TrackingResult(emptyMap(), tracking.getMatchedRaws(), tracking.getUnmatchedBases(), tracking.getUnmatchedRaws());
}
/**
* Special case where we want to do the issue tracking with the reference branch, and copy matched issue to the current branch.
*/
private boolean isFirstAnalysisSecondaryBranch() {
if (analysisMetadataHolder.isFirstAnalysis()) {
return !analysisMetadataHolder.getBranch().isMain();
}
return false;
}
}
| 3,065 | 41.583333 | 135 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/IssueVisitor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.core.issue.DefaultIssue;
public abstract class IssueVisitor {
/**
* This method is called for each component before processing its issues.
* The component does not necessarily have issues.
*/
public void beforeComponent(Component component) {
}
/**
* This method is called for each issue of a component when tracking is done and issue is initialized.
* That means that the following fields are set: resolution, status, line, creation date, uuid
* and all the fields merged from base issues.
* <br/>
* The related rule is active in the Quality profile. Issues on inactive rules
* are ignored.
*/
public void onIssue(Component component, DefaultIssue issue) {
}
/**
* This method is called on a component before issues are persisted to cache.
*/
public void beforeCaching(Component component) {
}
public void afterComponent(Component component) {
}
}
| 1,888 | 31.568966 | 104 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/IssueVisitors.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.core.issue.DefaultIssue;
public class IssueVisitors {
private final IssueVisitor[] visitors;
public IssueVisitors(IssueVisitor[] visitors) {
this.visitors = visitors;
}
public void beforeComponent(Component component) {
for (IssueVisitor visitor : visitors) {
visitor.beforeComponent(component);
}
}
public void onIssue(Component component, DefaultIssue issue) {
for (IssueVisitor visitor : visitors) {
visitor.onIssue(component, issue);
}
}
public void afterComponent(Component component) {
for (IssueVisitor visitor : visitors) {
visitor.afterComponent(component);
}
}
public void beforeCaching(Component component) {
for (IssueVisitor visitor : visitors) {
visitor.beforeCaching(component);
}
}
}
| 1,761 | 29.912281 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/IssuesRepositoryVisitor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.util.ArrayList;
import java.util.List;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.core.issue.DefaultIssue;
/**
* Saves issues in the ComponentIssuesRepository
* The repository should only hold the issues for a single component, so we use a mutable list
*/
public class IssuesRepositoryVisitor extends IssueVisitor {
private final MutableComponentIssuesRepository componentIssuesRepository;
private final List<DefaultIssue> componentIssues = new ArrayList<>();
public IssuesRepositoryVisitor(MutableComponentIssuesRepository componentIssuesRepository) {
this.componentIssuesRepository = componentIssuesRepository;
}
@Override
public void beforeComponent(Component component) {
componentIssues.clear();
}
@Override
public void onIssue(Component component, DefaultIssue issue) {
componentIssues.add(issue);
}
@Override
public void afterComponent(Component component) {
componentIssuesRepository.setIssues(component, componentIssues);
}
}
| 1,926 | 34.685185 | 94 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/LoadComponentUuidsHavingOpenIssuesVisitor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit;
import org.sonar.ce.task.projectanalysis.component.TypeAwareVisitorAdapter;
import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.PRE_ORDER;
/**
* Load all open components having open issues of the project
*/
public class LoadComponentUuidsHavingOpenIssuesVisitor extends TypeAwareVisitorAdapter {
private final BaseIssuesLoader baseIssuesLoader;
private final ComponentsWithUnprocessedIssues componentsWithUnprocessedIssues;
public LoadComponentUuidsHavingOpenIssuesVisitor(BaseIssuesLoader baseIssuesLoader, ComponentsWithUnprocessedIssues componentsWithUnprocessedIssues) {
super(CrawlerDepthLimit.PROJECT, PRE_ORDER);
this.baseIssuesLoader = baseIssuesLoader;
this.componentsWithUnprocessedIssues = componentsWithUnprocessedIssues;
}
@Override
public void visitProject(Component project) {
componentsWithUnprocessedIssues.setUuids(baseIssuesLoader.loadUuidsOfComponentsWithOpenIssues());
}
}
| 1,985 | 41.255319 | 152 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/MovedIssueVisitor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.util.Date;
import java.util.Optional;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.filemove.MovedFilesRepository;
import org.sonar.ce.task.projectanalysis.filemove.MovedFilesRepository.OriginalFile;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.server.issue.IssueFieldsSetter;
import static com.google.common.base.Preconditions.checkState;
public class MovedIssueVisitor extends IssueVisitor {
private final AnalysisMetadataHolder analysisMetadataHolder;
private final MovedFilesRepository movedFilesRepository;
private final IssueFieldsSetter issueUpdater;
public MovedIssueVisitor(AnalysisMetadataHolder analysisMetadataHolder, MovedFilesRepository movedFilesRepository, IssueFieldsSetter issueUpdater) {
this.analysisMetadataHolder = analysisMetadataHolder;
this.movedFilesRepository = movedFilesRepository;
this.issueUpdater = issueUpdater;
}
@Override
public void onIssue(Component component, DefaultIssue issue) {
if (component.getType() != Component.Type.FILE || component.getUuid().equals(issue.componentUuid())) {
return;
}
Optional<OriginalFile> originalFileOptional = movedFilesRepository.getOriginalFile(component);
checkState(originalFileOptional.isPresent(),
"Issue %s for component %s has a different component key but no original file exist in MovedFilesRepository",
issue, component);
OriginalFile originalFile = originalFileOptional.get();
String fileUuid = originalFile.uuid();
checkState(fileUuid.equals(issue.componentUuid()),
"Issue %s doesn't belong to file %s registered as original file of current file %s",
issue, fileUuid, component);
// changes the issue's component uuid, and set issue as changed, to enforce it is persisted to DB
issueUpdater.setIssueComponent(issue, component.getUuid(), component.getKey(), new Date(analysisMetadataHolder.getAnalysisDate()));
}
}
| 2,945 | 45.761905 | 150 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/MutableComponentIssuesRepository.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.util.List;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.core.issue.DefaultIssue;
public interface MutableComponentIssuesRepository extends ComponentIssuesRepository {
/**
* Add issues of the component.
* *
* @throws NullPointerException if {@code component} is {@code null}
* @throws NullPointerException if {@code issues} is {@code null}
*/
void setIssues(Component component, List<DefaultIssue> issues);
}
| 1,372 | 36.108108 | 85 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/NewAdHocRule.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import com.google.common.base.Preconditions;
import java.util.Objects;
import javax.annotation.CheckForNull;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rules.RuleType;
import org.sonar.scanner.protocol.Constants;
import org.sonar.scanner.protocol.output.ScannerReport;
import static org.apache.commons.lang.StringUtils.isNotBlank;
import static org.apache.commons.lang.StringUtils.trimToNull;
@Immutable
public class NewAdHocRule {
private final RuleKey key;
private final String engineId;
private final String ruleId;
private final String name;
private final String description;
private final String severity;
private final RuleType ruleType;
private final boolean hasDetails;
public NewAdHocRule(ScannerReport.AdHocRule ruleFromScannerReport) {
Preconditions.checkArgument(isNotBlank(ruleFromScannerReport.getEngineId()), "'engine id' not expected to be null for an ad hoc rule");
Preconditions.checkArgument(isNotBlank(ruleFromScannerReport.getRuleId()), "'rule id' not expected to be null for an ad hoc rule");
Preconditions.checkArgument(isNotBlank(ruleFromScannerReport.getName()), "'name' not expected to be null for an ad hoc rule");
Preconditions.checkArgument(ruleFromScannerReport.getSeverity() != Constants.Severity.UNSET_SEVERITY , "'severity' not expected to be null for an ad hoc rule");
Preconditions.checkArgument(ruleFromScannerReport.getType() != ScannerReport.IssueType.UNSET, "'issue type' not expected to be null for an ad hoc rule");
this.key = RuleKey.of(RuleKey.EXTERNAL_RULE_REPO_PREFIX + ruleFromScannerReport.getEngineId(), ruleFromScannerReport.getRuleId());
this.engineId = ruleFromScannerReport.getEngineId();
this.ruleId = ruleFromScannerReport.getRuleId();
this.name = ruleFromScannerReport.getName();
this.description = trimToNull(ruleFromScannerReport.getDescription());
this.severity = ruleFromScannerReport.getSeverity().name();
this.ruleType = RuleType.valueOf(ruleFromScannerReport.getType().name());
this.hasDetails = true;
}
public NewAdHocRule(ScannerReport.ExternalIssue fromIssue) {
Preconditions.checkArgument(isNotBlank(fromIssue.getEngineId()), "'engine id' not expected to be null for an ad hoc rule");
Preconditions.checkArgument(isNotBlank(fromIssue.getRuleId()), "'rule id' not expected to be null for an ad hoc rule");
this.key = RuleKey.of(RuleKey.EXTERNAL_RULE_REPO_PREFIX + fromIssue.getEngineId(), fromIssue.getRuleId());
this.engineId = fromIssue.getEngineId();
this.ruleId = fromIssue.getRuleId();
this.name = null;
this.description = null;
this.severity = null;
this.ruleType = null;
this.hasDetails = false;
}
public RuleKey getKey() {
return key;
}
public String getEngineId() {
return engineId;
}
public String getRuleId() {
return ruleId;
}
@CheckForNull
public String getName() {
return name;
}
@CheckForNull
public String getDescription() {
return description;
}
@CheckForNull
public String getSeverity() {
return severity;
}
@CheckForNull
public RuleType getRuleType() {
return ruleType;
}
public boolean hasDetails() {
return hasDetails;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
NewAdHocRule that = (NewAdHocRule) o;
return Objects.equals(key, that.key);
}
@Override
public int hashCode() {
return key.hashCode();
}
}
| 4,493 | 33.837209 | 164 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/NewEffortAggregator.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import com.google.common.base.MoreObjects;
import java.util.HashMap;
import java.util.Map;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.ce.task.projectanalysis.component.Component;
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.core.issue.DefaultIssue;
import static org.sonar.api.measures.CoreMetrics.NEW_RELIABILITY_REMEDIATION_EFFORT_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_REMEDIATION_EFFORT_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_TECHNICAL_DEBT_KEY;
/**
* Compute new effort related measures :
* {@link CoreMetrics#NEW_TECHNICAL_DEBT_KEY}
* {@link CoreMetrics#NEW_RELIABILITY_REMEDIATION_EFFORT_KEY}
* {@link CoreMetrics#NEW_SECURITY_REMEDIATION_EFFORT_KEY}
*/
public class NewEffortAggregator extends IssueVisitor {
private final Map<String, NewEffortCounter> counterByComponentUuid = new HashMap<>();
private final MeasureRepository measureRepository;
private final Metric newMaintainabilityEffortMetric;
private final Metric newReliabilityEffortMetric;
private final Metric newSecurityEffortMetric;
private final NewIssueClassifier newIssueClassifier;
private NewEffortCounter counter = null;
public NewEffortAggregator(MetricRepository metricRepository, MeasureRepository measureRepository, NewIssueClassifier newIssueClassifier) {
this.measureRepository = measureRepository;
this.newMaintainabilityEffortMetric = metricRepository.getByKey(NEW_TECHNICAL_DEBT_KEY);
this.newReliabilityEffortMetric = metricRepository.getByKey(NEW_RELIABILITY_REMEDIATION_EFFORT_KEY);
this.newSecurityEffortMetric = metricRepository.getByKey(NEW_SECURITY_REMEDIATION_EFFORT_KEY);
this.newIssueClassifier = newIssueClassifier;
}
@Override
public void beforeComponent(Component component) {
counter = new NewEffortCounter();
counterByComponentUuid.put(component.getUuid(), counter);
for (Component child : component.getChildren()) {
NewEffortCounter childSum = counterByComponentUuid.remove(child.getUuid());
if (childSum != null) {
counter.add(childSum);
}
}
}
@Override
public void onIssue(Component component, DefaultIssue issue) {
if (issue.resolution() == null && issue.effortInMinutes() != null) {
counter.add(component, issue);
}
}
@Override
public void afterComponent(Component component) {
if (newIssueClassifier.isEnabled()) {
computeMeasure(component, newMaintainabilityEffortMetric, counter.maintainabilitySum);
computeMeasure(component, newReliabilityEffortMetric, counter.reliabilitySum);
computeMeasure(component, newSecurityEffortMetric, counter.securitySum);
}
counter = null;
}
private void computeMeasure(Component component, Metric metric, EffortSum effortSum) {
long value = effortSum.isEmpty ? 0 : effortSum.newEffort;
measureRepository.add(component, metric, Measure.newMeasureBuilder().create(value));
}
private class NewEffortCounter {
private final EffortSum maintainabilitySum = new EffortSum();
private final EffortSum reliabilitySum = new EffortSum();
private final EffortSum securitySum = new EffortSum();
void add(NewEffortCounter otherCounter) {
maintainabilitySum.add(otherCounter.maintainabilitySum);
reliabilitySum.add(otherCounter.reliabilitySum);
securitySum.add(otherCounter.securitySum);
}
void add(Component component, DefaultIssue issue) {
long newEffort = calculate(component, issue);
switch (issue.type()) {
case CODE_SMELL:
maintainabilitySum.add(newEffort);
break;
case BUG:
reliabilitySum.add(newEffort);
break;
case VULNERABILITY:
securitySum.add(newEffort);
break;
case SECURITY_HOTSPOT:
// Not counted
break;
default:
throw new IllegalStateException(String.format("Unknown type '%s'", issue.type()));
}
}
long calculate(Component component, DefaultIssue issue) {
if (newIssueClassifier.isNew(component, issue)) {
return MoreObjects.firstNonNull(issue.effortInMinutes(), 0L);
}
return 0L;
}
}
private static class EffortSum {
private Long newEffort;
private boolean isEmpty = true;
void add(long newEffort) {
long previous = MoreObjects.firstNonNull(this.newEffort, 0L);
this.newEffort = previous + newEffort;
isEmpty = false;
}
void add(EffortSum other) {
Long otherValue = other.newEffort;
if (otherValue != null) {
add(otherValue);
}
}
}
}
| 5,732 | 35.987097 | 141 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/NewIssueClassifier.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
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.period.PeriodHolder;
import org.sonar.ce.task.projectanalysis.source.NewLinesRepository;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.db.newcodeperiod.NewCodePeriodType;
public class NewIssueClassifier {
private final NewLinesRepository newLinesRepository;
private final PeriodHolder periodHolder;
private final AnalysisMetadataHolder analysisMetadataHolder;
public NewIssueClassifier(NewLinesRepository newLinesRepository, PeriodHolder periodHolder, AnalysisMetadataHolder analysisMetadataHolder) {
this.newLinesRepository = newLinesRepository;
this.periodHolder = periodHolder;
this.analysisMetadataHolder = analysisMetadataHolder;
}
public boolean isEnabled() {
return analysisMetadataHolder.isPullRequest() || periodHolder.hasPeriodDate() ||
(periodHolder.hasPeriod() && isOnBranchUsingReferenceBranch());
}
public boolean isNew(Component component, DefaultIssue issue) {
if (analysisMetadataHolder.isPullRequest()) {
return true;
}
if (periodHolder.hasPeriod()) {
if (periodHolder.hasPeriodDate()) {
return periodHolder.getPeriod().isOnPeriod(issue.creationDate());
}
if (isOnBranchUsingReferenceBranch()) {
return hasAtLeastOneLocationOnChangedLines(component, issue);
}
}
return false;
}
public boolean isOnBranchUsingReferenceBranch() {
if (periodHolder.hasPeriod()) {
return periodHolder.getPeriod().getMode().equals(NewCodePeriodType.REFERENCE_BRANCH.name());
}
return false;
}
public boolean hasAtLeastOneLocationOnChangedLines(Component component, DefaultIssue issue) {
if (component.getType() != Component.Type.FILE) {
return false;
}
final Optional<Set<Integer>> newLinesOpt = newLinesRepository.getNewLines(component);
if (newLinesOpt.isEmpty()) {
return false;
}
Set<Integer> newLines = newLinesOpt.get();
return IssueLocations.allLinesFor(issue, component.getUuid()).anyMatch(newLines::contains);
}
}
| 3,132 | 36.297619 | 142 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/ProjectTrackerBaseLazyInput.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.util.List;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.db.DbClient;
class ProjectTrackerBaseLazyInput extends BaseInputFactory.BaseLazyInput {
private final ComponentIssuesLoader issuesLoader;
ProjectTrackerBaseLazyInput(DbClient dbClient, ComponentIssuesLoader issuesLoader, Component component) {
super(dbClient, component, null);
this.issuesLoader = issuesLoader;
}
@Override
protected List<DefaultIssue> loadIssues() {
return issuesLoader.loadOpenIssues(effectiveUuid);
}
}
| 1,487 | 36.2 | 107 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/ProtoIssueCache.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import org.sonar.api.utils.System2;
import org.sonar.api.utils.TempFolder;
import org.sonar.ce.task.projectanalysis.util.cache.ProtobufIssueDiskCache;
import javax.inject.Inject;
import java.io.File;
/**
* Cache of all the issues involved in the analysis. Their state is as it will be
* persisted in database (after issue tracking, auto-assignment, ...)
*/
public class ProtoIssueCache extends ProtobufIssueDiskCache {
@Inject
public ProtoIssueCache(TempFolder tempFolder, System2 system2) {
super(tempFolder.newFile("issues", ".dat"), system2);
}
public ProtoIssueCache(File file, System2 system2) {
super(file, system2);
}
}
| 1,544 | 34.930233 | 81 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/PullRequestSourceBranchMerger.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.util.Collection;
import java.util.Map;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.tracking.Input;
import org.sonar.core.issue.tracking.Tracker;
import org.sonar.core.issue.tracking.Tracking;
public class PullRequestSourceBranchMerger {
private final Tracker<DefaultIssue, DefaultIssue> tracker;
private final IssueLifecycle issueLifecycle;
private final TrackerSourceBranchInputFactory sourceBranchInputFactory;
public PullRequestSourceBranchMerger(Tracker<DefaultIssue, DefaultIssue> tracker, IssueLifecycle issueLifecycle, TrackerSourceBranchInputFactory sourceBranchInputFactory) {
this.tracker = tracker;
this.issueLifecycle = issueLifecycle;
this.sourceBranchInputFactory = sourceBranchInputFactory;
}
public void tryMergeIssuesFromSourceBranchOfPullRequest(Component component, Collection<DefaultIssue> newIssues, Input<DefaultIssue> rawInput) {
if (sourceBranchInputFactory.hasSourceBranchAnalysis()) {
Input<DefaultIssue> sourceBranchInput = sourceBranchInputFactory.createForSourceBranch(component);
DefaultTrackingInput rawPrTrackingInput = new DefaultTrackingInput(newIssues, rawInput.getLineHashSequence(), rawInput.getBlockHashSequence());
Tracking<DefaultIssue, DefaultIssue> prTracking = tracker.trackNonClosed(rawPrTrackingInput, sourceBranchInput);
for (Map.Entry<DefaultIssue, DefaultIssue> pair : prTracking.getMatchedRaws().entrySet()) {
issueLifecycle.copyExistingIssueFromSourceBranchToPullRequest(pair.getKey(), pair.getValue());
}
}
}
}
| 2,530 | 47.673077 | 174 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/PullRequestTrackerExecution.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.sonar.api.issue.Issue;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.source.NewLinesRepository;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.tracking.Input;
import org.sonar.core.issue.tracking.Tracker;
import org.sonar.core.issue.tracking.Tracking;
public class PullRequestTrackerExecution {
private final TrackerBaseInputFactory baseInputFactory;
private final Tracker<DefaultIssue, DefaultIssue> tracker;
private final NewLinesRepository newLinesRepository;
private final TrackerTargetBranchInputFactory targetInputFactory;
public PullRequestTrackerExecution(TrackerBaseInputFactory baseInputFactory, TrackerTargetBranchInputFactory targetInputFactory,
Tracker<DefaultIssue, DefaultIssue> tracker, NewLinesRepository newLinesRepository) {
this.baseInputFactory = baseInputFactory;
this.targetInputFactory = targetInputFactory;
this.tracker = tracker;
this.newLinesRepository = newLinesRepository;
}
public Tracking<DefaultIssue, DefaultIssue> track(Component component, Input<DefaultIssue> rawInput) {
// Step 1: only keep issues on changed lines
List<DefaultIssue> filteredRaws = keepIssuesHavingAtLeastOneLocationOnChangedLines(component, rawInput.getIssues());
Input<DefaultIssue> unmatchedRawsAfterChangedLineFiltering = createInput(rawInput, filteredRaws);
// Step 2: remove issues that are resolved in the target branch
Input<DefaultIssue> unmatchedRawsAfterTargetResolvedTracking;
if (targetInputFactory.hasTargetBranchAnalysis()) {
Input<DefaultIssue> targetInput = targetInputFactory.createForTargetBranch(component);
List<DefaultIssue> resolvedTargetIssues = targetInput.getIssues().stream().filter(i -> Issue.STATUS_RESOLVED.equals(i.status())).toList();
Input<DefaultIssue> resolvedTargetInput = createInput(targetInput, resolvedTargetIssues);
Tracking<DefaultIssue, DefaultIssue> prResolvedTracking = tracker.trackNonClosed(unmatchedRawsAfterChangedLineFiltering, resolvedTargetInput);
unmatchedRawsAfterTargetResolvedTracking = createInput(rawInput, prResolvedTracking.getUnmatchedRaws().toList());
} else {
unmatchedRawsAfterTargetResolvedTracking = unmatchedRawsAfterChangedLineFiltering;
}
// Step 3: track issues with previous analysis of the current PR
Input<DefaultIssue> previousAnalysisInput = baseInputFactory.create(component);
return tracker.trackNonClosed(unmatchedRawsAfterTargetResolvedTracking, previousAnalysisInput);
}
private static Input<DefaultIssue> createInput(Input<DefaultIssue> input, Collection<DefaultIssue> issues) {
return new DefaultTrackingInput(issues, input.getLineHashSequence(), input.getBlockHashSequence());
}
private List<DefaultIssue> keepIssuesHavingAtLeastOneLocationOnChangedLines(Component component, Collection<DefaultIssue> issues) {
if (component.getType() != Component.Type.FILE) {
return Collections.emptyList();
}
final Optional<Set<Integer>> newLinesOpt = newLinesRepository.getNewLines(component);
if (!newLinesOpt.isPresent()) {
return Collections.emptyList();
}
final Set<Integer> newLines = newLinesOpt.get();
return issues.stream()
.filter(i -> IssueLocations.allLinesFor(i, component.getUuid()).anyMatch(newLines::contains))
.toList();
}
}
| 4,418 | 48.1 | 148 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/ReferenceBranchTrackerExecution.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.tracking.Input;
import org.sonar.core.issue.tracking.Tracker;
import org.sonar.core.issue.tracking.Tracking;
public class ReferenceBranchTrackerExecution {
private final TrackerReferenceBranchInputFactory referenceBranchInputFactory;
private final Tracker<DefaultIssue, DefaultIssue> tracker;
public ReferenceBranchTrackerExecution(TrackerReferenceBranchInputFactory referenceBranchInputFactory, Tracker<DefaultIssue, DefaultIssue> tracker) {
this.referenceBranchInputFactory = referenceBranchInputFactory;
this.tracker = tracker;
}
public Tracking<DefaultIssue, DefaultIssue> track(Component component, Input<DefaultIssue> rawInput) {
return tracker.trackNonClosed(rawInput, referenceBranchInputFactory.create(component));
}
}
| 1,780 | 42.439024 | 151 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/RemoveProcessedComponentsVisitor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.util.Optional;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.filemove.MovedFilesRepository;
public class RemoveProcessedComponentsVisitor extends IssueVisitor {
private final ComponentsWithUnprocessedIssues componentsWithUnprocessedIssues;
private final MovedFilesRepository movedFilesRepository;
public RemoveProcessedComponentsVisitor(ComponentsWithUnprocessedIssues componentsWithUnprocessedIssues, MovedFilesRepository movedFilesRepository) {
this.componentsWithUnprocessedIssues = componentsWithUnprocessedIssues;
this.movedFilesRepository = movedFilesRepository;
}
@Override
public void afterComponent(Component component) {
componentsWithUnprocessedIssues.remove(component.getUuid());
Optional<MovedFilesRepository.OriginalFile> originalFile = movedFilesRepository.getOriginalFile(component);
if (originalFile.isPresent()) {
componentsWithUnprocessedIssues.remove(originalFile.get().uuid());
}
}
}
| 1,914 | 42.522727 | 151 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/Rule.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.util.Set;
import javax.annotation.CheckForNull;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.rules.RuleType;
import org.sonar.api.server.debt.DebtRemediationFunction;
public interface Rule {
String getUuid();
RuleKey getKey();
String getName();
@CheckForNull
String getLanguage();
RuleStatus getStatus();
/**
* Will be null for external rules
*/
@CheckForNull
RuleType getType();
boolean isExternal();
boolean isAdHoc();
/**
* Get all tags, whatever system or user tags.
*/
Set<String> getTags();
@CheckForNull
DebtRemediationFunction getRemediationFunction();
@CheckForNull
String getPluginKey();
String getDefaultRuleDescription();
String getSeverity();
Set<String> getSecurityStandards();
}
| 1,714 | 24.220588 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/RuleImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import com.google.common.base.MoreObjects;
import java.util.Optional;
import java.util.Set;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.rules.RuleType;
import org.sonar.api.server.debt.DebtRemediationFunction;
import org.sonar.api.server.debt.internal.DefaultDebtRemediationFunction;
import org.sonar.db.rule.RuleDescriptionSectionDto;
import org.sonar.db.rule.RuleDto;
import static com.google.common.collect.Sets.union;
@Immutable
public class RuleImpl implements Rule {
private final String uuid;
private final RuleKey key;
private final String name;
private final String language;
private final RuleStatus status;
private final Set<String> tags;
private final DebtRemediationFunction remediationFunction;
private final RuleType type;
private final String pluginKey;
private final boolean isExternal;
private final boolean isAdHoc;
private final String defaultRuleDescription;
private final String severity;
private final Set<String> securityStandards;
public RuleImpl(RuleDto dto) {
this.uuid = dto.getUuid();
this.key = dto.getKey();
this.name = dto.getName();
this.language = dto.getLanguage();
this.status = dto.getStatus();
this.tags = union(dto.getSystemTags(), dto.getTags());
this.remediationFunction = effectiveRemediationFunction(dto);
this.type = RuleType.valueOfNullable(dto.getType());
this.pluginKey = dto.getPluginKey();
this.isExternal = dto.isExternal();
this.isAdHoc = dto.isAdHoc();
this.defaultRuleDescription = getNonNullDefaultRuleDescription(dto);
this.severity = Optional.ofNullable(dto.getSeverityString()).orElse(dto.getAdHocSeverity());
this.securityStandards = dto.getSecurityStandards();
}
private static String getNonNullDefaultRuleDescription(RuleDto dto) {
return Optional.ofNullable(dto.getDefaultRuleDescriptionSection())
.map(RuleDescriptionSectionDto::getContent)
.orElse("");
}
@Override
public String getUuid() {
return this.uuid;
}
@Override
public RuleKey getKey() {
return key;
}
@Override
public String getName() {
return name;
}
@Override
@CheckForNull
public String getLanguage() {
return language;
}
@Override
public RuleStatus getStatus() {
return status;
}
@Override
public Set<String> getTags() {
return tags;
}
@Override
public DebtRemediationFunction getRemediationFunction() {
return remediationFunction;
}
@Override
public RuleType getType() {
return type;
}
@CheckForNull
@Override
public String getPluginKey() {
return pluginKey;
}
public String getDefaultRuleDescription() {
return defaultRuleDescription;
}
@Override
public String getSeverity() {
return severity;
}
@Override
public Set<String> getSecurityStandards() {
return securityStandards;
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
RuleImpl rule = (RuleImpl) o;
return key.equals(rule.key);
}
@Override
public int hashCode() {
return key.hashCode();
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("uuid", uuid)
.add("key", key)
.add("name", name)
.add("language", language)
.add("status", status)
.add("tags", tags)
.add("pluginKey", pluginKey)
.toString();
}
@CheckForNull
private static DebtRemediationFunction effectiveRemediationFunction(RuleDto dto) {
String fn = dto.getRemediationFunction();
if (fn != null) {
return new DefaultDebtRemediationFunction(DebtRemediationFunction.Type.valueOf(fn), dto.getRemediationGapMultiplier(), dto.getRemediationBaseEffort());
}
String defaultFn = dto.getDefRemediationFunction();
if (defaultFn != null) {
return new DefaultDebtRemediationFunction(DebtRemediationFunction.Type.valueOf(defaultFn), dto.getDefRemediationGapMultiplier(), dto.getDefRemediationBaseEffort());
}
return null;
}
@Override
public boolean isAdHoc() {
return isAdHoc;
}
@Override
public boolean isExternal() {
return isExternal;
}
}
| 5,299 | 26.46114 | 170 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/RuleRepository.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.util.Optional;
import java.util.function.Supplier;
import org.sonar.api.rule.RuleKey;
import org.sonar.db.DbSession;
/**
* Repository of every rule in DB (including manual rules) whichever their status.
*/
public interface RuleRepository {
/**
* @throws NullPointerException if {@code key} is {@code null}
* @throws IllegalArgumentException when there is no Rule for the specified RuleKey in the repository
*/
Rule getByKey(RuleKey key);
/**
* @throws IllegalArgumentException when there is no Rule for the specified RuleKey in the repository
*/
Rule getByUuid(String uuid);
/**
* @throws NullPointerException if {@code key} is {@code null}
*/
Optional<Rule> findByKey(RuleKey key);
Optional<Rule> findByUuid(String uuid);
void addOrUpdateAddHocRuleIfNeeded(RuleKey ruleKey, Supplier<NewAdHocRule> ruleSupplier);
void saveOrUpdateAddHocRules(DbSession dbSession);
}
| 1,820 | 32.109091 | 103 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/RuleRepositoryImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import com.google.common.collect.Multimap;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Supplier;
import javax.annotation.CheckForNull;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.rules.RuleType;
import org.sonar.api.server.debt.DebtRemediationFunction;
import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.rule.DeprecatedRuleKeyDto;
import org.sonar.db.rule.RuleDto;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
public class RuleRepositoryImpl implements RuleRepository {
@CheckForNull
private Map<RuleKey, Rule> rulesByKey;
@CheckForNull
private Map<String, Rule> rulesByUuid;
private final AdHocRuleCreator creator;
private final DbClient dbClient;
private Map<RuleKey, NewAdHocRule> adHocRulesPersist = new HashMap<>();
public RuleRepositoryImpl(AdHocRuleCreator creator, DbClient dbClient) {
this.creator = creator;
this.dbClient = dbClient;
}
public void addOrUpdateAddHocRuleIfNeeded(RuleKey ruleKey, Supplier<NewAdHocRule> ruleSupplier) {
ensureInitialized();
Rule existingRule = rulesByKey.get(ruleKey);
if (existingRule == null || (existingRule.isAdHoc() && !adHocRulesPersist.containsKey(ruleKey))) {
NewAdHocRule newAdHocRule = ruleSupplier.get();
adHocRulesPersist.put(ruleKey, newAdHocRule);
rulesByKey.put(ruleKey, new AdHocRuleWrapper(newAdHocRule));
}
}
@Override
public void saveOrUpdateAddHocRules(DbSession dbSession) {
ensureInitialized();
adHocRulesPersist.values().forEach(r -> persistAndIndex(dbSession, r));
}
private void persistAndIndex(DbSession dbSession, NewAdHocRule adHocRule) {
Rule rule = new RuleImpl(creator.persistAndIndex(dbSession, adHocRule));
rulesByUuid.put(rule.getUuid(), rule);
rulesByKey.put(adHocRule.getKey(), rule);
}
@Override
public Rule getByKey(RuleKey key) {
verifyKeyArgument(key);
ensureInitialized();
Rule rule = rulesByKey.get(key);
checkArgument(rule != null, "Can not find rule for key %s. This rule does not exist in DB", key);
return rule;
}
@Override
public Optional<Rule> findByKey(RuleKey key) {
verifyKeyArgument(key);
ensureInitialized();
return Optional.ofNullable(rulesByKey.get(key));
}
@Override
public Rule getByUuid(String uuid) {
ensureInitialized();
Rule rule = rulesByUuid.get(uuid);
checkArgument(rule != null, "Can not find rule for uuid %s. This rule does not exist in DB", uuid);
return rule;
}
@Override
public Optional<Rule> findByUuid(String uuid) {
ensureInitialized();
return Optional.ofNullable(rulesByUuid.get(uuid));
}
private static void verifyKeyArgument(RuleKey key) {
requireNonNull(key, "RuleKey can not be null");
}
private void ensureInitialized() {
if (rulesByKey == null) {
try (DbSession dbSession = dbClient.openSession(false)) {
loadRulesFromDb(dbSession);
}
}
}
private void loadRulesFromDb(DbSession dbSession) {
this.rulesByKey = new HashMap<>();
this.rulesByUuid = new HashMap<>();
Multimap<String, DeprecatedRuleKeyDto> deprecatedRuleKeysByRuleUuid = dbClient.ruleDao().selectAllDeprecatedRuleKeys(dbSession).stream()
.collect(MoreCollectors.index(DeprecatedRuleKeyDto::getRuleUuid));
for (RuleDto ruleDto : dbClient.ruleDao().selectAll(dbSession)) {
Rule rule = new RuleImpl(ruleDto);
rulesByKey.put(ruleDto.getKey(), rule);
rulesByUuid.put(ruleDto.getUuid(), rule);
deprecatedRuleKeysByRuleUuid.get(ruleDto.getUuid()).forEach(t -> rulesByKey.put(RuleKey.of(t.getOldRepositoryKey(), t.getOldRuleKey()), rule));
}
}
private static class AdHocRuleWrapper implements Rule {
private final NewAdHocRule addHocRule;
private AdHocRuleWrapper(NewAdHocRule addHocRule) {
this.addHocRule = addHocRule;
}
public NewAdHocRule getDelegate() {
return addHocRule;
}
@Override
public String getUuid() {
throw new UnsupportedOperationException("Rule is not persisted, can't know the uuid");
}
@Override
public RuleKey getKey() {
return addHocRule.getKey();
}
@Override
public String getName() {
return addHocRule.getName();
}
@Override
@CheckForNull
public String getLanguage() {
return null;
}
@Override
public RuleStatus getStatus() {
return RuleStatus.defaultStatus();
}
@Override
@CheckForNull
public RuleType getType() {
return addHocRule.getRuleType();
}
@Override
public boolean isExternal() {
return true;
}
@Override
public boolean isAdHoc() {
return true;
}
@Override
public Set<String> getTags() {
return Collections.emptySet();
}
@CheckForNull
@Override
public DebtRemediationFunction getRemediationFunction() {
return null;
}
@CheckForNull
@Override
public String getPluginKey() {
return null;
}
@Override
public String getDefaultRuleDescription() {
return addHocRule.getDescription();
}
@Override
public String getSeverity() {
return addHocRule.getSeverity();
}
@Override
public Set<String> getSecurityStandards() {
return Collections.emptySet();
}
}
}
| 6,467 | 27 | 149 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/RuleTagsCopier.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.core.issue.DefaultIssue;
import static com.google.common.collect.Sets.union;
public class RuleTagsCopier extends IssueVisitor {
private final RuleRepository ruleRepository;
public RuleTagsCopier(RuleRepository ruleRepository) {
this.ruleRepository = ruleRepository;
}
@Override
public void onIssue(Component component, DefaultIssue issue) {
if (issue.isNew()) {
// analyzer can provide some tags. They must be merged with rule tags
Rule rule = ruleRepository.getByKey(issue.ruleKey());
issue.setTags(union(issue.tags(), rule.getTags()));
}
}
}
| 1,563 | 34.545455 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/ScmAccountToUser.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import org.sonar.ce.task.projectanalysis.util.cache.MemoryCache;
import org.sonar.db.user.UserIdDto;
/**
* Cache of dictionary {SCM account -> SQ user uuid and login}. Kept in memory
* during the execution of Compute Engine.
*/
public class ScmAccountToUser extends MemoryCache<String, UserIdDto> {
public ScmAccountToUser(ScmAccountToUserLoader loader) {
super(loader);
}
}
| 1,280 | 36.676471 | 78 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/ScmAccountToUserLoader.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import com.google.common.base.Joiner;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.ce.task.projectanalysis.util.cache.CacheLoader;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.user.UserIdDto;
/**
* Loads the association between a SCM account and a SQ user
*/
public class ScmAccountToUserLoader implements CacheLoader<String, UserIdDto> {
private static final Logger LOGGER = LoggerFactory.getLogger(ScmAccountToUserLoader.class);
private final DbClient dbClient;
public ScmAccountToUserLoader(DbClient dbClient) {
this.dbClient = dbClient;
}
@Override
public UserIdDto load(String scmAccount) {
try (DbSession dbSession = dbClient.openSession(false)) {
List<UserIdDto> users = dbClient.userDao().selectActiveUsersByScmAccountOrLoginOrEmail(dbSession, scmAccount);
if (users.size() == 1) {
return users.iterator().next();
}
if (!users.isEmpty()) {
Collection<String> logins = users.stream()
.map(UserIdDto::getLogin)
.sorted()
.toList();
if (LOGGER.isWarnEnabled()) {
LOGGER.warn(String.format("Multiple users share the SCM account '%s': %s", scmAccount, Joiner.on(", ").join(logins)));
}
}
return null;
}
}
@Override
public Map<String, UserIdDto> loadAll(Collection<? extends String> scmAccounts) {
throw new UnsupportedOperationException("Loading by multiple scm accounts is not supported yet");
}
}
| 2,486 | 34.028169 | 128 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/SiblingIssue.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.util.Date;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.rule.RuleKey;
import org.sonar.core.issue.tracking.Trackable;
import org.sonar.db.component.BranchType;
@Immutable
public class SiblingIssue implements Trackable {
private final String key;
private final Integer line;
private final String message;
private final String lineHash;
private final RuleKey ruleKey;
private final String status;
private final String prKey;
private final BranchType branchType;
private final Date updateDate;
SiblingIssue(String key, @Nullable Integer line, @Nullable String message, @Nullable String lineHash, RuleKey ruleKey, String status, String prKey, BranchType branchType,
Date updateDate) {
this.key = key;
this.line = line;
this.message = message;
this.lineHash = lineHash;
this.ruleKey = ruleKey;
this.status = status;
this.prKey = prKey;
this.branchType = branchType;
this.updateDate = updateDate;
}
public String getKey() {
return key;
}
@CheckForNull
@Override
public Integer getLine() {
return line;
}
@CheckForNull
@Override
public String getMessage() {
return message;
}
public BranchType getBranchType() {
return branchType;
}
@CheckForNull
@Override
public String getLineHash() {
return lineHash;
}
@Override
public RuleKey getRuleKey() {
return ruleKey;
}
@Override
public String getStatus() {
return status;
}
public String getPrKey() {
return prKey;
}
@Override
public Date getUpdateDate() {
return updateDate;
}
@Override
public int hashCode() {
return key.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
SiblingIssue other = (SiblingIssue) obj;
return key.equals(other.key);
}
}
| 2,948 | 23.371901 | 172 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/SiblingsIssueMerger.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.util.Collection;
import java.util.Map;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.tracking.SimpleTracker;
import org.sonar.core.issue.tracking.Tracking;
import org.springframework.beans.factory.annotation.Autowired;
public class SiblingsIssueMerger {
private final SiblingsIssuesLoader siblingsIssuesLoader;
private final SimpleTracker<DefaultIssue, SiblingIssue> tracker;
private final IssueLifecycle issueLifecycle;
@Autowired(required = false)
public SiblingsIssueMerger(SiblingsIssuesLoader resolvedSiblingsIssuesLoader, IssueLifecycle issueLifecycle) {
this(resolvedSiblingsIssuesLoader, new SimpleTracker<>(), issueLifecycle);
}
@Autowired(required = false)
public SiblingsIssueMerger(SiblingsIssuesLoader siblingsIssuesLoader, SimpleTracker<DefaultIssue, SiblingIssue> tracker, IssueLifecycle issueLifecycle) {
this.siblingsIssuesLoader = siblingsIssuesLoader;
this.tracker = tracker;
this.issueLifecycle = issueLifecycle;
}
/**
* Look for all unclosed issues in PR targeting the same branch, and run
* a light issue tracking to find matches. Then merge issue attributes in the new issues.
*/
public void tryMerge(Component component, Collection<DefaultIssue> newIssues) {
Collection<SiblingIssue> siblingIssues = siblingsIssuesLoader.loadCandidateSiblingIssuesForMerging(component);
Tracking<DefaultIssue, SiblingIssue> tracking = tracker.track(newIssues, siblingIssues);
Map<DefaultIssue, SiblingIssue> matchedRaws = tracking.getMatchedRaws();
Map<SiblingIssue, DefaultIssue> defaultIssues = siblingsIssuesLoader.loadDefaultIssuesWithChanges(matchedRaws.values());
for (Map.Entry<DefaultIssue, SiblingIssue> e : matchedRaws.entrySet()) {
SiblingIssue issue = e.getValue();
issueLifecycle.mergeConfirmedOrResolvedFromPrOrBranch(e.getKey(), defaultIssues.get(issue), issue.getBranchType(), issue.getPrKey());
}
}
}
| 2,909 | 43.769231 | 155 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/SiblingsIssuesLoader.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.SiblingComponentsWithOpenIssues;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.issue.PrIssueDto;
import static org.sonar.api.utils.DateUtils.longToDate;
public class SiblingsIssuesLoader {
private final SiblingComponentsWithOpenIssues siblingComponentsWithOpenIssues;
private final DbClient dbClient;
private final ComponentIssuesLoader componentIssuesLoader;
public SiblingsIssuesLoader(SiblingComponentsWithOpenIssues siblingComponentsWithOpenIssues, DbClient dbClient,
ComponentIssuesLoader componentIssuesLoader) {
this.siblingComponentsWithOpenIssues = siblingComponentsWithOpenIssues;
this.dbClient = dbClient;
this.componentIssuesLoader = componentIssuesLoader;
}
public Collection<SiblingIssue> loadCandidateSiblingIssuesForMerging(Component component) {
Set<String> uuids = siblingComponentsWithOpenIssues.getUuids(component.getKey());
if (uuids.isEmpty()) {
return Collections.emptyList();
}
try (DbSession session = dbClient.openSession(false)) {
return dbClient.issueDao().selectOpenByComponentUuids(session, uuids)
.stream()
.map(SiblingsIssuesLoader::toSiblingIssue)
.toList();
}
}
private static SiblingIssue toSiblingIssue(PrIssueDto dto) {
return new SiblingIssue(dto.getKey(), dto.getLine(), dto.getMessage(), dto.getChecksum(), dto.getRuleKey(), dto.getStatus(), dto.getBranchKey(),
dto.getBranchType(), longToDate(dto.getIssueUpdateDate()));
}
public Map<SiblingIssue, DefaultIssue> loadDefaultIssuesWithChanges(Collection<SiblingIssue> lightIssues) {
if (lightIssues.isEmpty()) {
return Collections.emptyMap();
}
Map<String, SiblingIssue> issuesByKey = lightIssues.stream().collect(Collectors.toMap(SiblingIssue::getKey, i -> i));
try (DbSession session = dbClient.openSession(false)) {
List<DefaultIssue> issues = dbClient.issueDao().selectByKeys(session, issuesByKey.keySet())
.stream()
.map(IssueDto::toDefaultIssue)
.toList();
componentIssuesLoader.loadChanges(session, issues);
return issues.stream()
.collect(Collectors.toMap(i -> issuesByKey.get(i.key()), Function.identity()));
}
}
}
| 3,520 | 38.561798 | 148 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/SourceBranchComponentUuids.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.annotation.CheckForNull;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ComponentDto;
/**
* Cache a map between component keys and uuids in the source branch of a pull request
*/
public class SourceBranchComponentUuids {
private final AnalysisMetadataHolder analysisMetadataHolder;
private final DbClient dbClient;
private Map<String, String> sourceBranchComponentsUuidsByKey;
private boolean hasSourceBranchAnalysis;
public SourceBranchComponentUuids(AnalysisMetadataHolder analysisMetadataHolder, DbClient dbClient) {
this.analysisMetadataHolder = analysisMetadataHolder;
this.dbClient = dbClient;
}
private void lazyInit() {
if (sourceBranchComponentsUuidsByKey == null) {
sourceBranchComponentsUuidsByKey = new HashMap<>();
if (analysisMetadataHolder.isPullRequest()) {
try (DbSession dbSession = dbClient.openSession(false)) {
initForSourceBranch(dbSession);
}
} else {
hasSourceBranchAnalysis = false;
}
}
}
private void initForSourceBranch(DbSession dbSession) {
Optional<BranchDto> branchDtoOpt = dbClient.branchDao().selectByBranchKey(dbSession, analysisMetadataHolder.getProject().getUuid(),
analysisMetadataHolder.getBranch().getName());
String sourceBranchUuid = branchDtoOpt.map(BranchDto::getUuid).orElse(null);
hasSourceBranchAnalysis = sourceBranchUuid != null && dbClient.snapshotDao().selectLastAnalysisByRootComponentUuid(dbSession, sourceBranchUuid).isPresent();
if (hasSourceBranchAnalysis) {
List<ComponentDto> targetComponents = dbClient.componentDao().selectByBranchUuid(sourceBranchUuid, dbSession);
for (ComponentDto dto : targetComponents) {
sourceBranchComponentsUuidsByKey.put(dto.getKey(), dto.uuid());
}
}
}
public boolean hasSourceBranchAnalysis() {
lazyInit();
return hasSourceBranchAnalysis;
}
@CheckForNull
public String getSourceBranchComponentUuid(String key) {
lazyInit();
return sourceBranchComponentsUuidsByKey.get(key);
}
}
| 3,209 | 36.764706 | 160 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/TargetBranchComponentUuids.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.annotation.CheckForNull;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ComponentDto;
/**
* Cache a map between component keys and uuids in the merge branch and optionally the target branch (for PR and SLB, and only if this target branch is analyzed)
*/
public class TargetBranchComponentUuids {
private final AnalysisMetadataHolder analysisMetadataHolder;
private final DbClient dbClient;
private Map<String, String> targetBranchComponentsUuidsByKey;
private boolean hasTargetBranchAnalysis;
public TargetBranchComponentUuids(AnalysisMetadataHolder analysisMetadataHolder, DbClient dbClient) {
this.analysisMetadataHolder = analysisMetadataHolder;
this.dbClient = dbClient;
}
private void lazyInit() {
if (targetBranchComponentsUuidsByKey == null) {
targetBranchComponentsUuidsByKey = new HashMap<>();
if (analysisMetadataHolder.isPullRequest()) {
try (DbSession dbSession = dbClient.openSession(false)) {
initForTargetBranch(dbSession);
}
} else {
hasTargetBranchAnalysis = false;
}
}
}
private void initForTargetBranch(DbSession dbSession) {
Optional<BranchDto> branchDtoOpt = dbClient.branchDao().selectByBranchKey(dbSession, analysisMetadataHolder.getProject().getUuid(),
analysisMetadataHolder.getBranch().getTargetBranchName());
String targetBranchUuid = branchDtoOpt.map(BranchDto::getUuid).orElse(null);
hasTargetBranchAnalysis = targetBranchUuid != null && dbClient.snapshotDao().selectLastAnalysisByRootComponentUuid(dbSession, targetBranchUuid).isPresent();
if (hasTargetBranchAnalysis) {
List<ComponentDto> targetComponents = dbClient.componentDao().selectByBranchUuid(targetBranchUuid, dbSession);
for (ComponentDto dto : targetComponents) {
targetBranchComponentsUuidsByKey.put(dto.getKey(), dto.uuid());
}
}
}
public boolean hasTargetBranchAnalysis() {
lazyInit();
return hasTargetBranchAnalysis;
}
@CheckForNull
public String getTargetBranchComponentUuid(String key) {
lazyInit();
return targetBranchComponentsUuidsByKey.get(key);
}
}
| 3,296 | 37.788235 | 161 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/TrackerBaseInputFactory.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nullable;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.filemove.MovedFilesRepository;
import org.sonar.ce.task.projectanalysis.filemove.MovedFilesRepository.OriginalFile;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.tracking.Input;
import org.sonar.db.DbClient;
/**
* Factory of {@link Input} of base data for issue tracking. Data are lazy-loaded.
*/
public class TrackerBaseInputFactory extends BaseInputFactory {
private final ComponentIssuesLoader issuesLoader;
private final DbClient dbClient;
private final MovedFilesRepository movedFilesRepository;
public TrackerBaseInputFactory(ComponentIssuesLoader issuesLoader, DbClient dbClient, MovedFilesRepository movedFilesRepository) {
this.issuesLoader = issuesLoader;
this.dbClient = dbClient;
this.movedFilesRepository = movedFilesRepository;
}
public Input<DefaultIssue> create(Component component) {
if (component.getType() == Component.Type.PROJECT) {
return new ProjectTrackerBaseLazyInput(dbClient, issuesLoader, component);
}
if (component.getType() == Component.Type.DIRECTORY) {
// Folders have no issues
return new EmptyTrackerBaseLazyInput(dbClient, component);
}
return new FileTrackerBaseLazyInput(dbClient, component, movedFilesRepository.getOriginalFile(component).orElse(null));
}
private class FileTrackerBaseLazyInput extends BaseLazyInput {
private FileTrackerBaseLazyInput(DbClient dbClient, Component component, @Nullable OriginalFile originalFile) {
super(dbClient, component, originalFile);
}
@Override
protected List<DefaultIssue> loadIssues() {
return issuesLoader.loadOpenIssues(effectiveUuid);
}
}
private static class EmptyTrackerBaseLazyInput extends BaseLazyInput {
private EmptyTrackerBaseLazyInput(DbClient dbClient, Component component) {
super(dbClient, component, null);
}
@Override
protected List<DefaultIssue> loadIssues() {
return Collections.emptyList();
}
}
}
| 3,058 | 34.16092 | 132 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/TrackerExecution.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.util.Set;
import java.util.stream.Collectors;
import org.sonar.api.issue.Issue;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.tracking.Input;
import org.sonar.core.issue.tracking.NonClosedTracking;
import org.sonar.core.issue.tracking.Tracker;
import org.sonar.core.issue.tracking.Tracking;
public class TrackerExecution {
private final TrackerBaseInputFactory baseInputFactory;
private final ClosedIssuesInputFactory closedIssuesInputFactory;
private final Tracker<DefaultIssue, DefaultIssue> tracker;
private final ComponentIssuesLoader componentIssuesLoader;
private final AnalysisMetadataHolder analysisMetadataHolder;
public TrackerExecution(TrackerBaseInputFactory baseInputFactory,
ClosedIssuesInputFactory closedIssuesInputFactory, Tracker<DefaultIssue, DefaultIssue> tracker,
ComponentIssuesLoader componentIssuesLoader, AnalysisMetadataHolder analysisMetadataHolder) {
this.baseInputFactory = baseInputFactory;
this.closedIssuesInputFactory = closedIssuesInputFactory;
this.tracker = tracker;
this.componentIssuesLoader = componentIssuesLoader;
this.analysisMetadataHolder = analysisMetadataHolder;
}
public Tracking<DefaultIssue, DefaultIssue> track(Component component, Input<DefaultIssue> rawInput) {
Input<DefaultIssue> openBaseIssuesInput = baseInputFactory.create(component);
NonClosedTracking<DefaultIssue, DefaultIssue> openIssueTracking = tracker.trackNonClosed(rawInput, openBaseIssuesInput);
if (openIssueTracking.isComplete() || analysisMetadataHolder.isFirstAnalysis()) {
return openIssueTracking;
}
Input<DefaultIssue> closedIssuesBaseInput = closedIssuesInputFactory.create(component);
Tracking<DefaultIssue, DefaultIssue> closedIssuesTracking = tracker.trackClosed(openIssueTracking, closedIssuesBaseInput);
// changes of closed issues need to be loaded in order to:
// - compute right transition from workflow
// - recover fields values from before they were closed
Set<DefaultIssue> matchesClosedIssues = closedIssuesTracking.getMatchedRaws().values().stream()
.filter(t -> Issue.STATUS_CLOSED.equals(t.getStatus()))
.collect(Collectors.toSet());
componentIssuesLoader.loadLatestDiffChangesForReopeningOfClosedIssues(matchesClosedIssues);
return closedIssuesTracking;
}
}
| 3,385 | 45.383562 | 126 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/TrackerRawInputFactory.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nullable;
import org.jetbrains.annotations.NotNull;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rules.RuleType;
import org.sonar.api.utils.Duration;
import org.slf4j.LoggerFactory;
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.projectanalysis.issue.filter.IssueFilter;
import org.sonar.ce.task.projectanalysis.qualityprofile.ActiveRulesHolder;
import org.sonar.ce.task.projectanalysis.source.SourceLinesHashRepository;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.tracking.Input;
import org.sonar.core.issue.tracking.LazyInput;
import org.sonar.core.issue.tracking.LineHashSequence;
import org.sonar.core.util.CloseableIterator;
import org.sonar.db.protobuf.DbCommons;
import org.sonar.db.protobuf.DbIssues;
import org.sonar.scanner.protocol.Constants.Severity;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.protocol.output.ScannerReport.IssueType;
import org.sonar.server.rule.CommonRuleKeys;
import static org.apache.commons.lang.StringUtils.isNotEmpty;
import static org.sonar.api.issue.Issue.STATUS_OPEN;
import static org.sonar.api.issue.Issue.STATUS_TO_REVIEW;
public class TrackerRawInputFactory {
private static final long DEFAULT_EXTERNAL_ISSUE_EFFORT = 0L;
private final TreeRootHolder treeRootHolder;
private final BatchReportReader reportReader;
private final IssueFilter issueFilter;
private final SourceLinesHashRepository sourceLinesHash;
private final RuleRepository ruleRepository;
private final ActiveRulesHolder activeRulesHolder;
public TrackerRawInputFactory(TreeRootHolder treeRootHolder, BatchReportReader reportReader, SourceLinesHashRepository sourceLinesHash,
IssueFilter issueFilter, RuleRepository ruleRepository, ActiveRulesHolder activeRulesHolder) {
this.treeRootHolder = treeRootHolder;
this.reportReader = reportReader;
this.sourceLinesHash = sourceLinesHash;
this.issueFilter = issueFilter;
this.ruleRepository = ruleRepository;
this.activeRulesHolder = activeRulesHolder;
}
public Input<DefaultIssue> create(Component component) {
return new RawLazyInput(component);
}
private class RawLazyInput extends LazyInput<DefaultIssue> {
private final Component component;
private RawLazyInput(Component component) {
this.component = component;
}
@Override
protected LineHashSequence loadLineHashSequence() {
if (component.getType() == Component.Type.FILE) {
return new LineHashSequence(sourceLinesHash.getLineHashesMatchingDBVersion(component));
} else {
return new LineHashSequence(Collections.emptyList());
}
}
@Override
protected List<DefaultIssue> loadIssues() {
List<DefaultIssue> result = new ArrayList<>();
if (component.getReportAttributes().getRef() == null) {
return result;
}
try (CloseableIterator<ScannerReport.Issue> reportIssues = reportReader.readComponentIssues(component.getReportAttributes().getRef())) {
// optimization - do not load line hashes if there are no issues -> getLineHashSequence() is executed
// as late as possible
while (reportIssues.hasNext()) {
ScannerReport.Issue reportIssue = reportIssues.next();
if (isOnInactiveRule(reportIssue)) {
continue;
}
if (!isIssueOnUnsupportedCommonRule(reportIssue)) {
LoggerFactory.getLogger(getClass()).debug("Ignored issue from analysis report on rule {}:{}", reportIssue.getRuleRepository(), reportIssue.getRuleKey());
continue;
}
DefaultIssue issue = toIssue(getLineHashSequence(), reportIssue);
if (issueFilter.accept(issue, component)) {
result.add(issue);
}
}
}
Map<RuleKey, ScannerReport.AdHocRule> adHocRuleMap = new HashMap<>();
try (CloseableIterator<ScannerReport.AdHocRule> reportAdHocRule = reportReader.readAdHocRules()) {
while (reportAdHocRule.hasNext()) {
ScannerReport.AdHocRule adHocRule = reportAdHocRule.next();
adHocRuleMap.put(RuleKey.of(RuleKey.EXTERNAL_RULE_REPO_PREFIX + adHocRule.getEngineId(), adHocRule.getRuleId()), adHocRule);
}
}
try (CloseableIterator<ScannerReport.ExternalIssue> reportExternalIssues = reportReader.readComponentExternalIssues(component.getReportAttributes().getRef())) {
// optimization - do not load line hashes if there are no issues -> getLineHashSequence() is executed
// as late as possible
while (reportExternalIssues.hasNext()) {
ScannerReport.ExternalIssue reportExternalIssue = reportExternalIssues.next();
result.add(toExternalIssue(getLineHashSequence(), reportExternalIssue, adHocRuleMap));
}
}
return result;
}
private boolean isOnInactiveRule(ScannerReport.Issue reportIssue) {
RuleKey ruleKey = RuleKey.of(reportIssue.getRuleRepository(), reportIssue.getRuleKey());
return !activeRulesHolder.get(ruleKey).isPresent();
}
private boolean isIssueOnUnsupportedCommonRule(ScannerReport.Issue issue) {
// issues on batch common rules are ignored. This feature
// is natively supported by compute engine since 5.2.
return !issue.getRuleRepository().startsWith(CommonRuleKeys.REPOSITORY_PREFIX);
}
private DefaultIssue toIssue(LineHashSequence lineHashSeq, ScannerReport.Issue reportIssue) {
DefaultIssue issue = new DefaultIssue();
init(issue, STATUS_OPEN);
RuleKey ruleKey = RuleKey.of(reportIssue.getRuleRepository(), reportIssue.getRuleKey());
issue.setRuleKey(ruleKey);
if (reportIssue.hasTextRange()) {
int startLine = reportIssue.getTextRange().getStartLine();
issue.setLine(startLine);
issue.setChecksum(lineHashSeq.getHashForLine(startLine));
} else {
issue.setChecksum("");
}
if (isNotEmpty(reportIssue.getMsg())) {
issue.setMessage(reportIssue.getMsg());
if (!reportIssue.getMsgFormattingList().isEmpty()) {
issue.setMessageFormattings(convertMessageFormattings(reportIssue.getMsgFormattingList()));
}
} else {
Rule rule = ruleRepository.getByKey(ruleKey);
issue.setMessage(rule.getName());
}
if (reportIssue.getSeverity() != Severity.UNSET_SEVERITY) {
issue.setSeverity(reportIssue.getSeverity().name());
}
if (Double.compare(reportIssue.getGap(), 0D) != 0) {
issue.setGap(reportIssue.getGap());
}
DbIssues.Locations.Builder dbLocationsBuilder = DbIssues.Locations.newBuilder();
if (reportIssue.hasTextRange()) {
dbLocationsBuilder.setTextRange(convertTextRange(reportIssue.getTextRange()));
}
for (ScannerReport.Flow flow : reportIssue.getFlowList()) {
if (flow.getLocationCount() > 0) {
DbIssues.Flow.Builder dbFlowBuilder = convertLocations(flow);
dbLocationsBuilder.addFlow(dbFlowBuilder);
}
}
issue.setIsFromExternalRuleEngine(false);
issue.setLocations(dbLocationsBuilder.build());
issue.setQuickFixAvailable(reportIssue.getQuickFixAvailable());
issue.setRuleDescriptionContextKey(reportIssue.hasRuleDescriptionContextKey() ? reportIssue.getRuleDescriptionContextKey() : null);
issue.setCodeVariants(reportIssue.getCodeVariantsList());
return issue;
}
private DbIssues.Flow.Builder convertLocations(ScannerReport.Flow flow) {
DbIssues.Flow.Builder dbFlowBuilder = DbIssues.Flow.newBuilder();
for (ScannerReport.IssueLocation location : flow.getLocationList()) {
convertLocation(location).ifPresent(dbFlowBuilder::addLocation);
}
if (isNotEmpty(flow.getDescription())) {
dbFlowBuilder.setDescription(flow.getDescription());
}
toFlowType(flow.getType()).ifPresent(dbFlowBuilder::setType);
return dbFlowBuilder;
}
private DefaultIssue toExternalIssue(LineHashSequence lineHashSeq, ScannerReport.ExternalIssue reportExternalIssue, Map<RuleKey, ScannerReport.AdHocRule> adHocRuleMap) {
DefaultIssue issue = new DefaultIssue();
RuleType type = toRuleType(reportExternalIssue.getType());
init(issue, type == RuleType.SECURITY_HOTSPOT ? STATUS_TO_REVIEW : STATUS_OPEN);
RuleKey ruleKey = RuleKey.of(RuleKey.EXTERNAL_RULE_REPO_PREFIX + reportExternalIssue.getEngineId(), reportExternalIssue.getRuleId());
issue.setRuleKey(ruleKey);
if (reportExternalIssue.hasTextRange()) {
int startLine = reportExternalIssue.getTextRange().getStartLine();
issue.setLine(startLine);
issue.setChecksum(lineHashSeq.getHashForLine(startLine));
} else {
issue.setChecksum("");
}
if (isNotEmpty(reportExternalIssue.getMsg())) {
issue.setMessage(reportExternalIssue.getMsg());
if (!reportExternalIssue.getMsgFormattingList().isEmpty()) {
issue.setMessageFormattings(convertMessageFormattings(reportExternalIssue.getMsgFormattingList()));
}
}
if (reportExternalIssue.getSeverity() != Severity.UNSET_SEVERITY) {
issue.setSeverity(reportExternalIssue.getSeverity().name());
}
issue.setEffort(Duration.create(reportExternalIssue.getEffort() != 0 ? reportExternalIssue.getEffort() : DEFAULT_EXTERNAL_ISSUE_EFFORT));
DbIssues.Locations.Builder dbLocationsBuilder = DbIssues.Locations.newBuilder();
if (reportExternalIssue.hasTextRange()) {
dbLocationsBuilder.setTextRange(convertTextRange(reportExternalIssue.getTextRange()));
}
for (ScannerReport.Flow flow : reportExternalIssue.getFlowList()) {
if (flow.getLocationCount() > 0) {
DbIssues.Flow.Builder dbFlowBuilder = convertLocations(flow);
dbLocationsBuilder.addFlow(dbFlowBuilder);
}
}
issue.setIsFromExternalRuleEngine(true);
issue.setLocations(dbLocationsBuilder.build());
issue.setType(type);
ruleRepository.addOrUpdateAddHocRuleIfNeeded(ruleKey, () -> toAdHocRule(reportExternalIssue, adHocRuleMap.get(issue.ruleKey())));
return issue;
}
private NewAdHocRule toAdHocRule(ScannerReport.ExternalIssue reportIssue, @Nullable ScannerReport.AdHocRule adHocRule) {
if (adHocRule != null) {
return new NewAdHocRule(adHocRule);
}
return new NewAdHocRule(reportIssue);
}
private Optional<DbIssues.FlowType> toFlowType(ScannerReport.FlowType flowType) {
switch (flowType) {
case DATA:
return Optional.of(DbIssues.FlowType.DATA);
case EXECUTION:
return Optional.of(DbIssues.FlowType.EXECUTION);
case UNDEFINED:
return Optional.empty();
default:
throw new IllegalArgumentException("Unrecognized type: " + flowType);
}
}
private RuleType toRuleType(IssueType type) {
switch (type) {
case BUG:
return RuleType.BUG;
case CODE_SMELL:
return RuleType.CODE_SMELL;
case VULNERABILITY:
return RuleType.VULNERABILITY;
case SECURITY_HOTSPOT:
return RuleType.SECURITY_HOTSPOT;
case UNRECOGNIZED:
default:
throw new IllegalStateException("Invalid issue type: " + type);
}
}
private DefaultIssue init(DefaultIssue issue, String initialStatus) {
issue.setStatus(initialStatus);
issue.setResolution(null);
issue.setComponentUuid(component.getUuid());
issue.setComponentKey(component.getKey());
issue.setProjectUuid(treeRootHolder.getRoot().getUuid());
issue.setProjectKey(treeRootHolder.getRoot().getKey());
return issue;
}
private Optional<DbIssues.Location> convertLocation(ScannerReport.IssueLocation source) {
DbIssues.Location.Builder target = DbIssues.Location.newBuilder();
if (source.getComponentRef() != 0 && source.getComponentRef() != component.getReportAttributes().getRef()) {
// SONAR-10781 Component might not exist because on PR, only changed components are included in the report
Optional<Component> optionalComponent = treeRootHolder.getOptionalComponentByRef(source.getComponentRef());
if (!optionalComponent.isPresent()) {
return Optional.empty();
}
target.setComponentId(optionalComponent.get().getUuid());
}
if (isNotEmpty(source.getMsg())) {
target.setMsg(source.getMsg());
source.getMsgFormattingList()
.forEach(m -> target.addMsgFormatting(convertMessageFormatting(m)));
}
if (source.hasTextRange()) {
ScannerReport.TextRange sourceRange = source.getTextRange();
DbCommons.TextRange.Builder targetRange = convertTextRange(sourceRange);
target.setTextRange(targetRange);
}
return Optional.of(target.build());
}
private DbCommons.TextRange.Builder convertTextRange(ScannerReport.TextRange sourceRange) {
DbCommons.TextRange.Builder targetRange = DbCommons.TextRange.newBuilder();
targetRange.setStartLine(sourceRange.getStartLine());
targetRange.setStartOffset(sourceRange.getStartOffset());
targetRange.setEndLine(sourceRange.getEndLine());
targetRange.setEndOffset(sourceRange.getEndOffset());
return targetRange;
}
}
private static DbIssues.MessageFormattings convertMessageFormattings(List<ScannerReport.MessageFormatting> msgFormattings) {
DbIssues.MessageFormattings.Builder builder = DbIssues.MessageFormattings.newBuilder();
msgFormattings.stream()
.forEach(m -> builder.addMessageFormatting(TrackerRawInputFactory.convertMessageFormatting(m)));
return builder.build();
}
@NotNull
private static DbIssues.MessageFormatting convertMessageFormatting(ScannerReport.MessageFormatting m) {
DbIssues.MessageFormatting.Builder msgFormattingBuilder = DbIssues.MessageFormatting.newBuilder();
return msgFormattingBuilder
.setStart(m.getStart())
.setEnd(m.getEnd())
.setType(DbIssues.MessageFormattingType.valueOf(m.getType().name())).build();
}
}
| 15,368 | 43.163793 | 173 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/TrackerReferenceBranchInputFactory.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nullable;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.ReferenceBranchComponentUuids;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.tracking.Input;
import org.sonar.core.issue.tracking.LazyInput;
import org.sonar.core.issue.tracking.LineHashSequence;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
public class TrackerReferenceBranchInputFactory {
private static final LineHashSequence EMPTY_LINE_HASH_SEQUENCE = new LineHashSequence(Collections.emptyList());
private final ComponentIssuesLoader componentIssuesLoader;
private final DbClient dbClient;
private final ReferenceBranchComponentUuids referenceBranchComponentUuids;
public TrackerReferenceBranchInputFactory(ComponentIssuesLoader componentIssuesLoader, ReferenceBranchComponentUuids referenceBranchComponentUuids, DbClient dbClient) {
this.componentIssuesLoader = componentIssuesLoader;
this.referenceBranchComponentUuids = referenceBranchComponentUuids;
this.dbClient = dbClient;
// TODO detect file moves?
}
public Input<DefaultIssue> create(Component component) {
String referenceBranchComponentUuid = referenceBranchComponentUuids.getComponentUuid(component.getKey());
return new ReferenceLazyInput(component.getType(), referenceBranchComponentUuid);
}
private class ReferenceLazyInput extends LazyInput<DefaultIssue> {
private final Component.Type type;
private final String referenceBranchComponentUuid;
private ReferenceLazyInput(Component.Type type, @Nullable String referenceBranchComponentUuid) {
this.type = type;
this.referenceBranchComponentUuid = referenceBranchComponentUuid;
}
@Override
protected LineHashSequence loadLineHashSequence() {
if (referenceBranchComponentUuid == null || type != Component.Type.FILE) {
return EMPTY_LINE_HASH_SEQUENCE;
}
try (DbSession session = dbClient.openSession(false)) {
List<String> hashes = dbClient.fileSourceDao().selectLineHashes(session, referenceBranchComponentUuid);
if (hashes == null || hashes.isEmpty()) {
return EMPTY_LINE_HASH_SEQUENCE;
}
return new LineHashSequence(hashes);
}
}
@Override
protected List<DefaultIssue> loadIssues() {
if (referenceBranchComponentUuid == null) {
return Collections.emptyList();
}
return componentIssuesLoader.loadOpenIssuesWithChanges(referenceBranchComponentUuid);
}
}
}
| 3,510 | 39.356322 | 170 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/TrackerSourceBranchInputFactory.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nullable;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.tracking.Input;
import org.sonar.core.issue.tracking.LazyInput;
import org.sonar.core.issue.tracking.LineHashSequence;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
public class TrackerSourceBranchInputFactory {
private static final LineHashSequence EMPTY_LINE_HASH_SEQUENCE = new LineHashSequence(Collections.emptyList());
private final ComponentIssuesLoader componentIssuesLoader;
private final DbClient dbClient;
private final SourceBranchComponentUuids sourceBranchComponentUuids;
public TrackerSourceBranchInputFactory(ComponentIssuesLoader componentIssuesLoader, SourceBranchComponentUuids sourceBranchComponentUuids,
DbClient dbClient) {
this.componentIssuesLoader = componentIssuesLoader;
this.sourceBranchComponentUuids = sourceBranchComponentUuids;
this.dbClient = dbClient;
}
public boolean hasSourceBranchAnalysis() {
return sourceBranchComponentUuids.hasSourceBranchAnalysis();
}
public Input<DefaultIssue> createForSourceBranch(Component component) {
String sourceBranchComponentUuid = sourceBranchComponentUuids.getSourceBranchComponentUuid(component.getKey());
return new SourceBranchLazyInput(component.getType(), sourceBranchComponentUuid);
}
private class SourceBranchLazyInput extends LazyInput<DefaultIssue> {
private final Component.Type type;
private final String sourceBranchComponentUuid;
private SourceBranchLazyInput(Component.Type type, @Nullable String sourceBranchComponentUuid) {
this.type = type;
this.sourceBranchComponentUuid = sourceBranchComponentUuid;
}
@Override
protected LineHashSequence loadLineHashSequence() {
if (sourceBranchComponentUuid == null || type != Component.Type.FILE) {
return EMPTY_LINE_HASH_SEQUENCE;
}
try (DbSession session = dbClient.openSession(false)) {
List<String> hashes = dbClient.fileSourceDao().selectLineHashes(session, sourceBranchComponentUuid);
if (hashes == null || hashes.isEmpty()) {
return EMPTY_LINE_HASH_SEQUENCE;
}
return new LineHashSequence(hashes);
}
}
@Override
protected List<DefaultIssue> loadIssues() {
if (sourceBranchComponentUuid == null) {
return Collections.emptyList();
}
return componentIssuesLoader.loadOpenIssuesWithChanges(sourceBranchComponentUuid);
}
}
}
| 3,495 | 37.844444 | 140 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/TrackerTargetBranchInputFactory.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nullable;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.filemove.MovedFilesRepository;
import org.sonar.ce.task.projectanalysis.filemove.MovedFilesRepository.OriginalFile;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.tracking.Input;
import org.sonar.core.issue.tracking.LazyInput;
import org.sonar.core.issue.tracking.LineHashSequence;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
public class TrackerTargetBranchInputFactory {
private static final LineHashSequence EMPTY_LINE_HASH_SEQUENCE = new LineHashSequence(Collections.emptyList());
private final ComponentIssuesLoader componentIssuesLoader;
private final DbClient dbClient;
private final TargetBranchComponentUuids targetBranchComponentUuids;
private final MovedFilesRepository movedFilesRepository;
public TrackerTargetBranchInputFactory(ComponentIssuesLoader componentIssuesLoader, TargetBranchComponentUuids targetBranchComponentUuids,
DbClient dbClient, MovedFilesRepository movedFilesRepository) {
this.componentIssuesLoader = componentIssuesLoader;
this.targetBranchComponentUuids = targetBranchComponentUuids;
this.dbClient = dbClient;
this.movedFilesRepository = movedFilesRepository;
}
public boolean hasTargetBranchAnalysis() {
return targetBranchComponentUuids.hasTargetBranchAnalysis();
}
public Input<DefaultIssue> createForTargetBranch(Component component) {
String targetBranchComponentUuid = getTargetBranchComponentUuid(component);
return new TargetLazyInput(component.getType(), targetBranchComponentUuid);
}
private String getTargetBranchComponentUuid(Component component) {
Optional<String> targetBranchOriginalComponentKey = getOriginalComponentKey(component);
if (targetBranchOriginalComponentKey.isPresent()) {
return targetBranchComponentUuids.getTargetBranchComponentUuid(targetBranchOriginalComponentKey.get());
}
return targetBranchComponentUuids.getTargetBranchComponentUuid(component.getKey());
}
private Optional<String> getOriginalComponentKey(Component component) {
return movedFilesRepository
.getOriginalPullRequestFile(component)
.map(OriginalFile::key);
}
private class TargetLazyInput extends LazyInput<DefaultIssue> {
private final Component.Type type;
private final String targetBranchComponentUuid;
private TargetLazyInput(Component.Type type, @Nullable String targetBranchComponentUuid) {
this.type = type;
this.targetBranchComponentUuid = targetBranchComponentUuid;
}
@Override
protected LineHashSequence loadLineHashSequence() {
if (targetBranchComponentUuid == null || type != Component.Type.FILE) {
return EMPTY_LINE_HASH_SEQUENCE;
}
try (DbSession session = dbClient.openSession(false)) {
List<String> hashes = dbClient.fileSourceDao().selectLineHashes(session, targetBranchComponentUuid);
if (hashes == null || hashes.isEmpty()) {
return EMPTY_LINE_HASH_SEQUENCE;
}
return new LineHashSequence(hashes);
}
}
@Override
protected List<DefaultIssue> loadIssues() {
if (targetBranchComponentUuid == null) {
return Collections.emptyList();
}
return componentIssuesLoader.loadOpenIssuesWithChanges(targetBranchComponentUuid);
}
}
}
| 4,396 | 38.612613 | 140 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/TrackingResult.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import java.util.Map;
import java.util.stream.Stream;
import org.sonar.core.issue.DefaultIssue;
public class TrackingResult {
private final Map<DefaultIssue, DefaultIssue> issuesToCopy;
private final Map<DefaultIssue, DefaultIssue> issuesToMerge;
private final Stream<DefaultIssue> issuesToClose;
private final Stream<DefaultIssue> newIssues;
public TrackingResult(Map<DefaultIssue, DefaultIssue> issuesToCopy, Map<DefaultIssue, DefaultIssue> issuesToMerge,
Stream<DefaultIssue> issuesToClose, Stream<DefaultIssue> newIssues) {
this.issuesToCopy = issuesToCopy;
this.issuesToMerge = issuesToMerge;
this.issuesToClose = issuesToClose;
this.newIssues = newIssues;
}
public Map<DefaultIssue, DefaultIssue> issuesToCopy() {
return issuesToCopy;
}
public Map<DefaultIssue, DefaultIssue> issuesToMerge() {
return issuesToMerge;
}
public Stream<DefaultIssue> issuesToClose() {
return issuesToClose;
}
public Stream<DefaultIssue> newIssues() {
return newIssues;
}
}
| 1,921 | 33.321429 | 116 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/UpdateConflictResolver.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue;
import com.google.common.annotations.VisibleForTesting;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.issue.IssueMapper;
/**
* Support concurrent modifications on issues made by analysis and users at the same time
* See https://jira.sonarsource.com/browse/SONAR-4309
*/
public class UpdateConflictResolver {
private static final Logger LOG = LoggerFactory.getLogger(UpdateConflictResolver.class);
public void resolve(DefaultIssue issue, IssueDto dbIssue, IssueMapper mapper) {
LOG.debug("Resolve conflict on issue {}", issue.key());
mergeFields(dbIssue, issue);
mapper.update(IssueDto.toDtoForUpdate(issue, System.currentTimeMillis()));
}
@VisibleForTesting
void mergeFields(IssueDto dbIssue, DefaultIssue issue) {
resolveAssignee(dbIssue, issue);
resolveSeverity(dbIssue, issue);
resolveEffortToFix(dbIssue, issue);
resolveResolution(dbIssue, issue);
resolveStatus(dbIssue, issue);
}
private static void resolveStatus(IssueDto dbIssue, DefaultIssue issue) {
issue.setStatus(dbIssue.getStatus());
}
private static void resolveResolution(IssueDto dbIssue, DefaultIssue issue) {
issue.setResolution(dbIssue.getResolution());
}
private static void resolveEffortToFix(IssueDto dbIssue, DefaultIssue issue) {
issue.setGap(dbIssue.getGap());
}
private static void resolveSeverity(IssueDto dbIssue, DefaultIssue issue) {
if (dbIssue.isManualSeverity()) {
issue.setManualSeverity(true);
issue.setSeverity(dbIssue.getSeverity());
}
// else keep severity as declared in quality profile
}
private static void resolveAssignee(IssueDto dbIssue, DefaultIssue issue) {
issue.setAssigneeUuid(dbIssue.getAssigneeUuid());
}
}
| 2,726 | 34.881579 | 90 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.ce.task.projectanalysis.issue;
import javax.annotation.ParametersAreNonnullByDefault;
| 979 | 39.833333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/filter/IssueFilter.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.issue.filter;
import com.google.common.base.Splitter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.sonar.api.ce.ComputeEngineSide;
import org.sonar.api.config.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.ConfigurationRepository;
import org.sonar.core.issue.DefaultIssue;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Strings.isNullOrEmpty;
import static java.lang.String.format;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.FILE;
import static org.sonar.core.config.IssueExclusionProperties.PATTERNS_MULTICRITERIA_EXCLUSION_KEY;
import static org.sonar.core.config.IssueExclusionProperties.PATTERNS_MULTICRITERIA_INCLUSION_KEY;
import static org.sonar.core.config.IssueExclusionProperties.RESOURCE_KEY;
import static org.sonar.core.config.IssueExclusionProperties.RULE_KEY;
@ComputeEngineSide
public class IssueFilter {
private static final Logger LOG = LoggerFactory.getLogger(IssueFilter.class);
private final List<IssuePattern> exclusionPatterns;
private final List<IssuePattern> inclusionPatterns;
public IssueFilter(ConfigurationRepository configRepository) {
Configuration config = configRepository.getConfiguration();
this.exclusionPatterns = loadPatterns(PATTERNS_MULTICRITERIA_EXCLUSION_KEY, config);
this.inclusionPatterns = loadPatterns(PATTERNS_MULTICRITERIA_INCLUSION_KEY, config);
}
public boolean accept(DefaultIssue issue, Component component) {
if (component.getType() != FILE || (exclusionPatterns.isEmpty() && inclusionPatterns.isEmpty())) {
return true;
}
if (isExclude(issue, component)) {
return false;
}
return isInclude(issue, component);
}
private boolean isExclude(DefaultIssue issue, Component file) {
IssuePattern matchingPattern = null;
Iterator<IssuePattern> patternIterator = exclusionPatterns.iterator();
while (matchingPattern == null && patternIterator.hasNext()) {
IssuePattern nextPattern = patternIterator.next();
if (nextPattern.match(issue, file)) {
matchingPattern = nextPattern;
}
}
if (matchingPattern != null) {
LOG.debug("Issue {} ignored by exclusion pattern {}", issue, matchingPattern);
return true;
}
return false;
}
private boolean isInclude(DefaultIssue issue, Component file) {
boolean atLeastOneRuleMatched = false;
boolean atLeastOnePatternFullyMatched = false;
IssuePattern matchingPattern = null;
for (IssuePattern pattern : inclusionPatterns) {
if (pattern.getRulePattern().match(issue.ruleKey().toString())) {
atLeastOneRuleMatched = true;
String filePath = file.getName();
if (filePath != null && pattern.getComponentPattern().match(filePath)) {
atLeastOnePatternFullyMatched = true;
matchingPattern = pattern;
}
}
}
if (atLeastOneRuleMatched) {
if (atLeastOnePatternFullyMatched) {
LOG.debug("Issue {} enforced by pattern {}", issue, matchingPattern);
}
return atLeastOnePatternFullyMatched;
} else {
return true;
}
}
private static List<IssuePattern> loadPatterns(String propertyKey, Configuration settings) {
List<IssuePattern> patterns = new ArrayList<>();
String patternConf = settings.get(propertyKey).orElse("");
for (String id : Splitter.on(",").omitEmptyStrings().split(patternConf)) {
String propPrefix = propertyKey + "." + id + ".";
String componentPathPattern = settings.get(propPrefix + RESOURCE_KEY).orElse(null);
checkArgument(!isNullOrEmpty(componentPathPattern), format("File path pattern cannot be empty. Please check '%s' settings", propertyKey));
String ruleKeyPattern = settings.get(propPrefix + RULE_KEY).orElse(null);
checkArgument(!isNullOrEmpty(ruleKeyPattern), format("Rule key pattern cannot be empty. Please check '%s' settings", propertyKey));
patterns.add(new IssuePattern(componentPathPattern, ruleKeyPattern));
}
return patterns;
}
}
| 5,112 | 40.233871 | 144 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/filter/IssuePattern.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.issue.filter;
import javax.annotation.Nullable;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.utils.WildcardPattern;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.core.issue.DefaultIssue;
public class IssuePattern {
private WildcardPattern componentPattern;
private WildcardPattern rulePattern;
public IssuePattern(String componentPattern, String rulePattern) {
this.componentPattern = WildcardPattern.create(componentPattern);
this.rulePattern = WildcardPattern.create(rulePattern);
}
public WildcardPattern getComponentPattern() {
return componentPattern;
}
public WildcardPattern getRulePattern() {
return rulePattern;
}
boolean match(DefaultIssue issue, Component file) {
return matchComponent(file.getName()) && matchRule(issue.ruleKey());
}
boolean matchRule(RuleKey rule) {
return rulePattern.match(rule.toString());
}
boolean matchComponent(@Nullable String path) {
return path != null && componentPattern.match(path);
}
@Override
public String toString() {
return "IssuePattern{" +
"componentPattern=" + componentPattern +
", rulePattern=" + rulePattern +
'}';
}
}
| 2,096 | 30.772727 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/filter/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.issue.filter;
import javax.annotation.ParametersAreNonnullByDefault;
| 986 | 40.125 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/language/HandleUnanalyzedLanguagesStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.language;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.stream.Collectors;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.log.CeTaskMessages;
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.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.platform.EditionProvider;
import org.sonar.core.platform.PlatformEditionProvider;
import org.sonar.db.ce.CeTaskMessageType;
import static java.lang.String.format;
import static org.sonar.core.language.UnanalyzedLanguages.C;
import static org.sonar.core.language.UnanalyzedLanguages.CPP;
import static org.sonar.server.metric.UnanalyzedLanguageMetrics.UNANALYZED_CPP_KEY;
import static org.sonar.server.metric.UnanalyzedLanguageMetrics.UNANALYZED_C_KEY;
/**
* Check if there are files that could be analyzed with a higher SQ edition.
*/
public class HandleUnanalyzedLanguagesStep implements ComputationStep {
static final String DESCRIPTION = "Check upgrade possibility for not analyzed code files.";
private static final String LANGUAGE_UPGRADE_MESSAGE = "%s detected in this project during the last analysis. %s cannot be analyzed with your" +
" current SonarQube edition. Please consider <a target=\"_blank\" href=\"https://www.sonarqube.org/trial-request/developer-edition/?referrer=sonarqube-cpp\">upgrading to" +
" Developer Edition</a> to find Bugs, Code Smells, Vulnerabilities and Security Hotspots in %s.";
private final BatchReportReader reportReader;
private final CeTaskMessages ceTaskMessages;
private final PlatformEditionProvider editionProvider;
private final System2 system;
private final TreeRootHolder treeRootHolder;
private final MeasureRepository measureRepository;
private final Metric unanalyzedCMetric;
private final Metric unanalyzedCppMetric;
public HandleUnanalyzedLanguagesStep(BatchReportReader reportReader, CeTaskMessages ceTaskMessages, PlatformEditionProvider editionProvider,
System2 system, TreeRootHolder treeRootHolder, MetricRepository metricRepository, MeasureRepository measureRepository) {
this.reportReader = reportReader;
this.ceTaskMessages = ceTaskMessages;
this.editionProvider = editionProvider;
this.system = system;
this.treeRootHolder = treeRootHolder;
this.measureRepository = measureRepository;
this.unanalyzedCMetric = metricRepository.getByKey(UNANALYZED_C_KEY);
this.unanalyzedCppMetric = metricRepository.getByKey(UNANALYZED_CPP_KEY);
}
@Override
public void execute(Context context) {
editionProvider.get().ifPresent(edition -> {
if (!edition.equals(EditionProvider.Edition.COMMUNITY)) {
return;
}
Map<String, Integer> filesPerLanguage = reportReader.readMetadata().getNotAnalyzedFilesByLanguageMap()
.entrySet()
.stream()
.filter(entry -> entry.getValue() > 0)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
if (filesPerLanguage.isEmpty()) {
return;
}
ceTaskMessages.add(constructMessage(filesPerLanguage));
computeMeasures(filesPerLanguage);
});
}
private CeTaskMessages.Message constructMessage(Map<String, Integer> filesPerLanguage) {
SortedMap<String, Integer> sortedLanguageMap = new TreeMap<>(filesPerLanguage);
Iterator<Map.Entry<String, Integer>> iterator = sortedLanguageMap.entrySet().iterator();
Map.Entry<String, Integer> firstLanguage = iterator.next();
StringBuilder languageLabel = new StringBuilder(firstLanguage.getKey());
StringBuilder fileCountLabel = new StringBuilder(format("%s unanalyzed %s", firstLanguage.getValue(), firstLanguage.getKey()));
while (iterator.hasNext()) {
Map.Entry<String, Integer> nextLanguage = iterator.next();
if (iterator.hasNext()) {
languageLabel.append(", ");
fileCountLabel.append(", ");
} else {
languageLabel.append(" and ");
fileCountLabel.append(" and ");
}
languageLabel.append(nextLanguage.getKey());
fileCountLabel.append(format("%s unanalyzed %s", nextLanguage.getValue(), nextLanguage.getKey()));
}
if (sortedLanguageMap.size() == 1 && sortedLanguageMap.entrySet().iterator().next().getValue() == 1) {
fileCountLabel.append(" file was");
} else {
fileCountLabel.append(" files were");
}
String message = format(LANGUAGE_UPGRADE_MESSAGE, fileCountLabel, languageLabel, sortedLanguageMap.size() == 1 ? "this file" : "these files");
return new CeTaskMessages.Message(message, system.now(), CeTaskMessageType.SUGGEST_DEVELOPER_EDITION_UPGRADE);
}
private void computeMeasures(Map<String, Integer> filesPerLanguage) {
Component project = treeRootHolder.getRoot();
Integer unanalyzedCFiles = filesPerLanguage.getOrDefault(C.toString(), 0);
if (unanalyzedCFiles > 0) {
measureRepository.add(project, unanalyzedCMetric, Measure.newMeasureBuilder().create(unanalyzedCFiles));
}
Integer unanalyzedCppFiles = filesPerLanguage.getOrDefault(CPP.toString(), 0);
if (unanalyzedCppFiles > 0) {
measureRepository.add(project, unanalyzedCppMetric, Measure.newMeasureBuilder().create(unanalyzedCppFiles));
}
}
@Override
public String getDescription() {
return DESCRIPTION;
}
}
| 6,601 | 43.911565 | 176 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/language/LanguageRepository.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.language;
import java.util.Optional;
import org.sonar.api.resources.Language;
public interface LanguageRepository {
Optional<Language> find(String languageKey);
}
| 1,052 | 36.607143 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/language/LanguageRepositoryImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.language;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.sonar.api.resources.Language;
import org.springframework.beans.factory.annotation.Autowired;
/**
* Implementation of {@link LanguageRepository} which find {@link Language} instances available in the container.
*/
public class LanguageRepositoryImpl implements LanguageRepository {
private final Map<String, Language> languagesByKey;
@Autowired(required = false)
public LanguageRepositoryImpl() {
this.languagesByKey = Collections.emptyMap();
}
@Autowired(required = false)
public LanguageRepositoryImpl(Language... languages) {
this.languagesByKey = Arrays.stream(languages).filter(Objects::nonNull).collect(Collectors.toMap(Language::getKey, Function.identity()));
}
@Override
public Optional<Language> find(String languageKey) {
return Optional.ofNullable(languagesByKey.get(languageKey));
}
}
| 1,944 | 35.018519 | 141 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/language/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.language;
import javax.annotation.ParametersAreNonnullByDefault;
| 982 | 39.958333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/locations/flow/Flow.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.locations.flow;
import java.util.List;
public class Flow {
private List<Location> locations;
public Flow() {
// nothing to do
}
public List<Location> getLocations() {
return locations;
}
public void setLocations(List<Location> locations) {
this.locations = locations;
}
}
| 1,188 | 29.487179 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/locations/flow/FlowGenerator.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.locations.flow;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.db.protobuf.DbCommons;
import org.sonar.db.protobuf.DbIssues;
import static java.util.stream.Collectors.toCollection;
public class FlowGenerator {
private final TreeRootHolder treeRootHolder;
public FlowGenerator(TreeRootHolder treeRootHolder) {
this.treeRootHolder = treeRootHolder;
}
public List<Flow> convertFlows(String componentName, @Nullable DbIssues.Locations issueLocations) {
if (issueLocations == null) {
return Collections.emptyList();
}
return issueLocations.getFlowList().stream()
.map(sourceFlow -> toFlow(componentName, sourceFlow))
.collect(Collectors.toCollection(LinkedList::new));
}
private Flow toFlow(String componentName, DbIssues.Flow sourceFlow) {
Flow flow = new Flow();
List<Location> locations = getFlowLocations(componentName, sourceFlow);
flow.setLocations(locations);
return flow;
}
private List<Location> getFlowLocations(String componentName, DbIssues.Flow sourceFlow) {
return sourceFlow.getLocationList().stream()
.map(sourceLocation -> toLocation(componentName, sourceLocation))
.collect(toCollection(LinkedList::new));
}
private Location toLocation(String componentName, DbIssues.Location sourceLocation) {
Location location = new Location();
Component locationComponent = treeRootHolder.getComponentByUuid(sourceLocation.getComponentId());
String filePath = Optional.ofNullable(locationComponent).map(Component::getName).orElse(componentName);
location.setFilePath(filePath);
location.setMessage(sourceLocation.getMsg());
TextRange textRange = getTextRange(sourceLocation.getTextRange(), sourceLocation.getChecksum());
location.setTextRange(textRange);
return location;
}
private static TextRange getTextRange(DbCommons.TextRange source, String checksum) {
TextRange textRange = new TextRange();
textRange.setStartLine(source.getStartLine());
textRange.setStartLineOffset(source.getStartOffset());
textRange.setEndLine(source.getEndLine());
textRange.setEndLineOffset(source.getEndOffset());
textRange.setHash(checksum);
return textRange;
}
}
| 3,369 | 38.186047 | 107 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/locations/flow/Location.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.locations.flow;
public class Location {
private String filePath;
private String message;
private TextRange textRange;
public Location() {
// nothing to do
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public TextRange getTextRange() {
return textRange;
}
public void setTextRange(TextRange textRange) {
this.textRange = textRange;
}
}
| 1,480 | 25.927273 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/locations/flow/TextRange.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.locations.flow;
public class TextRange {
private int startLine;
private int startLineOffset;
private int endLine;
private int endLineOffset;
private String hash;
public TextRange() {
// nothing to do
}
public int getStartLine() {
return startLine;
}
public void setStartLine(int startLine) {
this.startLine = startLine;
}
public int getStartLineOffset() {
return startLineOffset;
}
public void setStartLineOffset(int startLineOffset) {
this.startLineOffset = startLineOffset;
}
public int getEndLine() {
return endLine;
}
public void setEndLine(int endLine) {
this.endLine = endLine;
}
public int getEndLineOffset() {
return endLineOffset;
}
public void setEndLineOffset(int endLineOffset) {
this.endLineOffset = endLineOffset;
}
public String getHash() {
return hash;
}
public void setHash(String hash) {
this.hash = hash;
}
}
| 1,824 | 23.662162 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/locations/flow/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.locations.flow;
import javax.annotation.ParametersAreNonnullByDefault;
| 988 | 40.208333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/measure/BatchMeasureToMeasure.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.measure;
import java.util.Objects;
import java.util.Optional;
import javax.annotation.Nullable;
import org.sonar.ce.task.projectanalysis.metric.Metric;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.protocol.output.ScannerReport.Measure.ValueCase;
import static java.util.Optional.of;
import static org.apache.commons.lang.StringUtils.trimToNull;
public class BatchMeasureToMeasure {
public Optional<Measure> toMeasure(@Nullable ScannerReport.Measure batchMeasure, Metric metric) {
Objects.requireNonNull(metric);
if (batchMeasure == null) {
return Optional.empty();
}
Measure.NewMeasureBuilder builder = Measure.newMeasureBuilder();
switch (metric.getType().getValueType()) {
case INT:
return toIntegerMeasure(builder, batchMeasure);
case LONG:
return toLongMeasure(builder, batchMeasure);
case DOUBLE:
return toDoubleMeasure(builder, batchMeasure);
case BOOLEAN:
return toBooleanMeasure(builder, batchMeasure);
case STRING:
return toStringMeasure(builder, batchMeasure);
case LEVEL:
return toLevelMeasure(builder, batchMeasure);
case NO_VALUE:
return toNoValueMeasure(builder);
default:
throw new IllegalArgumentException("Unsupported Measure.ValueType " + metric.getType().getValueType());
}
}
private static Optional<Measure> toIntegerMeasure(Measure.NewMeasureBuilder builder, ScannerReport.Measure batchMeasure) {
if (batchMeasure.getValueCase() == ValueCase.VALUE_NOT_SET) {
return toNoValueMeasure(builder);
}
return of(builder.create(batchMeasure.getIntValue().getValue(), trimToNull(batchMeasure.getIntValue().getData())));
}
private static Optional<Measure> toLongMeasure(Measure.NewMeasureBuilder builder, ScannerReport.Measure batchMeasure) {
if (batchMeasure.getValueCase() == ValueCase.VALUE_NOT_SET) {
return toNoValueMeasure(builder);
}
return of(builder.create(batchMeasure.getLongValue().getValue(), trimToNull(batchMeasure.getLongValue().getData())));
}
private static Optional<Measure> toDoubleMeasure(Measure.NewMeasureBuilder builder, ScannerReport.Measure batchMeasure) {
if (batchMeasure.getValueCase() == ValueCase.VALUE_NOT_SET) {
return toNoValueMeasure(builder);
}
return of(builder.create(batchMeasure.getDoubleValue().getValue(),
// Decimals are not truncated in scanner report, so an arbitrary decimal scale is applied when reading values from report
org.sonar.api.measures.Metric.MAX_DECIMAL_SCALE, trimToNull(batchMeasure.getDoubleValue().getData())));
}
private static Optional<Measure> toBooleanMeasure(Measure.NewMeasureBuilder builder, ScannerReport.Measure batchMeasure) {
if (batchMeasure.getValueCase() == ValueCase.VALUE_NOT_SET) {
return toNoValueMeasure(builder);
}
return of(builder.create(batchMeasure.getBooleanValue().getValue(), trimToNull(batchMeasure.getBooleanValue().getData())));
}
private static Optional<Measure> toStringMeasure(Measure.NewMeasureBuilder builder, ScannerReport.Measure batchMeasure) {
if (batchMeasure.getValueCase() == ValueCase.VALUE_NOT_SET) {
return toNoValueMeasure(builder);
}
return of(builder.create(batchMeasure.getStringValue().getValue()));
}
private static Optional<Measure> toLevelMeasure(Measure.NewMeasureBuilder builder, ScannerReport.Measure batchMeasure) {
if (batchMeasure.getValueCase() == ValueCase.VALUE_NOT_SET) {
return toNoValueMeasure(builder);
}
Optional<Measure.Level> level = Measure.Level.toLevel(batchMeasure.getStringValue().getValue());
if (level.isEmpty()) {
return toNoValueMeasure(builder);
}
return of(builder.create(level.get()));
}
private static Optional<Measure> toNoValueMeasure(Measure.NewMeasureBuilder builder) {
return of(builder.createNoValue());
}
}
| 4,818 | 41.646018 | 127 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/measure/BestValueOptimization.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.measure;
import java.util.function.Predicate;
import javax.annotation.Nonnull;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.metric.Metric;
import static java.util.Objects.requireNonNull;
import static org.sonar.ce.task.projectanalysis.measure.Measure.ValueType.NO_VALUE;
public class BestValueOptimization implements Predicate<Measure> {
private final Metric metric;
private BestValueOptimization(Metric metric) {
this.metric = requireNonNull(metric);
}
public static Predicate<Measure> from(Metric metric, Component component) {
if (isBestValueOptimized(metric) && isBestValueOptimized(component)) {
return new BestValueOptimization(metric);
}
return x -> false;
}
private static boolean isBestValueOptimized(Metric metric) {
return metric.isBestValueOptimized();
}
private static boolean isBestValueOptimized(Component component) {
return component.getType() == Component.Type.FILE;
}
@Override
public boolean test(@Nonnull Measure measure) {
return isBestValueOptimized(measure);
}
private boolean isBestValueOptimized(Measure measure) {
return measure.getData() == null
&& !measure.hasQualityGateStatus()
&& (measure.getValueType() == NO_VALUE || isBestValue(measure, metric.getBestValue()));
}
private static boolean isBestValue(Measure measure, Double bestValue) {
switch (measure.getValueType()) {
case BOOLEAN:
return (bestValue.intValue() == 1) == measure.getBooleanValue();
case INT:
return bestValue.intValue() == measure.getIntValue();
case LONG:
return bestValue.longValue() == measure.getLongValue();
case DOUBLE:
return bestValue.compareTo(measure.getDoubleValue()) == 0;
default:
return false;
}
}
}
| 2,729 | 34 | 93 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/measure/LiveMeasureDtoToMeasure.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.measure;
import java.util.Optional;
import javax.annotation.Nullable;
import org.sonar.ce.task.projectanalysis.metric.Metric;
import org.sonar.db.measure.LiveMeasureDto;
import static java.util.Objects.requireNonNull;
import static java.util.Optional.of;
import static org.sonar.ce.task.projectanalysis.measure.Measure.Level.toLevel;
public class LiveMeasureDtoToMeasure {
public Optional<Measure> toMeasure(@Nullable LiveMeasureDto measureDto, Metric metric) {
requireNonNull(metric);
if (measureDto == null) {
return Optional.empty();
}
Double value = measureDto.getValue();
String data = measureDto.getDataAsString();
switch (metric.getType().getValueType()) {
case INT:
return toIntegerMeasure(value, data);
case LONG:
return toLongMeasure(value, data);
case DOUBLE:
return toDoubleMeasure(value, data);
case BOOLEAN:
return toBooleanMeasure(value, data);
case STRING:
return toStringMeasure(data);
case LEVEL:
return toLevelMeasure(data);
case NO_VALUE:
return toNoValueMeasure();
default:
throw new IllegalArgumentException("Unsupported Measure.ValueType " + metric.getType().getValueType());
}
}
private static Optional<Measure> toIntegerMeasure(@Nullable Double value, @Nullable String data) {
if (value == null) {
return toNoValueMeasure();
}
return of(Measure.newMeasureBuilder().create(value.intValue(), data));
}
private static Optional<Measure> toLongMeasure(@Nullable Double value, @Nullable String data) {
if (value == null) {
return toNoValueMeasure();
}
return of(Measure.newMeasureBuilder().create(value.longValue(), data));
}
private static Optional<Measure> toDoubleMeasure(@Nullable Double value, @Nullable String data) {
if (value == null) {
return toNoValueMeasure();
}
return of(Measure.newMeasureBuilder().create(value, org.sonar.api.measures.Metric.MAX_DECIMAL_SCALE, data));
}
private static Optional<Measure> toBooleanMeasure(@Nullable Double value, @Nullable String data) {
if (value == null) {
return toNoValueMeasure();
}
return of(Measure.newMeasureBuilder().create(Double.compare(value, 1.0D) == 0, data));
}
private static Optional<Measure> toStringMeasure(@Nullable String data) {
if (data == null) {
return toNoValueMeasure();
}
return of(Measure.newMeasureBuilder().create(data));
}
private static Optional<Measure> toLevelMeasure(@Nullable String data) {
if (data == null) {
return toNoValueMeasure();
}
Optional<Measure.Level> level = toLevel(data);
if (!level.isPresent()) {
return toNoValueMeasure();
}
return of(Measure.newMeasureBuilder().create(level.get()));
}
private static Optional<Measure> toNoValueMeasure() {
return of(Measure.newMeasureBuilder().createNoValue());
}
}
| 3,825 | 33.468468 | 112 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/measure/MapBasedRawMeasureRepository.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.measure;
import gnu.trove.map.hash.THashMap;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.metric.Metric;
import static com.google.common.base.Preconditions.checkArgument;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
/**
* Map based implementation of MeasureRepository which supports only raw measures.
* Intended to be used as a delegate of other MeasureRepository implementations (hence the final keyword).
*/
public final class MapBasedRawMeasureRepository<T> implements MeasureRepository {
private final Function<Component, T> componentToKey;
private final Map<T, Map<String, Measure>> measures = new THashMap<>();
public MapBasedRawMeasureRepository(Function<Component, T> componentToKey) {
this.componentToKey = requireNonNull(componentToKey);
}
/**
* @throws UnsupportedOperationException all the time, not supported
*/
@Override
public Optional<Measure> getBaseMeasure(Component component, Metric metric) {
throw new UnsupportedOperationException("This implementation of MeasureRepository supports only raw measures");
}
@Override
public Optional<Measure> getRawMeasure(final Component component, final Metric metric) {
// fail fast
requireNonNull(component);
requireNonNull(metric);
return find(component, metric);
}
@Override
public void add(Component component, Metric metric, Measure measure) {
requireNonNull(component);
checkValueTypeConsistency(metric, measure);
Optional<Measure> existingMeasure = find(component, metric);
if (existingMeasure.isPresent()) {
throw new UnsupportedOperationException(
format(
"a measure can be set only once for a specific Component (key=%s), Metric (key=%s). Use update method",
component.getKey(),
metric.getKey()));
}
add(component, metric, measure, OverridePolicy.OVERRIDE);
}
@Override
public void update(Component component, Metric metric, Measure measure) {
requireNonNull(component);
checkValueTypeConsistency(metric, measure);
Optional<Measure> existingMeasure = find(component, metric);
if (!existingMeasure.isPresent()) {
throw new UnsupportedOperationException(
format(
"a measure can be updated only if one already exists for a specific Component (key=%s), Metric (key=%s). Use add method",
component.getKey(),
metric.getKey()));
}
add(component, metric, measure, OverridePolicy.OVERRIDE);
}
private static void checkValueTypeConsistency(Metric metric, Measure measure) {
checkArgument(
measure.getValueType() == Measure.ValueType.NO_VALUE || measure.getValueType() == metric.getType().getValueType(),
"Measure's ValueType (%s) is not consistent with the Metric's ValueType (%s)",
measure.getValueType(), metric.getType().getValueType());
}
@Override
public Map<String, Measure> getRawMeasures(Component component) {
T componentKey = componentToKey.apply(component);
return measures.getOrDefault(componentKey, Collections.emptyMap());
}
private Optional<Measure> find(Component component, Metric metric) {
T componentKey = componentToKey.apply(component);
Map<String, Measure> measuresPerMetric = measures.get(componentKey);
if (measuresPerMetric == null) {
return Optional.empty();
}
return Optional.ofNullable(measuresPerMetric.get(metric.getKey()));
}
public void add(Component component, Metric metric, Measure measure, OverridePolicy overridePolicy) {
requireNonNull(component);
requireNonNull(measure);
requireNonNull(measure);
requireNonNull(overridePolicy);
T componentKey = componentToKey.apply(component);
Map<String, Measure> measuresPerMetric = measures.computeIfAbsent(componentKey, key -> new THashMap<>());
if (!measuresPerMetric.containsKey(metric.getKey()) || overridePolicy == OverridePolicy.OVERRIDE) {
measuresPerMetric.put(metric.getKey(), measure);
}
}
public enum OverridePolicy {
OVERRIDE, DO_NOT_OVERRIDE
}
}
| 5,133 | 37.313433 | 131 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/measure/Measure.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.measure;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.ce.task.projectanalysis.util.cache.DoubleCache;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
public interface Measure {
enum ValueType {
NO_VALUE, BOOLEAN, INT, LONG, DOUBLE, STRING, LEVEL
}
enum Level {
OK("Passed"),
ERROR("Failed"),
/**
* @deprecated since 7.6, warning quality gates doesn't exist anymore on new analysis
*/
@Deprecated
WARN("Orange");
private final String label;
Level(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
public static Optional<Level> toLevel(@Nullable String level) {
if (level == null) {
return Optional.empty();
}
try {
return Optional.of(Level.valueOf(level));
} catch (IllegalArgumentException e) {
return Optional.empty();
}
}
}
/**
* The type of value stored in the measure.
*/
ValueType getValueType();
/**
* The value of this measure as a boolean if the type is {@link Measure.ValueType#BOOLEAN}.
*
* @throws IllegalStateException if the value type of the measure is not {@link Measure.ValueType#BOOLEAN}
*/
boolean getBooleanValue();
/**
* The value of this measure as a int if the type is {@link Measure.ValueType#INT}.
*
* @throws IllegalStateException if the value type of the measure is not {@link Measure.ValueType#INT}
*/
int getIntValue();
/**
* The value of this measure as a long if the type is {@link Measure.ValueType#LONG}.
*
* @throws IllegalStateException if the value type of the measure is not {@link Measure.ValueType#LONG}
*/
long getLongValue();
/**
* The value of this measure as a double if the type is {@link Measure.ValueType#DOUBLE}.
*
* @throws IllegalStateException if the value type of the measure is not {@link Measure.ValueType#DOUBLE}
*/
double getDoubleValue();
/**
* The value of this measure as a String if the type is {@link Measure.ValueType#STRING}.
*
* @throws IllegalStateException if the value type of the measure is not {@link Measure.ValueType#STRING}
*/
String getStringValue();
/**
* The value of this measure as a Level if the type is {@link Measure.ValueType#LEVEL}.
*
* @throws IllegalStateException if the value type of the measure is not {@link Measure.ValueType#LEVEL}
*/
Level getLevelValue();
/**
* The data of this measure if it exists.
* <p>
* If the measure type is {@link Measure.ValueType#STRING}, the value returned by this function is the same as {@link #getStringValue()}.
* </p>
*/
String getData();
/**
* Any Measure, which ever is its value type, can have a QualityGate status.
*/
boolean hasQualityGateStatus();
/**
* The QualityGate status for this measure.
* <strong>Don't call this method unless you've checked the result of {@link #hasQualityGateStatus()} first</strong>
*
* @throws IllegalStateException if the measure has no QualityGate status
*/
QualityGateStatus getQualityGateStatus();
default boolean isEmpty() {
return getValueType() == ValueType.NO_VALUE && getData() == null;
}
static NewMeasureBuilder newMeasureBuilder() {
return new NewMeasureBuilder();
}
static UpdateMeasureBuilder updatedMeasureBuilder(Measure measure) {
return new UpdateMeasureBuilder(measure);
}
class MeasureImpl implements Measure {
private final ValueType valueType;
@CheckForNull
private final Double value;
@CheckForNull
private final String data;
@CheckForNull
private final Level dataLevel;
@CheckForNull
private final QualityGateStatus qualityGateStatus;
private MeasureImpl(ValueType valueType, @Nullable Double value, @Nullable String data, @Nullable Level dataLevel, @Nullable QualityGateStatus qualityGateStatus) {
this.valueType = valueType;
this.value = DoubleCache.intern(value);
this.data = data;
this.dataLevel = dataLevel;
this.qualityGateStatus = qualityGateStatus;
}
@Override
public ValueType getValueType() {
return valueType;
}
@Override
public boolean getBooleanValue() {
checkValueType(ValueType.BOOLEAN, valueType);
return value != null && value.intValue() == 1;
}
@Override
public int getIntValue() {
checkValueType(ValueType.INT, valueType);
return value.intValue();
}
@Override
public long getLongValue() {
checkValueType(ValueType.LONG, valueType);
return value.longValue();
}
@Override
public double getDoubleValue() {
checkValueType(ValueType.DOUBLE, valueType);
return value;
}
@Override
public String getStringValue() {
checkValueType(ValueType.STRING, valueType);
return data;
}
@Override
public Level getLevelValue() {
checkValueType(ValueType.LEVEL, valueType);
return dataLevel;
}
@Override
public String getData() {
return data;
}
@Override
public boolean hasQualityGateStatus() {
return this.qualityGateStatus != null;
}
@Override
public QualityGateStatus getQualityGateStatus() {
checkState(qualityGateStatus != null, "Measure does not have an QualityGate status");
return this.qualityGateStatus;
}
private static void checkValueType(ValueType expected, ValueType valueType) {
if (valueType != expected) {
throw new IllegalStateException(
String.format(
"value can not be converted to %s because current value type is a %s",
expected.toString().toLowerCase(Locale.US),
valueType));
}
}
@Override
public String toString() {
return toStringHelper(this)
.add("valueType", valueType)
.add("value", value)
.add("data", data)
.add("dataLevel", dataLevel)
.add("qualityGateStatus", qualityGateStatus)
.toString();
}
}
class ValueMeasureImpl implements Measure {
private final ValueType valueType;
@CheckForNull
private final Double value;
private ValueMeasureImpl(ValueType valueType, @Nullable Double value) {
this.valueType = valueType;
this.value = DoubleCache.intern(value);
}
@Override
public ValueType getValueType() {
return valueType;
}
@Override
public boolean getBooleanValue() {
MeasureImpl.checkValueType(ValueType.BOOLEAN, valueType);
return value != null && value.intValue() == 1;
}
@Override
public int getIntValue() {
MeasureImpl.checkValueType(ValueType.INT, valueType);
return value.intValue();
}
@Override
public long getLongValue() {
MeasureImpl.checkValueType(ValueType.LONG, valueType);
return value.longValue();
}
@Override
public double getDoubleValue() {
MeasureImpl.checkValueType(ValueType.DOUBLE, valueType);
return value;
}
@Override
public String getStringValue() {
throw new IllegalStateException();
}
@Override
public Level getLevelValue() {
throw new IllegalStateException();
}
@Override
public String getData() {
return null;
}
@Override
public boolean hasQualityGateStatus() {
return false;
}
@Override
public QualityGateStatus getQualityGateStatus() {
throw new IllegalStateException("Measure does not have an QualityGate status");
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
ValueMeasureImpl that = (ValueMeasureImpl) o;
return valueType == that.valueType && Objects.equals(value, that.value);
}
@Override
public int hashCode() {
return Objects.hash(valueType, value);
}
@Override
public String toString() {
return toStringHelper(this)
.add("valueType", valueType)
.add("value", value)
.toString();
}
}
class NoValueMeasureImpl implements Measure {
@Override
public ValueType getValueType() {
return ValueType.NO_VALUE;
}
@Override
public boolean getBooleanValue() {
throw new IllegalStateException();
}
@Override
public int getIntValue() {
throw new IllegalStateException();
}
@Override
public long getLongValue() {
throw new IllegalStateException();
}
@Override
public double getDoubleValue() {
throw new IllegalStateException();
}
@Override
public String getStringValue() {
throw new IllegalStateException();
}
@Override
public Level getLevelValue() {
throw new IllegalStateException();
}
@Override
public String getData() {
return null;
}
@Override
public boolean hasQualityGateStatus() {
return false;
}
@Override
public QualityGateStatus getQualityGateStatus() {
throw new IllegalStateException("Measure does not have an QualityGate status");
}
@Override
public String toString() {
return toStringHelper(this)
.add("valueType", ValueType.NO_VALUE)
.toString();
}
}
class NewMeasureBuilder {
private QualityGateStatus qualityGateStatus;
public NewMeasureBuilder setQualityGateStatus(QualityGateStatus qualityGateStatus) {
this.qualityGateStatus = requireNonNull(qualityGateStatus, "QualityGateStatus can not be set to null");
return this;
}
public Measure create(boolean value, @Nullable String data) {
return createInternal(ValueType.BOOLEAN, value ? 1.0D : 0.0D, data);
}
public Measure create(boolean value) {
return create(value, null);
}
public Measure create(int value, @Nullable String data) {
return createInternal(ValueType.INT, value, data);
}
public Measure create(int value) {
return create(value, null);
}
public Measure create(long value, @Nullable String data) {
return createInternal(ValueType.LONG, value, data);
}
public Measure create(long value) {
return create(value, null);
}
public Measure create(double value, int decimalScale, @Nullable String data) {
checkArgument(!Double.isNaN(value), "NaN is not allowed as a Measure value");
double scaledValue = scale(value, decimalScale);
return createInternal(ValueType.DOUBLE, scaledValue, data);
}
private Measure createInternal(ValueType type, double value, @Nullable String data) {
if (data == null && qualityGateStatus == null) {
return new ValueMeasureImpl(type, value);
}
return new MeasureImpl(type, value, data, null, qualityGateStatus);
}
public Measure create(double value, int decimalScale) {
return create(value, decimalScale, null);
}
public Measure create(double value) {
return create(value, org.sonar.api.measures.Metric.MAX_DECIMAL_SCALE);
}
public Measure create(String value) {
return new MeasureImpl(ValueType.STRING, null, requireNonNull(value), null, qualityGateStatus);
}
public Measure create(Level level) {
return new MeasureImpl(ValueType.LEVEL, null, null, requireNonNull(level), qualityGateStatus);
}
public Measure createNoValue() {
if (qualityGateStatus == null) {
return new NoValueMeasureImpl();
}
return new MeasureImpl(ValueType.NO_VALUE, null, null, null, qualityGateStatus);
}
private static double scale(double value, int decimalScale) {
BigDecimal bd = BigDecimal.valueOf(value);
return bd.setScale(decimalScale, RoundingMode.HALF_UP).doubleValue();
}
}
final class UpdateMeasureBuilder {
private final Measure source;
private QualityGateStatus qualityGateStatus;
public UpdateMeasureBuilder(Measure source) {
this.source = requireNonNull(source, "Can not create a measure from null");
}
/**
* Sets the QualityGateStatus of the updated Measure to create.
*
* @throws NullPointerException if the specified {@link QualityGateStatus} is {@code null}
* @throws UnsupportedOperationException if the source measure already has a {@link QualityGateStatus}
*/
public UpdateMeasureBuilder setQualityGateStatus(QualityGateStatus qualityGateStatus) {
if (source.hasQualityGateStatus()) {
throw new UnsupportedOperationException("QualityGate status can not be changed if already set on source Measure");
}
this.qualityGateStatus = requireNonNull(qualityGateStatus, "QualityGateStatus can not be set to null");
return this;
}
public Measure create() {
Double value;
switch (source.getValueType()) {
case DOUBLE:
value = source.getDoubleValue();
break;
case INT:
value = (double) source.getIntValue();
break;
case LONG:
value = (double) source.getLongValue();
break;
case BOOLEAN:
value = source.getBooleanValue() ? 1.0 : 0.0;
break;
case NO_VALUE:
default:
value = null;
break;
}
Level level = source.getValueType() == ValueType.LEVEL ? source.getLevelValue() : null;
QualityGateStatus status = source.hasQualityGateStatus() ? source.getQualityGateStatus() : qualityGateStatus;
return new MeasureImpl(source.getValueType(), value, source.getData(), level, status);
}
}
}
| 14,860 | 27.414914 | 167 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/measure/MeasureComputersHolder.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.measure;
import org.sonar.ce.task.projectanalysis.api.measurecomputer.MeasureComputerWrapper;
public interface MeasureComputersHolder {
/**
* Return the list of measure computers sorted by the way they should be executed
*
* @throws IllegalStateException if the measure computers haven't been initialized
*/
Iterable<MeasureComputerWrapper> getMeasureComputers();
}
| 1,270 | 37.515152 | 84 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/measure/MeasureComputersHolderImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.measure;
import java.util.Objects;
import java.util.stream.StreamSupport;
import javax.annotation.CheckForNull;
import org.sonar.ce.task.projectanalysis.api.measurecomputer.MeasureComputerWrapper;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
public class MeasureComputersHolderImpl implements MutableMeasureComputersHolder {
@CheckForNull
private Iterable<MeasureComputerWrapper> measureComputers;
@Override
public Iterable<MeasureComputerWrapper> getMeasureComputers() {
checkState(this.measureComputers != null, "Measure computers have not been initialized yet");
return measureComputers;
}
@Override
public void setMeasureComputers(Iterable<MeasureComputerWrapper> measureComputers) {
requireNonNull(measureComputers, "Measure computers cannot be null");
checkState(this.measureComputers == null, "Measure computers have already been initialized");
this.measureComputers = StreamSupport.stream(measureComputers.spliterator(), false).filter(Objects::nonNull).toList();
}
}
| 1,968 | 40.020833 | 122 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/measure/MeasureComputersVisitor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.measure;
import org.sonar.api.ce.measure.MeasureComputer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.ce.task.projectanalysis.api.measurecomputer.MeasureComputerContextImpl;
import org.sonar.ce.task.projectanalysis.api.measurecomputer.MeasureComputerWrapper;
import org.sonar.ce.task.projectanalysis.component.ConfigurationRepository;
import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit;
import org.sonar.ce.task.projectanalysis.component.TypeAwareVisitorAdapter;
import org.sonar.ce.task.projectanalysis.issue.ComponentIssuesRepository;
import org.sonar.ce.task.projectanalysis.metric.MetricRepository;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.FILE;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.SUBVIEW;
import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.POST_ORDER;
public class MeasureComputersVisitor extends TypeAwareVisitorAdapter {
private static final Logger LOGGER = LoggerFactory.getLogger(MeasureComputersVisitor.class);
private final MetricRepository metricRepository;
private final MeasureRepository measureRepository;
private final ConfigurationRepository settings;
private final MeasureComputersHolder measureComputersHolder;
private final ComponentIssuesRepository componentIssuesRepository;
public MeasureComputersVisitor(MetricRepository metricRepository, MeasureRepository measureRepository, ConfigurationRepository settings,
MeasureComputersHolder measureComputersHolder, ComponentIssuesRepository componentIssuesRepository) {
super(CrawlerDepthLimit.reportMaxDepth(FILE).withViewsMaxDepth(SUBVIEW), POST_ORDER);
this.metricRepository = metricRepository;
this.measureRepository = measureRepository;
this.settings = settings;
this.measureComputersHolder = measureComputersHolder;
this.componentIssuesRepository = componentIssuesRepository;
}
@Override
public void visitAny(org.sonar.ce.task.projectanalysis.component.Component component) {
MeasureComputerContextImpl context = new MeasureComputerContextImpl(component, settings, measureRepository, metricRepository, componentIssuesRepository);
for (MeasureComputerWrapper measureComputerWrapper : measureComputersHolder.getMeasureComputers()) {
context.setDefinition(measureComputerWrapper.getDefinition());
MeasureComputer measureComputer = measureComputerWrapper.getComputer();
LOGGER.trace("Measure computer '{}' is computing component {}", measureComputer, component);
measureComputer.compute(context);
}
}
}
| 3,498 | 49.710145 | 157 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/measure/MeasureDtoToMeasure.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.measure;
import java.util.Optional;
import javax.annotation.Nullable;
import org.sonar.ce.task.projectanalysis.metric.Metric;
import org.sonar.db.measure.MeasureDto;
import static java.util.Objects.requireNonNull;
import static java.util.Optional.of;
import static org.sonar.ce.task.projectanalysis.measure.Measure.Level.toLevel;
public class MeasureDtoToMeasure {
public Optional<Measure> toMeasure(@Nullable MeasureDto measureDto, Metric metric) {
requireNonNull(metric);
if (measureDto == null) {
return Optional.empty();
}
Double value = measureDto.getValue();
String data = measureDto.getData();
switch (metric.getType().getValueType()) {
case INT:
return toIntegerMeasure(measureDto, value, data);
case LONG:
return toLongMeasure(measureDto, value, data);
case DOUBLE:
return toDoubleMeasure(measureDto, value, data);
case BOOLEAN:
return toBooleanMeasure(measureDto, value, data);
case STRING:
return toStringMeasure(measureDto, data);
case LEVEL:
return toLevelMeasure(measureDto, data);
case NO_VALUE:
return toNoValueMeasure(measureDto);
default:
throw new IllegalArgumentException("Unsupported Measure.ValueType " + metric.getType().getValueType());
}
}
private static Optional<Measure> toIntegerMeasure(MeasureDto measureDto, @Nullable Double value, String data) {
if (value == null) {
return toNoValueMeasure(measureDto);
}
return of(setCommonProperties(Measure.newMeasureBuilder(), measureDto).create(value.intValue(), data));
}
private static Optional<Measure> toLongMeasure(MeasureDto measureDto, @Nullable Double value, String data) {
if (value == null) {
return toNoValueMeasure(measureDto);
}
return of(setCommonProperties(Measure.newMeasureBuilder(), measureDto).create(value.longValue(), data));
}
private static Optional<Measure> toDoubleMeasure(MeasureDto measureDto, @Nullable Double value, String data) {
if (value == null) {
return toNoValueMeasure(measureDto);
}
return of(setCommonProperties(Measure.newMeasureBuilder(), measureDto)
.create(value, org.sonar.api.measures.Metric.MAX_DECIMAL_SCALE, data));
}
private static Optional<Measure> toBooleanMeasure(MeasureDto measureDto, @Nullable Double value, String data) {
if (value == null) {
return toNoValueMeasure(measureDto);
}
return of(setCommonProperties(Measure.newMeasureBuilder(), measureDto).create(Double.compare(value, 1.0D) == 0, data));
}
private static Optional<Measure> toStringMeasure(MeasureDto measureDto, @Nullable String data) {
if (data == null) {
return toNoValueMeasure(measureDto);
}
return of(setCommonProperties(Measure.newMeasureBuilder(), measureDto).create(data));
}
private static Optional<Measure> toLevelMeasure(MeasureDto measureDto, @Nullable String data) {
if (data == null) {
return toNoValueMeasure(measureDto);
}
Optional<Measure.Level> level = toLevel(data);
if (!level.isPresent()) {
return toNoValueMeasure(measureDto);
}
return of(setCommonProperties(Measure.newMeasureBuilder(), measureDto).create(level.get()));
}
private static Optional<Measure> toNoValueMeasure(MeasureDto measureDto) {
return of(setCommonProperties(Measure.newMeasureBuilder(), measureDto).createNoValue());
}
private static Measure.NewMeasureBuilder setCommonProperties(Measure.NewMeasureBuilder builder, MeasureDto measureDto) {
if (measureDto.getAlertStatus() != null) {
Optional<Measure.Level> qualityGateStatus = toLevel(measureDto.getAlertStatus());
if (qualityGateStatus.isPresent()) {
builder.setQualityGateStatus(new QualityGateStatus(qualityGateStatus.get(), measureDto.getAlertText()));
}
}
return builder;
}
}
| 4,767 | 38.081967 | 123 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/measure/MeasureRepository.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.measure;
import java.util.Map;
import java.util.Optional;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.metric.Metric;
import org.sonar.ce.task.projectanalysis.metric.MetricImpl;
public interface MeasureRepository {
/**
* Retrieves the base measure (ie. the one currently existing in DB) for the specified {@link Component} for
* the specified {@link MetricImpl} if it exists.
* <p>
* This method searches for Measure which are specific to the Component.
* </p>
*
* @throws NullPointerException if either argument is {@code null}
*/
Optional<Measure> getBaseMeasure(Component component, Metric metric);
/**
* Retrieves the measure created during the current analysis for the specified {@link Component} for the specified
* {@link Metric} if it exists (ie. one created by the Compute Engine or the Scanner).
*/
Optional<Measure> getRawMeasure(Component component, Metric metric);
/**
* Returns the {@link Measure}s for the specified {@link Component} mapped by their metric key.
*/
Map<String, Measure> getRawMeasures(Component component);
/**
* Adds the specified measure for the specified Component and Metric. There can be no more than one measure for a
* specific combination of Component, Metric.
*
* @throws NullPointerException if any of the arguments is null
* @throws UnsupportedOperationException when trying to add a measure when one already exists for the specified Component/Metric paar
*/
void add(Component component, Metric metric, Measure measure);
/**
* Updates the specified measure for the specified Component and Metric. There can be no more than one measure for a
* specific combination of Component, Metric.
*
* @throws NullPointerException if any of the arguments is null
* @throws UnsupportedOperationException when trying to update a non existing measure
*/
void update(Component component, Metric metric, Measure measure);
}
| 2,913 | 40.628571 | 135 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/measure/MeasureRepositoryImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.measure;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.sonar.ce.task.projectanalysis.batch.BatchReportReader;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.measure.MapBasedRawMeasureRepository.OverridePolicy;
import org.sonar.ce.task.projectanalysis.metric.Metric;
import org.sonar.ce.task.projectanalysis.metric.MetricRepository;
import org.sonar.ce.task.projectanalysis.metric.ReportMetricValidator;
import org.sonar.core.util.CloseableIterator;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.measure.MeasureDto;
import org.sonar.scanner.protocol.output.ScannerReport;
import static java.util.Objects.requireNonNull;
import static org.sonar.ce.task.projectanalysis.component.ComponentFunctions.toComponentUuid;
public class MeasureRepositoryImpl implements MeasureRepository {
private final MapBasedRawMeasureRepository<String> delegate = new MapBasedRawMeasureRepository<>(toComponentUuid());
private final DbClient dbClient;
private final BatchReportReader reportReader;
private final BatchMeasureToMeasure batchMeasureToMeasure;
private final MetricRepository metricRepository;
private final ReportMetricValidator reportMetricValidator;
private MeasureDtoToMeasure measureTransformer = new MeasureDtoToMeasure();
private final Set<Integer> loadedComponents = new HashSet<>();
public MeasureRepositoryImpl(DbClient dbClient, BatchReportReader reportReader, MetricRepository metricRepository,
ReportMetricValidator reportMetricValidator) {
this.dbClient = dbClient;
this.reportReader = reportReader;
this.reportMetricValidator = reportMetricValidator;
this.batchMeasureToMeasure = new BatchMeasureToMeasure();
this.metricRepository = metricRepository;
}
@Override
public Optional<Measure> getBaseMeasure(Component component, Metric metric) {
// fail fast
requireNonNull(component);
requireNonNull(metric);
try (DbSession dbSession = dbClient.openSession(false)) {
Optional<MeasureDto> measureDto = dbClient.measureDao().selectLastMeasure(dbSession, component.getUuid(), metric.getKey());
if (measureDto.isPresent()) {
return measureTransformer.toMeasure(measureDto.get(), metric);
}
return Optional.empty();
}
}
@Override
public Optional<Measure> getRawMeasure(Component component, Metric metric) {
Optional<Measure> local = delegate.getRawMeasure(component, metric);
if (local.isPresent()) {
return local;
}
// look up in batch after loading (if not yet loaded) measures from batch
loadBatchMeasuresForComponent(component);
return delegate.getRawMeasure(component, metric);
}
@Override
public void add(Component component, Metric metric, Measure measure) {
delegate.add(component, metric, measure);
}
@Override
public void update(Component component, Metric metric, Measure measure) {
delegate.update(component, metric, measure);
}
@Override
public Map<String, Measure> getRawMeasures(Component component) {
loadBatchMeasuresForComponent(component);
return delegate.getRawMeasures(component);
}
private void loadBatchMeasuresForComponent(Component component) {
Integer ref = component.getReportAttributes().getRef();
if (ref == null || !loadedComponents.add(ref)) {
return;
}
try (CloseableIterator<ScannerReport.Measure> readIt = reportReader.readComponentMeasures(component.getReportAttributes().getRef())) {
while (readIt.hasNext()) {
ScannerReport.Measure batchMeasure = readIt.next();
String metricKey = batchMeasure.getMetricKey();
if (reportMetricValidator.validate(metricKey)) {
Metric metric = metricRepository.getByKey(metricKey);
batchMeasureToMeasure.toMeasure(batchMeasure, metric).ifPresent(measure -> delegate.add(component, metric, measure, OverridePolicy.DO_NOT_OVERRIDE));
}
}
}
}
}
| 4,924 | 39.04065 | 159 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/measure/MeasureToMeasureDto.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.measure;
import javax.annotation.CheckForNull;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.metric.Metric;
import org.sonar.db.measure.LiveMeasureDto;
import org.sonar.db.measure.MeasureDto;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
public class MeasureToMeasureDto {
private final AnalysisMetadataHolder analysisMetadataHolder;
private final TreeRootHolder treeRootHolder;
public MeasureToMeasureDto(AnalysisMetadataHolder analysisMetadataHolder, TreeRootHolder treeRootHolder) {
this.analysisMetadataHolder = analysisMetadataHolder;
this.treeRootHolder = treeRootHolder;
}
public MeasureDto toMeasureDto(Measure measure, Metric metric, Component component) {
MeasureDto out = new MeasureDto();
out.setMetricUuid(metric.getUuid());
out.setComponentUuid(component.getUuid());
out.setAnalysisUuid(analysisMetadataHolder.getUuid());
if (measure.hasQualityGateStatus()) {
setAlert(out, measure.getQualityGateStatus());
}
out.setValue(valueAsDouble(measure));
out.setData(data(measure));
return out;
}
public LiveMeasureDto toLiveMeasureDto(Measure measure, Metric metric, Component component) {
LiveMeasureDto out = new LiveMeasureDto();
out.setMetricUuid(metric.getUuid());
out.setComponentUuid(component.getUuid());
out.setProjectUuid(treeRootHolder.getRoot().getUuid());
out.setValue(valueAsDouble(measure));
out.setData(data(measure));
return out;
}
private static void setAlert(MeasureDto measureDto, QualityGateStatus qualityGateStatus) {
measureDto.setAlertStatus(qualityGateStatus.getStatus().name());
measureDto.setAlertText(qualityGateStatus.getText());
}
private static String data(Measure in) {
switch (in.getValueType()) {
case NO_VALUE, BOOLEAN, INT, LONG, DOUBLE:
return in.getData();
case STRING:
return in.getStringValue();
case LEVEL:
return in.getLevelValue().name();
default:
return null;
}
}
/**
* return the numerical value as a double. It's the type used in db.
* Returns null if no numerical value found
*/
@CheckForNull
private static Double valueAsDouble(Measure measure) {
return switch (measure.getValueType()) {
case BOOLEAN -> measure.getBooleanValue() ? 1.0D : 0.0D;
case INT -> (double) measure.getIntValue();
case LONG -> (double) measure.getLongValue();
case DOUBLE -> measure.getDoubleValue();
default -> null;
};
}
}
| 3,530 | 35.78125 | 108 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/measure/MutableMeasureComputersHolder.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.measure;
import org.sonar.ce.task.projectanalysis.api.measurecomputer.MeasureComputerWrapper;
/**
* A {@link MeasureComputersHolder} which value can be set only once.
*/
public interface MutableMeasureComputersHolder extends MeasureComputersHolder {
/**
* Initializes the measure computers in the holder.
*
* @throws NullPointerException if the specified Iterable is {@code null}
* @throws IllegalStateException if the holder has already been initialized
*/
void setMeasureComputers(Iterable<MeasureComputerWrapper> measureComputers);
}
| 1,446 | 38.108108 | 84 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/measure/PostMeasuresComputationCheck.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.measure;
import org.sonar.api.ExtensionPoint;
import org.sonar.api.ce.ComputeEngineSide;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.component.Component;
/**
* Extension point that is called during processing of a task
* by {@link PostMeasuresComputationChecksStep}.
*
* It is stateless, the same instance is reused for all tasks.
* As a consequence Compute Engine task components can't be injected
* as dependencies.
*/
@ComputeEngineSide
@ExtensionPoint
public interface PostMeasuresComputationCheck {
/**
* This method can make the task fail by throwing a {@link RuntimeException}
*/
void onCheck(Context context);
interface Context {
/**
* Return the project UUID, as returned by {@link AnalysisMetadataHolder#getProject()#getUuid()}.
*
* It means that when analyzing a non main-branch, it will be the UUID of the project, not the UUId of the branch/pull-request.
*/
String getProjectUuid();
/**
* Return the ncloc computed for the current analysis
*/
int getNcloc();
Component getRoot();
}
}
| 2,032 | 31.790323 | 131 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/measure/PostMeasuresComputationChecksStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.measure;
import java.util.Optional;
import org.sonar.api.ce.ComputeEngineSide;
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.TreeRootHolder;
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.springframework.beans.factory.annotation.Autowired;
/**
* Execute {@link PostMeasuresComputationCheck} instances in no specific order.
* If an extension fails (throws an exception), consecutive extensions
* won't be called.
*/
@ComputeEngineSide
public class PostMeasuresComputationChecksStep implements ComputationStep {
private final TreeRootHolder treeRootHolder;
private final MetricRepository metricRepository;
private final MeasureRepository measureRepository;
private final AnalysisMetadataHolder analysisMetadataHolder;
private final PostMeasuresComputationCheck[] extensions;
@Autowired(required = false)
public PostMeasuresComputationChecksStep(TreeRootHolder treeRootHolder, MetricRepository metricRepository, MeasureRepository measureRepository,
AnalysisMetadataHolder analysisMetadataHolder, PostMeasuresComputationCheck[] extensions) {
this.treeRootHolder = treeRootHolder;
this.metricRepository = metricRepository;
this.measureRepository = measureRepository;
this.analysisMetadataHolder = analysisMetadataHolder;
this.extensions = extensions;
}
/**
* Used when zero {@link PostMeasuresComputationCheck} are registered into container.
*/
@Autowired(required = false)
public PostMeasuresComputationChecksStep(TreeRootHolder treeRootHolder, MetricRepository metricRepository, MeasureRepository measureRepository,
AnalysisMetadataHolder analysisMetadataHolder) {
this(treeRootHolder, metricRepository, measureRepository, analysisMetadataHolder, new PostMeasuresComputationCheck[0]);
}
@Override
public void execute(ComputationStep.Context context) {
PostMeasuresComputationCheck.Context extensionContext = new ContextImpl();
for (PostMeasuresComputationCheck extension : extensions) {
extension.onCheck(extensionContext);
}
}
@Override
public String getDescription() {
return "Checks executed after computation of measures";
}
private class ContextImpl implements PostMeasuresComputationCheck.Context {
@Override
public String getProjectUuid() {
return analysisMetadataHolder.getProject().getUuid();
}
@Override
public int getNcloc() {
Metric nclocMetric = metricRepository.getByKey(CoreMetrics.NCLOC_KEY);
Optional<Measure> nclocMeasure = measureRepository.getRawMeasure(treeRootHolder.getRoot(), nclocMetric);
return nclocMeasure.map(Measure::getIntValue).orElse(0);
}
@Override public Component getRoot() {
return treeRootHolder.getRoot();
}
}
}
| 3,928 | 38.686869 | 145 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/measure/QualityGateStatus.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.measure;
import com.google.common.base.MoreObjects;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import static java.util.Objects.requireNonNull;
/**
* A QualityGate status has a level and an optional describing text.
*/
@Immutable
public final class QualityGateStatus {
private final Measure.Level status;
@CheckForNull
private final String text;
/**
* Creates a QualityGateStatus without a text.
*/
public QualityGateStatus(Measure.Level status) {
this(status, null);
}
/**
* Creates a QualityGateStatus with a optional text.
*/
public QualityGateStatus(Measure.Level status, @Nullable String text) {
this.status = requireNonNull(status);
this.text = text;
}
public Measure.Level getStatus() {
return status;
}
@CheckForNull
public String getText() {
return text;
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
QualityGateStatus that = (QualityGateStatus) o;
return status == that.status && java.util.Objects.equals(text, that.text);
}
@Override
public int hashCode() {
return java.util.Objects.hash(status, text);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("status", status)
.add("text", text)
.toString();
}
}
| 2,374 | 26.298851 | 78 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.