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/measure/RatingMeasures.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.EnumMap;
import org.sonar.server.measure.Rating;
import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilder;
public class RatingMeasures {
private static final EnumMap<Rating, Measure> ratingMeasureCache;
static {
ratingMeasureCache = new EnumMap<>(Rating.class);
for (Rating r : Rating.values()) {
ratingMeasureCache.put(r, newMeasureBuilder().create(r.getIndex(), r.name()));
}
}
private RatingMeasures() {
// static only
}
public static Measure get(Rating rating) {
return ratingMeasureCache.get(rating);
}
}
| 1,492 | 32.177778 | 84 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/measure/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.measure;
import javax.annotation.ParametersAreNonnullByDefault;
| 981 | 39.916667 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/measure/qualitygatedetails/EvaluatedCondition.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.qualitygatedetails;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import org.sonar.ce.task.projectanalysis.qualitygate.Condition;
import static java.util.Objects.requireNonNull;
@Immutable
public final class EvaluatedCondition {
private final Condition condition;
private final Measure.Level level;
private final String actualValue;
public EvaluatedCondition(Condition condition, Measure.Level level, @Nullable Object actualValue) {
this.condition = requireNonNull(condition);
this.level = requireNonNull(level);
this.actualValue = actualValue == null ? "" : actualValue.toString();
}
public Condition getCondition() {
return condition;
}
public Measure.Level getLevel() {
return level;
}
public String getActualValue() {
return actualValue;
}
}
| 1,784 | 32.679245 | 101 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/measure/qualitygatedetails/QualityGateDetailsData.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.qualitygatedetails;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.util.List;
import java.util.stream.StreamSupport;
import javax.annotation.concurrent.Immutable;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import org.sonar.ce.task.projectanalysis.qualitygate.Condition;
import org.sonar.server.qualitygate.ConditionComparator;
import static java.util.Objects.requireNonNull;
@Immutable
public class QualityGateDetailsData {
private static final String FIELD_LEVEL = "level";
private static final String FIELD_IGNORED_CONDITIONS = "ignoredConditions";
private final Measure.Level level;
private final List<EvaluatedCondition> conditions;
private final boolean ignoredConditions;
public QualityGateDetailsData(Measure.Level level, Iterable<EvaluatedCondition> conditions, boolean ignoredConditions) {
this.level = requireNonNull(level);
this.conditions = StreamSupport.stream(conditions.spliterator(), false)
.sorted(new ConditionComparator<>(c -> c.getCondition().getMetric().getKey()))
.toList();
this.ignoredConditions = ignoredConditions;
}
public String toJson() {
JsonObject details = new JsonObject();
details.addProperty(FIELD_LEVEL, level.toString());
JsonArray conditionResults = new JsonArray();
for (EvaluatedCondition condition : this.conditions) {
conditionResults.add(toJson(condition));
}
details.add("conditions", conditionResults);
details.addProperty(FIELD_IGNORED_CONDITIONS, ignoredConditions);
return details.toString();
}
private static JsonObject toJson(EvaluatedCondition evaluatedCondition) {
Condition condition = evaluatedCondition.getCondition();
JsonObject result = new JsonObject();
result.addProperty("metric", condition.getMetric().getKey());
result.addProperty("op", condition.getOperator().getDbValue());
if (condition.useVariation()) {
// without this for new_ metrics, the UI will show "-" instead of
// the actual value in the QG failure reason
result.addProperty("period", 1);
}
result.addProperty("error", condition.getErrorThreshold());
result.addProperty("actual", evaluatedCondition.getActualValue());
result.addProperty(FIELD_LEVEL, evaluatedCondition.getLevel().name());
return result;
}
}
| 3,226 | 39.3375 | 122 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/measure/qualitygatedetails/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.measure.qualitygatedetails;
import javax.annotation.ParametersAreNonnullByDefault;
| 1,000 | 40.708333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/metric/Metric.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.metric;
import javax.annotation.CheckForNull;
import org.sonar.ce.task.projectanalysis.measure.Measure;
public interface Metric {
/**
* The metric's uuid (ie. its database identifier)
*/
String getUuid();
/**
* The Metric's key is its domain identifier.
*/
String getKey();
String getName();
MetricType getType();
/**
* When Metric is "bestValueOptimized" _and_ the component it belongs to is a FILE, any measure which has the same
* value as the best value of the metric should _not_ be persisted into the DB to save on DB usage.
*/
boolean isBestValueOptimized();
/**
* The best value for the current Metric, if there is any
*/
@CheckForNull
Double getBestValue();
/**
* The decimal scale of float measures. Returned value is greater than or equal zero.
* @throws IllegalStateException if the value type is not decimal (see {@link org.sonar.ce.task.projectanalysis.measure.Measure.ValueType}
*/
int getDecimalScale();
boolean isDeleteHistoricalData();
enum MetricType {
INT(Measure.ValueType.INT),
MILLISEC(Measure.ValueType.LONG),
RATING(Measure.ValueType.INT),
WORK_DUR(Measure.ValueType.LONG),
FLOAT(Measure.ValueType.DOUBLE),
PERCENT(Measure.ValueType.DOUBLE),
BOOL(Measure.ValueType.BOOLEAN),
STRING(Measure.ValueType.STRING),
DISTRIB(Measure.ValueType.STRING),
DATA(Measure.ValueType.STRING),
LEVEL(Measure.ValueType.LEVEL);
private final Measure.ValueType valueType;
MetricType(Measure.ValueType valueType) {
this.valueType = valueType;
}
public Measure.ValueType getValueType() {
return valueType;
}
}
}
| 2,556 | 29.440476 | 140 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/metric/MetricDtoToMetric.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.metric;
import java.util.function.Function;
import javax.annotation.Nonnull;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import org.sonar.ce.task.projectanalysis.util.cache.DoubleCache;
import org.sonar.db.metric.MetricDto;
import static com.google.common.base.MoreObjects.firstNonNull;
public enum MetricDtoToMetric implements Function<MetricDto, Metric> {
INSTANCE;
private static final int DEFAULT_DECIMAL_SCALE = 1;
@Override
@Nonnull
public Metric apply(@Nonnull MetricDto metricDto) {
Metric.MetricType metricType = Metric.MetricType.valueOf(metricDto.getValueType());
Integer decimalScale = null;
if (metricType.getValueType() == Measure.ValueType.DOUBLE) {
decimalScale = firstNonNull(metricDto.getDecimalScale(), DEFAULT_DECIMAL_SCALE);
}
return new MetricImpl(
metricDto.getUuid(), metricDto.getKey(), metricDto.getShortName(), metricType,
decimalScale,
DoubleCache.intern(metricDto.getBestValue()), metricDto.isOptimizedBestValue(),
metricDto.isDeleteHistoricalData());
}
}
| 1,952 | 37.294118 | 87 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/metric/MetricImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.metric;
import java.util.Objects;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
@Immutable
public final class MetricImpl implements Metric {
private final String uuid;
private final String key;
private final String name;
private final MetricType type;
private final Integer decimalScale;
private final Double bestValue;
private final boolean bestValueOptimized;
private boolean deleteHistoricalData;
public MetricImpl(String uuid, String key, String name, MetricType type) {
this(uuid, key, name, type, null, null, false, false);
}
public MetricImpl(String uuid, String key, String name, MetricType type, @Nullable Integer decimalScale,
@Nullable Double bestValue, boolean bestValueOptimized, boolean deleteHistoricalData) {
checkArgument(!bestValueOptimized || bestValue != null, "A BestValue must be specified if Metric is bestValueOptimized");
this.uuid = uuid;
this.key = checkNotNull(key);
this.name = checkNotNull(name);
this.type = checkNotNull(type);
if (type.getValueType() == Measure.ValueType.DOUBLE) {
this.decimalScale = firstNonNull(decimalScale, org.sonar.api.measures.Metric.DEFAULT_DECIMAL_SCALE);
} else {
this.decimalScale = decimalScale;
}
this.bestValueOptimized = bestValueOptimized;
this.bestValue = bestValue;
this.deleteHistoricalData = deleteHistoricalData;
}
@Override
public String getUuid() {
return uuid;
}
@Override
public String getKey() {
return key;
}
@Override
public String getName() {
return name;
}
@Override
public MetricType getType() {
return type;
}
@Override
public int getDecimalScale() {
checkState(decimalScale != null, "Decimal scale is not defined on metric %s", key);
return decimalScale;
}
@Override
@CheckForNull
public Double getBestValue() {
return bestValue;
}
@Override
public boolean isBestValueOptimized() {
return bestValueOptimized;
}
@Override
public boolean isDeleteHistoricalData() {
return deleteHistoricalData;
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MetricImpl metric = (MetricImpl) o;
return Objects.equals(key, metric.key);
}
@Override
public int hashCode() {
return key.hashCode();
}
@Override
public String toString() {
return toStringHelper(this)
.add("uuid", uuid)
.add("key", key)
.add("name", name)
.add("type", type)
.add("bestValue", bestValue)
.add("bestValueOptimized", bestValueOptimized)
.add("deleteHistoricalData", deleteHistoricalData)
.toString();
}
}
| 4,084 | 28.388489 | 125 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/metric/MetricModule.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.metric;
import org.sonar.core.metric.ScannerMetrics;
import org.sonar.core.platform.Module;
public class MetricModule extends Module {
@Override
protected void configureModule() {
add(
ScannerMetrics.class,
ReportMetricValidatorImpl.class,
MetricRepositoryImpl.class);
}
}
| 1,188 | 33.970588 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/metric/MetricRepository.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.metric;
import java.util.List;
import java.util.Optional;
public interface MetricRepository {
/**
* Gets the {@link Metric} with the specific key.
* <p>Since it does not make sense to encounter a reference (ie. a key) to a Metric during processing of
* a new analysis and not finding it in DB (metrics are never deleted), this method will throw an
* IllegalStateException if the metric with the specified key can not be found.</p>
*
* @throws IllegalStateException if no Metric with the specified key is found
* @throws NullPointerException if the specified key is {@code null}
*/
Metric getByKey(String key);
/**
* Gets the {@link Metric} with the specific uuid.
*
* @throws IllegalStateException if no Metric with the specified uuid is found
*/
Metric getByUuid(String uuid);
/**
* Gets the {@link Metric} with the specific uuid if it exists in the repository.
*/
Optional<Metric> getOptionalByUuid(String uuid);
/**
* Get iterable of all {@link Metric}.
*/
Iterable<Metric> getAll();
/**
* Returns all the {@link Metric}s for the specific type.
*/
List<Metric> getMetricsByType(Metric.MetricType type);
}
| 2,075 | 33.032787 | 106 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/metric/MetricRepositoryImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.metric;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.annotation.CheckForNull;
import org.sonar.api.Startable;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.metric.MetricDto;
import static java.util.Objects.requireNonNull;
public class MetricRepositoryImpl implements MetricRepository, Startable {
private final DbClient dbClient;
@CheckForNull
private Map<String, Metric> metricsByKey;
@CheckForNull
private Map<String, Metric> metricsByUuid;
public MetricRepositoryImpl(DbClient dbClient) {
this.dbClient = dbClient;
}
@Override
public void start() {
try (DbSession dbSession = dbClient.openSession(false)) {
List<MetricDto> metricList = dbClient.metricDao().selectEnabled(dbSession);
this.metricsByKey = metricList.stream().map(MetricDtoToMetric.INSTANCE).collect(Collectors.toMap(Metric::getKey, x -> x));
this.metricsByUuid = metricList.stream().map(MetricDtoToMetric.INSTANCE).collect(Collectors.toMap(Metric::getUuid, x -> x));
}
}
@Override
public void stop() {
// nothing to do when stopping
}
@Override
public Metric getByKey(String key) {
requireNonNull(key);
verifyMetricsInitialized();
Metric res = this.metricsByKey.get(key);
if (res == null) {
throw new IllegalStateException(String.format("Metric with key '%s' does not exist", key));
}
return res;
}
@Override
public Metric getByUuid(String uuid) {
return getOptionalByUuid(uuid)
.orElseThrow(() -> new IllegalStateException(String.format("Metric with uuid '%s' does not exist", uuid)));
}
@Override
public Optional<Metric> getOptionalByUuid(String uuid) {
verifyMetricsInitialized();
return Optional.ofNullable(this.metricsByUuid.get(uuid));
}
@Override
public Iterable<Metric> getAll() {
return metricsByKey.values();
}
@Override
public List<Metric> getMetricsByType(Metric.MetricType type) {
verifyMetricsInitialized();
return metricsByKey.values().stream().filter(m -> m.getType() == type).toList();
}
private void verifyMetricsInitialized() {
if (this.metricsByKey == null) {
throw new IllegalStateException("Metric cache has not been initialized");
}
}
}
| 3,211 | 30.184466 | 130 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/metric/ReportMetricValidator.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.metric;
/**
* Validate metric to know if it can be read from the batch
*/
public interface ReportMetricValidator {
boolean validate(String metricKey);
}
| 1,045 | 33.866667 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/metric/ReportMetricValidatorImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.metric;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.measures.Metric;
import org.sonar.core.metric.ScannerMetrics;
public class ReportMetricValidatorImpl implements ReportMetricValidator {
private static final Logger LOG = LoggerFactory.getLogger(ReportMetricValidatorImpl.class);
private final Map<String, Metric> metricByKey;
private final Set<String> alreadyLoggedMetricKeys = new HashSet<>();
public ReportMetricValidatorImpl(ScannerMetrics scannerMetrics) {
this.metricByKey = scannerMetrics.getMetrics().stream().collect(Collectors.toMap(Metric::getKey, Function.identity()));
}
@Override
public boolean validate(String metricKey) {
Metric metric = metricByKey.get(metricKey);
if (metric == null) {
if (!alreadyLoggedMetricKeys.contains(metricKey)) {
LOG.debug("The metric '{}' is ignored and should not be send in the batch report", metricKey);
alreadyLoggedMetricKeys.add(metricKey);
}
return false;
}
return true;
}
}
| 2,062 | 36.509091 | 123 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/metric/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.metric;
import javax.annotation.ParametersAreNonnullByDefault;
| 980 | 39.875 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/notification/NotificationFactory.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.notification;
import com.google.common.collect.ImmutableMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.api.ce.ComputeEngineSide;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.utils.Durations;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.analysis.Branch;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.DepthTraversalTypeAwareCrawler;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.projectanalysis.component.TypeAwareVisitorAdapter;
import org.sonar.ce.task.projectanalysis.issue.RuleRepository;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.db.user.UserDto;
import org.sonar.server.issue.notification.IssuesChangesNotification;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.AnalysisChange;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.ChangedIssue;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.Project;
import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.User;
import org.sonar.server.issue.notification.IssuesChangesNotificationSerializer;
import org.sonar.server.issue.notification.MyNewIssuesNotification;
import org.sonar.server.issue.notification.NewIssuesNotification;
import org.sonar.server.issue.notification.NewIssuesNotification.DetailsSupplier;
import org.sonar.server.issue.notification.NewIssuesNotification.RuleDefinition;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.PRE_ORDER;
import static org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit.FILE;
import static org.sonar.db.component.BranchType.PULL_REQUEST;
@ComputeEngineSide
public class NotificationFactory {
private final TreeRootHolder treeRootHolder;
private final AnalysisMetadataHolder analysisMetadataHolder;
private final RuleRepository ruleRepository;
private final Durations durations;
private final IssuesChangesNotificationSerializer issuesChangesSerializer;
private Map<String, Component> componentsByUuid;
public NotificationFactory(TreeRootHolder treeRootHolder, AnalysisMetadataHolder analysisMetadataHolder,
RuleRepository ruleRepository, Durations durations, IssuesChangesNotificationSerializer issuesChangesSerializer) {
this.treeRootHolder = treeRootHolder;
this.analysisMetadataHolder = analysisMetadataHolder;
this.ruleRepository = ruleRepository;
this.durations = durations;
this.issuesChangesSerializer = issuesChangesSerializer;
}
public MyNewIssuesNotification newMyNewIssuesNotification(Map<String, UserDto> assigneesByUuid) {
verifyAssigneesByUuid(assigneesByUuid);
return new MyNewIssuesNotification(durations, new DetailsSupplierImpl(assigneesByUuid));
}
public NewIssuesNotification newNewIssuesNotification(Map<String, UserDto> assigneesByUuid) {
verifyAssigneesByUuid(assigneesByUuid);
return new NewIssuesNotification(durations, new DetailsSupplierImpl(assigneesByUuid));
}
public IssuesChangesNotification newIssuesChangesNotification(Set<DefaultIssue> issues, Map<String, UserDto> assigneesByUuid) {
AnalysisChange change = new AnalysisChange(analysisMetadataHolder.getAnalysisDate());
Set<ChangedIssue> changedIssues = issues.stream()
.map(issue -> new ChangedIssue.Builder(issue.key())
.setAssignee(getAssignee(issue.assignee(), assigneesByUuid))
.setNewResolution(issue.resolution())
.setNewStatus(issue.status())
.setRule(getRuleByRuleKey(issue.ruleKey()))
.setProject(getProject())
.build())
.collect(Collectors.toSet());
return issuesChangesSerializer.serialize(new IssuesChangesNotificationBuilder(changedIssues, change));
}
@CheckForNull
public User getAssignee(@Nullable String assigneeUuid, Map<String, UserDto> assigneesByUuid) {
if (assigneeUuid == null) {
return null;
}
UserDto dto = assigneesByUuid.get(assigneeUuid);
checkState(dto != null, "Can not find DTO for assignee uuid %s", assigneeUuid);
return new User(dto.getUuid(), dto.getLogin(), dto.getName());
}
private IssuesChangesNotificationBuilder.Rule getRuleByRuleKey(RuleKey ruleKey) {
return ruleRepository.findByKey(ruleKey)
.map(t -> new IssuesChangesNotificationBuilder.Rule(ruleKey, t.getType(), t.getName()))
.orElseThrow(() -> new IllegalStateException("Can not find rule " + ruleKey + " in RuleRepository"));
}
private Project getProject() {
Component project = treeRootHolder.getRoot();
Branch branch = analysisMetadataHolder.getBranch();
Project.Builder builder = new Project.Builder(project.getUuid())
.setKey(project.getKey())
.setProjectName(project.getName());
if (branch.getType() != PULL_REQUEST && !branch.isMain()) {
builder.setBranchName(branch.getName());
}
return builder.build();
}
private static void verifyAssigneesByUuid(Map<String, UserDto> assigneesByUuid) {
requireNonNull(assigneesByUuid, "assigneesByUuid can't be null");
}
private class DetailsSupplierImpl implements DetailsSupplier {
private final Map<String, UserDto> assigneesByUuid;
private DetailsSupplierImpl(Map<String, UserDto> assigneesByUuid) {
this.assigneesByUuid = assigneesByUuid;
}
@Override
public Optional<RuleDefinition> getRuleDefinitionByRuleKey(RuleKey ruleKey) {
requireNonNull(ruleKey, "ruleKey can't be null");
return ruleRepository.findByKey(ruleKey)
.map(t -> new RuleDefinition(t.getName(), t.getLanguage()));
}
@Override
public Optional<String> getComponentNameByUuid(String uuid) {
requireNonNull(uuid, "uuid can't be null");
return Optional.ofNullable(lazyLoadComponentsByUuid().get(uuid))
.map(t -> t.getType() == Component.Type.FILE || t.getType() == Component.Type.DIRECTORY ? t.getShortName() : t.getName());
}
private Map<String, Component> lazyLoadComponentsByUuid() {
if (componentsByUuid == null) {
ImmutableMap.Builder<String, Component> builder = ImmutableMap.builder();
new DepthTraversalTypeAwareCrawler(new TypeAwareVisitorAdapter(FILE, PRE_ORDER) {
@Override
public void visitAny(Component any) {
builder.put(any.getUuid(), any);
}
}).visit(treeRootHolder.getRoot());
componentsByUuid = builder.build();
}
return componentsByUuid;
}
@Override
public Optional<String> getUserNameByUuid(String uuid) {
requireNonNull(uuid, "uuid can't be null");
return Optional.ofNullable(assigneesByUuid.get(uuid))
.map(UserDto::getName);
}
}
}
| 8,010 | 44.259887 | 130 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/notification/ReportAnalysisFailureNotification.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.notification;
import javax.annotation.CheckForNull;
import org.sonar.api.notifications.Notification;
public class ReportAnalysisFailureNotification extends Notification {
public static final String TYPE = "ce-report-task-failure";
public ReportAnalysisFailureNotification() {
super(TYPE);
}
@CheckForNull
public String getProjectKey() {
return getFieldValue("project.key");
}
}
| 1,288 | 32.921053 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/notification/ReportAnalysisFailureNotificationBuilder.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.notification;
import javax.annotation.Nullable;
import static java.util.Objects.requireNonNull;
public record ReportAnalysisFailureNotificationBuilder(Project project, Task task, String errorMessage) {
public ReportAnalysisFailureNotificationBuilder(Project project, Task task, @Nullable String errorMessage) {
this.project = requireNonNull(project, "project can't be null");
this.task = requireNonNull(task, "task can't be null");
this.errorMessage = errorMessage;
}
public record Project(String uuid, String key, String name, String branchName) {
public Project(String uuid, String key, String name, @Nullable String branchName) {
this.uuid = requireNonNull(uuid, "uuid can't be null");
this.key = requireNonNull(key, "key can't be null");
this.name = requireNonNull(name, "name can't be null");
this.branchName = branchName;
}
}
public record Task(String uuid, long createdAt, long failedAt) {
public Task(String uuid, long createdAt, long failedAt) {
this.uuid = requireNonNull(uuid, "uuid can't be null");
this.createdAt = createdAt;
this.failedAt = failedAt;
}
}
}
| 2,045 | 38.346154 | 110 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/notification/ReportAnalysisFailureNotificationEmailTemplate.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.notification;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import javax.annotation.CheckForNull;
import org.sonar.api.config.EmailSettings;
import org.sonar.api.notifications.Notification;
import org.sonar.server.issue.notification.EmailMessage;
import org.sonar.server.issue.notification.EmailTemplate;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.sonar.api.utils.DateUtils.formatDateTime;
public class ReportAnalysisFailureNotificationEmailTemplate implements EmailTemplate {
private static final char LINE_RETURN = '\n';
private static final char TAB = '\t';
private final ReportAnalysisFailureNotificationSerializer serializer;
protected final EmailSettings settings;
public ReportAnalysisFailureNotificationEmailTemplate(ReportAnalysisFailureNotificationSerializer serializer, EmailSettings settings) {
this.serializer = serializer;
this.settings = settings;
}
@Override
@CheckForNull
public EmailMessage format(Notification notification) {
if (!(notification instanceof ReportAnalysisFailureNotification)) {
return null;
}
ReportAnalysisFailureNotificationBuilder taskFailureNotification = serializer.fromNotification((ReportAnalysisFailureNotification) notification);
String projectUuid = taskFailureNotification.project().uuid();
String projectFullName = computeProjectFullName(taskFailureNotification.project());
return new EmailMessage()
.setMessageId(notification.getType() + "/" + projectUuid)
.setSubject(subject(projectFullName))
.setPlainTextMessage(message(projectFullName, taskFailureNotification));
}
private static String computeProjectFullName(ReportAnalysisFailureNotificationBuilder.Project project) {
String branchName = project.branchName();
if (branchName != null) {
return String.format("%s (%s)", project.name(), branchName);
}
return project.name();
}
private static String subject(String projectFullName) {
return String.format("%s: Background task in failure", projectFullName);
}
private String message(String projectFullName, ReportAnalysisFailureNotificationBuilder taskFailureNotification) {
ReportAnalysisFailureNotificationBuilder.Project project = taskFailureNotification.project();
ReportAnalysisFailureNotificationBuilder.Task task = taskFailureNotification.task();
StringBuilder res = new StringBuilder();
res.append("Project:").append(TAB).append(projectFullName).append(LINE_RETURN);
res.append("Background task:").append(TAB).append(task.uuid()).append(LINE_RETURN);
res.append("Submission time:").append(TAB).append(formatDateTime(task.createdAt())).append(LINE_RETURN);
res.append("Failure time:").append(TAB).append(formatDateTime(task.failedAt())).append(LINE_RETURN);
String errorMessage = taskFailureNotification.errorMessage();
if (errorMessage != null) {
res.append(LINE_RETURN);
res.append("Error message:").append(TAB).append(errorMessage).append(LINE_RETURN);
}
res.append(LINE_RETURN);
res.append("More details at: ").append(String.format("%s/project/background_tasks?id=%s", settings.getServerBaseURL(), encode(project.key())));
return res.toString();
}
private static String encode(String toEncode) {
try {
return URLEncoder.encode(toEncode, UTF_8.name());
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("Encoding not supported", e);
}
}
}
| 4,388 | 41.201923 | 149 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/notification/ReportAnalysisFailureNotificationHandler.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.notification;
import com.google.common.collect.Multimap;
import java.util.Collection;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.sonar.api.web.UserRole;
import org.sonar.server.notification.EmailNotificationHandler;
import org.sonar.server.notification.NotificationDispatcherMetadata;
import org.sonar.server.notification.NotificationManager;
import org.sonar.server.notification.NotificationManager.SubscriberPermissionsOnProject;
import org.sonar.server.notification.email.EmailNotificationChannel;
import org.sonar.server.notification.email.EmailNotificationChannel.EmailDeliveryRequest;
import static java.util.Collections.emptySet;
import static org.sonar.core.util.stream.MoreCollectors.index;
public class ReportAnalysisFailureNotificationHandler extends EmailNotificationHandler<ReportAnalysisFailureNotification> {
private static final String KEY = "CeReportTaskFailure";
private static final NotificationDispatcherMetadata METADATA = NotificationDispatcherMetadata.create(KEY)
.setProperty(NotificationDispatcherMetadata.GLOBAL_NOTIFICATION, String.valueOf(true))
.setProperty(NotificationDispatcherMetadata.PER_PROJECT_NOTIFICATION, String.valueOf(true));
private static final SubscriberPermissionsOnProject REQUIRED_SUBSCRIBER_PERMISSIONS = new SubscriberPermissionsOnProject(UserRole.ADMIN, UserRole.USER);
private final NotificationManager notificationManager;
public ReportAnalysisFailureNotificationHandler(NotificationManager notificationManager, EmailNotificationChannel emailNotificationChannel) {
super(emailNotificationChannel);
this.notificationManager = notificationManager;
}
@Override
public Optional<NotificationDispatcherMetadata> getMetadata() {
return Optional.of(METADATA);
}
public static NotificationDispatcherMetadata newMetadata() {
return METADATA;
}
@Override
public Class<ReportAnalysisFailureNotification> getNotificationClass() {
return ReportAnalysisFailureNotification.class;
}
@Override
public Set<EmailDeliveryRequest> toEmailDeliveryRequests(Collection<ReportAnalysisFailureNotification> notifications) {
Multimap<String, ReportAnalysisFailureNotification> notificationsByProjectKey = notifications.stream()
.filter(t -> t.getProjectKey() != null)
.collect(index(ReportAnalysisFailureNotification::getProjectKey));
if (notificationsByProjectKey.isEmpty()) {
return emptySet();
}
return notificationsByProjectKey.asMap().entrySet()
.stream()
.flatMap(e -> toEmailDeliveryRequests(e.getKey(), e.getValue()))
.collect(Collectors.toSet());
}
private Stream<? extends EmailDeliveryRequest> toEmailDeliveryRequests(String projectKey, Collection<ReportAnalysisFailureNotification> notifications) {
return notificationManager.findSubscribedEmailRecipients(KEY, projectKey, REQUIRED_SUBSCRIBER_PERMISSIONS)
.stream()
.flatMap(emailRecipient -> notifications.stream()
.map(notification -> new EmailDeliveryRequest(emailRecipient.email(), notification)));
}
}
| 4,016 | 44.134831 | 154 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/notification/ReportAnalysisFailureNotificationModule.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.notification;
import org.sonar.core.platform.Module;
public class ReportAnalysisFailureNotificationModule extends Module {
@Override
protected void configureModule() {
add(
ReportAnalysisFailureNotificationHandler.class,
ReportAnalysisFailureNotificationHandler.newMetadata(),
ReportAnalysisFailureNotificationSerializerImpl.class,
ReportAnalysisFailureNotificationEmailTemplate.class);
}
}
| 1,312 | 37.617647 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/notification/ReportAnalysisFailureNotificationSerializer.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.notification;
public interface ReportAnalysisFailureNotificationSerializer {
ReportAnalysisFailureNotification toNotification(ReportAnalysisFailureNotificationBuilder reportAnalysisFailureNotificationBuilder);
ReportAnalysisFailureNotificationBuilder fromNotification(ReportAnalysisFailureNotification notification);
}
| 1,210 | 43.851852 | 134 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/notification/ReportAnalysisFailureNotificationSerializerImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.notification;
import static java.lang.String.valueOf;
public class ReportAnalysisFailureNotificationSerializerImpl implements ReportAnalysisFailureNotificationSerializer {
private static final String FIELD_PROJECT_UUID = "project.uuid";
private static final String FIELD_PROJECT_KEY = "project.key";
private static final String FIELD_PROJECT_NAME = "project.name";
private static final String FIELD_PROJECT_BRANCH = "project.branchName";
private static final String FIELD_TASK_UUID = "task.uuid";
private static final String FIELD_TASK_CREATED_AT = "task.createdAt";
private static final String FIELD_TASK_FAILED_AT = "task.failedAt";
private static final String FIELD_ERROR_MESSAGE = "error.message";
@Override
public ReportAnalysisFailureNotification toNotification(ReportAnalysisFailureNotificationBuilder reportAnalysisFailureNotificationBuilder) {
ReportAnalysisFailureNotification notification = new ReportAnalysisFailureNotification();
notification
.setFieldValue(FIELD_PROJECT_UUID, reportAnalysisFailureNotificationBuilder.project().uuid())
.setFieldValue(FIELD_PROJECT_KEY, reportAnalysisFailureNotificationBuilder.project().key())
.setFieldValue(FIELD_PROJECT_NAME, reportAnalysisFailureNotificationBuilder.project().name())
.setFieldValue(FIELD_PROJECT_BRANCH, reportAnalysisFailureNotificationBuilder.project().branchName())
.setFieldValue(FIELD_TASK_UUID, reportAnalysisFailureNotificationBuilder.task().uuid())
.setFieldValue(FIELD_TASK_CREATED_AT, valueOf(reportAnalysisFailureNotificationBuilder.task().createdAt()))
.setFieldValue(FIELD_TASK_FAILED_AT, valueOf(reportAnalysisFailureNotificationBuilder.task().failedAt()))
.setFieldValue(FIELD_ERROR_MESSAGE, reportAnalysisFailureNotificationBuilder.errorMessage());
return notification;
}
@Override
public ReportAnalysisFailureNotificationBuilder fromNotification(ReportAnalysisFailureNotification notification) {
return new ReportAnalysisFailureNotificationBuilder(
new ReportAnalysisFailureNotificationBuilder.Project(
notification.getFieldValue(FIELD_PROJECT_UUID),
notification.getFieldValue(FIELD_PROJECT_KEY),
notification.getFieldValue(FIELD_PROJECT_NAME),
notification.getFieldValue(FIELD_PROJECT_BRANCH)),
new ReportAnalysisFailureNotificationBuilder.Task(
notification.getFieldValue(FIELD_TASK_UUID),
Long.valueOf(notification.getFieldValue(FIELD_TASK_CREATED_AT)),
Long.valueOf(notification.getFieldValue(FIELD_TASK_FAILED_AT))),
notification.getFieldValue(FIELD_ERROR_MESSAGE));
}
}
| 3,518 | 53.984375 | 142 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/notification/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.notification;
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/period/NewCodePeriodResolver.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.period;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.MessageException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.component.SnapshotQuery;
import org.sonar.db.event.EventDto;
import org.sonar.db.newcodeperiod.NewCodePeriodDto;
import org.sonar.db.newcodeperiod.NewCodePeriodParser;
import org.sonar.db.newcodeperiod.NewCodePeriodType;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static java.lang.String.format;
import static org.sonar.db.component.SnapshotDto.STATUS_PROCESSED;
import static org.sonar.db.component.SnapshotQuery.SORT_FIELD.BY_DATE;
import static org.sonar.db.component.SnapshotQuery.SORT_ORDER.ASC;
public class NewCodePeriodResolver {
private static final Logger LOG = LoggerFactory.getLogger(NewCodePeriodResolver.class);
private final DbClient dbClient;
private final AnalysisMetadataHolder analysisMetadataHolder;
public NewCodePeriodResolver(DbClient dbClient, AnalysisMetadataHolder analysisMetadataHolder) {
this.dbClient = dbClient;
this.analysisMetadataHolder = analysisMetadataHolder;
}
@CheckForNull
public Period resolve(DbSession dbSession, String branchUuid, NewCodePeriodDto newCodePeriodDto, String projectVersion) {
return toPeriod(newCodePeriodDto.getType(), newCodePeriodDto.getValue(), dbSession, projectVersion, branchUuid);
}
@CheckForNull
private Period toPeriod(NewCodePeriodType type, @Nullable String value, DbSession dbSession, String projectVersion, String rootUuid) {
switch (type) {
case NUMBER_OF_DAYS:
checkNotNullValue(value, type);
Integer days = NewCodePeriodParser.parseDays(value);
return resolveByDays(dbSession, rootUuid, days, value, analysisMetadataHolder.getAnalysisDate());
case PREVIOUS_VERSION:
return resolveByPreviousVersion(dbSession, rootUuid, projectVersion);
case SPECIFIC_ANALYSIS:
checkNotNullValue(value, type);
return resolveBySpecificAnalysis(dbSession, rootUuid, value);
case REFERENCE_BRANCH:
checkNotNullValue(value, type);
return resolveByReferenceBranch(value);
default:
throw new IllegalStateException("Unexpected type: " + type);
}
}
private static Period resolveByReferenceBranch(String value) {
return newPeriod(NewCodePeriodType.REFERENCE_BRANCH, value, null);
}
private Period resolveBySpecificAnalysis(DbSession dbSession, String rootUuid, String value) {
SnapshotDto baseline = dbClient.snapshotDao().selectByUuid(dbSession, value)
.filter(t -> t.getRootComponentUuid().equals(rootUuid))
.orElseThrow(() -> new IllegalStateException("Analysis '" + value + "' of project '" + rootUuid
+ "' defined as the baseline does not exist"));
LOG.debug("Resolving new code period with a specific analysis");
return newPeriod(NewCodePeriodType.SPECIFIC_ANALYSIS, value, baseline.getCreatedAt());
}
private Period resolveByPreviousVersion(DbSession dbSession, String rootComponentUuid, String projectVersion) {
List<EventDto> versions = dbClient.eventDao().selectVersionsByMostRecentFirst(dbSession, rootComponentUuid);
if (versions.isEmpty()) {
return findOldestAnalysis(dbSession, rootComponentUuid);
}
String mostRecentVersion = Optional.ofNullable(versions.iterator().next().getName())
.orElseThrow(() -> new IllegalStateException("selectVersionsByMostRecentFirst returned a DTO which didn't have a name"));
if (versions.size() == 1 && projectVersion.equals(mostRecentVersion)) {
return findOldestAnalysis(dbSession, rootComponentUuid);
}
return resolvePreviousVersion(dbSession, projectVersion, versions, mostRecentVersion);
}
private Period resolveByDays(DbSession dbSession, String rootUuid, Integer days, String value, long referenceDate) {
checkPeriodProperty(days > 0, value, "number of days is <= 0");
List<SnapshotDto> snapshots = dbClient.snapshotDao().selectAnalysesByQuery(dbSession, createCommonQuery(rootUuid)
.setCreatedBefore(referenceDate).setSort(BY_DATE, ASC));
Instant targetDate = DateUtils.addDays(Instant.ofEpochMilli(referenceDate), -days);
LOG.debug("Resolving new code period by {} days: {}", days, supplierToString(() -> logDate(targetDate)));
SnapshotDto snapshot = findNearestSnapshotToTargetDate(snapshots, targetDate);
return newPeriod(NewCodePeriodType.NUMBER_OF_DAYS, String.valueOf((int) days), snapshot.getCreatedAt());
}
private Period resolvePreviousVersion(DbSession dbSession, String currentVersion, List<EventDto> versions, String mostRecentVersion) {
EventDto previousVersion = versions.get(currentVersion.equals(mostRecentVersion) ? 1 : 0);
LOG.debug("Resolving new code period by previous version: {}", previousVersion.getName());
return newPeriod(dbSession, previousVersion);
}
private Period findOldestAnalysis(DbSession dbSession, String rootComponentUuid) {
LOG.debug("Resolving first analysis as new code period as there is only one existing version");
Optional<Period> period = dbClient.snapshotDao().selectOldestAnalysis(dbSession, rootComponentUuid)
.map(dto -> newPeriod(NewCodePeriodType.PREVIOUS_VERSION, null, dto.getCreatedAt()));
ensureNotOnFirstAnalysis(period.isPresent());
return period.get();
}
private Period newPeriod(DbSession dbSession, EventDto previousVersion) {
Optional<Period> period = dbClient.snapshotDao().selectByUuid(dbSession, previousVersion.getAnalysisUuid())
.map(dto -> newPeriod(NewCodePeriodType.PREVIOUS_VERSION, dto.getProjectVersion(), dto.getCreatedAt()));
if (!period.isPresent()) {
throw new IllegalStateException(format("Analysis '%s' for version event '%s' has been deleted",
previousVersion.getAnalysisUuid(), previousVersion.getName()));
}
return period.get();
}
private static Period newPeriod(NewCodePeriodType type, @Nullable String value, @Nullable Long date) {
return new Period(type.name(), value, date);
}
private static Object supplierToString(Supplier<String> s) {
return new Object() {
@Override
public String toString() {
return s.get();
}
};
}
private static SnapshotQuery createCommonQuery(String projectUuid) {
return new SnapshotQuery().setRootComponentUuid(projectUuid).setStatus(STATUS_PROCESSED);
}
private static SnapshotDto findNearestSnapshotToTargetDate(List<SnapshotDto> snapshots, Instant targetDate) {
// FIXME shouldn't this be the first analysis after targetDate?
Duration bestDuration = null;
SnapshotDto nearest = null;
ensureNotOnFirstAnalysis(!snapshots.isEmpty());
for (SnapshotDto snapshot : snapshots) {
Instant createdAt = Instant.ofEpochMilli(snapshot.getCreatedAt());
Duration duration = Duration.between(targetDate, createdAt).abs();
if (bestDuration == null || duration.compareTo(bestDuration) <= 0) {
bestDuration = duration;
nearest = snapshot;
}
}
return nearest;
}
private static void checkPeriodProperty(boolean test, String propertyValue, String testDescription, Object... args) {
if (!test) {
LOG.debug("Invalid code period '{}': {}", propertyValue, supplierToString(() -> format(testDescription, args)));
throw MessageException.of(format("Invalid new code period. '%s' is not one of: " +
"integer > 0, date before current analysis j, \"previous_version\", or version string that exists in the project' \n" +
"Please contact a project administrator to correct this setting", propertyValue));
}
}
private static void ensureNotOnFirstAnalysis(boolean expression) {
checkState(expression, "Attempting to resolve period while no analysis exist for project");
}
private static void checkNotNullValue(@Nullable String value, NewCodePeriodType type) {
checkNotNull(value, "Value can't be null with type %s", type);
}
private static String logDate(Instant instant) {
return DateUtils.formatDate(instant.truncatedTo(ChronoUnit.SECONDS));
}
}
| 9,476 | 44.782609 | 136 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/period/NewCodeReferenceBranchComponentUuids.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.period;
import com.google.common.base.Preconditions;
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;
import org.sonar.db.newcodeperiod.NewCodePeriodType;
/**
* Cache a map between component keys and uuids in the reference branch
*/
public class NewCodeReferenceBranchComponentUuids {
private final DbClient dbClient;
private final AnalysisMetadataHolder analysisMetadataHolder;
private final PeriodHolder periodHolder;
private Map<String, String> referenceBranchComponentsUuidsByKey;
public NewCodeReferenceBranchComponentUuids(AnalysisMetadataHolder analysisMetadataHolder, PeriodHolder periodHolder, DbClient dbClient) {
this.analysisMetadataHolder = analysisMetadataHolder;
this.periodHolder = periodHolder;
this.dbClient = dbClient;
}
private void lazyInit() {
if (referenceBranchComponentsUuidsByKey == null) {
Preconditions.checkState(periodHolder.hasPeriod() && periodHolder.getPeriod().getMode().equals(NewCodePeriodType.REFERENCE_BRANCH.name()));
referenceBranchComponentsUuidsByKey = new HashMap<>();
try (DbSession dbSession = dbClient.openSession(false)) {
String referenceKey = periodHolder.getPeriod().getModeParameter() != null ? periodHolder.getPeriod().getModeParameter() : "";
Optional<BranchDto> opt = dbClient.branchDao().selectByBranchKey(dbSession, analysisMetadataHolder.getProject().getUuid(), referenceKey);
if (opt.isPresent()) {
init(opt.get().getUuid(), dbSession);
}
}
}
}
private void init(String referenceBranchUuid, DbSession dbSession) {
boolean hasReferenceBranchAnalysis = dbClient.snapshotDao().selectLastAnalysisByRootComponentUuid(dbSession, referenceBranchUuid).isPresent();
if (hasReferenceBranchAnalysis) {
List<ComponentDto> components = dbClient.componentDao().selectByBranchUuid(referenceBranchUuid, dbSession);
for (ComponentDto dto : components) {
referenceBranchComponentsUuidsByKey.put(dto.getKey(), dto.uuid());
}
}
}
@CheckForNull
public String getComponentUuid(String key) {
lazyInit();
return referenceBranchComponentsUuidsByKey.get(key);
}
}
| 3,356 | 39.939024 | 146 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/period/Period.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.period;
import java.util.Date;
import java.util.Objects;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import static com.google.common.base.MoreObjects.toStringHelper;
import static java.util.Objects.hash;
import static java.util.Objects.requireNonNull;
import static org.sonar.api.utils.DateUtils.truncateToSeconds;
@Immutable
public class Period {
private final String mode;
private final String modeParameter;
private final Long date;
public Period(String mode, @Nullable String modeParameter, @Nullable Long date) {
this.mode = requireNonNull(mode);
this.modeParameter = modeParameter;
this.date = date;
}
public String getMode() {
return mode;
}
@CheckForNull
public String getModeParameter() {
return modeParameter;
}
@CheckForNull
public Long getDate() {
return date;
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Period period = (Period) o;
return Objects.equals(date, period.date) && Objects.equals(mode, period.mode) && Objects.equals(modeParameter, period.modeParameter);
}
public boolean isOnPeriod(Date date) {
if (this.date == null) {
return false;
}
return date.getTime() > truncateToSeconds(this.date);
}
@Override
public int hashCode() {
return hash(mode, modeParameter, date);
}
@Override
public String toString() {
return toStringHelper(this)
.add("mode", mode)
.add("modeParameter", modeParameter)
.add("date", date)
.toString();
}
}
| 2,585 | 27.108696 | 137 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/period/PeriodHolder.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.period;
/**
* Repository of period used to compute differential measures.
* Here are the steps to retrieve the period :
* - Read the period property ${@link org.sonar.core.config.CorePropertyDefinitions#LEAK_PERIOD}
* - Try to find the matching snapshots from the property
* - If a snapshot is found, the period is added to the repository
*/
public interface PeriodHolder {
/**
* Finds out whether the holder contains a Period
*
* @throws IllegalStateException if the periods haven't been initialized
*/
boolean hasPeriod();
/**
* Finds out whether the holder contains a Period with a date
*
* @throws IllegalStateException if the periods haven't been initialized
*/
boolean hasPeriodDate();
/**
* Retrieve the period from the Holder.
*
* @throws IllegalStateException if the period hasn't been initialized
* @throws IllegalStateException if there is no period
*/
Period getPeriod();
}
| 1,834 | 32.363636 | 96 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/period/PeriodHolderImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.period;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkState;
public class PeriodHolderImpl implements PeriodHolder {
@CheckForNull
private Period period = null;
private boolean initialized = false;
/**
* Initializes the periods in the holder.
*
* @throws IllegalStateException if the holder has already been initialized
*/
public void setPeriod(@Nullable Period period) {
checkState(!initialized, "Period have already been initialized");
this.period = period;
this.initialized = true;
}
@Override
public boolean hasPeriod() {
checkHolderIsInitialized();
return period != null;
}
@Override
public boolean hasPeriodDate() {
checkHolderIsInitialized();
return period != null && period.getDate() != null;
}
@Override
public Period getPeriod() {
checkHolderIsInitialized();
checkState(period != null, "There is no period. Use hasPeriod() before calling this method");
return period;
}
private void checkHolderIsInitialized() {
checkState(initialized, "Period have not been initialized yet");
}
}
| 2,058 | 29.279412 | 97 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/period/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.period;
import javax.annotation.ParametersAreNonnullByDefault;
| 980 | 39.875 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/purge/IndexPurgeListener.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.purge;
import java.util.List;
import org.sonar.api.server.ServerSide;
import org.sonar.db.purge.PurgeListener;
import org.sonar.server.issue.index.IssueIndexer;
@ServerSide
public class IndexPurgeListener implements PurgeListener {
private final IssueIndexer issueIndexer;
public IndexPurgeListener(IssueIndexer issueIndexer) {
this.issueIndexer = issueIndexer;
}
@Override
public void onIssuesRemoval(String projectUuid, List<String> issueKeys) {
issueIndexer.deleteByKeys(projectUuid, issueKeys);
}
}
| 1,413 | 33.487805 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/purge/ProjectCleaner.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.purge;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.CoreProperties;
import org.sonar.api.ce.ComputeEngineSide;
import org.sonar.api.config.Configuration;
import org.sonar.api.server.ServerSide;
import org.sonar.api.utils.TimeUtils;
import org.sonar.db.DbSession;
import org.sonar.db.purge.PurgeConfiguration;
import org.sonar.db.purge.PurgeDao;
import org.sonar.db.purge.PurgeListener;
import org.sonar.db.purge.PurgeProfiler;
import org.sonar.db.purge.period.DefaultPeriodCleaner;
import static org.sonar.db.purge.PurgeConfiguration.newDefaultPurgeConfiguration;
@ServerSide
@ComputeEngineSide
public class ProjectCleaner {
private static final Logger LOG = LoggerFactory.getLogger(ProjectCleaner.class);
private final PurgeProfiler profiler;
private final PurgeListener purgeListener;
private final PurgeDao purgeDao;
private final DefaultPeriodCleaner periodCleaner;
public ProjectCleaner(PurgeDao purgeDao, DefaultPeriodCleaner periodCleaner, PurgeProfiler profiler, PurgeListener purgeListener) {
this.purgeDao = purgeDao;
this.periodCleaner = periodCleaner;
this.profiler = profiler;
this.purgeListener = purgeListener;
}
public ProjectCleaner purge(DbSession session, String rootUuid, String projectUuid, Configuration projectConfig, Set<String> disabledComponentUuids) {
long start = System.currentTimeMillis();
profiler.reset();
periodCleaner.clean(session, rootUuid, projectConfig);
PurgeConfiguration configuration = newDefaultPurgeConfiguration(projectConfig, rootUuid, projectUuid, disabledComponentUuids);
purgeDao.purge(session, configuration, purgeListener, profiler);
session.commit();
logProfiling(start, projectConfig);
return this;
}
private void logProfiling(long start, Configuration config) {
if (config.getBoolean(CoreProperties.PROFILING_LOG_PROPERTY).orElse(false)) {
long duration = System.currentTimeMillis() - start;
LOG.info("");
LOG.atInfo().setMessage(" -------- Profiling for purge: {} --------").addArgument(() -> TimeUtils.formatDuration(duration)).log();
LOG.info("");
for (String line : profiler.getProfilingResult(duration)) {
LOG.info(line);
}
LOG.info("");
LOG.info(" -------- End of profiling for purge --------");
LOG.info("");
}
}
}
| 3,266 | 37.435294 | 152 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/purge/PurgeDatastoresStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.purge;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.component.ConfigurationRepository;
import org.sonar.ce.task.projectanalysis.component.DisabledComponentsHolder;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
public class PurgeDatastoresStep implements ComputationStep {
private final ProjectCleaner projectCleaner;
private final DbClient dbClient;
private final TreeRootHolder treeRootHolder;
private final ConfigurationRepository configRepository;
private final DisabledComponentsHolder disabledComponentsHolder;
private final AnalysisMetadataHolder analysisMetadataHolder;
public PurgeDatastoresStep(DbClient dbClient, ProjectCleaner projectCleaner, TreeRootHolder treeRootHolder,
ConfigurationRepository configRepository, DisabledComponentsHolder disabledComponentsHolder, AnalysisMetadataHolder analysisMetadataHolder) {
this.projectCleaner = projectCleaner;
this.dbClient = dbClient;
this.treeRootHolder = treeRootHolder;
this.configRepository = configRepository;
this.disabledComponentsHolder = disabledComponentsHolder;
this.analysisMetadataHolder = analysisMetadataHolder;
}
@Override
public void execute(ComputationStep.Context context) {
try (DbSession dbSession = dbClient.openSession(true)) {
// applies to views and projects
String projectUuid = analysisMetadataHolder.getProject().getUuid();
projectCleaner.purge(dbSession, treeRootHolder.getRoot().getUuid(), projectUuid, configRepository.getConfiguration(), disabledComponentsHolder.getUuids());
dbSession.commit();
}
}
@Override
public String getDescription() {
return "Purge db";
}
}
| 2,736 | 41.765625 | 161 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/purge/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.purge;
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/pushevent/IssueEvent.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.pushevent;
public abstract class IssueEvent {
private String key;
private String projectKey;
protected IssueEvent() {
// nothing to do
}
protected IssueEvent(String key, String projectKey) {
this.key = key;
this.projectKey = projectKey;
}
public abstract String getEventName();
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getProjectKey() {
return projectKey;
}
public void setProjectKey(String projectKey) {
this.projectKey = projectKey;
}
@Override
public String toString() {
return "IssueEvent{" +
"name='" + getEventName() + '\'' +
", key='" + key + '\'' +
", projectKey='" + projectKey + '\'' +
'}';
}
}
| 1,655 | 25.285714 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/pushevent/PushEventFactory.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.pushevent;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.Optional;
import java.util.Set;
import org.jetbrains.annotations.NotNull;
import org.sonar.api.ce.ComputeEngineSide;
import org.sonar.api.rules.RuleType;
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.issue.Rule;
import org.sonar.ce.task.projectanalysis.issue.RuleRepository;
import org.sonar.ce.task.projectanalysis.locations.flow.FlowGenerator;
import org.sonar.ce.task.projectanalysis.locations.flow.Location;
import org.sonar.ce.task.projectanalysis.locations.flow.TextRange;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.db.protobuf.DbCommons;
import org.sonar.db.protobuf.DbIssues;
import org.sonar.db.pushevent.PushEventDto;
import org.sonar.server.issue.TaintChecker;
import org.sonar.server.security.SecurityStandards;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Objects.requireNonNull;
import static org.sonar.server.security.SecurityStandards.fromSecurityStandards;
@ComputeEngineSide
public class PushEventFactory {
private static final Gson GSON = new GsonBuilder().create();
private final TreeRootHolder treeRootHolder;
private final AnalysisMetadataHolder analysisMetadataHolder;
private final TaintChecker taintChecker;
private final FlowGenerator flowGenerator;
private final RuleRepository ruleRepository;
public PushEventFactory(TreeRootHolder treeRootHolder, AnalysisMetadataHolder analysisMetadataHolder, TaintChecker taintChecker,
FlowGenerator flowGenerator, RuleRepository ruleRepository) {
this.treeRootHolder = treeRootHolder;
this.analysisMetadataHolder = analysisMetadataHolder;
this.taintChecker = taintChecker;
this.flowGenerator = flowGenerator;
this.ruleRepository = ruleRepository;
}
public Optional<PushEventDto> raiseEventOnIssue(String projectUuid, DefaultIssue currentIssue) {
var currentIssueComponentUuid = currentIssue.componentUuid();
if (currentIssueComponentUuid == null) {
return Optional.empty();
}
var component = treeRootHolder.getComponentByUuid(currentIssueComponentUuid);
if (isTaintVulnerability(currentIssue)) {
return raiseTaintVulnerabilityEvent(projectUuid, component, currentIssue);
}
if (isSecurityHotspot(currentIssue)) {
return raiseSecurityHotspotEvent(projectUuid, component, currentIssue);
}
return Optional.empty();
}
private boolean isTaintVulnerability(DefaultIssue issue) {
return taintChecker.isTaintVulnerability(issue);
}
private static boolean isSecurityHotspot(DefaultIssue issue) {
return RuleType.SECURITY_HOTSPOT.equals(issue.type());
}
private Optional<PushEventDto> raiseTaintVulnerabilityEvent(String projectUuid, Component component, DefaultIssue issue) {
if (shouldCreateRaisedEvent(issue)) {
return Optional.of(raiseTaintVulnerabilityRaisedEvent(projectUuid, component, issue));
}
if (issue.isBeingClosed()) {
return Optional.of(raiseTaintVulnerabilityClosedEvent(projectUuid, issue));
}
return Optional.empty();
}
private Optional<PushEventDto> raiseSecurityHotspotEvent(String projectUuid, Component component, DefaultIssue issue) {
if (shouldCreateRaisedEvent(issue)) {
return Optional.of(raiseSecurityHotspotRaisedEvent(projectUuid, component, issue));
}
if (issue.isBeingClosed()) {
return Optional.of(raiseSecurityHotspotClosedEvent(projectUuid, component, issue));
}
return Optional.empty();
}
private static boolean shouldCreateRaisedEvent(DefaultIssue issue) {
return issue.isNew() || issue.isCopied() || isReopened(issue);
}
private static boolean isReopened(DefaultIssue currentIssue) {
var currentChange = currentIssue.currentChange();
if (currentChange == null) {
return false;
}
var status = currentChange.get("status");
return status != null && Set.of("CLOSED|OPEN", "CLOSED|TO_REVIEW").contains(status.toString());
}
private PushEventDto raiseTaintVulnerabilityRaisedEvent(String projectUuid, Component component, DefaultIssue issue) {
TaintVulnerabilityRaised event = prepareEvent(component, issue);
return createPushEventDto(projectUuid, issue, event);
}
private TaintVulnerabilityRaised prepareEvent(Component component, DefaultIssue issue) {
TaintVulnerabilityRaised event = new TaintVulnerabilityRaised();
event.setProjectKey(issue.projectKey());
event.setCreationDate(issue.creationDate().getTime());
event.setKey(issue.key());
event.setSeverity(issue.severity());
event.setRuleKey(issue.getRuleKey().toString());
event.setType(issue.type().name());
event.setBranch(analysisMetadataHolder.getBranch().getName());
event.setMainLocation(prepareMainLocation(component, issue));
event.setFlows(flowGenerator.convertFlows(component.getName(), requireNonNull(issue.getLocations())));
issue.getRuleDescriptionContextKey().ifPresent(event::setRuleDescriptionContextKey);
return event;
}
private static Location prepareMainLocation(Component component, DefaultIssue issue) {
DbIssues.Locations issueLocations = requireNonNull(issue.getLocations());
TextRange mainLocationTextRange = getTextRange(issueLocations.getTextRange(), issueLocations.getChecksum());
Location mainLocation = new Location();
Optional.ofNullable(issue.getMessage()).ifPresent(mainLocation::setMessage);
mainLocation.setFilePath(component.getName());
mainLocation.setTextRange(mainLocationTextRange);
return mainLocation;
}
private static PushEventDto createPushEventDto(String projectUuid, DefaultIssue issue, IssueEvent event) {
return new PushEventDto()
.setName(event.getEventName())
.setProjectUuid(projectUuid)
.setLanguage(issue.language())
.setPayload(serializeEvent(event));
}
private static PushEventDto raiseTaintVulnerabilityClosedEvent(String projectUuid, DefaultIssue issue) {
TaintVulnerabilityClosed event = new TaintVulnerabilityClosed(issue.key(), issue.projectKey());
return createPushEventDto(projectUuid, issue, event);
}
private PushEventDto raiseSecurityHotspotRaisedEvent(String projectUuid, Component component, DefaultIssue issue) {
SecurityHotspotRaised event = new SecurityHotspotRaised();
event.setKey(issue.key());
event.setProjectKey(issue.projectKey());
event.setStatus(issue.getStatus());
event.setCreationDate(issue.creationDate().getTime());
event.setMainLocation(prepareMainLocation(component, issue));
event.setRuleKey(issue.getRuleKey().toString());
event.setVulnerabilityProbability(getVulnerabilityProbability(issue));
event.setBranch(analysisMetadataHolder.getBranch().getName());
event.setAssignee(issue.assigneeLogin());
return createPushEventDto(projectUuid, issue, event);
}
private String getVulnerabilityProbability(DefaultIssue issue) {
Rule rule = ruleRepository.getByKey(issue.getRuleKey());
SecurityStandards.SQCategory sqCategory = fromSecurityStandards(rule.getSecurityStandards()).getSqCategory();
return sqCategory.getVulnerability().name();
}
private static PushEventDto raiseSecurityHotspotClosedEvent(String projectUuid, Component component, DefaultIssue issue) {
SecurityHotspotClosed event = new SecurityHotspotClosed();
event.setKey(issue.key());
event.setProjectKey(issue.projectKey());
event.setStatus(issue.getStatus());
event.setResolution(issue.resolution());
event.setFilePath(component.getName());
return createPushEventDto(projectUuid, issue, event);
}
private static byte[] serializeEvent(IssueEvent event) {
return GSON.toJson(event).getBytes(UTF_8);
}
@NotNull
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;
}
}
| 9,221 | 41.497696 | 130 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/pushevent/SecurityHotspotClosed.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.pushevent;
import com.google.common.annotations.VisibleForTesting;
import javax.annotation.Nullable;
public class SecurityHotspotClosed extends IssueEvent {
@VisibleForTesting
static final String EVENT_NAME = "SecurityHotspotClosed";
private String status;
private String resolution;
private String filePath;
public SecurityHotspotClosed() {
// nothing to do
}
@Override
public String getEventName() {
return EVENT_NAME;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getResolution() {
return resolution;
}
public void setResolution(@Nullable String resolution) {
this.resolution = resolution;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
}
| 1,768 | 25.402985 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/pushevent/SecurityHotspotRaised.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.pushevent;
import com.google.common.annotations.VisibleForTesting;
import javax.annotation.Nullable;
import org.sonar.ce.task.projectanalysis.locations.flow.Location;
public class SecurityHotspotRaised extends IssueEvent {
@VisibleForTesting
static final String EVENT_NAME = "SecurityHotspotRaised";
private String status;
private String vulnerabilityProbability;
private long creationDate;
private Location mainLocation;
private String ruleKey;
private String branch;
private String assignee;
public SecurityHotspotRaised() {
// nothing to do
}
@Override
public String getEventName() {
return EVENT_NAME;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getVulnerabilityProbability() {
return vulnerabilityProbability;
}
public void setVulnerabilityProbability(String vulnerabilityProbability) {
this.vulnerabilityProbability = vulnerabilityProbability;
}
public long getCreationDate() {
return creationDate;
}
public void setCreationDate(long creationDate) {
this.creationDate = creationDate;
}
public Location getMainLocation() {
return mainLocation;
}
public void setMainLocation(Location mainLocation) {
this.mainLocation = mainLocation;
}
public String getRuleKey() {
return ruleKey;
}
public void setRuleKey(String ruleKey) {
this.ruleKey = ruleKey;
}
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
public String getAssignee() {
return assignee;
}
public void setAssignee(@Nullable String assignee) {
this.assignee = assignee;
}
}
| 2,627 | 24.269231 | 76 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/pushevent/TaintVulnerabilityClosed.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.pushevent;
public class TaintVulnerabilityClosed extends IssueEvent {
private static final String EVENT_NAME = "TaintVulnerabilityClosed";
public TaintVulnerabilityClosed() {
// nothing to do
}
public TaintVulnerabilityClosed(String key, String projectKey) {
super(key, projectKey);
}
@Override
public String getEventName() {
return EVENT_NAME;
}
}
| 1,267 | 31.512821 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/pushevent/TaintVulnerabilityRaised.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.pushevent;
import java.util.List;
import java.util.Optional;
import org.sonar.ce.task.projectanalysis.locations.flow.Flow;
import org.sonar.ce.task.projectanalysis.locations.flow.Location;
public class TaintVulnerabilityRaised extends IssueEvent {
private static final String EVENT_NAME = "TaintVulnerabilityRaised";
private String branch;
private long creationDate;
private String ruleKey;
private String severity;
private String type;
private Location mainLocation;
private List<Flow> flows;
private String ruleDescriptionContextKey;
public TaintVulnerabilityRaised() {
// nothing to do
}
@Override
public String getEventName() {
return EVENT_NAME;
}
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
public long getCreationDate() {
return creationDate;
}
public void setCreationDate(long creationDate) {
this.creationDate = creationDate;
}
public String getRuleKey() {
return ruleKey;
}
public void setRuleKey(String ruleKey) {
this.ruleKey = ruleKey;
}
public String getSeverity() {
return severity;
}
public void setSeverity(String severity) {
this.severity = severity;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Location getMainLocation() {
return mainLocation;
}
public void setMainLocation(Location mainLocation) {
this.mainLocation = mainLocation;
}
public List<Flow> getFlows() {
return flows;
}
public void setFlows(List<Flow> flows) {
this.flows = flows;
}
public Optional<String> getRuleDescriptionContextKey() {
return Optional.ofNullable(ruleDescriptionContextKey);
}
public void setRuleDescriptionContextKey(String ruleDescriptionContextKey) {
this.ruleDescriptionContextKey = ruleDescriptionContextKey;
}
}
| 2,815 | 23.920354 | 78 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/pushevent/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.pushevent;
import javax.annotation.ParametersAreNonnullByDefault;
| 983 | 40 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/qualitygate/Condition.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.qualitygate;
import com.google.common.base.MoreObjects;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.sonar.ce.task.projectanalysis.metric.Metric;
import static java.util.Objects.hash;
import static java.util.Objects.requireNonNull;
@Immutable
public class Condition {
public enum Operator {
GREATER_THAN("GT"), LESS_THAN("LT");
private final String dbValue;
Operator(String dbValue) {
this.dbValue = dbValue;
}
public String getDbValue() {
return dbValue;
}
}
private final Metric metric;
private final Operator operator;
private final String errorThreshold;
private final boolean useVariation;
public Condition(Metric metric, String operator, String errorThreshold) {
this.metric = requireNonNull(metric);
this.operator = parseFromDbValue(requireNonNull(operator));
this.useVariation = metric.getKey().startsWith("new_");
this.errorThreshold = errorThreshold;
}
private static Operator parseFromDbValue(String str) {
for (Operator operator : Operator.values()) {
if (operator.dbValue.equals(str)) {
return operator;
}
}
throw new IllegalArgumentException(String.format("Unsupported operator value: '%s'", str));
}
public Metric getMetric() {
return metric;
}
public boolean useVariation() {
return useVariation;
}
public Operator getOperator() {
return operator;
}
public String getErrorThreshold() {
return errorThreshold;
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Condition that = (Condition) o;
return java.util.Objects.equals(metric, that.metric);
}
@Override
public int hashCode() {
return hash(metric);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("metric", metric)
.add("operator", operator)
.add("errorThreshold", errorThreshold)
.toString();
}
}
| 2,974 | 26.045455 | 95 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/qualitygate/ConditionEvaluator.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.qualitygate;
import java.util.EnumSet;
import java.util.Optional;
import javax.annotation.CheckForNull;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import org.sonar.ce.task.projectanalysis.metric.Metric;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Optional.of;
import static org.sonar.ce.task.projectanalysis.metric.Metric.MetricType.FLOAT;
import static org.sonar.ce.task.projectanalysis.metric.Metric.MetricType.INT;
import static org.sonar.ce.task.projectanalysis.metric.Metric.MetricType.LEVEL;
import static org.sonar.ce.task.projectanalysis.metric.Metric.MetricType.MILLISEC;
import static org.sonar.ce.task.projectanalysis.metric.Metric.MetricType.PERCENT;
import static org.sonar.ce.task.projectanalysis.metric.Metric.MetricType.RATING;
import static org.sonar.ce.task.projectanalysis.metric.Metric.MetricType.WORK_DUR;
public final class ConditionEvaluator {
private static final EnumSet<Metric.MetricType> SUPPORTED_METRIC_TYPE = EnumSet.of(INT, MILLISEC, RATING, WORK_DUR, FLOAT, PERCENT, LEVEL);
/**
* Evaluates the condition for the specified measure
*/
public EvaluationResult evaluate(Condition condition, Measure measure) {
checkArgument(SUPPORTED_METRIC_TYPE.contains(condition.getMetric().getType()), "Conditions on MetricType %s are not supported", condition.getMetric().getType());
Comparable measureComparable = parseMeasure(measure);
if (measureComparable == null) {
return new EvaluationResult(Measure.Level.OK, null);
}
return evaluateCondition(condition, measureComparable)
.orElseGet(() -> new EvaluationResult(Measure.Level.OK, measureComparable));
}
private static Optional<EvaluationResult> evaluateCondition(Condition condition, Comparable<?> measureComparable) {
try {
Comparable conditionComparable = parseConditionValue(condition.getMetric(), condition.getErrorThreshold());
if (doesReachThresholds(measureComparable, conditionComparable, condition)) {
return of(new EvaluationResult(Measure.Level.ERROR, measureComparable));
}
return Optional.empty();
} catch (NumberFormatException badValueFormat) {
throw new IllegalArgumentException(String.format(
"Quality Gate: Unable to parse value '%s' to compare against %s",
condition.getErrorThreshold(), condition.getMetric().getName()));
}
}
private static boolean doesReachThresholds(Comparable measureValue, Comparable criteriaValue, Condition condition) {
int comparison = measureValue.compareTo(criteriaValue);
switch (condition.getOperator()) {
case GREATER_THAN:
return comparison > 0;
case LESS_THAN:
return comparison < 0;
default:
throw new IllegalArgumentException(String.format("Unsupported operator '%s'", condition.getOperator()));
}
}
private static Comparable parseConditionValue(Metric metric, String value) {
switch (metric.getType().getValueType()) {
case INT:
return parseInteger(value);
case LONG:
return Long.parseLong(value);
case DOUBLE:
return Double.parseDouble(value);
case LEVEL:
return value;
default:
throw new IllegalArgumentException(String.format("Unsupported value type %s. Can not convert condition value", metric.getType().getValueType()));
}
}
private static Comparable<Integer> parseInteger(String value) {
return value.contains(".") ? Integer.parseInt(value.substring(0, value.indexOf('.'))) : Integer.parseInt(value);
}
@CheckForNull
private static Comparable parseMeasure(Measure measure) {
switch (measure.getValueType()) {
case INT:
return measure.getIntValue();
case LONG:
return measure.getLongValue();
case DOUBLE:
return measure.getDoubleValue();
case LEVEL:
return measure.getLevelValue().name();
case NO_VALUE:
return null;
default:
throw new IllegalArgumentException(
String.format("Unsupported measure ValueType %s. Can not parse measure to a Comparable", measure.getValueType()));
}
}
}
| 5,046 | 40.710744 | 165 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/qualitygate/ConditionStatus.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.qualitygate;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
@Immutable
public class ConditionStatus {
public static final ConditionStatus NO_VALUE_STATUS = new ConditionStatus(EvaluationStatus.NO_VALUE, null);
private final EvaluationStatus status;
@CheckForNull
private final String value;
private ConditionStatus(EvaluationStatus status, @Nullable String value) {
this.status = requireNonNull(status, "status can not be null");
this.value = value;
}
public static ConditionStatus create(EvaluationStatus status, String value) {
requireNonNull(status, "status can not be null");
checkArgument(status != EvaluationStatus.NO_VALUE, "EvaluationStatus 'NO_VALUE' can not be used with this method, use constant ConditionStatus.NO_VALUE_STATUS instead.");
requireNonNull(value, "value can not be null");
return new ConditionStatus(status, value);
}
public EvaluationStatus getStatus() {
return status;
}
/**
* @return {@code null} when {@link #getStatus()} is {@link EvaluationStatus#NO_VALUE}, otherwise non {@code null}
*/
@CheckForNull
public String getValue() {
return value;
}
@Override
public String toString() {
return "ConditionStatus{" +
"status=" + status +
", value='" + value + '\'' +
'}';
}
public enum EvaluationStatus {
NO_VALUE, OK, ERROR
}
}
| 2,437 | 31.945946 | 174 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/qualitygate/EvaluationResult.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.qualitygate;
import com.google.common.base.MoreObjects;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import static java.util.Objects.requireNonNull;
public record EvaluationResult(Measure.Level level, @CheckForNull Comparable<?> value) {
public EvaluationResult(Measure.Level level, @Nullable Comparable<?> value) {
this.level = requireNonNull(level);
this.value = value;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("level", level)
.add("value", value)
.toString();
}
}
| 1,524 | 34.465116 | 88 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/qualitygate/EvaluationResultTextConverter.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.qualitygate;
import javax.annotation.CheckForNull;
public interface EvaluationResultTextConverter {
@CheckForNull
String asText(Condition condition, EvaluationResult evaluationResult);
}
| 1,078 | 37.535714 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/qualitygate/EvaluationResultTextConverterImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.qualitygate;
import java.util.Locale;
import java.util.Map;
import javax.annotation.CheckForNull;
import org.sonar.api.utils.Duration;
import org.sonar.api.utils.Durations;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import org.sonar.ce.task.projectanalysis.metric.Metric;
import org.sonar.core.i18n.I18n;
import static java.util.Objects.requireNonNull;
public final class EvaluationResultTextConverterImpl implements EvaluationResultTextConverter {
private static final Map<Condition.Operator, String> OPERATOR_LABELS = Map.of(
Condition.Operator.GREATER_THAN, ">",
Condition.Operator.LESS_THAN, "<");
private final I18n i18n;
private final Durations durations;
public EvaluationResultTextConverterImpl(I18n i18n, Durations durations) {
this.i18n = i18n;
this.durations = durations;
}
@Override
@CheckForNull
public String asText(Condition condition, EvaluationResult evaluationResult) {
requireNonNull(condition);
if (evaluationResult.level() == Measure.Level.OK) {
return null;
}
return getAlertLabel(condition);
}
private String getAlertLabel(Condition condition) {
String metric = i18n.message(Locale.ENGLISH, "metric." + condition.getMetric().getKey() + ".name", condition.getMetric().getName());
return metric +
" " + OPERATOR_LABELS.get(condition.getOperator()) + " " +
alertValue(condition);
}
private String alertValue(Condition condition) {
if (condition.getMetric().getType() == Metric.MetricType.WORK_DUR) {
return formatDuration(condition.getErrorThreshold());
}
return condition.getErrorThreshold();
}
private String formatDuration(String value) {
return durations.format(Duration.create(Long.parseLong(value)));
}
}
| 2,651 | 34.36 | 136 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/qualitygate/MutableQualityGateHolder.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.qualitygate;
import org.sonar.server.qualitygate.EvaluatedQualityGate;
public interface MutableQualityGateHolder extends QualityGateHolder {
/**
* Sets the quality gate.
* Setting a quality gate more than once is not allowed and it can never be set to {@code null}.
*
* @throws NullPointerException if {@code qualityGate} is {@code null}
* @throws IllegalStateException if the holder has already been initialized
*/
void setQualityGate(QualityGate qualityGate);
/**
* Sets the evaluation of quality gate.
* Setting more than once is not allowed and it can never be set to {@code null}.
*
* @throws NullPointerException if {@code qualityGate} is {@code null}
* @throws IllegalStateException if the holder has already been initialized
*/
void setEvaluation(EvaluatedQualityGate evaluation);
}
| 1,723 | 39.093023 | 98 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/qualitygate/MutableQualityGateStatusHolder.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.qualitygate;
import java.util.Map;
public interface MutableQualityGateStatusHolder extends QualityGateStatusHolder {
/**
* Sets the status of the quality gate and its conditions in the holder.
*
* @throws NullPointerException if either {@code globalStatus} or {@code statusPerCondition} is {@code null}
* @throws IllegalArgumentException if {@code statusPerCondition} is empty
* @throws IllegalStateException if the status has already been set in the holder
*/
void setStatus(QualityGateStatus globalStatus, Map<Condition, ConditionStatus> statusPerCondition);
}
| 1,472 | 42.323529 | 110 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/qualitygate/QualityGate.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.qualitygate;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Objects;
import java.util.Set;
import javax.annotation.concurrent.Immutable;
import static java.util.Collections.unmodifiableSet;
@Immutable
public class QualityGate {
private final String uuid;
private final String name;
private final Set<Condition> conditions;
public QualityGate(String uuid, String name, Collection<Condition> conditions) {
this.uuid = uuid;
this.name = Objects.requireNonNull(name);
this.conditions = unmodifiableSet(new LinkedHashSet<>(conditions));
}
public String getUuid() {
return uuid;
}
public String getName() {
return name;
}
public Set<Condition> getConditions() {
return conditions;
}
}
| 1,648 | 29.537037 | 82 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/qualitygate/QualityGateHolder.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.qualitygate;
import java.util.Optional;
import org.sonar.server.qualitygate.EvaluatedQualityGate;
public interface QualityGateHolder {
/**
* The QualityGate for the project if there is any.
*
* @throws IllegalStateException if the holder has not been initialized (ie. we don't know yet what is the QualityGate)
*/
Optional<QualityGate> getQualityGate();
/**
* Evaluation of quality gate, including status and condition details.
*
* @throws IllegalStateException if the holder has not been initialized (ie. gate has not been evaluated yet)
*/
Optional<EvaluatedQualityGate> getEvaluation();
}
| 1,512 | 36.825 | 121 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/qualitygate/QualityGateHolderImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.qualitygate;
import java.util.Optional;
import org.sonar.server.qualitygate.EvaluatedQualityGate;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
public class QualityGateHolderImpl implements MutableQualityGateHolder {
private QualityGate qualityGate;
private EvaluatedQualityGate evaluation;
@Override
public void setQualityGate(QualityGate g) {
// fail fast
requireNonNull(g);
checkState(qualityGate == null, "QualityGateHolder can be initialized only once");
this.qualityGate = g;
}
@Override
public Optional<QualityGate> getQualityGate() {
checkState(qualityGate != null, "QualityGate has not been set yet");
return Optional.of(qualityGate);
}
@Override
public void setEvaluation(EvaluatedQualityGate g) {
// fail fast
requireNonNull(g);
checkState(evaluation == null, "QualityGateHolder evaluation can be initialized only once");
this.evaluation = g;
}
@Override
public Optional<EvaluatedQualityGate> getEvaluation() {
checkState(evaluation != null, "Evaluation of QualityGate has not been set yet");
return Optional.of(evaluation);
}
}
| 2,075 | 32.483871 | 96 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/qualitygate/QualityGateService.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.qualitygate;
import org.sonar.server.project.Project;
public interface QualityGateService {
/**
* Retrieve the {@link QualityGate} from the database associated with project. If there's none, it returns the default quality gate.
*/
QualityGate findEffectiveQualityGate(Project project);
}
| 1,185 | 38.533333 | 134 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/qualitygate/QualityGateServiceImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.qualitygate;
import java.util.Collection;
import java.util.Objects;
import java.util.Optional;
import org.sonar.ce.task.projectanalysis.metric.MetricRepository;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualitygate.QualityGateConditionDto;
import org.sonar.db.qualitygate.QualityGateDto;
import org.sonar.server.project.Project;
public class QualityGateServiceImpl implements QualityGateService {
private final DbClient dbClient;
private final MetricRepository metricRepository;
public QualityGateServiceImpl(DbClient dbClient, MetricRepository metricRepository) {
this.dbClient = dbClient;
this.metricRepository = metricRepository;
}
@Override
public QualityGate findEffectiveQualityGate(Project project) {
return findQualityGate(project).orElseGet(this::findDefaultQualityGate);
}
private QualityGate findDefaultQualityGate() {
try (DbSession dbSession = dbClient.openSession(false)) {
QualityGateDto qualityGateDto = dbClient.qualityGateDao().selectDefault(dbSession);
if (qualityGateDto == null) {
throw new IllegalStateException("The default Quality gate is missing");
}
return toQualityGate(dbSession, qualityGateDto);
}
}
private Optional<QualityGate> findQualityGate(Project project) {
try (DbSession dbSession = dbClient.openSession(false)) {
return Optional.ofNullable(dbClient.qualityGateDao().selectByProjectUuid(dbSession, project.getUuid()))
.map(qg -> toQualityGate(dbSession, qg));
}
}
private QualityGate toQualityGate(DbSession dbSession, QualityGateDto qualityGateDto) {
Collection<QualityGateConditionDto> dtos = dbClient.gateConditionDao().selectForQualityGate(dbSession, qualityGateDto.getUuid());
Collection<Condition> conditions = dtos.stream()
.map(input -> metricRepository.getOptionalByUuid(input.getMetricUuid())
.map(metric -> new Condition(metric, input.getOperator(), input.getErrorThreshold()))
.orElse(null))
.filter(Objects::nonNull)
.toList();
return new QualityGate(qualityGateDto.getUuid(), qualityGateDto.getName(), conditions);
}
}
| 3,050 | 39.144737 | 133 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/qualitygate/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.qualitygate;
public enum QualityGateStatus {
OK, ERROR
}
| 945 | 36.84 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/qualitygate/QualityGateStatusHolder.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.qualitygate;
import java.util.Map;
public interface QualityGateStatusHolder {
/**
* The global status of the quality gate (if there is a quality gate on the project).
*
* @throws IllegalStateException if status has not yet been set in the holder
* @see QualityGateHolder#getQualityGate()
*/
QualityGateStatus getStatus();
/**
* The status per condition of the quality gate (if there is a quality gate on the project).
*
* @throws IllegalStateException if status has not yet been set in the holder
* @see QualityGateHolder#getQualityGate()
*/
Map<Condition, ConditionStatus> getStatusPerConditions();
}
| 1,529 | 35.428571 | 94 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/qualitygate/QualityGateStatusHolderImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.qualitygate;
import com.google.common.collect.ImmutableMap;
import java.util.Map;
import javax.annotation.CheckForNull;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
public class QualityGateStatusHolderImpl implements MutableQualityGateStatusHolder {
@CheckForNull
private QualityGateStatus status;
@CheckForNull
private Map<Condition, ConditionStatus> statusPerCondition;
@Override
public QualityGateStatus getStatus() {
checkInitialized();
return status;
}
@Override
public Map<Condition, ConditionStatus> getStatusPerConditions() {
checkInitialized();
return statusPerCondition;
}
private void checkInitialized() {
checkState(status != null, "Quality gate status has not been set yet");
}
@Override
public void setStatus(QualityGateStatus globalStatus, Map<Condition, ConditionStatus> statusPerCondition) {
checkState(status == null, "Quality gate status has already been set in the holder");
requireNonNull(globalStatus, "global status can not be null");
requireNonNull(statusPerCondition, "status per condition can not be null");
this.status = globalStatus;
this.statusPerCondition = ImmutableMap.copyOf(statusPerCondition);
}
}
| 2,164 | 33.365079 | 109 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/qualitygate/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.ce.task.projectanalysis.qualitygate;
import javax.annotation.ParametersAreNonnullByDefault;
| 985 | 40.083333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/qualitymodel/MaintainabilityMeasuresVisitor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.qualitymodel;
import java.util.Optional;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit;
import org.sonar.ce.task.projectanalysis.component.PathAwareVisitorAdapter;
import org.sonar.ce.task.projectanalysis.formula.counter.RatingValue;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import org.sonar.ce.task.projectanalysis.measure.MeasureRepository;
import org.sonar.ce.task.projectanalysis.measure.RatingMeasures;
import org.sonar.ce.task.projectanalysis.metric.Metric;
import org.sonar.ce.task.projectanalysis.metric.MetricRepository;
import org.sonar.server.measure.Rating;
import static org.sonar.api.measures.CoreMetrics.DEVELOPMENT_COST_KEY;
import static org.sonar.api.measures.CoreMetrics.EFFORT_TO_REACH_MAINTAINABILITY_RATING_A_KEY;
import static org.sonar.api.measures.CoreMetrics.NCLOC_KEY;
import static org.sonar.api.measures.CoreMetrics.SQALE_DEBT_RATIO_KEY;
import static org.sonar.api.measures.CoreMetrics.SQALE_RATING_KEY;
import static org.sonar.api.measures.CoreMetrics.TECHNICAL_DEBT_KEY;
import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilder;
/**
* Compute measures related to maintainability for projects and descendants :
* {@link CoreMetrics#DEVELOPMENT_COST_KEY}
* {@link CoreMetrics#SQALE_DEBT_RATIO_KEY}
* {@link CoreMetrics#SQALE_RATING_KEY}
* {@link CoreMetrics#EFFORT_TO_REACH_MAINTAINABILITY_RATING_A_KEY}
*/
public class MaintainabilityMeasuresVisitor extends PathAwareVisitorAdapter<MaintainabilityMeasuresVisitor.Counter> {
private final MeasureRepository measureRepository;
private final RatingSettings ratingSettings;
private final Metric nclocMetric;
private final Metric developmentCostMetric;
private final Metric maintainabilityRemediationEffortMetric;
private final Metric debtRatioMetric;
private final Metric maintainabilityRatingMetric;
private final Metric effortToMaintainabilityRatingAMetric;
public MaintainabilityMeasuresVisitor(MetricRepository metricRepository, MeasureRepository measureRepository, RatingSettings ratingSettings) {
super(CrawlerDepthLimit.FILE, Order.POST_ORDER, CounterFactory.INSTANCE);
this.measureRepository = measureRepository;
this.ratingSettings = ratingSettings;
// Input metrics
this.nclocMetric = metricRepository.getByKey(NCLOC_KEY);
this.maintainabilityRemediationEffortMetric = metricRepository.getByKey(TECHNICAL_DEBT_KEY);
// Output metrics
this.developmentCostMetric = metricRepository.getByKey(DEVELOPMENT_COST_KEY);
this.debtRatioMetric = metricRepository.getByKey(SQALE_DEBT_RATIO_KEY);
this.maintainabilityRatingMetric = metricRepository.getByKey(SQALE_RATING_KEY);
this.effortToMaintainabilityRatingAMetric = metricRepository.getByKey(EFFORT_TO_REACH_MAINTAINABILITY_RATING_A_KEY);
}
@Override
public void visitProject(Component project, Path<Counter> path) {
computeAndSaveMeasures(project, path);
}
@Override
public void visitDirectory(Component directory, Path<Counter> path) {
computeAndSaveMeasures(directory, path);
}
@Override
public void visitFile(Component file, Path<Counter> path) {
path.current().addDevCosts(computeDevelopmentCost(file));
computeAndSaveMeasures(file, path);
}
private long computeDevelopmentCost(Component file) {
Optional<Measure> measure = measureRepository.getRawMeasure(file, nclocMetric);
long ncloc = measure.map(Measure::getIntValue).orElse(0);
return ncloc * ratingSettings.getDevCost(file.getFileAttributes().getLanguageKey());
}
private void computeAndSaveMeasures(Component component, Path<Counter> path) {
addDevelopmentCostMeasure(component, path.current());
double density = computeDensity(component, path.current());
addDebtRatioMeasure(component, density);
addMaintainabilityRatingMeasure(component, density);
addEffortToMaintainabilityRatingAMeasure(component, path);
addToParent(path);
}
private double computeDensity(Component component, Counter developmentCost) {
Optional<Measure> measure = measureRepository.getRawMeasure(component, maintainabilityRemediationEffortMetric);
double maintainabilityRemediationEffort = measure.isPresent() ? measure.get().getLongValue() : 0L;
if (Double.doubleToRawLongBits(developmentCost.devCosts) != 0L) {
return maintainabilityRemediationEffort / developmentCost.devCosts;
}
return 0D;
}
private void addDevelopmentCostMeasure(Component component, Counter developmentCost) {
// the value of this measure is stored as a string because it can exceed the size limit of number storage on some DB
measureRepository.add(component, developmentCostMetric, newMeasureBuilder().create(Long.toString(developmentCost.devCosts)));
}
private void addDebtRatioMeasure(Component component, double density) {
measureRepository.add(component, debtRatioMetric, newMeasureBuilder().create(100.0 * density, debtRatioMetric.getDecimalScale()));
}
private void addMaintainabilityRatingMeasure(Component component, double density) {
Rating rating = ratingSettings.getDebtRatingGrid().getRatingForDensity(density);
measureRepository.add(component, maintainabilityRatingMetric, RatingMeasures.get(rating));
}
private void addEffortToMaintainabilityRatingAMeasure(Component component, Path<Counter> path) {
long developmentCostValue = path.current().devCosts;
Optional<Measure> effortMeasure = measureRepository.getRawMeasure(component, maintainabilityRemediationEffortMetric);
long effort = effortMeasure.isPresent() ? effortMeasure.get().getLongValue() : 0L;
long upperGradeCost = ((Double) (ratingSettings.getDebtRatingGrid().getGradeLowerBound(Rating.B) * developmentCostValue)).longValue();
long effortToRatingA = upperGradeCost < effort ? (effort - upperGradeCost) : 0L;
measureRepository.add(component, effortToMaintainabilityRatingAMetric, Measure.newMeasureBuilder().create(effortToRatingA));
}
private static void addToParent(Path<Counter> path) {
if (!path.isRoot()) {
path.parent().add(path.current());
}
}
public static final class Counter {
private long devCosts = 0;
private RatingValue reliabilityRating = new RatingValue();
private RatingValue securityRating = new RatingValue();
private Counter() {
// prevents instantiation
}
void add(Counter otherCounter) {
addDevCosts(otherCounter.devCosts);
reliabilityRating.increment(otherCounter.reliabilityRating);
securityRating.increment(otherCounter.securityRating);
}
void addDevCosts(long developmentCosts) {
this.devCosts += developmentCosts;
}
}
private static final class CounterFactory extends SimpleStackElementFactory<Counter> {
public static final CounterFactory INSTANCE = new CounterFactory();
private CounterFactory() {
// prevents instantiation
}
@Override
public Counter createForAny(Component component) {
return new Counter();
}
}
}
| 8,006 | 42.994505 | 144 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/qualitymodel/NewMaintainabilityMeasuresVisitor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.qualitymodel;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.utils.KeyValueFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit;
import org.sonar.ce.task.projectanalysis.component.PathAwareVisitorAdapter;
import org.sonar.ce.task.projectanalysis.formula.counter.LongValue;
import org.sonar.ce.task.projectanalysis.issue.IntegrateIssuesVisitor;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import org.sonar.ce.task.projectanalysis.measure.MeasureRepository;
import org.sonar.ce.task.projectanalysis.metric.Metric;
import org.sonar.ce.task.projectanalysis.metric.MetricRepository;
import org.sonar.ce.task.projectanalysis.source.NewLinesRepository;
import static org.sonar.api.measures.CoreMetrics.NCLOC_DATA_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_DEVELOPMENT_COST_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_MAINTAINABILITY_RATING_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_SQALE_DEBT_RATIO_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_TECHNICAL_DEBT_KEY;
import static org.sonar.api.utils.KeyValueFormat.newIntegerConverter;
import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.POST_ORDER;
import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilder;
/**
* This visitor depends on {@link IntegrateIssuesVisitor} for the computation of
* metric {@link CoreMetrics#NEW_TECHNICAL_DEBT}.
* Compute following measure :
* {@link CoreMetrics#NEW_SQALE_DEBT_RATIO_KEY}
* {@link CoreMetrics#NEW_MAINTAINABILITY_RATING_KEY}
*/
public class NewMaintainabilityMeasuresVisitor extends PathAwareVisitorAdapter<NewMaintainabilityMeasuresVisitor.Counter> {
private static final Logger LOG = LoggerFactory.getLogger(NewMaintainabilityMeasuresVisitor.class);
private final MeasureRepository measureRepository;
private final NewLinesRepository newLinesRepository;
private final RatingSettings ratingSettings;
private final Metric newDebtMetric;
private final Metric nclocDataMetric;
private final Metric newDevelopmentCostMetric;
private final Metric newDebtRatioMetric;
private final Metric newMaintainabilityRatingMetric;
public NewMaintainabilityMeasuresVisitor(MetricRepository metricRepository, MeasureRepository measureRepository, NewLinesRepository newLinesRepository,
RatingSettings ratingSettings) {
super(CrawlerDepthLimit.FILE, POST_ORDER, CounterFactory.INSTANCE);
this.measureRepository = measureRepository;
this.newLinesRepository = newLinesRepository;
this.ratingSettings = ratingSettings;
// computed by NewDebtAggregator which is executed by IntegrateIssuesVisitor
this.newDebtMetric = metricRepository.getByKey(NEW_TECHNICAL_DEBT_KEY);
// which line is ncloc and which isn't
this.nclocDataMetric = metricRepository.getByKey(NCLOC_DATA_KEY);
// output metrics
this.newDevelopmentCostMetric = metricRepository.getByKey(NEW_DEVELOPMENT_COST_KEY);
this.newDebtRatioMetric = metricRepository.getByKey(NEW_SQALE_DEBT_RATIO_KEY);
this.newMaintainabilityRatingMetric = metricRepository.getByKey(NEW_MAINTAINABILITY_RATING_KEY);
}
@Override
public void visitProject(Component project, Path<Counter> path) {
computeAndSaveNewDebtRatioMeasure(project, path);
}
@Override
public void visitDirectory(Component directory, Path<Counter> path) {
computeAndSaveNewDebtRatioMeasure(directory, path);
increaseNewDebtAndDevCostOfParent(path);
}
@Override
public void visitFile(Component file, Path<Counter> path) {
initNewDebtRatioCounter(file, path);
computeAndSaveNewDebtRatioMeasure(file, path);
increaseNewDebtAndDevCostOfParent(path);
}
private void computeAndSaveNewDebtRatioMeasure(Component component, Path<Counter> path) {
if (!newLinesRepository.newLinesAvailable()) {
return;
}
double density = computeDensity(path.current());
double newDebtRatio = 100.0 * density;
int newMaintainability = ratingSettings.getDebtRatingGrid().getRatingForDensity(density).getIndex();
float newDevelopmentCost = path.current().getDevCost().getValue();
measureRepository.add(component, this.newDevelopmentCostMetric, newMeasureBuilder().create(newDevelopmentCost));
measureRepository.add(component, this.newDebtRatioMetric, newMeasureBuilder().create(newDebtRatio));
measureRepository.add(component, this.newMaintainabilityRatingMetric, newMeasureBuilder().create(newMaintainability));
}
private static double computeDensity(Counter counter) {
LongValue newDebt = counter.getNewDebt();
if (newDebt.isSet()) {
long developmentCost = counter.getDevCost().getValue();
if (developmentCost != 0L) {
return newDebt.getValue() / (double) developmentCost;
}
}
return 0D;
}
private static long getLongValue(Optional<Measure> measure) {
return measure.map(NewMaintainabilityMeasuresVisitor::getLongValue).orElse(0L);
}
private static long getLongValue(Measure measure) {
return measure.getLongValue();
}
private void initNewDebtRatioCounter(Component file, Path<Counter> path) {
// first analysis, no period, no differential value to compute, save processing time and return now
if (!newLinesRepository.newLinesAvailable()) {
return;
}
Optional<Set<Integer>> changedLines = newLinesRepository.getNewLines(file);
if (!changedLines.isPresent()) {
LOG.trace(String.format("No information about changed lines is available for file '%s'. Dev cost will be zero.", file.getKey()));
return;
}
Optional<Measure> nclocDataMeasure = measureRepository.getRawMeasure(file, this.nclocDataMetric);
if (!nclocDataMeasure.isPresent()) {
return;
}
initNewDebtRatioCounter(path.current(), file, nclocDataMeasure.get(), changedLines.get());
}
private void initNewDebtRatioCounter(Counter devCostCounter, Component file, Measure nclocDataMeasure, Set<Integer> changedLines) {
boolean hasDevCost = false;
long lineDevCost = ratingSettings.getDevCost(file.getFileAttributes().getLanguageKey());
for (Integer nclocLineIndex : nclocLineIndexes(nclocDataMeasure)) {
if (changedLines.contains(nclocLineIndex)) {
devCostCounter.incrementDevCost(lineDevCost);
hasDevCost = true;
}
}
if (hasDevCost) {
long newDebt = getLongValue(measureRepository.getRawMeasure(file, this.newDebtMetric));
devCostCounter.incrementNewDebt(newDebt);
}
}
private static void increaseNewDebtAndDevCostOfParent(Path<Counter> path) {
path.parent().add(path.current());
}
/**
* NCLOC_DATA contains Key-value pairs, where key - is a number of line, and value - is an indicator of whether line
* contains code (1) or not (0).
* This method parses the value of the NCLOC_DATA measure and return the line numbers of lines which contain code.
*/
private static Iterable<Integer> nclocLineIndexes(Measure nclocDataMeasure) {
Map<Integer, Integer> parsedNclocData = KeyValueFormat.parse(nclocDataMeasure.getData(), newIntegerConverter(), newIntegerConverter());
return parsedNclocData.entrySet()
.stream()
.filter(entry -> entry.getValue() == 1)
.map(Map.Entry::getKey)
.toList();
}
public static final class Counter {
private final LongValue newDebt = new LongValue();
private final LongValue devCost = new LongValue();
public void add(Counter counter) {
this.newDebt.increment(counter.newDebt);
this.devCost.increment(counter.devCost);
}
LongValue incrementNewDebt(long value) {
return newDebt.increment(value);
}
LongValue incrementDevCost(long value) {
return devCost.increment(value);
}
LongValue getNewDebt() {
return this.newDebt;
}
LongValue getDevCost() {
return this.devCost;
}
}
private static class CounterFactory extends SimpleStackElementFactory<Counter> {
public static final CounterFactory INSTANCE = new CounterFactory();
@Override
public Counter createForAny(Component component) {
return new Counter();
}
}
}
| 9,240 | 39.530702 | 153 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/qualitymodel/NewReliabilityAndSecurityRatingMeasuresVisitor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.qualitymodel;
import com.google.common.collect.ImmutableMap;
import java.util.Map;
import org.sonar.api.ce.measure.Issue;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.PathAwareVisitorAdapter;
import org.sonar.ce.task.projectanalysis.formula.counter.RatingValue;
import org.sonar.ce.task.projectanalysis.issue.ComponentIssuesRepository;
import org.sonar.ce.task.projectanalysis.issue.NewIssueClassifier;
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 org.sonar.server.measure.Rating;
import static org.sonar.api.measures.CoreMetrics.NEW_RELIABILITY_RATING_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_RATING_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.VULNERABILITY;
import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.POST_ORDER;
import static org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit.LEAVES;
import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilder;
import static org.sonar.server.measure.Rating.A;
import static org.sonar.server.measure.Rating.B;
import static org.sonar.server.measure.Rating.C;
import static org.sonar.server.measure.Rating.D;
import static org.sonar.server.measure.Rating.E;
/**
* Compute following measures :
* {@link CoreMetrics#NEW_RELIABILITY_RATING_KEY}
* {@link CoreMetrics#NEW_SECURITY_RATING_KEY}
*/
public class NewReliabilityAndSecurityRatingMeasuresVisitor extends PathAwareVisitorAdapter<NewReliabilityAndSecurityRatingMeasuresVisitor.Counter> {
private static final Map<String, Rating> RATING_BY_SEVERITY = ImmutableMap.of(
BLOCKER, E,
CRITICAL, D,
MAJOR, C,
MINOR, B,
INFO, A);
private final MeasureRepository measureRepository;
private final ComponentIssuesRepository componentIssuesRepository;
private final Map<String, Metric> metricsByKey;
private final NewIssueClassifier newIssueClassifier;
public NewReliabilityAndSecurityRatingMeasuresVisitor(MetricRepository metricRepository, MeasureRepository measureRepository,
ComponentIssuesRepository componentIssuesRepository, NewIssueClassifier newIssueClassifier) {
super(LEAVES, POST_ORDER, new CounterFactory(newIssueClassifier));
this.measureRepository = measureRepository;
this.componentIssuesRepository = componentIssuesRepository;
// Output metrics
this.metricsByKey = ImmutableMap.of(
NEW_RELIABILITY_RATING_KEY, metricRepository.getByKey(NEW_RELIABILITY_RATING_KEY),
NEW_SECURITY_RATING_KEY, metricRepository.getByKey(NEW_SECURITY_RATING_KEY));
this.newIssueClassifier = newIssueClassifier;
}
@Override
public void visitProject(Component project, Path<Counter> path) {
computeAndSaveMeasures(project, path);
}
@Override
public void visitDirectory(Component directory, Path<Counter> path) {
computeAndSaveMeasures(directory, path);
}
@Override
public void visitFile(Component file, Path<Counter> path) {
computeAndSaveMeasures(file, path);
}
private void computeAndSaveMeasures(Component component, Path<Counter> path) {
if (!newIssueClassifier.isEnabled()) {
return;
}
initRatingsToA(path);
processIssues(component, path);
path.current().newRatingValueByMetric.entrySet()
.stream()
.filter(entry -> entry.getValue().isSet())
.forEach(
entry -> measureRepository.add(
component,
metricsByKey.get(entry.getKey()),
newMeasureBuilder().create(entry.getValue().getValue().getIndex())));
addToParent(path);
}
private static void initRatingsToA(Path<Counter> path) {
path.current().newRatingValueByMetric.values().forEach(entry -> entry.increment(A));
}
private void processIssues(Component component, Path<Counter> path) {
componentIssuesRepository.getIssues(component)
.stream()
.filter(issue -> issue.resolution() == null)
.filter(issue -> issue.type().equals(BUG) || issue.type().equals(VULNERABILITY))
.forEach(issue -> path.current().processIssue(issue));
}
private static void addToParent(Path<Counter> path) {
if (!path.isRoot()) {
path.parent().add(path.current());
}
}
static class Counter {
private final Map<String, RatingValue> newRatingValueByMetric = Map.of(
NEW_RELIABILITY_RATING_KEY, new RatingValue(),
NEW_SECURITY_RATING_KEY, new RatingValue());
private final NewIssueClassifier newIssueClassifier;
private final Component component;
public Counter(NewIssueClassifier newIssueClassifier, Component component) {
this.newIssueClassifier = newIssueClassifier;
this.component = component;
}
void add(Counter otherCounter) {
newRatingValueByMetric.forEach((metric, rating) -> rating.increment(otherCounter.newRatingValueByMetric.get(metric)));
}
void processIssue(Issue issue) {
if (newIssueClassifier.isNew(component, (DefaultIssue) issue)) {
Rating rating = RATING_BY_SEVERITY.get(issue.severity());
if (issue.type().equals(BUG)) {
newRatingValueByMetric.get(NEW_RELIABILITY_RATING_KEY).increment(rating);
} else if (issue.type().equals(VULNERABILITY)) {
newRatingValueByMetric.get(NEW_SECURITY_RATING_KEY).increment(rating);
}
}
}
}
private static final class CounterFactory extends SimpleStackElementFactory<NewReliabilityAndSecurityRatingMeasuresVisitor.Counter> {
private final NewIssueClassifier newIssueClassifier;
private CounterFactory(NewIssueClassifier newIssueClassifier) {
this.newIssueClassifier = newIssueClassifier;
}
@Override
public Counter createForAny(Component component) {
return new Counter(newIssueClassifier, component);
}
}
}
| 7,192 | 39.410112 | 149 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/qualitymodel/NewSecurityReviewMeasuresVisitor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.qualitymodel;
import java.util.Optional;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.PathAwareVisitorAdapter;
import org.sonar.ce.task.projectanalysis.issue.ComponentIssuesRepository;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import org.sonar.ce.task.projectanalysis.measure.MeasureRepository;
import org.sonar.ce.task.projectanalysis.metric.Metric;
import org.sonar.ce.task.projectanalysis.metric.MetricRepository;
import org.sonar.ce.task.projectanalysis.issue.NewIssueClassifier;
import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS_REVIEWED_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS_REVIEWED_STATUS_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS_TO_REVIEW_STATUS_KEY;
import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_REVIEW_RATING_KEY;
import static org.sonar.api.rules.RuleType.SECURITY_HOTSPOT;
import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.POST_ORDER;
import static org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit.FILE;
import static org.sonar.server.security.SecurityReviewRating.computePercent;
import static org.sonar.server.security.SecurityReviewRating.computeRating;
public class NewSecurityReviewMeasuresVisitor extends PathAwareVisitorAdapter<SecurityReviewCounter> {
private final ComponentIssuesRepository componentIssuesRepository;
private final MeasureRepository measureRepository;
private final Metric newSecurityReviewRatingMetric;
private final Metric newSecurityHotspotsReviewedMetric;
private final Metric newSecurityHotspotsReviewedStatusMetric;
private final Metric newSecurityHotspotsToReviewStatusMetric;
private final NewIssueClassifier newIssueClassifier;
public NewSecurityReviewMeasuresVisitor(ComponentIssuesRepository componentIssuesRepository, MeasureRepository measureRepository, MetricRepository metricRepository,
NewIssueClassifier newIssueClassifier) {
super(FILE, POST_ORDER, NewSecurityReviewMeasuresVisitor.CounterFactory.INSTANCE);
this.componentIssuesRepository = componentIssuesRepository;
this.measureRepository = measureRepository;
this.newSecurityReviewRatingMetric = metricRepository.getByKey(NEW_SECURITY_REVIEW_RATING_KEY);
this.newSecurityHotspotsReviewedMetric = metricRepository.getByKey(NEW_SECURITY_HOTSPOTS_REVIEWED_KEY);
this.newSecurityHotspotsReviewedStatusMetric = metricRepository.getByKey(NEW_SECURITY_HOTSPOTS_REVIEWED_STATUS_KEY);
this.newSecurityHotspotsToReviewStatusMetric = metricRepository.getByKey(NEW_SECURITY_HOTSPOTS_TO_REVIEW_STATUS_KEY);
this.newIssueClassifier = newIssueClassifier;
}
@Override
public void visitProject(Component project, Path<SecurityReviewCounter> path) {
if (!newIssueClassifier.isEnabled()) {
return;
}
computeMeasure(project, path);
// The following measures are only computed on projects level as they are required to compute the others measures on applications
measureRepository.add(project, newSecurityHotspotsReviewedStatusMetric, Measure.newMeasureBuilder().create(path.current().getHotspotsReviewed()));
measureRepository.add(project, newSecurityHotspotsToReviewStatusMetric, Measure.newMeasureBuilder().create(path.current().getHotspotsToReview()));
}
@Override
public void visitDirectory(Component directory, Path<SecurityReviewCounter> path) {
computeMeasure(directory, path);
}
@Override
public void visitFile(Component file, Path<SecurityReviewCounter> path) {
computeMeasure(file, path);
}
private void computeMeasure(Component component, Path<SecurityReviewCounter> path) {
componentIssuesRepository.getIssues(component)
.stream()
.filter(issue -> issue.type().equals(SECURITY_HOTSPOT))
.filter(issue -> newIssueClassifier.isNew(component, issue))
.forEach(issue -> path.current().processHotspot(issue));
Optional<Double> percent = computePercent(path.current().getHotspotsToReview(), path.current().getHotspotsReviewed());
measureRepository.add(component, newSecurityReviewRatingMetric, Measure.newMeasureBuilder().create(computeRating(percent.orElse(null)).getIndex()));
percent.ifPresent(p -> measureRepository.add(component, newSecurityHotspotsReviewedMetric, Measure.newMeasureBuilder().create(p)));
if (!path.isRoot()) {
path.parent().add(path.current());
}
}
private static final class CounterFactory extends SimpleStackElementFactory<SecurityReviewCounter> {
public static final NewSecurityReviewMeasuresVisitor.CounterFactory INSTANCE = new NewSecurityReviewMeasuresVisitor.CounterFactory();
private CounterFactory() {
// prevents instantiation
}
@Override
public SecurityReviewCounter createForAny(Component component) {
return new SecurityReviewCounter();
}
}
}
| 5,822 | 49.198276 | 166 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/qualitymodel/RatingSettings.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.qualitymodel;
import com.google.common.collect.ImmutableMap;
import java.util.Map;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.ce.ComputeEngineSide;
import org.sonar.api.config.Configuration;
import org.sonar.api.utils.MessageException;
import org.sonar.server.measure.DebtRatingGrid;
import static java.lang.String.format;
import static org.sonar.api.CoreProperties.DEVELOPMENT_COST;
import static org.sonar.api.CoreProperties.LANGUAGE_SPECIFIC_PARAMETERS;
import static org.sonar.api.CoreProperties.LANGUAGE_SPECIFIC_PARAMETERS_LANGUAGE_KEY;
import static org.sonar.api.CoreProperties.LANGUAGE_SPECIFIC_PARAMETERS_MAN_DAYS_KEY;
import static org.sonar.api.CoreProperties.LANGUAGE_SPECIFIC_PARAMETERS_SIZE_METRIC_KEY;
@ComputeEngineSide
public class RatingSettings {
private final DebtRatingGrid ratingGrid;
private final long defaultDevCost;
private final Map<String, LanguageSpecificConfiguration> languageSpecificConfigurationByLanguageKey;
public RatingSettings(Configuration config) {
ratingGrid = new DebtRatingGrid(config);
defaultDevCost = initDefaultDevelopmentCost(config);
languageSpecificConfigurationByLanguageKey = initLanguageSpecificConfigurationByLanguageKey(config);
}
public DebtRatingGrid getDebtRatingGrid() {
return ratingGrid;
}
public long getDevCost(@Nullable String languageKey) {
if (languageKey != null) {
try {
LanguageSpecificConfiguration languageSpecificConfig = getSpecificParametersForLanguage(languageKey);
if (languageSpecificConfig != null && languageSpecificConfig.getManDays() != null) {
return Long.parseLong(languageSpecificConfig.getManDays());
}
} catch (NumberFormatException e) {
throw new IllegalArgumentException(format("The manDays for language %s is not a valid long number", languageKey), e);
}
}
return defaultDevCost;
}
@CheckForNull
private LanguageSpecificConfiguration getSpecificParametersForLanguage(String languageKey) {
return languageSpecificConfigurationByLanguageKey.get(languageKey);
}
private static Map<String, LanguageSpecificConfiguration> initLanguageSpecificConfigurationByLanguageKey(Configuration config) {
ImmutableMap.Builder<String, LanguageSpecificConfiguration> builder = ImmutableMap.builder();
String[] languageConfigIndexes = config.getStringArray(LANGUAGE_SPECIFIC_PARAMETERS);
for (String languageConfigIndex : languageConfigIndexes) {
String languagePropertyKey = LANGUAGE_SPECIFIC_PARAMETERS + "." + languageConfigIndex + "." + LANGUAGE_SPECIFIC_PARAMETERS_LANGUAGE_KEY;
String languageKey = config.get(languagePropertyKey)
.orElseThrow(() -> MessageException.of("Technical debt configuration is corrupted. At least one language specific parameter has no Language key. " +
"Contact your administrator to update this configuration in the global administration section of SonarQube."));
builder.put(languageKey, LanguageSpecificConfiguration.create(config, languageConfigIndex));
}
return builder.build();
}
private static long initDefaultDevelopmentCost(Configuration config) {
try {
return Long.parseLong(config.get(DEVELOPMENT_COST).get());
} catch (NumberFormatException e) {
throw new IllegalArgumentException("The value of the development cost property '" + DEVELOPMENT_COST
+ "' is incorrect. Expected long but got '" + config.get(DEVELOPMENT_COST).get() + "'", e);
}
}
@Immutable
private static class LanguageSpecificConfiguration {
private final String language;
private final String manDays;
private final String metricKey;
private LanguageSpecificConfiguration(String language, String manDays, String metricKey) {
this.language = language;
this.manDays = manDays;
this.metricKey = metricKey;
}
static LanguageSpecificConfiguration create(Configuration config, String configurationId) {
String configurationPrefix = LANGUAGE_SPECIFIC_PARAMETERS + "." + configurationId + ".";
String language = config.get(configurationPrefix + LANGUAGE_SPECIFIC_PARAMETERS_LANGUAGE_KEY).orElse(null);
String manDays = config.get(configurationPrefix + LANGUAGE_SPECIFIC_PARAMETERS_MAN_DAYS_KEY).orElse(null);
String metric = config.get(configurationPrefix + LANGUAGE_SPECIFIC_PARAMETERS_SIZE_METRIC_KEY).orElse(null);
return new LanguageSpecificConfiguration(language, manDays, metric);
}
String getLanguage() {
return language;
}
String getManDays() {
return manDays;
}
String getMetricKey() {
return metricKey;
}
}
}
| 5,629 | 41.014925 | 156 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/qualitymodel/ReliabilityAndSecurityRatingMeasuresVisitor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.qualitymodel;
import com.google.common.collect.ImmutableMap;
import java.util.Map;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.PathAwareVisitorAdapter;
import org.sonar.ce.task.projectanalysis.formula.counter.RatingValue;
import org.sonar.ce.task.projectanalysis.issue.ComponentIssuesRepository;
import org.sonar.ce.task.projectanalysis.measure.MeasureRepository;
import org.sonar.ce.task.projectanalysis.measure.RatingMeasures;
import org.sonar.ce.task.projectanalysis.metric.Metric;
import org.sonar.ce.task.projectanalysis.metric.MetricRepository;
import org.sonar.server.measure.Rating;
import static org.sonar.api.measures.CoreMetrics.RELIABILITY_RATING_KEY;
import static org.sonar.api.measures.CoreMetrics.SECURITY_RATING_KEY;
import static org.sonar.api.rules.RuleType.BUG;
import static org.sonar.api.rules.RuleType.VULNERABILITY;
import static org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit.FILE;
import static org.sonar.server.measure.Rating.RATING_BY_SEVERITY;
/**
* Compute following measures for projects and descendants:
* {@link CoreMetrics#RELIABILITY_RATING_KEY}
* {@link CoreMetrics#SECURITY_RATING_KEY}
*/
public class ReliabilityAndSecurityRatingMeasuresVisitor extends PathAwareVisitorAdapter<ReliabilityAndSecurityRatingMeasuresVisitor.Counter> {
private final MeasureRepository measureRepository;
private final ComponentIssuesRepository componentIssuesRepository;
private final Map<String, Metric> metricsByKey;
public ReliabilityAndSecurityRatingMeasuresVisitor(MetricRepository metricRepository, MeasureRepository measureRepository, ComponentIssuesRepository componentIssuesRepository) {
super(FILE, Order.POST_ORDER, CounterFactory.INSTANCE);
this.measureRepository = measureRepository;
this.componentIssuesRepository = componentIssuesRepository;
// Output metrics
Metric reliabilityRatingMetric = metricRepository.getByKey(RELIABILITY_RATING_KEY);
Metric securityRatingMetric = metricRepository.getByKey(SECURITY_RATING_KEY);
this.metricsByKey = ImmutableMap.of(
RELIABILITY_RATING_KEY, reliabilityRatingMetric,
SECURITY_RATING_KEY, securityRatingMetric);
}
@Override
public void visitProject(Component project, Path<Counter> path) {
computeAndSaveMeasures(project, path);
}
@Override
public void visitDirectory(Component directory, Path<Counter> path) {
computeAndSaveMeasures(directory, path);
}
@Override
public void visitFile(Component file, Path<Counter> path) {
computeAndSaveMeasures(file, path);
}
private void computeAndSaveMeasures(Component component, Path<Counter> path) {
processIssues(component, path);
path.current().ratingValueByMetric.forEach((key, value) -> {
Rating rating = value.getValue();
measureRepository.add(component, metricsByKey.get(key), RatingMeasures.get(rating));
});
if (!path.isRoot()) {
path.parent().add(path.current());
}
}
private void processIssues(Component component, Path<Counter> path) {
componentIssuesRepository.getIssues(component)
.stream()
.filter(issue -> issue.resolution() == null)
.forEach(issue -> {
Rating rating = RATING_BY_SEVERITY.get(issue.severity());
if (issue.type().equals(BUG)) {
path.current().ratingValueByMetric.get(RELIABILITY_RATING_KEY).increment(rating);
} else if (issue.type().equals(VULNERABILITY)) {
path.current().ratingValueByMetric.get(SECURITY_RATING_KEY).increment(rating);
}
});
}
static final class Counter {
private Map<String, RatingValue> ratingValueByMetric = ImmutableMap.of(
RELIABILITY_RATING_KEY, new RatingValue(),
SECURITY_RATING_KEY, new RatingValue());
private Counter() {
// prevents instantiation
}
void add(Counter otherCounter) {
ratingValueByMetric.forEach((key, value) -> value.increment(otherCounter.ratingValueByMetric.get(key)));
}
}
private static final class CounterFactory extends PathAwareVisitorAdapter.SimpleStackElementFactory<ReliabilityAndSecurityRatingMeasuresVisitor.Counter> {
public static final CounterFactory INSTANCE = new CounterFactory();
private CounterFactory() {
// prevents instantiation
}
@Override
public Counter createForAny(Component component) {
return new Counter();
}
}
}
| 5,361 | 38.718519 | 179 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/qualitymodel/SecurityReviewCounter.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.qualitymodel;
import org.sonar.api.ce.measure.Issue;
import static org.sonar.api.issue.Issue.STATUS_REVIEWED;
import static org.sonar.api.issue.Issue.STATUS_TO_REVIEW;
final class SecurityReviewCounter {
private int hotspotsReviewed;
private int hotspotsToReview;
SecurityReviewCounter() {
// prevents instantiation
}
void processHotspot(Issue issue) {
if (issue.status().equals(STATUS_REVIEWED)) {
hotspotsReviewed++;
} else if (issue.status().equals(STATUS_TO_REVIEW)) {
hotspotsToReview++;
}
}
void add(SecurityReviewCounter otherCounter) {
hotspotsReviewed += otherCounter.hotspotsReviewed;
hotspotsToReview += otherCounter.hotspotsToReview;
}
public int getHotspotsReviewed() {
return hotspotsReviewed;
}
public int getHotspotsToReview() {
return hotspotsToReview;
}
}
| 1,735 | 30 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/qualitymodel/SecurityReviewMeasuresVisitor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.qualitymodel;
import java.util.Optional;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.PathAwareVisitor;
import org.sonar.ce.task.projectanalysis.component.PathAwareVisitorAdapter;
import org.sonar.ce.task.projectanalysis.issue.ComponentIssuesRepository;
import org.sonar.ce.task.projectanalysis.measure.MeasureRepository;
import org.sonar.ce.task.projectanalysis.measure.RatingMeasures;
import org.sonar.ce.task.projectanalysis.metric.Metric;
import org.sonar.ce.task.projectanalysis.metric.MetricRepository;
import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_REVIEWED_KEY;
import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_REVIEWED_STATUS_KEY;
import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_TO_REVIEW_STATUS_KEY;
import static org.sonar.api.measures.CoreMetrics.SECURITY_REVIEW_RATING_KEY;
import static org.sonar.api.rules.RuleType.SECURITY_HOTSPOT;
import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.POST_ORDER;
import static org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit.FILE;
import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilder;
import static org.sonar.server.security.SecurityReviewRating.computePercent;
import static org.sonar.server.security.SecurityReviewRating.computeRating;
public class SecurityReviewMeasuresVisitor extends PathAwareVisitorAdapter<SecurityReviewCounter> {
private final ComponentIssuesRepository componentIssuesRepository;
private final MeasureRepository measureRepository;
private final Metric securityReviewRatingMetric;
private final Metric securityHotspotsReviewedMetric;
private final Metric securityHotspotsReviewedStatusMetric;
private final Metric securityHotspotsToReviewStatusMetric;
public SecurityReviewMeasuresVisitor(ComponentIssuesRepository componentIssuesRepository, MeasureRepository measureRepository, MetricRepository metricRepository) {
super(FILE, POST_ORDER, SecurityReviewMeasuresVisitor.CounterFactory.INSTANCE);
this.componentIssuesRepository = componentIssuesRepository;
this.measureRepository = measureRepository;
this.securityReviewRatingMetric = metricRepository.getByKey(SECURITY_REVIEW_RATING_KEY);
this.securityHotspotsReviewedMetric = metricRepository.getByKey(SECURITY_HOTSPOTS_REVIEWED_KEY);
this.securityHotspotsReviewedStatusMetric = metricRepository.getByKey(SECURITY_HOTSPOTS_REVIEWED_STATUS_KEY);
this.securityHotspotsToReviewStatusMetric = metricRepository.getByKey(SECURITY_HOTSPOTS_TO_REVIEW_STATUS_KEY);
}
@Override
public void visitProject(Component project, Path<SecurityReviewCounter> path) {
computeMeasure(project, path);
}
@Override
public void visitDirectory(Component directory, PathAwareVisitor.Path<SecurityReviewCounter> path) {
computeMeasure(directory, path);
}
@Override
public void visitFile(Component file, PathAwareVisitor.Path<SecurityReviewCounter> path) {
computeMeasure(file, path);
}
private void computeMeasure(Component component, PathAwareVisitor.Path<SecurityReviewCounter> path) {
componentIssuesRepository.getIssues(component)
.stream()
.filter(issue -> issue.type().equals(SECURITY_HOTSPOT))
.forEach(issue -> path.current().processHotspot(issue));
measureRepository.add(component, securityHotspotsReviewedStatusMetric, newMeasureBuilder().create(path.current().getHotspotsReviewed()));
measureRepository.add(component, securityHotspotsToReviewStatusMetric, newMeasureBuilder().create(path.current().getHotspotsToReview()));
Optional<Double> percent = computePercent(path.current().getHotspotsToReview(), path.current().getHotspotsReviewed());
measureRepository.add(component, securityReviewRatingMetric, RatingMeasures.get(computeRating(percent.orElse(null))));
percent.ifPresent(p -> measureRepository.add(component, securityHotspotsReviewedMetric, newMeasureBuilder().create(p, securityHotspotsReviewedMetric.getDecimalScale())));
if (!path.isRoot()) {
path.parent().add(path.current());
}
}
private static final class CounterFactory extends PathAwareVisitorAdapter.SimpleStackElementFactory<SecurityReviewCounter> {
public static final SecurityReviewMeasuresVisitor.CounterFactory INSTANCE = new SecurityReviewMeasuresVisitor.CounterFactory();
private CounterFactory() {
// prevents instantiation
}
@Override
public SecurityReviewCounter createForAny(Component component) {
return new SecurityReviewCounter();
}
}
}
| 5,496 | 49.898148 | 174 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/qualitymodel/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.qualitymodel;
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/qualityprofile/ActiveRule.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.qualityprofile;
import com.google.common.collect.ImmutableMap;
import java.util.Map;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.rule.RuleKey;
@Immutable
public class ActiveRule {
private final RuleKey ruleKey;
private final String severity;
private final Map<String, String> params;
private final String pluginKey;
private final long updatedAt;
private final String qProfileKey;
public ActiveRule(RuleKey ruleKey, String severity, Map<String, String> params, long updatedAt, @Nullable String pluginKey, String qProfileKey) {
this.ruleKey = ruleKey;
this.severity = severity;
this.pluginKey = pluginKey;
this.params = ImmutableMap.copyOf(params);
this.updatedAt = updatedAt;
this.qProfileKey = qProfileKey;
}
public RuleKey getRuleKey() {
return ruleKey;
}
public String getSeverity() {
return severity;
}
public Map<String, String> getParams() {
return params;
}
public long getUpdatedAt() {
return updatedAt;
}
@CheckForNull
public String getPluginKey() {
return pluginKey;
}
public String getQProfileKey() {
return qProfileKey;
}
}
| 2,114 | 28.375 | 147 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/qualityprofile/ActiveRulesHolder.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.qualityprofile;
import java.util.Optional;
import org.sonar.api.rule.RuleKey;
public interface ActiveRulesHolder {
Optional<ActiveRule> get(RuleKey ruleKey);
}
| 1,051 | 34.066667 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/qualityprofile/ActiveRulesHolderImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.qualityprofile;
import com.google.common.collect.ImmutableMap;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.sonar.api.rule.RuleKey;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
public class ActiveRulesHolderImpl implements ActiveRulesHolder {
private Map<RuleKey, ActiveRule> activeRulesByKey = null;
@Override
public Optional<ActiveRule> get(RuleKey ruleKey) {
checkState(activeRulesByKey != null, "Active rules have not been initialized yet");
return Optional.ofNullable(activeRulesByKey.get(ruleKey));
}
public Collection<ActiveRule> getAll() {
checkState(activeRulesByKey != null, "Active rules have not been initialized yet");
return activeRulesByKey.values();
}
public void set(Collection<ActiveRule> activeRules) {
requireNonNull(activeRules, "Active rules cannot be null");
checkState(activeRulesByKey == null, "Active rules have already been initialized");
Map<RuleKey, ActiveRule> temp = new HashMap<>();
for (ActiveRule activeRule : activeRules) {
ActiveRule previousValue = temp.put(activeRule.getRuleKey(), activeRule);
if (previousValue != null) {
throw new IllegalArgumentException("Active rule must not be declared multiple times: " + activeRule.getRuleKey());
}
}
activeRulesByKey = ImmutableMap.copyOf(temp);
}
}
| 2,342 | 37.409836 | 122 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/qualityprofile/MutableQProfileStatusRepository.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.qualityprofile;
public interface MutableQProfileStatusRepository extends QProfileStatusRepository {
/**
* @throws IllegalStateException if the given quality profile is already registered
*/
void register(String qpKey, Status status);
}
| 1,132 | 39.464286 | 85 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/qualityprofile/QProfileStatusRepository.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.qualityprofile;
import java.util.Optional;
public interface QProfileStatusRepository {
Optional<Status> get(String qpKey);
enum Status {
/**
* the QP was used in the last analysis but not anymore in the current one.
*/
REMOVED,
/**
* the QP was not used in the last analysis
*/
ADDED,
/**
* the QP was used in the last and current analysis and a rule has changed
*/
UPDATED,
/**
* neither the QP or a rule has changed since last analysis
*/
UNCHANGED
}
}
| 1,422 | 29.276596 | 79 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/qualityprofile/QProfileStatusRepositoryImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.qualityprofile;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
public class QProfileStatusRepositoryImpl implements MutableQProfileStatusRepository {
private final Map<String, Status> statuses = new HashMap<>();
@Override
public Optional<Status> get(@Nullable String qpKey) {
return Optional.ofNullable(statuses.get(qpKey));
}
@Override
public void register(String qpKey, Status status) {
checkNotNull(qpKey, "qpKey can't be null");
checkNotNull(status, "status can't be null");
checkState(statuses.put(qpKey, status) == null, "Quality Profile '%s' is already registered", qpKey);
}
}
| 1,696 | 35.891304 | 105 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/qualityprofile/RegisterQualityProfileStatusStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.qualityprofile;
import java.util.Collections;
import java.util.Map;
import java.util.stream.Collectors;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit;
import org.sonar.ce.task.projectanalysis.component.DepthTraversalTypeAwareCrawler;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.projectanalysis.component.TypeAwareVisitorAdapter;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import org.sonar.ce.task.projectanalysis.measure.MeasureRepository;
import org.sonar.ce.task.projectanalysis.metric.MetricRepository;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.server.qualityprofile.QPMeasureData;
import org.sonar.server.qualityprofile.QualityProfile;
import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.POST_ORDER;
import static org.sonar.ce.task.projectanalysis.qualityprofile.QProfileStatusRepository.Status.ADDED;
import static org.sonar.ce.task.projectanalysis.qualityprofile.QProfileStatusRepository.Status.REMOVED;
import static org.sonar.ce.task.projectanalysis.qualityprofile.QProfileStatusRepository.Status.UNCHANGED;
import static org.sonar.ce.task.projectanalysis.qualityprofile.QProfileStatusRepository.Status.UPDATED;
public class RegisterQualityProfileStatusStep implements ComputationStep {
private TreeRootHolder treeRootHolder;
private MeasureRepository measureRepository;
private MetricRepository metricRepository;
private MutableQProfileStatusRepository qProfileStatusRepository;
private AnalysisMetadataHolder analysisMetadataHolder;
public RegisterQualityProfileStatusStep(TreeRootHolder treeRootHolder, MeasureRepository measureRepository, MetricRepository metricRepository,
MutableQProfileStatusRepository qProfileStatusRepository, AnalysisMetadataHolder analysisMetadataHolder) {
this.treeRootHolder = treeRootHolder;
this.measureRepository = measureRepository;
this.metricRepository = metricRepository;
this.qProfileStatusRepository = qProfileStatusRepository;
this.analysisMetadataHolder = analysisMetadataHolder;
}
@Override
public void execute(Context context) {
new DepthTraversalTypeAwareCrawler(
new TypeAwareVisitorAdapter(CrawlerDepthLimit.PROJECT, POST_ORDER) {
@Override
public void visitProject(Component tree) {
executeForProject(tree);
}
}).visit(treeRootHolder.getRoot());
}
private void executeForProject(Component project) {
measureRepository.getBaseMeasure(project, metricRepository.getByKey(CoreMetrics.QUALITY_PROFILES_KEY)).ifPresent(baseProfilesMeasure -> {
Map<String, QualityProfile> baseProfiles = parseJsonData(baseProfilesMeasure);
Map<String, QualityProfile> rawProfiles = analysisMetadataHolder
.getQProfilesByLanguage().values().stream()
.collect(Collectors.toMap(QualityProfile::getQpKey, q -> q));
registerNoMoreUsedProfiles(baseProfiles, rawProfiles);
registerNewOrUpdatedProfiles(baseProfiles, rawProfiles);
});
}
private void registerNoMoreUsedProfiles(Map<String, QualityProfile> baseProfiles, Map<String, QualityProfile> rawProfiles) {
for (QualityProfile baseProfile : baseProfiles.values()) {
if (!rawProfiles.containsKey(baseProfile.getQpKey())) {
register(baseProfile, REMOVED);
}
}
}
private void registerNewOrUpdatedProfiles(Map<String, QualityProfile> baseProfiles, Map<String, QualityProfile> rawProfiles) {
for (QualityProfile profile : rawProfiles.values()) {
QualityProfile baseProfile = baseProfiles.get(profile.getQpKey());
if (baseProfile == null) {
register(profile, ADDED);
} else if (profile.getRulesUpdatedAt().after(baseProfile.getRulesUpdatedAt())) {
register(baseProfile, UPDATED);
} else {
register(baseProfile, UNCHANGED);
}
}
}
private void register(QualityProfile profile, QProfileStatusRepository.Status status) {
qProfileStatusRepository.register(profile.getQpKey(), status);
}
private static Map<String, QualityProfile> parseJsonData(Measure measure) {
String data = measure.getStringValue();
if (data == null) {
return Collections.emptyMap();
}
return QPMeasureData.fromJson(data).getProfilesByKey();
}
@Override
public String getDescription() {
return "Compute Quality Profile status";
}
}
| 5,474 | 43.153226 | 144 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/qualityprofile/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.qualityprofile;
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/scm/Changeset.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.scm;
import java.util.Objects;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import static java.util.Objects.requireNonNull;
@Immutable
public final class Changeset {
@CheckForNull
private final String revision;
private final long date;
@CheckForNull
private final String author;
private Changeset(Builder builder) {
this.revision = builder.revision;
this.author = builder.author;
this.date = builder.date;
}
public static Builder newChangesetBuilder() {
return new Builder();
}
public static class Builder {
private String revision;
private Long date;
@CheckForNull
private String author;
private Builder() {
// prevents direct instantiation
}
public Builder setRevision(@Nullable String revision) {
this.revision = revision;
return this;
}
public Builder setDate(Long date) {
this.date = checkDate(date);
return this;
}
public Builder setAuthor(@Nullable String author) {
this.author = author;
return this;
}
public Changeset build() {
checkDate(date);
return new Changeset(this);
}
private static long checkDate(Long date) {
return requireNonNull(date, "Date cannot be null");
}
}
@CheckForNull
public String getRevision() {
return revision;
}
public long getDate() {
return date;
}
@CheckForNull
public String getAuthor() {
return author;
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Changeset changeset = (Changeset) o;
return Objects.equals(revision, changeset.revision) && Objects.equals(author, changeset.author) && Objects.equals(date, changeset.date);
}
@Override
public int hashCode() {
return Objects.hash(revision, author, date);
}
@Override
public String toString() {
return "Changeset{" +
"revision='" + revision + '\'' +
", author='" + author + '\'' +
", date=" + date +
'}';
}
}
| 3,054 | 23.837398 | 140 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/scm/DbScmInfo.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.scm;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.sonar.db.protobuf.DbFileSources;
/**
* ScmInfo implementation based on the lines stored in DB
*/
@Immutable
class DbScmInfo implements ScmInfo {
private final ScmInfo delegate;
private final String fileHash;
private DbScmInfo(ScmInfo delegate, String fileHash) {
this.delegate = delegate;
this.fileHash = fileHash;
}
public static Optional<DbScmInfo> create(List<DbFileSources.Line> lines, int lineCount, String fileHash) {
LineToChangeset lineToChangeset = new LineToChangeset();
Changeset[] lineChanges = new Changeset[lineCount];
boolean lineAdded = false;
for (DbFileSources.Line line : lines) {
Changeset changeset = lineToChangeset.apply(line);
if (changeset == null) {
continue;
}
lineChanges[line.getLine() - 1] = changeset;
lineAdded = true;
}
if (!lineAdded) {
return Optional.empty();
}
return Optional.of(new DbScmInfo(new ScmInfoImpl(lineChanges), fileHash));
}
public String fileHash() {
return fileHash;
}
@Override
public Changeset getLatestChangeset() {
return delegate.getLatestChangeset();
}
@Override
public Changeset getChangesetForLine(int lineNumber) {
return delegate.getChangesetForLine(lineNumber);
}
@Override
public boolean hasChangesetForLine(int lineNumber) {
return delegate.hasChangesetForLine(lineNumber);
}
@Override
public Changeset[] getAllChangesets() {
return delegate.getAllChangesets();
}
/**
* Transforms {@link org.sonar.db.protobuf.DbFileSources.Line} into {@link Changeset}
*/
private static class LineToChangeset implements Function<DbFileSources.Line, Changeset> {
private final Changeset.Builder builder = Changeset.newChangesetBuilder();
private final Map<Changeset, Changeset> cache = new HashMap<>();
@Override
@Nullable
public Changeset apply(@Nonnull DbFileSources.Line input) {
if (input.hasScmDate()) {
Changeset cs = builder
.setRevision(input.hasScmRevision() ? input.getScmRevision().intern() : null)
.setAuthor(input.hasScmAuthor() ? input.getScmAuthor().intern() : null)
.setDate(input.getScmDate())
.build();
if (cache.containsKey(cs)) {
return cache.get(cs);
}
cache.put(cs, cs);
return cs;
}
return null;
}
}
}
| 3,526 | 29.145299 | 108 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/scm/GeneratedScmInfo.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.scm;
import javax.annotation.concurrent.Immutable;
import static com.google.common.base.Preconditions.checkState;
@Immutable
public class GeneratedScmInfo {
private GeneratedScmInfo() {
// static only
}
public static ScmInfo create(long analysisDate, int lines) {
checkState(lines > 0, "No changesets");
Changeset changeset = Changeset.newChangesetBuilder()
.setDate(analysisDate)
.build();
Changeset[] lineChangeset = new Changeset[lines];
for (int i = 0; i < lines; i++) {
lineChangeset[i] = changeset;
}
return new ScmInfoImpl(lineChangeset);
}
public static ScmInfo create(long analysisDate, int[] matches, ScmInfo dbScmInfo) {
Changeset changeset = Changeset.newChangesetBuilder()
.setDate(analysisDate)
.build();
Changeset[] dbChangesets = dbScmInfo.getAllChangesets();
Changeset[] changesets = new Changeset[matches.length];
for (int i = 0; i < matches.length; i++) {
// db changeset can be null if it contains no date
if (matches[i] > 0 && dbChangesets[matches[i] - 1] != null) {
changesets[i] = dbChangesets[matches[i] - 1];
} else {
changesets[i] = changeset;
}
}
return new ScmInfoImpl(changesets);
}
}
| 2,142 | 31.969231 | 85 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/scm/ReportScmInfo.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.scm;
import java.util.HashMap;
import java.util.Map;
import java.util.function.IntFunction;
import javax.annotation.concurrent.Immutable;
import org.sonar.scanner.protocol.output.ScannerReport;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
import static org.apache.commons.lang.StringUtils.isNotEmpty;
/**
* ScmInfo implementation based on the changeset information from the Report
*/
@Immutable
class ReportScmInfo {
ReportScmInfo() {
// static only
}
public static ScmInfo create(ScannerReport.Changesets changesets) {
requireNonNull(changesets);
Changeset[] lineChangesets = new Changeset[changesets.getChangesetIndexByLineCount()];
LineIndexToChangeset lineIndexToChangeset = new LineIndexToChangeset(changesets);
for (int i = 0; i < changesets.getChangesetIndexByLineCount(); i++) {
lineChangesets[i] = lineIndexToChangeset.apply(i);
}
return new ScmInfoImpl(lineChangesets);
}
private static class LineIndexToChangeset implements IntFunction<Changeset> {
private final ScannerReport.Changesets changesets;
private final Map<Integer, Changeset> changesetCache;
private final Changeset.Builder builder = Changeset.newChangesetBuilder();
private LineIndexToChangeset(ScannerReport.Changesets changesets) {
this.changesets = changesets;
this.changesetCache = new HashMap<>(changesets.getChangesetCount());
}
@Override
public Changeset apply(int lineNumber) {
int changesetIndex = changesets.getChangesetIndexByLine(lineNumber);
return changesetCache.computeIfAbsent(changesetIndex, idx -> convert(changesets.getChangeset(changesetIndex), lineNumber));
}
private Changeset convert(ScannerReport.Changesets.Changeset changeset, int line) {
checkState(isNotEmpty(changeset.getRevision()), "Changeset on line %s must have a revision", line + 1);
checkState(changeset.getDate() != 0, "Changeset on line %s must have a date", line + 1);
return builder
.setRevision(changeset.getRevision().intern())
.setAuthor(isNotEmpty(changeset.getAuthor()) ? changeset.getAuthor().intern() : null)
.setDate(changeset.getDate())
.build();
}
}
}
| 3,150 | 37.901235 | 129 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/scm/ScmInfo.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.scm;
/**
* Represents changeset information for a file. If SCM information is present, it will be the author, revision and date fetched from SCM
* for every line. Otherwise, it's a date that corresponds the the analysis date in which the line was modified.
*/
public interface ScmInfo {
/**
* Get most recent ChangeSet of the file. Can never be null
*/
Changeset getLatestChangeset();
/**
* Get ChangeSet of the file for given line
*
* @throws IllegalArgumentException if there is no Changeset for the specified line
*/
Changeset getChangesetForLine(int lineNumber);
/**
* Check if there's a ChangeSet for given line
*/
boolean hasChangesetForLine(int lineNumber);
/**
* Return all ChangeSets, index by line number. Some values might be null.
*/
Changeset[] getAllChangesets();
}
| 1,721 | 32.764706 | 136 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/scm/ScmInfoDbLoader.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.scm;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.analysis.Branch;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.ReferenceBranchComponentUuids;
import org.sonar.ce.task.projectanalysis.filemove.MovedFilesRepository;
import org.sonar.ce.task.projectanalysis.period.NewCodeReferenceBranchComponentUuids;
import org.sonar.ce.task.projectanalysis.period.PeriodHolder;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.newcodeperiod.NewCodePeriodType;
import org.sonar.db.source.FileSourceDto;
public class ScmInfoDbLoader {
private static final Logger LOGGER = LoggerFactory.getLogger(ScmInfoDbLoader.class);
private final AnalysisMetadataHolder analysisMetadataHolder;
private final MovedFilesRepository movedFilesRepository;
private final DbClient dbClient;
private final ReferenceBranchComponentUuids referenceBranchComponentUuid;
private final NewCodeReferenceBranchComponentUuids newCodeReferenceBranchComponentUuids;
private final PeriodHolder periodHolder;
public ScmInfoDbLoader(AnalysisMetadataHolder analysisMetadataHolder, MovedFilesRepository movedFilesRepository,
DbClient dbClient,
ReferenceBranchComponentUuids referenceBranchComponentUuid,
NewCodeReferenceBranchComponentUuids newCodeReferenceBranchComponentUuids,
PeriodHolder periodHolder) {
this.analysisMetadataHolder = analysisMetadataHolder;
this.movedFilesRepository = movedFilesRepository;
this.dbClient = dbClient;
this.referenceBranchComponentUuid = referenceBranchComponentUuid;
this.newCodeReferenceBranchComponentUuids = newCodeReferenceBranchComponentUuids;
this.periodHolder = periodHolder;
}
public Optional<DbScmInfo> getScmInfo(Component file) {
Optional<String> uuid = getFileUUid(file);
if (uuid.isEmpty()) {
return Optional.empty();
}
LOGGER.trace("Reading SCM info from DB for file '{}'", uuid.get());
try (DbSession dbSession = dbClient.openSession(false)) {
FileSourceDto dto = dbClient.fileSourceDao().selectByFileUuid(dbSession, uuid.get());
if (dto == null) {
return Optional.empty();
}
return DbScmInfo.create(dto.getSourceData().getLinesList(), dto.getLineCount(), dto.getSrcHash());
}
}
private Optional<String> getFileUUid(Component file) {
if (!analysisMetadataHolder.isFirstAnalysis() && !analysisMetadataHolder.isPullRequest() && !isReferenceBranch()) {
Optional<MovedFilesRepository.OriginalFile> originalFile = movedFilesRepository.getOriginalFile(file);
if (originalFile.isPresent()) {
return originalFile.map(MovedFilesRepository.OriginalFile::uuid);
}
return Optional.of(file.getUuid());
}
if (isReferenceBranch()) {
var referencedBranchComponentUuid = newCodeReferenceBranchComponentUuids.getComponentUuid(file.getKey());
if (referencedBranchComponentUuid != null) {
return Optional.of(referencedBranchComponentUuid);
}
// no file to diff was found or missing reference branch changeset - use existing file
return Optional.of(file.getUuid());
}
// at this point, it's the first analysis of a branch with copyFromPrevious flag true or any analysis of a PR
Branch branch = analysisMetadataHolder.getBranch();
if (!branch.isMain()) {
return Optional.ofNullable(referenceBranchComponentUuid.getComponentUuid(file.getKey()));
}
return Optional.empty();
}
private boolean isReferenceBranch() {
return periodHolder.hasPeriod() && periodHolder.getPeriod().getMode().equals(NewCodePeriodType.REFERENCE_BRANCH.name());
}
}
| 4,720 | 42.712963 | 124 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/scm/ScmInfoImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.scm;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.utils.Preconditions;
@Immutable
public class ScmInfoImpl implements ScmInfo {
private final Changeset latestChangeset;
private final Changeset[] lineChangesets;
public ScmInfoImpl(Changeset[] lineChangesets) {
Preconditions.checkNotNull(lineChangesets);
Preconditions.checkState(lineChangesets.length > 0, "ScmInfo cannot be empty");
this.lineChangesets = lineChangesets;
this.latestChangeset = computeLatestChangeset(lineChangesets);
}
private static Changeset computeLatestChangeset(Changeset[] lineChangesets) {
return Arrays.stream(lineChangesets).filter(Objects::nonNull).max(Comparator.comparingLong(Changeset::getDate))
.orElseThrow(() -> new IllegalStateException("Expecting at least one Changeset to be present"));
}
@Override
public Changeset getLatestChangeset() {
return latestChangeset;
}
@Override
public Changeset getChangesetForLine(int lineNumber) {
if (!hasChangesetForLine(lineNumber)) {
throw new IllegalArgumentException("There's no changeset on line " + lineNumber);
}
return lineChangesets[lineNumber - 1];
}
@Override
public boolean hasChangesetForLine(int lineNumber) {
return lineNumber > 0 && lineNumber - 1 < lineChangesets.length && lineChangesets[lineNumber - 1] != null;
}
@Override
public Changeset[] getAllChangesets() {
return lineChangesets;
}
@Override
public String toString() {
return "ScmInfoImpl{" +
"latestChangeset=" + latestChangeset +
", lineChangesets={" + IntStream.range(0, lineChangesets.length).mapToObj(i -> i + 1 + "=" + lineChangesets[i]).collect(Collectors.joining(", "))
+ "}}";
}
}
| 2,774 | 34.576923 | 151 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/scm/ScmInfoRepository.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.scm;
import java.util.Optional;
import org.sonar.ce.task.projectanalysis.component.Component;
/**
* Return SCM information of components.
*
* It will always search in the db if there's nothing in the report.
*/
public interface ScmInfoRepository {
/**
* Returns Scm info for the specified component if there is any, first looking into the report, then into the database
* <p>
* If there's nothing in the report and in the db (on first analysis for instance), then it return a {@link Optional#empty()}.
* </p>
* <p>
* This method will always return {@link Optional#empty()} if the specified component's type is not {@link Component.Type#FILE}.
* </p>
*
* @throws NullPointerException if argument is {@code null}
*/
Optional<ScmInfo> getScmInfo(Component component);
}
| 1,693 | 36.644444 | 130 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/scm/ScmInfoRepositoryImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with 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.scm;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.batch.BatchReportReader;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.FileStatuses;
import org.sonar.ce.task.projectanalysis.source.SourceLinesDiff;
import org.sonar.scanner.protocol.output.ScannerReport;
import static java.util.Objects.requireNonNull;
public class ScmInfoRepositoryImpl implements ScmInfoRepository {
private static final Logger LOGGER = LoggerFactory.getLogger(ScmInfoRepositoryImpl.class);
private final BatchReportReader scannerReportReader;
private final Map<Component, Optional<ScmInfo>> scmInfoCache = new HashMap<>();
private final ScmInfoDbLoader scmInfoDbLoader;
private final AnalysisMetadataHolder analysisMetadata;
private final SourceLinesDiff sourceLinesDiff;
private final FileStatuses fileStatuses;
public ScmInfoRepositoryImpl(BatchReportReader scannerReportReader, AnalysisMetadataHolder analysisMetadata, ScmInfoDbLoader scmInfoDbLoader,
SourceLinesDiff sourceLinesDiff, FileStatuses fileStatuses) {
this.scannerReportReader = scannerReportReader;
this.analysisMetadata = analysisMetadata;
this.scmInfoDbLoader = scmInfoDbLoader;
this.sourceLinesDiff = sourceLinesDiff;
this.fileStatuses = fileStatuses;
}
@Override
public Optional<ScmInfo> getScmInfo(Component component) {
requireNonNull(component, "Component cannot be null");
if (component.getType() != Component.Type.FILE) {
return Optional.empty();
}
return scmInfoCache.computeIfAbsent(component, this::getScmInfoForComponent);
}
private Optional<ScmInfo> getScmInfoForComponent(Component component) {
ScannerReport.Changesets changesets = scannerReportReader.readChangesets(component.getReportAttributes().getRef());
if (changesets == null) {
LOGGER.trace("No SCM info for file '{}'", component.getKey());
// SCM not available. It might have been available before - copy information for unchanged lines but don't keep author and revision.
return generateAndMergeDb(component, false);
}
// will be empty if the flag "copy from previous" is set, or if the file is empty.
if (changesets.getChangesetCount() == 0) {
return generateAndMergeDb(component, changesets.getCopyFromPrevious());
}
return getScmInfoFromReport(component, changesets);
}
private static Optional<ScmInfo> getScmInfoFromReport(Component file, ScannerReport.Changesets changesets) {
LOGGER.trace("Reading SCM info from report for file '{}'", file.getKey());
return Optional.of(ReportScmInfo.create(changesets));
}
private Optional<ScmInfo> generateScmInfoForAllFile(Component file) {
if (file.getFileAttributes().getLines() == 0) {
return Optional.empty();
}
return Optional.of(GeneratedScmInfo.create(analysisMetadata.getAnalysisDate(), file.getFileAttributes().getLines()));
}
private static ScmInfo removeAuthorAndRevision(ScmInfo info) {
Changeset[] changesets = Arrays.stream(info.getAllChangesets())
.map(ScmInfoRepositoryImpl::removeAuthorAndRevision)
.toArray(Changeset[]::new);
return new ScmInfoImpl(changesets);
}
@CheckForNull
private static Changeset removeAuthorAndRevision(@Nullable Changeset changeset) {
// some changesets might be null if they are missing in the DB or if they contained no date
if (changeset == null) {
return null;
}
return Changeset.newChangesetBuilder().setDate(changeset.getDate()).build();
}
/**
* Get SCM information in the DB, if it exists, and use it for lines that didn't change. It optionally removes author and revision
* information (only keeping change dates).
* If the information is not present in the DB or some lines don't match existing lines in the DB,
* we generate change dates based on the analysis date.
*/
private Optional<ScmInfo> generateAndMergeDb(Component file, boolean keepAuthorAndRevision) {
Optional<DbScmInfo> dbInfoOpt = scmInfoDbLoader.getScmInfo(file);
if (dbInfoOpt.isEmpty()) {
return generateScmInfoForAllFile(file);
}
ScmInfo scmInfo = keepAuthorAndRevision ? dbInfoOpt.get() : removeAuthorAndRevision(dbInfoOpt.get());
if (fileStatuses.isUnchanged(file)) {
return Optional.of(scmInfo);
}
// generate date for new/changed lines
int[] matchingLines = sourceLinesDiff.computeMatchingLines(file);
return Optional.of(GeneratedScmInfo.create(analysisMetadata.getAnalysisDate(), matchingLines, scmInfo));
}
}
| 5,744 | 40.630435 | 143 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/scm/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.ce.task.projectanalysis.scm;
import javax.annotation.ParametersAreNonnullByDefault;
| 977 | 39.75 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/DbLineHashVersion.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.source;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.CheckForNull;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.ReferenceBranchComponentUuids;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.source.LineHashVersion;
public class DbLineHashVersion {
private final Map<Component, LineHashVersion> lineHashVersionPerComponent = new HashMap<>();
private final DbClient dbClient;
private final AnalysisMetadataHolder analysisMetadataHolder;
private final ReferenceBranchComponentUuids referenceBranchComponentUuids;
public DbLineHashVersion(DbClient dbClient, AnalysisMetadataHolder analysisMetadataHolder, ReferenceBranchComponentUuids referenceBranchComponentUuids) {
this.dbClient = dbClient;
this.analysisMetadataHolder = analysisMetadataHolder;
this.referenceBranchComponentUuids = referenceBranchComponentUuids;
}
/**
* Reads from DB the version of line hashes for a component and returns whether it was generated taking into account the ranges of significant code.
* The response is cached.
* Returns false if the component is not in the DB.
*/
public boolean hasLineHashesWithSignificantCode(Component component) {
return lineHashVersionPerComponent.computeIfAbsent(component, this::compute) == LineHashVersion.WITH_SIGNIFICANT_CODE;
}
/**
* Reads from DB the version of line hashes for a component and returns whether it was generated taking into account the ranges of significant code.
* The response is cached.
* Returns false if the component is not in the DB.
*/
public boolean hasLineHashesWithoutSignificantCode(Component component) {
return lineHashVersionPerComponent.computeIfAbsent(component, this::compute) == LineHashVersion.WITHOUT_SIGNIFICANT_CODE;
}
@CheckForNull
private LineHashVersion compute(Component component) {
try (DbSession session = dbClient.openSession(false)) {
String referenceComponentUuid = getReferenceComponentUuid(component);
if (referenceComponentUuid != null) {
return dbClient.fileSourceDao().selectLineHashesVersion(session, referenceComponentUuid);
} else {
return null;
}
}
}
@CheckForNull
private String getReferenceComponentUuid(Component component) {
if (analysisMetadataHolder.isPullRequest()) {
return referenceBranchComponentUuids.getComponentUuid(component.getKey());
} else {
return component.getUuid();
}
}
}
| 3,507 | 41.26506 | 155 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/FileSourceDataComputer.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.source;
import java.util.List;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.scm.Changeset;
import org.sonar.core.hash.SourceHashComputer;
import org.sonar.core.util.CloseableIterator;
import org.sonar.db.protobuf.DbFileSources;
public class FileSourceDataComputer {
private final SourceLinesRepository sourceLinesRepository;
private final SourceLineReadersFactory sourceLineReadersFactory;
private final SourceLinesHashRepository sourceLinesHash;
private final SourceHashComputer sourceHashComputer;
public FileSourceDataComputer(SourceLinesRepository sourceLinesRepository, SourceLineReadersFactory sourceLineReadersFactory,
SourceLinesHashRepository sourceLinesHash) {
this.sourceLinesRepository = sourceLinesRepository;
this.sourceLineReadersFactory = sourceLineReadersFactory;
this.sourceLinesHash = sourceLinesHash;
this.sourceHashComputer = new SourceHashComputer();
}
public Data compute(Component file, FileSourceDataWarnings fileSourceDataWarnings) {
try (CloseableIterator<String> linesIterator = sourceLinesRepository.readLines(file);
SourceLineReadersFactory.LineReaders lineReaders = sourceLineReadersFactory.getLineReaders(file)) {
SourceLinesHashRepositoryImpl.LineHashesComputer lineHashesComputer = sourceLinesHash.getLineHashesComputerToPersist(file);
DbFileSources.Data.Builder fileSourceBuilder = DbFileSources.Data.newBuilder();
int currentLine = 0;
while (linesIterator.hasNext()) {
currentLine++;
String lineSource = linesIterator.next();
boolean hasNextLine = linesIterator.hasNext();
sourceHashComputer.addLine(lineSource, hasNextLine);
lineHashesComputer.addLine(lineSource);
DbFileSources.Line.Builder lineBuilder = fileSourceBuilder
.addLinesBuilder()
.setSource(lineSource)
.setLine(currentLine);
lineReaders.read(lineBuilder, readError -> fileSourceDataWarnings.addWarning(file, readError));
}
Changeset latestChangeWithRevision = lineReaders.getLatestChangeWithRevision();
return new Data(fileSourceBuilder.build(), lineHashesComputer.getResult(), sourceHashComputer.getHash(), latestChangeWithRevision);
}
}
public static class Data {
private final DbFileSources.Data fileSourceData;
private final List<String> lineHashes;
private final String srcHash;
private final Changeset latestChangeWithRevision;
public Data(DbFileSources.Data fileSourceData, List<String> lineHashes, String srcHash, @Nullable Changeset latestChangeWithRevision) {
this.fileSourceData = fileSourceData;
this.lineHashes = lineHashes;
this.srcHash = srcHash;
this.latestChangeWithRevision = latestChangeWithRevision;
}
public String getSrcHash() {
return srcHash;
}
public List<String> getLineHashes() {
return lineHashes;
}
public DbFileSources.Data getLineData() {
return fileSourceData;
}
@CheckForNull
public Changeset getLatestChangeWithRevision() {
return latestChangeWithRevision;
}
}
}
| 4,118 | 38.605769 | 139 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/FileSourceDataWarnings.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.source;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.HashSet;
import java.util.Set;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.log.CeTaskMessages;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.source.linereader.LineReader;
import static com.google.common.base.Preconditions.checkState;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.joining;
import static org.sonar.ce.task.projectanalysis.source.linereader.LineReader.Data.HIGHLIGHTING;
import static org.sonar.ce.task.projectanalysis.source.linereader.LineReader.Data.SYMBOLS;
public class FileSourceDataWarnings {
private static final Comparator<Component> COMPONENT_COMPARATOR = Comparator.comparingInt(t -> t.getReportAttributes().getRef());
private final CeTaskMessages taskMessages;
private final System2 system2;
private final EnumMap<LineReader.Data, Set<Component>> fileErrorsPerData = new EnumMap<>(LineReader.Data.class);
private boolean closed = false;
public FileSourceDataWarnings(CeTaskMessages taskMessages, System2 system2) {
this.taskMessages = taskMessages;
this.system2 = system2;
}
public void addWarning(Component file, LineReader.ReadError readError) {
checkNotCommitted();
requireNonNull(file, "file can't be null");
requireNonNull(readError, "readError can't be null");
fileErrorsPerData.compute(readError.data(), (data, existingList) -> {
Set<Component> res = existingList == null ? new HashSet<>() : existingList;
res.add(file);
return res;
});
}
public void commitWarnings() {
checkNotCommitted();
this.closed = true;
createWarning(HIGHLIGHTING, "highlighting");
createWarning(SYMBOLS, "symbol");
}
private void createWarning(LineReader.Data data, String dataWording) {
Set<Component> filesWithErrors = fileErrorsPerData.get(data);
if (filesWithErrors == null) {
return;
}
taskMessages.add(new CeTaskMessages.Message(computeMessage(dataWording, filesWithErrors), system2.now()));
}
private static String computeMessage(String dataWording, Set<Component> filesWithErrors) {
if (filesWithErrors.size() == 1) {
Component file = filesWithErrors.iterator().next();
return format("Inconsistent %s data detected on file '%s'. " +
"File source may have been modified while analysis was running.",
dataWording,
file.getName());
}
String lineHeader = "\n ° ";
return format("Inconsistent %s data detected on some files (%s in total). " +
"File source may have been modified while analysis was running.", dataWording, filesWithErrors.size())
+ filesWithErrors.stream()
.sorted(COMPONENT_COMPARATOR)
.limit(5)
.map(Component::getName)
.collect(joining(lineHeader, lineHeader, ""));
}
private void checkNotCommitted() {
checkState(!closed, "warnings already commit");
}
}
| 3,940 | 37.637255 | 131 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/LastCommitVisitor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.source;
import java.util.Optional;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit;
import org.sonar.ce.task.projectanalysis.component.PathAwareVisitorAdapter;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import org.sonar.ce.task.projectanalysis.measure.MeasureRepository;
import org.sonar.ce.task.projectanalysis.metric.Metric;
import org.sonar.ce.task.projectanalysis.metric.MetricRepository;
import org.sonar.ce.task.projectanalysis.scm.ScmInfo;
import org.sonar.ce.task.projectanalysis.scm.ScmInfoRepository;
import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.POST_ORDER;
public class LastCommitVisitor extends PathAwareVisitorAdapter<LastCommitVisitor.LastCommit> {
private final MeasureRepository measureRepository;
private final ScmInfoRepository scmInfoRepository;
private final Metric lastCommitDateMetric;
public LastCommitVisitor(MetricRepository metricRepository, MeasureRepository measureRepository, ScmInfoRepository scmInfoRepository) {
super(CrawlerDepthLimit.LEAVES, POST_ORDER, new SimpleStackElementFactory<LastCommit>() {
@Override
public LastCommit createForAny(Component component) {
return new LastCommit();
}
/** Stack item is not used at ProjectView level, saves on instantiating useless objects */
@Override
public LastCommit createForProjectView(Component projectView) {
return null;
}
});
this.measureRepository = measureRepository;
this.scmInfoRepository = scmInfoRepository;
this.lastCommitDateMetric = metricRepository.getByKey(CoreMetrics.LAST_COMMIT_DATE_KEY);
}
@Override
public void visitProject(Component project, Path<LastCommit> path) {
saveAndAggregate(project, path);
}
@Override
public void visitDirectory(Component directory, Path<LastCommit> path) {
saveAndAggregate(directory, path);
}
@Override
public void visitFile(Component file, Path<LastCommit> path) {
// load SCM blame information from report. It can be absent when the file was not touched
// since previous analysis (optimization to decrease execution of blame commands). In this case
// the date is loaded from database, as it did not change from previous analysis.
Optional<ScmInfo> scmInfoOptional = scmInfoRepository.getScmInfo(file);
if (scmInfoOptional.isPresent()) {
ScmInfo scmInfo = scmInfoOptional.get();
path.current().addDate(scmInfo.getLatestChangeset().getDate());
}
saveAndAggregate(file, path);
}
@Override
public void visitView(Component view, Path<LastCommit> path) {
saveAndAggregate(view, path);
}
@Override
public void visitSubView(Component subView, Path<LastCommit> path) {
saveAndAggregate(subView, path);
}
@Override
public void visitProjectView(Component projectView, Path<LastCommit> path) {
Optional<Measure> rawMeasure = measureRepository.getRawMeasure(projectView, lastCommitDateMetric);
// path.parent() should never fail as a project view must never be a root component
rawMeasure.ifPresent(measure -> path.parent().addDate(measure.getLongValue()));
}
private void saveAndAggregate(Component component, Path<LastCommit> path) {
long maxDate = path.current().getDate();
if (maxDate > 0L) {
measureRepository.add(component, lastCommitDateMetric, Measure.newMeasureBuilder().create(maxDate));
if (!path.isRoot()) {
path.parent().addDate(maxDate);
}
}
}
public static final class LastCommit {
private long date = 0;
public void addDate(long l) {
this.date = Math.max(this.date, l);
}
public long getDate() {
return date;
}
}
}
| 4,701 | 36.919355 | 137 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/NewLinesRepository.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.source;
import com.google.common.base.Preconditions;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.batch.BatchReportReader;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.period.PeriodHolder;
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.db.newcodeperiod.NewCodePeriodType;
public class NewLinesRepository {
private final BatchReportReader reportReader;
private final AnalysisMetadataHolder analysisMetadataHolder;
private final ScmInfoRepository scmInfoRepository;
private final PeriodHolder periodHolder;
private final Map<Component, Optional<Set<Integer>>> reportChangedLinesCache = new HashMap<>();
public NewLinesRepository(BatchReportReader reportReader, AnalysisMetadataHolder analysisMetadataHolder, PeriodHolder periodHolder, ScmInfoRepository scmInfoRepository) {
this.reportReader = reportReader;
this.analysisMetadataHolder = analysisMetadataHolder;
this.scmInfoRepository = scmInfoRepository;
this.periodHolder = periodHolder;
}
public boolean newLinesAvailable() {
return analysisMetadataHolder.isPullRequest() || periodHolder.hasPeriodDate() || isReferenceBranch();
}
public Optional<Set<Integer>> getNewLines(Component file) {
Preconditions.checkArgument(file.getType() == Component.Type.FILE, "Changed lines are only available on files, but was: " + file.getType().name());
if (!newLinesAvailable()) {
return Optional.empty();
}
Optional<Set<Integer>> reportChangedLines = getChangedLinesFromReport(file);
if (reportChangedLines.isPresent()) {
return reportChangedLines;
}
return computeNewLinesFromScm(file);
}
/**
* If the changed lines are not in the report or if we are not analyzing a P/R or a branch using a "reference branch", we fall back to this method.
* If there is a period and SCM information, we compare the change dates of each line with the start of the period to figure out if a line is new or not.
*/
private Optional<Set<Integer>> computeNewLinesFromScm(Component component) {
Optional<ScmInfo> scmInfoOpt = scmInfoRepository.getScmInfo(component);
if (scmInfoOpt.isEmpty()) {
return Optional.empty();
}
ScmInfo scmInfo = scmInfoOpt.get();
Changeset[] allChangesets = scmInfo.getAllChangesets();
Set<Integer> lines = new HashSet<>();
// in PRs, we consider changes introduced in this analysis as new, hence subtracting 1.
long referenceDate = useAnalysisDateAsReferenceDate() ? (analysisMetadataHolder.getAnalysisDate() - 1) : periodHolder.getPeriod().getDate();
for (int i = 0; i < allChangesets.length; i++) {
if (allChangesets[i] != null && isLineInPeriod(allChangesets[i].getDate(), referenceDate)) {
lines.add(i + 1);
}
}
return Optional.of(lines);
}
private boolean useAnalysisDateAsReferenceDate() {
return analysisMetadataHolder.isPullRequest() || NewCodePeriodType.REFERENCE_BRANCH.name().equals(periodHolder.getPeriod().getMode());
}
/**
* A line belongs to a Period if its date is older than the SNAPSHOT's date of the period.
*/
private static boolean isLineInPeriod(long lineDate, long referenceDate) {
return lineDate > referenceDate;
}
private Optional<Set<Integer>> getChangedLinesFromReport(Component file) {
if (analysisMetadataHolder.isPullRequest() || isReferenceBranch()) {
return reportChangedLinesCache.computeIfAbsent(file, this::readFromReport);
}
return Optional.empty();
}
private boolean isReferenceBranch() {
return periodHolder.hasPeriod() && periodHolder.getPeriod().getMode().equals(NewCodePeriodType.REFERENCE_BRANCH.name());
}
private Optional<Set<Integer>> readFromReport(Component file) {
return reportReader.readComponentChangedLines(file.getReportAttributes().getRef())
.map(c -> new HashSet<>(c.getLineList()));
}
}
| 5,119 | 41.666667 | 172 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/PersistFileSourcesStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.source;
import java.util.List;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.ObjectUtils;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit;
import org.sonar.ce.task.projectanalysis.component.DepthTraversalTypeAwareCrawler;
import org.sonar.ce.task.projectanalysis.component.PreviousSourceHashRepository;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.projectanalysis.component.TypeAwareVisitorAdapter;
import org.sonar.ce.task.projectanalysis.scm.Changeset;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.core.util.UuidFactory;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.protobuf.DbFileSources;
import org.sonar.db.source.FileHashesDto;
import org.sonar.db.source.FileSourceDto;
import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.PRE_ORDER;
public class PersistFileSourcesStep implements ComputationStep {
private final DbClient dbClient;
private final System2 system2;
private final TreeRootHolder treeRootHolder;
private final SourceLinesHashRepository sourceLinesHash;
private final FileSourceDataComputer fileSourceDataComputer;
private final FileSourceDataWarnings fileSourceDataWarnings;
private final UuidFactory uuidFactory;
private final PreviousSourceHashRepository previousSourceHashRepository;
public PersistFileSourcesStep(DbClient dbClient, System2 system2, TreeRootHolder treeRootHolder,
SourceLinesHashRepository sourceLinesHash, FileSourceDataComputer fileSourceDataComputer,
FileSourceDataWarnings fileSourceDataWarnings, UuidFactory uuidFactory, PreviousSourceHashRepository previousSourceHashRepository) {
this.dbClient = dbClient;
this.system2 = system2;
this.treeRootHolder = treeRootHolder;
this.sourceLinesHash = sourceLinesHash;
this.fileSourceDataComputer = fileSourceDataComputer;
this.fileSourceDataWarnings = fileSourceDataWarnings;
this.uuidFactory = uuidFactory;
this.previousSourceHashRepository = previousSourceHashRepository;
}
@Override
public void execute(ComputationStep.Context context) {
// Don't use batch insert for file_sources since keeping all data in memory can produce OOM for big files
try (DbSession dbSession = dbClient.openSession(false)) {
new DepthTraversalTypeAwareCrawler(new FileSourceVisitor(dbSession))
.visit(treeRootHolder.getRoot());
} finally {
fileSourceDataWarnings.commitWarnings();
}
}
private class FileSourceVisitor extends TypeAwareVisitorAdapter {
private final DbSession session;
private String branchUuid;
private FileSourceVisitor(DbSession session) {
super(CrawlerDepthLimit.FILE, PRE_ORDER);
this.session = session;
}
@Override
public void visitProject(Component branch) {
this.branchUuid = branch.getUuid();
}
@Override
public void visitFile(Component file) {
try {
FileSourceDataComputer.Data fileSourceData = fileSourceDataComputer.compute(file, fileSourceDataWarnings);
persistSource(fileSourceData, file);
} catch (Exception e) {
throw new IllegalStateException(String.format("Cannot persist sources of %s", file.getKey()), e);
}
}
private void persistSource(FileSourceDataComputer.Data fileSourceData, Component file) {
DbFileSources.Data lineData = fileSourceData.getLineData();
byte[] binaryData = FileSourceDto.encodeSourceData(lineData);
String dataHash = DigestUtils.md5Hex(binaryData);
String srcHash = fileSourceData.getSrcHash();
List<String> lineHashes = fileSourceData.getLineHashes();
Changeset latestChangeWithRevision = fileSourceData.getLatestChangeWithRevision();
int lineHashesVersion = sourceLinesHash.getLineHashesVersion(file);
FileHashesDto previousDto = previousSourceHashRepository.getDbFile(file).orElse(null);
if (previousDto == null) {
FileSourceDto dto = new FileSourceDto()
.setUuid(uuidFactory.create())
.setProjectUuid(branchUuid)
.setFileUuid(file.getUuid())
.setBinaryData(binaryData)
.setSrcHash(srcHash)
.setDataHash(dataHash)
.setLineHashes(lineHashes)
.setLineHashesVersion(lineHashesVersion)
.setCreatedAt(system2.now())
.setUpdatedAt(system2.now())
.setRevision(computeRevision(latestChangeWithRevision));
dbClient.fileSourceDao().insert(session, dto);
session.commit();
} else {
// Update only if data_hash has changed or if src_hash is missing or revision is missing (progressive migration)
boolean binaryDataUpdated = !dataHash.equals(previousDto.getDataHash());
boolean srcHashUpdated = !srcHash.equals(previousDto.getSrcHash());
String revision = computeRevision(latestChangeWithRevision);
boolean revisionUpdated = !ObjectUtils.equals(revision, previousDto.getRevision());
boolean lineHashesVersionUpdated = previousDto.getLineHashesVersion() != lineHashesVersion;
if (binaryDataUpdated || srcHashUpdated || revisionUpdated || lineHashesVersionUpdated) {
FileSourceDto updatedDto = new FileSourceDto()
.setUuid(previousDto.getUuid())
.setBinaryData(binaryData)
.setDataHash(dataHash)
.setSrcHash(srcHash)
.setLineHashes(lineHashes)
.setLineHashesVersion(lineHashesVersion)
.setRevision(revision)
.setUpdatedAt(system2.now());
dbClient.fileSourceDao().update(session, updatedDto);
session.commit();
}
}
}
@CheckForNull
private String computeRevision(@Nullable Changeset latestChangeWithRevision) {
if (latestChangeWithRevision == null) {
return null;
}
return latestChangeWithRevision.getRevision();
}
}
@Override
public String getDescription() {
return "Persist sources";
}
}
| 7,106 | 42.072727 | 136 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/ReportIterator.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.source;
import com.google.common.base.Throwables;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Parser;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.sonar.core.util.CloseableIterator;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
public class ReportIterator<E> extends CloseableIterator<E> {
private final Parser<E> parser;
private InputStream stream;
public ReportIterator(File file, Parser<E> parser) {
try {
this.parser = parser;
this.stream = FileUtils.openInputStream(file);
} catch (IOException e) {
throw Throwables.propagate(e);
}
}
@Override
protected E doNext() {
try {
return parser.parseDelimitedFrom(stream);
} catch (InvalidProtocolBufferException e) {
throw Throwables.propagate(e);
}
}
@Override
protected void doClose() {
IOUtils.closeQuietly(stream);
}
}
| 1,858 | 29.47541 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/SignificantCodeRepository.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.source;
import java.util.Optional;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.core.hash.LineRange;
import org.sonar.core.util.CloseableIterator;
import org.sonar.scanner.protocol.output.ScannerReport.LineSgnificantCode;
import org.sonar.ce.task.projectanalysis.batch.BatchReportReader;
public class SignificantCodeRepository {
private final BatchReportReader reportReader;
public SignificantCodeRepository(BatchReportReader reportReader) {
this.reportReader = reportReader;
}
public Optional<LineRange[]> getRangesPerLine(Component component) {
int numLines = component.getFileAttributes().getLines();
Optional<CloseableIterator<LineSgnificantCode>> opt = reportReader.readComponentSignificantCode(component.getReportAttributes().getRef());
if (!opt.isPresent()) {
return Optional.empty();
}
try (CloseableIterator<LineSgnificantCode> significantCode = opt.get()) {
return Optional.of(toArray(significantCode, numLines));
}
}
private static LineRange[] toArray(CloseableIterator<LineSgnificantCode> lineRanges, int numLines) {
LineRange[] ranges = new LineRange[numLines];
LineSgnificantCode currentLine = null;
for (int i = 0; i < numLines; i++) {
if (currentLine == null) {
if (!lineRanges.hasNext()) {
break;
}
currentLine = lineRanges.next();
}
if (currentLine.getLine() == i + 1) {
ranges[i] = new LineRange(currentLine.getStartOffset(), currentLine.getEndOffset());
currentLine = null;
}
}
return ranges;
}
}
| 2,493 | 35.144928 | 142 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/SourceHashRepository.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.source;
import org.sonar.ce.task.projectanalysis.component.Component;
public interface SourceHashRepository {
/**
* The hash of the source of the specified FILE component in the analysis report.
* <p>
* The source hash will be cached by the repository so that only the first call to this method will cost a file
* access on disk.
* </p>
*
* @throws NullPointerException if specified component is {@code null}
* @throws IllegalArgumentException if specified component if not a {@link Component.Type#FILE}
* @throws IllegalStateException if source hash for the specified component can not be computed
*/
String getRawSourceHash(Component file);
}
| 1,568 | 38.225 | 113 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/SourceHashRepositoryImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.source;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.core.hash.SourceHashComputer;
import org.sonar.core.util.CloseableIterator;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
public class SourceHashRepositoryImpl implements SourceHashRepository {
private static final String SOURCE_OR_HASH_FAILURE_ERROR_MSG = "Failed to read source and compute hashes for component %s";
private final SourceLinesRepository sourceLinesRepository;
private final Map<String, String> rawSourceHashesByKey = new HashMap<>();
public SourceHashRepositoryImpl(SourceLinesRepository sourceLinesRepository) {
this.sourceLinesRepository = sourceLinesRepository;
}
@Override
public String getRawSourceHash(Component file) {
checkComponentArgument(file);
if (rawSourceHashesByKey.containsKey(file.getKey())) {
return checkSourceHash(file.getKey(), rawSourceHashesByKey.get(file.getKey()));
} else {
String newSourceHash = computeRawSourceHash(file);
rawSourceHashesByKey.put(file.getKey(), newSourceHash);
return checkSourceHash(file.getKey(), newSourceHash);
}
}
private static void checkComponentArgument(Component file) {
requireNonNull(file, "Specified component can not be null");
checkArgument(file.getType() == Component.Type.FILE, "File source information can only be retrieved from FILE components (got %s)", file.getType());
}
private String computeRawSourceHash(Component file) {
SourceHashComputer sourceHashComputer = new SourceHashComputer();
try (CloseableIterator<String> linesIterator = sourceLinesRepository.readLines(file)) {
while (linesIterator.hasNext()) {
sourceHashComputer.addLine(linesIterator.next(), linesIterator.hasNext());
}
return sourceHashComputer.getHash();
}
}
private static String checkSourceHash(String fileKey, @Nullable String newSourceHash) {
checkState(newSourceHash != null, SOURCE_OR_HASH_FAILURE_ERROR_MSG, fileKey);
return newSourceHash;
}
}
| 3,128 | 40.171053 | 152 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/SourceLineReadersFactory.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.source;
import com.google.common.annotations.VisibleForTesting;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.ce.task.projectanalysis.batch.BatchReportReader;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.duplication.DuplicationRepository;
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.ce.task.projectanalysis.source.linereader.CoverageLineReader;
import org.sonar.ce.task.projectanalysis.source.linereader.DuplicationLineReader;
import org.sonar.ce.task.projectanalysis.source.linereader.HighlightingLineReader;
import org.sonar.ce.task.projectanalysis.source.linereader.IsNewLineReader;
import org.sonar.ce.task.projectanalysis.source.linereader.LineReader;
import org.sonar.ce.task.projectanalysis.source.linereader.RangeOffsetConverter;
import org.sonar.ce.task.projectanalysis.source.linereader.ScmLineReader;
import org.sonar.ce.task.projectanalysis.source.linereader.SymbolsLineReader;
import org.sonar.core.util.CloseableIterator;
import org.sonar.db.protobuf.DbFileSources;
import org.sonar.scanner.protocol.output.ScannerReport;
public class SourceLineReadersFactory {
private final BatchReportReader reportReader;
private final ScmInfoRepository scmInfoRepository;
private final DuplicationRepository duplicationRepository;
private final NewLinesRepository newLinesRepository;
public SourceLineReadersFactory(BatchReportReader reportReader, ScmInfoRepository scmInfoRepository, DuplicationRepository duplicationRepository,
NewLinesRepository newLinesRepository) {
this.reportReader = reportReader;
this.scmInfoRepository = scmInfoRepository;
this.duplicationRepository = duplicationRepository;
this.newLinesRepository = newLinesRepository;
}
public LineReaders getLineReaders(Component component) {
List<LineReader> readers = new ArrayList<>();
List<CloseableIterator<?>> closeables = new ArrayList<>();
ScmLineReader scmLineReader = null;
int componentRef = component.getReportAttributes().getRef();
CloseableIterator<ScannerReport.LineCoverage> coverageIt = reportReader.readComponentCoverage(componentRef);
closeables.add(coverageIt);
readers.add(new CoverageLineReader(coverageIt));
Optional<ScmInfo> scmInfoOptional = scmInfoRepository.getScmInfo(component);
if (scmInfoOptional.isPresent()) {
scmLineReader = new ScmLineReader(scmInfoOptional.get());
readers.add(scmLineReader);
}
RangeOffsetConverter rangeOffsetConverter = new RangeOffsetConverter();
CloseableIterator<ScannerReport.SyntaxHighlightingRule> highlightingIt = reportReader.readComponentSyntaxHighlighting(componentRef);
closeables.add(highlightingIt);
readers.add(new HighlightingLineReader(component, highlightingIt, rangeOffsetConverter));
CloseableIterator<ScannerReport.Symbol> symbolsIt = reportReader.readComponentSymbols(componentRef);
closeables.add(symbolsIt);
readers.add(new SymbolsLineReader(component, symbolsIt, rangeOffsetConverter));
readers.add(new DuplicationLineReader(duplicationRepository.getDuplications(component)));
readers.add(new IsNewLineReader(newLinesRepository, component));
return new LineReadersImpl(readers, scmLineReader, closeables);
}
interface LineReaders extends AutoCloseable {
void read(DbFileSources.Line.Builder lineBuilder, Consumer<LineReader.ReadError> readErrorConsumer);
@CheckForNull
Changeset getLatestChangeWithRevision();
@Override
void close();
}
@VisibleForTesting
static final class LineReadersImpl implements LineReaders {
final List<LineReader> readers;
@Nullable
final ScmLineReader scmLineReader;
final List<CloseableIterator<?>> closeables;
LineReadersImpl(List<LineReader> readers, @Nullable ScmLineReader scmLineReader, List<CloseableIterator<?>> closeables) {
this.readers = readers;
this.scmLineReader = scmLineReader;
this.closeables = closeables;
}
@Override
public void close() {
for (CloseableIterator<?> reportIterator : closeables) {
reportIterator.close();
}
}
public void read(DbFileSources.Line.Builder lineBuilder, Consumer<LineReader.ReadError> readErrorConsumer) {
for (LineReader r : readers) {
r.read(lineBuilder)
.ifPresent(readErrorConsumer);
}
}
@Override
@CheckForNull
public Changeset getLatestChangeWithRevision() {
return scmLineReader == null ? null : scmLineReader.getLatestChangeWithRevision();
}
}
}
| 5,725 | 41.102941 | 147 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/SourceLinesDiff.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.source;
import org.sonar.ce.task.projectanalysis.component.Component;
public interface SourceLinesDiff {
/**
* Creates a diff between the file in the database and the file in the report using Myers' algorithm, and links matching lines between
* both files.
* @return an array with one entry for each line in the left side. Those entries point either to a line in the right side, or to 0,
* in which case it means the line was added.
*/
int[] computeMatchingLines(Component component);
}
| 1,394 | 41.272727 | 136 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/SourceLinesDiffFinder.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.source;
import difflib.myers.DifferentiationFailedException;
import difflib.myers.MyersDiff;
import difflib.myers.PathNode;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SourceLinesDiffFinder {
private static final Logger LOG = LoggerFactory.getLogger(SourceLinesDiffFinder.class);
public int[] findMatchingLines(List<String> left, List<String> right) {
int[] index = new int[right.size()];
int dbLine = left.size();
int reportLine = right.size();
try {
PathNode node = new MyersDiff<String>().buildPath(left, right);
while (node.prev != null) {
PathNode prevNode = node.prev;
if (!node.isSnake()) {
// additions
reportLine -= (node.j - prevNode.j);
// removals
dbLine -= (node.i - prevNode.i);
} else {
// matches
for (int i = node.i; i > prevNode.i; i--) {
index[reportLine - 1] = dbLine;
reportLine--;
dbLine--;
}
}
node = prevNode;
}
} catch (DifferentiationFailedException e) {
LOG.error("Error finding matching lines", e);
return index;
}
return index;
}
}
| 2,112 | 31.015152 | 89 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/SourceLinesDiffImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.source;
import java.util.Collections;
import java.util.List;
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.period.NewCodeReferenceBranchComponentUuids;
import org.sonar.ce.task.projectanalysis.component.ReferenceBranchComponentUuids;
import org.sonar.ce.task.projectanalysis.filemove.MovedFilesRepository;
import org.sonar.ce.task.projectanalysis.period.PeriodHolder;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.newcodeperiod.NewCodePeriodType;
import org.sonar.db.source.FileSourceDao;
public class SourceLinesDiffImpl implements SourceLinesDiff {
private final DbClient dbClient;
private final FileSourceDao fileSourceDao;
private final SourceLinesHashRepository sourceLinesHash;
private final ReferenceBranchComponentUuids referenceBranchComponentUuids;
private final MovedFilesRepository movedFilesRepository;
private final AnalysisMetadataHolder analysisMetadataHolder;
private final PeriodHolder periodHolder;
private final NewCodeReferenceBranchComponentUuids newCodeReferenceBranchComponentUuids;
public SourceLinesDiffImpl(DbClient dbClient, FileSourceDao fileSourceDao, SourceLinesHashRepository sourceLinesHash, ReferenceBranchComponentUuids referenceBranchComponentUuids,
MovedFilesRepository movedFilesRepository, AnalysisMetadataHolder analysisMetadataHolder, PeriodHolder periodHolder,
NewCodeReferenceBranchComponentUuids newCodeReferenceBranchComponentUuids) {
this.dbClient = dbClient;
this.fileSourceDao = fileSourceDao;
this.sourceLinesHash = sourceLinesHash;
this.referenceBranchComponentUuids = referenceBranchComponentUuids;
this.movedFilesRepository = movedFilesRepository;
this.analysisMetadataHolder = analysisMetadataHolder;
this.periodHolder = periodHolder;
this.newCodeReferenceBranchComponentUuids = newCodeReferenceBranchComponentUuids;
}
@Override
public int[] computeMatchingLines(Component component) {
List<String> database = getDBLines(component);
List<String> report = getReportLines(component);
return new SourceLinesDiffFinder().findMatchingLines(database, report);
}
private List<String> getDBLines(Component component) {
try (DbSession dbSession = dbClient.openSession(false)) {
String uuid;
if (analysisMetadataHolder.isPullRequest()) {
uuid = referenceBranchComponentUuids.getComponentUuid(component.getKey());
} else if (periodHolder.hasPeriod() && periodHolder.getPeriod().getMode().equals(NewCodePeriodType.REFERENCE_BRANCH.name())) {
uuid = newCodeReferenceBranchComponentUuids.getComponentUuid(component.getKey());
} else {
Optional<MovedFilesRepository.OriginalFile> originalFile = movedFilesRepository.getOriginalFile(component);
uuid = originalFile.map(MovedFilesRepository.OriginalFile::uuid).orElse(component.getUuid());
}
if (uuid == null) {
return Collections.emptyList();
}
List<String> database = fileSourceDao.selectLineHashes(dbSession, uuid);
if (database == null) {
return Collections.emptyList();
}
return database;
}
}
private List<String> getReportLines(Component component) {
return sourceLinesHash.getLineHashesMatchingDBVersion(component);
}
}
| 4,314 | 43.484536 | 180 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/SourceLinesHashCache.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.source;
import com.google.common.base.Preconditions;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import org.sonar.api.utils.TempFolder;
import org.sonar.ce.task.projectanalysis.component.Component;
public class SourceLinesHashCache {
private static final String FILE_NAME_PREFIX = "hashes-";
private final Path cacheDirectoryPath;
private final Set<Integer> cacheFileIds = new HashSet<>();
public SourceLinesHashCache(TempFolder tempFolder) {
this.cacheDirectoryPath = tempFolder.newDir().toPath();
}
public List<String> computeIfAbsent(Component component, Function<Component, List<String>> hashesComputer) {
int ref = getId(component);
if (cacheFileIds.add(ref)) {
List<String> hashes = hashesComputer.apply(component);
save(ref, hashes);
return hashes;
} else {
return load(ref);
}
}
/**
* @throws IllegalStateException if the requested value is not cached
*/
public List<String> get(Component component) {
Preconditions.checkState(contains(component), "Source line hashes for component %s not cached", component);
return load(getId(component));
}
public boolean contains(Component component) {
return cacheFileIds.contains(getId(component));
}
private static int getId(Component component) {
return component.getReportAttributes().getRef();
}
private void save(int fileId, List<String> hashes) {
Path filePath = getFilePath(fileId);
try {
Files.write(filePath, hashes, StandardCharsets.UTF_8);
} catch (IOException e) {
throw new IllegalStateException(String.format("Failed to write to '%s'", filePath), e);
}
}
private List<String> load(int fileId) {
Path filePath = getFilePath(fileId);
try {
return Files.readAllLines(filePath, StandardCharsets.UTF_8);
} catch (IOException e) {
throw new IllegalStateException(String.format("Failed to read '%s'", filePath), e);
}
}
private Path getFilePath(int fileId) {
return cacheDirectoryPath.resolve(FILE_NAME_PREFIX + fileId);
}
}
| 3,130 | 32.308511 | 111 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/source/SourceLinesHashRepository.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.source;
import java.util.List;
import org.sonar.ce.task.projectanalysis.component.Component;
/**
* Generates line hashes from source code included in the report.
* Line hashes are versioned. Currently there are 2 possible versions: Hashes created using the entire line, or hashes created using
* only the "significant code" part of the line. The "significant code" can be optionally provided by code analyzers, meaning that
* the line hash for a given file can be of either versions.
* We always persist line hashes taking into account "significant code", if it's provided.
* When the line hashes are used for comparison with line hashes stored in the DB, we try to generate them using the same version
* as the ones in the DB. This ensures that the line hashes are actually comparable.
*/
public interface SourceLinesHashRepository {
/**
* Read from the report the line hashes for a file.
* The line hashes will have the version matching the version of the line hashes existing in the report, if possible.
*/
List<String> getLineHashesMatchingDBVersion(Component component);
/**
* Get a line hash computer that can be used when persisting the line hashes in the DB.
* The version of the line hashes that are generated by the computer will be the one that takes into account significant code,
* if it was provided by a code analyzer.
*/
SourceLinesHashRepositoryImpl.LineHashesComputer getLineHashesComputerToPersist(Component component);
/**
* Get the version of the line hashes for a given component in the report
*/
int getLineHashesVersion(Component component);
}
| 2,507 | 46.320755 | 132 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.