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/component/ComponentUuidFactory.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
public interface ComponentUuidFactory {
/**
* Get UUID from database if it exists, otherwise generate a new one.
*/
String getOrCreateForKey(String key);
}
| 1,064 | 35.724138 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/ComponentUuidFactoryImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.sonar.ce.task.projectanalysis.analysis.Branch;
import org.sonar.core.util.Uuids;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchType;
import org.sonar.db.component.KeyWithUuidDto;
public class ComponentUuidFactoryImpl implements ComponentUuidFactory {
private final Map<String, String> uuidsByKey = new HashMap<>();
/** For the sake of consistency it is important that sub-portfolios have the same uuid as the associated component.
* As sub-portfolio have no component associated with their creation, it is necessary to look search for their uuid.
* see SONAR-19407 for more info
*
* @param dbClient
* @param dbSession
* @param rootKey
*/
public ComponentUuidFactoryImpl(DbClient dbClient, DbSession dbSession, String rootKey) {
List<KeyWithUuidDto> projectKeys = dbClient.componentDao().selectUuidsByKeyFromProjectKey(dbSession, rootKey);
List<KeyWithUuidDto> portFolioKeys = dbClient.portfolioDao().selectUuidsByKey(dbSession, rootKey);
projectKeys.forEach(dto -> uuidsByKey.put(dto.key(), dto.uuid()));
portFolioKeys.forEach(dto -> uuidsByKey.putIfAbsent(dto.key(), dto.uuid()));
}
public ComponentUuidFactoryImpl(DbClient dbClient, DbSession dbSession, String rootKey, Branch branch) {
List<KeyWithUuidDto> keys;
if (branch.isMain()) {
keys = dbClient.componentDao().selectUuidsByKeyFromProjectKey(dbSession, rootKey);
} else if (branch.getType() == BranchType.PULL_REQUEST) {
keys = dbClient.componentDao().selectUuidsByKeyFromProjectKeyAndPullRequest(dbSession, rootKey, branch.getPullRequestKey());
} else {
keys = dbClient.componentDao().selectUuidsByKeyFromProjectKeyAndBranch(dbSession, rootKey, branch.getName());
}
keys.forEach(dto -> uuidsByKey.put(dto.key(), dto.uuid()));
}
/**
* Get UUID from database if it exists, otherwise generate a new one.
*/
@Override
public String getOrCreateForKey(String key) {
return uuidsByKey.computeIfAbsent(key, k -> Uuids.create());
}
}
| 3,028 | 42.271429 | 130 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/ComponentVisitor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
public interface ComponentVisitor {
Order getOrder();
CrawlerDepthLimit getMaxDepth();
enum Order {
/**
* Each component is visited BEFORE its children. Top-down traversal of
* tree of components.
*/
PRE_ORDER,
/**
* Each component is visited AFTER its children. Bottom-up traversal of
* tree of components.
*/
POST_ORDER
}
}
| 1,281 | 29.52381 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/ConfigurationRepository.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
import org.sonar.api.config.Configuration;
public interface ConfigurationRepository {
Configuration getConfiguration();
}
| 1,024 | 34.344828 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/ConfigurationRepositoryImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import org.sonar.api.config.Configuration;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.analysis.ProjectConfigurationFactory;
/**
* Repository of component settings implementation based on a memory cache.
*/
public class ConfigurationRepositoryImpl implements ConfigurationRepository {
private final Supplier<Configuration> configuration;
public ConfigurationRepositoryImpl(AnalysisMetadataHolder analysisMetadataHolder, ProjectConfigurationFactory f) {
this.configuration = Suppliers.memoize(() -> {
String projectUuid = analysisMetadataHolder.getProject().getUuid();
return f.newProjectConfiguration(projectUuid);
});
}
@Override
public Configuration getConfiguration() {
return configuration.get();
}
}
| 1,796 | 37.234043 | 116 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/CrawlerDepthLimit.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import static com.google.common.base.Preconditions.checkArgument;
/**
* Represents the limit down a {@link Component} tree a {@link ComponentCrawler} can go to.
*
* A limit can be defined for a tree of Report components, a tree of Views components or both.
*
* Constants are provided for limits specific to a component tree (see {@link #PROJECT}).
*
* Limits for both trees can be created using the {@link #reportMaxDepth(Component.Type)} static method.
*/
@Immutable
public class CrawlerDepthLimit {
private static final String UNSUPPORTED_TYPE_UOE_MSG = "Specified type is neither a report type nor a views type";
public static final CrawlerDepthLimit PROJECT = new CrawlerDepthLimit(Component.Type.PROJECT, null);
public static final CrawlerDepthLimit DIRECTORY = new CrawlerDepthLimit(Component.Type.DIRECTORY, null);
public static final CrawlerDepthLimit FILE = new CrawlerDepthLimit(Component.Type.FILE, null);
public static final CrawlerDepthLimit VIEW = new CrawlerDepthLimit(null, Component.Type.VIEW);
public static final CrawlerDepthLimit SUBVIEW = new CrawlerDepthLimit(null, Component.Type.SUBVIEW);
public static final CrawlerDepthLimit PROJECT_VIEW = new CrawlerDepthLimit(null, Component.Type.PROJECT_VIEW);
public static final CrawlerDepthLimit LEAVES = new CrawlerDepthLimit(Component.Type.FILE, Component.Type.PROJECT_VIEW);
public static final CrawlerDepthLimit ROOTS = new CrawlerDepthLimit(Component.Type.PROJECT, Component.Type.VIEW);
@CheckForNull
private final Component.Type reportMaxDepth;
@CheckForNull
private final Component.Type viewsMaxDepth;
private CrawlerDepthLimit(@Nullable Component.Type reportMaxDepth, @Nullable Component.Type viewsMaxDepth) {
checkArgument(reportMaxDepth != null || viewsMaxDepth != null,
"At least one type must be non null");
checkArgument(reportMaxDepth == null || reportMaxDepth.isReportType());
checkArgument(viewsMaxDepth == null || viewsMaxDepth.isViewsType());
this.reportMaxDepth = reportMaxDepth;
this.viewsMaxDepth = viewsMaxDepth;
}
public static Builder reportMaxDepth(Component.Type reportMaxDepth) {
return new Builder(reportMaxDepth);
}
public static class Builder {
private final Component.Type reportMaxDepth;
public Builder(Component.Type reportMaxDepth) {
checkArgument(reportMaxDepth.isReportType(), "A Report max depth must be a report type");
this.reportMaxDepth = reportMaxDepth;
}
public CrawlerDepthLimit withViewsMaxDepth(Component.Type viewsMaxDepth) {
checkArgument(viewsMaxDepth.isViewsType(), "A Views max depth must be a views type");
return new CrawlerDepthLimit(reportMaxDepth, viewsMaxDepth);
}
}
public boolean isDeeperThan(Component.Type otherType) {
if (otherType.isViewsType()) {
return this.viewsMaxDepth != null && this.viewsMaxDepth.isDeeperThan(otherType);
}
if (otherType.isReportType()) {
return this.reportMaxDepth != null && this.reportMaxDepth.isDeeperThan(otherType);
}
throw new UnsupportedOperationException(UNSUPPORTED_TYPE_UOE_MSG);
}
public boolean isHigherThan(Component.Type otherType) {
if (otherType.isViewsType()) {
return this.viewsMaxDepth != null && this.viewsMaxDepth.isHigherThan(otherType);
}
if (otherType.isReportType()) {
return this.reportMaxDepth != null && this.reportMaxDepth.isHigherThan(otherType);
}
throw new UnsupportedOperationException(UNSUPPORTED_TYPE_UOE_MSG);
}
public boolean isSameAs(Component.Type otherType) {
if (otherType.isViewsType()) {
return otherType == this.viewsMaxDepth;
}
if (otherType.isReportType()) {
return otherType == this.reportMaxDepth;
}
throw new UnsupportedOperationException(UNSUPPORTED_TYPE_UOE_MSG);
}
}
| 4,831 | 41.761062 | 121 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/DefaultBranchImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
import org.sonar.ce.task.projectanalysis.analysis.Branch;
import org.sonar.db.component.BranchType;
/**
* Implementation of {@link Branch} for default/main branch. It is used
* when no branch is provided as a scanner parameter or if the branch plugin is not installed.
*/
public class DefaultBranchImpl implements Branch {
private final String branchName;
public DefaultBranchImpl(String branch) {
this.branchName = branch;
}
@Override
public BranchType getType() {
return BranchType.BRANCH;
}
@Override
public boolean isMain() {
return true;
}
@Override
public String getReferenceBranchUuid() {
throw new IllegalStateException("Not valid for the main branch");
}
@Override
public String getName() {
return branchName;
}
@Override
public boolean supportsCrossProjectCpd() {
return true;
}
@Override
public String getPullRequestKey() {
throw new IllegalStateException("Only a branch of type PULL_REQUEST can have a pull request id.");
}
@Override
public String getTargetBranchName() {
throw new IllegalStateException("Only on a pull request");
}
}
| 2,036 | 27.690141 | 102 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/DepthTraversalTypeAwareCrawler.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
import static java.util.Objects.requireNonNull;
/**
* Implementation of {@link ComponentCrawler} that implements a depth traversal of a {@link Component} tree.
* <p>It supports visiting traversal in either pre-order or post-order</p>
* It supports a max depth for crawling (component strictly deeper than the specified type will be ignored).
*/
public final class DepthTraversalTypeAwareCrawler implements ComponentCrawler {
private final TypeAwareVisitor visitor;
public DepthTraversalTypeAwareCrawler(TypeAwareVisitor visitor) {
this.visitor = requireNonNull(visitor);
}
@Override
public void visit(Component component) {
try {
visitImpl(component);
} catch (RuntimeException e) {
VisitException.rethrowOrWrap(e, "Visit of Component {key=%s,uuid=%s,type=%s} failed", component.getKey(), component.getUuid(), component.getType());
}
}
private void visitImpl(Component component) {
if (!verifyDepth(component)) {
return;
}
if (this.visitor.getOrder() == ComponentVisitor.Order.PRE_ORDER) {
visitNode(component);
}
visitChildren(component);
if (this.visitor.getOrder() == ComponentVisitor.Order.POST_ORDER) {
visitNode(component);
}
}
private boolean verifyDepth(Component component) {
CrawlerDepthLimit maxDepth = this.visitor.getMaxDepth();
return maxDepth.isSameAs(component.getType()) || maxDepth.isDeeperThan(component.getType());
}
private void visitNode(Component component) {
this.visitor.visitAny(component);
switch (component.getType()) {
case PROJECT:
this.visitor.visitProject(component);
break;
case DIRECTORY:
this.visitor.visitDirectory(component);
break;
case FILE:
this.visitor.visitFile(component);
break;
case VIEW:
this.visitor.visitView(component);
break;
case SUBVIEW:
this.visitor.visitSubView(component);
break;
case PROJECT_VIEW:
this.visitor.visitProjectView(component);
break;
default:
throw new IllegalArgumentException("Unsupported Component type " + component.getType());
}
}
private void visitChildren(Component component) {
for (Component child : component.getChildren()) {
if (verifyDepth(child)) {
visit(child);
}
}
}
}
| 3,261 | 31.29703 | 154 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/DequeBasedPath.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;
import java.util.NoSuchElementException;
final class DequeBasedPath<T> implements PathAwareVisitor.Path<T>, Iterable<PathAwareVisitor.PathElement<T>> {
private final Deque<PathAwareVisitor.PathElement<T>> deque = new ArrayDeque<>();
@Override
public T current() {
return deque.getFirst().element();
}
@Override
public T parent() {
Iterator<PathAwareVisitor.PathElement<T>> iterator = deque.iterator();
if (iterator.hasNext()) {
iterator.next();
if (iterator.hasNext()) {
return iterator.next().element();
}
}
throw new NoSuchElementException("Path is either empty or has only one element. There is no parent");
}
@Override
public boolean isRoot() {
return deque.size() == 1;
}
@Override
public T root() {
return deque.getLast().element();
}
@Override
public Iterator<PathAwareVisitor.PathElement<T>> iterator() {
return deque.iterator();
}
@Override
public Iterable<PathAwareVisitor.PathElement<T>> getCurrentPath() {
return this;
}
public void add(PathAwareVisitor.PathElement<T> pathElement) {
deque.addFirst(pathElement);
}
public PathAwareVisitor.PathElement<T> pop() {
return deque.pop();
}
}
| 2,200 | 28.346667 | 110 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/DisabledComponentsHolder.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
import java.util.Set;
public interface DisabledComponentsHolder {
Set<String> getUuids();
}
| 994 | 33.310345 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/DisabledComponentsHolderImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
import java.util.Set;
import static com.google.common.base.Preconditions.checkState;
public class DisabledComponentsHolderImpl implements MutableDisabledComponentsHolder {
private Set<String> uuids = null;
@Override
public Set<String> getUuids() {
checkState(uuids != null, "UUIDs have not been set in repository");
return uuids;
}
@Override
public void setUuids(Set<String> uuids) {
checkState(this.uuids == null, "UUIDs have already been set in repository");
this.uuids = uuids;
}
}
| 1,417 | 32.761905 | 86 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/FileAttributes.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import static com.google.common.base.Preconditions.checkArgument;
import static org.apache.commons.lang.StringUtils.abbreviate;
import static org.apache.commons.lang.StringUtils.trimToNull;
import static org.sonar.db.component.ComponentValidator.MAX_COMPONENT_NAME_LENGTH;
/**
* The attributes specific to a Component of type {@link Component.Type#FILE}.
*/
@Immutable
public class FileAttributes {
private final boolean unitTest;
@CheckForNull
private final String languageKey;
private final boolean markedAsUnchanged;
private final int lines;
private String oldRelativePath;
public FileAttributes(boolean unitTest, @Nullable String languageKey, int lines) {
this(unitTest, languageKey, lines, false, null);
}
public FileAttributes(boolean unitTest, @Nullable String languageKey, int lines, boolean markedAsUnchanged, @Nullable String oldRelativePath) {
this.unitTest = unitTest;
this.languageKey = languageKey;
this.markedAsUnchanged = markedAsUnchanged;
checkArgument(lines > 0, "Number of lines must be greater than zero");
this.lines = lines;
this.oldRelativePath = formatOldRelativePath(oldRelativePath);
}
public boolean isMarkedAsUnchanged() {
return markedAsUnchanged;
}
public boolean isUnitTest() {
return unitTest;
}
@CheckForNull
public String getLanguageKey() {
return languageKey;
}
/**
* The old relative path of a file when a move is detected by the SCM in the scope of a Pull Request.
*/
@CheckForNull
public String getOldRelativePath() {
return oldRelativePath;
}
/**
* Number of lines of the file, can never be less than 1
*/
public int getLines() {
return lines;
}
@Override
public String toString() {
return "FileAttributes{" +
"languageKey='" + languageKey + '\'' +
", unitTest=" + unitTest +
", lines=" + lines +
", markedAsUnchanged=" + markedAsUnchanged +
", oldRelativePath='" + oldRelativePath + '\'' +
'}';
}
private static String formatOldRelativePath(@Nullable String path) {
return abbreviate(trimToNull(path), MAX_COMPONENT_NAME_LENGTH);
}
}
| 3,165 | 30.979798 | 145 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/FileStatuses.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
import java.util.Set;
public interface FileStatuses {
/**
* A file is unchanged compared to the last analysis if it was detected as unchanged by the scanner and
* it's confirmed to be unchanged by the CE, by comparing file hashes.
*/
boolean isUnchanged(Component component);
boolean isDataUnchanged(Component component);
Set<String> getFileUuidsMarkedAsUnchanged();
}
| 1,287 | 34.777778 | 105 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/FileStatusesImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.source.SourceHashRepository;
import org.sonar.db.source.FileHashesDto;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Collections.unmodifiableSet;
import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.PRE_ORDER;
public class FileStatusesImpl implements FileStatuses {
private final PreviousSourceHashRepository previousSourceHashRepository;
private final SourceHashRepository sourceHashRepository;
private final AnalysisMetadataHolder analysisMetadataHolder;
private final TreeRootHolder treeRootHolder;
private Set<String> fileUuidsMarkedAsUnchanged;
public FileStatusesImpl(AnalysisMetadataHolder analysisMetadataHolder, TreeRootHolder treeRootHolder, PreviousSourceHashRepository previousSourceHashRepository,
SourceHashRepository sourceHashRepository) {
this.analysisMetadataHolder = analysisMetadataHolder;
this.treeRootHolder = treeRootHolder;
this.previousSourceHashRepository = previousSourceHashRepository;
this.sourceHashRepository = sourceHashRepository;
}
public void initialize() {
fileUuidsMarkedAsUnchanged = new HashSet<>();
if (!analysisMetadataHolder.isPullRequest() && !analysisMetadataHolder.isFirstAnalysis()) {
new DepthTraversalTypeAwareCrawler(new Visitor()).visit(treeRootHolder.getRoot());
}
}
private class Visitor extends TypeAwareVisitorAdapter {
private boolean canTrustUnchangedFlags = true;
private Visitor() {
super(CrawlerDepthLimit.FILE, PRE_ORDER);
}
@Override
public void visitFile(Component file) {
if (file.getStatus() != Component.Status.SAME || !canTrustUnchangedFlags) {
return;
}
canTrustUnchangedFlags = hashEquals(file);
if (canTrustUnchangedFlags) {
if (file.getFileAttributes().isMarkedAsUnchanged()) {
fileUuidsMarkedAsUnchanged.add(file.getUuid());
}
} else {
fileUuidsMarkedAsUnchanged.clear();
}
}
}
@Override
public boolean isUnchanged(Component component) {
failIfNotInitialized();
return component.getStatus() == Component.Status.SAME && hashEquals(component);
}
@Override
public boolean isDataUnchanged(Component component) {
failIfNotInitialized();
return fileUuidsMarkedAsUnchanged.contains(component.getUuid());
}
@Override
public Set<String> getFileUuidsMarkedAsUnchanged() {
failIfNotInitialized();
return unmodifiableSet(fileUuidsMarkedAsUnchanged);
}
private boolean hashEquals(Component component) {
Optional<String> dbHash = previousSourceHashRepository.getDbFile(component).map(FileHashesDto::getSrcHash);
return dbHash.map(hash -> hash.equals(sourceHashRepository.getRawSourceHash(component))).orElse(false);
}
private void failIfNotInitialized() {
checkState(fileUuidsMarkedAsUnchanged != null, "Not initialized");
}
}
| 3,983 | 36.584906 | 162 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/MutableDisabledComponentsHolder.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
import java.util.Set;
public interface MutableDisabledComponentsHolder extends DisabledComponentsHolder {
void setUuids(Set<String> uuids);
}
| 1,044 | 35.034483 | 83 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/MutableTreeRootHolder.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
public interface MutableTreeRootHolder extends TreeRootHolder {
/**
* Sets the root of the component tree in the TreeRootHolder.
*
* @throws NullPointerException if {@code newRoot} is {@code null}
* @throws IllegalStateException if root {@link Component} has already been set
*/
MutableTreeRootHolder setRoots(Component root, Component reportRoot);
}
| 1,269 | 37.484848 | 81 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/NopFileStatuses.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
import java.util.Set;
/**
* No operation implementation of {@link FileStatuses}
*/
public final class NopFileStatuses implements FileStatuses {
@Override
public boolean isUnchanged(Component component) {
return false;
}
@Override
public boolean isDataUnchanged(Component component) {
return false;
}
@Override
public Set<String> getFileUuidsMarkedAsUnchanged() {
return Set.of();
}
}
| 1,319 | 27.695652 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/PathAwareCrawler.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import javax.annotation.Nonnull;
import javax.annotation.concurrent.Immutable;
import static com.google.common.collect.FluentIterable.from;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.POST_ORDER;
import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.PRE_ORDER;
/**
* A {@link ComponentCrawler} which provide access to a representation of the path from the root to the currently visited
* Component. It also provides a way to have an object associated to each Component and access it and all of its
* parent's.
* As for {@link DepthTraversalTypeAwareCrawler}, this crawler supports max depth visit and ordering.
*/
public final class PathAwareCrawler<T> implements ComponentCrawler {
private final PathAwareVisitor<T> visitor;
private final DequeBasedPath<T> stack = new DequeBasedPath<>();
public PathAwareCrawler(PathAwareVisitor<T> visitor) {
this.visitor = requireNonNull(visitor);
}
@Override
public void visit(Component component) {
try {
visitImpl(component);
} catch (RuntimeException e) {
VisitException.rethrowOrWrap(
e,
"Visit failed for Component {key=%s,type=%s} %s",
component.getKey(), component.getType(), new ComponentPathPrinter<>(stack));
}
}
private void visitImpl(Component component) {
if (!verifyDepth(component)) {
return;
}
stack.add(new PathElementImpl<>(component, createForComponent(component)));
if (this.visitor.getOrder() == PRE_ORDER) {
visitNode(component);
}
visitChildren(component);
if (this.visitor.getOrder() == POST_ORDER) {
visitNode(component);
}
stack.pop();
}
private boolean verifyDepth(Component component) {
CrawlerDepthLimit maxDepth = this.visitor.getMaxDepth();
return maxDepth.isSameAs(component.getType()) || maxDepth.isDeeperThan(component.getType());
}
private void visitChildren(Component component) {
for (Component child : component.getChildren()) {
if (verifyDepth(component)) {
visit(child);
}
}
}
private void visitNode(Component component) {
this.visitor.visitAny(component, stack);
switch (component.getType()) {
case PROJECT:
this.visitor.visitProject(component, stack);
break;
case DIRECTORY:
this.visitor.visitDirectory(component, stack);
break;
case FILE:
this.visitor.visitFile(component, stack);
break;
case VIEW:
this.visitor.visitView(component, stack);
break;
case SUBVIEW:
this.visitor.visitSubView(component, stack);
break;
case PROJECT_VIEW:
this.visitor.visitProjectView(component, stack);
break;
default:
throw new IllegalArgumentException(format("Unsupported component type %s, no visitor method to call", component.getType()));
}
}
private T createForComponent(Component component) {
switch (component.getType()) {
case PROJECT:
return this.visitor.getFactory().createForProject(component);
case DIRECTORY:
return this.visitor.getFactory().createForDirectory(component);
case FILE:
return this.visitor.getFactory().createForFile(component);
case VIEW:
return this.visitor.getFactory().createForView(component);
case SUBVIEW:
return this.visitor.getFactory().createForSubView(component);
case PROJECT_VIEW:
return this.visitor.getFactory().createForProjectView(component);
default:
throw new IllegalArgumentException(format("Unsupported component type %s, can not create stack object", component.getType()));
}
}
/**
* A simple object wrapping the currentPath allowing to compute the string representing the path only if
* the VisitException is actually built (ie. method {@link ComponentPathPrinter#toString()} is called
* by the internal {@link String#format(String, Object...)} of
* {@link VisitException#rethrowOrWrap(RuntimeException, String, Object...)}.
*/
@Immutable
private static final class ComponentPathPrinter<T> {
private static final Joiner PATH_ELEMENTS_JOINER = Joiner.on("->");
private final DequeBasedPath<T> currentPath;
private ComponentPathPrinter(DequeBasedPath<T> currentPath) {
this.currentPath = currentPath;
}
@Override
public String toString() {
if (currentPath.isRoot()) {
return "";
}
return " located " + toKeyPath(currentPath);
}
private static <T> String toKeyPath(Iterable<PathAwareVisitor.PathElement<T>> currentPath) {
return PATH_ELEMENTS_JOINER.join(from(currentPath).transform(PathElementToComponentAsString.INSTANCE).skip(1));
}
private enum PathElementToComponentAsString implements Function<PathAwareVisitor.PathElement<?>, String> {
INSTANCE;
@Override
@Nonnull
public String apply(@Nonnull PathAwareVisitor.PathElement<?> input) {
return format("%s(type=%s)", input.component().getKey(), input.component().getType());
}
}
}
}
| 6,182 | 33.735955 | 134 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/PathAwareVisitor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
import java.util.NoSuchElementException;
/**
* A {@link ComponentVisitor} which provide access to a representation of the path from the root to the currently visited
* Component. It also provides a way to have an object associated to each Component and access it and all of its
* parent's.
*/
public interface PathAwareVisitor<T> extends ComponentVisitor {
StackElementFactory<T> getFactory();
/**
* Called when encountering a Component of type {@link Component.Type#PROJECT}
*/
void visitProject(Component project, Path<T> path);
/**
* Called when encountering a Component of type {@link Component.Type#DIRECTORY}
*/
void visitDirectory(Component directory, Path<T> path);
/**
* Called when encountering a Component of type {@link Component.Type#FILE}
*/
void visitFile(Component file, Path<T> path);
/**
* Called when encountering a Component of type {@link Component.Type#VIEW}
*/
void visitView(Component view, Path<T> path);
/**
* Called when encountering a Component of type {@link Component.Type#SUBVIEW}
*/
void visitSubView(Component subView, Path<T> path);
/**
* Called when encountering a Component of type {@link Component.Type#PROJECT_VIEW}
*/
void visitProjectView(Component projectView, Path<T> path);
/**
* Called for any component, <strong>in addition</strong> to the methods specific to each type
*/
void visitAny(Component component, Path<T> path);
interface StackElementFactory<T> {
T createForProject(Component project);
T createForDirectory(Component directory);
T createForFile(Component file);
T createForView(Component view);
T createForSubView(Component subView);
T createForProjectView(Component projectView);
}
interface Path<T> {
/**
* The stacked element of the current Component.
*/
T current();
/**
* Tells whether the current Component is the root of the tree.
*/
boolean isRoot();
/**
* The stacked element of the parent of the current Component.
*
* @throws NoSuchElementException if the current Component is the root of the tree
* @see #isRoot()
*/
T parent();
/**
* The stacked element of the root of the tree.
*/
T root();
/**
* The path to the current Component as an Iterable of {@link PathAwareVisitor.PathElement} which starts with
* the {@link PathAwareVisitor.PathElement} of the current Component and ends with the
* {@link PathAwareVisitor.PathElement} of the root of the tree.
*/
Iterable<PathElement<T>> getCurrentPath();
}
interface PathElement<T> {
/**
* The Component on the path.
*/
Component component();
/**
* The stacked element for the Component of this PathElement.
*/
T element();
}
}
| 3,726 | 28.346457 | 121 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/PathAwareVisitorAdapter.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
import static java.util.Objects.requireNonNull;
/**
* A adapter of the {@link PathAwareVisitor} to be able to visit only some component types
*/
public abstract class PathAwareVisitorAdapter<T> implements PathAwareVisitor<T> {
private final CrawlerDepthLimit maxDepth;
private final Order order;
private final StackElementFactory<T> factory;
public PathAwareVisitorAdapter(CrawlerDepthLimit maxDepth, Order order, StackElementFactory<T> factory) {
this.maxDepth = requireNonNull(maxDepth);
this.order = requireNonNull(order);
this.factory = requireNonNull(factory, "Factory can not be null");
}
@Override
public CrawlerDepthLimit getMaxDepth() {
return maxDepth;
}
@Override
public Order getOrder() {
return order;
}
@Override
public StackElementFactory<T> getFactory() {
return factory;
}
@Override
public void visitProject(Component project, Path<T> path) {
// empty implementation, meant to be override at will by subclasses
}
@Override
public void visitDirectory(Component directory, Path<T> path) {
// empty implementation, meant to be override at will by subclasses
}
@Override
public void visitFile(Component file, Path<T> path) {
// empty implementation, meant to be override at will by subclasses
}
@Override
public void visitView(Component view, Path<T> path) {
// empty implementation, meant to be override at will by subclasses
}
@Override
public void visitSubView(Component subView, Path<T> path) {
// empty implementation, meant to be override at will by subclasses
}
@Override
public void visitProjectView(Component projectView, Path<T> path) {
// empty implementation, meant to be override at will by subclasses
}
@Override
public void visitAny(Component component, Path<T> path) {
// empty implementation, meant to be override at will by subclasses
}
/**
* A Simple implementation which uses the same factory method for all types which can be implemented by subclasses:
* {@link #createForAny(Component)}.
*/
public abstract static class SimpleStackElementFactory<T> implements StackElementFactory<T> {
public abstract T createForAny(Component component);
@Override
public T createForProject(Component project) {
return createForAny(project);
}
@Override
public T createForDirectory(Component directory) {
return createForAny(directory);
}
@Override
public T createForFile(Component file) {
return createForAny(file);
}
@Override
public T createForView(Component view) {
return createForAny(view);
}
@Override
public T createForSubView(Component subView) {
return createForAny(subView);
}
@Override
public T createForProjectView(Component projectView) {
return createForAny(projectView);
}
}
}
| 3,781 | 28.317829 | 117 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/PathAwareVisitorWrapper.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
import static java.lang.String.format;
public class PathAwareVisitorWrapper<T> implements VisitorWrapper {
private final PathAwareVisitor<T> delegate;
private final DequeBasedPath<T> stack = new DequeBasedPath<>();
public PathAwareVisitorWrapper(PathAwareVisitor<T> delegate) {
this.delegate = delegate;
}
@Override
public ComponentVisitor getWrappedVisitor() {
return this.delegate;
}
@Override
public void beforeComponent(Component component){
stack.add(new PathElementImpl<>(component, createForComponent(component)));
}
@Override
public void afterComponent(Component component){
stack.pop();
}
@Override
public void visitProject(Component tree) {
delegate.visitProject(tree, stack);
}
@Override
public void visitDirectory(Component tree) {
delegate.visitDirectory(tree, stack);
}
@Override
public void visitFile(Component tree) {
delegate.visitFile(tree, stack);
}
@Override
public void visitView(Component view) {
delegate.visitView(view, stack);
}
@Override
public void visitSubView(Component subView) {
delegate.visitSubView(subView, stack);
}
@Override
public void visitProjectView(Component projectView) {
delegate.visitProjectView(projectView, stack);
}
@Override
public void visitAny(Component component) {
delegate.visitAny(component, stack);
}
@Override
public ComponentVisitor.Order getOrder() {
return delegate.getOrder();
}
@Override
public CrawlerDepthLimit getMaxDepth() {
return delegate.getMaxDepth();
}
private T createForComponent(Component component) {
switch (component.getType()) {
case PROJECT:
return delegate.getFactory().createForProject(component);
case DIRECTORY:
return delegate.getFactory().createForDirectory(component);
case FILE:
return delegate.getFactory().createForFile(component);
case VIEW:
return delegate.getFactory().createForView(component);
case SUBVIEW:
return delegate.getFactory().createForSubView(component);
case PROJECT_VIEW:
return delegate.getFactory().createForProjectView(component);
default:
throw new IllegalArgumentException(format("Unsupported component type %s, can not create stack object", component.getType()));
}
}
@Override
public String toString() {
return delegate.toString();
}
}
| 3,316 | 27.110169 | 134 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/PathElementImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
record PathElementImpl<T>(Component component, T element) implements PathAwareVisitor.PathElement<T> {
}
| 1,002 | 40.791667 | 102 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/PreviousSourceHashRepository.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
import java.util.Optional;
import org.sonar.db.source.FileHashesDto;
public interface PreviousSourceHashRepository {
Optional<FileHashesDto> getDbFile(Component component);
}
| 1,075 | 37.428571 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/PreviousSourceHashRepositoryImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import org.sonar.db.source.FileHashesDto;
import static org.sonar.api.utils.Preconditions.checkNotNull;
import static org.sonar.api.utils.Preconditions.checkState;
public class PreviousSourceHashRepositoryImpl implements PreviousSourceHashRepository {
private Map<String, FileHashesDto> previousFileHashesByUuid = null;
public void set(Map<String, FileHashesDto> previousFileHashesByUuid) {
checkState(this.previousFileHashesByUuid == null, "Repository already initialized");
checkNotNull(previousFileHashesByUuid);
this.previousFileHashesByUuid = Collections.unmodifiableMap(previousFileHashesByUuid);
}
public Map<String, FileHashesDto> getMap() {
return previousFileHashesByUuid;
}
@Override
public Optional<FileHashesDto> getDbFile(Component component) {
checkState(previousFileHashesByUuid != null, "Repository not initialized");
return Optional.ofNullable(previousFileHashesByUuid.get(component.getUuid()));
}
}
| 1,939 | 38.591837 | 90 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/ProjectAttributes.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
import java.util.Optional;
import javax.annotation.Nullable;
import static java.util.Objects.requireNonNull;
public class ProjectAttributes {
private final String projectVersion;
@Nullable
private final String buildString;
@Nullable
private final String scmRevisionId;
public ProjectAttributes(String projectVersion, @Nullable String buildString, @Nullable String scmRevisionId) {
this.projectVersion = requireNonNull(projectVersion, "project version can't be null");
this.buildString = buildString;
this.scmRevisionId = scmRevisionId;
}
public ProjectAttributes(ProjectAttributes projectAttributes) {
this.projectVersion = projectAttributes.projectVersion;
this.buildString = projectAttributes.buildString;
this.scmRevisionId = projectAttributes.scmRevisionId;
}
public String getProjectVersion() {
return projectVersion;
}
public Optional<String> getBuildString() {
return Optional.ofNullable(buildString);
}
public Optional<String> getScmRevisionId() {
return Optional.ofNullable(scmRevisionId);
}
@Override
public String toString() {
return "ProjectAttributes{" +
"projectVersion='" + projectVersion + '\'' +
"buildString='" + buildString + '\'' +
"scmRevisionId='" + scmRevisionId + '\'' +
'}';
}
}
| 2,211 | 31.057971 | 113 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/ProjectPersister.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.project.ProjectDto;
/**
* Creates or updates the data in table {@code PROJECTS} for the current root.
*/
public class ProjectPersister {
private final DbClient dbClient;
private final TreeRootHolder treeRootHolder;
private final System2 system2;
public ProjectPersister(DbClient dbClient, TreeRootHolder treeRootHolder, System2 system2) {
this.dbClient = dbClient;
this.treeRootHolder = treeRootHolder;
this.system2 = system2;
}
public void persist(DbSession dbSession) {
if (shouldSkip(treeRootHolder.getRoot())) {
return;
}
ProjectDto dbProjectDto = dbClient.projectDao().selectProjectByKey(dbSession, treeRootHolder.getRoot().getKey())
.orElseThrow(() -> new IllegalStateException("Project has been deleted by end-user during analysis"));
ProjectDto projectDto = toProjectDto(treeRootHolder.getRoot());
if (hasChanged(dbProjectDto, projectDto)) {
// insert or update in projects table
dbClient.projectDao().update(dbSession, projectDto);
}
}
private static boolean shouldSkip(Component rootComponent) {
return !rootComponent.getType().equals(Component.Type.PROJECT) && !rootComponent.getType().equals(Component.Type.PROJECT_VIEW);
}
private static boolean hasChanged(ProjectDto dbProject, ProjectDto newProject) {
return !StringUtils.equals(dbProject.getName(), newProject.getName()) ||
!StringUtils.equals(dbProject.getDescription(), newProject.getDescription());
}
private ProjectDto toProjectDto(Component root) {
ProjectDto projectDto = new ProjectDto();
projectDto.setUuid(root.getUuid());
projectDto.setName(root.getName());
projectDto.setDescription(root.getDescription());
projectDto.setUpdatedAt(system2.now());
projectDto.setKey(root.getKey());
projectDto.setQualifier(root.getType().equals(Component.Type.PROJECT) ? Qualifiers.PROJECT : Qualifiers.APP);
return projectDto;
}
}
| 3,034 | 37.910256 | 131 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/ProjectViewAttributes.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import static java.util.Objects.requireNonNull;
@Immutable
public class ProjectViewAttributes {
private final String uuid;
private final String originalKey;
@CheckForNull
private final Long analysisDate;
private final String branchName;
public ProjectViewAttributes(String uuid, String originalKey, @Nullable Long analysisDate, @Nullable String branchName) {
this.uuid = requireNonNull(uuid, "uuid can't be null");
this.originalKey = requireNonNull(originalKey, "originalKey can't be null");
this.analysisDate = analysisDate;
this.branchName = branchName;
}
public String getUuid() {
return uuid;
}
@CheckForNull
public Long getAnalysisDate() {
return analysisDate;
}
public String getBranchName() {
return branchName;
}
public String getOriginalKey() {
return originalKey;
}
@Override
public String toString() {
return "ProjectViewAttributes{" +
", uuid='" + uuid + '\'' +
", branchName='" + branchName + '\'' +
", analysisDate=" + analysisDate +
'}';
}
}
| 2,078 | 29.130435 | 123 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/ReferenceBranchComponentUuids.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
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 static com.google.common.base.Preconditions.checkState;
/**
* Cache a map between component keys and uuids in the reference branch
*/
public class ReferenceBranchComponentUuids {
private final AnalysisMetadataHolder analysisMetadataHolder;
private final DbClient dbClient;
private Map<String, String> referenceBranchComponentsUuidsByKey;
private String referenceBranchName;
private boolean hasReferenceBranchAnalysis;
public ReferenceBranchComponentUuids(AnalysisMetadataHolder analysisMetadataHolder, DbClient dbClient) {
this.analysisMetadataHolder = analysisMetadataHolder;
this.dbClient = dbClient;
}
private void lazyInit() {
if (referenceBranchComponentsUuidsByKey == null) {
String referenceBranchUuid = analysisMetadataHolder.getBranch().getReferenceBranchUuid();
referenceBranchComponentsUuidsByKey = new HashMap<>();
try (DbSession dbSession = dbClient.openSession(false)) {
Optional<BranchDto> opt = dbClient.branchDao().selectByUuid(dbSession, referenceBranchUuid);
checkState(opt.isPresent(), "Reference branch '%s' does not exist", referenceBranchUuid);
referenceBranchName = opt.get().getKey();
init(referenceBranchUuid, dbSession);
}
}
}
private void init(String referenceBranchUuid, DbSession dbSession) {
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());
}
}
}
public boolean hasReferenceBranchAnalysis() {
lazyInit();
return hasReferenceBranchAnalysis;
}
public String getReferenceBranchName() {
lazyInit();
return referenceBranchName;
}
@CheckForNull
public String getComponentUuid(String key) {
lazyInit();
return referenceBranchComponentsUuidsByKey.get(key);
}
}
| 3,362 | 34.776596 | 138 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/ReportAttributes.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
import java.util.Optional;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
/**
* Component properties which are specific to the Scanner Report.
*/
@Immutable
public class ReportAttributes {
@CheckForNull
private final Integer ref;
@CheckForNull
private final String scmPath;
private ReportAttributes(Builder builder) {
this.ref = builder.ref;
this.scmPath = builder.scmPath;
}
public static Builder newBuilder(@Nullable Integer ref) {
return new Builder(ref);
}
public static class Builder {
@CheckForNull
private final Integer ref;
@CheckForNull
private String scmPath;
private Builder(@Nullable Integer ref) {
this.ref = ref;
}
public Builder setScmPath(@Nullable String scmPath) {
this.scmPath = scmPath;
return this;
}
public ReportAttributes build() {
return new ReportAttributes(this);
}
}
/**
* The component ref in the batch report.
* Will be null for directories.
*/
@CheckForNull
public Integer getRef() {
return ref;
}
/**
* The path of the component relative the SCM root the project is part of.
* <p>
* Can be {@link Optional#empty() empty} if project is not version controlled,
* otherwise should be non {@link Optional#isPresent() non empty} for all components.
*/
public Optional<String> getScmPath() {
return Optional.ofNullable(scmPath);
}
@Override
public String toString() {
return "ReportAttributes{" +
"ref=" + ref +
", scmPath='" + scmPath + '\'' +
'}';
}
}
| 2,530 | 26.215054 | 87 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/SiblingComponentsWithOpenIssues.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.KeyWithUuidDto;
/**
* Cache a map of component key -> set<uuid> in:
* - sibling PRs that have open issues
* - branches that use reference branch as new code period setting and have it set to currently analysed branch
*/
public class SiblingComponentsWithOpenIssues {
private final DbClient dbClient;
private final AnalysisMetadataHolder metadataHolder;
private final TreeRootHolder treeRootHolder;
private Map<String, Set<String>> uuidsByKey;
public SiblingComponentsWithOpenIssues(TreeRootHolder treeRootHolder, AnalysisMetadataHolder metadataHolder, DbClient dbClient) {
this.treeRootHolder = treeRootHolder;
this.metadataHolder = metadataHolder;
this.dbClient = dbClient;
}
private void loadUuidsByKey() {
String currentBranchUuid = treeRootHolder.getRoot().getUuid();
String referenceBranchUuid;
uuidsByKey = new HashMap<>();
try (DbSession dbSession = dbClient.openSession(false)) {
if (metadataHolder.isPullRequest()) {
referenceBranchUuid = metadataHolder.getBranch().getReferenceBranchUuid();
} else {
referenceBranchUuid = currentBranchUuid;
addComponentsFromBranchesThatUseCurrentBranchAsNewCodePeriodReferenceAndHaveOpenIssues(dbSession);
}
addComponentsFromPullRequestsTargetingCurrentBranchThatHaveOpenIssues(dbSession, referenceBranchUuid, currentBranchUuid);
}
}
private void addComponentsFromBranchesThatUseCurrentBranchAsNewCodePeriodReferenceAndHaveOpenIssues(DbSession dbSession) {
String projectUuid = metadataHolder.getProject().getUuid();
String currentBranchName = metadataHolder.getBranch().getName();
Set<String> branchUuids = dbClient.newCodePeriodDao().selectBranchesReferencing(dbSession, projectUuid, currentBranchName);
List<KeyWithUuidDto> components = dbClient.componentDao().selectComponentsFromBranchesThatHaveOpenIssues(dbSession, branchUuids);
for (KeyWithUuidDto dto : components) {
uuidsByKey.computeIfAbsent(dto.key(), s -> new HashSet<>()).add(dto.uuid());
}
}
private void addComponentsFromPullRequestsTargetingCurrentBranchThatHaveOpenIssues(DbSession dbSession, String referenceBranchUuid, String currentBranchUuid) {
List<KeyWithUuidDto> components = dbClient.componentDao().selectComponentsFromPullRequestsTargetingCurrentBranchThatHaveOpenIssues(
dbSession, referenceBranchUuid, currentBranchUuid);
for (KeyWithUuidDto dto : components) {
uuidsByKey.computeIfAbsent(dto.key(), s -> new HashSet<>()).add(dto.uuid());
}
}
public Set<String> getUuids(String componentKey) {
if (uuidsByKey == null) {
loadUuidsByKey();
}
return uuidsByKey.getOrDefault(componentKey, Collections.emptySet());
}
}
| 3,951 | 39.742268 | 161 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/SubViewAttributes.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
@Immutable
public class SubViewAttributes {
private final String originalViewUuid;
public SubViewAttributes(@Nullable String originalViewUuid) {
this.originalViewUuid = originalViewUuid;
}
/**
* Return the original view uuid when the sub view is a local view
*/
@CheckForNull
public String getOriginalViewUuid() {
return originalViewUuid;
}
@Override
public String toString() {
return "SubViewAttributes{" +
"originalViewUuid='" + originalViewUuid + '\'' +
'}';
}
}
| 1,535 | 30.346939 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/TreeRootHolder.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
import java.util.Optional;
/**
* The tree of components defined in the scanner report.
*/
public interface TreeRootHolder {
/**
* @return true if the holder is empty
*/
boolean isEmpty();
/**
* The root of the tree, for example the project or the portfolio.
* With branches, it will refer to the root component of the branch.
*
* On a pull request, it contains ONLY:
* 1. The PROJECT component (tree root)
* 2. The FILE components whose status is not SAME
* 3. Intermediary MODULE and DIRECTORY components that lead to FILE leafs that are not SAME
*
* @throws IllegalStateException if the holder is empty (ie. there is no root yet)
*/
Component getRoot();
/**
* The root of the components that were in the scanner report.
* This tree may include components that are not persisted,
* just kept in memory for computation purposes, such as overall coverage
* in pull requests.
*
* @throws IllegalStateException if the holder is empty (ie. there is no root yet)
*/
Component getReportTreeRoot();
/**
* Return a component by its batch reference
*
* @throws IllegalStateException if the holder is empty (ie. there is no root yet)
* @throws IllegalArgumentException if there's no {@link Component} with the specified reference
*/
Component getComponentByRef(int ref);
/**
* Return a component by its uuid
*
* @throws IllegalStateException if the holder is empty (ie. there is no root yet)
* @throws IllegalArgumentException if there's no {@link Component} with the specified reference
*/
Component getComponentByUuid(String uuid);
/**
* Return a component by its batch reference. Returns {@link Optional#empty()} if there's
* no {@link Component} with the specified reference
*
* @throws IllegalStateException if the holder is empty (ie. there is no root yet)
* @deprecated This method was introduced as a quick fix for SONAR-10781. Ultimately one should never manipulate component
* ref that doesn't exist in the scanner report
*/
@Deprecated
Optional<Component> getOptionalComponentByRef(int ref);
/**
* Return a component from the report tree (see {@link #getReportTreeRoot()}, by its batch reference.
*
* @throws IllegalStateException if the holder is empty (ie. there is no root yet)
* @throws IllegalArgumentException if there's no {@link Component} with the specified reference
*/
Component getReportTreeComponentByRef(int ref);
/**
* Number of components, including root.
*
* @throws IllegalStateException if the holder is empty (ie. there is no root yet)
*/
int getSize();
}
| 3,553 | 35.265306 | 124 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/TreeRootHolderImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
import com.google.common.collect.ImmutableMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import javax.annotation.CheckForNull;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
import static org.apache.commons.lang.StringUtils.isNotBlank;
import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.POST_ORDER;
/**
* Holds the reference to the root of the {@link Component} tree for the current CE run.
*/
public class TreeRootHolderImpl implements MutableTreeRootHolder {
@CheckForNull
private Map<Integer, Component> componentsByRef = null;
@CheckForNull
private Map<Integer, Component> extendedComponentsByRef = null;
@CheckForNull
private Map<String, Component> componentsByUuid = null;
private int size = 0;
private Component root = null;
private Component extendedTreeRoot = null;
@Override
public boolean isEmpty() {
return this.root == null;
}
@Override
public MutableTreeRootHolder setRoots(Component root, Component reportRoot) {
checkState(this.root == null, "root can not be set twice in holder");
this.root = requireNonNull(root, "root can not be null");
this.extendedTreeRoot = requireNonNull(reportRoot, "extended tree root can not be null");
return this;
}
@Override
public Component getRoot() {
checkInitialized();
return this.root;
}
@Override
public Component getReportTreeRoot() {
checkInitialized();
return this.extendedTreeRoot;
}
@Override
public Component getComponentByRef(int ref) {
return getOptionalComponentByRef(ref)
.orElseThrow(() -> new IllegalArgumentException(String.format("Component with ref '%s' can't be found", ref)));
}
@Override
public Component getComponentByUuid(String uuid) {
checkInitialized();
ensureComponentByRefAndUuidArePopulated();
return componentsByUuid.get(uuid);
}
@Override
public Optional<Component> getOptionalComponentByRef(int ref) {
checkInitialized();
ensureComponentByRefAndUuidArePopulated();
return Optional.ofNullable(componentsByRef.get(ref));
}
@Override
public Component getReportTreeComponentByRef(int ref) {
checkInitialized();
ensureExtendedComponentByRefIsPopulated();
Component c = extendedComponentsByRef.get(ref);
if (c == null) {
throw new IllegalArgumentException(String.format("Component with ref '%s' can't be found", ref));
}
return c;
}
@Override
public int getSize() {
checkInitialized();
ensureComponentByRefAndUuidArePopulated();
return size;
}
private void ensureExtendedComponentByRefIsPopulated() {
if (extendedComponentsByRef != null) {
return;
}
final ImmutableMap.Builder<Integer, Component> builder = ImmutableMap.builder();
new DepthTraversalTypeAwareCrawler(
new TypeAwareVisitorAdapter(CrawlerDepthLimit.FILE, POST_ORDER) {
@Override
public void visitAny(Component component) {
if (component.getReportAttributes().getRef() != null) {
builder.put(component.getReportAttributes().getRef(), component);
}
}
}).visit(this.extendedTreeRoot);
this.extendedComponentsByRef = builder.build();
}
private void ensureComponentByRefAndUuidArePopulated() {
if (componentsByRef != null && componentsByUuid != null) {
return;
}
final ImmutableMap.Builder<Integer, Component> builderByRef = ImmutableMap.builder();
final Map<String, Component> builderByUuid = new HashMap<>();
new DepthTraversalTypeAwareCrawler(
new TypeAwareVisitorAdapter(CrawlerDepthLimit.FILE, POST_ORDER) {
@Override
public void visitAny(Component component) {
size++;
if (component.getReportAttributes().getRef() != null) {
builderByRef.put(component.getReportAttributes().getRef(), component);
}
if (isNotBlank(component.getUuid())) {
builderByUuid.put(component.getUuid(), component);
}
}
}).visit(this.root);
this.componentsByRef = builderByRef.build();
this.componentsByUuid = ImmutableMap.copyOf(builderByUuid);
}
private void checkInitialized() {
checkState(this.root != null, "Holder has not been initialized yet");
}
}
| 5,249 | 32.653846 | 117 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/TypeAwareVisitor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
/**
* A {@link ComponentVisitor} which can exposes methods which ensure the type of the visited Component.
*/
public interface TypeAwareVisitor extends ComponentVisitor {
/**
* Called when encountering a Component of type {@link Component.Type#PROJECT}
*/
void visitProject(Component project);
/**
* Called when encountering a Component of type {@link Component.Type#DIRECTORY}
*/
void visitDirectory(Component directory);
/**
* Called when encountering a Component of type {@link Component.Type#FILE}
*/
void visitFile(Component file);
/**
* Called when encountering a Component of type {@link Component.Type#VIEW}
*/
void visitView(Component view);
/**
* Called when encountering a Component of type {@link Component.Type#SUBVIEW}
*/
void visitSubView(Component subView);
/**
* Called when encountering a Component of type {@link Component.Type#PROJECT_VIEW}
*/
void visitProjectView(Component projectView);
/**
* Called for any component, <strong>in addition</strong> to the methods specific to each type
*/
void visitAny(Component any);
}
| 2,019 | 31.580645 | 103 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/TypeAwareVisitorAdapter.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
import static java.util.Objects.requireNonNull;
/**
* A adapter of the {@link TypeAwareVisitor} to be able to visit only some component types
*/
public abstract class TypeAwareVisitorAdapter implements TypeAwareVisitor {
protected final CrawlerDepthLimit maxDepth;
protected final Order order;
public TypeAwareVisitorAdapter(CrawlerDepthLimit maxDepth, Order order) {
this.maxDepth = requireNonNull(maxDepth);
this.order = requireNonNull(order);
}
@Override
public CrawlerDepthLimit getMaxDepth() {
return maxDepth;
}
@Override
public Order getOrder() {
return order;
}
/**
* Called when encountering a Component of type {@link Component.Type#PROJECT}
*/
@Override
public void visitProject(Component project) {
// empty implementation, meant to be override at will by subclasses
}
/**
* Called when encountering a Component of type {@link Component.Type#DIRECTORY}
*/
@Override
public void visitDirectory(Component directory) {
// empty implementation, meant to be override at will by subclasses
}
/**
* Called when encountering a Component of type {@link Component.Type#FILE}
*/
@Override
public void visitFile(Component file) {
// empty implementation, meant to be override at will by subclasses
}
/**
* Called when encountering a Component of type {@link Component.Type#VIEW}
*/
@Override
public void visitView(Component view) {
// empty implementation, meant to be override at will by subclasses
}
/**
* Called when encountering a Component of type {@link Component.Type#SUBVIEW}
*/
@Override
public void visitSubView(Component subView) {
// empty implementation, meant to be override at will by subclasses
}
/**
* Called when encountering a Component of type {@link Component.Type#PROJECT_VIEW}
*/
@Override
public void visitProjectView(Component projectView) {
// empty implementation, meant to be override at will by subclasses
}
/**
* Called for any component, <strong>in addition</strong> to the methods specific to each type
*/
@Override
public void visitAny(Component any) {
// empty implementation, meant to be override at will by subclasses
}
}
| 3,132 | 29.125 | 96 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/TypeAwareVisitorWrapper.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
public class TypeAwareVisitorWrapper implements VisitorWrapper {
private final TypeAwareVisitor delegate;
public TypeAwareVisitorWrapper(TypeAwareVisitor delegate) {
this.delegate = delegate;
}
@Override
public ComponentVisitor getWrappedVisitor() {
return this.delegate;
}
@Override
public void beforeComponent(Component component) {
// Nothing to do
}
@Override
public void afterComponent(Component component) {
// Nothing to do
}
@Override
public void visitProject(Component tree) {
delegate.visitProject(tree);
}
@Override
public void visitDirectory(Component tree) {
delegate.visitDirectory(tree);
}
@Override
public void visitFile(Component tree) {
delegate.visitFile(tree);
}
@Override
public void visitView(Component view) {
delegate.visitView(view);
}
@Override
public void visitSubView(Component subView) {
delegate.visitSubView(subView);
}
@Override
public void visitProjectView(Component projectView) {
delegate.visitProjectView(projectView);
}
@Override
public void visitAny(Component component) {
delegate.visitAny(component);
}
@Override
public ComponentVisitor.Order getOrder() {
return delegate.getOrder();
}
@Override
public CrawlerDepthLimit getMaxDepth() {
return delegate.getMaxDepth();
}
@Override
public String toString() {
return delegate.toString();
}
}
| 2,331 | 23.547368 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/ViewAttributes.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
import java.util.Arrays;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.resources.Qualifiers;
import static java.util.Objects.requireNonNull;
@Immutable
public class ViewAttributes {
public enum Type {
PORTFOLIO(Qualifiers.VIEW), APPLICATION(Qualifiers.APP);
private final String qualifier;
Type(String qualifier) {
this.qualifier = qualifier;
}
public String getQualifier() {
return qualifier;
}
public static Type fromQualifier(String qualifier) {
return Arrays.stream(values())
.filter(type -> type.getQualifier().equals(qualifier))
.findFirst()
.orElseThrow(() -> new IllegalStateException(String.format("Qualifier '%s' is not supported", qualifier)));
}
}
private final Type type;
public ViewAttributes(Type type) {
this.type = requireNonNull(type, "Type cannot be null");
}
public Type getType() {
return type;
}
@Override
public String toString() {
return "viewAttributes{" +
"type='" + type + '\'' +
'}';
}
}
| 1,963 | 27.463768 | 115 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/VisitException.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
import static java.lang.String.format;
/**
* Wrapper {@link RuntimeException} of any {@link RuntimeException} thrown during the visit of the Component tree.
*
* Use {@link #rethrowOrWrap(RuntimeException, String, Object...)} to avoid having {@link VisitException} as cause of
* another {@link VisitException}
*/
public class VisitException extends RuntimeException {
public VisitException(String message, RuntimeException cause) {
super(message, cause);
}
/**
* @param e the {@link RuntimeException} to wrap unless it is an instance of {@link VisitException}
* @param pattern a {@link String#format(String, Object...)} pattern
* @param args optional {@link String#format(String, Object...)} arguments
*/
public static void rethrowOrWrap(RuntimeException e, String pattern, Object... args) {
if (e instanceof VisitException) {
throw e;
} else {
throw new VisitException(format(pattern, args), e);
}
}
}
| 1,856 | 37.6875 | 117 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/VisitorWrapper.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
public interface VisitorWrapper extends TypeAwareVisitor {
ComponentVisitor getWrappedVisitor();
void beforeComponent(Component component);
void afterComponent(Component component);
}
| 1,091 | 34.225806 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/VisitorsCrawler.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
import com.google.common.collect.ImmutableMap;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import org.slf4j.LoggerFactory;
import org.sonar.core.util.logs.Profiler;
import static com.google.common.collect.Iterables.concat;
import static java.util.Objects.requireNonNull;
/**
* This crawler make any number of {@link TypeAwareVisitor} or {@link PathAwareVisitor} defined in a list visit a component tree, component per component, in the order of the list
*/
public class VisitorsCrawler implements ComponentCrawler {
private final boolean computeDuration;
private final Map<ComponentVisitor, VisitorDuration> visitorCumulativeDurations;
private final List<VisitorWrapper> preOrderVisitorWrappers;
private final List<VisitorWrapper> postOrderVisitorWrappers;
public VisitorsCrawler(Collection<ComponentVisitor> visitors) {
this(visitors, false);
}
public VisitorsCrawler(Collection<ComponentVisitor> visitors, boolean computeDuration) {
List<VisitorWrapper> visitorWrappers = visitors.stream().map(ToVisitorWrapper.INSTANCE).toList();
this.preOrderVisitorWrappers = visitorWrappers.stream().filter(MathPreOrderVisitor.INSTANCE).toList();
this.postOrderVisitorWrappers = visitorWrappers.stream().filter(MatchPostOrderVisitor.INSTANCE).toList();
this.computeDuration = computeDuration;
this.visitorCumulativeDurations = computeDuration ? visitors.stream().collect(Collectors.toMap(v -> v, v -> new VisitorDuration())) : Collections.emptyMap();
}
public Map<ComponentVisitor, Long> getCumulativeDurations() {
if (computeDuration) {
return visitorCumulativeDurations.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().getDuration()));
}
return Collections.emptyMap();
}
@Override
public void visit(final Component component) {
try {
visitImpl(component);
} catch (RuntimeException e) {
VisitException.rethrowOrWrap(
e,
"Visit of Component {key=%s,type=%s} failed",
component.getKey(), component.getType());
}
}
private void visitImpl(Component component) {
MatchVisitorMaxDepth visitorMaxDepth = MatchVisitorMaxDepth.forComponent(component);
List<VisitorWrapper> preOrderVisitorWrappersToExecute = preOrderVisitorWrappers.stream().filter(visitorMaxDepth).toList();
List<VisitorWrapper> postOrderVisitorWrappersToExecute = postOrderVisitorWrappers.stream().filter(visitorMaxDepth).toList();
if (preOrderVisitorWrappersToExecute.isEmpty() && postOrderVisitorWrappersToExecute.isEmpty()) {
return;
}
for (VisitorWrapper visitorWrapper : concat(preOrderVisitorWrappers, postOrderVisitorWrappers)) {
visitorWrapper.beforeComponent(component);
}
for (VisitorWrapper visitorWrapper : preOrderVisitorWrappersToExecute) {
visitNode(component, visitorWrapper);
}
visitChildren(component);
for (VisitorWrapper visitorWrapper : postOrderVisitorWrappersToExecute) {
visitNode(component, visitorWrapper);
}
for (VisitorWrapper visitorWrapper : concat(preOrderVisitorWrappersToExecute, postOrderVisitorWrappersToExecute)) {
visitorWrapper.afterComponent(component);
}
}
private void visitChildren(Component component) {
for (Component child : component.getChildren()) {
visit(child);
}
}
private void visitNode(Component component, VisitorWrapper visitor) {
Profiler profiler = Profiler.create(LoggerFactory.getLogger(visitor.getWrappedVisitor().getClass()))
.startTrace("Visiting component {}", component.getKey());
visitor.visitAny(component);
switch (component.getType()) {
case PROJECT:
visitor.visitProject(component);
break;
case DIRECTORY:
visitor.visitDirectory(component);
break;
case FILE:
visitor.visitFile(component);
break;
case VIEW:
visitor.visitView(component);
break;
case SUBVIEW:
visitor.visitSubView(component);
break;
case PROJECT_VIEW:
visitor.visitProjectView(component);
break;
default:
throw new IllegalStateException(String.format("Unknown type %s", component.getType().name()));
}
long duration = profiler.stopTrace();
incrementDuration(visitor, duration);
}
private void incrementDuration(VisitorWrapper visitorWrapper, long duration) {
if (computeDuration) {
visitorCumulativeDurations.get(visitorWrapper.getWrappedVisitor()).increment(duration);
}
}
private enum ToVisitorWrapper implements Function<ComponentVisitor, VisitorWrapper> {
INSTANCE;
@Override
public VisitorWrapper apply(@Nonnull ComponentVisitor componentVisitor) {
if (componentVisitor instanceof TypeAwareVisitor typeAwareVisitor) {
return new TypeAwareVisitorWrapper(typeAwareVisitor);
} else if (componentVisitor instanceof PathAwareVisitor<?> pathAwareVisitor) {
return new PathAwareVisitorWrapper(pathAwareVisitor);
} else {
throw new IllegalArgumentException("Only TypeAwareVisitor and PathAwareVisitor can be used");
}
}
}
private static class MatchVisitorMaxDepth implements Predicate<VisitorWrapper> {
private static final Map<Component.Type, MatchVisitorMaxDepth> INSTANCES = buildInstances();
private final Component.Type type;
private MatchVisitorMaxDepth(Component.Type type) {
this.type = requireNonNull(type);
}
private static Map<Component.Type, MatchVisitorMaxDepth> buildInstances() {
ImmutableMap.Builder<Component.Type, MatchVisitorMaxDepth> builder = ImmutableMap.builder();
for (Component.Type type : Component.Type.values()) {
builder.put(type, new MatchVisitorMaxDepth(type));
}
return builder.build();
}
public static MatchVisitorMaxDepth forComponent(Component component) {
return INSTANCES.get(component.getType());
}
@Override
public boolean test(VisitorWrapper visitorWrapper) {
CrawlerDepthLimit maxDepth = visitorWrapper.getMaxDepth();
return maxDepth.isSameAs(type) || maxDepth.isDeeperThan(type);
}
}
private enum MathPreOrderVisitor implements Predicate<VisitorWrapper> {
INSTANCE;
@Override
public boolean test(VisitorWrapper visitorWrapper) {
return visitorWrapper.getOrder() == ComponentVisitor.Order.PRE_ORDER;
}
}
private enum MatchPostOrderVisitor implements Predicate<VisitorWrapper> {
INSTANCE;
@Override
public boolean test(VisitorWrapper visitorWrapper) {
return visitorWrapper.getOrder() == ComponentVisitor.Order.POST_ORDER;
}
}
private static final class VisitorDuration {
private long duration = 0;
public void increment(long duration) {
this.duration += duration;
}
public long getDuration() {
return duration;
}
}
}
| 7,984 | 35.461187 | 179 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/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.component;
import javax.annotation.ParametersAreNonnullByDefault;
| 983 | 40 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/container/ContainerFactory.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.container;
import javax.annotation.Nullable;
import org.sonar.ce.task.CeTask;
import org.sonar.ce.task.container.TaskContainer;
import org.sonar.core.platform.SpringComponentContainer;
public interface ContainerFactory {
TaskContainer create(SpringComponentContainer parent, CeTask task, @Nullable ReportAnalysisComponentProvider[] componentProviders);
}
| 1,245 | 39.193548 | 133 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/container/ContainerFactoryImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.container;
import javax.annotation.Nullable;
import org.sonar.ce.task.CeTask;
import org.sonar.ce.task.container.TaskContainer;
import org.sonar.ce.task.container.TaskContainerImpl;
import org.sonar.core.platform.SpringComponentContainer;
public class ContainerFactoryImpl implements ContainerFactory {
@Override
public TaskContainer create(SpringComponentContainer parent, CeTask task, @Nullable ReportAnalysisComponentProvider[] componentProviders) {
return new TaskContainerImpl(parent, new ProjectAnalysisTaskContainerPopulator(task, componentProviders));
}
}
| 1,461 | 42 | 141 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/container/ProjectAnalysisTaskContainerPopulator.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.container;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Nullable;
import org.sonar.ce.task.CeTask;
import org.sonar.ce.task.container.TaskContainer;
import org.sonar.ce.task.log.CeTaskMessagesImpl;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisFromSonarQube94Visitor;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderImpl;
import org.sonar.ce.task.projectanalysis.api.posttask.PostProjectAnalysisTasksExecutor;
import org.sonar.ce.task.projectanalysis.batch.BatchReportDirectoryHolderImpl;
import org.sonar.ce.task.projectanalysis.batch.BatchReportReaderImpl;
import org.sonar.ce.task.projectanalysis.component.BranchLoader;
import org.sonar.ce.task.projectanalysis.component.BranchPersisterImpl;
import org.sonar.ce.task.projectanalysis.component.ConfigurationRepositoryImpl;
import org.sonar.ce.task.projectanalysis.component.DisabledComponentsHolderImpl;
import org.sonar.ce.task.projectanalysis.component.FileStatusesImpl;
import org.sonar.ce.task.projectanalysis.component.PreviousSourceHashRepositoryImpl;
import org.sonar.ce.task.projectanalysis.component.ProjectPersister;
import org.sonar.ce.task.projectanalysis.component.ReferenceBranchComponentUuids;
import org.sonar.ce.task.projectanalysis.component.SiblingComponentsWithOpenIssues;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolderImpl;
import org.sonar.ce.task.projectanalysis.duplication.CrossProjectDuplicationStatusHolderImpl;
import org.sonar.ce.task.projectanalysis.duplication.DuplicationMeasures;
import org.sonar.ce.task.projectanalysis.duplication.DuplicationRepositoryImpl;
import org.sonar.ce.task.projectanalysis.duplication.IntegrateCrossProjectDuplications;
import org.sonar.ce.task.projectanalysis.event.EventRepositoryImpl;
import org.sonar.ce.task.projectanalysis.filemove.AddedFileRepositoryImpl;
import org.sonar.ce.task.projectanalysis.filemove.FileSimilarityImpl;
import org.sonar.ce.task.projectanalysis.filemove.MutableMovedFilesRepositoryImpl;
import org.sonar.ce.task.projectanalysis.filemove.ScoreMatrixDumperImpl;
import org.sonar.ce.task.projectanalysis.filemove.SourceSimilarityImpl;
import org.sonar.ce.task.projectanalysis.filesystem.ComputationTempFolderProvider;
import org.sonar.ce.task.projectanalysis.issue.BaseIssuesLoader;
import org.sonar.ce.task.projectanalysis.issue.CloseIssuesOnRemovedComponentsVisitor;
import org.sonar.ce.task.projectanalysis.issue.ClosedIssuesInputFactory;
import org.sonar.ce.task.projectanalysis.issue.ComponentIssuesLoader;
import org.sonar.ce.task.projectanalysis.issue.ComponentIssuesRepositoryImpl;
import org.sonar.ce.task.projectanalysis.issue.ComponentsWithUnprocessedIssues;
import org.sonar.ce.task.projectanalysis.issue.ComputeLocationHashesVisitor;
import org.sonar.ce.task.projectanalysis.issue.DebtCalculator;
import org.sonar.ce.task.projectanalysis.issue.DefaultAssignee;
import org.sonar.ce.task.projectanalysis.issue.EffortAggregator;
import org.sonar.ce.task.projectanalysis.issue.IntegrateIssuesVisitor;
import org.sonar.ce.task.projectanalysis.issue.IssueAssigner;
import org.sonar.ce.task.projectanalysis.issue.IssueChangesToDeleteRepository;
import org.sonar.ce.task.projectanalysis.issue.IssueCounter;
import org.sonar.ce.task.projectanalysis.issue.IssueCreationDateCalculator;
import org.sonar.ce.task.projectanalysis.issue.IssueLifecycle;
import org.sonar.ce.task.projectanalysis.issue.IssueOnReferenceBranchVisitor;
import org.sonar.ce.task.projectanalysis.issue.IssueTrackingDelegator;
import org.sonar.ce.task.projectanalysis.issue.IssueVisitors;
import org.sonar.ce.task.projectanalysis.issue.IssuesRepositoryVisitor;
import org.sonar.ce.task.projectanalysis.issue.LoadComponentUuidsHavingOpenIssuesVisitor;
import org.sonar.ce.task.projectanalysis.issue.MovedIssueVisitor;
import org.sonar.ce.task.projectanalysis.issue.NewEffortAggregator;
import org.sonar.ce.task.projectanalysis.issue.NewIssueClassifier;
import org.sonar.ce.task.projectanalysis.issue.ProtoIssueCache;
import org.sonar.ce.task.projectanalysis.issue.PullRequestSourceBranchMerger;
import org.sonar.ce.task.projectanalysis.issue.PullRequestTrackerExecution;
import org.sonar.ce.task.projectanalysis.issue.ReferenceBranchTrackerExecution;
import org.sonar.ce.task.projectanalysis.issue.RemoveProcessedComponentsVisitor;
import org.sonar.ce.task.projectanalysis.issue.RuleRepositoryImpl;
import org.sonar.ce.task.projectanalysis.issue.RuleTagsCopier;
import org.sonar.ce.task.projectanalysis.issue.ScmAccountToUser;
import org.sonar.ce.task.projectanalysis.issue.ScmAccountToUserLoader;
import org.sonar.ce.task.projectanalysis.issue.SiblingsIssueMerger;
import org.sonar.ce.task.projectanalysis.issue.SiblingsIssuesLoader;
import org.sonar.ce.task.projectanalysis.issue.SourceBranchComponentUuids;
import org.sonar.ce.task.projectanalysis.issue.TargetBranchComponentUuids;
import org.sonar.ce.task.projectanalysis.issue.TrackerBaseInputFactory;
import org.sonar.ce.task.projectanalysis.issue.TrackerExecution;
import org.sonar.ce.task.projectanalysis.issue.TrackerRawInputFactory;
import org.sonar.ce.task.projectanalysis.issue.TrackerReferenceBranchInputFactory;
import org.sonar.ce.task.projectanalysis.issue.TrackerSourceBranchInputFactory;
import org.sonar.ce.task.projectanalysis.issue.TrackerTargetBranchInputFactory;
import org.sonar.ce.task.projectanalysis.issue.UpdateConflictResolver;
import org.sonar.ce.task.projectanalysis.issue.filter.IssueFilter;
import org.sonar.ce.task.projectanalysis.language.LanguageRepositoryImpl;
import org.sonar.ce.task.projectanalysis.locations.flow.FlowGenerator;
import org.sonar.ce.task.projectanalysis.measure.MeasureComputersHolderImpl;
import org.sonar.ce.task.projectanalysis.measure.MeasureComputersVisitor;
import org.sonar.ce.task.projectanalysis.measure.MeasureRepositoryImpl;
import org.sonar.ce.task.projectanalysis.measure.MeasureToMeasureDto;
import org.sonar.ce.task.projectanalysis.metric.MetricModule;
import org.sonar.ce.task.projectanalysis.notification.NotificationFactory;
import org.sonar.ce.task.projectanalysis.period.NewCodePeriodResolver;
import org.sonar.ce.task.projectanalysis.period.NewCodeReferenceBranchComponentUuids;
import org.sonar.ce.task.projectanalysis.period.PeriodHolderImpl;
import org.sonar.ce.task.projectanalysis.pushevent.PushEventFactory;
import org.sonar.ce.task.projectanalysis.qualitygate.EvaluationResultTextConverterImpl;
import org.sonar.ce.task.projectanalysis.qualitygate.QualityGateHolderImpl;
import org.sonar.ce.task.projectanalysis.qualitygate.QualityGateServiceImpl;
import org.sonar.ce.task.projectanalysis.qualitygate.QualityGateStatusHolderImpl;
import org.sonar.ce.task.projectanalysis.qualitymodel.MaintainabilityMeasuresVisitor;
import org.sonar.ce.task.projectanalysis.qualitymodel.NewMaintainabilityMeasuresVisitor;
import org.sonar.ce.task.projectanalysis.qualitymodel.NewReliabilityAndSecurityRatingMeasuresVisitor;
import org.sonar.ce.task.projectanalysis.qualitymodel.NewSecurityReviewMeasuresVisitor;
import org.sonar.ce.task.projectanalysis.qualitymodel.RatingSettings;
import org.sonar.ce.task.projectanalysis.qualitymodel.ReliabilityAndSecurityRatingMeasuresVisitor;
import org.sonar.ce.task.projectanalysis.qualitymodel.SecurityReviewMeasuresVisitor;
import org.sonar.ce.task.projectanalysis.qualityprofile.ActiveRulesHolderImpl;
import org.sonar.ce.task.projectanalysis.qualityprofile.QProfileStatusRepositoryImpl;
import org.sonar.ce.task.projectanalysis.scm.ScmInfoDbLoader;
import org.sonar.ce.task.projectanalysis.scm.ScmInfoRepositoryImpl;
import org.sonar.ce.task.projectanalysis.source.DbLineHashVersion;
import org.sonar.ce.task.projectanalysis.source.FileSourceDataComputer;
import org.sonar.ce.task.projectanalysis.source.FileSourceDataWarnings;
import org.sonar.ce.task.projectanalysis.source.LastCommitVisitor;
import org.sonar.ce.task.projectanalysis.source.NewLinesRepository;
import org.sonar.ce.task.projectanalysis.source.SignificantCodeRepository;
import org.sonar.ce.task.projectanalysis.source.SourceHashRepositoryImpl;
import org.sonar.ce.task.projectanalysis.source.SourceLineReadersFactory;
import org.sonar.ce.task.projectanalysis.source.SourceLinesDiffImpl;
import org.sonar.ce.task.projectanalysis.source.SourceLinesHashCache;
import org.sonar.ce.task.projectanalysis.source.SourceLinesHashRepositoryImpl;
import org.sonar.ce.task.projectanalysis.source.SourceLinesRepositoryImpl;
import org.sonar.ce.task.projectanalysis.step.ReportComputationSteps;
import org.sonar.ce.task.projectanalysis.step.SmallChangesetQualityGateSpecialCase;
import org.sonar.ce.task.projectanalysis.webhook.WebhookPostTask;
import org.sonar.ce.task.setting.SettingsLoader;
import org.sonar.ce.task.step.ComputationStepExecutor;
import org.sonar.ce.task.step.ComputationSteps;
import org.sonar.ce.task.taskprocessor.MutableTaskResultHolderImpl;
import org.sonar.core.issue.tracking.Tracker;
import org.sonar.core.platform.ContainerPopulator;
import org.sonar.server.issue.TaintChecker;
import org.sonar.server.setting.ProjectConfigurationLoaderImpl;
import org.sonar.server.view.index.ViewIndex;
public final class ProjectAnalysisTaskContainerPopulator implements ContainerPopulator<TaskContainer> {
private static final ReportAnalysisComponentProvider[] NO_REPORT_ANALYSIS_COMPONENT_PROVIDERS = new ReportAnalysisComponentProvider[0];
private final CeTask task;
private final ReportAnalysisComponentProvider[] componentProviders;
public ProjectAnalysisTaskContainerPopulator(CeTask task, @Nullable ReportAnalysisComponentProvider[] componentProviders) {
this.task = task;
this.componentProviders = componentProviders == null ? NO_REPORT_ANALYSIS_COMPONENT_PROVIDERS : componentProviders;
}
@Override
public void populateContainer(TaskContainer container) {
ComputationSteps steps = new ReportComputationSteps(container);
container.add(SettingsLoader.class);
container.add(task);
container.add(steps);
container.add(componentClasses());
for (ReportAnalysisComponentProvider componentProvider : componentProviders) {
container.add(componentProvider.getComponents());
}
container.add(steps.orderedStepClasses());
}
/**
* List of all objects to be injected in the ioc container dedicated to computation stack.
* Does not contain the steps declared in {@link ReportComputationSteps#orderedStepClasses()}.
*/
private static List<Object> componentClasses() {
return Arrays.asList(
ProjectConfigurationLoaderImpl.class,
PostProjectAnalysisTasksExecutor.class,
ComputationStepExecutor.class,
// messages/warnings
CeTaskMessagesImpl.class,
FileSourceDataWarnings.class,
// File System
new ComputationTempFolderProvider(),
FileStatusesImpl.class,
new MetricModule(),
// holders
AnalysisMetadataHolderImpl.class,
CrossProjectDuplicationStatusHolderImpl.class,
BatchReportDirectoryHolderImpl.class,
TreeRootHolderImpl.class,
PeriodHolderImpl.class,
QualityGateHolderImpl.class,
QualityGateStatusHolderImpl.class,
RatingSettings.class,
ActiveRulesHolderImpl.class,
MeasureComputersHolderImpl.class,
MutableTaskResultHolderImpl.class,
BatchReportReaderImpl.class,
ReferenceBranchComponentUuids.class,
NewCodeReferenceBranchComponentUuids.class,
SiblingComponentsWithOpenIssues.class,
// repositories
PreviousSourceHashRepositoryImpl.class,
LanguageRepositoryImpl.class,
MeasureRepositoryImpl.class,
EventRepositoryImpl.class,
ConfigurationRepositoryImpl.class,
DisabledComponentsHolderImpl.class,
QualityGateServiceImpl.class,
EvaluationResultTextConverterImpl.class,
SourceLinesRepositoryImpl.class,
SourceHashRepositoryImpl.class,
SourceLinesDiffImpl.class,
ScmInfoRepositoryImpl.class,
ScmInfoDbLoader.class,
DuplicationRepositoryImpl.class,
SourceLinesHashRepositoryImpl.class,
DbLineHashVersion.class,
SignificantCodeRepository.class,
SourceLinesHashCache.class,
NewLinesRepository.class,
FileSourceDataComputer.class,
SourceLineReadersFactory.class,
QProfileStatusRepositoryImpl.class,
IssueChangesToDeleteRepository.class,
// issues
RuleRepositoryImpl.class,
ScmAccountToUserLoader.class,
ScmAccountToUser.class,
ProtoIssueCache.class,
DefaultAssignee.class,
IssueVisitors.class,
IssueLifecycle.class,
NewIssueClassifier.class,
ComponentsWithUnprocessedIssues.class,
ComponentIssuesRepositoryImpl.class,
IssueFilter.class,
FlowGenerator.class,
// push events
PushEventFactory.class,
// order is important: RuleTypeCopier must be the first one. And DebtAggregator must be before NewDebtAggregator (new debt requires
// debt)
RuleTagsCopier.class,
IssueCreationDateCalculator.class,
ComputeLocationHashesVisitor.class,
DebtCalculator.class,
EffortAggregator.class,
NewEffortAggregator.class,
IssueAssigner.class,
IssueCounter.class,
MovedIssueVisitor.class,
IssuesRepositoryVisitor.class,
RemoveProcessedComponentsVisitor.class,
IssueOnReferenceBranchVisitor.class,
// visitors : order is important, measure computers must be executed at the end in order to access to every measures / issues
AnalysisFromSonarQube94Visitor.class,
LoadComponentUuidsHavingOpenIssuesVisitor.class,
IntegrateIssuesVisitor.class,
TaintChecker.class,
CloseIssuesOnRemovedComponentsVisitor.class,
MaintainabilityMeasuresVisitor.class,
NewMaintainabilityMeasuresVisitor.class,
ReliabilityAndSecurityRatingMeasuresVisitor.class,
NewReliabilityAndSecurityRatingMeasuresVisitor.class,
SecurityReviewMeasuresVisitor.class,
NewSecurityReviewMeasuresVisitor.class,
LastCommitVisitor.class,
MeasureComputersVisitor.class,
TargetBranchComponentUuids.class,
UpdateConflictResolver.class,
TrackerBaseInputFactory.class,
TrackerTargetBranchInputFactory.class,
TrackerRawInputFactory.class,
TrackerReferenceBranchInputFactory.class,
TrackerSourceBranchInputFactory.class,
SourceBranchComponentUuids.class,
ClosedIssuesInputFactory.class,
Tracker.class,
TrackerExecution.class,
PullRequestTrackerExecution.class,
PullRequestSourceBranchMerger.class,
ReferenceBranchTrackerExecution.class,
ComponentIssuesLoader.class,
BaseIssuesLoader.class,
IssueTrackingDelegator.class,
BranchPersisterImpl.class,
ProjectPersister.class,
SiblingsIssuesLoader.class,
SiblingsIssueMerger.class,
NewCodePeriodResolver.class,
// filemove
ScoreMatrixDumperImpl.class,
SourceSimilarityImpl.class,
FileSimilarityImpl.class,
MutableMovedFilesRepositoryImpl.class,
AddedFileRepositoryImpl.class,
// duplication
IntegrateCrossProjectDuplications.class,
DuplicationMeasures.class,
// views
ViewIndex.class,
BranchLoader.class,
MeasureToMeasureDto.class,
SmallChangesetQualityGateSpecialCase.class,
// webhooks
WebhookPostTask.class,
// notifications
NotificationFactory.class);
}
}
| 16,326 | 48.03003 | 137 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/container/ReportAnalysisComponentProvider.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.container;
import java.util.List;
import org.sonar.api.ce.ComputeEngineSide;
@ComputeEngineSide
public interface ReportAnalysisComponentProvider {
/**
* Return the list of components to add to the state-full container of a Compute Engine report analysis task
*/
List<Object> getComponents();
}
| 1,193 | 34.117647 | 110 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/container/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.container;
import javax.annotation.ParametersAreNonnullByDefault;
| 983 | 40 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/duplication/AbstractDuplicate.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.duplication;
import javax.annotation.Nullable;
import static java.util.Objects.requireNonNull;
abstract class AbstractDuplicate implements Duplicate {
private final TextBlock textBlock;
protected AbstractDuplicate(TextBlock textBlock) {
this.textBlock = requireNonNull(textBlock, "textBlock of duplicate can not be null");
}
@Override
public TextBlock getTextBlock() {
return textBlock;
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AbstractDuplicate that = (AbstractDuplicate) o;
return textBlock.equals(that.textBlock);
}
@Override
public int hashCode() {
return textBlock.hashCode();
}
}
| 1,661 | 28.678571 | 89 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/duplication/CrossProjectDuplicate.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.duplication;
import java.util.Objects;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import static java.util.Objects.requireNonNull;
@Immutable
public class CrossProjectDuplicate extends AbstractDuplicate {
private final String fileKey;
public CrossProjectDuplicate(String fileKey, TextBlock textBlock) {
super(textBlock);
this.fileKey = requireNonNull(fileKey, "fileKey can not be null");
}
public String getFileKey() {
return fileKey;
}
@Override
public String toString() {
return "CrossProjectDuplicate{" +
"fileKey='" + fileKey + '\'' +
", textBlock=" + getTextBlock() +
'}';
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass() || !super.equals(o)) {
return false;
}
CrossProjectDuplicate that = (CrossProjectDuplicate) o;
return fileKey.equals(that.fileKey);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), fileKey);
}
}
| 1,967 | 28.818182 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/duplication/CrossProjectDuplicationStatusHolder.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.duplication;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
/**
* A simple holder to know if the cross project duplication should be computed or not.
*
* A log will be displayed whether or not the cross project duplication is enabled or not.
*/
public interface CrossProjectDuplicationStatusHolder {
/**
* Cross project duplications is enabled when :
* <ui>
* <li>{@link AnalysisMetadataHolder#isCrossProjectDuplicationEnabled()} is true</li>
* <li>{@link AnalysisMetadataHolder#getBranch()} ()} is null</li>
* </ui>
*/
boolean isEnabled();
}
| 1,489 | 35.341463 | 90 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/duplication/CrossProjectDuplicationStatusHolderImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.duplication;
import javax.annotation.CheckForNull;
import org.sonar.api.Startable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import static com.google.common.base.Preconditions.checkState;
public class CrossProjectDuplicationStatusHolderImpl implements CrossProjectDuplicationStatusHolder, Startable {
private static final Logger LOGGER = LoggerFactory.getLogger(CrossProjectDuplicationStatusHolderImpl.class);
@CheckForNull
private Boolean enabled;
private final AnalysisMetadataHolder analysisMetadataHolder;
public CrossProjectDuplicationStatusHolderImpl(AnalysisMetadataHolder analysisMetadataHolder) {
this.analysisMetadataHolder = analysisMetadataHolder;
}
@Override
public boolean isEnabled() {
checkState(enabled != null, "Flag hasn't been initialized, the start() should have been called before.");
return enabled;
}
@Override
public void start() {
boolean enabledInReport = analysisMetadataHolder.isCrossProjectDuplicationEnabled();
boolean supportedByBranch = analysisMetadataHolder.getBranch().supportsCrossProjectCpd();
if (enabledInReport && supportedByBranch) {
LOGGER.debug("Cross project duplication is enabled");
this.enabled = true;
} else {
if (!enabledInReport) {
LOGGER.debug("Cross project duplication is disabled because it's disabled in the analysis report");
} else {
LOGGER.debug("Cross project duplication is disabled because of a branch is used");
}
this.enabled = false;
}
}
@Override
public void stop() {
// nothing to do
}
}
| 2,557 | 35.542857 | 112 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/duplication/DetailedTextBlock.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.duplication;
import java.util.Objects;
import javax.annotation.Nullable;
/**
* Given that:
* <ul>
* <li>some language plugins are able to multiple duplication for the same textblock but with a
* different starting and/or ending offset</li>
* <li>there is no way to distinguish these block from each other as the offsets (or any other
* information) is not sent in the analysis report</li>
* </ul>,
* we are uniquely (and blindly) identifying each original block reported in the analysis report.
*/
public class DetailedTextBlock extends TextBlock {
private final int id;
/**
* @throws IllegalArgumentException if {@code start} is 0 or less
* @throws IllegalStateException if {@code end} is less than {@code start}
*/
public DetailedTextBlock(int id, int start, int end) {
super(start, end);
this.id = id;
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
DetailedTextBlock that = (DetailedTextBlock) o;
return id == that.id;
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), id);
}
}
| 2,147 | 31.545455 | 97 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/duplication/Duplicate.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.duplication;
public interface Duplicate {
TextBlock getTextBlock();
}
| 958 | 37.36 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/duplication/Duplication.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.duplication;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
import javax.annotation.Nonnull;
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 final class Duplication {
private static final Comparator<Duplicate> DUPLICATE_COMPARATOR = DuplicateComparatorByType.INSTANCE
.thenComparing(DuplicateToFileKey.INSTANCE).thenComparing(DuplicateToTextBlock.INSTANCE);
private final TextBlock original;
private final Duplicate[] duplicates;
/**
* @throws NullPointerException if {@code original} is {@code null} or {@code duplicates} is {@code null} or {@code duplicates} contains {@code null}
* @throws IllegalArgumentException if {@code duplicates} is empty
* @throws IllegalArgumentException if {@code duplicates} contains a {@link InnerDuplicate} with {@code original}
*/
public Duplication(TextBlock original, List<Duplicate> duplicates) {
this.original = requireNonNull(original, "original TextBlock can not be null");
validateDuplicates(original, duplicates);
this.duplicates = duplicates.stream().sorted(DUPLICATE_COMPARATOR).distinct().toArray(Duplicate[]::new);
}
private static void validateDuplicates(TextBlock original, List<Duplicate> duplicates) {
requireNonNull(duplicates, "duplicates can not be null");
checkArgument(!duplicates.isEmpty(), "duplicates can not be empty");
for (Duplicate dup : duplicates) {
requireNonNull(dup, "duplicates can not contain null");
if (dup instanceof InnerDuplicate) {
checkArgument(!original.equals(dup.getTextBlock()), "TextBlock of an InnerDuplicate can not be the original TextBlock");
}
}
}
/**
* The duplicated block.
*/
public TextBlock getOriginal() {
return this.original;
}
/**
* The duplicates of the original, sorted by inner duplicates, then project duplicates, then cross-project duplicates.
* For each category of duplicate, they are sorted by:
* <ul>
* <li>file key (unless it's an InnerDuplicate)</li>
* <li>then by TextBlocks by start line and in case of same line, by shortest first</li>
* </ul
* <p>The returned set can not be empty and no inner duplicate can contain the original {@link TextBlock}.</p>
*/
public Duplicate[] getDuplicates() {
return this.duplicates;
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Duplication that = (Duplication) o;
return original.equals(that.original) && Arrays.equals(duplicates, that.duplicates);
}
@Override
public int hashCode() {
return Arrays.deepHashCode(new Object[] {original, duplicates});
}
@Override
public String toString() {
return "Duplication{" +
"original=" + original +
", duplicates=" + Arrays.toString(duplicates) +
'}';
}
private enum DuplicateComparatorByType implements Comparator<Duplicate> {
INSTANCE;
@Override
public int compare(Duplicate o1, Duplicate o2) {
return toIndexType(o1) - toIndexType(o2);
}
private static int toIndexType(Duplicate duplicate) {
if (duplicate instanceof InnerDuplicate) {
return 0;
}
if (duplicate instanceof InProjectDuplicate) {
return 1;
}
if (duplicate instanceof CrossProjectDuplicate) {
return 2;
}
throw new IllegalArgumentException("Unsupported type of Duplicate " + duplicate.getClass().getName());
}
}
private enum DuplicateToTextBlock implements Function<Duplicate, TextBlock> {
INSTANCE;
@Override
@Nonnull
public TextBlock apply(@Nonnull Duplicate input) {
return input.getTextBlock();
}
}
private enum DuplicateToFileKey implements Function<Duplicate, String> {
INSTANCE;
@Override
@Nonnull
public String apply(@Nonnull Duplicate duplicate) {
if (duplicate instanceof InnerDuplicate) {
return "";
}
if (duplicate instanceof InProjectDuplicate inProjectDuplicate) {
return inProjectDuplicate.getFile().getKey();
}
if (duplicate instanceof CrossProjectDuplicate crossProjectDuplicate) {
return crossProjectDuplicate.getFileKey();
}
throw new IllegalArgumentException("Unsupported type of Duplicate " + duplicate.getClass().getName());
}
}
}
| 5,481 | 33.2625 | 155 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/duplication/DuplicationMeasures.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.duplication;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.inject.Inject;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.PathAwareCrawler;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.projectanalysis.formula.Counter;
import org.sonar.ce.task.projectanalysis.formula.CounterInitializationContext;
import org.sonar.ce.task.projectanalysis.formula.CreateMeasureContext;
import org.sonar.ce.task.projectanalysis.formula.Formula;
import org.sonar.ce.task.projectanalysis.formula.FormulaExecutorComponentVisitor;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import org.sonar.ce.task.projectanalysis.measure.MeasureRepository;
import org.sonar.ce.task.projectanalysis.metric.MetricRepository;
import static com.google.common.collect.Iterables.isEmpty;
import static java.util.Objects.requireNonNull;
import static org.sonar.api.measures.CoreMetrics.DUPLICATED_BLOCKS_KEY;
import static org.sonar.api.measures.CoreMetrics.DUPLICATED_FILES_KEY;
import static org.sonar.api.measures.CoreMetrics.DUPLICATED_LINES_DENSITY_KEY;
import static org.sonar.api.measures.CoreMetrics.DUPLICATED_LINES_KEY;
import static org.sonar.api.measures.CoreMetrics.LINES_KEY;
public class DuplicationMeasures {
protected final List<Formula<?>> formulas;
protected final TreeRootHolder treeRootHolder;
protected final MetricRepository metricRepository;
protected final MeasureRepository measureRepository;
private final DuplicationRepository duplicationRepository;
@Inject
public DuplicationMeasures(TreeRootHolder treeRootHolder, MetricRepository metricRepository, MeasureRepository measureRepository,
@Nullable DuplicationRepository duplicationRepository) {
this.treeRootHolder = treeRootHolder;
this.metricRepository = metricRepository;
this.measureRepository = measureRepository;
// will be null for views
this.duplicationRepository = duplicationRepository;
this.formulas = List.of(new DuplicationFormula());
}
public DuplicationMeasures(TreeRootHolder treeRootHolder, MetricRepository metricRepository, MeasureRepository measureRepository) {
this(treeRootHolder, metricRepository, measureRepository, null);
}
public void execute() {
new PathAwareCrawler<>(
FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository).buildFor(formulas))
.visit(treeRootHolder.getReportTreeRoot());
}
protected DuplicationCounter createCounter() {
return new DuplicationCounter(duplicationRepository);
}
protected static class DuplicationCounter implements Counter<DuplicationCounter> {
@CheckForNull
private final DuplicationRepository duplicationRepository;
protected int fileCount = 0;
protected int blockCount = 0;
protected int dupLineCount = 0;
protected int lineCount = 0;
private DuplicationCounter(@Nullable DuplicationRepository duplicationRepository) {
this.duplicationRepository = duplicationRepository;
}
@Override
public void aggregate(DuplicationCounter counter) {
this.fileCount += counter.fileCount;
this.blockCount += counter.blockCount;
this.dupLineCount += counter.dupLineCount;
this.lineCount += counter.lineCount;
}
@Override
public void initialize(CounterInitializationContext context) {
Component leaf = context.getLeaf();
if (leaf.getType() == Component.Type.FILE && !leaf.getFileAttributes().isUnitTest()) {
initializeForFile(leaf);
} else if (leaf.getType() == Component.Type.PROJECT_VIEW) {
initializeForProjectView(context);
}
}
protected void initializeForFile(Component file) {
// don't use measure since it won't be available for some files in the report tree in PRs
this.lineCount = file.getFileAttributes().getLines();
Iterable<Duplication> duplications = requireNonNull(this.duplicationRepository, "DuplicationRepository missing")
.getDuplications(file);
if (isEmpty(duplications)) {
return;
}
// use a set to count lines only once
Set<Integer> duplicatedLineNumbers = new HashSet<>();
int blocks = 0;
for (Duplication duplication : duplications) {
blocks++;
addLines(duplication.getOriginal(), duplicatedLineNumbers);
InnerDuplicate[] innerDuplicates = Arrays.stream(duplication.getDuplicates())
.filter(InnerDuplicate.class::isInstance)
.map(InnerDuplicate.class::cast)
.toArray(InnerDuplicate[]::new);
for (InnerDuplicate innerDuplicate : innerDuplicates) {
blocks++;
addLines(innerDuplicate.getTextBlock(), duplicatedLineNumbers);
}
}
this.fileCount += 1;
this.blockCount += blocks;
this.dupLineCount += duplicatedLineNumbers.size();
}
private static void addLines(TextBlock textBlock, Set<Integer> duplicatedLineNumbers) {
for (int i = textBlock.getStart(); i <= textBlock.getEnd(); i++) {
duplicatedLineNumbers.add(i);
}
}
private void initializeForProjectView(CounterInitializationContext context) {
fileCount += getMeasure(context, DUPLICATED_FILES_KEY);
blockCount += getMeasure(context, DUPLICATED_BLOCKS_KEY);
dupLineCount += getMeasure(context, DUPLICATED_LINES_KEY);
lineCount += getMeasure(context, LINES_KEY);
}
private static int getMeasure(CounterInitializationContext context, String metricKey) {
Optional<Measure> files = context.getMeasure(metricKey);
return files.map(Measure::getIntValue).orElse(0);
}
}
private final class DuplicationFormula implements Formula<DuplicationCounter> {
@Override
public DuplicationCounter createNewCounter() {
return createCounter();
}
@Override
public Optional<Measure> createMeasure(DuplicationCounter counter, CreateMeasureContext context) {
switch (context.getMetric().getKey()) {
case DUPLICATED_FILES_KEY:
return Optional.of(Measure.newMeasureBuilder().create(counter.fileCount));
case DUPLICATED_LINES_KEY:
return Optional.of(Measure.newMeasureBuilder().create(counter.dupLineCount));
case DUPLICATED_LINES_DENSITY_KEY:
return createDuplicatedLinesDensityMeasure(counter, context);
case DUPLICATED_BLOCKS_KEY:
return Optional.of(Measure.newMeasureBuilder().create(counter.blockCount));
default:
throw new IllegalArgumentException("Unsupported metric " + context.getMetric());
}
}
private Optional<Measure> createDuplicatedLinesDensityMeasure(DuplicationCounter counter, CreateMeasureContext context) {
int duplicatedLines = counter.dupLineCount;
int nbLines = counter.lineCount;
if (nbLines > 0) {
double density = Math.min(100.0, 100.0 * duplicatedLines / nbLines);
return Optional.of(Measure.newMeasureBuilder().create(density, context.getMetric().getDecimalScale()));
}
return Optional.empty();
}
@Override
public String[] getOutputMetricKeys() {
return new String[] {DUPLICATED_FILES_KEY, DUPLICATED_LINES_KEY, DUPLICATED_LINES_DENSITY_KEY, DUPLICATED_BLOCKS_KEY};
}
}
}
| 8,332 | 40.457711 | 133 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/duplication/DuplicationRepository.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.duplication;
import org.sonar.ce.task.projectanalysis.component.Component;
/**
* Repository of code duplications in files of the project.
* <p>
* It stores:
* <ul>
* <li>inner duplications (ie. duplications of blocks inside the same file)</li>
* <li>project duplications (ie. duplications of blocks between two files of the current project)</li>
* <li>cross-project duplications (ie. duplications of blocks of code between a file of the current project and a file of another project)</li>
* </ul>
* </p>
*/
public interface DuplicationRepository {
/**
* Returns the duplications in the specified file {@link Component}, if any.
*
* @throws NullPointerException if {@code file} is {@code null}
* @throws IllegalArgumentException if the type of the {@link Component} argument is not {@link Component.Type#FILE}
*/
Iterable<Duplication> getDuplications(Component file);
/**
* Adds a project duplication in the specified file {@link Component} to the repository.
*
* @throws NullPointerException if any argument is {@code null}
* @throws IllegalArgumentException if the type of the {@link Component} argument is not {@link Component.Type#FILE}
*/
void add(Component file, Duplication duplication);
}
| 2,139 | 39.377358 | 145 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/duplication/DuplicationRepositoryImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.duplication;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import java.util.Collection;
import java.util.Collections;
import org.sonar.ce.task.projectanalysis.component.Component;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.Objects.requireNonNull;
/**
* In-memory implementation of {@link DuplicationRepository}.
*/
public class DuplicationRepositoryImpl implements DuplicationRepository {
private Multimap<String, Duplication> duplications = HashMultimap.create();
@Override
public Iterable<Duplication> getDuplications(Component file) {
checkFileComponentArgument(file);
Collection<Duplication> res = this.duplications.asMap().get(file.getKey());
if (res == null) {
return Collections.emptyList();
}
return res;
}
@Override
public void add(Component file, Duplication duplication) {
checkFileComponentArgument(file);
checkNotNull(duplication, "duplication can not be null");
duplications.put(file.getKey(), duplication);
}
private static void checkFileComponentArgument(Component file) {
requireNonNull(file, "file can not be null");
checkArgument(file.getType() == Component.Type.FILE, "type of file must be FILE");
}
}
| 2,238 | 34.539683 | 86 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/duplication/InExtendedProjectDuplicate.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.duplication;
import org.sonar.ce.task.projectanalysis.component.Component;
public class InExtendedProjectDuplicate extends InProjectDuplicate {
public InExtendedProjectDuplicate(Component file, TextBlock textBlock) {
super(file, textBlock);
}
@Override
public String toString() {
return "InExtendedProjectDuplicate{" +
"file=" + file +
", textBlock=" + getTextBlock() +
'}';
}
}
| 1,303 | 34.243243 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/duplication/InProjectDuplicate.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.duplication;
import java.util.Objects;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.sonar.ce.task.projectanalysis.component.Component;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
@Immutable
public class InProjectDuplicate extends AbstractDuplicate {
protected final Component file;
public InProjectDuplicate(Component file, TextBlock textBlock) {
super(textBlock);
requireNonNull(file, "file can not be null");
checkArgument(file.getType() == Component.Type.FILE, "file must be of type FILE");
this.file = file;
}
public Component getFile() {
return file;
}
@Override
public String toString() {
return "InProjectDuplicate{" +
"file=" + file +
", textBlock=" + getTextBlock() +
'}';
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
InProjectDuplicate that = (InProjectDuplicate) o;
return file.equals(that.file);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), file);
}
}
| 2,172 | 28.767123 | 86 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/duplication/InnerDuplicate.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.duplication;
import javax.annotation.concurrent.Immutable;
@Immutable
public final class InnerDuplicate extends AbstractDuplicate {
public InnerDuplicate(TextBlock textBlock) {
super(textBlock);
}
@Override
public String toString() {
return "InnerDuplicate{" +
"textBlock=" + getTextBlock() +
'}';
}
}
| 1,221 | 31.157895 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/duplication/IntegrateCrossProjectDuplications.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.duplication;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Predicate;
import javax.annotation.Nonnull;
import org.sonar.api.config.Configuration;
import org.sonar.api.utils.System2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.ce.task.log.CeTaskMessages;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.duplications.block.Block;
import org.sonar.duplications.detector.suffixtree.SuffixTreeCloneDetectionAlgorithm;
import org.sonar.duplications.index.CloneGroup;
import org.sonar.duplications.index.CloneIndex;
import org.sonar.duplications.index.ClonePart;
import org.sonar.duplications.index.PackedMemoryCloneIndex;
/**
* Transform a list of duplication blocks into clone groups, then add these clone groups into the duplication repository.
*/
public class IntegrateCrossProjectDuplications {
private static final Logger LOGGER = LoggerFactory.getLogger(IntegrateCrossProjectDuplications.class);
private static final String JAVA_KEY = "java";
private static final String DEPRECATED_WARNING = "This analysis uses the deprecated cross-project duplication feature.";
private static final String DEPRECATED_WARNING_DASHBOARD = "This project uses the deprecated cross-project duplication feature.";
private static final int MAX_CLONE_GROUP_PER_FILE = 100;
private static final int MAX_CLONE_PART_PER_GROUP = 100;
private final Configuration config;
private final DuplicationRepository duplicationRepository;
private final Map<String, NumberOfUnitsNotLessThan> numberOfUnitsByLanguage = new HashMap<>();
public IntegrateCrossProjectDuplications(CrossProjectDuplicationStatusHolder crossProjectDuplicationStatusHolder, Configuration config,
DuplicationRepository duplicationRepository, CeTaskMessages ceTaskMessages, System2 system) {
this.config = config;
this.duplicationRepository = duplicationRepository;
if (crossProjectDuplicationStatusHolder.isEnabled()) {
LOGGER.warn(DEPRECATED_WARNING);
ceTaskMessages.add(new CeTaskMessages.Message(DEPRECATED_WARNING_DASHBOARD, system.now()));
}
}
public void computeCpd(Component component, Collection<Block> originBlocks, Collection<Block> duplicationBlocks) {
CloneIndex duplicationIndex = new PackedMemoryCloneIndex();
populateIndex(duplicationIndex, originBlocks);
populateIndex(duplicationIndex, duplicationBlocks);
List<CloneGroup> duplications = SuffixTreeCloneDetectionAlgorithm.detect(duplicationIndex, originBlocks);
Iterable<CloneGroup> filtered = duplications.stream()
.filter(getNumberOfUnitsNotLessThan(component.getFileAttributes().getLanguageKey()))
.toList();
addDuplications(component, filtered);
}
private static void populateIndex(CloneIndex duplicationIndex, Collection<Block> duplicationBlocks) {
for (Block block : duplicationBlocks) {
duplicationIndex.insert(block);
}
}
private void addDuplications(Component file, Iterable<CloneGroup> duplications) {
int cloneGroupCount = 0;
for (CloneGroup duplication : duplications) {
cloneGroupCount++;
if (cloneGroupCount > MAX_CLONE_GROUP_PER_FILE) {
LOGGER.warn("Too many duplication groups on file {}. Keeping only the first {} groups.", file.getKey(), MAX_CLONE_GROUP_PER_FILE);
break;
}
addDuplication(file, duplication);
}
}
private void addDuplication(Component file, CloneGroup duplication) {
ClonePart originPart = duplication.getOriginPart();
List<Duplicate> duplicates = convertClonePartsToDuplicates(file, duplication);
if (!duplicates.isEmpty()) {
duplicationRepository.add(
file,
new Duplication(new TextBlock(originPart.getStartLine(), originPart.getEndLine()), duplicates));
}
}
private static List<Duplicate> convertClonePartsToDuplicates(final Component file, CloneGroup duplication) {
final ClonePart originPart = duplication.getOriginPart();
return duplication.getCloneParts().stream()
.filter(new DoesNotMatchSameComponentKey(originPart.getResourceId()))
.filter(new DuplicateLimiter(file, originPart))
.map(ClonePartToCrossProjectDuplicate.INSTANCE)
.toList();
}
private NumberOfUnitsNotLessThan getNumberOfUnitsNotLessThan(String language) {
NumberOfUnitsNotLessThan numberOfUnitsNotLessThan = numberOfUnitsByLanguage.get(language);
if (numberOfUnitsNotLessThan == null) {
numberOfUnitsNotLessThan = new NumberOfUnitsNotLessThan(getMinimumTokens(language));
numberOfUnitsByLanguage.put(language, numberOfUnitsNotLessThan);
}
return numberOfUnitsNotLessThan;
}
private int getMinimumTokens(String languageKey) {
// The java language is an exception : it doesn't compute tokens but statement, so the settings could not be used.
if (languageKey.equalsIgnoreCase(JAVA_KEY)) {
return 0;
}
return config.getInt("sonar.cpd." + languageKey + ".minimumTokens").orElse(100);
}
private static class NumberOfUnitsNotLessThan implements Predicate<CloneGroup> {
private final int min;
NumberOfUnitsNotLessThan(int min) {
this.min = min;
}
@Override
public boolean test(@Nonnull CloneGroup input) {
return input.getLengthInUnits() >= min;
}
}
private static class DoesNotMatchSameComponentKey implements Predicate<ClonePart> {
private final String componentKey;
private DoesNotMatchSameComponentKey(String componentKey) {
this.componentKey = componentKey;
}
@Override
public boolean test(@Nonnull ClonePart part) {
return !part.getResourceId().equals(componentKey);
}
}
private static class DuplicateLimiter implements Predicate<ClonePart> {
private final Component file;
private final ClonePart originPart;
private int counter = 0;
DuplicateLimiter(Component file, ClonePart originPart) {
this.file = file;
this.originPart = originPart;
}
@Override
public boolean test(@Nonnull ClonePart input) {
if (counter == MAX_CLONE_PART_PER_GROUP) {
LOGGER.warn("Too many duplication references on file {} for block at line {}. Keeping only the first {} references.",
file.getKey(), originPart.getStartLine(), MAX_CLONE_PART_PER_GROUP);
}
boolean res = counter < MAX_CLONE_GROUP_PER_FILE;
counter++;
return res;
}
}
private enum ClonePartToCrossProjectDuplicate implements Function<ClonePart, Duplicate> {
INSTANCE;
@Override
@Nonnull
public Duplicate apply(@Nonnull ClonePart input) {
return new CrossProjectDuplicate(
input.getResourceId(),
new TextBlock(input.getStartLine(), input.getEndLine()));
}
}
}
| 7,726 | 38.423469 | 138 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/duplication/TextBlock.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.duplication;
import java.util.Objects;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkArgument;
/**
* A block of text in some file represented by its first line index (1-based) and its last line index (included).
* <p>
* This class defines a natural ordering which sorts {@link TextBlock} by lowest start line first and then, in case of
* same start line, by smallest size (ie. lowest end line).
* </p>
*/
public class TextBlock implements Comparable<TextBlock> {
private final int start;
private final int end;
/**
* @throws IllegalArgumentException if {@code start} is 0 or less
* @throws IllegalStateException if {@code end} is less than {@code start}
*/
public TextBlock(int start, int end) {
checkArgument(start > 0, "First line index must be >= 1");
checkArgument(end >= start, "Last line index must be >= first line index");
this.start = start;
this.end = end;
}
public int getStart() {
return start;
}
public int getEnd() {
return end;
}
@Override
public int compareTo(TextBlock other) {
int res = start - other.start;
if (res == 0) {
return end - other.end;
}
return res;
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
TextBlock textBlock = (TextBlock) o;
return start == textBlock.start && end == textBlock.end;
}
@Override
public int hashCode() {
return Objects.hash(start, end);
}
@Override
public String toString() {
return "TextBlock{" +
"start=" + start +
", end=" + end +
'}';
}
}
| 2,604 | 27.626374 | 118 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/duplication/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.duplication;
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/event/Event.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.event;
import java.util.Objects;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import static java.util.Objects.requireNonNull;
@Immutable
public class Event {
private final String name;
private final Category category;
@Nullable
private final String data;
@Nullable
private final String description;
private Event(String name, Category category, @Nullable String data, @Nullable String description) {
this.name = requireNonNull(name);
this.category = requireNonNull(category);
this.data = data;
this.description = description;
}
public static Event createAlert(String name, @Nullable String data, @Nullable String description) {
return new Event(name, Category.ALERT, data, description);
}
public static Event createProfile(String name, @Nullable String data, @Nullable String description) {
return new Event(name, Category.PROFILE, data, description);
}
public String getName() {
return name;
}
public Category getCategory() {
return category;
}
public String getData() {
return data;
}
@Nullable
public String getDescription() {
return description;
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Event event = (Event) o;
return Objects.equals(name, event.name) &&
Objects.equals(category, event.category);
}
@Override
public int hashCode() {
return Objects.hash(name, category);
}
public enum Category {
ALERT, PROFILE
}
}
| 2,512 | 26.315217 | 103 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/event/EventRepository.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.event;
public interface EventRepository {
/**
* @throws NullPointerException if {@code event} is {@code null}
*/
void add(Event event);
Iterable<Event> getEvents();
}
| 1,066 | 34.566667 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/event/EventRepositoryImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.event;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import static java.util.Objects.requireNonNull;
public class EventRepositoryImpl implements EventRepository {
private final List<Event> events = new LinkedList<>();
@Override
public void add(Event event) {
events.add(requireNonNull(event));
}
@Override
public Iterable<Event> getEvents() {
return Collections.unmodifiableList(this.events);
}
}
| 1,345 | 31.829268 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/event/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.event;
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/filemove/AddedFileRepository.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.filemove;
import org.sonar.ce.task.projectanalysis.component.Component;
public interface AddedFileRepository {
/**
* @return {@code true} for any component on first analysis, otherwise {@code true} only if the specified component is
* a {@link Component.Type#FILE file} registered to the repository.
*/
boolean isAdded(Component component);
}
| 1,251 | 39.387097 | 120 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/filemove/AddedFileRepositoryImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.filemove;
import java.util.HashSet;
import java.util.Set;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.component.Component;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
public class AddedFileRepositoryImpl implements MutableAddedFileRepository {
private final Set<Component> addedComponents = new HashSet<>();
private final AnalysisMetadataHolder analysisMetadataHolder;
public AddedFileRepositoryImpl(AnalysisMetadataHolder analysisMetadataHolder) {
this.analysisMetadataHolder = analysisMetadataHolder;
}
@Override
public boolean isAdded(Component component) {
checkComponent(component);
if (analysisMetadataHolder.isFirstAnalysis()) {
return true;
}
return addedComponents.contains(component);
}
@Override
public void register(Component component) {
checkComponent(component);
checkArgument(component.getType() == Component.Type.FILE, "component must be a file");
checkState(analysisMetadataHolder.isPullRequest() || !analysisMetadataHolder.isFirstAnalysis(), "No file can be registered on first branch analysis");
addedComponents.add(component);
}
private static void checkComponent(Component component) {
checkNotNull(component, "component can't be null");
}
}
| 2,348 | 37.508197 | 154 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/filemove/FileMoveDetectionStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.filemove;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.apache.ibatis.session.ResultContext;
import org.apache.ibatis.session.ResultHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.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.filemove.FileSimilarity.File;
import org.sonar.ce.task.projectanalysis.filemove.FileSimilarity.FileImpl;
import org.sonar.ce.task.projectanalysis.filemove.FileSimilarity.LazyFileImpl;
import org.sonar.ce.task.projectanalysis.source.SourceLinesHashRepository;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.core.util.logs.Profiler;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.FileMoveRowDto;
import org.sonar.db.source.LineHashesWithUuidDto;
import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.POST_ORDER;
public class FileMoveDetectionStep implements ComputationStep {
static final int MIN_REQUIRED_SCORE = 85;
private static final Logger LOG = LoggerFactory.getLogger(FileMoveDetectionStep.class);
private static final Comparator<ScoreMatrix.ScoreFile> SCORE_FILE_COMPARATOR = (o1, o2) -> -1 * Integer.compare(o1.getLineCount(), o2.getLineCount());
private static final double LOWER_BOUND_RATIO = 0.84;
private static final double UPPER_BOUND_RATIO = 1.18;
private final AnalysisMetadataHolder analysisMetadataHolder;
private final TreeRootHolder rootHolder;
private final DbClient dbClient;
private final FileSimilarity fileSimilarity;
private final MutableMovedFilesRepository movedFilesRepository;
private final SourceLinesHashRepository sourceLinesHash;
private final ScoreMatrixDumper scoreMatrixDumper;
private final MutableAddedFileRepository addedFileRepository;
public FileMoveDetectionStep(AnalysisMetadataHolder analysisMetadataHolder, TreeRootHolder rootHolder, DbClient dbClient,
FileSimilarity fileSimilarity, MutableMovedFilesRepository movedFilesRepository, SourceLinesHashRepository sourceLinesHash,
ScoreMatrixDumper scoreMatrixDumper, MutableAddedFileRepository addedFileRepository) {
this.analysisMetadataHolder = analysisMetadataHolder;
this.rootHolder = rootHolder;
this.dbClient = dbClient;
this.fileSimilarity = fileSimilarity;
this.movedFilesRepository = movedFilesRepository;
this.sourceLinesHash = sourceLinesHash;
this.scoreMatrixDumper = scoreMatrixDumper;
this.addedFileRepository = addedFileRepository;
}
@Override
public String getDescription() {
return "Detect file moves";
}
@Override
public void execute(ComputationStep.Context context) {
if (analysisMetadataHolder.isPullRequest()) {
LOG.debug("Currently within Pull Request scope. Do nothing.");
return;
}
// do nothing if no files in db (first analysis)
if (analysisMetadataHolder.isFirstAnalysis()) {
LOG.debug("First analysis. Do nothing.");
return;
}
Profiler p = Profiler.createIfTrace(LOG);
p.start();
Map<String, Component> reportFilesByUuid = getReportFilesByUuid(this.rootHolder.getRoot());
context.getStatistics().add("reportFiles", reportFilesByUuid.size());
if (reportFilesByUuid.isEmpty()) {
LOG.debug("No files in report. No file move detection.");
return;
}
Map<String, DbComponent> dbFilesByUuid = getDbFilesByUuid();
context.getStatistics().add("dbFiles", dbFilesByUuid.size());
Set<String> addedFileUuids = difference(reportFilesByUuid.keySet(), dbFilesByUuid.keySet());
context.getStatistics().add("addedFiles", addedFileUuids.size());
if (dbFilesByUuid.isEmpty()) {
registerAddedFiles(addedFileUuids, reportFilesByUuid, null);
LOG.debug("Previous snapshot has no file. No file move detection.");
return;
}
Set<String> removedFileUuids = difference(dbFilesByUuid.keySet(), reportFilesByUuid.keySet());
// can't find matches if at least one of the added or removed files groups is empty => abort
if (addedFileUuids.isEmpty() || removedFileUuids.isEmpty()) {
registerAddedFiles(addedFileUuids, reportFilesByUuid, null);
LOG.debug("Either no files added or no files removed. Do nothing.");
return;
}
// retrieve file data from report
Map<String, File> addedFileHashesByUuid = getReportFileHashesByUuid(reportFilesByUuid, addedFileUuids);
p.stopTrace("loaded");
// compute score matrix
p.start();
ScoreMatrix scoreMatrix = computeScoreMatrix(dbFilesByUuid, removedFileUuids, addedFileHashesByUuid);
p.stopTrace("Score matrix computed");
scoreMatrixDumper.dumpAsCsv(scoreMatrix);
// not a single match with score higher than MIN_REQUIRED_SCORE => abort
if (scoreMatrix.getMaxScore() < MIN_REQUIRED_SCORE) {
context.getStatistics().add("movedFiles", 0);
registerAddedFiles(addedFileUuids, reportFilesByUuid, null);
LOG.debug("max score in matrix is less than min required score ({}). Do nothing.", MIN_REQUIRED_SCORE);
return;
}
p.start();
MatchesByScore matchesByScore = MatchesByScore.create(scoreMatrix);
ElectedMatches electedMatches = electMatches(removedFileUuids, addedFileHashesByUuid, matchesByScore);
p.stopTrace("Matches elected");
context.getStatistics().add("movedFiles", electedMatches.size());
registerMatches(dbFilesByUuid, reportFilesByUuid, electedMatches);
registerAddedFiles(addedFileUuids, reportFilesByUuid, electedMatches);
}
public Set<String> difference(Set<String> set1, Set<String> set2) {
if (set1.isEmpty() || set2.isEmpty()) {
return set1;
}
return Sets.difference(set1, set2).immutableCopy();
}
private void registerMatches(Map<String, DbComponent> dbFilesByUuid, Map<String, Component> reportFilesByUuid, ElectedMatches electedMatches) {
LOG.debug("{} files moves found", electedMatches.size());
for (Match validatedMatch : electedMatches) {
movedFilesRepository.setOriginalFile(
reportFilesByUuid.get(validatedMatch.reportUuid()),
toOriginalFile(dbFilesByUuid.get(validatedMatch.dbUuid())));
LOG.trace("File move found: {}", validatedMatch);
}
}
private void registerAddedFiles(Set<String> addedFileUuids, Map<String, Component> reportFilesByUuid, @Nullable ElectedMatches electedMatches) {
if (electedMatches == null || electedMatches.isEmpty()) {
addedFileUuids.stream()
.map(reportFilesByUuid::get)
.forEach(addedFileRepository::register);
} else {
Set<String> reallyAddedFileUuids = new HashSet<>(addedFileUuids);
for (Match electedMatch : electedMatches) {
reallyAddedFileUuids.remove(electedMatch.reportUuid());
}
reallyAddedFileUuids.stream()
.map(reportFilesByUuid::get)
.forEach(addedFileRepository::register);
}
}
private Map<String, DbComponent> getDbFilesByUuid() {
try (DbSession dbSession = dbClient.openSession(false)) {
ImmutableList.Builder<DbComponent> builder = ImmutableList.builder();
dbClient.componentDao().scrollAllFilesForFileMove(dbSession, rootHolder.getRoot().getUuid(),
resultContext -> {
FileMoveRowDto row = resultContext.getResultObject();
builder.add(new DbComponent(row.getKey(), row.getUuid(), row.getPath(), row.getLineCount()));
});
return builder.build().stream()
.collect(Collectors.toMap(DbComponent::uuid, Function.identity()));
}
}
private static Map<String, Component> getReportFilesByUuid(Component root) {
final ImmutableMap.Builder<String, Component> builder = ImmutableMap.builder();
new DepthTraversalTypeAwareCrawler(
new TypeAwareVisitorAdapter(CrawlerDepthLimit.FILE, POST_ORDER) {
@Override
public void visitFile(Component file) {
builder.put(file.getUuid(), file);
}
}).visit(root);
return builder.build();
}
private Map<String, File> getReportFileHashesByUuid(Map<String, Component> reportFilesByUuid, Set<String> addedFileUuids) {
return addedFileUuids.stream().collect(Collectors.toMap(fileUuid -> fileUuid, fileUuid -> {
Component component = reportFilesByUuid.get(fileUuid);
return new LazyFileImpl(() -> getReportFileLineHashes(component), component.getFileAttributes().getLines());
}));
}
private List<String> getReportFileLineHashes(Component component) {
// this is not ideal because if the file moved, this component won't exist in DB with the same UUID.
// Assuming that the file also had significant code before the move, it will be fine.
return sourceLinesHash.getLineHashesMatchingDBVersion(component);
}
private ScoreMatrix computeScoreMatrix(Map<String, DbComponent> dtosByUuid, Set<String> removedFileUuids, Map<String, File> addedFileHashesByUuid) {
ScoreMatrix.ScoreFile[] addedFiles = addedFileHashesByUuid.entrySet().stream()
.map(e -> new ScoreMatrix.ScoreFile(e.getKey(), e.getValue().getLineCount()))
.toArray(ScoreMatrix.ScoreFile[]::new);
ScoreMatrix.ScoreFile[] removedFiles = removedFileUuids.stream()
.map(key -> {
DbComponent dbComponent = dtosByUuid.get(key);
return new ScoreMatrix.ScoreFile(dbComponent.uuid(), dbComponent.lineCount());
})
.toArray(ScoreMatrix.ScoreFile[]::new);
// sort by highest line count first
Arrays.sort(addedFiles, SCORE_FILE_COMPARATOR);
Arrays.sort(removedFiles, SCORE_FILE_COMPARATOR);
int[][] scoreMatrix = new int[removedFiles.length][addedFiles.length];
int smallestAddedFileSize = addedFiles[0].getLineCount();
int largestAddedFileSize = addedFiles[addedFiles.length - 1].getLineCount();
Map<String, Integer> removedFilesIndexesByUuid = new HashMap<>(removedFileUuids.size());
for (int removeFileIndex = 0; removeFileIndex < removedFiles.length; removeFileIndex++) {
ScoreMatrix.ScoreFile removedFile = removedFiles[removeFileIndex];
int lowerBound = (int) Math.floor(removedFile.getLineCount() * LOWER_BOUND_RATIO);
int upperBound = (int) Math.ceil(removedFile.getLineCount() * UPPER_BOUND_RATIO);
// no need to compute score if all files are out of bound, so no need to load line hashes from DB
if (smallestAddedFileSize <= lowerBound || largestAddedFileSize >= upperBound) {
continue;
}
removedFilesIndexesByUuid.put(removedFile.getFileUuid(), removeFileIndex);
}
LineHashesWithKeyDtoResultHandler rowHandler = new LineHashesWithKeyDtoResultHandler(removedFilesIndexesByUuid, removedFiles,
addedFiles, addedFileHashesByUuid, scoreMatrix);
try (DbSession dbSession = dbClient.openSession(false)) {
dbClient.fileSourceDao().scrollLineHashes(dbSession, removedFilesIndexesByUuid.keySet(), rowHandler);
}
return new ScoreMatrix(removedFiles, addedFiles, scoreMatrix, rowHandler.getMaxScore());
}
private final class LineHashesWithKeyDtoResultHandler implements ResultHandler<LineHashesWithUuidDto> {
private final Map<String, Integer> removedFileIndexesByUuid;
private final ScoreMatrix.ScoreFile[] removedFiles;
private final ScoreMatrix.ScoreFile[] newFiles;
private final Map<String, File> newFilesByUuid;
private final int[][] scoreMatrix;
private int maxScore;
private LineHashesWithKeyDtoResultHandler(Map<String, Integer> removedFileIndexesByUuid, ScoreMatrix.ScoreFile[] removedFiles,
ScoreMatrix.ScoreFile[] newFiles, Map<String, File> newFilesByUuid,
int[][] scoreMatrix) {
this.removedFileIndexesByUuid = removedFileIndexesByUuid;
this.removedFiles = removedFiles;
this.newFiles = newFiles;
this.newFilesByUuid = newFilesByUuid;
this.scoreMatrix = scoreMatrix;
}
@Override
public void handleResult(ResultContext<? extends LineHashesWithUuidDto> resultContext) {
LineHashesWithUuidDto lineHashesDto = resultContext.getResultObject();
if (lineHashesDto.getPath() == null) {
return;
}
int removedFileIndex = removedFileIndexesByUuid.get(lineHashesDto.getUuid());
ScoreMatrix.ScoreFile removedFile = removedFiles[removedFileIndex];
int lowerBound = (int) Math.floor(removedFile.getLineCount() * LOWER_BOUND_RATIO);
int upperBound = (int) Math.ceil(removedFile.getLineCount() * UPPER_BOUND_RATIO);
for (int newFileIndex = 0; newFileIndex < newFiles.length; newFileIndex++) {
ScoreMatrix.ScoreFile newFile = newFiles[newFileIndex];
if (newFile.getLineCount() >= upperBound) {
continue;
}
if (newFile.getLineCount() <= lowerBound) {
break;
}
File fileHashesInDb = new FileImpl(lineHashesDto.getLineHashes());
File unmatchedFile = newFilesByUuid.get(newFile.getFileUuid());
int score = fileSimilarity.score(fileHashesInDb, unmatchedFile);
scoreMatrix[removedFileIndex][newFileIndex] = score;
if (score > maxScore) {
maxScore = score;
}
}
}
int getMaxScore() {
return maxScore;
}
}
private static ElectedMatches electMatches(Set<String> dbFileUuids, Map<String, File> reportFileSourcesByUuid, MatchesByScore matchesByScore) {
ElectedMatches electedMatches = new ElectedMatches(matchesByScore, dbFileUuids, reportFileSourcesByUuid);
Multimap<String, Match> matchesPerFileForScore = ArrayListMultimap.create();
matchesByScore.forEach(matches -> electMatches(matches, electedMatches, matchesPerFileForScore));
return electedMatches;
}
private static void electMatches(@Nullable List<Match> matches, ElectedMatches electedMatches, Multimap<String, Match> matchesPerFileForScore) {
// no match for this score value, ignore
if (matches == null) {
return;
}
List<Match> matchesToValidate = electedMatches.filter(matches);
if (matchesToValidate.isEmpty()) {
return;
}
if (matchesToValidate.size() == 1) {
Match match = matchesToValidate.get(0);
electedMatches.add(match);
} else {
matchesPerFileForScore.clear();
for (Match match : matchesToValidate) {
matchesPerFileForScore.put(match.dbUuid(), match);
matchesPerFileForScore.put(match.reportUuid(), match);
}
// validate non-ambiguous matches (i.e. the match is the only match of either the db file and the report file)
for (Match match : matchesToValidate) {
int dbFileMatchesCount = matchesPerFileForScore.get(match.dbUuid()).size();
int reportFileMatchesCount = matchesPerFileForScore.get(match.reportUuid()).size();
if (dbFileMatchesCount == 1 && reportFileMatchesCount == 1) {
electedMatches.add(match);
}
}
}
}
private static MovedFilesRepository.OriginalFile toOriginalFile(DbComponent dbComponent) {
return new MovedFilesRepository.OriginalFile(dbComponent.uuid(), dbComponent.key());
}
public record DbComponent(String key, String uuid, String path, int lineCount) {
}
private static class ElectedMatches implements Iterable<Match> {
private final List<Match> matches;
private final Set<String> matchedFileUuids;
public ElectedMatches(MatchesByScore matchesByScore, Set<String> dbFileUuids, Map<String, File> reportFileHashesByUuid) {
this.matches = new ArrayList<>(matchesByScore.getSize());
this.matchedFileUuids = new HashSet<>(dbFileUuids.size() + reportFileHashesByUuid.size());
}
public void add(Match match) {
matches.add(match);
matchedFileUuids.add(match.dbUuid());
matchedFileUuids.add(match.reportUuid());
}
public List<Match> filter(Collection<Match> matches) {
return matches.stream().filter(this::notAlreadyMatched).toList();
}
private boolean notAlreadyMatched(Match input) {
return !(matchedFileUuids.contains(input.dbUuid()) || matchedFileUuids.contains(input.reportUuid()));
}
@Override
public Iterator<Match> iterator() {
return matches.iterator();
}
public int size() {
return matches.size();
}
public boolean isEmpty() {
return matches.isEmpty();
}
}
}
| 17,981 | 42.539952 | 152 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/filemove/FileSimilarity.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.filemove;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import static java.util.Collections.emptyList;
import static java.util.Objects.requireNonNull;
public interface FileSimilarity {
interface File {
List<String> getLineHashes();
int getLineCount();
}
final class FileImpl implements File {
private final List<String> lineHashes;
private final int lineCount;
FileImpl(List<String> lineHashes) {
this.lineHashes = requireNonNull(lineHashes, "lineHashes can not be null");
this.lineCount = lineHashes.size();
}
/**
* List of hash of each line. An empty list is returned
* if file content is empty.
*/
public List<String> getLineHashes() {
return lineHashes;
}
public int getLineCount() {
return lineCount;
}
}
final class LazyFileImpl implements File {
private final Supplier<List<String>> supplier;
private final int lineCount;
private List<String> lineHashes;
LazyFileImpl(Supplier<List<String>> supplier, int lineCount) {
this.supplier = requireNonNull(supplier, "supplier can not be null");
this.lineCount = lineCount;
}
/**
* List of hash of each line. An empty list is returned
* if file content is empty.
*/
public List<String> getLineHashes() {
ensureSupplierCalled();
return lineHashes;
}
private void ensureSupplierCalled() {
if (lineHashes == null) {
lineHashes = Optional.ofNullable(supplier.get()).orElse(emptyList());
}
}
public int getLineCount() {
return lineCount;
}
}
int score(File file1, File file2);
}
| 2,573 | 27.285714 | 81 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/filemove/FileSimilarityImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.filemove;
public class FileSimilarityImpl implements FileSimilarity {
private final SourceSimilarity sourceSimilarity;
public FileSimilarityImpl(SourceSimilarity sourceSimilarity) {
this.sourceSimilarity = sourceSimilarity;
}
@Override
public int score(File file1, File file2) {
// Algorithm could be improved by increasing score
// depending on filename similarity
// Current implementation relies on file content only.
return sourceSimilarity.score(file1.getLineHashes(), file2.getLineHashes());
}
}
| 1,424 | 35.538462 | 80 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/filemove/Match.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.filemove;
record Match(String dbUuid, String reportUuid) {
@Override
public String toString() {
return '{' + dbUuid + "=>" + reportUuid + '}';
}
}
| 1,043 | 36.285714 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/filemove/MatchesByScore.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.filemove;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import static org.sonar.ce.task.projectanalysis.filemove.FileMoveDetectionStep.MIN_REQUIRED_SCORE;
abstract class MatchesByScore implements Iterable<List<Match>> {
public static MatchesByScore create(ScoreMatrix scoreMatrix) {
if (scoreMatrix.getMaxScore() < MIN_REQUIRED_SCORE) {
return EmptyMatchesByScore.INSTANCE;
}
MatchesByScoreImpl res = new MatchesByScoreImpl(scoreMatrix);
res.populate();
return res;
}
public abstract int getSize();
private static final class MatchesByScoreImpl extends MatchesByScore implements ScoreMatrix.ScoreMatrixVisitor {
private final ScoreMatrix scoreMatrix;
private final List<Match>[] matches;
private int totalMatches = 0;
private MatchesByScoreImpl(ScoreMatrix scoreMatrix) {
this.scoreMatrix = scoreMatrix;
this.matches = new List[scoreMatrix.getMaxScore() - MIN_REQUIRED_SCORE + 1];
}
private void populate() {
scoreMatrix.accept(this);
}
@Override
public void visit(ScoreMatrix.ScoreFile removedFile, ScoreMatrix.ScoreFile newFile, int score) {
if (!isAcceptableScore(score)) {
return;
}
// Store higher score first so that iterator get higher score first
int index = scoreMatrix.getMaxScore() - score;
if (matches[index] == null) {
matches[index] = new ArrayList<>(1);
}
Match match = new Match(removedFile.getFileUuid(), newFile.getFileUuid());
matches[index].add(match);
totalMatches++;
}
private static boolean isAcceptableScore(int score) {
return score >= MIN_REQUIRED_SCORE;
}
@Override
public int getSize() {
return totalMatches;
}
@Override
public Iterator<List<Match>> iterator() {
return Arrays.asList(matches).iterator();
}
}
private static class EmptyMatchesByScore extends MatchesByScore {
private static final EmptyMatchesByScore INSTANCE = new EmptyMatchesByScore();
@Override
public int getSize() {
return 0;
}
@Override
public Iterator<List<Match>> iterator() {
return Collections.<List<Match>>emptyList().iterator();
}
}
}
| 3,187 | 30.254902 | 114 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/filemove/MovedFilesRepository.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.filemove;
import java.util.Optional;
import javax.annotation.Nullable;
import org.sonar.ce.task.projectanalysis.component.Component;
import static java.util.Objects.requireNonNull;
public interface MovedFilesRepository {
/**
* The original file for the specified component if it was registered as a moved file in the repository.
* <p>
* Calling this method with a Component which is not a file, will always return {@link Optional#empty()}.
* </p>
*/
Optional<OriginalFile> getOriginalFile(Component file);
/**
* The original file for the specified component if it was registered as a moved file inside the scope of a Pull Request.
* <p>
* Calling this method with a Component which is not a file, will always return {@link Optional#empty()}.
* </p>
*/
Optional<OriginalFile> getOriginalPullRequestFile(Component file);
record OriginalFile(String uuid, String key) {
public OriginalFile(String uuid, String key) {
this.uuid = requireNonNull(uuid, "uuid can not be null");
this.key = requireNonNull(key, "key can not be null");
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
OriginalFile that = (OriginalFile) o;
return uuid.equals(that.uuid);
}
@Override
public int hashCode() {
return uuid.hashCode();
}
@Override
public String toString() {
return "OriginalFile{" +
"uuid='" + uuid + '\'' +
", key='" + key + '\'' +
'}';
}
}
}
| 2,510 | 31.61039 | 123 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/filemove/MutableAddedFileRepository.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.filemove;
import org.sonar.ce.task.projectanalysis.component.Component;
public interface MutableAddedFileRepository extends AddedFileRepository {
/**
* @throws IllegalArgumentException if the specified component is not a {@link Component.Type#FILE File}
* @throws IllegalStateException on first analysis as all components are added on first analysis, none should be
* registered for performance reasons.
*/
void register(Component file);
}
| 1,352 | 40 | 114 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/filemove/MutableMovedFilesRepository.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.filemove;
import org.sonar.ce.task.projectanalysis.component.Component;
public interface MutableMovedFilesRepository extends MovedFilesRepository {
/**
* Registers the original file for the specified file of the report.
*
* @throws IllegalArgumentException if {@code file} type is not {@link Component.Type#FILE}
* @throws IllegalStateException if {@code file} already has an original file
*/
void setOriginalFile(Component file, OriginalFile originalFile);
/**
* Registers the original file for the specified file that has been renamed/moved inside the scope of a Pull Request.
*
* @throws IllegalArgumentException if {@code file} type is not {@link Component.Type#FILE}
* @throws IllegalStateException if {@code file} already has an original file
*/
void setOriginalPullRequestFile(Component file, OriginalFile originalFile);
}
| 1,756 | 41.853659 | 119 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/filemove/MutableMovedFilesRepositoryImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.filemove;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.sonar.ce.task.projectanalysis.component.Component;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
public class MutableMovedFilesRepositoryImpl implements MutableMovedFilesRepository {
private final Map<String, OriginalFile> originalFiles = new HashMap<>();
private final Map<String, OriginalFile> originalPullRequestFiles = new HashMap<>();
@Override
public void setOriginalFile(Component file, OriginalFile originalFile) {
storeOriginalFileInCache(originalFiles, file, originalFile);
}
@Override
public void setOriginalPullRequestFile(Component file, OriginalFile originalFile) {
storeOriginalFileInCache(originalPullRequestFiles, file, originalFile);
}
@Override
public Optional<OriginalFile> getOriginalFile(Component file) {
return retrieveOriginalFileFromCache(originalFiles, file);
}
@Override
public Optional<OriginalFile> getOriginalPullRequestFile(Component file) {
return retrieveOriginalFileFromCache(originalPullRequestFiles, file);
}
private static void storeOriginalFileInCache(Map<String, OriginalFile> originalFiles, Component file, OriginalFile originalFile) {
requireNonNull(file, "file can't be null");
requireNonNull(originalFile, "originalFile can't be null");
checkArgument(file.getType() == Component.Type.FILE, "file must be of type FILE");
OriginalFile existingOriginalFile = originalFiles.get(file.getKey());
checkState(existingOriginalFile == null || existingOriginalFile.equals(originalFile),
"Original file %s already registered for file %s. Unable to register %s.", existingOriginalFile, file, originalFile);
if (existingOriginalFile == null) {
originalFiles.put(file.getKey(), originalFile);
}
}
private static Optional<OriginalFile> retrieveOriginalFileFromCache(Map<String, OriginalFile> originalFiles, Component file) {
requireNonNull(file, "file can't be null");
if (file.getType() != Component.Type.FILE) {
return Optional.empty();
}
return Optional.ofNullable(originalFiles.get(file.getKey()));
}
}
| 3,175 | 38.7 | 132 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/filemove/PullRequestFileMoveDetectionStep.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.filemove;
import com.google.common.collect.ImmutableMap;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import org.apache.ibatis.session.ResultHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.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.filemove.FileMoveDetectionStep.DbComponent;
import org.sonar.ce.task.projectanalysis.filemove.MovedFilesRepository.OriginalFile;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.FileMoveRowDto;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toMap;
import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.POST_ORDER;
public class PullRequestFileMoveDetectionStep implements ComputationStep {
private static final Logger LOG = LoggerFactory.getLogger(PullRequestFileMoveDetectionStep.class);
private final AnalysisMetadataHolder analysisMetadataHolder;
private final TreeRootHolder rootHolder;
private final DbClient dbClient;
private final MutableMovedFilesRepository movedFilesRepository;
private final MutableAddedFileRepository addedFileRepository;
public PullRequestFileMoveDetectionStep(AnalysisMetadataHolder analysisMetadataHolder, TreeRootHolder rootHolder, DbClient dbClient,
MutableMovedFilesRepository movedFilesRepository, MutableAddedFileRepository addedFileRepository) {
this.analysisMetadataHolder = analysisMetadataHolder;
this.rootHolder = rootHolder;
this.dbClient = dbClient;
this.movedFilesRepository = movedFilesRepository;
this.addedFileRepository = addedFileRepository;
}
@Override
public String getDescription() {
return "Detect file moves in Pull Request scope";
}
@Override
public void execute(ComputationStep.Context context) {
if (!analysisMetadataHolder.isPullRequest()) {
LOG.debug("Currently not within Pull Request scope. Do nothing.");
return;
}
Map<String, Component> reportFilesByUuid = getReportFilesByUuid(this.rootHolder.getRoot());
context.getStatistics().add("reportFiles", reportFilesByUuid.size());
if (reportFilesByUuid.isEmpty()) {
LOG.debug("No files in report. No file move detection.");
return;
}
Map<String, DbComponent> targetBranchDbFilesByUuid = getTargetBranchDbFilesByUuid(analysisMetadataHolder);
context.getStatistics().add("dbFiles", targetBranchDbFilesByUuid.size());
if (targetBranchDbFilesByUuid.isEmpty()) {
registerNewlyAddedFiles(reportFilesByUuid);
context.getStatistics().add("addedFiles", reportFilesByUuid.size());
LOG.debug("Target branch has no files. No file move detection.");
return;
}
Collection<Component> movedFiles = getMovedFilesByUuid(reportFilesByUuid);
context.getStatistics().add("movedFiles", movedFiles.size());
Map<String, Component> newlyAddedFilesByUuid = getNewlyAddedFilesByUuid(reportFilesByUuid, targetBranchDbFilesByUuid);
context.getStatistics().add("addedFiles", newlyAddedFilesByUuid.size());
Map<String, DbComponent> dbFilesByPathReference = toDbFilesByPathReferenceMap(targetBranchDbFilesByUuid.values());
registerMovedFiles(movedFiles, dbFilesByPathReference);
registerNewlyAddedFiles(newlyAddedFilesByUuid);
}
private void registerMovedFiles(Collection<Component> movedFiles, Map<String, DbComponent> dbFilesByPathReference) {
movedFiles
.forEach(movedFile -> registerMovedFile(dbFilesByPathReference, movedFile));
}
private void registerMovedFile(Map<String, DbComponent> dbFiles, Component movedFile) {
retrieveDbFile(dbFiles, movedFile)
.ifPresent(dbFile -> movedFilesRepository.setOriginalPullRequestFile(movedFile, toOriginalFile(dbFile)));
}
private void registerNewlyAddedFiles(Map<String, Component> newAddedFilesByUuid) {
newAddedFilesByUuid
.values()
.forEach(addedFileRepository::register);
}
private static Map<String, Component> getNewlyAddedFilesByUuid(Map<String, Component> reportFilesByUuid, Map<String, DbComponent> dbFilesByUuid) {
return reportFilesByUuid
.values()
.stream()
.filter(file -> Objects.isNull(file.getFileAttributes().getOldRelativePath()))
.filter(file -> !dbFilesByUuid.containsKey(file.getUuid()))
.collect(toMap(Component::getUuid, identity()));
}
private static Collection<Component> getMovedFilesByUuid(Map<String, Component> reportFilesByUuid) {
return reportFilesByUuid
.values()
.stream()
.filter(file -> Objects.nonNull(file.getFileAttributes().getOldRelativePath()))
.toList();
}
private static Optional<DbComponent> retrieveDbFile(Map<String, DbComponent> dbFilesByPathReference, Component file) {
return Optional.ofNullable(dbFilesByPathReference.get(file.getFileAttributes().getOldRelativePath()));
}
private Map<String, DbComponent> getTargetBranchDbFilesByUuid(AnalysisMetadataHolder analysisMetadataHolder) {
try (DbSession dbSession = dbClient.openSession(false)) {
return getTargetBranchUuid(dbSession, analysisMetadataHolder.getProject().getUuid(), analysisMetadataHolder.getBranch().getTargetBranchName())
.map(targetBranchUUid -> getTargetBranchDbFilesByUuid(dbSession, targetBranchUUid))
.orElse(Map.of());
}
}
private Map<String, DbComponent> getTargetBranchDbFilesByUuid(DbSession dbSession, String targetBranchUuid) {
Map<String, DbComponent> files = new HashMap<>();
dbClient.componentDao().scrollAllFilesForFileMove(dbSession, targetBranchUuid, accumulateFilesForFileMove(files));
return files;
}
private static ResultHandler<FileMoveRowDto> accumulateFilesForFileMove(Map<String, DbComponent> accumulator) {
return resultContext -> {
DbComponent component = rowToDbComponent(resultContext.getResultObject());
accumulator.put(component.uuid(), component);
};
}
private static DbComponent rowToDbComponent(FileMoveRowDto row) {
return new DbComponent(row.getKey(), row.getUuid(), row.getPath(), row.getLineCount());
}
private Optional<String> getTargetBranchUuid(DbSession dbSession, String projectUuid, String targetBranchName) {
return dbClient.branchDao().selectByBranchKey(dbSession, projectUuid, targetBranchName)
.map(BranchDto::getUuid);
}
private static Map<String, DbComponent> toDbFilesByPathReferenceMap(Collection<DbComponent> dbFiles) {
return dbFiles
.stream()
.collect(toMap(DbComponent::path, identity()));
}
private static Map<String, Component> getReportFilesByUuid(Component root) {
final ImmutableMap.Builder<String, Component> builder = ImmutableMap.builder();
new DepthTraversalTypeAwareCrawler(
new TypeAwareVisitorAdapter(CrawlerDepthLimit.FILE, POST_ORDER) {
@Override
public void visitFile(Component file) {
builder.put(file.getUuid(), file);
}
}).visit(root);
return builder.build();
}
private static OriginalFile toOriginalFile(DbComponent dbComponent) {
return new OriginalFile(dbComponent.uuid(), dbComponent.key());
}
}
| 8,575 | 41.88 | 148 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/filemove/ScoreMatrix.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.filemove;
import java.util.Arrays;
final class ScoreMatrix {
private final ScoreFile[] removedFiles;
private final ScoreFile[] newFiles;
private final int[][] scores;
private final int maxScore;
public ScoreMatrix(ScoreFile[] removedFiles, ScoreFile[] newFiles, int[][] scores, int maxScore) {
this.removedFiles = removedFiles;
this.newFiles = newFiles;
this.scores = scores;
this.maxScore = maxScore;
}
public void accept(ScoreMatrixVisitor visitor) {
for (int removedFileIndex = 0; removedFileIndex < removedFiles.length; removedFileIndex++) {
for (int newFileIndex = 0; newFileIndex < newFiles.length; newFileIndex++) {
int score = scores[removedFileIndex][newFileIndex];
visitor.visit(removedFiles[removedFileIndex], newFiles[newFileIndex], score);
}
}
}
public String toCsv(char separator) {
StringBuilder res = new StringBuilder();
// first row: empty column, then one column for each report file (its uuid)
res.append("newFiles=>").append(separator);
Arrays.stream(newFiles).forEach(f -> res.append(f.getFileUuid()).append('(').append(f.getLineCount()).append(')').append(separator));
// rows with data: column with db file (its uuid), then one column for each value
accept(new ScoreMatrixVisitor() {
private ScoreFile previousRemovedFile = null;
@Override
public void visit(ScoreFile removedFile, ScoreFile newFile, int score) {
if (previousRemovedFile != removedFile) {
res.append('\n').append(removedFile.getFileUuid()).append('(').append(removedFile.getLineCount()).append(')').append(separator);
previousRemovedFile = removedFile;
}
res.append(score).append(separator);
}
});
return res.toString();
}
@FunctionalInterface
public interface ScoreMatrixVisitor {
void visit(ScoreFile removedFile, ScoreFile newFile, int score);
}
public int getMaxScore() {
return maxScore;
}
static class ScoreFile {
private final String fileUuid;
private final int lineCount;
ScoreFile(String fileUuid, int lineCount) {
this.fileUuid = fileUuid;
this.lineCount = lineCount;
}
public String getFileUuid() {
return fileUuid;
}
public int getLineCount() {
return lineCount;
}
}
}
| 3,219 | 32.894737 | 138 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/filemove/ScoreMatrixDumper.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.filemove;
public interface ScoreMatrixDumper {
void dumpAsCsv(ScoreMatrix scoreMatrix);
}
| 978 | 38.16 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/filemove/ScoreMatrixDumperImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.filemove;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.sonar.api.config.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.ce.task.CeTask;
import org.sonar.server.platform.ServerFileSystem;
import static java.nio.charset.StandardCharsets.UTF_8;
public class ScoreMatrixDumperImpl implements ScoreMatrixDumper {
private static final Logger LOG = LoggerFactory.getLogger(ScoreMatrixDumperImpl.class);
private final Configuration configuration;
private final CeTask ceTask;
private final ServerFileSystem fs;
public ScoreMatrixDumperImpl(Configuration configuration, CeTask ceTask, ServerFileSystem fs) {
this.configuration = configuration;
this.ceTask = ceTask;
this.fs = fs;
}
@Override
public void dumpAsCsv(ScoreMatrix scoreMatrix) {
if (configuration.getBoolean("sonar.filemove.dumpCsv").orElse(false)) {
try {
Path tempFile = fs.getTempDir().toPath()
.resolve(String.format("score-matrix-%s.csv", ceTask.getUuid()));
try (BufferedWriter writer = Files.newBufferedWriter(tempFile, UTF_8)) {
writer.write(scoreMatrix.toCsv(';'));
}
LOG.info("File move similarity score matrix dumped as CSV: {}", tempFile);
} catch (IOException e) {
LOG.error("Failed to dump ScoreMatrix as CSV", e);
}
}
}
}
| 2,318 | 35.809524 | 97 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/filemove/SourceSimilarity.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.filemove;
import java.util.List;
public interface SourceSimilarity {
/**
* the higher the more similar. Order is not important (TODO to be verified). 100% = same source.
* Range: between 0 and 100
*/
<T extends Object> int score(List<T> left, List<T> right);
}
| 1,162 | 35.34375 | 99 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/filemove/SourceSimilarityImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.filemove;
import java.util.List;
import static java.lang.Math.max;
import static java.lang.Math.min;
public class SourceSimilarityImpl implements SourceSimilarity {
@Override
public <T> int score(List<T> left, List<T> right) {
if (left.isEmpty() && right.isEmpty()) {
return 0;
}
int distance = levenshteinDistance(left, right);
return (int) (100 * (1.0 - ((double) distance) / (max(left.size(), right.size()))));
}
private static <T> int levenshteinDistance(List<T> left, List<T> right) {
int len0 = left.size() + 1;
int len1 = right.size() + 1;
// the array of distances
int[] cost = new int[len0];
int[] newcost = new int[len0];
// initial cost of skipping prefix in String s0
for (int i = 0; i < len0; i++) {
cost[i] = i;
}
// dynamically computing the array of distances
// transformation cost for each letter in s1
for (int j = 1; j < len1; j++) {
// initial cost of skipping prefix in String s1
newcost[0] = j;
// transformation cost for each letter in s0
for (int i = 1; i < len0; i++) {
// matching current letters in both strings
int match = left.get(i - 1).equals(right.get(j - 1)) ? 0 : 1;
// computing cost for each transformation
int costReplace = cost[i - 1] + match;
int costInsert = cost[i] + 1;
int costDelete = newcost[i - 1] + 1;
// keep minimum cost
newcost[i] = min(min(costInsert, costDelete), costReplace);
}
// swap cost/newcost arrays
int[] swap = cost;
cost = newcost;
newcost = swap;
}
// the distance is the cost for transforming all letters in both strings
return cost[len0 - 1];
}
}
| 2,625 | 31.02439 | 88 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/filemove/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.filemove;
import javax.annotation.ParametersAreNonnullByDefault;
| 983 | 38.36 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/filesystem/ComputationTempFolderProvider.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.filesystem;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.sonar.api.impl.utils.DefaultTempFolder;
import org.sonar.api.utils.TempFolder;
import org.sonar.server.platform.ServerFileSystem;
import org.springframework.context.annotation.Bean;
/**
* Provides a TempFolder instance pointing to a directory dedicated to the processing of a specific item.
* This directory will be deleted at the end of the processing.
* This directory is located in the "ce" directory of the temp directory of the SonarQube instance.
*/
public class ComputationTempFolderProvider {
@Bean("ComputationTempFolder")
public TempFolder provide(ServerFileSystem fs) {
File tempDir = new File(fs.getTempDir(), "ce");
try {
FileUtils.forceMkdir(tempDir);
} catch (IOException e) {
throw new IllegalStateException("Unable to create computation temp directory " + tempDir, e);
}
File computationDir = new DefaultTempFolder(tempDir).newDir();
return new DefaultTempFolder(computationDir, true);
}
}
| 1,952 | 39.6875 | 105 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/filesystem/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.filesystem;
import javax.annotation.ParametersAreNonnullByDefault;
| 984 | 40.041667 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/formula/AverageFormula.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.formula;
import java.util.Optional;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import static java.util.Objects.requireNonNull;
public class AverageFormula implements Formula<AverageFormula.AverageCounter> {
private final String outputMetricKey;
private final String mainMetric;
private final String byMetric;
private AverageFormula(Builder builder) {
this.outputMetricKey = builder.outputMetricKey;
this.mainMetric = builder.mainMetric;
this.byMetric = builder.byMetric;
}
@Override
public AverageCounter createNewCounter() {
return new AverageCounter();
}
@Override
public Optional<Measure> createMeasure(AverageCounter counter, CreateMeasureContext context) {
Optional<Double> mainValueOptional = counter.getMainValue();
Optional<Double> byValueOptional = counter.getByValue();
if (mainValueOptional.isPresent() && byValueOptional.isPresent()) {
double mainValue = mainValueOptional.get();
double byValue = byValueOptional.get();
if (byValue > 0D) {
return Optional.of(Measure.newMeasureBuilder().create(mainValue / byValue, context.getMetric().getDecimalScale()));
}
}
return Optional.empty();
}
@Override
public String[] getOutputMetricKeys() {
return new String[] {outputMetricKey};
}
public static class Builder {
private String outputMetricKey;
private String mainMetric;
private String byMetric;
private Builder() {
// prevents instantiation outside static method
}
public static Builder newBuilder() {
return new Builder();
}
public Builder setOutputMetricKey(String m) {
this.outputMetricKey = m;
return this;
}
public Builder setMainMetricKey(String m) {
this.mainMetric = m;
return this;
}
public Builder setByMetricKey(String m) {
this.byMetric = m;
return this;
}
public AverageFormula build() {
requireNonNull(outputMetricKey, "Output metric key cannot be null");
requireNonNull(mainMetric, "Main metric Key cannot be null");
requireNonNull(byMetric, "By metric Key cannot be null");
return new AverageFormula(this);
}
}
class AverageCounter implements Counter<AverageCounter> {
private boolean initialized = false;
private double mainValue = 0D;
private double byValue = 0D;
@Override
public void aggregate(AverageCounter counter) {
addValuesIfPresent(counter.getMainValue(), counter.getByValue());
}
@Override
public void initialize(CounterInitializationContext context) {
Optional<Double> mainValueOptional = getDoubleValue(context.getMeasure(mainMetric));
Optional<Double> byValueOptional = getDoubleValue(context.getMeasure(byMetric));
addValuesIfPresent(mainValueOptional, byValueOptional);
}
private void addValuesIfPresent(Optional<Double> counterMainValue, Optional<Double> counterByValue) {
if (counterMainValue.isPresent() && counterByValue.isPresent()) {
initialized = true;
mainValue += counterMainValue.get();
byValue += counterByValue.get();
}
}
public Optional<Double> getMainValue() {
return getValue(mainValue);
}
public Optional<Double> getByValue() {
return getValue(byValue);
}
private Optional<Double> getValue(double value) {
if (initialized) {
return Optional.of(value);
}
return Optional.empty();
}
private Optional<Double> getDoubleValue(Optional<Measure> measureOptional) {
if (!measureOptional.isPresent()) {
return Optional.empty();
}
Measure measure = measureOptional.get();
switch (measure.getValueType()) {
case DOUBLE:
return Optional.of(measure.getDoubleValue());
case LONG:
return Optional.of((double) measure.getLongValue());
case INT:
return Optional.of((double) measure.getIntValue());
case NO_VALUE:
return Optional.empty();
default:
throw new IllegalArgumentException(String.format("Measure of type '%s' are not supported", measure.getValueType().name()));
}
}
}
}
| 5,088 | 30.41358 | 133 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/formula/Counter.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.formula;
import org.sonar.ce.task.projectanalysis.component.Component;
/**
* A counter is used to aggregate some data
*/
public interface Counter<T extends Counter<T>> {
/**
* This method is used on not leaf levels, to aggregate the value of the specified counter of a child to the counter
* of the current component.
*/
void aggregate(T counter);
/**
* This method is called on leaves of the Component tree (usually a {@link Component.Type#FILE} or a {@link Component.Type#PROJECT_VIEW}
* but can also be a {@link Component.Type#SUBVIEW} or {@link Component.Type#VIEW}) to initialize the counter.
*/
void initialize(CounterInitializationContext context);
}
| 1,576 | 36.547619 | 138 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/formula/CounterInitializationContext.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.formula;
import java.util.Optional;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.measure.Measure;
/**
* The context passing information to {@link Counter#initialize(CounterInitializationContext)}.
*/
public interface CounterInitializationContext {
/**
* The Component representing the currently processed leaf.
*/
Component getLeaf();
/**
* Retrieve the measure for the current component for the specified metric key if it exists.
*/
Optional<Measure> getMeasure(String metricKey);
}
| 1,454 | 33.642857 | 95 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/formula/CreateMeasureContext.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.formula;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.metric.Metric;
/**
* Context passing information to implementation of {@link Formula#createMeasure(Counter, CreateMeasureContext)} method.
*/
public interface CreateMeasureContext {
/**
* The component for which the measure is to be created.
*/
Component getComponent();
/**
* The Metric for which the measure is to be created.
*/
Metric getMetric();
}
| 1,376 | 33.425 | 120 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/formula/DistributionFormula.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.formula;
import java.util.Optional;
import org.sonar.api.ce.measure.RangeDistributionBuilder;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import static java.util.Objects.requireNonNull;
public class DistributionFormula implements Formula<DistributionFormula.DistributionCounter> {
private final String metricKey;
public DistributionFormula(String metricKey) {
this.metricKey = requireNonNull(metricKey, "Metric key cannot be null");
}
@Override
public DistributionCounter createNewCounter() {
return new DistributionCounter();
}
@Override
public Optional<Measure> createMeasure(DistributionCounter counter, CreateMeasureContext context) {
Component.Type componentType = context.getComponent().getType();
Optional<String> value = counter.getValue();
if (value.isPresent() && CrawlerDepthLimit.LEAVES.isDeeperThan(componentType)) {
return Optional.of(Measure.newMeasureBuilder().create(value.get()));
}
return Optional.empty();
}
@Override
public String[] getOutputMetricKeys() {
return new String[] {metricKey};
}
class DistributionCounter implements Counter<DistributionCounter> {
private final RangeDistributionBuilder distribution = new RangeDistributionBuilder();
private boolean initialized = false;
@Override
public void aggregate(DistributionCounter counter) {
Optional<String> value = counter.getValue();
if (value.isPresent()) {
initialized = true;
distribution.add(value.get());
}
}
@Override
public void initialize(CounterInitializationContext context) {
Optional<Measure> measureOptional = context.getMeasure(metricKey);
String data = measureOptional.isPresent() ? measureOptional.get().getData() : null;
if (data != null) {
initialized = true;
distribution.add(data);
}
}
public Optional<String> getValue() {
if (initialized) {
return Optional.ofNullable(distribution.build());
}
return Optional.empty();
}
}
}
| 3,073 | 33.155556 | 101 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/formula/Formula.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.formula;
import java.util.Optional;
import org.sonar.ce.task.projectanalysis.measure.Measure;
/**
* A formula is used to aggregated data on all nodes of a component tree
*/
public interface Formula<T extends Counter> {
/**
* Method responsible for creating an new instance of a the counter used by this formula.
*/
T createNewCounter();
/**
* This method is used to create a measure on each node, using the value of the counter
* If {@link Optional#empty()} is returned, no measure will be created
*
* @param context the context for which the measure must be created
*/
Optional<Measure> createMeasure(T counter, CreateMeasureContext context);
/**
* The metric associated to the measure
*/
String[] getOutputMetricKeys();
}
| 1,656 | 32.816327 | 91 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/formula/FormulaExecutorComponentVisitor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.formula;
import com.google.common.collect.ImmutableList;
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.component.Component;
import org.sonar.ce.task.projectanalysis.component.ComponentVisitor;
import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit;
import org.sonar.ce.task.projectanalysis.component.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 static java.util.Objects.requireNonNull;
public class FormulaExecutorComponentVisitor extends PathAwareVisitorAdapter<FormulaExecutorComponentVisitor.Counters> {
private static final SimpleStackElementFactory<Counters> COUNTERS_FACTORY = new SimpleStackElementFactory<Counters>() {
@Override
public Counters createForAny(Component component) {
return new Counters();
}
@Override
public Counters createForFile(Component component) {
// No need to create a counter on leaf levels
return null;
}
@Override
public Counters createForProjectView(Component projectView) {
// No need to create a counter on leaf levels
return null;
}
};
private final MetricRepository metricRepository;
private final MeasureRepository measureRepository;
private final List<Formula<?>> formulas;
private FormulaExecutorComponentVisitor(Builder builder, Iterable<Formula<?>> formulas) {
super(CrawlerDepthLimit.LEAVES, ComponentVisitor.Order.POST_ORDER, COUNTERS_FACTORY);
this.measureRepository = builder.measureRepository;
this.metricRepository = builder.metricRepository;
this.formulas = ImmutableList.copyOf(formulas);
}
public static Builder newBuilder(MetricRepository metricRepository, MeasureRepository measureRepository) {
return new Builder(metricRepository, measureRepository);
}
public static class Builder {
private final MetricRepository metricRepository;
private final MeasureRepository measureRepository;
private Builder(MetricRepository metricRepository, MeasureRepository measureRepository) {
this.metricRepository = requireNonNull(metricRepository);
this.measureRepository = requireNonNull(measureRepository);
}
public Builder create(MetricRepository metricRepository, MeasureRepository measureRepository) {
return new Builder(metricRepository, measureRepository);
}
public FormulaExecutorComponentVisitor buildFor(Iterable<Formula<?>> formulas) {
return new FormulaExecutorComponentVisitor(this, formulas);
}
}
@Override
public void visitProject(Component project, Path<FormulaExecutorComponentVisitor.Counters> path) {
process(project, path);
}
@Override
public void visitDirectory(Component directory, Path<FormulaExecutorComponentVisitor.Counters> path) {
process(directory, path);
}
@Override
public void visitFile(Component file, Path<FormulaExecutorComponentVisitor.Counters> path) {
process(file, path);
}
@Override
public void visitView(Component view, Path<Counters> path) {
process(view, path);
}
@Override
public void visitSubView(Component subView, Path<Counters> path) {
process(subView, path);
}
@Override
public void visitProjectView(Component projectView, Path<Counters> path) {
process(projectView, path);
}
private void process(Component component, Path<FormulaExecutorComponentVisitor.Counters> path) {
if (component.getChildren().isEmpty()) {
processLeaf(component, path);
} else {
processNotLeaf(component, path);
}
}
private void processNotLeaf(Component component, Path<FormulaExecutorComponentVisitor.Counters> path) {
for (Formula formula : formulas) {
Counter counter = path.current().getCounter(formula);
// If there were no file under this node, the counter won't be initialized
if (counter != null) {
for (String metricKey : formula.getOutputMetricKeys()) {
addNewMeasure(component, metricKey, formula, counter);
}
aggregateToParent(path, formula, counter);
}
}
}
private void processLeaf(Component component, Path<FormulaExecutorComponentVisitor.Counters> path) {
CounterInitializationContext counterContext = new CounterInitializationContextImpl(component);
for (Formula formula : formulas) {
Counter counter = formula.createNewCounter();
counter.initialize(counterContext);
for (String metricKey : formula.getOutputMetricKeys()) {
addNewMeasure(component, metricKey, formula, counter);
}
aggregateToParent(path, formula, counter);
}
}
private void addNewMeasure(Component component, String metricKey, Formula formula, Counter counter) {
// no new measure can be created by formulas for PROJECT_VIEW components, their measures are the copy
if (component.getType() == Component.Type.PROJECT_VIEW) {
return;
}
Metric metric = metricRepository.getByKey(metricKey);
Optional<Measure> measure = formula.createMeasure(counter, new CreateMeasureContextImpl(component, metric));
if (measure.isPresent()) {
measureRepository.add(component, metric, measure.get());
}
}
private static void aggregateToParent(Path<FormulaExecutorComponentVisitor.Counters> path, Formula formula, Counter currentCounter) {
if (!path.isRoot()) {
path.parent().aggregate(formula, currentCounter);
}
}
private class CounterInitializationContextImpl implements CounterInitializationContext {
private final Component component;
public CounterInitializationContextImpl(Component component) {
this.component = component;
}
@Override
public Component getLeaf() {
return component;
}
@Override
public Optional<Measure> getMeasure(String metricKey) {
return measureRepository.getRawMeasure(component, metricRepository.getByKey(metricKey));
}
}
public static class Counters {
Map<Formula, Counter> countersByFormula = new HashMap<>();
public void aggregate(Formula formula, Counter childCounter) {
Counter counter = countersByFormula.get(formula);
if (counter == null) {
countersByFormula.put(formula, childCounter);
} else {
counter.aggregate(childCounter);
}
}
/**
* Counter can be null on a level when it has not been fed by children levels
*/
@CheckForNull
public Counter getCounter(Formula formula) {
return countersByFormula.get(formula);
}
}
private static class CreateMeasureContextImpl implements CreateMeasureContext {
private final Component component;
private final Metric metric;
public CreateMeasureContextImpl(Component component, Metric metric) {
this.component = component;
this.metric = metric;
}
@Override
public Component getComponent() {
return component;
}
@Override
public Metric getMetric() {
return metric;
}
}
}
| 8,120 | 33.557447 | 135 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/formula/SumFormula.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.formula;
import java.util.Optional;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit;
import org.sonar.ce.task.projectanalysis.formula.counter.IntSumCounter;
import org.sonar.ce.task.projectanalysis.formula.counter.LongSumCounter;
import org.sonar.ce.task.projectanalysis.formula.counter.SumCounter;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import static java.util.Objects.requireNonNull;
public abstract class SumFormula<T extends SumCounter<U, T>, U extends Number> implements Formula<T> {
protected final String metricKey;
@CheckForNull
protected final U defaultInputValue;
public SumFormula(String metricKey, @Nullable U defaultInputValue) {
this.metricKey = requireNonNull(metricKey, "Metric key cannot be null");
this.defaultInputValue = defaultInputValue;
}
public static IntSumFormula createIntSumFormula(String metricKey) {
return createIntSumFormula(metricKey, null);
}
public static IntSumFormula createIntSumFormula(String metricKey, @Nullable Integer defaultInputValue) {
return new IntSumFormula(metricKey, defaultInputValue);
}
public static class IntSumFormula extends SumFormula<IntSumCounter, Integer> {
private IntSumFormula(String metricKey, @Nullable Integer defaultInputValue) {
super(metricKey, defaultInputValue);
}
@Override
public IntSumCounter createNewCounter() {
return new IntSumCounter(metricKey, defaultInputValue);
}
@Override
public Optional<Measure> createMeasure(IntSumCounter counter, CreateMeasureContext context) {
Optional<Integer> valueOptional = counter.getValue();
if (shouldCreateMeasure(context, valueOptional)) {
return Optional.of(Measure.newMeasureBuilder().create(valueOptional.get()));
}
return Optional.empty();
}
}
public static LongSumFormula createLongSumFormula(String metricKey) {
return createLongSumFormula(metricKey, null);
}
public static LongSumFormula createLongSumFormula(String metricKey, @Nullable Long defaultInputValue) {
return new LongSumFormula(metricKey, defaultInputValue);
}
public static class LongSumFormula extends SumFormula<LongSumCounter, Long> {
private LongSumFormula(String metricKey, @Nullable Long defaultInputValue) {
super(metricKey, defaultInputValue);
}
@Override
public LongSumCounter createNewCounter() {
return new LongSumCounter(metricKey, defaultInputValue);
}
@Override
public Optional<Measure> createMeasure(LongSumCounter counter, CreateMeasureContext context) {
Optional<Long> valueOptional = counter.getValue();
if (shouldCreateMeasure(context, valueOptional)) {
return Optional.of(Measure.newMeasureBuilder().create(valueOptional.get()));
}
return Optional.empty();
}
}
private static <T extends Number> boolean shouldCreateMeasure(CreateMeasureContext context, Optional<T> value) {
return value.isPresent() && CrawlerDepthLimit.LEAVES.isDeeperThan(context.getComponent().getType());
}
@Override
public String[] getOutputMetricKeys() {
return new String[] {metricKey};
}
}
| 4,110 | 37.064815 | 114 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/formula/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.ce.task.projectanalysis.formula;
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/formula/counter/DoubleValue.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.formula.counter;
import javax.annotation.Nullable;
/**
* Convenience class wrapping a double to compute the value and know it is has ever been set.
*/
public class DoubleValue {
private boolean set = false;
private double value = 0L;
/**
* @return the current {@link DoubleValue} so that chained calls on a specific {@link DoubleValue} instance can be done
*/
public DoubleValue increment(double increment) {
this.value += increment;
this.set = true;
return this;
}
/**
* @return the current {@link DoubleValue} so that chained calls on a specific {@link DoubleValue} instance can be done
*/
public DoubleValue increment(@Nullable DoubleValue value) {
if (value != null && value.isSet()) {
increment(value.value);
}
return this;
}
public boolean isSet() {
return set;
}
public double getValue() {
return value;
}
}
| 1,783 | 29.237288 | 121 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/formula/counter/IntSumCounter.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.formula.counter;
import java.util.Optional;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.ce.task.projectanalysis.formula.CounterInitializationContext;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import static java.util.Objects.requireNonNull;
/**
* Simple counter that do the sum of an integer measure
*/
public class IntSumCounter implements SumCounter<Integer, IntSumCounter> {
private final String metricKey;
@CheckForNull
private final Integer defaultInputValue;
private int value = 0;
private boolean initialized = false;
public IntSumCounter(String metricKey) {
this(metricKey, null);
}
public IntSumCounter(String metricKey, @Nullable Integer defaultInputValue) {
this.metricKey = requireNonNull(metricKey, "metricKey can not be null");
this.defaultInputValue = defaultInputValue;
}
@Override
public void aggregate(IntSumCounter counter) {
if (counter.getValue().isPresent()) {
addValue(counter.getValue().get());
}
}
@Override
public void initialize(CounterInitializationContext context) {
Optional<Measure> measureOptional = context.getMeasure(metricKey);
if (measureOptional.isPresent()) {
addValue(measureOptional.get().getIntValue());
} else if (defaultInputValue != null) {
addValue(defaultInputValue);
}
}
private void addValue(int newValue) {
initialized = true;
value += newValue;
}
@Override
public Optional<Integer> getValue() {
if (initialized) {
return Optional.of(value);
}
return Optional.empty();
}
}
| 2,500 | 29.876543 | 79 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/formula/counter/IntValue.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.formula.counter;
import javax.annotation.Nullable;
/**
* Convenience class wrapping an int to compute the value and know it is has ever been set.
*/
public class IntValue {
private boolean set = false;
private int value = 0;
/**
* @return the current {@link IntValue} so that chained calls on a specific {@link IntValue} instance can be done
*/
public IntValue increment(int increment) {
this.value += increment;
this.set = true;
return this;
}
/**
* @return the current {@link IntValue} so that chained calls on a specific {@link IntValue} instance can be done
*/
public IntValue increment(@Nullable IntValue value) {
if (value != null && value.isSet()) {
increment(value.value);
}
return this;
}
public boolean isSet() {
return set;
}
public int getValue() {
return value;
}
}
| 1,747 | 28.627119 | 115 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/formula/counter/LongSumCounter.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.formula.counter;
import java.util.Optional;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.ce.task.projectanalysis.formula.CounterInitializationContext;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import static java.util.Objects.requireNonNull;
/**
* Simple counter that do the sum of an integer measure
*/
public class LongSumCounter implements SumCounter<Long, LongSumCounter> {
private final String metricKey;
@CheckForNull
private final Long defaultInputValue;
private long value = 0;
private boolean initialized = false;
public LongSumCounter(String metricKey) {
this(metricKey, null);
}
public LongSumCounter(String metricKey, @Nullable Long defaultInputValue) {
this.metricKey = requireNonNull(metricKey, "metricKey can not be null");
this.defaultInputValue = defaultInputValue;
}
@Override
public void aggregate(LongSumCounter counter) {
if (counter.getValue().isPresent()) {
addValue(counter.getValue().get());
}
}
@Override
public void initialize(CounterInitializationContext context) {
Optional<Measure> measureOptional = context.getMeasure(metricKey);
if (measureOptional.isPresent()) {
addValue(measureOptional.get().getLongValue());
} else if (defaultInputValue != null) {
addValue(defaultInputValue);
}
}
private void addValue(long newValue) {
initialized = true;
value += newValue;
}
@Override
public Optional<Long> getValue() {
if (initialized) {
return Optional.of(value);
}
return Optional.empty();
}
}
| 2,496 | 29.82716 | 78 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/formula/counter/LongValue.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.formula.counter;
import javax.annotation.Nullable;
/**
* Convenience class wrapping a long to compute the value and know it is has ever been set.
*/
public class LongValue {
private boolean set = false;
private long value = 0L;
/**
* @return the current {@link LongValue} so that chained calls on a specific {@link LongValue} instance can be done
*/
public LongValue increment(long increment) {
this.value += increment;
this.set = true;
return this;
}
/**
* @return the current {@link LongValue} so that chained calls on a specific {@link LongValue} instance can be done
*/
public LongValue increment(@Nullable LongValue value) {
if (value != null && value.isSet()) {
increment(value.value);
}
return this;
}
public boolean isSet() {
return set;
}
public long getValue() {
return value;
}
}
| 1,759 | 28.830508 | 117 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.