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/projectexport/component/MutableComponentRepository.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.component; public interface MutableComponentRepository extends ComponentRepository { /** * Adds the reference of a Component (designated by it's uuid) to the repository and keep tracks of whether * specified uuid is one of a File. * * @throws IllegalArgumentException if the specified uuid is already registered with another ref in the repository. * @throws IllegalArgumentException if the specified uuid is already registered with another File flag */ void register(long ref, String uuid, boolean file); }
1,413
43.1875
117
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/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.projectexport.component; import javax.annotation.ParametersAreNonnullByDefault;
981
39.916667
75
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/file/ExportLineHashesStep.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.file; import com.sonarsource.governance.projectdump.protobuf.ProjectDump; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.Set; import org.slf4j.LoggerFactory; import org.sonar.ce.task.projectexport.component.ComponentRepository; import org.sonar.ce.task.projectexport.steps.DumpElement; import org.sonar.ce.task.projectexport.steps.DumpWriter; import org.sonar.ce.task.projectexport.steps.StreamWriter; import org.sonar.ce.task.step.ComputationStep; import org.sonar.db.DatabaseUtils; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import static com.google.common.collect.Iterables.partition; import static java.lang.String.format; import static org.sonar.ce.task.projectexport.util.ResultSetUtils.emptyIfNull; import static org.sonar.db.DatabaseUtils.PARTITION_SIZE_FOR_ORACLE; import static org.sonar.db.DatabaseUtils.closeQuietly; public class ExportLineHashesStep implements ComputationStep { private final DbClient dbClient; private final DumpWriter dumpWriter; private final ComponentRepository componentRepository; public ExportLineHashesStep(DbClient dbClient, DumpWriter dumpWriter, ComponentRepository componentRepository) { this.dbClient = dbClient; this.dumpWriter = dumpWriter; this.componentRepository = componentRepository; } @Override public String getDescription() { return "Export line hashes"; } @Override public void execute(Context context) { Set<String> allFileUuids = componentRepository.getFileUuids(); PreparedStatement stmt = null; ResultSet rs = null; long count = 0; try (StreamWriter<ProjectDump.LineHashes> output = dumpWriter.newStreamWriter(DumpElement.LINES_HASHES)) { if (allFileUuids.isEmpty()) { return; } try (DbSession dbSession = dbClient.openSession(false)) { ProjectDump.LineHashes.Builder builder = ProjectDump.LineHashes.newBuilder(); for (List<String> fileUuids : partition(allFileUuids, PARTITION_SIZE_FOR_ORACLE)) { stmt = createStatement(dbSession, fileUuids); rs = stmt.executeQuery(); while (rs.next()) { ProjectDump.LineHashes lineHashes = toLinehashes(builder, rs); output.write(lineHashes); count++; } closeQuietly(rs); closeQuietly(stmt); } LoggerFactory.getLogger(getClass()).debug("Lines hashes of {} files exported", count); } catch (Exception e) { throw new IllegalStateException(format("Lines hashes export failed after processing %d files successfully", count), e); } finally { closeQuietly(rs); closeQuietly(stmt); } } } private PreparedStatement createStatement(DbSession dbSession, List<String> uuids) throws SQLException { String sql = "select" + " file_uuid, line_hashes, project_uuid" + " FROM file_sources" + " WHERE file_uuid in (%s)" + " order by created_at, uuid"; PreparedStatement stmt = dbClient.getMyBatis().newScrollingSelectStatement(dbSession, format(sql, wildCardStringFor(uuids))); try { int i = 1; for (String uuid : uuids) { stmt.setString(i, uuid); i++; } return stmt; } catch (Exception e) { DatabaseUtils.closeQuietly(stmt); throw e; } } private static String wildCardStringFor(List<String> uuids) { switch (uuids.size()) { case 0: throw new IllegalArgumentException("uuids can not be empty"); case 1: return "?"; default: return createWildCardStringFor(uuids); } } private static String createWildCardStringFor(List<String> uuids) { int size = (uuids.size() * 2) - 1; char[] res = new char[size]; for (int j = 0; j < size; j++) { if (j % 2 == 0) { res[j] = '?'; } else { res[j] = ','; } } return new String(res); } private ProjectDump.LineHashes toLinehashes(ProjectDump.LineHashes.Builder builder, ResultSet rs) throws SQLException { builder.clear(); return builder .setComponentRef(componentRepository.getRef(rs.getString(1))) .setHashes(emptyIfNull(rs, 2)) .setProjectUuid(emptyIfNull(rs, 3)) .build(); } }
5,193
34.094595
129
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/file/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.ce.task.projectexport.file; import javax.annotation.ParametersAreNonnullByDefault;
976
39.708333
75
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/issue/ExportIssuesChangelogStep.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.issue; import com.sonarsource.governance.projectdump.protobuf.ProjectDump; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.slf4j.LoggerFactory; import org.sonar.ce.task.projectexport.steps.DumpElement; import org.sonar.ce.task.projectexport.steps.DumpWriter; import org.sonar.ce.task.projectexport.steps.ProjectHolder; import org.sonar.ce.task.projectexport.steps.StreamWriter; import org.sonar.ce.task.step.ComputationStep; import org.sonar.db.DatabaseUtils; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import static java.lang.String.format; import static org.sonar.ce.task.projectexport.util.ResultSetUtils.defaultIfNull; import static org.sonar.ce.task.projectexport.util.ResultSetUtils.emptyIfNull; public class ExportIssuesChangelogStep implements ComputationStep { private static final String STATUS_CLOSED = "CLOSED"; private static final String QUERY = "select" + " ic.kee, ic.issue_key, ic.change_type, ic.change_data, ic.user_login," + " ic.issue_change_creation_date, ic.created_at, pb.uuid" + " from issue_changes ic" + " join issues i on i.kee = ic.issue_key" + " join project_branches pb on pb.uuid = i.project_uuid" + " where pb.project_uuid = ? and pb.branch_type = 'BRANCH' and pb.exclude_from_purge = ? " + " and i.status <> ?" + " order by ic.created_at asc"; private final DbClient dbClient; private final ProjectHolder projectHolder; private final DumpWriter dumpWriter; public ExportIssuesChangelogStep(DbClient dbClient, ProjectHolder projectHolder, DumpWriter dumpWriter) { this.dbClient = dbClient; this.projectHolder = projectHolder; this.dumpWriter = dumpWriter; } @Override public String getDescription() { return "Export issues changelog"; } @Override public void execute(Context context) { long count = 0; try ( StreamWriter<ProjectDump.IssueChange> output = dumpWriter.newStreamWriter(DumpElement.ISSUES_CHANGELOG); DbSession dbSession = dbClient.openSession(false); PreparedStatement stmt = createStatement(dbSession); ResultSet rs = stmt.executeQuery()) { ProjectDump.IssueChange.Builder builder = ProjectDump.IssueChange.newBuilder(); while (rs.next()) { ProjectDump.IssueChange issue = toIssuesChange(builder, rs); output.write(issue); count++; } LoggerFactory.getLogger(getClass()).debug("{} issue changes exported", count); } catch (Exception e) { throw new IllegalStateException(format("Issues changelog export failed after processing %d issue changes successfully", count), e); } } private PreparedStatement createStatement(DbSession dbSession) throws SQLException { // export oldest entries first, so they can be imported with smallest ids PreparedStatement stmt = dbClient.getMyBatis().newScrollingSelectStatement(dbSession, QUERY); try { stmt.setString(1, projectHolder.projectDto().getUuid()); stmt.setBoolean(2, true); stmt.setString(3, STATUS_CLOSED); return stmt; } catch (Exception t) { DatabaseUtils.closeQuietly(stmt); throw t; } } private static ProjectDump.IssueChange toIssuesChange(ProjectDump.IssueChange.Builder builder, ResultSet rs) throws SQLException { builder.clear(); return builder .setKey(emptyIfNull(rs, 1)) .setIssueUuid(rs.getString(2)) .setChangeType(emptyIfNull(rs, 3)) .setChangeData(emptyIfNull(rs, 4)) .setUserUuid(emptyIfNull(rs, 5)) .setCreatedAt(defaultIfNull(rs, 6, defaultIfNull(rs, 7, 0L))) .setProjectUuid(rs.getString(8)) .build(); } }
4,569
38.396552
137
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/issue/ExportIssuesStep.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.issue; import com.google.common.annotations.VisibleForTesting; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; import com.sonarsource.governance.projectdump.protobuf.ProjectDump; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.Objects; import java.util.Optional; import org.sonar.api.rule.RuleKey; import org.slf4j.LoggerFactory; import org.sonar.ce.task.projectexport.component.ComponentRepository; import org.sonar.ce.task.projectexport.rule.Rule; import org.sonar.ce.task.projectexport.rule.RuleRepository; import org.sonar.ce.task.projectexport.steps.DumpElement; import org.sonar.ce.task.projectexport.steps.DumpElement.IssueDumpElement; import org.sonar.ce.task.projectexport.steps.DumpWriter; import org.sonar.ce.task.projectexport.steps.ProjectHolder; import org.sonar.ce.task.projectexport.steps.StreamWriter; import org.sonar.ce.task.step.ComputationStep; import org.sonar.db.DatabaseUtils; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.protobuf.DbIssues; import static java.lang.String.format; import static org.sonar.ce.task.projectexport.util.ResultSetUtils.defaultIfNull; import static org.sonar.ce.task.projectexport.util.ResultSetUtils.emptyIfNull; public class ExportIssuesStep implements ComputationStep { private static final String RULE_STATUS_REMOVED = "REMOVED"; private static final String ISSUE_STATUS_CLOSED = "CLOSED"; // ordered by rule_id to reduce calls to RuleRepository private static final String QUERY = "select" + " i.kee, r.uuid, r.plugin_rule_key, r.plugin_name, i.issue_type," + " i.component_uuid, i.message, i.line, i.checksum, i.status," + " i.resolution, i.severity, i.manual_severity, i.gap, effort," + " i.assignee, i.author_login, i.tags, i.issue_creation_date," + " i.issue_update_date, i.issue_close_date, i.locations, i.project_uuid," + " i.rule_description_context_key, i.message_formattings, i.code_variants " + " from issues i" + " join rules r on r.uuid = i.rule_uuid and r.status <> ?" + " join components p on p.uuid = i.project_uuid" + " join project_branches pb on pb.uuid = p.uuid" + " where pb.project_uuid = ? and pb.branch_type = 'BRANCH' and pb.exclude_from_purge=?" + " and i.status <> ?" + " order by" + " i.rule_uuid asc, i.created_at asc"; private final DbClient dbClient; private final ProjectHolder projectHolder; private final DumpWriter dumpWriter; private final RuleRegistrar ruleRegistrar; private final ComponentRepository componentRepository; public ExportIssuesStep(DbClient dbClient, ProjectHolder projectHolder, DumpWriter dumpWriter, RuleRepository ruleRepository, ComponentRepository componentRepository) { this.dbClient = dbClient; this.projectHolder = projectHolder; this.dumpWriter = dumpWriter; this.componentRepository = componentRepository; this.ruleRegistrar = new RuleRegistrar(ruleRepository); } @Override public String getDescription() { return "Export issues"; } @Override public void execute(Context context) { long count = 0; try ( StreamWriter<ProjectDump.Issue> output = dumpWriter.newStreamWriter(DumpElement.ISSUES); DbSession dbSession = dbClient.openSession(false); PreparedStatement stmt = createStatement(dbSession); ResultSet rs = stmt.executeQuery()) { ProjectDump.Issue.Builder builder = ProjectDump.Issue.newBuilder(); while (rs.next()) { ProjectDump.Issue issue = toIssue(builder, rs); output.write(issue); count++; } LoggerFactory.getLogger(getClass()).debug("{} issues exported", count); } catch (Exception e) { throw new IllegalStateException(format("Issue export failed after processing %d issues successfully", count), e); } } private PreparedStatement createStatement(DbSession dbSession) throws SQLException { PreparedStatement stmt = dbClient.getMyBatis().newScrollingSelectStatement(dbSession, QUERY); try { stmt.setString(1, RULE_STATUS_REMOVED); stmt.setString(2, projectHolder.projectDto().getUuid()); stmt.setBoolean(3, true); stmt.setString(4, ISSUE_STATUS_CLOSED); return stmt; } catch (Exception t) { DatabaseUtils.closeQuietly(stmt); throw t; } } private ProjectDump.Issue toIssue(ProjectDump.Issue.Builder builder, ResultSet rs) throws SQLException { builder.clear(); String issueUuid = rs.getString(1); setRule(builder, rs); builder .setUuid(issueUuid) .setType(rs.getInt(5)) .setComponentRef(componentRepository.getRef(rs.getString(6))) .setMessage(emptyIfNull(rs, 7)) .setLine(rs.getInt(8)) .setChecksum(emptyIfNull(rs, 9)) .setStatus(emptyIfNull(rs, 10)) .setResolution(emptyIfNull(rs, 11)) .setSeverity(emptyIfNull(rs, 12)) .setManualSeverity(rs.getBoolean(13)) .setGap(defaultIfNull(rs, 14, IssueDumpElement.NO_GAP)) .setEffort(defaultIfNull(rs, 15, IssueDumpElement.NO_EFFORT)) .setAssignee(emptyIfNull(rs, 16)) .setAuthor(emptyIfNull(rs, 17)) .setTags(emptyIfNull(rs, 18)) .setIssueCreatedAt(rs.getLong(19)) .setIssueUpdatedAt(rs.getLong(20)) .setIssueClosedAt(rs.getLong(21)) .setProjectUuid(rs.getString(23)) .setCodeVariants(emptyIfNull(rs, 26)); Optional.ofNullable(rs.getString(24)).ifPresent(builder::setRuleDescriptionContextKey); setLocations(builder, rs, issueUuid); setMessageFormattings(builder, rs, issueUuid); return builder.build(); } private void setRule(ProjectDump.Issue.Builder builder, ResultSet rs) throws SQLException { String ruleUuid = rs.getString(2); String ruleKey = rs.getString(3); String repositoryKey = rs.getString(4); builder.setRuleRef(ruleRegistrar.register(ruleUuid, repositoryKey, ruleKey).ref()); } private static void setLocations(ProjectDump.Issue.Builder builder, ResultSet rs, String issueUuid) throws SQLException { try { byte[] bytes = rs.getBytes(22); if (bytes != null) { // fail fast, ensure we can read data from DB DbIssues.Locations.parseFrom(bytes); builder.setLocations(ByteString.copyFrom(bytes)); } } catch (InvalidProtocolBufferException e) { throw new IllegalStateException(format("Fail to read locations from DB for issue %s", issueUuid), e); } } private static void setMessageFormattings(ProjectDump.Issue.Builder builder, ResultSet rs, String issueUuid) throws SQLException { try { byte[] bytes = rs.getBytes(25); if (bytes != null) { // fail fast, ensure we can read data from DB DbIssues.MessageFormattings messageFormattings = DbIssues.MessageFormattings.parseFrom(bytes); if (messageFormattings != null) { builder.addAllMessageFormattings(dbToDumpMessageFormatting(messageFormattings.getMessageFormattingList())); } } } catch (InvalidProtocolBufferException e) { throw new IllegalStateException(format("Fail to read message formattings from DB for issue %s", issueUuid), e); } } @VisibleForTesting static List<ProjectDump.MessageFormatting> dbToDumpMessageFormatting(List<DbIssues.MessageFormatting> messageFormattingList) { return messageFormattingList.stream() .map(e -> ProjectDump.MessageFormatting.newBuilder() .setStart(e.getStart()) .setEnd(e.getEnd()) .setType(ProjectDump.MessageFormattingType.valueOf(e.getType().name())).build()) .toList(); } private static class RuleRegistrar { private final RuleRepository ruleRepository; private Rule previousRule = null; private String previousRuleUuid = null; private RuleRegistrar(RuleRepository ruleRepository) { this.ruleRepository = ruleRepository; } public Rule register(String ruleUuid, String repositoryKey, String ruleKey) { if (Objects.equals(previousRuleUuid, ruleUuid)) { return previousRule; } return lookup(ruleUuid, RuleKey.of(repositoryKey, ruleKey)); } private Rule lookup(String ruleUuid, RuleKey ruleKey) { this.previousRule = ruleRepository.register(ruleUuid, ruleKey); this.previousRuleUuid = ruleUuid; return previousRule; } } }
9,294
39.947137
132
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/issue/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.ce.task.projectexport.issue; import javax.annotation.ParametersAreNonnullByDefault;
977
39.75
75
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/rule/ExportAdHocRulesStep.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.rule; import com.sonarsource.governance.projectdump.protobuf.ProjectDump; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.slf4j.LoggerFactory; import org.sonar.ce.task.projectexport.steps.DumpElement; import org.sonar.ce.task.projectexport.steps.DumpWriter; import org.sonar.ce.task.projectexport.steps.ProjectHolder; import org.sonar.ce.task.projectexport.steps.StreamWriter; import org.sonar.ce.task.step.ComputationStep; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import static java.lang.String.format; import static org.sonar.ce.task.projectexport.util.ResultSetUtils.defaultIfNull; import static org.sonar.ce.task.projectexport.util.ResultSetUtils.emptyIfNull; public class ExportAdHocRulesStep implements ComputationStep { private static final String RULE_STATUS_REMOVED = "REMOVED"; private static final String ISSUE_STATUS_CLOSED = "CLOSED"; private static final String QUERY = "select" + " r.uuid, r.plugin_key, r.plugin_rule_key, r.plugin_name, r.name, r.status, r.rule_type, r.scope, r.ad_hoc_name," + " r.ad_hoc_description,r.ad_hoc_severity, r.ad_hoc_type" + " from rules r" + " inner join issues i on r.uuid = i.rule_uuid and r.status <> ? and r.is_ad_hoc = ?" + " left join components p on p.uuid = i.project_uuid" + " left join project_branches pb on pb.uuid = p.uuid" + " where pb.project_uuid = ? and pb.branch_type = 'BRANCH' and pb.exclude_from_purge = ?" + " and i.status <> ?" + " order by" + " i.rule_uuid asc"; private final DbClient dbClient; private final ProjectHolder projectHolder; private final DumpWriter dumpWriter; public ExportAdHocRulesStep(DbClient dbClient, ProjectHolder projectHolder, DumpWriter dumpWriter) { this.dbClient = dbClient; this.projectHolder = projectHolder; this.dumpWriter = dumpWriter; } @Override public void execute(Context context) { long count = 0L; try ( StreamWriter<ProjectDump.AdHocRule> output = dumpWriter.newStreamWriter(DumpElement.AD_HOC_RULES); DbSession dbSession = dbClient.openSession(false); PreparedStatement stmt = dbClient.getMyBatis().newScrollingSelectStatement(dbSession, QUERY)) { stmt.setString(1, RULE_STATUS_REMOVED); stmt.setBoolean(2, true); stmt.setString(3, projectHolder.projectDto().getUuid()); stmt.setBoolean(4, true); stmt.setString(5, ISSUE_STATUS_CLOSED); try (ResultSet rs = stmt.executeQuery()) { ProjectDump.AdHocRule.Builder adHocRuleBuilder = ProjectDump.AdHocRule.newBuilder(); while (rs.next()) { ProjectDump.AdHocRule rule = convertToAdHocRule(rs, adHocRuleBuilder); output.write(rule); count++; } LoggerFactory.getLogger(getClass()).debug("{} ad-hoc rules exported", count); } } catch (Exception e) { throw new IllegalStateException(format("Ad-hoc rules export failed after processing %d rules successfully", count), e); } } private static ProjectDump.AdHocRule convertToAdHocRule(ResultSet rs, ProjectDump.AdHocRule.Builder builder) throws SQLException { return builder .clear() .setRef(rs.getString(1)) .setPluginKey(emptyIfNull(rs, 2)) .setPluginRuleKey(rs.getString(3)) .setPluginName(rs.getString(4)) .setName(emptyIfNull(rs, 5)) .setStatus(emptyIfNull(rs, 6)) .setType(rs.getInt(7)) .setScope(rs.getString(8)) .setMetadata(buildMetadata(rs)) .build(); } private static ProjectDump.AdHocRule.RuleMetadata buildMetadata(ResultSet rs) throws SQLException { return ProjectDump.AdHocRule.RuleMetadata.newBuilder() .setAdHocName(emptyIfNull(rs, 9)) .setAdHocDescription(emptyIfNull(rs, 10)) .setAdHocSeverity(emptyIfNull(rs, 11)) .setAdHocType(defaultIfNull(rs, 12, 0)) .build(); } @Override public String getDescription() { return "Export ad-hoc rules"; } }
4,868
39.575
132
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/rule/ExportRuleStep.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.rule; import com.sonarsource.governance.projectdump.protobuf.ProjectDump; import org.slf4j.LoggerFactory; import org.sonar.ce.task.projectexport.steps.DumpElement; import org.sonar.ce.task.projectexport.steps.DumpWriter; import org.sonar.ce.task.projectexport.steps.StreamWriter; import org.sonar.ce.task.step.ComputationStep; import static java.lang.String.format; public class ExportRuleStep implements ComputationStep { private final RuleRepository ruleRepository; private final DumpWriter dumpWriter; public ExportRuleStep(RuleRepository ruleRepository, DumpWriter dumpWriter) { this.ruleRepository = ruleRepository; this.dumpWriter = dumpWriter; } @Override public String getDescription() { return "Export rules"; } @Override public void execute(Context context) { long count = 0; try (StreamWriter<ProjectDump.Rule> writer = dumpWriter.newStreamWriter(DumpElement.RULES)) { ProjectDump.Rule.Builder ruleBuilder = ProjectDump.Rule.newBuilder(); for (Rule rule : ruleRepository.getAll()) { ProjectDump.Rule ruleMessage = toRuleMessage(ruleBuilder, rule); writer.write(ruleMessage); count++; } LoggerFactory.getLogger(getClass()).debug("{} rules exported", count); } catch (Exception e) { throw new IllegalStateException(format("Rule Export failed after processing %d rules successfully", count), e); } } private static ProjectDump.Rule toRuleMessage(ProjectDump.Rule.Builder ruleBuilder, Rule rule) { ruleBuilder.clear(); return ruleBuilder .setRef(rule.ref()) .setKey(rule.key()) .setRepository(rule.repository()) .build(); } }
2,561
35.6
117
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/rule/Rule.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.rule; import java.util.Objects; import javax.annotation.Nullable; import static java.util.Objects.requireNonNull; public record Rule(String ref, String repository, String key) { public Rule(String ref, String repository, String key) { this.ref = ref; this.repository = requireNonNull(repository, "repository 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 instanceof Rule)) { return false; } Rule rule = (Rule) o; return repository.equals(rule.repository) && key.equals(rule.key); } @Override public int hashCode() { return Objects.hash(repository, key); } @Override public String toString() { return "Rule{" + "ref='" + ref + "', repository='" + repository + "', key='" + key + "'}"; } }
1,784
30.315789
79
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/rule/RuleRepository.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.rule; import java.util.Collection; import org.sonar.api.rule.RuleKey; /** * This repository is responsible to register ids for {@link RuleKey}s and keeping track of them so that it can return * all of them in {@link #getAll()}. */ public interface RuleRepository { /** * Register the specified ref for the specified ruleKey and return it's representing {@link Rule} object. * * @throws IllegalArgumentException if the specified ruleKey is not the same as the one already in the repository (if any) */ Rule register(String ref, RuleKey ruleKey); Collection<Rule> getAll(); }
1,483
35.195122
124
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/rule/RuleRepositoryImpl.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.rule; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.sonar.api.rule.RuleKey; import static java.lang.String.format; import static java.util.Objects.requireNonNull; public class RuleRepositoryImpl implements RuleRepository { private final Map<String, Rule> rulesByUuid = new HashMap<>(); @Override public Rule register(String ref, RuleKey ruleKey) { requireNonNull(ruleKey, "ruleKey can not be null"); Rule rule = rulesByUuid.get(ref); if (rule != null) { if (!ruleKey.repository().equals(rule.repository()) || !ruleKey.rule().equals(rule.key())) { throw new IllegalArgumentException(format( "Specified RuleKey '%s' is not equal to the one already registered in repository for ref %s: '%s'", ruleKey, ref, RuleKey.of(rule.repository(), rule.key()))); } return rule; } rule = new Rule(ref, ruleKey.repository(), ruleKey.rule()); rulesByUuid.put(ref, rule); return rule; } @Override public Collection<Rule> getAll() { return List.copyOf(rulesByUuid.values()); } }
2,008
33.050847
109
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/rule/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.ce.task.projectexport.rule; import javax.annotation.ParametersAreNonnullByDefault;
976
39.708333
75
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/steps/DumpElement.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.steps; import com.google.protobuf.Message; import com.google.protobuf.Parser; import com.sonarsource.governance.projectdump.protobuf.ProjectDump; import javax.annotation.concurrent.Immutable; /** * File element in the dump report. */ @Immutable public class DumpElement<M extends Message> { public static final long NO_DATETIME = 0; public static final DumpElement<ProjectDump.Metadata> METADATA = new DumpElement<>("metadata.pb", ProjectDump.Metadata.parser()); public static final DumpElement<ProjectDump.Component> COMPONENTS = new DumpElement<>("components.pb", ProjectDump.Component.parser()); public static final DumpElement<ProjectDump.Branch> BRANCHES = new DumpElement<>("branches.pb", ProjectDump.Branch.parser()); public static final DumpElement<ProjectDump.Analysis> ANALYSES = new DumpElement<>("analyses.pb", ProjectDump.Analysis.parser()); public static final DumpElement<ProjectDump.Measure> MEASURES = new DumpElement<>("measures.pb", ProjectDump.Measure.parser()); public static final DumpElement<ProjectDump.LiveMeasure> LIVE_MEASURES = new DumpElement<>("live_measures.pb", ProjectDump.LiveMeasure.parser()); public static final DumpElement<ProjectDump.Metric> METRICS = new DumpElement<>("metrics.pb", ProjectDump.Metric.parser()); public static final IssueDumpElement ISSUES = new IssueDumpElement(); public static final DumpElement<ProjectDump.IssueChange> ISSUES_CHANGELOG = new DumpElement<>("issues_changelog.pb", ProjectDump.IssueChange.parser()); public static final DumpElement<ProjectDump.AdHocRule> AD_HOC_RULES = new DumpElement<>("ad_hoc_rules.pb", ProjectDump.AdHocRule.parser()); public static final DumpElement<ProjectDump.Rule> RULES = new DumpElement<>("rules.pb", ProjectDump.Rule.parser()); public static final DumpElement<ProjectDump.Link> LINKS = new DumpElement<>("links.pb", ProjectDump.Link.parser()); public static final DumpElement<ProjectDump.Event> EVENTS = new DumpElement<>("events.pb", ProjectDump.Event.parser()); public static final DumpElement<ProjectDump.Setting> SETTINGS = new DumpElement<>("settings.pb", ProjectDump.Setting.parser()); public static final DumpElement<ProjectDump.Plugin> PLUGINS = new DumpElement<>("plugins.pb", ProjectDump.Plugin.parser()); public static final DumpElement<ProjectDump.LineHashes> LINES_HASHES = new DumpElement<>("lines_hashes.pb", ProjectDump.LineHashes.parser()); public static final DumpElement<ProjectDump.NewCodePeriod> NEW_CODE_PERIODS = new DumpElement<>("new_code_periods.pb", ProjectDump.NewCodePeriod.parser()); private final String filename; private final Parser<M> parser; private DumpElement(String filename, Parser<M> parser) { this.filename = filename; this.parser = parser; } public String filename() { return filename; } public Parser<M> parser() { return parser; } public static class IssueDumpElement extends DumpElement<ProjectDump.Issue> { public static final int NO_LINE = 0; public static final double NO_GAP = -1; public static final long NO_EFFORT = -1; public IssueDumpElement() { super("issues.pb", ProjectDump.Issue.parser()); } } }
4,048
50.910256
157
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/steps/DumpReader.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.steps; import com.google.protobuf.Message; import com.sonarsource.governance.projectdump.protobuf.ProjectDump; import java.io.File; public interface DumpReader { File zipFile(); File tempRootDir(); ProjectDump.Metadata metadata(); <M extends Message> MessageStream<M> stream(DumpElement<M> elt); }
1,196
31.351351
75
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/steps/DumpWriter.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.steps; import com.google.protobuf.Message; import com.sonarsource.governance.projectdump.protobuf.ProjectDump; /** * Writes project dump on disk */ public interface DumpWriter { /** * Writes a single metadata message. Can be called only once. * @throws IllegalStateException if metadata has already been written * @throws IllegalStateException if already published (see {@link #publish()}) */ void write(ProjectDump.Metadata metadata); /** * Writes a stream of protobuf objects. Streams are appended. * @throws IllegalStateException if already published (see {@link #publish()}) */ <M extends Message> StreamWriter<M> newStreamWriter(DumpElement<M> elt); /** * Publishes the dump file by zipping directory and moving zip file to directory /data. * @throws IllegalStateException if metadata has not been written * @throws IllegalStateException if already published */ void publish(); }
1,821
34.72549
89
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/steps/DumpWriterImpl.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.steps; import com.google.protobuf.Message; import com.sonarsource.governance.projectdump.protobuf.ProjectDump; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.concurrent.atomic.AtomicBoolean; import org.sonar.api.utils.TempFolder; import org.slf4j.LoggerFactory; import org.sonar.ce.task.projectexport.taskprocessor.ProjectDescriptor; import org.sonar.ce.task.projectexport.util.ProjectExportDumpFS; import static org.apache.commons.io.FileUtils.sizeOf; import static org.sonar.ce.task.projectexport.steps.DumpElement.METADATA; import static org.sonar.ce.task.util.Files2.FILES2; import static org.sonar.ce.task.util.Protobuf2.PROTOBUF2; import static org.sonar.core.util.FileUtils.humanReadableByteCountSI; public class DumpWriterImpl implements DumpWriter { private final ProjectDescriptor descriptor; private final ProjectExportDumpFS projectExportDumpFS; private final TempFolder tempFolder; private final File rootDir; private final AtomicBoolean metadataWritten = new AtomicBoolean(false); private final AtomicBoolean published = new AtomicBoolean(false); public DumpWriterImpl(ProjectDescriptor descriptor, ProjectExportDumpFS projectExportDumpFS, TempFolder tempFolder) { this.descriptor = descriptor; this.projectExportDumpFS = projectExportDumpFS; this.tempFolder = tempFolder; this.rootDir = tempFolder.newDir(); } @Override public void write(ProjectDump.Metadata metadata) { checkNotPublished(); if (metadataWritten.get()) { throw new IllegalStateException("Metadata has already been written"); } File file = new File(rootDir, METADATA.filename()); try (FileOutputStream output = FILES2.openOutputStream(file, false)) { PROTOBUF2.writeTo(metadata, output); metadataWritten.set(true); } catch (IOException e) { throw new IllegalStateException("Can not write to file " + file, e); } } @Override public <M extends Message> StreamWriter<M> newStreamWriter(DumpElement<M> elt) { checkNotPublished(); File file = new File(rootDir, elt.filename()); return StreamWriterImpl.create(file); } @Override public void publish() { checkNotPublished(); if (!metadataWritten.get()) { throw new IllegalStateException("Metadata is missing"); } File zip = tempFolder.newFile(); FILES2.zipDir(rootDir, zip); File targetZip = projectExportDumpFS.exportDumpOf(descriptor); FILES2.deleteIfExists(targetZip); FILES2.moveFile(zip, targetZip); FILES2.deleteIfExists(rootDir); LoggerFactory.getLogger(getClass()).info("Dump file published | size={} | path={}", humanReadableByteCountSI(sizeOf(targetZip)), targetZip.getAbsolutePath()); published.set(true); } private void checkNotPublished() { if (published.get()) { throw new IllegalStateException("Dump is already published"); } } }
3,796
36.594059
162
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/steps/ExportEventsStep.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.steps; import com.sonarsource.governance.projectdump.protobuf.ProjectDump; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.slf4j.LoggerFactory; import org.sonar.ce.task.projectexport.component.ComponentRepository; import org.sonar.ce.task.step.ComputationStep; import org.sonar.db.DatabaseUtils; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.SnapshotDto; import static java.lang.String.format; import static org.apache.commons.lang.StringUtils.defaultString; import static org.sonar.db.DatabaseUtils.getString; public class ExportEventsStep implements ComputationStep { private static final String QUERY = "select" + " p.uuid, e.name, e.analysis_uuid, e.category, e.description, e.event_data, e.event_date, e.uuid" + " from events e" + " join snapshots s on s.uuid=e.analysis_uuid" + " join components p on p.uuid=s.root_component_uuid" + " join project_branches pb on pb.uuid=p.uuid" + " where pb.project_uuid=? and pb.branch_type = 'BRANCH' and pb.exclude_from_purge=? and s.status=? and p.enabled=?"; private final DbClient dbClient; private final ProjectHolder projectHolder; private final ComponentRepository componentRepository; private final DumpWriter dumpWriter; public ExportEventsStep(DbClient dbClient, ProjectHolder projectHolder, ComponentRepository componentRepository, DumpWriter dumpWriter) { this.dbClient = dbClient; this.projectHolder = projectHolder; this.componentRepository = componentRepository; this.dumpWriter = dumpWriter; } @Override public void execute(Context context) { long count = 0L; try ( StreamWriter<ProjectDump.Event> output = dumpWriter.newStreamWriter(DumpElement.EVENTS); DbSession dbSession = dbClient.openSession(false); PreparedStatement stmt = buildSelectStatement(dbSession); ResultSet rs = stmt.executeQuery()) { ProjectDump.Event.Builder builder = ProjectDump.Event.newBuilder(); while (rs.next()) { ProjectDump.Event event = convertToEvent(rs, builder); output.write(event); count++; } LoggerFactory.getLogger(getClass()).debug("{} events exported", count); } catch (Exception e) { throw new IllegalStateException(format("Event Export failed after processing %d events successfully", count), e); } } private PreparedStatement buildSelectStatement(DbSession dbSession) throws SQLException { PreparedStatement stmt = dbClient.getMyBatis().newScrollingSelectStatement(dbSession, QUERY); try { stmt.setString(1, projectHolder.projectDto().getUuid()); stmt.setBoolean(2, true); stmt.setString(3, SnapshotDto.STATUS_PROCESSED); stmt.setBoolean(4, true); return stmt; } catch (Exception e) { DatabaseUtils.closeQuietly(stmt); throw e; } } private ProjectDump.Event convertToEvent(ResultSet rs, ProjectDump.Event.Builder builder) throws SQLException { long componentRef = componentRepository.getRef(rs.getString(1)); return builder .clear() .setComponentRef(componentRef) .setName(defaultString(getString(rs, 2))) .setAnalysisUuid(getString(rs, 3)) .setCategory(defaultString(getString(rs, 4))) .setDescription(defaultString(getString(rs, 5))) .setData(defaultString(getString(rs, 6))) .setDate(rs.getLong(7)) .setUuid(rs.getString(8)) .build(); } @Override public String getDescription() { return "Export events"; } }
4,454
37.076923
139
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/steps/ExportLinksStep.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.steps; import com.sonarsource.governance.projectdump.protobuf.ProjectDump; import java.util.List; import org.slf4j.LoggerFactory; import org.sonar.ce.task.step.ComputationStep; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.ProjectLinkDto; import org.sonar.db.project.ProjectExportMapper; import static java.lang.String.format; import static org.apache.commons.lang.StringUtils.defaultString; public class ExportLinksStep implements ComputationStep { private final DbClient dbClient; private final ProjectHolder projectHolder; private final DumpWriter dumpWriter; public ExportLinksStep(DbClient dbClient, ProjectHolder projectHolder, DumpWriter dumpWriter) { this.dbClient = dbClient; this.projectHolder = projectHolder; this.dumpWriter = dumpWriter; } @Override public void execute(Context context) { long count = 0L; try { try (DbSession dbSession = dbClient.openSession(false); StreamWriter<ProjectDump.Link> linksWriter = dumpWriter.newStreamWriter(DumpElement.LINKS)) { ProjectDump.Link.Builder builder = ProjectDump.Link.newBuilder(); List<ProjectLinkDto> links = dbSession.getMapper(ProjectExportMapper.class).selectLinksForExport(projectHolder.projectDto().getUuid()); for (ProjectLinkDto link : links) { builder .clear() .setUuid(link.getUuid()) .setName(defaultString(link.getName())) .setHref(defaultString(link.getHref())) .setType(defaultString(link.getType())); linksWriter.write(builder.build()); ++count; } LoggerFactory.getLogger(getClass()).debug("{} links exported", count); } } catch (Exception e) { throw new IllegalStateException(format("Link export failed after processing %d link(s) successfully", count), e); } } @Override public String getDescription() { return "Export links"; } }
2,855
35.615385
143
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/steps/ExportLiveMeasuresStep.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.steps; import com.sonarsource.governance.projectdump.protobuf.ProjectDump; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.slf4j.LoggerFactory; import org.sonar.ce.task.projectexport.component.ComponentRepository; import org.sonar.ce.task.step.ComputationStep; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import static java.lang.String.format; import static org.apache.commons.lang.StringUtils.defaultString; import static org.sonar.db.DatabaseUtils.getDouble; import static org.sonar.db.DatabaseUtils.getString; public class ExportLiveMeasuresStep implements ComputationStep { private static final String QUERY = "select pm.metric_uuid, pm.component_uuid, pm.text_value, pm.value, m.name" + " from live_measures pm" + " join metrics m on m.uuid=pm.metric_uuid" + " join components p on p.uuid = pm.component_uuid" + " join components pp on pp.uuid = pm.project_uuid" + " join project_branches pb on pb.uuid=pp.uuid" + " where pb.project_uuid=? and pb.branch_type = 'BRANCH' and pb.exclude_from_purge=? and p.enabled=? and m.enabled=?"; private final DbClient dbClient; private final ProjectHolder projectHolder; private final ComponentRepository componentRepository; private final MutableMetricRepository metricHolder; private final DumpWriter dumpWriter; public ExportLiveMeasuresStep(DbClient dbClient, ProjectHolder projectHolder, ComponentRepository componentRepository, MutableMetricRepository metricHolder, DumpWriter dumpWriter) { this.dbClient = dbClient; this.projectHolder = projectHolder; this.componentRepository = componentRepository; this.metricHolder = metricHolder; this.dumpWriter = dumpWriter; } @Override public void execute(Context context) { long count = 0L; try ( StreamWriter<ProjectDump.LiveMeasure> output = dumpWriter.newStreamWriter(DumpElement.LIVE_MEASURES); DbSession dbSession = dbClient.openSession(false); PreparedStatement stmt = dbClient.getMyBatis().newScrollingSelectStatement(dbSession, QUERY)) { stmt.setString(1, projectHolder.projectDto().getUuid()); stmt.setBoolean(2, true); stmt.setBoolean(3, true); stmt.setBoolean(4, true); try (ResultSet rs = stmt.executeQuery()) { ProjectDump.LiveMeasure.Builder liveMeasureBuilder = ProjectDump.LiveMeasure.newBuilder(); ProjectDump.DoubleValue.Builder doubleBuilder = ProjectDump.DoubleValue.newBuilder(); while (rs.next()) { ProjectDump.LiveMeasure measure = convertToLiveMeasure(rs, liveMeasureBuilder, doubleBuilder); output.write(measure); count++; } LoggerFactory.getLogger(getClass()).debug("{} live measures exported", count); } } catch (Exception e) { throw new IllegalStateException(format("Live Measure Export failed after processing %d measures successfully", count), e); } } private ProjectDump.LiveMeasure convertToLiveMeasure(ResultSet rs, ProjectDump.LiveMeasure.Builder builder, ProjectDump.DoubleValue.Builder doubleBuilder) throws SQLException { long componentRef = componentRepository.getRef(rs.getString(2)); int metricRef = metricHolder.add(rs.getString(1)); builder .clear() .setMetricRef(metricRef) .setComponentRef(componentRef) .setTextValue(defaultString(getString(rs, 3))); Double value = getDouble(rs, 4); String metricKey = getString(rs, 5); if (value != null && metricKey != null) { if (metricKey.startsWith("new_")) { builder.setVariation(doubleBuilder.setValue(value).build()); } else { builder.setDoubleValue(doubleBuilder.setValue(value).build()); } } return builder.build(); } @Override public String getDescription() { return "Export live measures"; } }
4,763
40.789474
128
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/steps/ExportMeasuresStep.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.steps; import com.sonarsource.governance.projectdump.protobuf.ProjectDump; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.slf4j.LoggerFactory; import org.sonar.ce.task.projectexport.component.ComponentRepository; import org.sonar.ce.task.step.ComputationStep; import org.sonar.db.DatabaseUtils; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.SnapshotDto; import static java.lang.String.format; import static org.apache.commons.lang.StringUtils.defaultString; import static org.sonar.db.DatabaseUtils.getDouble; import static org.sonar.db.DatabaseUtils.getString; public class ExportMeasuresStep implements ComputationStep { private static final String QUERY = "select pm.metric_uuid, pm.analysis_uuid, pm.component_uuid, pm.text_value, pm.value," + " pm.alert_status, pm.alert_text, m.name" + " from project_measures pm" + " join metrics m on m.uuid=pm.metric_uuid" + " join snapshots s on s.uuid=pm.analysis_uuid" + " join components p on p.uuid=pm.component_uuid" + " join project_branches pb on pb.uuid=p.uuid" + " where pb.project_uuid=? and pb.branch_type = 'BRANCH' and pb.exclude_from_purge=?" + " and s.status=? and p.enabled=? and m.enabled=? and pm.person_id is null"; private final DbClient dbClient; private final ProjectHolder projectHolder; private final ComponentRepository componentRepository; private final MutableMetricRepository metricHolder; private final DumpWriter dumpWriter; public ExportMeasuresStep(DbClient dbClient, ProjectHolder projectHolder, ComponentRepository componentRepository, MutableMetricRepository metricHolder, DumpWriter dumpWriter) { this.dbClient = dbClient; this.projectHolder = projectHolder; this.componentRepository = componentRepository; this.metricHolder = metricHolder; this.dumpWriter = dumpWriter; } @Override public void execute(Context context) { long count = 0L; try ( StreamWriter<ProjectDump.Measure> output = dumpWriter.newStreamWriter(DumpElement.MEASURES); DbSession dbSession = dbClient.openSession(false); PreparedStatement stmt = createSelectStatement(dbSession); ResultSet rs = stmt.executeQuery()) { ProjectDump.Measure.Builder measureBuilder = ProjectDump.Measure.newBuilder(); ProjectDump.DoubleValue.Builder doubleBuilder = ProjectDump.DoubleValue.newBuilder(); while (rs.next()) { ProjectDump.Measure measure = convertToMeasure(rs, measureBuilder, doubleBuilder); output.write(measure); count++; } LoggerFactory.getLogger(getClass()).debug("{} measures exported", count); } catch (Exception e) { throw new IllegalStateException(format("Measure Export failed after processing %d measures successfully", count), e); } } private PreparedStatement createSelectStatement(DbSession dbSession) throws SQLException { PreparedStatement stmt = dbClient.getMyBatis().newScrollingSelectStatement(dbSession, QUERY); try { stmt.setString(1, projectHolder.projectDto().getUuid()); stmt.setBoolean(2, true); stmt.setString(3, SnapshotDto.STATUS_PROCESSED); stmt.setBoolean(4, true); stmt.setBoolean(5, true); return stmt; } catch (Exception t) { DatabaseUtils.closeQuietly(stmt); throw t; } } private ProjectDump.Measure convertToMeasure(ResultSet rs, ProjectDump.Measure.Builder builder, ProjectDump.DoubleValue.Builder doubleBuilder) throws SQLException { long componentRef = componentRepository.getRef(rs.getString(3)); int metricRef = metricHolder.add(rs.getString(1)); String metricKey = rs.getString(8); builder .clear() .setMetricRef(metricRef) .setAnalysisUuid(rs.getString(2)) .setComponentRef(componentRef) .setTextValue(defaultString(getString(rs, 4))); Double value = getDouble(rs, 5); if (value != null) { if (metricKey.startsWith("new_")) { builder.setVariation1(doubleBuilder.setValue(value).build()); } else { builder.setDoubleValue(doubleBuilder.setValue(value).build()); } } builder.setAlertStatus(defaultString(getString(rs, 6))); builder.setAlertText(defaultString(getString(rs, 7))); return builder.build(); } @Override public String getDescription() { return "Export measures"; } }
5,322
38.723881
154
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/steps/ExportMetricsStep.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.steps; import com.sonarsource.governance.projectdump.protobuf.ProjectDump; import java.util.List; import java.util.Map; import org.slf4j.LoggerFactory; import org.sonar.ce.task.step.ComputationStep; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.metric.MetricDto; import static java.lang.String.format; import static org.apache.commons.lang.StringUtils.defaultString; public class ExportMetricsStep implements ComputationStep { private final DbClient dbClient; private final MetricRepository metricsHolder; private final DumpWriter dumpWriter; public ExportMetricsStep(DbClient dbClient, MetricRepository metricsHolder, DumpWriter dumpWriter) { this.dbClient = dbClient; this.metricsHolder = metricsHolder; this.dumpWriter = dumpWriter; } @Override public void execute(Context context) { int count = 0; try ( StreamWriter<ProjectDump.Metric> output = dumpWriter.newStreamWriter(DumpElement.METRICS); DbSession dbSession = dbClient.openSession(false)) { ProjectDump.Metric.Builder builder = ProjectDump.Metric.newBuilder(); Map<String, Integer> refByUuid = metricsHolder.getRefByUuid(); List<MetricDto> dtos = dbClient.metricDao().selectByUuids(dbSession, refByUuid.keySet()); for (MetricDto dto : dtos) { builder .clear() .setRef(refByUuid.get(dto.getUuid())) .setKey(dto.getKey()) .setName(defaultString(dto.getShortName())); output.write(builder.build()); count++; } LoggerFactory.getLogger(getClass()).debug("{} metrics exported", count); } catch (Exception e) { throw new IllegalStateException(format("Metric Export failed after processing %d metrics successfully", count), e); } } @Override public String getDescription() { return "Export metrics"; } }
2,755
35.263158
121
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/steps/ExportNewCodePeriodsStep.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.steps; import com.sonarsource.governance.projectdump.protobuf.ProjectDump; import java.util.List; import org.slf4j.LoggerFactory; import org.sonar.ce.task.step.ComputationStep; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.newcodeperiod.NewCodePeriodDto; import org.sonar.db.project.ProjectExportMapper; import static java.lang.String.format; public class ExportNewCodePeriodsStep implements ComputationStep { private final DbClient dbClient; private final ProjectHolder projectHolder; private final DumpWriter dumpWriter; public ExportNewCodePeriodsStep(DbClient dbClient, ProjectHolder projectHolder, DumpWriter dumpWriter) { this.dbClient = dbClient; this.projectHolder = projectHolder; this.dumpWriter = dumpWriter; } @Override public void execute(Context context) { long count = 0L; try ( StreamWriter<ProjectDump.NewCodePeriod> output = dumpWriter.newStreamWriter(DumpElement.NEW_CODE_PERIODS); DbSession dbSession = dbClient.openSession(false)) { final ProjectDump.NewCodePeriod.Builder builder = ProjectDump.NewCodePeriod.newBuilder(); final List<NewCodePeriodDto> newCodePeriods = dbSession.getMapper(ProjectExportMapper.class) .selectNewCodePeriodsForExport(projectHolder.projectDto().getUuid()); for (NewCodePeriodDto newCodePeriod : newCodePeriods) { builder.clear() .setUuid(newCodePeriod.getUuid()) .setProjectUuid(newCodePeriod.getProjectUuid()) .setType(newCodePeriod.getType().name()); if (newCodePeriod.getBranchUuid() != null) { builder.setBranchUuid(newCodePeriod.getBranchUuid()); } if (newCodePeriod.getValue() != null) { builder.setValue(newCodePeriod.getValue()); } output.write(builder.build()); ++count; } LoggerFactory.getLogger(getClass()).debug("{} new code periods exported", count); } catch (Exception e) { throw new IllegalStateException(format("New Code Periods Export failed after processing %d new code periods successfully", count), e); } } @Override public String getDescription() { return "Export new code periods"; } }
3,103
36.39759
140
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/steps/ExportPluginsStep.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.steps; import com.sonarsource.governance.projectdump.protobuf.ProjectDump; import java.util.Collection; import org.apache.commons.lang.StringUtils; import org.slf4j.LoggerFactory; import org.sonar.ce.task.step.ComputationStep; import org.sonar.core.platform.PluginInfo; import org.sonar.core.platform.PluginRepository; import org.sonar.updatecenter.common.Version; public class ExportPluginsStep implements ComputationStep { private final PluginRepository pluginRepository; private final DumpWriter dumpWriter; public ExportPluginsStep(PluginRepository pluginRepository, DumpWriter dumpWriter) { this.pluginRepository = pluginRepository; this.dumpWriter = dumpWriter; } @Override public void execute(Context context) { try (StreamWriter<ProjectDump.Plugin> writer = dumpWriter.newStreamWriter(DumpElement.PLUGINS)) { Collection<PluginInfo> plugins = pluginRepository.getPluginInfos(); for (PluginInfo plugin : plugins) { ProjectDump.Plugin.Builder builder = ProjectDump.Plugin.newBuilder(); writer.write(convert(plugin, builder)); } LoggerFactory.getLogger(getClass()).debug("{} plugins exported", plugins.size()); } } private static ProjectDump.Plugin convert(PluginInfo plugin, ProjectDump.Plugin.Builder builder) { builder .clear() .setKey(plugin.getKey()) .setName(StringUtils.defaultString(plugin.getName())); Version version = plugin.getVersion(); if (version != null) { builder.setVersion(version.toString()); } return builder.build(); } @Override public String getDescription() { return "Export plugins"; } }
2,536
34.732394
101
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/steps/ExportSettingsStep.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.steps; import com.sonarsource.governance.projectdump.protobuf.ProjectDump; import java.util.List; import java.util.Set; import org.slf4j.LoggerFactory; import org.sonar.ce.task.step.ComputationStep; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.project.ProjectExportMapper; import org.sonar.db.property.PropertyDto; import static java.lang.String.format; import static org.apache.commons.lang.StringUtils.defaultString; public class ExportSettingsStep implements ComputationStep { /** * These properties are not exported as values depend on environment data that are not * exported within the dump (Quality Gate, users). */ private static final Set<String> IGNORED_KEYS = Set.of("sonar.issues.defaultAssigneeLogin"); private final DbClient dbClient; private final ProjectHolder projectHolder; private final DumpWriter dumpWriter; public ExportSettingsStep(DbClient dbClient, ProjectHolder projectHolder,DumpWriter dumpWriter) { this.dbClient = dbClient; this.projectHolder = projectHolder; this.dumpWriter = dumpWriter; } @Override public void execute(Context context) { long count = 0L; try ( StreamWriter<ProjectDump.Setting> output = dumpWriter.newStreamWriter(DumpElement.SETTINGS); DbSession dbSession = dbClient.openSession(false)) { final ProjectDump.Setting.Builder builder = ProjectDump.Setting.newBuilder(); final List<PropertyDto> properties = dbSession.getMapper(ProjectExportMapper.class).selectPropertiesForExport(projectHolder.projectDto().getUuid()) .stream() .filter(dto -> dto.getEntityUuid() != null) .filter(dto -> !IGNORED_KEYS.contains(dto.getKey())) .toList(); for (PropertyDto property : properties) { builder.clear() .setKey(property.getKey()) .setValue(defaultString(property.getValue())); output.write(builder.build()); ++count; } LoggerFactory.getLogger(getClass()).debug("{} settings exported", count); } catch (Exception e) { throw new IllegalStateException(format("Settings Export failed after processing %d settings successfully", count), e); } } @Override public String getDescription() { return "Export settings"; } }
3,171
36.317647
153
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/steps/LoadProjectStep.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.steps; import java.util.List; import org.sonar.api.utils.MessageException; import org.sonar.ce.task.projectexport.taskprocessor.ProjectDescriptor; import org.sonar.ce.task.step.ComputationStep; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.BranchDto; import org.sonar.db.project.ProjectDto; import static java.lang.String.format; /** * Loads project from database and verifies that it's valid: it must exist and be a project ! */ public class LoadProjectStep implements ComputationStep { private final ProjectDescriptor descriptor; private final MutableProjectHolder definitionHolder; private final DbClient dbClient; public LoadProjectStep(ProjectDescriptor descriptor, MutableProjectHolder definitionHolder, DbClient dbClient) { this.descriptor = descriptor; this.definitionHolder = definitionHolder; this.dbClient = dbClient; } @Override public void execute(Context context) { try (DbSession dbSession = dbClient.openSession(false)) { ProjectDto project = dbClient.projectDao().selectProjectByKey(dbSession, descriptor.getKey()) .orElseThrow(() -> MessageException.of(format("Project with key [%s] does not exist", descriptor.getKey()))); definitionHolder.setProjectDto(project); List<BranchDto> branches = dbClient.branchDao().selectByProject(dbSession, project).stream().toList(); definitionHolder.setBranches(branches); } } @Override public String getDescription() { return "Load project"; } }
2,420
35.681818
117
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/steps/MessageStream.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.steps; import com.google.protobuf.Message; public interface MessageStream<M extends Message> extends Iterable<M>, AutoCloseable { @Override void close(); }
1,047
33.933333
86
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/steps/MessageStreamImpl.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.steps; import com.google.protobuf.Message; import com.google.protobuf.Parser; import java.io.BufferedInputStream; import java.io.InputStream; import java.util.Iterator; import javax.annotation.CheckForNull; import org.sonar.api.utils.System2; import org.sonar.core.util.CloseableIterator; import static org.sonar.ce.task.util.Protobuf2.PROTOBUF2; public class MessageStreamImpl<M extends Message> implements MessageStream<M> { private final InputStream input; private final Parser<M> parser; public MessageStreamImpl(InputStream input, Parser<M> parser) { this.input = new BufferedInputStream(input); this.parser = parser; } @Override public Iterator<M> iterator() { return new StreamMessagesIterator(); } @Override public void close() { System2.INSTANCE.close(input); } private class StreamMessagesIterator extends CloseableIterator<M> { @CheckForNull @Override protected M doNext() { return PROTOBUF2.parseDelimitedFrom(parser, input); } @Override protected void doClose() { // no need, already handled by method close() of outer class } } }
2,016
29.560606
79
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/steps/MetricRepository.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.steps; import java.util.Map; /** * Database uuids of the metrics related to exported measures. */ public interface MetricRepository { /** * @return map of db uuids */ Map<String, Integer> getRefByUuid(); }
1,104
31.5
75
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/steps/MutableDumpReader.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.steps; import java.io.File; public interface MutableDumpReader extends DumpReader { void setZipFile(File file); void setTempRootDir(File d); }
1,033
34.655172
75
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/steps/MutableDumpReaderImpl.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.steps; import com.google.protobuf.Message; import com.sonarsource.governance.projectdump.protobuf.ProjectDump; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static org.sonar.ce.task.projectexport.steps.DumpElement.METADATA; import static org.sonar.ce.task.util.Files2.FILES2; import static org.sonar.ce.task.util.Protobuf2.PROTOBUF2; public class MutableDumpReaderImpl implements MutableDumpReader { private File zipFile = null; private File tempRootDir = null; @Override public void setZipFile(File file) { checkNotNull(file, "Project dump file can not be null"); checkArgument(file.exists(), "Project dump file does not exist: %s", file); checkArgument(file.isFile(), "Project dump is not a file: %s", file); this.zipFile = file; } @Override public void setTempRootDir(File d) { checkNotNull(d, "Dump extraction directory can not be null"); checkArgument(d.exists(), "Dump extraction directory does not exist: %s", d); checkArgument(d.isDirectory(), "Dump extraction is not a directory: %s", d); this.tempRootDir = d; } @Override public File zipFile() { checkState(zipFile != null, "Project dump file has not been set"); return zipFile; } @Override public File tempRootDir() { checkState(tempRootDir != null, "Dump file has not been extracted"); return tempRootDir; } @Override public ProjectDump.Metadata metadata() { File file = new File(tempRootDir(), METADATA.filename()); checkState(file.exists(), "Missing metadata file: %s", file); try (FileInputStream input = FILES2.openInputStream(file)) { return PROTOBUF2.parseFrom(METADATA.parser(), input); } catch (IOException e) { throw new IllegalStateException("Can not read file " + file, e); } } @Override public <M extends Message> MessageStream<M> stream(DumpElement<M> elt) { File file = new File(tempRootDir(), elt.filename()); checkState(file.exists(), "Missing file: %s", file); InputStream input = FILES2.openInputStream(file); return new MessageStreamImpl<>(input, elt.parser()); } }
3,241
35.426966
81
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/steps/MutableMetricRepository.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.steps; public interface MutableMetricRepository extends MetricRepository { int add(String metricUuid); }
993
35.814815
75
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/steps/MutableMetricRepositoryImpl.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.steps; import java.util.HashMap; import java.util.Map; public class MutableMetricRepositoryImpl implements MutableMetricRepository { private final Map<String, Integer> refByUuid = new HashMap<>(); private int ref = 0; @Override public Map<String, Integer> getRefByUuid() { return refByUuid; } @Override public int add(String metricUuid) { return refByUuid.computeIfAbsent(metricUuid, uuid -> ref++); } }
1,316
31.925
77
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/steps/MutableProjectHolder.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.steps; import java.util.List; import org.sonar.db.component.BranchDto; import org.sonar.db.project.ProjectDto; public interface MutableProjectHolder extends ProjectHolder { void setProjectDto(ProjectDto dto); void setBranches(List<BranchDto> branches); }
1,146
34.84375
75
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/steps/MutableProjectHolderImpl.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.steps; import java.util.Collections; import java.util.List; import org.sonar.db.component.BranchDto; import org.sonar.db.project.ProjectDto; import static com.google.common.collect.ImmutableList.copyOf; import static java.util.Objects.requireNonNull; public class MutableProjectHolderImpl implements MutableProjectHolder { private ProjectDto projectDto = null; private List<BranchDto> branches = Collections.emptyList(); @Override public void setProjectDto(ProjectDto dto) { requireNonNull(dto, "Project must not be null"); this.projectDto = dto; } @Override public void setBranches(List<BranchDto> branches) { requireNonNull(branches, "Branches must not be null"); this.branches = copyOf(branches); } @Override public ProjectDto projectDto() { requireNonNull(projectDto, "Project has not been loaded yet"); return projectDto; } @Override public List<BranchDto> branches() { return branches; } }
1,844
30.271186
75
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/steps/ProjectHolder.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.steps; import java.util.List; import org.sonar.db.component.BranchDto; import org.sonar.db.project.ProjectDto; public interface ProjectHolder { ProjectDto projectDto(); List<BranchDto> branches(); }
1,090
33.09375
75
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/steps/PublishDumpStep.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.steps; import org.sonar.ce.task.step.ComputationStep; /** * Zips the dump file and makes it available to users. */ public class PublishDumpStep implements ComputationStep { private final DumpWriter dumpWriter; public PublishDumpStep(DumpWriter dumpWriter) { this.dumpWriter = dumpWriter; } @Override public void execute(Context context) { dumpWriter.publish(); } @Override public String getDescription() { return "Publish dump file"; } }
1,360
29.244444
75
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/steps/StreamWriter.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.steps; import com.google.protobuf.Message; public interface StreamWriter<M extends Message> extends AutoCloseable { void write(M msg); @Override void close(); }
1,053
34.133333
75
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/steps/StreamWriterImpl.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.steps; import com.google.protobuf.Message; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import org.sonar.api.utils.System2; import static org.sonar.ce.task.util.Files2.FILES2; import static org.sonar.ce.task.util.Protobuf2.PROTOBUF2; public class StreamWriterImpl<M extends Message> implements StreamWriter<M> { private final OutputStream output; private StreamWriterImpl(OutputStream output) { this.output = new BufferedOutputStream(output); } @Override public void write(M message) { PROTOBUF2.writeDelimitedTo(message, output); } @Override public void close() { System2.INSTANCE.close(output); } public static <M extends Message> StreamWriterImpl<M> create(File file) { FileOutputStream output = FILES2.openOutputStream(file, true); return new StreamWriterImpl<>(output); } }
1,787
31.509091
77
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/steps/WriteMetadataStep.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.steps; import com.sonarsource.governance.projectdump.protobuf.ProjectDump; import org.sonar.api.utils.System2; import org.sonar.ce.task.step.ComputationStep; import org.sonar.core.platform.SonarQubeVersion; public class WriteMetadataStep implements ComputationStep { private final System2 system2; private final DumpWriter dumpWriter; private final ProjectHolder projectHolder; private final SonarQubeVersion sonarQubeVersion; public WriteMetadataStep(System2 system2, DumpWriter dumpWriter, ProjectHolder projectHolder, SonarQubeVersion sonarQubeVersion) { this.system2 = system2; this.dumpWriter = dumpWriter; this.projectHolder = projectHolder; this.sonarQubeVersion = sonarQubeVersion; } @Override public void execute(Context context) { dumpWriter.write(ProjectDump.Metadata.newBuilder() .setProjectKey(projectHolder.projectDto().getKey()) .setProjectUuid(projectHolder.projectDto().getUuid()) .setSonarqubeVersion(sonarQubeVersion.get().toString()) .setDumpDate(system2.now()) .build()); } @Override public String getDescription() { return "Write metadata"; } }
2,034
35.339286
132
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/steps/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.ce.task.projectexport.steps; import javax.annotation.ParametersAreNonnullByDefault;
977
39.75
75
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/taskprocessor/ProjectDescriptor.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.taskprocessor; import java.util.Objects; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import org.sonar.db.project.ProjectDto; import static java.util.Objects.requireNonNull; @Immutable public class ProjectDescriptor { private final String uuid; private final String key; private final String name; public ProjectDescriptor(String uuid, String key, String name) { this.uuid = requireNonNull(uuid); this.key = requireNonNull(key); this.name = requireNonNull(name); } /** * Build a {@link ProjectDescriptor} without checking qualifier of ComponentDto. */ public static ProjectDescriptor of(ProjectDto project) { return new ProjectDescriptor(project.getUuid(), project.getKey(), project.getName()); } public final String getUuid() { return uuid; } public final String getKey() { return key; } public final String getName() { return name; } @Override public final boolean equals(@Nullable Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ProjectDescriptor that = (ProjectDescriptor) o; return key.equals(that.key); } @Override public final int hashCode() { return Objects.hash(key); } @Override public final String toString() { return getClass().getSimpleName() + "{" + "uuid='" + uuid + '\'' + ", key='" + key + '\'' + ", name='" + name + '\'' + '}'; } }
2,386
26.755814
89
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/taskprocessor/ProjectExportTaskProcessor.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.taskprocessor; import java.util.Set; import org.sonar.ce.task.CeTask; import org.sonar.ce.task.CeTaskResult; import org.sonar.ce.task.container.TaskContainer; import org.sonar.ce.task.container.TaskContainerImpl; import org.sonar.ce.task.projectexport.ProjectExportContainerPopulator; import org.sonar.ce.task.projectexport.ProjectExportProcessor; import org.sonar.ce.task.taskprocessor.CeTaskProcessor; import org.sonar.core.platform.SpringComponentContainer; import static org.sonar.db.ce.CeTaskTypes.PROJECT_EXPORT; public class ProjectExportTaskProcessor implements CeTaskProcessor { private final SpringComponentContainer componentContainer; public ProjectExportTaskProcessor(SpringComponentContainer componentContainer) { this.componentContainer = componentContainer; } @Override public Set<String> getHandledCeTaskTypes() { return Set.of(PROJECT_EXPORT); } @Override public CeTaskResult process(CeTask task) { processProjectExport(task); return null; } private void processProjectExport(CeTask task) { CeTask.Component exportComponent = mandatoryComponent(task, PROJECT_EXPORT); failIfNotMain(exportComponent, task); ProjectDescriptor projectExportDescriptor = new ProjectDescriptor(exportComponent.getUuid(), mandatoryKey(exportComponent), mandatoryName(exportComponent)); try (TaskContainer taskContainer = new TaskContainerImpl(componentContainer, new ProjectExportContainerPopulator(projectExportDescriptor))) { taskContainer.bootup(); taskContainer.getComponentByType(ProjectExportProcessor.class).process(); } } private static void failIfNotMain(CeTask.Component exportComponent, CeTask task) { task.getEntity().filter(entity -> entity.equals(exportComponent)) .orElseThrow(() -> new IllegalStateException("Component of task must be the same as entity")); } private static CeTask.Component mandatoryComponent(CeTask task, String type) { return task.getComponent().orElseThrow(() -> new IllegalStateException(String.format("Task with type %s must have a component", type))); } private static String mandatoryKey(CeTask.Component component) { return component.getKey().orElseThrow(() -> new IllegalStateException("Task component must have a key")); } private static String mandatoryName(CeTask.Component component) { return component.getName().orElseThrow(() -> new IllegalStateException("Task component must have a name")); } }
3,357
38.97619
140
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/taskprocessor/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.ce.task.projectexport.taskprocessor; import javax.annotation.ParametersAreNonnullByDefault;
985
40.083333
75
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/util/ProjectExportDumpFS.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.util; import java.io.File; import org.sonar.ce.task.projectexport.taskprocessor.ProjectDescriptor; public interface ProjectExportDumpFS { /** * Create a File representing the exported dump of the specified {@link ProjectDescriptor}. * <p> * This method doesn't check nor enforce the File actually exist and/or is a regular file. * </p> */ File exportDumpOf(ProjectDescriptor descriptor); }
1,295
36.028571
93
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/util/ProjectExportDumpFSImpl.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.util; import java.io.File; import org.sonar.api.Startable; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.config.Configuration; import org.sonar.api.server.ServerSide; import org.sonar.ce.task.projectexport.taskprocessor.ProjectDescriptor; import org.sonar.ce.task.util.Files2; import static org.sonar.core.util.Slug.slugify; import static org.sonar.process.ProcessProperties.Property.PATH_DATA; @ServerSide @ComputeEngineSide public class ProjectExportDumpFSImpl implements ProjectExportDumpFS, Startable { private static final String GOVERNANCE_DIR_NAME = "governance"; private static final String PROJECT_DUMPS_DIR_NAME = "project_dumps"; private static final String DUMP_FILE_EXTENSION = ".zip"; private final File exportDir; public ProjectExportDumpFSImpl(Configuration config) { String dataPath = config.get(PATH_DATA.getKey()).get(); File governanceDir = new File(dataPath, GOVERNANCE_DIR_NAME); File projectDumpDir = new File(governanceDir, PROJECT_DUMPS_DIR_NAME); this.exportDir = new File(projectDumpDir, "export"); } @Override public void start() { Files2.FILES2.createDir(exportDir); } @Override public void stop() { // nothing to do } @Override public File exportDumpOf(ProjectDescriptor descriptor) { String fileName = slugify(descriptor.getKey()) + DUMP_FILE_EXTENSION; return new File(exportDir, fileName); } }
2,298
34.369231
80
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/util/ProjectImportDumpFS.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.util; import java.io.File; import org.sonar.ce.task.projectexport.taskprocessor.ProjectDescriptor; public interface ProjectImportDumpFS { /** * Create a File representing the archive dump of the specified {@link ProjectDescriptor} to be imported. * <p> * This method doesn't check nor enforce the File actually exist and/or is a regular file. * </p> */ File importDumpOf(ProjectDescriptor descriptor); }
1,309
36.428571
107
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/util/ProjectImportDumpFSImpl.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.util; import java.io.File; import org.sonar.api.Startable; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.config.Configuration; import org.sonar.api.server.ServerSide; import org.sonar.ce.task.projectexport.taskprocessor.ProjectDescriptor; import org.sonar.ce.task.util.Files2; import static org.sonar.core.util.Slug.slugify; import static org.sonar.process.ProcessProperties.Property.PATH_DATA; @ServerSide @ComputeEngineSide public class ProjectImportDumpFSImpl implements ProjectImportDumpFS, Startable { private static final String GOVERNANCE_DIR_NAME = "governance"; private static final String PROJECT_DUMPS_DIR_NAME = "project_dumps"; private static final String DUMP_FILE_EXTENSION = ".zip"; private final File importDir; public ProjectImportDumpFSImpl(Configuration config) { String dataPath = config.get(PATH_DATA.getKey()).get(); File governanceDir = new File(dataPath, GOVERNANCE_DIR_NAME); File projectDumpDir = new File(governanceDir, PROJECT_DUMPS_DIR_NAME); this.importDir = new File(projectDumpDir, "import"); } @Override public void start() { Files2.FILES2.createDir(importDir); } @Override public void stop() { // nothing to do } @Override public File importDumpOf(ProjectDescriptor descriptor) { String fileName = slugify(descriptor.getKey()) + DUMP_FILE_EXTENSION; return new File(importDir, fileName); } }
2,299
33.848485
80
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/util/ResultSetUtils.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.util; import java.sql.ResultSet; import java.sql.SQLException; public final class ResultSetUtils { private ResultSetUtils() { // prevents instantiation } public static int defaultIfNull(ResultSet rs, int columnIndex, int defaultValue) throws SQLException { int value = rs.getInt(columnIndex); if (rs.wasNull()) { return defaultValue; } return value; } public static double defaultIfNull(ResultSet rs, int columnIndex, double defaultValue) throws SQLException { double value = rs.getDouble(columnIndex); if (rs.wasNull()) { return defaultValue; } return value; } public static long defaultIfNull(ResultSet rs, int columnIndex, long defaultValue) throws SQLException { long value = rs.getLong(columnIndex); if (rs.wasNull()) { return defaultValue; } return value; } public static String emptyIfNull(ResultSet rs, int columnIndex) throws SQLException { String value = rs.getString(columnIndex); if (value == null) { return ""; } return value; } }
1,945
30.387097
110
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectexport/util/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.ce.task.projectexport.util; import javax.annotation.ParametersAreNonnullByDefault;
976
39.708333
75
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/util/Files2.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.util; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import javax.annotation.Nullable; import org.sonar.api.utils.ZipUtils; import org.sonar.core.util.FileUtils; import static com.google.common.base.Preconditions.checkState; import static java.lang.String.format; import static java.nio.file.Files.createDirectories; import static java.util.Objects.requireNonNull; /** * This utility class provides Java NIO based replacement for some methods of * {@link org.apache.commons.io.FileUtils Common IO FileUtils} class. * Only the methods which name ends with {@code "orThrowIOE"} may raise {@link IOException}. * Others wrap checked exceptions into {@link IllegalStateException}. */ public class Files2 { public static final Files2 FILES2 = new Files2(); private Files2() { // use FILES2 singleton } /** * Deletes a directory or a file if it exists, else does nothing. In the case * of a directly, it is deleted recursively. * * @param fileOrDir file or directory to delete * @throws IOException in case deletion is unsuccessful */ public void deleteIfExistsOrThrowIOE(File fileOrDir) throws IOException { if (!fileOrDir.exists()) { return; } if (fileOrDir.isDirectory()) { FileUtils.deleteDirectory(fileOrDir); } else { Files.delete(fileOrDir.toPath()); } } /** * Like {@link #deleteIfExistsOrThrowIOE(File)} but wraps {@link IOException} * into {@link IllegalStateException}. * * @throws IllegalStateException in case deletion is unsuccessful */ public void deleteIfExists(File fileOrDir) { try { deleteIfExistsOrThrowIOE(fileOrDir); } catch (IOException e) { throw new IllegalStateException("Can not delete " + fileOrDir, e); } } /** * Deletes a directory or a file if it exists, else does nothing. In the case * of a directly, it is deleted recursively. Any exception is trapped and * ignored. * * @param fileOrDir file or directory to delete. Can be {@code null}. */ public void deleteQuietly(@Nullable File fileOrDir) { FileUtils.deleteQuietly(fileOrDir); } /** * Moves a file. * * <p> * When the destination file is on another file system, do a "copy and delete". * </p> * * @param from the file to be moved * @param to the destination file * @throws NullPointerException if source or destination is {@code null} * @throws IOException if the destination file exists * @throws IOException if source or destination is invalid * @throws IOException if an IO error occurs moving the file */ public void moveFileOrThrowIOE(File from, File to) throws IOException { org.apache.commons.io.FileUtils.moveFile(from, to); } /** * Like {@link #moveFileOrThrowIOE(File, File)} but wraps {@link IOException} * into {@link IllegalStateException}. * * @param from the file to be moved * @param to the destination file * @throws IllegalStateException if the destination file exists * @throws IllegalStateException if source or destination is invalid * @throws IllegalStateException if an IO error occurs moving the file */ public void moveFile(File from, File to) { try { moveFileOrThrowIOE(from, to); } catch (IOException e) { throw new IllegalStateException("Can not move file " + from + " to " + to, e); } } /** * Opens a {@link FileOutputStream} for the specified file, checking and * creating the parent directory if it does not exist. * <p> * The parent directory will be created if it does not exist. * The file will be created if it does not exist. * * @param file the file to open for output, must not be {@code null} * @param append if {@code true}, then bytes will be added to the * end of the file rather than overwriting * @return a new {@link FileOutputStream} for the specified file * @throws IOException if the specified file is a directory * @throws IOException if the file can not be written to * @throws IOException if a parent directory can not be created */ public FileOutputStream openOutputStreamOrThrowIOE(File file, boolean append) throws IOException { if (file.exists()) { checkOrThrowIOE(!file.isDirectory(), "File %s exists but is a directory", file); checkOrThrowIOE(file.canWrite(), "File %s can not be written to", file); } else { File parent = file.getParentFile(); if (parent != null && !parent.mkdirs() && !parent.isDirectory()) { throw new IOException("Directory " + parent + " could not be created"); } } return new FileOutputStream(file, append); } /** * Opens a {@link FileOutputStream} for the specified file, checking and * creating the parent directory if it does not exist. * <p> * The parent directory will be created if it does not exist. * The file will be created if it does not exist. * * @param file the file to open for output, must not be {@code null} * @param append if {@code true}, then bytes will be added to the * end of the file rather than overwriting * @return a new {@link FileOutputStream} for the specified file * @throws IllegalStateException if the specified file is a directory * @throws IllegalStateException if the file can not be written to * @throws IllegalStateException if a parent directory can not be created */ public FileOutputStream openOutputStream(File file, boolean append) { try { return openOutputStreamOrThrowIOE(file, append); } catch (IOException e) { throw new IllegalStateException("Can not open file " + file, e); } } /** * Opens a {@link FileInputStream} for the specified file, providing better * error messages than simply calling {@code new FileInputStream(file)}. * * @param file the file to open, must not be {@code null} * @return a new {@link FileInputStream} for the specified file * @throws IOException if the file does not exist * @throws IOException if the specified file is a directory * @throws IOException if the file can not be read */ public FileInputStream openInputStreamOrThrowIOE(File file) throws IOException { checkOrThrowIOE(!file.isDirectory(), "File %s exists but is a directory", file); checkOrThrowIOE(file.exists(), "File %s does not exist", file); checkOrThrowIOE(file.canRead(), "File %s can not be read", file); return new FileInputStream(file); } /** * Opens a {@link FileInputStream} for the specified file, providing better * error messages than simply calling {@code new FileInputStream(file)}. * * @param file the file to open, must not be {@code null} * @return a new {@link FileInputStream} for the specified file * @throws IllegalStateException if the file does not exist * @throws IllegalStateException if the specified file is a directory * @throws IllegalStateException if the file can not be read */ public FileInputStream openInputStream(File file) { try { return openInputStreamOrThrowIOE(file); } catch (IOException e) { throw new IllegalStateException("Can not open file " + file, e); } } /** * Unzips a file to the specified directory. The directory is created if it does not exist. * * @throws IOException if {@code zipFile} is a directory * @throws IOException if {@code zipFile} does not exist * @throws IOException if {@code toDir} can not be created */ public void unzipToDirOrThrowIOE(File zipFile, File toDir) throws IOException { checkOrThrowIOE(!zipFile.isDirectory(), "File %s exists but is a directory", zipFile); checkOrThrowIOE(zipFile.exists(), "File %s does not exist", zipFile); ZipUtils.unzip(zipFile, toDir); } /** * Unzips a file to the specified directory. The directory is created if it does not exist. * * @throws IllegalStateException if {@code zipFile} is a directory * @throws IllegalStateException if {@code zipFile} does not exist * @throws IllegalStateException if {@code toDir} can not be created */ public void unzipToDir(File zipFile, File toDir) { try { unzipToDirOrThrowIOE(zipFile, toDir); } catch (IOException e) { throw new IllegalStateException("Can not unzip file " + zipFile + " to directory " + toDir, e); } } /** * Zips the directory {@code dir} to the file {@code toFile}. If {@code toFile} is overridden * if it exists, else it is created. * * @throws IllegalStateException if {@code dir} is a not directory * @throws IllegalStateException if {@code dir} does not exist * @throws IllegalStateException if {@code toFile} can not be created */ public void zipDirOrThrowIOE(File dir, File toFile) throws IOException { checkOrThrowIOE(dir.exists(), "Directory %s does not exist", dir); checkOrThrowIOE(dir.isDirectory(), "File %s exists but is not a directory", dir); ZipUtils.zipDir(dir, toFile); } /** * Zips the directory {@code dir} to the file {@code toFile}. If {@code toFile} is overridden * if it exists, else it is created. * * @throws IllegalStateException if {@code dir} is a not directory * @throws IllegalStateException if {@code dir} does not exist * @throws IllegalStateException if {@code toFile} can not be created */ public void zipDir(File dir, File toFile) { try { zipDirOrThrowIOE(dir, toFile); } catch (IOException e) { throw new IllegalStateException("Can not zip directory " + dir + " to file " + toFile, e); } } /** * Creates specified directory if it does not exist yet and any non existing parent. * * @throws IllegalStateException if specified File exists but is not a directory * @throws IllegalStateException if directory creation failed */ public void createDir(File dir) { Path dirPath = requireNonNull(dir, "dir can not be null").toPath(); if (dirPath.toFile().exists()) { checkState(dirPath.toFile().isDirectory(), "%s is not a directory", dirPath); } else { try { createDirectories(dirPath); } catch (IOException e) { throw new IllegalStateException(format("Failed to create directory %s", dirPath), e); } } } private static void checkOrThrowIOE(boolean expression, @Nullable String errorMessageTemplate, @Nullable Object... errorMessageArgs) throws IOException { if (!expression) { throw new IOException(format(errorMessageTemplate, errorMessageArgs)); } } }
11,475
37.381271
155
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/util/Protobuf2.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.util; import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.Message; import com.google.protobuf.Parser; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.annotation.CheckForNull; public class Protobuf2 { public static final Protobuf2 PROTOBUF2 = new Protobuf2(); private Protobuf2() { } public Protobuf2 writeTo(Message msg, OutputStream output) { try { msg.writeTo(output); } catch (IOException e) { throw new IllegalStateException("Can not write message " + msg, e); } return this; } public Protobuf2 writeDelimitedTo(Message msg, OutputStream output) { try { msg.writeDelimitedTo(output); } catch (IOException e) { throw new IllegalStateException("Can not write message " + msg, e); } return this; } public <M extends Message> M parseFrom(Parser<M> parser, InputStream input) { try { return parser.parseFrom(input); } catch (InvalidProtocolBufferException e) { throw new IllegalStateException("Can not parse message", e); } } @CheckForNull public <M extends Message> M parseDelimitedFrom(Parser<M> parser, InputStream input) { try { return parser.parseDelimitedFrom(input); } catch (InvalidProtocolBufferException e) { throw new IllegalStateException("Can not parse message", e); } } }
2,274
30.597222
88
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/util/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.util; import javax.annotation.ParametersAreNonnullByDefault;
962
39.125
75
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/analysis/AnalysisFromSonarQube94VisitorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.analysis; import org.junit.Before; import org.junit.Test; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.PathAwareVisitor; import org.sonar.ce.task.projectanalysis.component.ReportAttributes; 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 org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.sonar.ce.task.projectanalysis.analysis.AnalysisFromSonarQube94Visitor.AnalysisFromSonarQube94; import static org.sonar.ce.task.projectanalysis.analysis.AnalysisFromSonarQube94Visitor.AnalysisFromSonarQube94StackFactory; import static org.sonar.ce.task.projectanalysis.component.Component.Type.FILE; import static org.sonar.ce.task.projectanalysis.component.ComponentImpl.builder; public class AnalysisFromSonarQube94VisitorTest { private final MeasureRepository measureRepository = mock(MeasureRepository.class); private final MetricRepository metricRepository = mock(MetricRepository.class); private final Metric metric = mock(Metric.class); private AnalysisFromSonarQube94Visitor underTest; @Before public void before() { when(metricRepository.getByKey(anyString())).thenReturn(metric); underTest = new AnalysisFromSonarQube94Visitor(metricRepository, measureRepository); } @Test public void visitProject_createMeasureForMetric() { Component project = builder(FILE).setUuid("uuid") .setKey("dbKey") .setName("name") .setStatus(Component.Status.SAME) .setReportAttributes(mock(ReportAttributes.class)) .build(); PathAwareVisitor.Path<AnalysisFromSonarQube94> path = mock(PathAwareVisitor.Path.class); when(path.current()).thenReturn(new AnalysisFromSonarQube94()); underTest.visitProject(project, path); Measure expectedMeasure = Measure.newMeasureBuilder().create(true); verify(measureRepository).add(project, metric, expectedMeasure); } @Test public void analysisFromSonarQube94StackFactoryCreateForAny_shouldAlwaysReturnAnalysisFromSonarQube94() { AnalysisFromSonarQube94StackFactory factory = new AnalysisFromSonarQube94StackFactory(); AnalysisFromSonarQube94 analysisFromSonarQube94 = factory.createForAny(mock(Component.class)); assertThat(analysisFromSonarQube94.sonarQube94OrGreater).isTrue(); } }
3,564
41.440476
124
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/analysis/AnalysisImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.analysis; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class AnalysisImplTest { private static final long ID = 10; private static final String UUID = "uuid "; private static final long CREATED_AT = 123456789L; @Test public void build_snapshot() { Analysis analysis = new Analysis.Builder() .setUuid(UUID) .setCreatedAt(CREATED_AT) .build(); assertThat(analysis.getUuid()).isEqualTo(UUID); assertThat(analysis.getCreatedAt()).isEqualTo(CREATED_AT); } @Test public void fail_with_NPE_when_building_snapshot_without_uuid() { assertThatThrownBy(() -> new Analysis.Builder().setCreatedAt(CREATED_AT).build()) .isInstanceOf(NullPointerException.class) .hasMessage("uuid cannot be null"); } @Test public void fail_with_NPE_when_building_snapshot_without_created_at() { assertThatThrownBy(() -> new Analysis.Builder().setUuid(UUID).build()) .isInstanceOf(NullPointerException.class) .hasMessage("createdAt cannot be null"); } @Test public void test_toString() { assertThat(new Analysis.Builder() .setUuid(UUID) .setCreatedAt(CREATED_AT) .build()).hasToString("Analysis{uuid='uuid ', createdAt=123456789}"); } @Test public void test_equals_and_hascode() { Analysis analysis = new Analysis.Builder() .setUuid(UUID) .setCreatedAt(CREATED_AT) .build(); Analysis sameAnalysis = new Analysis.Builder() .setUuid(UUID) .setCreatedAt(CREATED_AT) .build(); Analysis otherAnalysis = new Analysis.Builder() .setUuid("other uuid") .setCreatedAt(CREATED_AT) .build(); assertThat(analysis) .isEqualTo(analysis) .isEqualTo(sameAnalysis) .isNotEqualTo(otherAnalysis) .isNotNull() .hasSameHashCodeAs(analysis.hashCode()) .hasSameHashCodeAs(sameAnalysis.hashCode()); assertThat(analysis.hashCode()).isNotEqualTo(otherAnalysis.hashCode()); } }
2,951
31.43956
85
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/analysis/AnalysisMetadataHolderImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.analysis; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Arrays; import java.util.Optional; import java.util.stream.Stream; import javax.annotation.Nullable; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.ce.task.projectanalysis.component.DefaultBranchImpl; import org.sonar.core.platform.PlatformEditionProvider; import org.sonar.db.component.BranchType; import org.sonar.server.project.Project; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.core.platform.EditionProvider.Edition; import static org.sonar.db.component.BranchDto.DEFAULT_MAIN_BRANCH_NAME; import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto; @RunWith(DataProviderRunner.class) public class AnalysisMetadataHolderImplTest { private static final Analysis baseProjectAnalysis = new Analysis.Builder() .setUuid("uuid_1") .setCreatedAt(123456789L) .build(); private static final long SOME_DATE = 10000000L; private final PlatformEditionProvider editionProvider = mock(PlatformEditionProvider.class); private final AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); @Test public void setUuid_throws_NPE_is_parameter_is_null() { assertThatThrownBy(() -> underTest.setUuid(null)) .isInstanceOf(NullPointerException.class) .hasMessage("Analysis uuid can't be null"); } @Test public void setUuid_throws_ISE_if_called_twice() { underTest.setUuid("org1"); assertThatThrownBy(() -> underTest.setUuid("org1")) .isInstanceOf(IllegalStateException.class) .hasMessage("Analysis uuid has already been set"); } @Test public void getAnalysisDate_returns_date_with_same_time_as_the_one_set_with_setAnalysisDate() { underTest.setAnalysisDate(SOME_DATE); assertThat(underTest.getAnalysisDate()).isEqualTo(SOME_DATE); } @Test public void get_new_code_reference_branch() { String newCodeReferenceBranch = "newCodeReferenceBranch"; underTest.setNewCodeReferenceBranch(newCodeReferenceBranch); assertThat(underTest.getNewCodeReferenceBranch()).hasValue(newCodeReferenceBranch); } @Test public void get_new_code_reference_branch_return_empty_when_holder_is_not_initialized() { assertThat(underTest.getNewCodeReferenceBranch()).isEmpty(); } @Test public void set_new_code_reference_branch_throws_ISE_when_called_twice() { String newCodeReferenceBranch = "newCodeReferenceBranch"; underTest.setNewCodeReferenceBranch(newCodeReferenceBranch); assertThatThrownBy(() -> underTest.setNewCodeReferenceBranch(newCodeReferenceBranch)) .isInstanceOf(IllegalStateException.class) .hasMessage("newCodeReferenceBranch has already been set"); } @Test public void getAnalysisDate_throws_ISE_when_holder_is_not_initialized() { assertThatThrownBy(() -> new AnalysisMetadataHolderImpl(editionProvider).getAnalysisDate()) .isInstanceOf(IllegalStateException.class) .hasMessage("Analysis date has not been set"); } @Test public void setAnalysisDate_throws_ISE_when_called_twice() { AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); underTest.setAnalysisDate(SOME_DATE); assertThatThrownBy(() -> underTest.setAnalysisDate(SOME_DATE)) .isInstanceOf(IllegalStateException.class) .hasMessage("Analysis date has already been set"); } @Test public void hasAnalysisDateBeenSet_returns_false_when_holder_is_not_initialized() { assertThat(new AnalysisMetadataHolderImpl(editionProvider).hasAnalysisDateBeenSet()).isFalse(); } @Test public void hasAnalysisDateBeenSet_returns_true_when_holder_date_is_set() { AnalysisMetadataHolderImpl holder = new AnalysisMetadataHolderImpl(editionProvider); holder.setAnalysisDate(46532); assertThat(holder.hasAnalysisDateBeenSet()).isTrue(); } @Test public void isFirstAnalysis_return_true() { AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); underTest.setBaseAnalysis(null); assertThat(underTest.isFirstAnalysis()).isTrue(); } @Test public void isFirstAnalysis_return_false() { AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); underTest.setBaseAnalysis(baseProjectAnalysis); assertThat(underTest.isFirstAnalysis()).isFalse(); } @Test public void isFirstAnalysis_throws_ISE_when_base_project_snapshot_is_not_set() { assertThatThrownBy(() -> new AnalysisMetadataHolderImpl(editionProvider).isFirstAnalysis()) .isInstanceOf(IllegalStateException.class) .hasMessage("Base project snapshot has not been set"); } @Test public void baseProjectSnapshot_throws_ISE_when_base_project_snapshot_is_not_set() { assertThatThrownBy(() -> new AnalysisMetadataHolderImpl(editionProvider).getBaseAnalysis()) .isInstanceOf(IllegalStateException.class) .hasMessage("Base project snapshot has not been set"); } @Test public void setBaseProjectSnapshot_throws_ISE_when_called_twice() { AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); underTest.setBaseAnalysis(baseProjectAnalysis); assertThatThrownBy(() -> underTest.setBaseAnalysis(baseProjectAnalysis)) .isInstanceOf(IllegalStateException.class) .hasMessage("Base project snapshot has already been set"); } @Test public void isCrossProjectDuplicationEnabled_return_true() { AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); underTest.setCrossProjectDuplicationEnabled(true); assertThat(underTest.isCrossProjectDuplicationEnabled()).isTrue(); } @Test public void isCrossProjectDuplicationEnabled_return_false() { AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); underTest.setCrossProjectDuplicationEnabled(false); assertThat(underTest.isCrossProjectDuplicationEnabled()).isFalse(); } @Test public void isCrossProjectDuplicationEnabled_throws_ISE_when_holder_is_not_initialized() { assertThatThrownBy(() -> new AnalysisMetadataHolderImpl(editionProvider).isCrossProjectDuplicationEnabled()) .isInstanceOf(IllegalStateException.class) .hasMessage("Cross project duplication flag has not been set"); } @Test public void setIsCrossProjectDuplicationEnabled_throws_ISE_when_called_twice() { AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); underTest.setCrossProjectDuplicationEnabled(true); assertThatThrownBy(() -> underTest.setCrossProjectDuplicationEnabled(false)) .isInstanceOf(IllegalStateException.class) .hasMessage("Cross project duplication flag has already been set"); } @Test public void set_branch() { AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); underTest.setBranch(new DefaultBranchImpl(DEFAULT_MAIN_BRANCH_NAME)); assertThat(underTest.getBranch().getName()).isEqualTo("main"); } @Test public void getBranch_throws_ISE_when_holder_is_not_initialized() { assertThatThrownBy(() -> new AnalysisMetadataHolderImpl(editionProvider).getBranch()) .isInstanceOf(IllegalStateException.class) .hasMessage("Branch has not been set"); } @Test public void setBranch_throws_ISE_when_called_twice() { AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); underTest.setBranch(new DefaultBranchImpl(DEFAULT_MAIN_BRANCH_NAME)); assertThatThrownBy(() -> underTest.setBranch(new DefaultBranchImpl("main"))) .isInstanceOf(IllegalStateException.class) .hasMessage("Branch has already been set"); } @Test @UseDataProvider("anyEditionIncludingNone") public void setBranch_does_not_fail_if_main_branch_on_any_edition(@Nullable Edition edition) { when(editionProvider.get()).thenReturn(Optional.ofNullable(edition)); Branch branch = mock(Branch.class); when(branch.isMain()).thenReturn(true); AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); underTest.setBranch(branch); assertThat(underTest.getBranch()).isSameAs(branch); } @Test @UseDataProvider("anyEditionIncludingNoneButCommunity") public void setBranch_does_not_fail_if_non_main_on_any_edition_but_Community(@Nullable Edition edition) { when(editionProvider.get()).thenReturn(Optional.ofNullable(edition)); Branch branch = mock(Branch.class); when(branch.isMain()).thenReturn(false); AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); underTest.setBranch(branch); assertThat(underTest.getBranch()).isSameAs(branch); } @Test public void setBranch_fails_if_non_main_branch_on_Community_edition() { when(editionProvider.get()).thenReturn(Optional.of(Edition.COMMUNITY)); Branch branch = mock(Branch.class); when(branch.isMain()).thenReturn(false); AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); assertThatThrownBy(() -> underTest.setBranch(branch)) .isInstanceOf(IllegalStateException.class) .hasMessage("Branches and Pull Requests are not supported in Community Edition"); } @DataProvider public static Object[][] anyEditionIncludingNone() { return Stream.concat( Stream.of((Edition) null), Arrays.stream(Edition.values())) .map(t -> new Object[] {t}) .toArray(Object[][]::new); } @DataProvider public static Object[][] anyEditionIncludingNoneButCommunity() { return Stream.concat( Stream.of((Edition) null), Arrays.stream(Edition.values())).filter(t -> t != Edition.COMMUNITY) .map(t -> new Object[] {t}) .toArray(Object[][]::new); } @Test public void setPullRequestId() { AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); String pullRequestId = "pr-123"; underTest.setPullRequestKey(pullRequestId); assertThat(underTest.getPullRequestKey()).isEqualTo(pullRequestId); } @Test public void getPullRequestId_throws_ISE_when_holder_is_not_initialized() { assertThatThrownBy(() -> new AnalysisMetadataHolderImpl(editionProvider).getPullRequestKey()) .isInstanceOf(IllegalStateException.class) .hasMessage("Pull request key has not been set"); } @Test public void setPullRequestId_throws_ISE_when_called_twice() { AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); underTest.setPullRequestKey("pr-123"); assertThatThrownBy(() -> underTest.setPullRequestKey("pr-234")) .isInstanceOf(IllegalStateException.class) .hasMessage("Pull request key has already been set"); } @Test public void set_and_get_project() { AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); Project project = Project.from(newPrivateProjectDto()); underTest.setProject(project); assertThat(underTest.getProject()).isSameAs(project); } @Test public void getProject_throws_ISE_when_holder_is_not_initialized() { assertThatThrownBy(() -> new AnalysisMetadataHolderImpl(editionProvider).getProject()) .isInstanceOf(IllegalStateException.class) .hasMessage("Project has not been set"); } @Test public void setProject_throws_ISE_when_called_twice() { AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); underTest.setProject(Project.from(newPrivateProjectDto())); assertThatThrownBy(() -> underTest.setProject(Project.from(newPrivateProjectDto()))) .isInstanceOf(IllegalStateException.class) .hasMessage("Project has already been set"); } @Test public void getRootComponentRef() { AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); underTest.setRootComponentRef(10); assertThat(underTest.getRootComponentRef()).isEqualTo(10); } @Test public void getRootComponentRef_throws_ISE_when_holder_is_not_initialized() { assertThatThrownBy(() -> new AnalysisMetadataHolderImpl(editionProvider).getRootComponentRef()) .isInstanceOf(IllegalStateException.class) .hasMessage("Root component ref has not been set"); } @Test public void setRootComponentRef_throws_ISE_when_called_twice() { AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); underTest.setRootComponentRef(10); assertThatThrownBy(() -> underTest.setRootComponentRef(9)) .isInstanceOf(IllegalStateException.class) .hasMessage("Root component ref has already been set"); } @Test public void getPullRequestBranch_returns_true() { Branch branch = mock(Branch.class); when(branch.getType()).thenReturn(BranchType.PULL_REQUEST); AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); underTest.setBranch(branch); assertThat(underTest.isPullRequest()).isTrue(); } @Test public void setScmRevision_throws_ISE_when_called_twice() { AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); underTest.setScmRevision("bd56dab"); assertThatThrownBy(() -> underTest.setScmRevision("bd56dab")) .isInstanceOf(IllegalStateException.class) .hasMessage("ScmRevision has already been set"); } @Test public void getScmRevision_returns_empty_if_scmRevision_is_not_initialized() { AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); assertThat(underTest.getScmRevision()).isNotPresent(); } @Test public void getScmRevision_returns_scmRevision_if_scmRevision_is_initialized() { AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); underTest.setScmRevision("bd56dab"); assertThat(underTest.getScmRevision()).hasValue("bd56dab"); } @Test public void getScmRevision_does_not_return_empty_string() { AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); underTest.setScmRevision(""); assertThat(underTest.getScmRevision()).isEmpty(); } @Test public void getScmRevision_does_not_return_blank_string() { AnalysisMetadataHolderImpl underTest = new AnalysisMetadataHolderImpl(editionProvider); underTest.setScmRevision(" "); assertThat(underTest.getScmRevision()).isEmpty(); } @Test public void isBranch_returns_true_for_initialized_branch() { Branch branch = mock(Branch.class); when(branch.getType()).thenReturn(BranchType.BRANCH); underTest.setBranch(branch); assertThat(underTest.isBranch()).isTrue(); } @Test public void isBranch_returns_false_for_pr() { Branch branch = mock(Branch.class); when(branch.getType()).thenReturn(BranchType.PULL_REQUEST); underTest.setBranch(branch); assertThat(underTest.isBranch()).isFalse(); } @Test public void isBranch_throws_ISE_for_not_initialized_branch() { assertThatThrownBy(underTest::isBranch) .isInstanceOf(IllegalStateException.class) .hasMessage("Branch has not been set"); } }
16,441
35.865471
112
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/analysis/ProjectConfigurationFactoryTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.analysis; import org.junit.Rule; import org.junit.Test; import org.sonar.api.config.Configuration; import org.sonar.api.config.internal.MapSettings; import org.sonar.db.DbTester; import org.sonar.db.project.ProjectDto; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.db.property.PropertyTesting.newComponentPropertyDto; public class ProjectConfigurationFactoryTest { @Rule public DbTester db = DbTester.create(); private final MapSettings settings = new MapSettings(); private final ProjectConfigurationFactory underTest = new ProjectConfigurationFactory(settings, db.getDbClient()); @Test public void return_global_settings() { settings.setProperty("key", "value"); Configuration config = underTest.newProjectConfiguration("unknown"); assertThat(config.get("key")).hasValue("value"); } @Test public void return_project_settings() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); db.properties().insertProperties(null, project.getKey(), project.getName(), project.getQualifier(), newComponentPropertyDto(project).setKey("1").setValue("val1"), newComponentPropertyDto(project).setKey("2").setValue("val2"), newComponentPropertyDto(project).setKey("3").setValue("val3")); Configuration config = underTest.newProjectConfiguration(project.getUuid()); assertThat(config.get("1")).hasValue("val1"); assertThat(config.get("2")).hasValue("val2"); assertThat(config.get("3")).hasValue("val3"); } @Test public void project_settings_override_global_settings() { settings.setProperty("key", "value"); ProjectDto project = db.components().insertPrivateProject().getProjectDto(); db.properties().insertProperties(null, project.getKey(), project.getName(), project.getQualifier(), newComponentPropertyDto(project).setKey("key").setValue("value2")); Configuration projectConfig = underTest.newProjectConfiguration(project.getUuid()); assertThat(projectConfig.get("key")).hasValue("value2"); } }
2,946
38.824324
116
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/analysis/ScannerPluginTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.analysis; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class ScannerPluginTest { @Test public void verify_getters() { ScannerPlugin plugin = new ScannerPlugin("key", "base", 12345L); assertThat(plugin.getKey()).isEqualTo("key"); assertThat(plugin.getBasePluginKey()).isEqualTo("base"); assertThat(plugin.getUpdatedAt()).isEqualTo(12345L); } @Test public void verify_toString() { ScannerPlugin plugin = new ScannerPlugin("key", "base", 12345L); assertThat(plugin).hasToString("ScannerPlugin{key='key', basePluginKey='base', updatedAt='12345'}"); } @Test public void equals_is_based_on_key_only() { ScannerPlugin plugin = new ScannerPlugin("key", "base", 12345L); assertThat(plugin) .isEqualTo(plugin) .isEqualTo(new ScannerPlugin("key", null, 45678L)) .isNotEqualTo(new ScannerPlugin("key2", "base", 12345L)) .isNotNull() .isNotEqualTo("toto"); } @Test public void hashcode_is_based_on_key_only() { ScannerPlugin plugin = new ScannerPlugin("key", "base", 12345L); assertThat(plugin).hasSameHashCodeAs("key"); } }
2,045
31.47619
104
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/measurecomputer/ComponentImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.api.measurecomputer; import org.junit.Test; import org.sonar.api.ce.measure.Component; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ComponentImplTest { @Test public void create_project() { ComponentImpl component = new ComponentImpl("Project", Component.Type.PROJECT, null); assertThat(component.getKey()).isEqualTo("Project"); assertThat(component.getType()).isEqualTo(Component.Type.PROJECT); } @Test public void create_source_file() { ComponentImpl component = new ComponentImpl("File", Component.Type.FILE, new ComponentImpl.FileAttributesImpl("xoo", false)); assertThat(component.getType()).isEqualTo(Component.Type.FILE); assertThat(component.getFileAttributes().getLanguageKey()).isEqualTo("xoo"); assertThat(component.getFileAttributes().isUnitTest()).isFalse(); } @Test public void create_test_file() { ComponentImpl component = new ComponentImpl("File", Component.Type.FILE, new ComponentImpl.FileAttributesImpl(null, true)); assertThat(component.getType()).isEqualTo(Component.Type.FILE); assertThat(component.getFileAttributes().isUnitTest()).isTrue(); assertThat(component.getFileAttributes().getLanguageKey()).isNull(); } @Test public void fail_with_ISE_when_calling_get_file_attributes_on_not_file() { assertThatThrownBy(() -> { ComponentImpl component = new ComponentImpl("Project", Component.Type.PROJECT, null); component.getFileAttributes(); }) .isInstanceOf(IllegalStateException.class) .hasMessage("Only component of type FILE have a FileAttributes object"); } @Test public void fail_with_IAE_when_trying_to_create_a_file_without_file_attributes() { assertThatThrownBy(() -> new ComponentImpl("File", Component.Type.FILE, null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("omponent of type FILE must have a FileAttributes object"); } @Test public void fail_with_IAE_when_trying_to_create_not_a_file_with_file_attributes() { assertThatThrownBy(() -> new ComponentImpl("Project", Component.Type.PROJECT, new ComponentImpl.FileAttributesImpl(null, true))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Only component of type FILE have a FileAttributes object"); } @Test public void fail_with_NPE_when_creating_component_without_key() { assertThatThrownBy(() -> new ComponentImpl(null, Component.Type.PROJECT, null)) .isInstanceOf(NullPointerException.class) .hasMessage("Key cannot be null"); } @Test public void fail_with_NPE_when_creating_component_without_type() { assertThatThrownBy(() -> new ComponentImpl("Project", null, null)) .isInstanceOf(NullPointerException.class) .hasMessage("Type cannot be null"); } @Test public void test_equals_and_hashcode() { ComponentImpl component = new ComponentImpl("Project1", Component.Type.PROJECT, null); ComponentImpl sameComponent = new ComponentImpl("Project1", Component.Type.PROJECT, null); ComponentImpl anotherComponent = new ComponentImpl("Project2", Component.Type.PROJECT, null); assertThat(component) .isEqualTo(component) .isEqualTo(sameComponent) .isNotEqualTo(anotherComponent) .isNotNull() .hasSameHashCodeAs(component) .hasSameHashCodeAs(sameComponent); assertThat(component.hashCode()).isNotEqualTo(anotherComponent.hashCode()); } @Test public void test_to_string() { assertThat(new ComponentImpl("File", Component.Type.FILE, new ComponentImpl.FileAttributesImpl("xoo", true))) .hasToString("ComponentImpl{key=File, type='FILE', fileAttributes=FileAttributesImpl{languageKey='xoo', unitTest=true}}"); } }
4,682
39.37069
132
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/measurecomputer/MeasureComputerContextImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.api.measurecomputer; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import org.junit.Rule; import org.junit.Test; import org.sonar.api.ce.measure.Component; import org.sonar.api.ce.measure.MeasureComputer; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.measures.CoreMetrics; import org.sonar.api.rule.RuleKey; import org.sonar.api.utils.Duration; import org.sonar.ce.task.projectanalysis.component.ConfigurationRepository; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; import org.sonar.ce.task.projectanalysis.issue.ComponentIssuesRepositoryRule; import org.sonar.ce.task.projectanalysis.measure.Measure; import org.sonar.ce.task.projectanalysis.measure.MeasureRepositoryRule; import org.sonar.ce.task.projectanalysis.metric.Metric; import org.sonar.ce.task.projectanalysis.metric.MetricImpl; import org.sonar.ce.task.projectanalysis.metric.MetricRepositoryRule; import org.sonar.core.issue.DefaultIssue; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.measures.CoreMetrics.COMMENT_LINES_KEY; import static org.sonar.api.measures.CoreMetrics.NCLOC_KEY; import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder; import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilder; public class MeasureComputerContextImplTest { private static final String INT_METRIC_KEY = "int_metric_key"; private static final String DOUBLE_METRIC_KEY = "double_metric_key"; private static final String LONG_METRIC_KEY = "long_metric_key"; private static final String STRING_METRIC_KEY = "string_metric_key"; private static final String BOOLEAN_METRIC_KEY = "boolean_metric_key"; private static final int PROJECT_REF = 1; private static final int FILE_1_REF = 12341; private static final String FILE_1_KEY = "fileKey"; private static final int FILE_2_REF = 12342; private static final org.sonar.ce.task.projectanalysis.component.Component FILE_1 = builder( org.sonar.ce.task.projectanalysis.component.Component.Type.FILE, FILE_1_REF) .setKey(FILE_1_KEY) .build(); @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule() .setRoot(builder(org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT, PROJECT_REF).setKey("project") .addChildren( FILE_1, builder(org.sonar.ce.task.projectanalysis.component.Component.Type.FILE, FILE_2_REF).setKey("fileKey2").build()) .build()); @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule() .add("1", CoreMetrics.NCLOC) .add(new MetricImpl("2", INT_METRIC_KEY, "int metric", Metric.MetricType.INT)) .add(new MetricImpl("3", DOUBLE_METRIC_KEY, "double metric", Metric.MetricType.FLOAT)) .add(new MetricImpl("4", LONG_METRIC_KEY, "long metric", Metric.MetricType.MILLISEC)) .add(new MetricImpl("5", STRING_METRIC_KEY, "string metric", Metric.MetricType.STRING)) .add(new MetricImpl("6", BOOLEAN_METRIC_KEY, "boolean metric", Metric.MetricType.BOOL)); @Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository); @Rule public ComponentIssuesRepositoryRule componentIssuesRepository = new ComponentIssuesRepositoryRule(treeRootHolder); ConfigurationRepository settingsRepository = mock(ConfigurationRepository.class); @Test public void get_component() { MeasureComputerContextImpl underTest = newContext(FILE_1_REF); assertThat(underTest.getComponent().getType()).isEqualTo(Component.Type.FILE); } @Test public void get_string_settings() { MapSettings serverSettings = new MapSettings(); serverSettings.setProperty("prop", "value"); when(settingsRepository.getConfiguration()).thenReturn(serverSettings.asConfig()); MeasureComputerContextImpl underTest = newContext(FILE_1_REF); assertThat(underTest.getSettings().getString("prop")).isEqualTo("value"); assertThat(underTest.getSettings().getString("unknown")).isNull(); } @Test public void get_string_array_settings() { MapSettings serverSettings = new MapSettings(); serverSettings.setProperty("prop", "1,3.4,8,50"); when(settingsRepository.getConfiguration()).thenReturn(serverSettings.asConfig()); MeasureComputerContextImpl underTest = newContext(FILE_1_REF); assertThat(underTest.getSettings().getStringArray("prop")).containsExactly("1", "3.4", "8", "50"); assertThat(underTest.getSettings().getStringArray("unknown")).isEmpty(); } @Test public void get_measure() { measureRepository.addRawMeasure(FILE_1_REF, NCLOC_KEY, newMeasureBuilder().create(10)); MeasureComputerContextImpl underTest = newContext(FILE_1_REF, NCLOC_KEY, COMMENT_LINES_KEY); assertThat(underTest.getMeasure(NCLOC_KEY).getIntValue()).isEqualTo(10); } @Test public void fail_with_IAE_when_get_measure_is_called_on_metric_not_in_input_list() { assertThatThrownBy(() -> { MeasureComputerContextImpl underTest = newContext(PROJECT_REF, "another metric", "debt"); underTest.getMeasure(NCLOC_KEY); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Only metrics in [another metric] can be used to load measures"); } @Test public void get_children_measures() { measureRepository.addRawMeasure(FILE_1_REF, NCLOC_KEY, newMeasureBuilder().create(10)); measureRepository.addRawMeasure(FILE_2_REF, NCLOC_KEY, newMeasureBuilder().create(12)); MeasureComputerContextImpl underTest = newContext(PROJECT_REF, NCLOC_KEY, COMMENT_LINES_KEY); assertThat(underTest.getChildrenMeasures(NCLOC_KEY)).hasSize(2); assertThat(underTest.getChildrenMeasures(NCLOC_KEY)).extracting("intValue").containsOnly(10, 12); } @Test public void get_children_measures_when_one_child_has_no_value() { measureRepository.addRawMeasure(FILE_1_REF, NCLOC_KEY, newMeasureBuilder().create(10)); // No data on file 2 MeasureComputerContextImpl underTest = newContext(PROJECT_REF, NCLOC_KEY, COMMENT_LINES_KEY); assertThat(underTest.getChildrenMeasures(NCLOC_KEY)).extracting("intValue").containsOnly(10); } @Test public void not_fail_to_get_children_measures_on_output_metric() { measureRepository.addRawMeasure(FILE_1_REF, INT_METRIC_KEY, newMeasureBuilder().create(10)); MeasureComputerContextImpl underTest = newContext(PROJECT_REF, NCLOC_KEY, INT_METRIC_KEY); assertThat(underTest.getChildrenMeasures(INT_METRIC_KEY)).hasSize(1); assertThat(underTest.getChildrenMeasures(INT_METRIC_KEY)).extracting("intValue").containsOnly(10); } @Test public void fail_with_IAE_when_get_children_measures_is_called_on_metric_not_in_input_list() { assertThatThrownBy(() -> { MeasureComputerContextImpl underTest = newContext(PROJECT_REF, "another metric", "debt"); underTest.getChildrenMeasures(NCLOC_KEY); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Only metrics in [another metric] can be used to load measures"); } @Test public void add_int_measure_create_measure_of_type_int_with_right_value() { MeasureComputerContextImpl underTest = newContext(PROJECT_REF, NCLOC_KEY, INT_METRIC_KEY); underTest.addMeasure(INT_METRIC_KEY, 10); Optional<Measure> measure = measureRepository.getAddedRawMeasure(PROJECT_REF, INT_METRIC_KEY); assertThat(measure).isPresent(); assertThat(measure.get().getIntValue()).isEqualTo(10); } @Test public void add_double_measure_create_measure_of_type_double_with_right_value() { MeasureComputerContextImpl underTest = newContext(PROJECT_REF, NCLOC_KEY, DOUBLE_METRIC_KEY); underTest.addMeasure(DOUBLE_METRIC_KEY, 10d); Optional<Measure> measure = measureRepository.getAddedRawMeasure(PROJECT_REF, DOUBLE_METRIC_KEY); assertThat(measure).isPresent(); assertThat(measure.get().getDoubleValue()).isEqualTo(10d); } @Test public void add_long_measure_create_measure_of_type_long_with_right_value() { MeasureComputerContextImpl underTest = newContext(PROJECT_REF, NCLOC_KEY, LONG_METRIC_KEY); underTest.addMeasure(LONG_METRIC_KEY, 10L); Optional<Measure> measure = measureRepository.getAddedRawMeasure(PROJECT_REF, LONG_METRIC_KEY); assertThat(measure).isPresent(); assertThat(measure.get().getLongValue()).isEqualTo(10L); } @Test public void add_string_measure_create_measure_of_type_string_with_right_value() { MeasureComputerContextImpl underTest = newContext(PROJECT_REF, NCLOC_KEY, STRING_METRIC_KEY); underTest.addMeasure(STRING_METRIC_KEY, "data"); Optional<Measure> measure = measureRepository.getAddedRawMeasure(PROJECT_REF, STRING_METRIC_KEY); assertThat(measure).isPresent(); assertThat(measure.get().getStringValue()).isEqualTo("data"); } @Test public void add_boolean_measure_create_measure_of_type_boolean_with_right_value() { MeasureComputerContextImpl underTest = newContext(PROJECT_REF, NCLOC_KEY, BOOLEAN_METRIC_KEY); underTest.addMeasure(BOOLEAN_METRIC_KEY, true); Optional<Measure> measure = measureRepository.getAddedRawMeasure(PROJECT_REF, BOOLEAN_METRIC_KEY); assertThat(measure).isPresent(); assertThat(measure.get().getBooleanValue()).isTrue(); } @Test public void fail_with_IAE_when_add_measure_is_called_on_metric_not_in_output_list() { assertThatThrownBy(() -> { MeasureComputerContextImpl underTest = newContext(PROJECT_REF, NCLOC_KEY, INT_METRIC_KEY); underTest.addMeasure(DOUBLE_METRIC_KEY, 10); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Only metrics in [int_metric_key] can be used to add measures. Metric 'double_metric_key' is not allowed."); } @Test public void fail_with_unsupported_operation_when_adding_measure_that_already_exists() { assertThatThrownBy(() -> { measureRepository.addRawMeasure(FILE_1_REF, INT_METRIC_KEY, newMeasureBuilder().create(20)); MeasureComputerContextImpl underTest = newContext(FILE_1_REF, NCLOC_KEY, INT_METRIC_KEY); underTest.addMeasure(INT_METRIC_KEY, 10); }) .isInstanceOf(UnsupportedOperationException.class) .hasMessage("A measure on metric 'int_metric_key' already exists on component 'fileKey'"); } @Test public void get_issues() { DefaultIssue issue = new DefaultIssue() .setKey("KEY") .setRuleKey(RuleKey.of("xoo", "S01")) .setSeverity("MAJOR") .setStatus("CLOSED") .setResolution("FIXED") .setEffort(Duration.create(10L)); MeasureComputerContextImpl underTest = newContext(PROJECT_REF, Arrays.asList(issue)); assertThat(underTest.getIssues()).hasSize(1); org.sonar.api.ce.measure.Issue result = underTest.getIssues().get(0); assertThat(result.key()).isEqualTo("KEY"); assertThat(result.ruleKey()).isEqualTo(RuleKey.of("xoo", "S01")); assertThat(result.severity()).isEqualTo("MAJOR"); assertThat(result.status()).isEqualTo("CLOSED"); assertThat(result.resolution()).isEqualTo("FIXED"); assertThat(result.effort()).isEqualTo(Duration.create(10L)); } private MeasureComputerContextImpl newContext(int componentRef) { return newContext(componentRef, NCLOC_KEY, COMMENT_LINES_KEY, Collections.emptyList()); } private MeasureComputerContextImpl newContext(int componentRef, List<DefaultIssue> issues) { return newContext(componentRef, NCLOC_KEY, COMMENT_LINES_KEY, issues); } private MeasureComputerContextImpl newContext(int componentRef, String inputMetric, String outputMetric) { return newContext(componentRef, inputMetric, outputMetric, Collections.emptyList()); } private MeasureComputerContextImpl newContext(int componentRef, String inputMetric, String outputMetric, List<DefaultIssue> issues) { componentIssuesRepository.setIssues(componentRef, issues); MeasureComputer.MeasureComputerDefinition definition = new MeasureComputerDefinitionImpl.BuilderImpl() .setInputMetrics(inputMetric) .setOutputMetrics(new String[] {outputMetric}) .build(); MeasureComputerContextImpl context = new MeasureComputerContextImpl(treeRootHolder.getComponentByRef(componentRef), settingsRepository, measureRepository, metricRepository, componentIssuesRepository); context.setDefinition(definition); return context; } }
13,416
43.723333
135
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/measurecomputer/MeasureComputerDefinitionImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.api.measurecomputer; import org.junit.Test; import org.sonar.api.ce.measure.MeasureComputer; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class MeasureComputerDefinitionImplTest { @Test public void build_measure_computer_definition() { String inputMetric = "ncloc"; String outputMetric = "comment_density"; MeasureComputer.MeasureComputerDefinition measureComputer = new MeasureComputerDefinitionImpl.BuilderImpl() .setInputMetrics(inputMetric) .setOutputMetrics(outputMetric) .build(); assertThat(measureComputer.getInputMetrics()).containsOnly(inputMetric); assertThat(measureComputer.getOutputMetrics()).containsOnly(outputMetric); } @Test public void build_measure_computer_with_multiple_metrics() { String[] inputMetrics = {"ncloc", "comment"}; String[] outputMetrics = {"comment_density_1", "comment_density_2"}; MeasureComputer.MeasureComputerDefinition measureComputer = new MeasureComputerDefinitionImpl.BuilderImpl() .setInputMetrics(inputMetrics) .setOutputMetrics(outputMetrics) .build(); assertThat(measureComputer.getInputMetrics()).containsOnly(inputMetrics); assertThat(measureComputer.getOutputMetrics()).containsOnly(outputMetrics); } @Test public void input_metrics_can_be_empty() { MeasureComputer.MeasureComputerDefinition measureComputer = new MeasureComputerDefinitionImpl.BuilderImpl() .setInputMetrics() .setOutputMetrics("comment_density_1", "comment_density_2") .build(); assertThat(measureComputer.getInputMetrics()).isEmpty(); } @Test public void input_metrics_is_empty_when_not_set() { MeasureComputer.MeasureComputerDefinition measureComputer = new MeasureComputerDefinitionImpl.BuilderImpl() .setOutputMetrics("comment_density_1", "comment_density_2") .build(); assertThat(measureComputer.getInputMetrics()).isEmpty(); } @Test public void fail_with_NPE_when_null_input_metrics() { assertThatThrownBy(() -> { new MeasureComputerDefinitionImpl.BuilderImpl() .setInputMetrics((String[]) null) .setOutputMetrics("comment_density_1", "comment_density_2"); }) .isInstanceOf(NullPointerException.class) .hasMessage("Input metrics cannot be null"); } @Test public void fail_with_NPE_when_one_input_metric_is_null() { assertThatThrownBy(() -> { new MeasureComputerDefinitionImpl.BuilderImpl() .setInputMetrics("ncloc", null) .setOutputMetrics("comment_density_1", "comment_density_2"); }) .isInstanceOf(NullPointerException.class) .hasMessage("Null metric is not allowed"); } @Test public void fail_with_NPE_when_no_output_metrics() { assertThatThrownBy(() -> { new MeasureComputerDefinitionImpl.BuilderImpl() .setInputMetrics("ncloc", "comment") .build(); }) .isInstanceOf(NullPointerException.class) .hasMessage("Output metrics cannot be null"); } @Test public void fail_with_NPE_when_null_output_metrics() { assertThatThrownBy(() -> { new MeasureComputerDefinitionImpl.BuilderImpl() .setInputMetrics("ncloc", "comment") .setOutputMetrics((String[]) null); }) .isInstanceOf(NullPointerException.class) .hasMessage("Output metrics cannot be null"); } @Test public void fail_with_NPE_when_one_output_metric_is_null() { assertThatThrownBy(() -> { new MeasureComputerDefinitionImpl.BuilderImpl() .setInputMetrics("ncloc", "comment") .setOutputMetrics("comment_density_1", null); }) .isInstanceOf(NullPointerException.class) .hasMessage("Null metric is not allowed"); } @Test public void fail_with_IAE_with_empty_output_metrics() { assertThatThrownBy(() -> { new MeasureComputerDefinitionImpl.BuilderImpl() .setInputMetrics("ncloc", "comment") .setOutputMetrics(); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("At least one output metric must be defined"); } @Test public void test_equals_and_hashcode() { MeasureComputer.MeasureComputerDefinition computer = new MeasureComputerDefinitionImpl.BuilderImpl() .setInputMetrics("ncloc", "comment") .setOutputMetrics("comment_density_1", "comment_density_2") .build(); MeasureComputer.MeasureComputerDefinition sameComputer = new MeasureComputerDefinitionImpl.BuilderImpl() .setInputMetrics("comment", "ncloc") .setOutputMetrics("comment_density_2", "comment_density_1") .build(); MeasureComputer.MeasureComputerDefinition anotherComputer = new MeasureComputerDefinitionImpl.BuilderImpl() .setInputMetrics("comment") .setOutputMetrics("debt") .build(); assertThat(computer) .isEqualTo(computer) .isEqualTo(sameComputer) .isNotEqualTo(anotherComputer) .isNotNull() .hasSameHashCodeAs(computer) .hasSameHashCodeAs(sameComputer) .doesNotHaveSameHashCodeAs(anotherComputer.hashCode()); } @Test public void test_to_string() { assertThat(new MeasureComputerDefinitionImpl.BuilderImpl() .setInputMetrics("ncloc", "comment") .setOutputMetrics("comment_density_1", "comment_density_2") .build()) .hasToString("MeasureComputerDefinitionImpl{inputMetricKeys=[ncloc, comment], outputMetrics=[comment_density_1, comment_density_2]}"); } }
6,387
34.88764
140
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/measurecomputer/MeasureImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.api.measurecomputer; import org.junit.Test; import org.sonar.ce.task.projectanalysis.measure.Measure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class MeasureImplTest { @Test public void get_int_value() { MeasureImpl measure = new MeasureImpl(Measure.newMeasureBuilder().create(1)); assertThat(measure.getIntValue()).isOne(); } @Test public void fail_with_ISE_when_not_int_value() { assertThatThrownBy(() -> { MeasureImpl measure = new MeasureImpl(Measure.newMeasureBuilder().create(1d, 1)); measure.getIntValue(); }) .isInstanceOf(IllegalStateException.class) .hasMessage("Value can not be converted to int because current value type is a DOUBLE"); } @Test public void get_double_value() { MeasureImpl measure = new MeasureImpl(Measure.newMeasureBuilder().create(1d, 1)); assertThat(measure.getDoubleValue()).isEqualTo(1d); } @Test public void fail_with_ISE_when_not_double_value() { assertThatThrownBy(() -> { MeasureImpl measure = new MeasureImpl(Measure.newMeasureBuilder().create(1)); measure.getDoubleValue(); }) .isInstanceOf(IllegalStateException.class) .hasMessage("Value can not be converted to double because current value type is a INT"); } @Test public void get_long_value() { MeasureImpl measure = new MeasureImpl(Measure.newMeasureBuilder().create(1L)); assertThat(measure.getLongValue()).isOne(); } @Test public void fail_with_ISE_when_not_long_value() { assertThatThrownBy(() -> { MeasureImpl measure = new MeasureImpl(Measure.newMeasureBuilder().create("value")); measure.getLongValue(); }) .isInstanceOf(IllegalStateException.class) .hasMessage("Value can not be converted to long because current value type is a STRING"); } @Test public void get_string_value() { MeasureImpl measure = new MeasureImpl(Measure.newMeasureBuilder().create("value")); assertThat(measure.getStringValue()).isEqualTo("value"); } @Test public void fail_with_ISE_when_not_string_value() { assertThatThrownBy(() -> { MeasureImpl measure = new MeasureImpl(Measure.newMeasureBuilder().create(1L)); measure.getStringValue(); }) .isInstanceOf(IllegalStateException.class) .hasMessage("Value can not be converted to string because current value type is a LONG"); } @Test public void get_boolean_value() { MeasureImpl measure = new MeasureImpl(Measure.newMeasureBuilder().create(true)); assertThat(measure.getBooleanValue()).isTrue(); } @Test public void fail_with_ISE_when_not_boolean_value() { assertThatThrownBy(() -> { MeasureImpl measure = new MeasureImpl(Measure.newMeasureBuilder().create(1d, 1)); measure.getBooleanValue(); }) .isInstanceOf(IllegalStateException.class) .hasMessage("Value can not be converted to boolean because current value type is a DOUBLE"); } @Test public void fail_with_ISE_when_creating_measure_with_no_value() { assertThatThrownBy(() -> new MeasureImpl(Measure.newMeasureBuilder().createNoValue())) .isInstanceOf(IllegalStateException.class) .hasMessage("Only following types are allowed [BOOLEAN, INT, LONG, DOUBLE, STRING]"); } @Test public void fail_with_ISE_when_creating_measure_with_not_allowed_value() { assertThatThrownBy(() -> new MeasureImpl(Measure.newMeasureBuilder().create(Measure.Level.ERROR))) .isInstanceOf(IllegalStateException.class) .hasMessage("Only following types are allowed [BOOLEAN, INT, LONG, DOUBLE, STRING]"); } @Test public void fail_with_NPE_when_creating_measure_with_null_measure() { assertThatThrownBy(() -> new MeasureImpl(null)) .isInstanceOf(NullPointerException.class) .hasMessage("Measure couldn't be null"); } }
4,789
35.287879
102
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/posttask/CeTaskImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.api.posttask; import org.junit.Test; import org.sonar.api.ce.posttask.CeTask; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class CeTaskImplTest { private static final String SOME_ID = "some id"; @Test public void constructor_throws_NPE_if_id_is_null() { assertThatThrownBy(() -> new CeTaskImpl(null, CeTask.Status.SUCCESS)) .isInstanceOf(NullPointerException.class) .hasMessageContaining("id can not be null"); } @Test public void constructor_throws_NPE_if_status_is_null() { assertThatThrownBy(() -> new CeTaskImpl(SOME_ID, null)) .isInstanceOf(NullPointerException.class) .hasMessage("status can not be null"); } @Test public void verify_getters() { CeTaskImpl underTest = new CeTaskImpl(SOME_ID, CeTask.Status.FAILED); assertThat(underTest.getId()).isEqualTo(SOME_ID); assertThat(underTest.getStatus()).isEqualTo(CeTask.Status.FAILED); } @Test public void verify_toString() { assertThat(new CeTaskImpl(SOME_ID, CeTask.Status.SUCCESS)).hasToString("CeTaskImpl{id='some id', status=SUCCESS}"); } }
2,053
34.413793
119
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/posttask/ConditionImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.api.posttask; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.api.ce.posttask.QualityGate; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @RunWith(DataProviderRunner.class) public class ConditionImplTest { private static final String METRIC_KEY = "metricKey"; private static final String ERROR_THRESHOLD = "error threshold"; private static final String VALUE = "value"; private ConditionImpl.Builder builder = ConditionImpl.newBuilder() .setStatus(QualityGate.EvaluationStatus.OK) .setMetricKey(METRIC_KEY) .setOperator(QualityGate.Operator.GREATER_THAN) .setErrorThreshold(ERROR_THRESHOLD) .setValue(VALUE); @Test public void build_throws_NPE_if_status_is_null() { builder.setStatus(null); assertThatThrownBy(() -> builder.build()) .isInstanceOf(NullPointerException.class) .hasMessage("status can not be null"); } @Test public void build_throws_NPE_if_metricKey_is_null() { builder.setMetricKey(null); assertThatThrownBy(() -> builder.build()) .isInstanceOf(NullPointerException.class) .hasMessage("metricKey can not be null"); } @Test public void build_throws_NPE_if_operator_is_null() { builder.setOperator(null); assertThatThrownBy(() -> builder.build()) .isInstanceOf(NullPointerException.class) .hasMessage("operator can not be null"); } @Test public void build_throws_NPE_if_error_threshold_is_null() { builder.setErrorThreshold(null); assertThatThrownBy(() -> builder.build()) .isInstanceOf(NullPointerException.class) .hasMessage("errorThreshold can not be null"); } @Test public void getValue_throws_ISE_when_condition_type_is_NO_VALUE() { builder.setStatus(QualityGate.EvaluationStatus.NO_VALUE).setValue(null); ConditionImpl condition = builder.build(); assertThatThrownBy(condition::getValue) .isInstanceOf(IllegalStateException.class) .hasMessage("There is no value when status is NO_VALUE"); } @DataProvider public static Object[][] allStatusesButNO_VALUE() { Object[][] res = new Object[QualityGate.EvaluationStatus.values().length - 1][1]; int i = 0; for (QualityGate.EvaluationStatus status : QualityGate.EvaluationStatus.values()) { if (status != QualityGate.EvaluationStatus.NO_VALUE) { res[i][0] = status; i++; } } return res; } @Test @UseDataProvider("allStatusesButNO_VALUE") public void build_throws_IAE_if_value_is_null_but_status_is_not_NO_VALUE(QualityGate.EvaluationStatus status) { builder.setStatus(status) .setValue(null); assertThatThrownBy(() -> builder.build()) .isInstanceOf(IllegalArgumentException.class) .hasMessage("value can not be null when status is not NO_VALUE"); } @Test public void build_throws_IAE_if_value_is_not_null_but_status_is_NO_VALUE() { builder.setStatus(QualityGate.EvaluationStatus.NO_VALUE); assertThatThrownBy(() -> builder.build()) .isInstanceOf(IllegalArgumentException.class) .hasMessage("value must be null when status is NO_VALUE"); } @Test public void toString_ConditionImpl_of_type_different_from_NO_VALUE() { assertThat(builder.build()) .hasToString( "ConditionImpl{status=OK, metricKey='metricKey', operator=GREATER_THAN, errorThreshold='error threshold', value='value'}"); } @Test public void toString_ConditionImpl_of_type_NO_VALUE() { builder.setStatus(QualityGate.EvaluationStatus.NO_VALUE) .setValue(null); assertThat(builder.build()) .hasToString( "ConditionImpl{status=NO_VALUE, metricKey='metricKey', operator=GREATER_THAN, errorThreshold='error threshold', value='null'}"); } @Test public void verify_getters() { ConditionImpl underTest = builder.build(); assertThat(underTest.getStatus()).isEqualTo(QualityGate.EvaluationStatus.OK); assertThat(underTest.getMetricKey()).isEqualTo(METRIC_KEY); assertThat(underTest.getOperator()).isEqualTo(QualityGate.Operator.GREATER_THAN); assertThat(underTest.getErrorThreshold()).isEqualTo(ERROR_THRESHOLD); assertThat(underTest.getValue()).isEqualTo(VALUE); } }
5,336
33.882353
136
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/posttask/ConditionToConditionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.api.posttask; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Collections; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.api.ce.posttask.QualityGate; import org.sonar.ce.task.projectanalysis.metric.Metric; import org.sonar.ce.task.projectanalysis.qualitygate.Condition; import org.sonar.ce.task.projectanalysis.qualitygate.ConditionStatus; import static com.google.common.collect.ImmutableMap.of; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(DataProviderRunner.class) public class ConditionToConditionTest { private static final String METRIC_KEY = "metricKey"; private static final String ERROR_THRESHOLD = "error threshold"; private static final Map<Condition, ConditionStatus> NO_STATUS_PER_CONDITIONS = Collections.emptyMap(); private static final String SOME_VALUE = "some value"; private static final ConditionStatus SOME_CONDITION_STATUS = ConditionStatus.create(ConditionStatus.EvaluationStatus.OK, SOME_VALUE); private static final Condition SOME_CONDITION = new Condition(newMetric(METRIC_KEY), Condition.Operator.LESS_THAN.getDbValue(), ERROR_THRESHOLD); @Test public void apply_throws_NPE_if_Condition_argument_is_null() { ConditionToCondition underTest = new ConditionToCondition(NO_STATUS_PER_CONDITIONS); assertThatThrownBy(() -> underTest.apply(null)) .isInstanceOf(NullPointerException.class); } @Test public void apply_throws_ISE_if_there_is_no_ConditionStatus_for_Condition_argument() { ConditionToCondition underTest = new ConditionToCondition(NO_STATUS_PER_CONDITIONS); assertThatThrownBy(() -> underTest.apply(SOME_CONDITION)) .isInstanceOf(IllegalStateException.class) .hasMessage("Missing ConditionStatus for condition on metric key " + METRIC_KEY); } @Test @UseDataProvider("allEvaluationStatuses") public void apply_converts_all_values_of_status(ConditionStatus.EvaluationStatus status) { ConditionToCondition underTest = new ConditionToCondition(of( SOME_CONDITION, status == ConditionStatus.EvaluationStatus.NO_VALUE ? ConditionStatus.NO_VALUE_STATUS : ConditionStatus.create(status, SOME_VALUE))); assertThat(underTest.apply(SOME_CONDITION).getStatus().name()).isEqualTo(status.name()); } @Test public void apply_converts_key_from_metric() { ConditionToCondition underTest = new ConditionToCondition(of(SOME_CONDITION, SOME_CONDITION_STATUS)); assertThat(underTest.apply(SOME_CONDITION).getMetricKey()).isEqualTo(METRIC_KEY); } @Test public void apply_copies_thresholds() { ConditionToCondition underTest = new ConditionToCondition(of(SOME_CONDITION, SOME_CONDITION_STATUS)); assertThat(underTest.apply(SOME_CONDITION).getErrorThreshold()).isEqualTo(ERROR_THRESHOLD); } @Test @UseDataProvider("allOperatorValues") public void apply_converts_all_values_of_operator(Condition.Operator operator) { Condition condition = new Condition(newMetric(METRIC_KEY), operator.getDbValue(), ERROR_THRESHOLD); ConditionToCondition underTest = new ConditionToCondition(of(condition, SOME_CONDITION_STATUS)); assertThat(underTest.apply(condition).getOperator().name()).isEqualTo(operator.name()); } @Test public void apply_copies_value() { Condition otherCondition = new Condition(newMetric(METRIC_KEY), Condition.Operator.LESS_THAN.getDbValue(), ERROR_THRESHOLD); ConditionToCondition underTest = new ConditionToCondition(of( SOME_CONDITION, SOME_CONDITION_STATUS, otherCondition, ConditionStatus.NO_VALUE_STATUS)); assertThat(underTest.apply(SOME_CONDITION).getValue()).isEqualTo(SOME_VALUE); QualityGate.Condition res = underTest.apply(otherCondition); assertThatThrownBy(res::getValue) .isInstanceOf(IllegalStateException.class) .hasMessage("There is no value when status is NO_VALUE"); } @DataProvider public static Object[][] allEvaluationStatuses() { Object[][] res = new Object[ConditionStatus.EvaluationStatus.values().length][1]; int i = 0; for (ConditionStatus.EvaluationStatus status : ConditionStatus.EvaluationStatus.values()) { res[i][0] = status; i++; } return res; } @DataProvider public static Object[][] allOperatorValues() { Object[][] res = new Object[Condition.Operator.values().length][1]; int i = 0; for (Condition.Operator operator : Condition.Operator.values()) { res[i][0] = operator; i++; } return res; } private static Metric newMetric(String metricKey) { Metric metric = mock(Metric.class); when(metric.getKey()).thenReturn(metricKey); return metric; } }
5,846
39.888112
147
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/posttask/PostProjectAnalysisTasksExecutorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.api.posttask; import com.google.common.collect.ImmutableMap; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import javax.annotation.Nullable; import org.apache.commons.lang.RandomStringUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import org.slf4j.event.Level; import org.sonar.api.ce.posttask.PostProjectAnalysisTask; import org.sonar.api.ce.posttask.Project; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.ce.task.CeTask; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.ce.task.projectanalysis.analysis.Branch; import org.sonar.ce.task.projectanalysis.batch.BatchReportReaderRule; import org.sonar.ce.task.projectanalysis.metric.Metric; import org.sonar.ce.task.projectanalysis.qualitygate.Condition; import org.sonar.ce.task.projectanalysis.qualitygate.ConditionStatus; import org.sonar.ce.task.projectanalysis.qualitygate.MutableQualityGateHolderRule; import org.sonar.ce.task.projectanalysis.qualitygate.MutableQualityGateStatusHolderRule; import org.sonar.ce.task.projectanalysis.qualitygate.QualityGate; import org.sonar.ce.task.projectanalysis.qualitygate.QualityGateStatus; import org.sonar.db.component.BranchType; import org.sonar.scanner.protocol.output.ScannerReport; import static com.google.common.collect.ImmutableList.of; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.ThrowableAssert.catchThrowable; import static org.assertj.core.data.MapEntry.entry; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(DataProviderRunner.class) public class PostProjectAnalysisTasksExecutorTest { private static final String QUALITY_GATE_UUID = "98451"; private static final String QUALITY_GATE_NAME = "qualityGate name"; private static final Condition CONDITION_1 = createCondition("metric key 1"); private static final Condition CONDITION_2 = createCondition("metric key 2"); @Rule public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule(); @Rule public MutableQualityGateHolderRule qualityGateHolder = new MutableQualityGateHolderRule(); @Rule public MutableQualityGateStatusHolderRule qualityGateStatusHolder = new MutableQualityGateStatusHolderRule(); @Rule public BatchReportReaderRule reportReader = new BatchReportReaderRule(); @Rule public LogTester logTester = new LogTester(); private final ArgumentCaptor<PostProjectAnalysisTask.Context> taskContextCaptor = ArgumentCaptor.forClass(PostProjectAnalysisTask.Context.class); private final CeTask.Component component = new CeTask.Component("component uuid", "component key", "component name"); private final CeTask.Component entity = new CeTask.Component("entity uuid", "component key", "component name"); private final CeTask ceTask = new CeTask.Builder() .setType("type") .setUuid("uuid") .setComponent(component) .setEntity(entity) .build(); private final PostProjectAnalysisTask postProjectAnalysisTask = newPostProjectAnalysisTask("PT1"); private final PostProjectAnalysisTasksExecutor underTest = new PostProjectAnalysisTasksExecutor( ceTask, analysisMetadataHolder, qualityGateHolder, qualityGateStatusHolder, reportReader, new PostProjectAnalysisTask[] {postProjectAnalysisTask}); @Before public void setUp() { qualityGateHolder.setQualityGate(new QualityGate(QUALITY_GATE_UUID, QUALITY_GATE_NAME, of(CONDITION_1, CONDITION_2))); qualityGateStatusHolder.setStatus(QualityGateStatus.OK, ImmutableMap.of( CONDITION_1, ConditionStatus.create(ConditionStatus.EvaluationStatus.OK, "value"), CONDITION_2, ConditionStatus.NO_VALUE_STATUS)); Branch branch = mock(Branch.class); when(branch.getType()).thenReturn(BranchType.BRANCH); analysisMetadataHolder .setBranch(branch); reportReader.setMetadata(ScannerReport.Metadata.newBuilder().build()); } @Test @UseDataProvider("booleanValues") public void does_not_fail_when_there_is_no_PostProjectAnalysisTasksExecutor(boolean allStepsExecuted) { new PostProjectAnalysisTasksExecutor(ceTask, analysisMetadataHolder, qualityGateHolder, qualityGateStatusHolder, reportReader, null) .finished(allStepsExecuted); } @Test @UseDataProvider("booleanValues") public void finished_calls_all_PostProjectAnalysisTask_in_order_of_the_array_and_passes_the_same_object_to_all(boolean allStepsExecuted) { PostProjectAnalysisTask postProjectAnalysisTask1 = newPostProjectAnalysisTask("PT1"); PostProjectAnalysisTask postProjectAnalysisTask2 = newPostProjectAnalysisTask("PT2"); InOrder inOrder = inOrder(postProjectAnalysisTask1, postProjectAnalysisTask2); new PostProjectAnalysisTasksExecutor( ceTask, analysisMetadataHolder, qualityGateHolder, qualityGateStatusHolder, reportReader, new PostProjectAnalysisTask[] {postProjectAnalysisTask1, postProjectAnalysisTask2}) .finished(allStepsExecuted); inOrder.verify(postProjectAnalysisTask1).finished(taskContextCaptor.capture()); inOrder.verify(postProjectAnalysisTask1).getDescription(); inOrder.verify(postProjectAnalysisTask2).finished(taskContextCaptor.capture()); inOrder.verify(postProjectAnalysisTask2).getDescription(); inOrder.verifyNoMoreInteractions(); ArgumentCaptor<PostProjectAnalysisTask.Context> taskContextCaptor = this.taskContextCaptor; List<PostProjectAnalysisTask.ProjectAnalysis> allValues = getAllProjectAnalyses(taskContextCaptor); assertThat(allValues).hasSize(2); assertThat(allValues.get(0)).isSameAs(allValues.get(1)); assertThat(logTester.logs()).hasSize(2); List<String> logs = logTester.logs(Level.INFO); assertThat(logs).hasSize(2); assertThat(logs.get(0)).matches("^PT1 \\| status=SUCCESS \\| time=\\d+ms$"); assertThat(logs.get(1)).matches("^PT2 \\| status=SUCCESS \\| time=\\d+ms$"); } @Test @UseDataProvider("booleanValues") public void organization_is_null(boolean allStepsExecuted) { underTest.finished(allStepsExecuted); verify(postProjectAnalysisTask).finished(taskContextCaptor.capture()); assertThat(taskContextCaptor.getValue().getProjectAnalysis().getOrganization()).isEmpty(); } @Test @UseDataProvider("booleanValues") public void CeTask_status_depends_on_finished_method_argument_is_true_or_false(boolean allStepsExecuted) { underTest.finished(allStepsExecuted); verify(postProjectAnalysisTask).finished(taskContextCaptor.capture()); assertThat(taskContextCaptor.getValue().getProjectAnalysis().getCeTask().getStatus()) .isEqualTo( allStepsExecuted ? org.sonar.api.ce.posttask.CeTask.Status.SUCCESS : org.sonar.api.ce.posttask.CeTask.Status.FAILED); } @Test public void ceTask_uuid_is_UUID_of_CeTask() { underTest.finished(true); verify(postProjectAnalysisTask).finished(taskContextCaptor.capture()); assertThat(taskContextCaptor.getValue().getProjectAnalysis().getCeTask().getId()) .isEqualTo(ceTask.getUuid()); } @Test public void project_uuid_key_and_name_come_from_CeTask() { underTest.finished(true); verify(postProjectAnalysisTask).finished(taskContextCaptor.capture()); Project project = taskContextCaptor.getValue().getProjectAnalysis().getProject(); assertThat(project.getUuid()).isEqualTo(ceTask.getEntity().get().getUuid()); assertThat(project.getKey()).isEqualTo(ceTask.getEntity().get().getKey().get()); assertThat(project.getName()).isEqualTo(ceTask.getEntity().get().getName().get()); } @Test public void date_comes_from_AnalysisMetadataHolder() { analysisMetadataHolder.setAnalysisDate(8_465_132_498L); analysisMetadataHolder.setUuid(RandomStringUtils.randomAlphanumeric(40)); underTest.finished(true); verify(postProjectAnalysisTask).finished(taskContextCaptor.capture()); assertThat(taskContextCaptor.getValue().getProjectAnalysis().getAnalysis().get().getDate()) .isEqualTo(new Date(analysisMetadataHolder.getAnalysisDate())); } @Test public void analysisDate_and_analysisUuid_comes_from_AnalysisMetadataHolder_when_set() { analysisMetadataHolder.setAnalysisDate(8465132498L); analysisMetadataHolder.setUuid(RandomStringUtils.randomAlphanumeric(40)); underTest.finished(true); verify(postProjectAnalysisTask).finished(taskContextCaptor.capture()); assertThat(taskContextCaptor.getValue().getProjectAnalysis().getAnalysis().get().getDate()) .isEqualTo(new Date(analysisMetadataHolder.getAnalysisDate())); assertThat(taskContextCaptor.getValue().getProjectAnalysis().getAnalysis().get().getAnalysisUuid()) .isEqualTo(analysisMetadataHolder.getUuid()); } @Test public void analysis_is_empty_when_not_set_in_AnalysisMetadataHolder() { underTest.finished(false); verify(postProjectAnalysisTask).finished(taskContextCaptor.capture()); assertThat(taskContextCaptor.getValue().getProjectAnalysis().getAnalysis()).isEmpty(); } @Test public void branch_comes_from_AnalysisMetadataHolder_when_set() { analysisMetadataHolder.setBranch(new Branch() { @Override public BranchType getType() { return BranchType.BRANCH; } @Override public boolean isMain() { return false; } @Override public String getReferenceBranchUuid() { throw new UnsupportedOperationException(); } @Override public String getName() { return "feature/foo"; } @Override public boolean supportsCrossProjectCpd() { throw new UnsupportedOperationException(); } @Override public String getPullRequestKey() { throw new UnsupportedOperationException(); } @Override public String getTargetBranchName() { throw new UnsupportedOperationException(); } @Override public String generateKey(String projectKey, @Nullable String fileOrDirPath) { throw new UnsupportedOperationException(); } }); underTest.finished(true); verify(postProjectAnalysisTask).finished(taskContextCaptor.capture()); org.sonar.api.ce.posttask.Branch branch = taskContextCaptor.getValue().getProjectAnalysis().getBranch().get(); assertThat(branch.isMain()).isFalse(); assertThat(branch.getName()).hasValue("feature/foo"); assertThat(branch.getType()).isEqualTo(BranchImpl.Type.BRANCH); } @Test public void qualityGate_is_null_when_finished_method_argument_is_false() { underTest.finished(false); verify(postProjectAnalysisTask).finished(taskContextCaptor.capture()); assertThat(taskContextCaptor.getValue().getProjectAnalysis().getQualityGate()).isNull(); } @Test public void qualityGate_is_populated_when_finished_method_argument_is_true() { underTest.finished(true); verify(postProjectAnalysisTask).finished(taskContextCaptor.capture()); org.sonar.api.ce.posttask.QualityGate qualityGate = taskContextCaptor.getValue().getProjectAnalysis().getQualityGate(); assertThat(qualityGate.getStatus()).isEqualTo(org.sonar.api.ce.posttask.QualityGate.Status.OK); assertThat(qualityGate.getId()).isEqualTo(QUALITY_GATE_UUID); assertThat(qualityGate.getName()).isEqualTo(QUALITY_GATE_NAME); assertThat(qualityGate.getConditions()).hasSize(2); } @Test public void scannerContext_loads_properties_from_scanner_report() { reportReader.putContextProperties(asList(ScannerReport.ContextProperty.newBuilder().setKey("foo").setValue("bar").build())); underTest.finished(true); verify(postProjectAnalysisTask).finished(taskContextCaptor.capture()); org.sonar.api.ce.posttask.ScannerContext scannerContext = taskContextCaptor.getValue().getProjectAnalysis().getScannerContext(); assertThat(scannerContext.getProperties()).containsExactly(entry("foo", "bar")); } @Test @UseDataProvider("booleanValues") public void logStatistics_add_fails_when_NPE_if_key_or_value_is_null(boolean allStepsExecuted) { underTest.finished(allStepsExecuted); verify(postProjectAnalysisTask).finished(taskContextCaptor.capture()); PostProjectAnalysisTask.LogStatistics logStatistics = taskContextCaptor.getValue().getLogStatistics(); assertThat(catchThrowable(() -> logStatistics.add(null, "foo"))) .isInstanceOf(NullPointerException.class) .hasMessage("Statistic has null key"); assertThat(catchThrowable(() -> logStatistics.add(null, null))) .isInstanceOf(NullPointerException.class) .hasMessage("Statistic has null key"); assertThat(catchThrowable(() -> logStatistics.add("bar", null))) .isInstanceOf(NullPointerException.class) .hasMessage("Statistic with key [bar] has null value"); } @Test @UseDataProvider("booleanValues") public void logStatistics_add_fails_with_IAE_if_key_is_time_or_status_ignoring_case(boolean allStepsExecuted) { underTest.finished(allStepsExecuted); verify(postProjectAnalysisTask).finished(taskContextCaptor.capture()); PostProjectAnalysisTask.LogStatistics logStatistics = taskContextCaptor.getValue().getLogStatistics(); for (String reservedKey : asList("time", "TIME", "TImE", "status", "STATUS", "STaTuS")) { assertThat(catchThrowable(() -> logStatistics.add(reservedKey, "foo"))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Statistic with key [" + reservedKey + "] is not accepted"); } } @Test @UseDataProvider("booleanValues") public void logStatistics_add_fails_with_IAE_if_same_key_with_exact_case_added_twice(boolean allStepsExecuted) { underTest.finished(allStepsExecuted); verify(postProjectAnalysisTask).finished(taskContextCaptor.capture()); PostProjectAnalysisTask.LogStatistics logStatistics = taskContextCaptor.getValue().getLogStatistics(); String key = RandomStringUtils.randomAlphabetic(10); logStatistics.add(key, new Object()); assertThat(catchThrowable(() -> logStatistics.add(key, "bar"))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Statistic with key [" + key + "] is already present"); } @Test @UseDataProvider("booleanValues") public void logStatistics_adds_statistics_to_end_of_task_log(boolean allStepsExecuted) { Map<String, Object> stats = new HashMap<>(); for (int i = 0; i <= new Random().nextInt(10); i++) { stats.put("statKey_" + i, "statVal_" + i); } PostProjectAnalysisTask logStatisticsTask = mock(PostProjectAnalysisTask.class); when(logStatisticsTask.getDescription()).thenReturn("PT1"); doAnswer(i -> { PostProjectAnalysisTask.Context context = i.getArgument(0); stats.forEach((k, v) -> context.getLogStatistics().add(k, v)); return null; }).when(logStatisticsTask) .finished(any(PostProjectAnalysisTask.Context.class)); new PostProjectAnalysisTasksExecutor( ceTask, analysisMetadataHolder, qualityGateHolder, qualityGateStatusHolder, reportReader, new PostProjectAnalysisTask[] {logStatisticsTask}) .finished(allStepsExecuted); verify(logStatisticsTask).finished(taskContextCaptor.capture()); assertThat(logTester.logs()).hasSize(1); List<String> logs = logTester.logs(Level.INFO); assertThat(logs).hasSize(1); StringBuilder expectedLog = new StringBuilder("^PT1 "); stats.forEach((k, v) -> expectedLog.append("\\| " + k + "=" + v + " ")); expectedLog.append("\\| status=SUCCESS \\| time=\\d+ms$"); assertThat(logs.get(0)).matches(expectedLog.toString()); } @Test @UseDataProvider("booleanValues") public void finished_does_not_fail_if_listener_throws_exception_and_execute_subsequent_listeners(boolean allStepsExecuted) { PostProjectAnalysisTask postProjectAnalysisTask1 = newPostProjectAnalysisTask("PT1"); PostProjectAnalysisTask postProjectAnalysisTask2 = newPostProjectAnalysisTask("PT2"); PostProjectAnalysisTask postProjectAnalysisTask3 = newPostProjectAnalysisTask("PT3"); InOrder inOrder = inOrder(postProjectAnalysisTask1, postProjectAnalysisTask2, postProjectAnalysisTask3); doThrow(new RuntimeException("Faking a listener throws an exception")) .when(postProjectAnalysisTask2) .finished(any(PostProjectAnalysisTask.Context.class)); new PostProjectAnalysisTasksExecutor( ceTask, analysisMetadataHolder, qualityGateHolder, qualityGateStatusHolder, reportReader, new PostProjectAnalysisTask[] {postProjectAnalysisTask1, postProjectAnalysisTask2, postProjectAnalysisTask3}) .finished(allStepsExecuted); inOrder.verify(postProjectAnalysisTask1).finished(taskContextCaptor.capture()); inOrder.verify(postProjectAnalysisTask1).getDescription(); inOrder.verify(postProjectAnalysisTask2).finished(taskContextCaptor.capture()); inOrder.verify(postProjectAnalysisTask2).getDescription(); inOrder.verify(postProjectAnalysisTask3).finished(taskContextCaptor.capture()); inOrder.verify(postProjectAnalysisTask3).getDescription(); inOrder.verifyNoMoreInteractions(); assertThat(logTester.logs()).hasSize(4); List<String> logs = logTester.logs(Level.INFO); assertThat(logs).hasSize(3); assertThat(logs.get(0)).matches("^PT1 \\| status=SUCCESS \\| time=\\d+ms$"); assertThat(logs.get(1)).matches("^PT2 \\| status=FAILED \\| time=\\d+ms$"); assertThat(logs.get(2)).matches("^PT3 \\| status=SUCCESS \\| time=\\d+ms$"); } @DataProvider public static Object[][] booleanValues() { return new Object[][] { {true}, {false} }; } private static Condition createCondition(String metricKey) { Metric metric = mock(Metric.class); when(metric.getKey()).thenReturn(metricKey); return new Condition(metric, Condition.Operator.LESS_THAN.getDbValue(), "error threshold"); } private static PostProjectAnalysisTask newPostProjectAnalysisTask(String description) { PostProjectAnalysisTask res = mock(PostProjectAnalysisTask.class); when(res.getDescription()).thenReturn(description); doAnswer(i -> null).when(res).finished(any(PostProjectAnalysisTask.Context.class)); return res; } private static List<PostProjectAnalysisTask.ProjectAnalysis> getAllProjectAnalyses(ArgumentCaptor<PostProjectAnalysisTask.Context> taskContextCaptor) { return taskContextCaptor.getAllValues() .stream() .map(PostProjectAnalysisTask.Context::getProjectAnalysis) .collect(toList()); } }
19,995
42.094828
153
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/posttask/ProjectImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.api.posttask; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ProjectImplTest { private static final String SOME_UUID = "some uuid"; private static final String SOME_KEY = "some key"; private static final String SOME_NAME = "some name"; @Test public void constructor_throws_NPE_if_uuid_is_null() { assertThatThrownBy(() -> new ProjectImpl(null, SOME_KEY, SOME_NAME)) .isInstanceOf(NullPointerException.class) .hasMessage("uuid can not be null"); } @Test public void constructor_throws_NPE_if_key_is_null() { assertThatThrownBy(() -> new ProjectImpl(SOME_UUID, null, SOME_NAME)) .isInstanceOf(NullPointerException.class) .hasMessage("key can not be null"); } @Test public void constructor_throws_NPE_if_name_is_null() { assertThatThrownBy(() -> new ProjectImpl(SOME_UUID, SOME_KEY, null)) .isInstanceOf(NullPointerException.class) .hasMessage("name can not be null"); } @Test public void verify_getters() { ProjectImpl underTest = new ProjectImpl(SOME_UUID, SOME_KEY, SOME_NAME); assertThat(underTest.getUuid()).isEqualTo(SOME_UUID); assertThat(underTest.getKey()).isEqualTo(SOME_KEY); assertThat(underTest.getName()).isEqualTo(SOME_NAME); } @Test public void verify_toString() { assertThat(new ProjectImpl(SOME_UUID, SOME_KEY, SOME_NAME)) .hasToString("ProjectImpl{uuid='some uuid', key='some key', name='some name'}"); } }
2,444
33.928571
86
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/posttask/QualityGateImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.api.posttask; import com.google.common.collect.ImmutableList; import java.util.Collections; import java.util.List; import org.junit.Test; import org.sonar.api.ce.posttask.QualityGate; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class QualityGateImplTest { private static final String SOME_ID = "some id"; private static final String SOME_NAME = "some name"; private static final QualityGate.Status SOME_STATUS = QualityGate.Status.OK; private QualityGate.Condition condition = mock(QualityGate.Condition.class); private QualityGateImpl underTest = new QualityGateImpl(SOME_ID, SOME_NAME, SOME_STATUS, ImmutableList.of(condition)); @Test public void constructor_throws_NPE_if_id_argument_is_null() { assertThatThrownBy(() -> new QualityGateImpl(null, SOME_NAME, SOME_STATUS, Collections.emptyList())) .isInstanceOf(NullPointerException.class) .hasMessage("id can not be null"); } @Test public void constructor_throws_NPE_if_name_argument_is_null() { assertThatThrownBy(() -> new QualityGateImpl(SOME_ID, null, SOME_STATUS, Collections.emptyList())) .isInstanceOf(NullPointerException.class) .hasMessage("name can not be null"); } @Test public void constructor_throws_NPE_if_status_argument_is_null() { assertThatThrownBy(() -> new QualityGateImpl(SOME_ID, SOME_NAME, null, Collections.emptyList())) .isInstanceOf(NullPointerException.class) .hasMessage("status can not be null"); } @Test public void constructor_throws_NPE_if_conditions_argument_is_null() { assertThatThrownBy(() -> new QualityGateImpl(SOME_ID, SOME_NAME, SOME_STATUS, null)) .isInstanceOf(NullPointerException.class) .hasMessage("conditions can not be null"); } @Test public void verify_getters() { List<QualityGate.Condition> conditions = ImmutableList.of(condition); QualityGateImpl underTest = new QualityGateImpl(SOME_ID, SOME_NAME, SOME_STATUS, conditions); assertThat(underTest.getId()).isEqualTo(SOME_ID); assertThat(underTest.getName()).isEqualTo(SOME_NAME); assertThat(underTest.getStatus()).isEqualTo(SOME_STATUS); assertThat(underTest.getConditions()).isEqualTo(conditions); } @Test public void verify_toString() { when(condition.toString()).thenReturn("{Condition}"); assertThat(underTest) .hasToString("QualityGateImpl{id='some id', name='some name', status=OK, conditions=[{Condition}]}"); } }
3,489
37.777778
120
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/posttask/TestPostTaskLogStatistics.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.api.posttask; import java.util.HashMap; import java.util.Map; import org.sonar.api.ce.posttask.PostProjectAnalysisTask; import static com.google.common.base.Preconditions.checkArgument; import static java.lang.String.format; import static java.util.Objects.requireNonNull; class TestPostTaskLogStatistics implements PostProjectAnalysisTask.LogStatistics { private final Map<String, Object> stats = new HashMap<>(); @Override public PostProjectAnalysisTask.LogStatistics add(String key, Object value) { requireNonNull(key, "Statistic has null key"); requireNonNull(value, () -> format("Statistic with key [%s] has null value", key)); checkArgument(!key.equalsIgnoreCase("time"), "Statistic with key [time] is not accepted"); checkArgument(!stats.containsKey(key), "Statistic with key [%s] is already present", key); stats.put(key, value); return this; } public Map<String, Object> getStats() { return stats; } }
1,841
38.191489
94
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/batch/BatchReportDirectoryHolderImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.batch; import java.io.File; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class BatchReportDirectoryHolderImplTest { @Test public void getDirectory_throws_ISE_if_holder_is_empty() { assertThatThrownBy(() -> new BatchReportDirectoryHolderImpl().getDirectory()) .isInstanceOf(IllegalStateException.class); } @Test public void getDirectory_returns_File_set_with_setDirectory() { File file = new File(""); BatchReportDirectoryHolderImpl holder = new BatchReportDirectoryHolderImpl(); holder.setDirectory(file); assertThat(holder.getDirectory()).isSameAs(file); } }
1,599
34.555556
82
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/batch/BatchReportReaderImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.batch; import com.google.common.collect.ImmutableList; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.impl.utils.JUnitTempFolder; import org.sonar.core.util.CloseableIterator; import org.sonar.scanner.protocol.output.FileStructure; import org.sonar.scanner.protocol.output.ScannerReport; import org.sonar.scanner.protocol.output.ScannerReportWriter; import static com.google.common.collect.ImmutableList.of; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class BatchReportReaderImplTest { private static final int COMPONENT_REF = 1; private static final ScannerReport.Changesets CHANGESETS = ScannerReport.Changesets.newBuilder().setComponentRef(COMPONENT_REF).build(); private static final ScannerReport.Measure MEASURE = ScannerReport.Measure.newBuilder().build(); private static final ScannerReport.Component COMPONENT = ScannerReport.Component.newBuilder().setRef(COMPONENT_REF).build(); private static final ScannerReport.Issue ISSUE = ScannerReport.Issue.newBuilder().build(); private static final ScannerReport.Duplication DUPLICATION = ScannerReport.Duplication.newBuilder().build(); private static final ScannerReport.CpdTextBlock DUPLICATION_BLOCK = ScannerReport.CpdTextBlock.newBuilder().build(); private static final ScannerReport.Symbol SYMBOL = ScannerReport.Symbol.newBuilder().build(); private static final ScannerReport.SyntaxHighlightingRule SYNTAX_HIGHLIGHTING_1 = ScannerReport.SyntaxHighlightingRule.newBuilder().build(); private static final ScannerReport.SyntaxHighlightingRule SYNTAX_HIGHLIGHTING_2 = ScannerReport.SyntaxHighlightingRule.newBuilder().build(); private static final ScannerReport.LineCoverage COVERAGE_1 = ScannerReport.LineCoverage.newBuilder().build(); private static final ScannerReport.LineCoverage COVERAGE_2 = ScannerReport.LineCoverage.newBuilder().build(); @Rule public JUnitTempFolder tempFolder = new JUnitTempFolder(); private ScannerReportWriter writer; private BatchReportReaderImpl underTest; @Before public void setUp() { BatchReportDirectoryHolder holder = new ImmutableBatchReportDirectoryHolder(tempFolder.newDir()); underTest = new BatchReportReaderImpl(holder); FileStructure fileStructure = new FileStructure(holder.getDirectory()); writer = new ScannerReportWriter(fileStructure); } @Test public void readMetadata_throws_ISE_if_no_metadata() { assertThatThrownBy(() -> underTest.readMetadata()) .isInstanceOf(IllegalStateException.class); } @Test public void readMetadata_result_is_cached() { ScannerReport.Metadata metadata = ScannerReport.Metadata.newBuilder().build(); writer.writeMetadata(metadata); ScannerReport.Metadata res = underTest.readMetadata(); assertThat(res).isEqualTo(metadata); assertThat(underTest.readMetadata()).isSameAs(res); } @Test public void readScannerLogs() throws IOException { File scannerLogFile = writer.getFileStructure().analysisLog(); FileUtils.write(scannerLogFile, "log1\nlog2"); CloseableIterator<String> logs = underTest.readScannerLogs(); assertThat(logs).toIterable().containsExactly("log1", "log2"); } @Test public void readScannerLogs_no_logs() { CloseableIterator<String> logs = underTest.readScannerLogs(); assertThat(logs.hasNext()).isFalse(); } @Test public void readComponentMeasures_returns_empty_list_if_there_is_no_measure() { assertThat(underTest.readComponentMeasures(COMPONENT_REF)).isExhausted(); } @Test public void verify_readComponentMeasures_returns_measures() { writer.appendComponentMeasure(COMPONENT_REF, MEASURE); try (CloseableIterator<ScannerReport.Measure> measures = underTest.readComponentMeasures(COMPONENT_REF)) { assertThat(measures.next()).isEqualTo(MEASURE); assertThat(measures.hasNext()).isFalse(); } } @Test public void readComponentMeasures_is_not_cached() { writer.appendComponentMeasure(COMPONENT_REF, MEASURE); assertThat(underTest.readComponentMeasures(COMPONENT_REF)).isNotSameAs(underTest.readComponentMeasures(COMPONENT_REF)); } @Test public void readChangesets_returns_null_if_no_changeset() { assertThat(underTest.readChangesets(COMPONENT_REF)).isNull(); } @Test public void verify_readChangesets_returns_changesets() { writer.writeComponentChangesets(CHANGESETS); ScannerReport.Changesets res = underTest.readChangesets(COMPONENT_REF); assertThat(res).isEqualTo(CHANGESETS); } @Test public void readChangesets_is_not_cached() { writer.writeComponentChangesets(CHANGESETS); assertThat(underTest.readChangesets(COMPONENT_REF)).isNotSameAs(underTest.readChangesets(COMPONENT_REF)); } @Test public void readComponent_throws_ISE_if_file_does_not_exist() { assertThatThrownBy(() -> underTest.readComponent(COMPONENT_REF)) .isInstanceOf(IllegalStateException.class); } @Test public void verify_readComponent_returns_Component() { writer.writeComponent(COMPONENT); assertThat(underTest.readComponent(COMPONENT_REF)).isEqualTo(COMPONENT); } @Test public void readComponent_is_not_cached() { writer.writeComponent(COMPONENT); assertThat(underTest.readComponent(COMPONENT_REF)).isNotSameAs(underTest.readComponent(COMPONENT_REF)); } @Test public void readComponentIssues_returns_empty_list_if_file_does_not_exist() { assertThat(underTest.readComponentIssues(COMPONENT_REF)).isExhausted(); } @Test public void verify_readComponentIssues_returns_Issues() { writer.writeComponentIssues(COMPONENT_REF, of(ISSUE)); try (CloseableIterator<ScannerReport.Issue> res = underTest.readComponentIssues(COMPONENT_REF)) { assertThat(res.next()).isEqualTo(ISSUE); assertThat(res.hasNext()).isFalse(); } } @Test public void readComponentIssues_it_not_cached() { writer.writeComponentIssues(COMPONENT_REF, of(ISSUE)); assertThat(underTest.readComponentIssues(COMPONENT_REF)).isNotSameAs(underTest.readComponentIssues(COMPONENT_REF)); } @Test public void readComponentDuplications_returns_empty_list_if_file_does_not_exist() { assertThat(underTest.readComponentDuplications(COMPONENT_REF)).isExhausted(); } @Test public void verify_readComponentDuplications_returns_Issues() { writer.writeComponentDuplications(COMPONENT_REF, of(DUPLICATION)); try (CloseableIterator<ScannerReport.Duplication> res = underTest.readComponentDuplications(COMPONENT_REF)) { assertThat(res.next()).isEqualTo(DUPLICATION); assertThat(res.hasNext()).isFalse(); } } @Test public void readComponentDuplications_it_not_cached() { writer.writeComponentDuplications(COMPONENT_REF, of(DUPLICATION)); assertThat(underTest.readComponentDuplications(COMPONENT_REF)).isNotSameAs(underTest.readComponentDuplications(COMPONENT_REF)); } @Test public void readComponentDuplicationBlocks_returns_empty_list_if_file_does_not_exist() { assertThat(underTest.readCpdTextBlocks(COMPONENT_REF)).isExhausted(); } @Test public void verify_readComponentDuplicationBlocks_returns_Issues() { writer.writeCpdTextBlocks(COMPONENT_REF, of(DUPLICATION_BLOCK)); try (CloseableIterator<ScannerReport.CpdTextBlock> res = underTest.readCpdTextBlocks(COMPONENT_REF)) { assertThat(res.next()).isEqualTo(DUPLICATION_BLOCK); assertThat(res.hasNext()).isFalse(); } } @Test public void readComponentDuplicationBlocks_is_not_cached() { writer.writeCpdTextBlocks(COMPONENT_REF, of(DUPLICATION_BLOCK)); assertThat(underTest.readCpdTextBlocks(COMPONENT_REF)).isNotSameAs(underTest.readCpdTextBlocks(COMPONENT_REF)); } @Test public void readComponentSymbols_returns_empty_list_if_file_does_not_exist() { assertThat(underTest.readComponentSymbols(COMPONENT_REF)).isExhausted(); } @Test public void verify_readComponentSymbols_returns_Issues() { writer.writeComponentSymbols(COMPONENT_REF, of(SYMBOL)); try (CloseableIterator<ScannerReport.Symbol> res = underTest.readComponentSymbols(COMPONENT_REF)) { assertThat(res.next()).isEqualTo(SYMBOL); assertThat(res.hasNext()).isFalse(); } } @Test public void readComponentSymbols_it_not_cached() { writer.writeComponentSymbols(COMPONENT_REF, of(SYMBOL)); assertThat(underTest.readComponentSymbols(COMPONENT_REF)).isNotSameAs(underTest.readComponentSymbols(COMPONENT_REF)); } @Test public void readComponentSyntaxHighlighting_returns_empty_CloseableIterator_when_file_does_not_exist() { assertThat(underTest.readComponentSyntaxHighlighting(COMPONENT_REF)).isExhausted(); } @Test public void verify_readComponentSyntaxHighlighting() { writer.writeComponentSyntaxHighlighting(COMPONENT_REF, of(SYNTAX_HIGHLIGHTING_1, SYNTAX_HIGHLIGHTING_2)); CloseableIterator<ScannerReport.SyntaxHighlightingRule> res = underTest.readComponentSyntaxHighlighting(COMPONENT_REF); assertThat(res).toIterable().containsExactly(SYNTAX_HIGHLIGHTING_1, SYNTAX_HIGHLIGHTING_2); res.close(); } @Test public void readComponentCoverage_returns_empty_CloseableIterator_when_file_does_not_exist() { assertThat(underTest.readComponentCoverage(COMPONENT_REF)).isExhausted(); } @Test public void verify_readComponentCoverage() { writer.writeComponentCoverage(COMPONENT_REF, of(COVERAGE_1, COVERAGE_2)); CloseableIterator<ScannerReport.LineCoverage> res = underTest.readComponentCoverage(COMPONENT_REF); assertThat(res).toIterable().containsExactly(COVERAGE_1, COVERAGE_2); res.close(); } @Test public void readFileSource_returns_absent_optional_when_file_does_not_exist() { assertThat(underTest.readFileSource(COMPONENT_REF)).isEmpty(); } @Test public void verify_readFileSource() throws IOException { File file = writer.getSourceFile(COMPONENT_REF); FileUtils.writeLines(file, of("1", "2", "3")); CloseableIterator<String> res = underTest.readFileSource(COMPONENT_REF).get(); assertThat(res).toIterable().containsExactly("1", "2", "3"); res.close(); } @Test public void verify_readAnalysisWarnings() { ScannerReport.AnalysisWarning warning1 = ScannerReport.AnalysisWarning.newBuilder().setText("warning 1").build(); ScannerReport.AnalysisWarning warning2 = ScannerReport.AnalysisWarning.newBuilder().setText("warning 2").build(); ImmutableList<ScannerReport.AnalysisWarning> warnings = of(warning1, warning2); writer.writeAnalysisWarnings(warnings); CloseableIterator<ScannerReport.AnalysisWarning> res = underTest.readAnalysisWarnings(); assertThat(res).toIterable().containsExactlyElementsOf(warnings); res.close(); } }
11,767
37.710526
142
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/batch/BatchReportReaderRule.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.batch; import com.google.common.base.Preconditions; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; import org.sonar.core.util.CloseableIterator; import org.sonar.scanner.protocol.output.ScannerReport; import org.sonar.scanner.protocol.output.ScannerReport.LineSgnificantCode; public class BatchReportReaderRule implements TestRule, BatchReportReader { private ScannerReport.Metadata metadata; private List<String> scannerLogs; private List<ScannerReport.ActiveRule> activeRules = new ArrayList<>(); private List<ScannerReport.ContextProperty> contextProperties = new ArrayList<>(); private Map<Integer, List<ScannerReport.Measure>> measures = new HashMap<>(); private Map<Integer, ScannerReport.Changesets> changesets = new HashMap<>(); private Map<Integer, ScannerReport.Component> components = new HashMap<>(); private Map<Integer, List<ScannerReport.Issue>> issues = new HashMap<>(); private Map<Integer, List<ScannerReport.ExternalIssue>> externalIssues = new HashMap<>(); private List<ScannerReport.AdHocRule> adHocRules = new ArrayList<>(); private Map<Integer, List<ScannerReport.Duplication>> duplications = new HashMap<>(); private Map<Integer, List<ScannerReport.CpdTextBlock>> duplicationBlocks = new HashMap<>(); private Map<Integer, List<ScannerReport.Symbol>> symbols = new HashMap<>(); private Map<Integer, List<ScannerReport.SyntaxHighlightingRule>> syntaxHighlightings = new HashMap<>(); private Map<Integer, List<ScannerReport.LineCoverage>> coverages = new HashMap<>(); private Map<Integer, List<String>> fileSources = new HashMap<>(); private Map<Integer, List<ScannerReport.LineSgnificantCode>> significantCode = new HashMap<>(); private Map<Integer, ScannerReport.ChangedLines> changedLines = new HashMap<>(); private List<ScannerReport.AnalysisWarning> analysisWarnings = Collections.emptyList(); private byte[] analysisCache; @Override public Statement apply(final Statement statement, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { try { statement.evaluate(); } finally { clear(); } } }; } private void clear() { this.metadata = null; this.scannerLogs = null; this.measures.clear(); this.changesets.clear(); this.components.clear(); this.issues.clear(); this.duplications.clear(); this.duplicationBlocks.clear(); this.symbols.clear(); this.syntaxHighlightings.clear(); this.coverages.clear(); this.fileSources.clear(); this.significantCode.clear(); } @Override public CloseableIterator<ScannerReport.ContextProperty> readContextProperties() { return CloseableIterator.from(contextProperties.iterator()); } public BatchReportReaderRule putContextProperties(List<ScannerReport.ContextProperty> contextProperties) { this.contextProperties = Objects.requireNonNull(contextProperties); return this; } @Override public ScannerReport.Metadata readMetadata() { if (metadata == null) { throw new IllegalStateException("Metadata is missing"); } return metadata; } @CheckForNull @Override public InputStream getAnalysisCache() { if (analysisCache == null) { return null; } return new ByteArrayInputStream(analysisCache); } public void setAnalysisCache(byte[] cache) { this.analysisCache = cache; } public BatchReportReaderRule setMetadata(ScannerReport.Metadata metadata) { this.metadata = metadata; return this; } @Override public CloseableIterator<String> readScannerLogs() { if (scannerLogs == null) { throw new IllegalStateException("Scanner logs are missing"); } return CloseableIterator.from(scannerLogs.iterator()); } public BatchReportReaderRule setScannerLogs(@Nullable List<String> logs) { this.scannerLogs = logs; return this; } @Override public CloseableIterator<ScannerReport.ActiveRule> readActiveRules() { if (activeRules == null) { throw new IllegalStateException("Active rules are not set"); } return CloseableIterator.from(activeRules.iterator()); } public BatchReportReaderRule putActiveRules(List<ScannerReport.ActiveRule> activeRules) { this.activeRules = activeRules; return this; } @Override public CloseableIterator<ScannerReport.Measure> readComponentMeasures(int componentRef) { return closeableIterator(this.measures.get(componentRef)); } public BatchReportReaderRule putMeasures(int componentRef, List<ScannerReport.Measure> measures) { this.measures.put(componentRef, measures); return this; } @Override @CheckForNull public ScannerReport.Changesets readChangesets(int componentRef) { return changesets.get(componentRef); } public BatchReportReaderRule putChangesets(ScannerReport.Changesets changesets) { this.changesets.put(changesets.getComponentRef(), changesets); return this; } @Override public ScannerReport.Component readComponent(int componentRef) { return components.get(componentRef); } public BatchReportReaderRule putComponent(ScannerReport.Component component) { this.components.put(component.getRef(), component); return this; } @Override public CloseableIterator<ScannerReport.Issue> readComponentIssues(int componentRef) { return closeableIterator(issues.get(componentRef)); } @Override public CloseableIterator<ScannerReport.ExternalIssue> readComponentExternalIssues(int componentRef) { return closeableIterator(externalIssues.get(componentRef)); } @Override public CloseableIterator<ScannerReport.AdHocRule> readAdHocRules() { return closeableIterator(adHocRules); } public BatchReportReaderRule putAdHocRules(List<ScannerReport.AdHocRule> adHocRules) { this.adHocRules = adHocRules; return this; } public BatchReportReaderRule putIssues(int componentRef, List<ScannerReport.Issue> issues) { this.issues.put(componentRef, issues); return this; } public BatchReportReaderRule putExternalIssues(int componentRef, List<ScannerReport.ExternalIssue> externalIssues) { this.externalIssues.put(componentRef, externalIssues); return this; } @Override public CloseableIterator<ScannerReport.Duplication> readComponentDuplications(int componentRef) { return closeableIterator(this.duplications.get(componentRef)); } public BatchReportReaderRule putDuplications(int componentRef, ScannerReport.Duplication... duplications) { this.duplications.put(componentRef, Arrays.asList(duplications)); return this; } @Override public CloseableIterator<ScannerReport.CpdTextBlock> readCpdTextBlocks(int componentRef) { return closeableIterator(this.duplicationBlocks.get(componentRef)); } public BatchReportReaderRule putDuplicationBlocks(int componentRef, List<ScannerReport.CpdTextBlock> duplicationBlocks) { this.duplicationBlocks.put(componentRef, duplicationBlocks); return this; } @Override public CloseableIterator<ScannerReport.Symbol> readComponentSymbols(int componentRef) { return closeableIterator(this.symbols.get(componentRef)); } private static <T> CloseableIterator<T> closeableIterator(@Nullable List<T> list) { return list == null ? CloseableIterator.emptyCloseableIterator() : CloseableIterator.from(list.iterator()); } public BatchReportReaderRule putSymbols(int componentRef, List<ScannerReport.Symbol> symbols) { this.symbols.put(componentRef, symbols); return this; } public BatchReportReaderRule putSignificantCode(int fileRef, List<ScannerReport.LineSgnificantCode> significantCode) { this.significantCode.put(fileRef, significantCode); return this; } @Override public Optional<CloseableIterator<LineSgnificantCode>> readComponentSignificantCode(int fileRef) { List<LineSgnificantCode> list = significantCode.get(fileRef); return list == null ? Optional.empty() : Optional.of(CloseableIterator.from(list.iterator())); } public BatchReportReaderRule putChangedLines(int fileRef, ScannerReport.ChangedLines fileChangedLines) { changedLines.put(fileRef, fileChangedLines); return this; } @Override public Optional<ScannerReport.ChangedLines> readComponentChangedLines(int fileRef) { return Optional.ofNullable(changedLines.get(fileRef)); } @Override public CloseableIterator<ScannerReport.AnalysisWarning> readAnalysisWarnings() { return closeableIterator(analysisWarnings); } public BatchReportReaderRule setAnalysisWarnings(List<ScannerReport.AnalysisWarning> analysisWarnings) { this.analysisWarnings = new ArrayList<>(analysisWarnings); return this; } @Override public CloseableIterator<ScannerReport.SyntaxHighlightingRule> readComponentSyntaxHighlighting(int fileRef) { return closeableIterator(this.syntaxHighlightings.get(fileRef)); } public BatchReportReaderRule putSyntaxHighlighting(int fileRef, List<ScannerReport.SyntaxHighlightingRule> syntaxHighlightings) { this.syntaxHighlightings.put(fileRef, syntaxHighlightings); return this; } @Override public CloseableIterator<ScannerReport.LineCoverage> readComponentCoverage(int fileRef) { return closeableIterator(this.coverages.get(fileRef)); } public BatchReportReaderRule putCoverage(int fileRef, List<ScannerReport.LineCoverage> coverages) { this.coverages.put(fileRef, coverages); return this; } @Override public Optional<CloseableIterator<String>> readFileSource(int fileRef) { List<String> lines = fileSources.get(fileRef); if (lines == null) { return Optional.empty(); } return Optional.of(CloseableIterator.from(lines.iterator())); } public BatchReportReaderRule putFileSourceLines(int fileRef, @Nullable String... lines) { Preconditions.checkNotNull(lines); this.fileSources.put(fileRef, Arrays.asList(lines)); return this; } public BatchReportReaderRule putFileSourceLines(int fileRef, List<String> lines) { this.fileSources.put(fileRef, lines); return this; } }
11,408
34.212963
131
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/batch/ImmutableBatchReportDirectoryHolder.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.batch; import java.io.File; import java.util.Objects; public class ImmutableBatchReportDirectoryHolder implements BatchReportDirectoryHolder { private final File directory; public ImmutableBatchReportDirectoryHolder(File directory) { this.directory = Objects.requireNonNull(directory); } @Override public File getDirectory() { return directory; } }
1,258
33.027027
88
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/BranchLoaderTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if 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.junit.Rule; import org.junit.Test; import org.sonar.api.utils.MessageException; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.ce.task.projectanalysis.analysis.Branch; import org.sonar.scanner.protocol.output.ScannerReport; import org.sonar.server.project.DefaultBranchNameResolver; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.sonar.db.component.BranchDto.DEFAULT_MAIN_BRANCH_NAME; public class BranchLoaderTest { @Rule public AnalysisMetadataHolderRule metadataHolder = new AnalysisMetadataHolderRule(); @Test public void throw_ME_if_both_delegate_absent_and_has_branch_parameters() { ScannerReport.Metadata metadata = ScannerReport.Metadata.newBuilder() .setBranchName("bar") .build(); assertThatThrownBy(() -> new BranchLoader(metadataHolder, mock(DefaultBranchNameResolver.class)).load(metadata)) .isInstanceOf(MessageException.class) .hasMessage("Current edition does not support branch feature"); } @Test public void regular_analysis_of_project_is_enabled_if_delegate_is_absent() { ScannerReport.Metadata metadata = ScannerReport.Metadata.newBuilder() .build(); DefaultBranchNameResolver branchNameResolver = mock(DefaultBranchNameResolver.class); when(branchNameResolver.getEffectiveMainBranchName()).thenReturn(DEFAULT_MAIN_BRANCH_NAME); new BranchLoader(metadataHolder, branchNameResolver).load(metadata); assertThat(metadataHolder.getBranch()).isNotNull(); Branch branch = metadataHolder.getBranch(); assertThat(branch.isMain()).isTrue(); assertThat(branch.getName()).isEqualTo(DEFAULT_MAIN_BRANCH_NAME); } @Test public void default_support_of_branches_is_enabled_if_delegate_is_present_for_main_branch() { ScannerReport.Metadata metadata = ScannerReport.Metadata.newBuilder() .build(); BranchLoaderDelegate delegate = mock(BranchLoaderDelegate.class); new BranchLoader(metadataHolder, delegate, mock(DefaultBranchNameResolver.class)).load(metadata); verify(delegate, times(1)).load(metadata); } }
3,251
39.148148
116
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/CallRecord.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if 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.Objects; import javax.annotation.CheckForNull; import javax.annotation.Nullable; class CallRecord { private final String method; @CheckForNull private final Integer ref; @CheckForNull private final String key; private CallRecord(String method, @Nullable Integer ref, @Nullable String key) { this.method = method; this.ref = ref; this.key = key; } public static CallRecord reportCallRecord(String method, Integer ref) { return new CallRecord(method, ref, method); } public static CallRecord viewsCallRecord(String method, String key) { return new CallRecord(method, null, key); } @Override public boolean equals(@Nullable Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CallRecord that = (CallRecord) o; return Objects.equals(ref, that.ref) && Objects.equals(key, that.key) && Objects.equals(method, that.method); } @Override public int hashCode() { return Objects.hash(method, ref, key); } @Override public String toString() { return "{" + "method='" + method + '\'' + ", ref=" + ref + ", key=" + key + '}'; } }
2,132
27.44
82
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/CallRecorderPathAwareVisitor.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if 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.ArrayList; import java.util.List; import java.util.NoSuchElementException; import java.util.stream.StreamSupport; import static com.google.common.base.Preconditions.checkArgument; class CallRecorderPathAwareVisitor extends PathAwareVisitorAdapter<Integer> { final List<PathAwareCallRecord> callsRecords = new ArrayList<>(); public CallRecorderPathAwareVisitor(CrawlerDepthLimit maxDepth, Order order) { super(maxDepth, order, new SimpleStackElementFactory<Integer>() { @Override public Integer createForAny(Component component) { return component.getType().isReportType() ? component.getReportAttributes().getRef() : Integer.valueOf(component.getKey()); } }); } @Override public void visitProject(Component project, Path<Integer> path) { callsRecords.add(reportCallRecord(project, path, "visitProject")); } @Override public void visitDirectory(Component directory, Path<Integer> path) { callsRecords.add(reportCallRecord(directory, path, "visitDirectory")); } @Override public void visitFile(Component file, Path<Integer> path) { callsRecords.add(reportCallRecord(file, path, "visitFile")); } @Override public void visitView(Component view, Path<Integer> path) { callsRecords.add(viewsCallRecord(view, path, "visitView")); } @Override public void visitSubView(Component subView, Path<Integer> path) { callsRecords.add(viewsCallRecord(subView, path, "visitSubView")); } @Override public void visitProjectView(Component projectView, Path<Integer> path) { callsRecords.add(viewsCallRecord(projectView, path, "visitProjectView")); } @Override public void visitAny(Component component, Path<Integer> path) { callsRecords.add(component.getType().isReportType() ? reportCallRecord(component, path, "visitAny") : viewsCallRecord(component, path, "visitAny")); } private static PathAwareCallRecord reportCallRecord(Component component, Path<Integer> path, String method) { return PathAwareCallRecord.reportCallRecord(method, component.getReportAttributes().getRef(), path.current(), getParent(path), path.root(), toValueList(path)); } private static PathAwareCallRecord viewsCallRecord(Component component, Path<Integer> path, String method) { return PathAwareCallRecord.viewsCallRecord(method, component.getKey(), path.current(), getParent(path), path.root(), toValueList(path)); } private static List<Integer> toValueList(Path<Integer> path) { return StreamSupport.stream(path.getCurrentPath().spliterator(), false).map(PathElement::element).toList(); } private static Integer getParent(Path<Integer> path) { try { Integer parent = path.parent(); checkArgument(parent != null, "Path.parent returned a null value!"); return parent; } catch (NoSuchElementException e) { return null; } } }
3,794
36.95
152
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/CallRecorderTypeAwareVisitor.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if 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.ArrayList; import java.util.List; class CallRecorderTypeAwareVisitor extends TypeAwareVisitorAdapter { final List<CallRecord> callsRecords = new ArrayList<>(); public CallRecorderTypeAwareVisitor(CrawlerDepthLimit maxDepth, Order order) { super(maxDepth, order); } @Override public void visitProject(Component project) { callsRecords.add(reportCallRecord(project, "visitProject")); } @Override public void visitDirectory(Component directory) { callsRecords.add(reportCallRecord(directory, "visitDirectory")); } @Override public void visitFile(Component file) { callsRecords.add(reportCallRecord(file, "visitFile")); } @Override public void visitView(Component view) { callsRecords.add(viewsCallRecord(view, "visitView")); } @Override public void visitSubView(Component subView) { callsRecords.add(viewsCallRecord(subView, "visitSubView")); } @Override public void visitProjectView(Component projectView) { callsRecords.add(viewsCallRecord(projectView, "visitProjectView")); } @Override public void visitAny(Component component) { callsRecords.add(component.getType().isReportType() ? reportCallRecord(component, "visitAny") : viewsCallRecord(component, "visitAny")); } private static CallRecord reportCallRecord(Component component, String method) { return CallRecord.reportCallRecord(method, component.getReportAttributes().getRef()); } private static CallRecord viewsCallRecord(Component component, String method) { return CallRecord.viewsCallRecord(method, component.getKey()); } }
2,507
32
140
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ComponentFunctionsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if 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.Random; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT; import static org.sonar.ce.task.projectanalysis.component.ComponentFunctions.toComponentUuid; public class ComponentFunctionsTest { private static final int SOME_INT = new Random().nextInt(); @Test public void toComponentUuid_returns_the_ref_of_the_Component() { assertThat(toComponentUuid().apply(ReportComponent.builder(PROJECT, SOME_INT).setUuid("uuid_" + SOME_INT).build())).isEqualTo("uuid_" + SOME_INT); } }
1,515
38.894737
150
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ComponentImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if 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 java.util.Collections; import org.junit.Test; import org.sonar.ce.task.projectanalysis.component.Component.Status; import static com.google.common.base.Strings.repeat; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; import static org.sonar.ce.task.projectanalysis.component.Component.Type.FILE; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT; import static org.sonar.ce.task.projectanalysis.component.ComponentImpl.builder; public class ComponentImplTest { static final String KEY = "KEY"; static final String UUID = "UUID"; @Test public void verify_key_uuid_and_name() { ComponentImpl component = buildSimpleComponent(FILE, KEY).setUuid(UUID).setName("name").build(); assertThat(component.getKey()).isEqualTo(KEY); assertThat(component.getUuid()).isEqualTo(UUID); assertThat(component.getName()).isEqualTo("name"); } @Test public void builder_throws_NPE_if_component_arg_is_Null() { assertThatThrownBy(() -> builder(null)) .isInstanceOf(NullPointerException.class); } @Test public void builder_throws_NPE_if_status_arg_is_Null() { assertThatThrownBy(() -> builder(FILE).setStatus(null)) .isInstanceOf(NullPointerException.class); } @Test public void builder_throws_NPE_if_status_is_Null() { assertThatThrownBy(() -> { builder(Component.Type.DIRECTORY) .setName("DIR") .setKey(KEY) .setUuid(UUID) .setReportAttributes(ReportAttributes.newBuilder(1).build()) .build(); }) .isInstanceOf(NullPointerException.class); } @Test public void set_key_throws_NPE_if_component_arg_is_Null() { assertThatThrownBy(() -> builder(FILE).setUuid(null)) .isInstanceOf(NullPointerException.class); } @Test public void set_uuid_throws_NPE_if_component_arg_is_Null() { assertThatThrownBy(() -> builder(FILE).setKey(null)) .isInstanceOf(NullPointerException.class); } @Test public void build_without_key_throws_NPE_if_component_arg_is_Null() { assertThatThrownBy(() -> builder(FILE).setUuid("ABCD").build()) .isInstanceOf(NullPointerException.class); } @Test public void build_without_uuid_throws_NPE_if_component_arg_is_Null() { assertThatThrownBy(() -> builder(FILE).setKey(KEY).build()) .isInstanceOf(NullPointerException.class); } @Test public void get_name_from_batch_component() { String name = "project"; ComponentImpl component = buildSimpleComponent(FILE, "file").setName(name).build(); assertThat(component.getName()).isEqualTo(name); } @Test public void getFileAttributes_throws_ISE_if_BatchComponent_does_not_have_type_FILE() { Arrays.stream(Component.Type.values()) .filter(type -> type != FILE) .forEach((componentType) -> { ComponentImpl component = buildSimpleComponent(componentType, componentType.name()).build(); try { component.getFileAttributes(); fail("A IllegalStateException should have been raised"); } catch (IllegalStateException e) { assertThat(e).hasMessage("Only component of type FILE have a FileAttributes object"); } }); } @Test public void getSubViewAttributes_throws_ISE_if_component_is_not_have_type_SUBVIEW() { Arrays.stream(Component.Type.values()) .filter(type -> type != FILE) .forEach((componentType) -> { ComponentImpl component = buildSimpleComponent(componentType, componentType.name()).build(); try { component.getSubViewAttributes(); fail("A IllegalStateException should have been raised"); } catch (IllegalStateException e) { assertThat(e).hasMessage("Only component of type SUBVIEW have a SubViewAttributes object"); } }); } @Test public void getViewAttributes_throws_ISE_if_component_is_not_have_type_VIEW() { Arrays.stream(Component.Type.values()) .filter(type -> type != FILE) .forEach((componentType) -> { ComponentImpl component = buildSimpleComponent(componentType, componentType.name()).build(); try { component.getViewAttributes(); fail("A IllegalStateException should have been raised"); } catch (IllegalStateException e) { assertThat(e).hasMessage("Only component of type VIEW have a ViewAttributes object"); } }); } @Test public void isUnitTest_returns_true_if_IsTest_is_set_in_BatchComponent() { ComponentImpl component = buildSimpleComponent(FILE, "file").setFileAttributes(new FileAttributes(true, null, 1)).build(); assertThat(component.getFileAttributes().isUnitTest()).isTrue(); } @Test public void isUnitTest_returns_value_of_language_of_BatchComponent() { String languageKey = "some language key"; ComponentImpl component = buildSimpleComponent(FILE, "file").setFileAttributes(new FileAttributes(false, languageKey, 1)).build(); assertThat(component.getFileAttributes().getLanguageKey()).isEqualTo(languageKey); } @Test public void keep_500_first_characters_of_name() { String veryLongString = repeat("a", 3_000); ComponentImpl underTest = buildSimpleComponent(FILE, "file") .setName(veryLongString) .build(); String expectedName = repeat("a", 500 - 3) + "..."; assertThat(underTest.getName()).isEqualTo(expectedName); } @Test public void keep_2000_first_characters_of_description() { String veryLongString = repeat("a", 3_000); ComponentImpl underTest = buildSimpleComponent(FILE, "file") .setDescription(veryLongString) .build(); String expectedDescription = repeat("a", 2_000 - 3) + "..."; assertThat(underTest.getDescription()).isEqualTo(expectedDescription); } @Test public void build_with_child() { ComponentImpl child = builder(FILE) .setName("CHILD_NAME") .setKey("CHILD_KEY") .setUuid("CHILD_UUID") .setStatus(Status.UNAVAILABLE) .setReportAttributes(ReportAttributes.newBuilder(2).build()) .build(); ComponentImpl componentImpl = builder(Component.Type.DIRECTORY) .setName("DIR") .setKey(KEY) .setUuid(UUID) .setStatus(Status.UNAVAILABLE) .setReportAttributes(ReportAttributes.newBuilder(1).build()) .addChildren(Collections.singletonList(child)) .build(); assertThat(componentImpl.getChildren()).hasSize(1); Component childReloaded = componentImpl.getChildren().iterator().next(); assertThat(childReloaded.getKey()).isEqualTo("CHILD_KEY"); assertThat(childReloaded.getUuid()).isEqualTo("CHILD_UUID"); assertThat(childReloaded.getType()).isEqualTo(FILE); } @Test public void equals_compares_on_uuid_only() { ComponentImpl.Builder builder = buildSimpleComponent(FILE, "1").setUuid(UUID); assertThat(builder.build()).isEqualTo(builder.build()); assertThat(builder.build()).isEqualTo(buildSimpleComponent(FILE, "2").setUuid(UUID).build()); assertThat(builder.build()).isNotEqualTo(buildSimpleComponent(FILE, "1").setUuid("otherUUid").build()); } @Test public void hashCode_is_hashcode_of_uuid() { ComponentImpl.Builder builder = buildSimpleComponent(FILE, "1").setUuid(UUID); assertThat(builder.build()).hasSameHashCodeAs(builder.build().hashCode()); assertThat(builder.build()).hasSameHashCodeAs(buildSimpleComponent(FILE, "2").setUuid(UUID).build().hashCode()); assertThat(builder.build()).hasSameHashCodeAs(UUID.hashCode()); } private static ComponentImpl.Builder buildSimpleComponent(Component.Type type, String dbKey) { ComponentImpl.Builder builder = builder(type) .setName("name_" + dbKey) .setKey(dbKey) .setStatus(Status.UNAVAILABLE) .setUuid("uuid_" + dbKey) .setReportAttributes(ReportAttributes.newBuilder(dbKey.hashCode()).build()); if (type == PROJECT) { String buildString = randomAlphabetic(15); builder.setProjectAttributes(new ProjectAttributes("version_1", buildString, "453def")); } return builder; } }
9,168
35.971774
134
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ComponentTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if 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 org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.ce.task.projectanalysis.component.Component.Type.DIRECTORY; import static org.sonar.ce.task.projectanalysis.component.Component.Type.FILE; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT_VIEW; import static org.sonar.ce.task.projectanalysis.component.Component.Type.SUBVIEW; import static org.sonar.ce.task.projectanalysis.component.Component.Type.VIEW; public class ComponentTest { @Test public void verify_type_is_deeper_than_when_comparing_to_itself() { for (Component.Type type : Component.Type.values()) { assertThat(type.isDeeperThan(type)).isFalse(); } } @Test public void FILE_type_is_deeper_than_all_other_types() { assertThat(Component.Type.FILE.isDeeperThan(DIRECTORY)).isTrue(); assertThat(Component.Type.FILE.isDeeperThan(PROJECT)).isTrue(); } @Test public void DIRECTORY_type_is_deeper_than_PROJECT() { assertThat(Component.Type.DIRECTORY.isDeeperThan(PROJECT)).isTrue(); } @Test public void FILE_type_is_higher_than_no_other_types() { assertThat(Component.Type.FILE.isHigherThan(DIRECTORY)).isFalse(); assertThat(Component.Type.FILE.isHigherThan(PROJECT)).isFalse(); } @Test public void DIRECTORY_type_is_higher_than_FILE() { assertThat(Component.Type.DIRECTORY.isHigherThan(FILE)).isTrue(); } @Test public void PROJECT_type_is_higher_than_all_other_types() { assertThat(Component.Type.PROJECT.isHigherThan(FILE)).isTrue(); assertThat(Component.Type.PROJECT.isHigherThan(DIRECTORY)).isTrue(); } @Test public void any_type_is_not_higher_than_itself() { assertThat(Component.Type.FILE.isHigherThan(FILE)).isFalse(); assertThat(Component.Type.DIRECTORY.isHigherThan(DIRECTORY)).isFalse(); assertThat(Component.Type.PROJECT.isHigherThan(PROJECT)).isFalse(); } @Test public void PROJECT_MODULE_DIRECTORY_and_FILE_are_report_types_and_not_views_types() { for (Component.Type type : Arrays.asList(PROJECT, DIRECTORY, FILE)) { assertThat(type.isReportType()).isTrue(); assertThat(type.isViewsType()).isFalse(); } } @Test public void VIEW_SUBVIEW_and_PROJECT_VIEW_are_views_types_and_not_report_types() { for (Component.Type type : Arrays.asList(VIEW, SUBVIEW, PROJECT_VIEW)) { assertThat(type.isViewsType()).isTrue(); assertThat(type.isReportType()).isFalse(); } } }
3,479
36.419355
88
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ComponentTreeBuilderTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if 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 java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Random; import java.util.function.Function; import java.util.function.UnaryOperator; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExternalResource; import org.sonar.ce.task.projectanalysis.analysis.Branch; import org.sonar.core.component.ComponentKeys; import org.sonar.scanner.protocol.output.ScannerReport; import org.sonar.server.project.Project; import static com.google.common.base.Preconditions.checkArgument; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.PRE_ORDER; import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto; import static org.sonar.scanner.protocol.output.ScannerReport.Component.ComponentType.FILE; import static org.sonar.scanner.protocol.output.ScannerReport.Component.ComponentType.PROJECT; import static org.sonar.scanner.protocol.output.ScannerReport.Component.ComponentType.UNRECOGNIZED; import static org.sonar.scanner.protocol.output.ScannerReport.Component.newBuilder; public class ComponentTreeBuilderTest { private static final ComponentKeyGenerator KEY_GENERATOR = (projectKey, path) -> "generated_" + ComponentKeys.createEffectiveKey(projectKey, path); private static final UnaryOperator<String> UUID_SUPPLIER = (componentKey) -> componentKey + "_uuid"; private static final EnumSet<ScannerReport.Component.ComponentType> REPORT_TYPES = EnumSet.of(PROJECT, FILE); private static final String NO_SCM_BASE_PATH = ""; // both no project as "" or null should be supported private static final ProjectAttributes SOME_PROJECT_ATTRIBUTES = new ProjectAttributes( randomAlphabetic(20), new Random().nextBoolean() ? null : randomAlphabetic(12), "1def5123"); @Rule public ScannerComponentProvider scannerComponentProvider = new ScannerComponentProvider(); private Project projectInDb = Project.from(newPrivateProjectDto(UUID_SUPPLIER.apply("K1")).setKey("K1").setDescription(null)); @Test public void build_throws_IAE_for_all_types_except_PROJECT_and_FILE() { Arrays.stream(ScannerReport.Component.ComponentType.values()) .filter((type) -> type != UNRECOGNIZED) .filter((type) -> !REPORT_TYPES.contains(type)) .forEach( (type) -> { scannerComponentProvider.clear(); ScannerReport.Component project = newBuilder() .setType(PROJECT) .setKey(projectInDb.getKey()) .setRef(1) .addChildRef(2) .setProjectRelativePath("root") .build(); scannerComponentProvider.add(newBuilder() .setRef(2) .setType(type) .setProjectRelativePath("src") .setLines(1)); try { call(project, NO_SCM_BASE_PATH, SOME_PROJECT_ATTRIBUTES); fail("Should have thrown a IllegalArgumentException"); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Unsupported component type '" + type + "'"); } }); } @Test public void build_throws_IAE_if_root_is_not_PROJECT() { Arrays.stream(ScannerReport.Component.ComponentType.values()) .filter((type) -> type != UNRECOGNIZED) .filter((type) -> !REPORT_TYPES.contains(type)) .forEach( (type) -> { ScannerReport.Component component = newBuilder().setType(type).build(); try { call(component); fail("Should have thrown a IllegalArgumentException"); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Expected root component of type 'PROJECT'"); } }); } @Test public void by_default_project_fields_are_loaded_from_report() { String nameInReport = "the name"; String descriptionInReport = "the desc"; String buildString = randomAlphabetic(21); Component root = call(newBuilder() .setType(PROJECT) .setKey(projectInDb.getKey()) .setRef(42) .setName(nameInReport) .setDescription(descriptionInReport) .build(), NO_SCM_BASE_PATH, new ProjectAttributes("6.5", buildString, "4124af4")); assertThat(root.getUuid()).isEqualTo("generated_K1_uuid"); assertThat(root.getKey()).isEqualTo("generated_K1"); assertThat(root.getType()).isEqualTo(Component.Type.PROJECT); assertThat(root.getName()).isEqualTo(nameInReport); assertThat(root.getShortName()).isEqualTo(nameInReport); assertThat(root.getDescription()).isEqualTo(descriptionInReport); assertThat(root.getReportAttributes().getRef()).isEqualTo(42); assertThat(root.getProjectAttributes().getProjectVersion()).contains("6.5"); assertThat(root.getProjectAttributes().getBuildString()).isEqualTo(Optional.of(buildString)); assertThatFileAttributesAreNotSet(root); } @Test public void project_name_is_loaded_from_db_if_absent_from_report() { Component root = call(newBuilder() .setType(PROJECT) .build(), NO_SCM_BASE_PATH, SOME_PROJECT_ATTRIBUTES); assertThat(root.getName()).isEqualTo(projectInDb.getName()); } @Test public void project_name_is_loaded_from_report_if_present_and_on_main_branch() { String reportName = randomAlphabetic(5); ScannerReport.Component reportProject = newBuilder() .setType(PROJECT) .setName(reportName) .build(); Component root = newUnderTest(SOME_PROJECT_ATTRIBUTES, true).buildProject(reportProject, NO_SCM_BASE_PATH); assertThat(root.getName()).isEqualTo(reportName); } @Test public void project_name_is_loaded_from_db_if_not_on_main_branch() { String reportName = randomAlphabetic(5); ScannerReport.Component reportProject = newBuilder() .setType(PROJECT) .setName(reportName) .build(); Component root = newUnderTest(SOME_PROJECT_ATTRIBUTES, false) .buildProject(reportProject, NO_SCM_BASE_PATH); assertThat(root.getName()).isEqualTo(projectInDb.getName()); } @Test public void project_description_is_loaded_from_db_if_absent_from_report() { Component root = call(newBuilder() .setType(PROJECT) .build(), NO_SCM_BASE_PATH, SOME_PROJECT_ATTRIBUTES); assertThat(root.getDescription()).isEqualTo(projectInDb.getDescription()); } @Test public void project_description_is_loaded_from_report_if_present_and_on_main_branch() { String reportDescription = randomAlphabetic(5); ScannerReport.Component reportProject = newBuilder() .setType(PROJECT) .setDescription(reportDescription) .build(); Component root = newUnderTest(SOME_PROJECT_ATTRIBUTES, true).buildProject(reportProject, NO_SCM_BASE_PATH); assertThat(root.getDescription()).isEqualTo(reportDescription); } @Test public void project_description_is_loaded_from_db_if_not_on_main_branch() { String reportDescription = randomAlphabetic(5); ScannerReport.Component reportProject = newBuilder() .setType(PROJECT) .setDescription(reportDescription) .build(); Component root = newUnderTest(SOME_PROJECT_ATTRIBUTES, false).buildProject(reportProject, NO_SCM_BASE_PATH); assertThat(root.getDescription()).isEqualTo(projectInDb.getDescription()); } @Test public void project_scmPath_is_empty_if_scmBasePath_is_empty() { Component root = call(newBuilder() .setType(PROJECT) .build(), NO_SCM_BASE_PATH, SOME_PROJECT_ATTRIBUTES); assertThat(root.getReportAttributes().getScmPath()).isEmpty(); } @Test public void projectAttributes_is_constructor_argument() { Component root = call(newBuilder() .setType(PROJECT) .build(), NO_SCM_BASE_PATH, SOME_PROJECT_ATTRIBUTES); assertThat(root.getProjectAttributes()).isSameAs(SOME_PROJECT_ATTRIBUTES); } @Test public void any_component_with_projectRelativePath_has_this_value_as_scmPath_if_scmBasePath_is_empty() { ScannerReport.Component project = newBuilder() .setType(PROJECT) .setKey(projectInDb.getKey()) .setRef(1) .addChildRef(2) .setProjectRelativePath("root") .build(); scannerComponentProvider.add(newBuilder() .setRef(2) .setType(FILE) .setProjectRelativePath("src/js/Foo.js") .setLines(1)); Component root = call(project, NO_SCM_BASE_PATH, SOME_PROJECT_ATTRIBUTES); assertThat(root.getReportAttributes().getScmPath()) .contains("root"); Component directory = root.getChildren().iterator().next(); assertThat(directory.getReportAttributes().getScmPath()) .contains("src/js"); Component file = directory.getChildren().iterator().next(); assertThat(file.getReportAttributes().getScmPath()) .contains("src/js/Foo.js"); } @Test public void any_component_with_projectRelativePath_has_this_value_appended_to_scmBasePath_and_a_slash_as_scmPath_if_scmBasePath_is_not_empty() { ScannerReport.Component project = createProject(); String scmBasePath = randomAlphabetic(10); Component root = call(project, scmBasePath, SOME_PROJECT_ATTRIBUTES); assertThat(root.getReportAttributes().getScmPath()) .contains(scmBasePath); Component directory = root.getChildren().iterator().next(); assertThat(directory.getReportAttributes().getScmPath()) .contains(scmBasePath + "/src/js"); Component file = directory.getChildren().iterator().next(); assertThat(file.getReportAttributes().getScmPath()) .contains(scmBasePath + "/src/js/Foo.js"); } private ScannerReport.Component createProject() { ScannerReport.Component project = newBuilder() .setType(PROJECT) .setKey(projectInDb.getKey()) .setRef(1) .addChildRef(2) .build(); scannerComponentProvider.add(newBuilder() .setRef(2) .setType(FILE) .setProjectRelativePath("src/js/Foo.js") .setLines(1)); return project; } @Test public void keys_of_directory_and_file_are_generated() { ScannerReport.Component project = createProject(); Component root = call(project); assertThat(root.getKey()).isEqualTo("generated_" + projectInDb.getKey()); assertThat(root.getChildren()).hasSize(1); Component directory = root.getChildren().iterator().next(); assertThat(directory.getKey()).isEqualTo("generated_" + projectInDb.getKey() + ":src/js"); assertThat(directory.getChildren()).hasSize(1); Component file = directory.getChildren().iterator().next(); assertThat(file.getKey()).isEqualTo("generated_" + projectInDb.getKey() + ":src/js/Foo.js"); assertThat(file.getChildren()).isEmpty(); } @Test public void modules_are_not_created() { ScannerReport.Component project = newBuilder() .setType(PROJECT) .setKey(projectInDb.getKey()) .setRef(1) .addChildRef(2) .build(); scannerComponentProvider.add(newBuilder() .setRef(2) .setType(FILE) .setProjectRelativePath("src/js/Foo.js") .setLines(1)); Component root = call(project); List<Component> components = root.getChildren(); assertThat(components).extracting("type").containsOnly(Component.Type.DIRECTORY); } @Test public void folder_hierarchy_is_created() { ScannerReport.Component project = newBuilder() .setType(PROJECT) .setKey(projectInDb.getKey()) .setRef(1) .addChildRef(4) .addChildRef(5) .addChildRef(6) .build(); scannerComponentProvider.add(newBuilder() .setRef(4) .setType(FILE) .setProjectRelativePath("src/main/xoo/Foo1.js") .setLines(1)); scannerComponentProvider.add(newBuilder() .setRef(5) .setType(FILE) .setProjectRelativePath("src/test/xoo/org/sonar/Foo2.js") .setLines(1)); scannerComponentProvider.add(newBuilder() .setRef(6) .setType(FILE) .setProjectRelativePath("pom.xml") .setLines(1)); Component root = call(project); assertThat(root.getChildren()).hasSize(2); Component pom = root.getChildren().get(1); assertThat(pom.getKey()).isEqualTo("generated_K1:pom.xml"); assertThat(pom.getName()).isEqualTo("pom.xml"); Component directory = root.getChildren().get(0); assertThat(directory.getKey()).isEqualTo("generated_K1:src"); assertThat(directory.getName()).isEqualTo("src"); // folders are collapsed and they only contain one directory Component d1 = directory.getChildren().get(0); assertThat(d1.getKey()).isEqualTo("generated_K1:src/main/xoo"); assertThat(d1.getName()).isEqualTo("src/main/xoo"); assertThat(d1.getShortName()).isEqualTo("main/xoo"); Component d2 = directory.getChildren().get(1); assertThat(d2.getKey()).isEqualTo("generated_K1:src/test/xoo/org/sonar"); assertThat(d2.getName()).isEqualTo("src/test/xoo/org/sonar"); assertThat(d2.getShortName()).isEqualTo("test/xoo/org/sonar"); } @Test public void collapse_directories_from_root() { ScannerReport.Component project = newBuilder() .setType(PROJECT) .setKey(projectInDb.getKey()) .setRef(1) .addChildRef(2) .build(); scannerComponentProvider.add(newBuilder() .setRef(2) .setType(FILE) .setProjectRelativePath("src/test/xoo/org/sonar/Foo2.js") .setLines(1)); Component root = call(project); // folders are collapsed and they only contain one directory Component dir = root.getChildren().get(0); assertThat(dir.getKey()).isEqualTo("generated_K1:src/test/xoo/org/sonar"); assertThat(dir.getName()).isEqualTo("src/test/xoo/org/sonar"); assertThat(dir.getShortName()).isEqualTo("src/test/xoo/org/sonar"); Component file = dir.getChildren().get(0); assertThat(file.getKey()).isEqualTo("generated_K1:src/test/xoo/org/sonar/Foo2.js"); assertThat(file.getName()).isEqualTo("src/test/xoo/org/sonar/Foo2.js"); assertThat(file.getShortName()).isEqualTo("Foo2.js"); } @Test public void directories_are_collapsed() { ScannerReport.Component project = newBuilder() .setType(PROJECT) .setKey(projectInDb.getKey()) .setRef(1) .addChildRef(2) .build(); scannerComponentProvider.add(newBuilder() .setRef(2) .setType(FILE) .setProjectRelativePath("src/js/Foo.js") .setLines(1)); Component root = call(project); Component directory = root.getChildren().iterator().next(); assertThat(directory.getKey()).isEqualTo("generated_K1:src/js"); assertThat(directory.getName()).isEqualTo("src/js"); assertThat(directory.getShortName()).isEqualTo("src/js"); Component file = directory.getChildren().iterator().next(); assertThat(file.getKey()).isEqualTo("generated_K1:src/js/Foo.js"); assertThat(file.getName()).isEqualTo("src/js/Foo.js"); assertThat(file.getShortName()).isEqualTo("Foo.js"); } @Test public void names_of_directory_and_file_are_based_on_the_path() { ScannerReport.Component project = newBuilder() .setType(PROJECT) .setKey(projectInDb.getKey()) .setRef(1) .addChildRef(2) .build(); scannerComponentProvider.add(newBuilder() .setRef(2) .setType(FILE) .setProjectRelativePath("src/js/Foo.js") .setName("") .setLines(1)); Component root = call(project); Component directory = root.getChildren().iterator().next(); assertThat(directory.getName()).isEqualTo("src/js"); assertThat(directory.getShortName()).isEqualTo("src/js"); Component file = directory.getChildren().iterator().next(); assertThat(file.getName()).isEqualTo("src/js/Foo.js"); assertThat(file.getShortName()).isEqualTo("Foo.js"); } @Test public void create_full_hierarchy_of_directories() { ScannerReport.Component project = newBuilder() .setType(PROJECT) .setKey(projectInDb.getKey()) .setRef(1) .addChildRef(2) .addChildRef(3) .build(); scannerComponentProvider.add(newBuilder() .setRef(2) .setType(FILE) .setProjectRelativePath("src/java/Bar.java") .setName("") .setLines(2)); scannerComponentProvider.add(newBuilder() .setRef(3) .setType(FILE) .setProjectRelativePath("src/js/Foo.js") .setName("") .setLines(1)); Component root = call(project); Component directory = root.getChildren().iterator().next(); assertThat(directory.getKey()).isEqualTo("generated_K1:src"); assertThat(directory.getName()).isEqualTo("src"); assertThat(directory.getShortName()).isEqualTo("src"); Component directoryJava = directory.getChildren().get(0); assertThat(directoryJava.getKey()).isEqualTo("generated_K1:src/java"); assertThat(directoryJava.getName()).isEqualTo("src/java"); assertThat(directoryJava.getShortName()).isEqualTo("java"); Component directoryJs = directory.getChildren().get(1); assertThat(directoryJs.getKey()).isEqualTo("generated_K1:src/js"); assertThat(directoryJs.getName()).isEqualTo("src/js"); assertThat(directoryJs.getShortName()).isEqualTo("js"); Component file = directoryJs.getChildren().iterator().next(); assertThat(file.getKey()).isEqualTo("generated_K1:src/js/Foo.js"); assertThat(file.getName()).isEqualTo("src/js/Foo.js"); assertThat(file.getShortName()).isEqualTo("Foo.js"); } private void assertThatFileAttributesAreNotSet(Component root) { try { root.getFileAttributes(); fail(); } catch (IllegalStateException e) { assertThat(e).hasMessage("Only component of type FILE have a FileAttributes object"); } } @Test public void keys_of_directory_and_files_includes_always_root_project() { ScannerReport.Component project = newBuilder() .setType(PROJECT) .setKey("project 1") .setRef(1) .addChildRef(31).build(); scannerComponentProvider.add(newBuilder().setRef(31).setType(FILE).setProjectRelativePath("file in project").setLines(1)); Component root = call(project); Map<String, Component> componentsByKey = indexComponentByKey(root); assertThat(componentsByKey.values()).extracting("key").startsWith("generated_project 1"); } @Test public void uuids_are_provided_by_supplier() { ScannerReport.Component project = newBuilder() .setType(PROJECT) .setKey("c1") .setRef(1) .addChildRef(2) .build(); scannerComponentProvider.add(newBuilder() .setRef(2) .setType(FILE) .setProjectRelativePath("src/js/Foo.js") .setLines(1)); Component root = call(project); assertThat(root.getUuid()).isEqualTo("generated_c1_uuid"); Component directory = root.getChildren().iterator().next(); assertThat(directory.getUuid()).isEqualTo("generated_c1:src/js_uuid"); Component file = directory.getChildren().iterator().next(); assertThat(file.getUuid()).isEqualTo("generated_c1:src/js/Foo.js_uuid"); } @Test public void files_have_markedAsUnchanged_flag() { ScannerReport.Component project = newBuilder() .setType(PROJECT) .setKey("c1") .setRef(1) .addChildRef(2) .build(); scannerComponentProvider.add(newBuilder() .setRef(2) .setType(FILE) .setMarkedAsUnchanged(true) .setProjectRelativePath("src/js/Foo.js") .setLines(1)); Component root = call(project); assertThat(root.getUuid()).isEqualTo("generated_c1_uuid"); Component directory = root.getChildren().iterator().next(); assertThat(directory.getUuid()).isEqualTo("generated_c1:src/js_uuid"); Component file = directory.getChildren().iterator().next(); assertThat(file.getFileAttributes().isMarkedAsUnchanged()).isTrue(); } @Test public void issues_are_relocated_from_directories_and_modules_to_root() { ScannerReport.Component project = newBuilder() .setType(PROJECT) .setKey("c1") .setRef(1) .addChildRef(2) .build(); ScannerReport.Component.Builder file = newBuilder() .setRef(2) .setType(FILE) .setProjectRelativePath("src/js/Foo.js") .setLines(1); scannerComponentProvider.add(file); call(project); } @Test public void descriptions_of_module_directory_and_file_are_null_if_absent_from_report() { ScannerReport.Component project = newBuilder() .setType(PROJECT) .setRef(1) .addChildRef(2) .build(); scannerComponentProvider.add(newBuilder() .setRef(2) .setType(FILE) .setProjectRelativePath("src/js/Foo.js") .setLines(1)); Component root = call(project); Component directory = root.getChildren().iterator().next(); assertThat(directory.getDescription()).isNull(); Component file = directory.getChildren().iterator().next(); assertThat(file.getDescription()).isNull(); } @Test public void descriptions_of_module_directory_and_file_are_null_if_empty_in_report() { ScannerReport.Component project = newBuilder() .setType(PROJECT) .setRef(1) .setDescription("") .addChildRef(2) .build(); scannerComponentProvider.add(newBuilder() .setRef(2) .setType(FILE) .setDescription("") .setProjectRelativePath("src/js/Foo.js") .setLines(1)); Component root = call(project); Component directory = root.getChildren().iterator().next(); assertThat(directory.getDescription()).isNull(); Component file = directory.getChildren().iterator().next(); assertThat(file.getDescription()).isNull(); } @Test public void descriptions_of_module_directory_and_file_are_set_from_report_if_present() { ScannerReport.Component project = newBuilder() .setType(PROJECT) .setRef(1) .addChildRef(2) .build(); scannerComponentProvider.add(newBuilder() .setRef(2) .setType(FILE) .setDescription("d") .setProjectRelativePath("src/js/Foo.js") .setLines(1)); Component root = call(project); Component directory = root.getChildren().iterator().next(); assertThat(directory.getDescription()).isNull(); Component file = directory.getChildren().iterator().next(); assertThat(file.getDescription()).isEqualTo("d"); } @Test public void only_nb_of_lines_is_mandatory_on_file_attributes() { ScannerReport.Component project = newBuilder() .setType(PROJECT) .setRef(1) .addChildRef(2) .build(); scannerComponentProvider.add(newBuilder() .setRef(2) .setType(FILE) .setProjectRelativePath("src/js/Foo.js") .setLines(1)); Component root = call(project); Component dir = root.getChildren().iterator().next(); Component file = dir.getChildren().iterator().next(); assertThat(file.getFileAttributes().getLines()).isOne(); assertThat(file.getFileAttributes().getLanguageKey()).isNull(); assertThat(file.getFileAttributes().isUnitTest()).isFalse(); } @Test public void language_file_attributes_is_null_if_empty_in_report() { ScannerReport.Component project = newBuilder() .setType(PROJECT) .setRef(1) .addChildRef(2) .build(); scannerComponentProvider.add(newBuilder() .setRef(2) .setType(FILE) .setProjectRelativePath("src/js/Foo.js") .setLines(1) .setLanguage("")); Component root = call(project); Component dir2 = root.getChildren().iterator().next(); Component file = dir2.getChildren().iterator().next(); assertThat(file.getFileAttributes().getLanguageKey()).isNull(); } @Test public void file_attributes_are_fully_loaded_from_report() { ScannerReport.Component project = newBuilder() .setType(PROJECT) .setRef(1) .addChildRef(2) .build(); scannerComponentProvider.add(newBuilder() .setRef(2) .setType(FILE) .setProjectRelativePath("src/js/Foo.js") .setLines(1) .setLanguage("js") .setIsTest(true)); Component root = call(project); Component dir = root.getChildren().iterator().next(); Component file = dir.getChildren().iterator().next(); assertThat(file.getFileAttributes().getLines()).isOne(); assertThat(file.getFileAttributes().getLanguageKey()).isEqualTo("js"); assertThat(file.getFileAttributes().isUnitTest()).isTrue(); } @Test public void throw_IAE_if_lines_is_absent_from_report() { ScannerReport.Component project = newBuilder() .setType(PROJECT) .setRef(1) .addChildRef(2) .build(); scannerComponentProvider.add(newBuilder() .setRef(2) .setType(FILE) .setProjectRelativePath("src/js/Foo.js")); assertThatThrownBy(() -> call(project)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("File 'src/js/Foo.js' has no line"); } @Test public void throw_IAE_if_lines_is_zero_in_report() { ScannerReport.Component project = newBuilder() .setType(PROJECT) .setRef(1) .addChildRef(2) .build(); scannerComponentProvider.add(newBuilder() .setRef(2) .setType(FILE) .setProjectRelativePath("src/js/Foo.js") .setLines(0)); assertThatThrownBy(() -> call(project)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("File 'src/js/Foo.js' has no line"); } @Test public void throw_IAE_if_lines_is_negative_in_report() { ScannerReport.Component project = newBuilder() .setType(PROJECT) .setRef(1) .addChildRef(2) .build(); scannerComponentProvider.add(newBuilder() .setRef(2) .setType(FILE) .setProjectRelativePath("src/js/Foo.js") .setLines(-10)); assertThatThrownBy(() -> call(project)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("File 'src/js/Foo.js' has no line"); } private static class ScannerComponentProvider extends ExternalResource implements Function<Integer, ScannerReport.Component> { private final Map<Integer, ScannerReport.Component> components = new HashMap<>(); @Override protected void before() { clear(); } public void clear() { components.clear(); } @Override public ScannerReport.Component apply(Integer componentRef) { return Objects.requireNonNull(components.get(componentRef), "No Component for componentRef " + componentRef); } public ScannerReport.Component add(ScannerReport.Component.Builder builder) { ScannerReport.Component component = builder.build(); ScannerReport.Component existing = components.put(component.getRef(), component); checkArgument(existing == null, "Component %s already set for ref %s", existing, component.getRef()); return component; } } private Component call(ScannerReport.Component project) { return call(project, NO_SCM_BASE_PATH, SOME_PROJECT_ATTRIBUTES); } private Component call(ScannerReport.Component project, String scmBasePath, ProjectAttributes projectAttributes) { return newUnderTest(projectAttributes, true).buildProject(project, scmBasePath); } private ComponentTreeBuilder newUnderTest(ProjectAttributes projectAttributes, boolean mainBranch) { Branch branch = mock(Branch.class); when(branch.isMain()).thenReturn(mainBranch); return new ComponentTreeBuilder(KEY_GENERATOR, UUID_SUPPLIER, scannerComponentProvider, projectInDb, branch, projectAttributes); } private static Map<String, Component> indexComponentByKey(Component root) { Map<String, Component> componentsByKey = new HashMap<>(); new DepthTraversalTypeAwareCrawler( new TypeAwareVisitorAdapter(CrawlerDepthLimit.FILE, PRE_ORDER) { @Override public void visitAny(Component any) { componentsByKey.put(any.getKey(), any); } }).visit(root); return componentsByKey; } }
29,057
34.179177
149
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ConfigurationRepositoryTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if 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.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.config.Configuration; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.System2; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.ce.task.projectanalysis.analysis.ProjectConfigurationFactory; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.property.PropertyDto; import org.sonar.server.project.Project; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto; public class ConfigurationRepositoryTest { @Rule public final DbTester db = DbTester.create(System2.INSTANCE); @Rule public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule(); private final DbClient dbClient = db.getDbClient(); private final MapSettings globalSettings = new MapSettings(); private final Project project = Project.from(newPrivateProjectDto()); private final Component root = mock(Component.class); private ConfigurationRepository underTest; @Before public void setUp() { analysisMetadataHolder.setProject(project); when(root.getUuid()).thenReturn(project.getUuid()); underTest = new ConfigurationRepositoryImpl(analysisMetadataHolder, new ProjectConfigurationFactory(globalSettings, dbClient)); } @Test public void get_project_settings_from_global_settings() { globalSettings.setProperty("key", "value"); Configuration config = underTest.getConfiguration(); assertThat(config.get("key")).hasValue("value"); } @Test public void get_project_settings_from_db() { insertComponentProperty(project.getUuid(), "key", "value"); Configuration config = underTest.getConfiguration(); assertThat(config.get("key")).hasValue("value"); } @Test public void call_twice_get_project_settings() { globalSettings.setProperty("key", "value"); Configuration config = underTest.getConfiguration(); assertThat(config.get("key")).hasValue("value"); config = underTest.getConfiguration(); assertThat(config.get("key")).hasValue("value"); } @Test public void project_settings_override_global_settings() { globalSettings.setProperty("key", "value1"); insertComponentProperty(project.getUuid(), "key", "value2"); Configuration config = underTest.getConfiguration(); assertThat(config.get("key")).hasValue("value2"); } @Test public void project_settings_are_cached_to_avoid_db_access() { insertComponentProperty(project.getUuid(), "key", "value"); Configuration config = underTest.getConfiguration(); assertThat(config.get("key")).hasValue("value"); db.executeUpdateSql("delete from properties"); db.commit(); assertThat(config.get("key")).hasValue("value"); } @Test public void branch_settings() { globalSettings.setProperty("global", "global value"); insertComponentProperty(project.getUuid(), "project", "project value"); insertComponentProperty(root.getUuid(), "branch", "branch value"); Configuration config = underTest.getConfiguration(); assertThat(config.get("global")).hasValue("global value"); assertThat(config.get("project")).hasValue("project value"); assertThat(config.get("branch")).hasValue("branch value"); } private void insertComponentProperty(String componentUuid, String propertyKey, String propertyValue) { db.properties().insertProperties(null, null, null, null, new PropertyDto().setKey(propertyKey).setValue(propertyValue).setEntityUuid(componentUuid)); } }
4,635
35.21875
131
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/CrawlerDepthLimitTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if 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.collect.ImmutableSet; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Arrays; import java.util.Set; import java.util.stream.Collectors; import javax.annotation.Nullable; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.ce.task.projectanalysis.component.Component.Type; import static com.google.common.base.Predicates.equalTo; import static com.google.common.base.Predicates.in; import static com.google.common.base.Predicates.not; import static com.google.common.collect.FluentIterable.from; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @RunWith(DataProviderRunner.class) public class CrawlerDepthLimitTest { private static final Set<Type> REPORT_TYPES = Arrays.stream(Type.values()).filter(Type::isReportType).collect(Collectors.toSet()); private static final Set<Type> VIEWS_TYPES = Arrays.stream(Type.values()).filter(Type::isViewsType).collect(Collectors.toSet()); @Test public void PROJECT_isSameAs_only_PROJECT_type() { assertIsSameAs(CrawlerDepthLimit.PROJECT, Type.PROJECT); } @Test public void PROJECT_isDeeper_than_no_type() { for (Type type : Type.values()) { assertThat(CrawlerDepthLimit.PROJECT.isDeeperThan(type)).as("isHigherThan(%s)", type).isFalse(); } } @Test public void PROJECT_isHigher_than_all_report_types_but_PROJECT() { assertThat(CrawlerDepthLimit.PROJECT.isHigherThan(Type.PROJECT)).isFalse(); for (Type reportType : from(REPORT_TYPES).filter(not(equalTo(Type.PROJECT)))) { assertThat(CrawlerDepthLimit.PROJECT.isHigherThan(reportType)).as("isHigherThan(%s)", reportType).isTrue(); } } @Test public void PROJECT_isDeeper_than_no_views_types() { for (Type viewsType : VIEWS_TYPES) { assertThat(CrawlerDepthLimit.PROJECT.isDeeperThan(viewsType)).as("isDeeperThan(%s)", viewsType).isFalse(); } } @Test public void PROJECT_isHigher_than_no_views_types() { assertIsHigherThanViewsType(CrawlerDepthLimit.PROJECT); } @Test public void DIRECTORY_isSameAs_only_DIRECTORY_type() { assertIsSameAs(CrawlerDepthLimit.DIRECTORY, Type.DIRECTORY); } @Test public void DIRECTORY_isDeeper_than_no_views_types() { assertIsDeeperThanViewsType(CrawlerDepthLimit.DIRECTORY); } @Test public void DIRECTORY_isDeeper_than_only_PROJECT_report_type() { assertIsDeeperThanReportType(CrawlerDepthLimit.DIRECTORY, Type.PROJECT); } @Test public void DIRECTORY_isHigher_than_only_FILE() { assertIsHigherThanReportType(CrawlerDepthLimit.DIRECTORY, Type.FILE); } @Test public void DIRECTORY_isHigher_than_no_views_type() { assertIsHigherThanViewsType(CrawlerDepthLimit.DIRECTORY); } @Test public void FILE_isSameAs_only_FILE_type() { assertIsSameAs(CrawlerDepthLimit.FILE, Type.FILE); } @Test public void FILE_isDeeper_than_no_views_types() { for (Type viewsType : VIEWS_TYPES) { assertThat(CrawlerDepthLimit.FILE.isDeeperThan(viewsType)).as("isDeeperThan(%s)", viewsType).isFalse(); } } @Test public void FILE_isHigher_than_no_views_types() { assertIsHigherThanViewsType(CrawlerDepthLimit.FILE); } @Test public void FILE_isHigher_than_no_report_types() { assertIsHigherThanReportType(CrawlerDepthLimit.FILE); } @Test public void FILE_isDeeper_than_only_PROJECT_MODULE_and_DIRECTORY_report_types() { assertIsDeeperThanReportType(CrawlerDepthLimit.FILE, Type.PROJECT, Type.DIRECTORY); } @Test public void VIEW_isSameAs_only_VIEW_type() { assertIsSameAs(CrawlerDepthLimit.VIEW, Type.VIEW); } @Test public void VIEW_isDeeper_than_no_type() { for (Type type : Type.values()) { assertThat(CrawlerDepthLimit.VIEW.isDeeperThan(type)).as("isDeeperThan(%s)", type).isFalse(); } } @Test public void VIEW_isHigher_than_all_views_types_but_VIEW() { assertThat(CrawlerDepthLimit.VIEW.isHigherThan(Type.VIEW)).isFalse(); for (Type viewsType : from(VIEWS_TYPES).filter(not(equalTo(Type.VIEW)))) { assertThat(CrawlerDepthLimit.VIEW.isHigherThan(viewsType)).as("isHigherThan(%s)", viewsType).isTrue(); } } @Test public void VIEW_isHigher_than_no_report_types() { assertIsHigherThanReportType(CrawlerDepthLimit.VIEW); } @Test public void VIEW_isDeeper_than_no_report_types() { assertIsDeeperThanReportType(CrawlerDepthLimit.VIEW); } @Test public void VIEW_isDeeper_than_no_views_types() { assertIsDeeperThanViewsType(CrawlerDepthLimit.VIEW); } @Test public void SUBVIEW_isSameAs_only_SUBVIEW_type() { assertIsSameAs(CrawlerDepthLimit.SUBVIEW, Type.SUBVIEW); } @Test public void SUBVIEW_isHigher_than_no_report_types() { assertIsHigherThanReportType(CrawlerDepthLimit.SUBVIEW); } @Test public void SUBVIEW_isDeeper_than_no_report_types() { assertIsDeeperThanReportType(CrawlerDepthLimit.SUBVIEW); } @Test public void SUBVIEW_isDeeper_than_only_VIEW_views_types() { assertIsDeeperThanReportType(CrawlerDepthLimit.SUBVIEW, Type.VIEW); } @Test public void PROJECT_VIEW_isSameAs_only_PROJECT_VIEW_type() { assertIsSameAs(CrawlerDepthLimit.PROJECT_VIEW, Type.PROJECT_VIEW); } @Test public void PROJECT_VIEW_isHigher_than_no_report_types() { assertIsHigherThanReportType(CrawlerDepthLimit.PROJECT_VIEW); } @Test public void PROJECT_VIEW_isDeeper_than_no_report_types() { assertIsDeeperThanReportType(CrawlerDepthLimit.PROJECT_VIEW); } @Test public void PROJECT_VIEW_isDeeper_than_VIEWS_and_SUBVIEWS_views_types() { assertIsDeeperThanViewsType(CrawlerDepthLimit.PROJECT_VIEW, Type.VIEW, Type.SUBVIEW); } @Test public void LEAVES_is_same_as_FILE_and_PROJECT_VIEW() { assertThat(CrawlerDepthLimit.LEAVES.isSameAs(Type.FILE)).isTrue(); assertThat(CrawlerDepthLimit.LEAVES.isSameAs(Type.PROJECT_VIEW)).isTrue(); for (Type type : from(asList(Type.values())).filter(not(in(ImmutableSet.of(Type.FILE, Type.PROJECT_VIEW))))) { assertThat(CrawlerDepthLimit.LEAVES.isSameAs(type)).isFalse(); } } @Test public void LEAVES_isDeeper_than_PROJECT_MODULE_and_DIRECTORY_report_types() { assertIsDeeperThanReportType(CrawlerDepthLimit.LEAVES, Type.PROJECT, Type.DIRECTORY); } @Test public void LEAVES_isDeeper_than_VIEW_and_SUBVIEW_views_types() { assertIsDeeperThanViewsType(CrawlerDepthLimit.LEAVES, Type.VIEW, Type.SUBVIEW); } @Test public void LEAVES_isHigher_than_no_report_types() { assertIsHigherThanReportType(CrawlerDepthLimit.LEAVES); } @Test public void LEAVES_isHigher_than_no_views_types() { assertIsHigherThanViewsType(CrawlerDepthLimit.LEAVES); } private void assertIsSameAs(CrawlerDepthLimit crawlerDepthLimit, Type expectedType) { assertThat(crawlerDepthLimit.isSameAs(expectedType)).isTrue(); for (Type type : from(asList(Type.values())).filter(not(equalTo(expectedType)))) { assertThat(crawlerDepthLimit.isSameAs(type)).isFalse(); } } private void assertIsHigherThanReportType(CrawlerDepthLimit depthLimit, Type... types) { for (Type type : types) { assertThat(depthLimit.isHigherThan(type)).as("isHigherThan(%s)", type).isTrue(); } for (Type reportType : from(REPORT_TYPES).filter(not(in(asList(types))))) { assertThat(depthLimit.isHigherThan(reportType)).as("isHigherThan(%s)", reportType).isFalse(); } } private void assertIsHigherThanViewsType(CrawlerDepthLimit depthLimit, Type... types) { for (Type type : types) { assertThat(depthLimit.isHigherThan(type)).as("isHigherThan(%s)", type).isTrue(); } for (Type reportType : from(VIEWS_TYPES).filter(not(in(asList(types))))) { assertThat(depthLimit.isHigherThan(reportType)).as("isHigherThan(%s)", reportType).isFalse(); } } private void assertIsDeeperThanReportType(CrawlerDepthLimit depthLimit, Type... types) { for (Type type : types) { assertThat(depthLimit.isDeeperThan(type)).as("isDeeperThan(%s)", type).isTrue(); } for (Type reportType : from(REPORT_TYPES).filter(not(in(asList(types))))) { assertThat(depthLimit.isDeeperThan(reportType)).as("isDeeperThan(%s)", reportType).isFalse(); } } private void assertIsDeeperThanViewsType(CrawlerDepthLimit depthLimit, Type... types) { for (Type type : types) { assertThat(depthLimit.isDeeperThan(type)).as("isDeeperThan(%s)", type).isTrue(); } for (Type reportType : from(VIEWS_TYPES).filter(not(in(asList(types))))) { assertThat(depthLimit.isDeeperThan(reportType)).as("isDeeperThan(%s)", reportType).isFalse(); } } @Test @UseDataProvider("viewsTypes") public void reportMaxDepth_throws_IAE_if_type_is_views(Type viewsType) { assertThatThrownBy(() -> CrawlerDepthLimit.reportMaxDepth(viewsType)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("A Report max depth must be a report type"); } @Test @UseDataProvider("reportTypes") public void reportMaxDepth_accepts_type_if_report_type(Type reportType) { CrawlerDepthLimit.reportMaxDepth(reportType); } @Test @UseDataProvider("reportTypes") public void withViewsMaxDepth_throws_IAE_if_type_is_report(Type reportType) { assertThatThrownBy(() -> CrawlerDepthLimit.reportMaxDepth(reportType).withViewsMaxDepth(reportType)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("A Views max depth must be a views type"); } @DataProvider public static Object[][] viewsTypes() { return from(VIEWS_TYPES).transform(new Function<Type, Object[]>() { @Nullable @Override public Object[] apply(Type input) { return new Object[] {input}; } }).toArray(Object[].class); } @DataProvider public static Object[][] reportTypes() { return from(REPORT_TYPES).transform(new Function<Type, Object[]>() { @Nullable @Override public Object[] apply(Type input) { return new Object[] {input}; } }).toArray(Object[].class); } }
11,167
33.469136
132
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/DefaultBranchImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if 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.junit.Test; import org.sonar.db.component.BranchType; import org.sonar.scanner.protocol.output.ScannerReport; import org.sonar.scanner.protocol.output.ScannerReport.Component.ComponentType; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.db.component.BranchDto.DEFAULT_MAIN_BRANCH_NAME; public class DefaultBranchImplTest { private static final String PROJECT_KEY = "P"; private static final ScannerReport.Component FILE = ScannerReport.Component.newBuilder().setType(ComponentType.FILE).setProjectRelativePath("src/Foo.js").build(); @Test public void default_branch_represents_the_project() { DefaultBranchImpl branch = new DefaultBranchImpl(DEFAULT_MAIN_BRANCH_NAME); assertThat(branch.isMain()).isTrue(); assertThat(branch.getType()).isEqualTo(BranchType.BRANCH); assertThat(branch.getName()).isEqualTo(DEFAULT_MAIN_BRANCH_NAME); assertThat(branch.supportsCrossProjectCpd()).isTrue(); assertThat(branch.generateKey(PROJECT_KEY, null)).isEqualTo("P"); assertThat(branch.generateKey(PROJECT_KEY, FILE.getProjectRelativePath())).isEqualTo("P:src/Foo.js"); } }
2,046
41.645833
164
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/DisabledComponentsHolderImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if 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.ImmutableSet; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class DisabledComponentsHolderImplTest { DisabledComponentsHolderImpl underTest = new DisabledComponentsHolderImpl(); @Test public void set_and_get_uuids() { underTest.setUuids(ImmutableSet.of("U1", "U2")); assertThat(underTest.getUuids()).containsExactly("U1", "U2"); } @Test public void setUuids_fails_if_called_twice() { underTest.setUuids(ImmutableSet.of("U1", "U2")); assertThatThrownBy(() -> underTest.setUuids(ImmutableSet.of("U1", "U2"))) .isInstanceOf(IllegalStateException.class) .hasMessage("UUIDs have already been set in repository"); } @Test public void getUuids_fails_if_not_initialized() { assertThatThrownBy(() -> underTest.getUuids()) .isInstanceOf(IllegalStateException.class) .hasMessage("UUIDs have not been set in repository"); } }
1,925
33.392857
78
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/FileAttributesTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if 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.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class FileAttributesTest { @Test public void create_production_file() { FileAttributes underTest = new FileAttributes(false, "java", 10, true,"C"); assertThat(underTest.isUnitTest()).isFalse(); assertThat(underTest.getLanguageKey()).isEqualTo("java"); assertThat(underTest.getLines()).isEqualTo(10); assertThat(underTest.isMarkedAsUnchanged()).isTrue(); assertThat(underTest.getOldRelativePath()).isEqualTo("C"); } @Test public void create_unit_test() { FileAttributes underTest = new FileAttributes(true, "java", 10, false,"oldName"); assertThat(underTest.isUnitTest()).isTrue(); assertThat(underTest.getLanguageKey()).isEqualTo("java"); assertThat(underTest.getLines()).isEqualTo(10); assertThat(underTest.isMarkedAsUnchanged()).isFalse(); assertThat(underTest.getOldRelativePath()).isEqualTo("oldName"); } @Test public void create_without_oldName() { FileAttributes underTest = new FileAttributes(true, "TypeScript", 10, false, null); assertThat(underTest.isUnitTest()).isTrue(); assertThat(underTest.getLanguageKey()).isEqualTo("TypeScript"); assertThat(underTest.getLines()).isEqualTo(10); assertThat(underTest.getOldRelativePath()).isNull(); } @Test public void create_without_language() { FileAttributes underTest = new FileAttributes(true, null, 10, false, null); assertThat(underTest.isUnitTest()).isTrue(); assertThat(underTest.getLanguageKey()).isNull(); assertThat(underTest.getLines()).isEqualTo(10); } @Test public void fail_with_IAE_when_lines_is_0() { assertThatThrownBy(() -> new FileAttributes(true, "java", 0, false, null)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Number of lines must be greater than zero"); } @Test public void fail_with_IAE_when_lines_is_less_than_0() { assertThatThrownBy(() -> new FileAttributes(true, "java", -10, false, null)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Number of lines must be greater than zero"); } @Test public void test_toString() { assertThat(new FileAttributes(true, "java", 10, true, "bobo")) .hasToString("FileAttributes{languageKey='java', unitTest=true, lines=10, markedAsUnchanged=true, oldRelativePath='bobo'}"); assertThat(new FileAttributes(false, null, 1, false, null)) .hasToString("FileAttributes{languageKey='null', unitTest=false, lines=1, markedAsUnchanged=false, oldRelativePath='null'}"); } }
3,549
38.010989
131
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/FileStatusesImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if 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.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.ce.task.projectanalysis.analysis.Analysis; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.ce.task.projectanalysis.source.SourceHashRepository; import org.sonar.db.source.FileHashesDto; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class FileStatusesImplTest { private static final String PROJECT_KEY = "PROJECT_KEY"; private static final String PROJECT_UUID = "UUID-1234"; @Rule public final TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); private final PreviousSourceHashRepository previousSourceHashRepository = mock(PreviousSourceHashRepository.class); private final SourceHashRepository sourceHashRepository = mock(SourceHashRepository.class); @Rule public final AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule(); private final FileStatusesImpl fileStatuses = new FileStatusesImpl(analysisMetadataHolder, treeRootHolder, previousSourceHashRepository, sourceHashRepository); @Before public void before() { analysisMetadataHolder.setBaseAnalysis(new Analysis.Builder().setUuid(PROJECT_UUID).setCreatedAt(1000L).build()); } @Test public void file_is_unchanged_only_if_status_is_SAME_and_hashes_equal() { Component file1 = ReportComponent.builder(Component.Type.FILE, 2, "FILE1_KEY").setStatus(Component.Status.SAME).build(); Component file2 = ReportComponent.builder(Component.Type.FILE, 3, "FILE2_KEY").setStatus(Component.Status.SAME).build(); Component file3 = ReportComponent.builder(Component.Type.FILE, 4, "FILE3_KEY").setStatus(Component.Status.CHANGED).build(); addDbFileHash(file1, "hash1"); addDbFileHash(file2, "different"); addDbFileHash(file3, "hash3"); addReportFileHash(file1, "hash1"); addReportFileHash(file2, "hash2"); addReportFileHash(file3, "hash3"); Component project = ReportComponent.builder(Component.Type.PROJECT, 1) .setUuid(PROJECT_UUID) .setKey(PROJECT_KEY) .addChildren(file1, file2, file3) .build(); treeRootHolder.setRoot(project); fileStatuses.initialize(); assertThat(fileStatuses.isUnchanged(file1)).isTrue(); assertThat(fileStatuses.isUnchanged(file2)).isFalse(); assertThat(fileStatuses.isUnchanged(file2)).isFalse(); } @Test public void isDataUnchanged_returns_false_if_any_SAME_status_is_incorrect() { Component file1 = ReportComponent.builder(Component.Type.FILE, 2, "FILE1_KEY").setStatus(Component.Status.SAME) .setFileAttributes(new FileAttributes(false, null, 10, true, null)).build(); Component file2 = ReportComponent.builder(Component.Type.FILE, 3, "FILE2_KEY").setStatus(Component.Status.SAME).build(); addDbFileHash(file1, "hash1"); addDbFileHash(file2, "different"); addReportFileHash(file1, "hash1"); addReportFileHash(file2, "hash2"); Component project = ReportComponent.builder(Component.Type.PROJECT, 1) .setUuid(PROJECT_UUID) .setKey(PROJECT_KEY) .addChildren(file1, file2) .build(); treeRootHolder.setRoot(project); fileStatuses.initialize(); assertThat(fileStatuses.isDataUnchanged(file1)).isFalse(); assertThat(fileStatuses.isDataUnchanged(file2)).isFalse(); } @Test public void isDataUnchanged_returns_false_no_previous_analysis() { analysisMetadataHolder.setBaseAnalysis(null); Component file1 = ReportComponent.builder(Component.Type.FILE, 2, "FILE1_KEY").setStatus(Component.Status.SAME) .setFileAttributes(new FileAttributes(false, null, 10, true, null)).build(); Component file2 = ReportComponent.builder(Component.Type.FILE, 3, "FILE2_KEY").setStatus(Component.Status.SAME).build(); addReportFileHash(file1, "hash1"); addReportFileHash(file2, "hash2"); Component project = ReportComponent.builder(Component.Type.PROJECT, 1) .setUuid(PROJECT_UUID) .setKey(PROJECT_KEY) .addChildren(file1, file2) .build(); treeRootHolder.setRoot(project); fileStatuses.initialize(); assertThat(fileStatuses.isDataUnchanged(file1)).isFalse(); assertThat(fileStatuses.isDataUnchanged(file2)).isFalse(); } @Test public void isDataUnchanged_returns_false_if_not_set_by_analyzer() { Component file1 = ReportComponent.builder(Component.Type.FILE, 2, "FILE1_KEY").setStatus(Component.Status.SAME) .setFileAttributes(new FileAttributes(false, null, 10, false,null)).build(); Component file2 = ReportComponent.builder(Component.Type.FILE, 3, "FILE2_KEY").setStatus(Component.Status.SAME).build(); addDbFileHash(file1, "hash1"); addDbFileHash(file2, "hash2"); addReportFileHash(file1, "hash1"); addReportFileHash(file2, "hash2"); Component project = ReportComponent.builder(Component.Type.PROJECT, 1) .setUuid(PROJECT_UUID) .setKey(PROJECT_KEY) .addChildren(file1, file2) .build(); treeRootHolder.setRoot(project); fileStatuses.initialize(); assertThat(fileStatuses.isDataUnchanged(file1)).isFalse(); assertThat(fileStatuses.isDataUnchanged(file2)).isFalse(); } @Test public void isDataUnchanged_returns_true_if_set_by_analyzer_and_all_SAME_status_are_correct() { Component file1 = ReportComponent.builder(Component.Type.FILE, 2, "FILE1_KEY").setStatus(Component.Status.SAME) .setFileAttributes(new FileAttributes(false, null, 10, true,null)).build(); Component file2 = ReportComponent.builder(Component.Type.FILE, 3, "FILE2_KEY").setStatus(Component.Status.SAME).build(); Component file3 = ReportComponent.builder(Component.Type.FILE, 4, "FILE3_KEY").setStatus(Component.Status.CHANGED).build(); addDbFileHash(file1, "hash1"); addDbFileHash(file2, "hash2"); addDbFileHash(file3, "hash3"); addReportFileHash(file1, "hash1"); addReportFileHash(file2, "hash2"); addReportFileHash(file3, "different"); Component project = ReportComponent.builder(Component.Type.PROJECT, 1) .setUuid(PROJECT_UUID) .setKey(PROJECT_KEY) .addChildren(file1, file2, file3) .build(); treeRootHolder.setRoot(project); fileStatuses.initialize(); assertThat(fileStatuses.isDataUnchanged(file1)).isTrue(); assertThat(fileStatuses.isDataUnchanged(file2)).isFalse(); verify(previousSourceHashRepository).getDbFile(file1); } @Test public void getFileUuidsMarkedAsUnchanged_whenNotInitialized_shouldFail() { assertThatThrownBy(fileStatuses::getFileUuidsMarkedAsUnchanged) .isInstanceOf(IllegalStateException.class) .hasMessage("Not initialized"); } @Test public void getFileUuidsMarkedAsUnchanged_shouldReturnMarkAsUnchangedFileUuids() { Component file1 = ReportComponent.builder(Component.Type.FILE, 2, "FILE1_KEY").setStatus(Component.Status.SAME) .setFileAttributes(new FileAttributes(false, null, 10, true, null)).build(); Component file2 = ReportComponent.builder(Component.Type.FILE, 3, "FILE2_KEY").setStatus(Component.Status.SAME).build(); addDbFileHash(file1, "hash1"); addDbFileHash(file2, "hash2"); addReportFileHash(file1, "hash1"); addReportFileHash(file2, "hash2"); Component project = ReportComponent.builder(Component.Type.PROJECT, 1) .setUuid(PROJECT_UUID) .setKey(PROJECT_KEY) .addChildren(file1, file2) .build(); treeRootHolder.setRoot(project); fileStatuses.initialize(); assertThat(fileStatuses.getFileUuidsMarkedAsUnchanged()).contains(file1.getUuid()); } private void addDbFileHash(Component file, String hash) { FileHashesDto fileHashesDto = new FileHashesDto().setSrcHash(hash); when(previousSourceHashRepository.getDbFile(file)).thenReturn(Optional.of(fileHashesDto)); } private void addReportFileHash(Component file, String hash) { when(sourceHashRepository.getRawSourceHash(file)).thenReturn(hash); } }
9,048
41.483568
161
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/NopFileStatusesTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if 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.junit.Test; import org.mockito.Mockito; import static org.assertj.core.api.Assertions.assertThat; public class NopFileStatusesTest { private final NopFileStatuses nopFileStatuses = new NopFileStatuses(); private final Component component = Mockito.mock(Component.class); @Test public void isUnchanged() { assertThat(nopFileStatuses.isUnchanged(component)).isFalse(); } @Test public void isDataUnchanged() { assertThat(nopFileStatuses.isDataUnchanged(component)).isFalse(); } @Test public void getFileUuidsMarkedAsUnchanged() { assertThat(nopFileStatuses.getFileUuidsMarkedAsUnchanged()).isEmpty(); } }
1,551
31.333333
75
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/PathAwareCallRecord.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if 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.List; import java.util.Objects; import javax.annotation.CheckForNull; import javax.annotation.Nullable; class PathAwareCallRecord { private final String method; @CheckForNull private final Integer ref; @CheckForNull private final String key; private final int current; @CheckForNull private final Integer parent; private final int root; private final List<Integer> path; private PathAwareCallRecord(String method, @Nullable Integer ref, @Nullable String key, int current, @Nullable Integer parent, int root, List<Integer> path) { this.method = method; this.ref = ref; this.key = key; this.current = current; this.parent = parent; this.root = root; this.path = path; } public static PathAwareCallRecord reportCallRecord(String method, Integer ref, int current, @Nullable Integer parent, int root, List<Integer> path) { return new PathAwareCallRecord(method, ref, method, current, parent, root, path); } public static PathAwareCallRecord viewsCallRecord(String method, String key, int current, @Nullable Integer parent, int root, List<Integer> path) { return new PathAwareCallRecord(method, null, key, current, parent, root, path); } @Override public boolean equals(@Nullable Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PathAwareCallRecord that = (PathAwareCallRecord) o; return Objects.equals(ref, that.ref) && Objects.equals(key, that.key) && Objects.equals(current, that.current) && Objects.equals(root, that.root) && Objects.equals(method, that.method) && Objects.equals(parent, that.parent) && Objects.equals(path, that.path); } @Override public int hashCode() { return Objects.hash(method, ref, key, current, parent, root, path); } @Override public String toString() { return "{" + "method='" + method + '\'' + ", ref=" + ref + ", key=" + key + ", current=" + current + ", parent=" + parent + ", root=" + root + ", path=" + path + '}'; } }
3,042
31.72043
160
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/PreviousSourceHashRepositoryImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if 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.Map; import org.junit.Test; import org.sonar.db.source.FileHashesDto; import org.sonar.db.source.FileSourceDto; import static java.util.Collections.emptyMap; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; public class PreviousSourceHashRepositoryImplTest { private final PreviousSourceHashRepositoryImpl previousFileHashesRepository = new PreviousSourceHashRepositoryImpl(); @Test public void return_file_hashes() { Component file1 = ReportComponent.builder(Component.Type.FILE, 1).build(); Component file2 = ReportComponent.builder(Component.Type.FILE, 2).build(); Component file3 = ReportComponent.builder(Component.Type.FILE, 3).build(); FileSourceDto fileSource1 = new FileSourceDto(); FileSourceDto fileSource2 = new FileSourceDto(); previousFileHashesRepository.set(Map.of(file1.getUuid(), fileSource1, file2.getUuid(), fileSource2)); assertThat(previousFileHashesRepository.getDbFile(file1)).contains(fileSource1); assertThat(previousFileHashesRepository.getDbFile(file2)).contains(fileSource2); assertThat(previousFileHashesRepository.getDbFile(file3)).isEmpty(); } @Test public void fail_if_not_set() { assertThatThrownBy(() -> previousFileHashesRepository.getDbFile(mock(Component.class))).isInstanceOf(IllegalStateException.class); } @Test public void fail_if_set_twice() { Map<String, FileHashesDto> empty = emptyMap(); previousFileHashesRepository.set(empty); assertThatThrownBy(() -> previousFileHashesRepository.set(empty)).isInstanceOf(IllegalStateException.class); } }
2,597
40.238095
134
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ReportPathAwareVisitorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if 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.Iterator; import java.util.List; import javax.annotation.Nullable; import org.junit.Test; import static com.google.common.collect.ImmutableList.of; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.ce.task.projectanalysis.component.Component.Type.DIRECTORY; import static org.sonar.ce.task.projectanalysis.component.Component.Type.FILE; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT; import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.POST_ORDER; import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.PRE_ORDER; public class ReportPathAwareVisitorTest { private static final int ROOT_REF = 1; private static final ReportComponent SOME_TREE_ROOT = ReportComponent.builder(PROJECT, ROOT_REF).addChildren( ReportComponent.builder(DIRECTORY, 11).addChildren( ReportComponent.builder(FILE, 111).build(), ReportComponent.builder(FILE, 112).build()) .build(), ReportComponent.builder(DIRECTORY, 12).addChildren( ReportComponent.builder(DIRECTORY, 121).addChildren( ReportComponent.builder(FILE, 1211).build()) .build()) .build()) .build(); @Test public void verify_preOrder_visit_call_when_visit_tree_with_depth_FILE() { CallRecorderPathAwareVisitor underTest = new CallRecorderPathAwareVisitor(CrawlerDepthLimit.FILE, PRE_ORDER); new PathAwareCrawler<>(underTest).visit(SOME_TREE_ROOT); Iterator<PathAwareCallRecord> expected = of( newCallRecord("visitAny", 1, null, of(1)), newCallRecord("visitProject", 1, null, of(1)), newCallRecord("visitAny", 11, 1, of(11, 1)), newCallRecord("visitDirectory", 11, 1, of(11, 1)), newCallRecord("visitAny", 111, 11, of(111, 11, 1)), newCallRecord("visitFile", 111, 11, of(111, 11, 1)), newCallRecord("visitAny", 112, 11, of(112, 11, 1)), newCallRecord("visitFile", 112, 11, of(112, 11, 1)), newCallRecord("visitAny", 12, 1, of(12, 1)), newCallRecord("visitDirectory", 12, 1, of(12, 1)), newCallRecord("visitAny", 121, 12, of(121, 12, 1)), newCallRecord("visitDirectory", 121, 12, of(121, 12, 1)), newCallRecord("visitAny", 1211, 121, of(1211, 121, 12, 1)), newCallRecord("visitFile", 1211, 121, of(1211, 121, 12, 1))).iterator(); verifyCallRecords(expected, underTest.callsRecords.iterator()); } @Test public void verify_preOrder_visit_call_when_visit_tree_with_depth_DIRECTORY() { CallRecorderPathAwareVisitor underTest = new CallRecorderPathAwareVisitor(CrawlerDepthLimit.DIRECTORY, PRE_ORDER); new PathAwareCrawler<>(underTest).visit(SOME_TREE_ROOT); Iterator<PathAwareCallRecord> expected = of( newCallRecord("visitAny", 1, null, of(1)), newCallRecord("visitProject", 1, null, of(1)), newCallRecord("visitAny", 11, 1, of(11, 1)), newCallRecord("visitDirectory", 11, 1, of(11, 1)), newCallRecord("visitAny", 12, 1, of(12, 1)), newCallRecord("visitDirectory", 12, 1, of(12, 1)), newCallRecord("visitAny", 121, 12, of(121, 12, 1)), newCallRecord("visitDirectory", 121, 12, of(121, 12, 1))).iterator(); verifyCallRecords(expected, underTest.callsRecords.iterator()); } @Test public void verify_preOrder_visit_call_when_visit_tree_with_depth_PROJECT() { CallRecorderPathAwareVisitor underTest = new CallRecorderPathAwareVisitor(CrawlerDepthLimit.PROJECT, PRE_ORDER); new PathAwareCrawler<>(underTest).visit(SOME_TREE_ROOT); Iterator<PathAwareCallRecord> expected = of( newCallRecord("visitAny", 1, null, of(1)), newCallRecord("visitProject", 1, null, of(1))).iterator(); verifyCallRecords(expected, underTest.callsRecords.iterator()); } @Test public void verify_postOrder_visit_call_when_visit_tree_with_depth_FILE() { CallRecorderPathAwareVisitor underTest = new CallRecorderPathAwareVisitor(CrawlerDepthLimit.FILE, POST_ORDER); new PathAwareCrawler<>(underTest).visit(SOME_TREE_ROOT); Iterator<PathAwareCallRecord> expected = of( newCallRecord("visitAny", 111, 11, of(111, 11, 1)), newCallRecord("visitFile", 111, 11, of(111, 11, 1)), newCallRecord("visitAny", 112, 11, of(112, 11, 1)), newCallRecord("visitFile", 112, 11, of(112, 11, 1)), newCallRecord("visitAny", 11, 1, of(11, 1)), newCallRecord("visitDirectory", 11, 1, of(11, 1)), newCallRecord("visitAny", 1211, 121, of(1211, 121, 12, 1)), newCallRecord("visitFile", 1211, 121, of(1211, 121, 12, 1)), newCallRecord("visitAny", 121, 12, of(121, 12, 1)), newCallRecord("visitDirectory", 121, 12, of(121, 12, 1)), newCallRecord("visitAny", 12, 1, of(12, 1)), newCallRecord("visitDirectory", 12, 1, of(12, 1)), newCallRecord("visitAny", 1, null, of(1)), newCallRecord("visitProject", 1, null, of(1))).iterator(); verifyCallRecords(expected, underTest.callsRecords.iterator()); } @Test public void verify_postOrder_visit_call_when_visit_tree_with_depth_DIRECTORY() { CallRecorderPathAwareVisitor underTest = new CallRecorderPathAwareVisitor(CrawlerDepthLimit.DIRECTORY, POST_ORDER); new PathAwareCrawler<>(underTest).visit(SOME_TREE_ROOT); Iterator<PathAwareCallRecord> expected = of( newCallRecord("visitAny", 11, 1, of(11, 1)), newCallRecord("visitDirectory", 11, 1, of(11, 1)), newCallRecord("visitAny", 121, 12, of(121, 12, 1)), newCallRecord("visitDirectory", 121, 12, of(121, 12, 1)), newCallRecord("visitAny", 12, 1, of(12, 1)), newCallRecord("visitDirectory", 12, 1, of(12, 1)), newCallRecord("visitAny", 1, null, of(1)), newCallRecord("visitProject", 1, null, of(1))).iterator(); verifyCallRecords(expected, underTest.callsRecords.iterator()); } @Test public void verify_postOrder_visit_call_when_visit_tree_with_depth_PROJECT() { CallRecorderPathAwareVisitor underTest = new CallRecorderPathAwareVisitor(CrawlerDepthLimit.PROJECT, POST_ORDER); new PathAwareCrawler<>(underTest).visit(SOME_TREE_ROOT); Iterator<PathAwareCallRecord> expected = of( newCallRecord("visitAny", 1, null, of(1)), newCallRecord("visitProject", 1, null, of(1))).iterator(); verifyCallRecords(expected, underTest.callsRecords.iterator()); } private static void verifyCallRecords(Iterator<PathAwareCallRecord> expected, Iterator<PathAwareCallRecord> actual) { while (expected.hasNext()) { assertThat(actual.next()).isEqualTo(expected.next()); } assertThat(expected.hasNext()).isEqualTo(actual.hasNext()); } private static PathAwareCallRecord newCallRecord(String method, int currentRef, @Nullable Integer parentRef, List<Integer> path) { return PathAwareCallRecord.reportCallRecord(method, currentRef, currentRef, parentRef, ROOT_REF, path); } }
7,779
46.439024
132
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ReportPostOrderDepthTraversalTypeAwareCrawlerTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if 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.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.ce.task.projectanalysis.component.Component.Type.DIRECTORY; import static org.sonar.ce.task.projectanalysis.component.Component.Type.FILE; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT; import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.POST_ORDER; public class ReportPostOrderDepthTraversalTypeAwareCrawlerTest { private static final Component FILE_5 = component(FILE, 5); private static final Component FILE_6 = component(FILE, 6); private static final Component DIRECTORY_4 = component(DIRECTORY, 4, FILE_5, FILE_6); private static final Component COMPONENT_TREE = component(PROJECT, 1, DIRECTORY_4); private final CallRecorderTypeAwareVisitor projectVisitor = new CallRecorderTypeAwareVisitor(CrawlerDepthLimit.PROJECT, POST_ORDER); private final CallRecorderTypeAwareVisitor directoryVisitor = new CallRecorderTypeAwareVisitor(CrawlerDepthLimit.DIRECTORY, POST_ORDER); private final CallRecorderTypeAwareVisitor fileVisitor = new CallRecorderTypeAwareVisitor(CrawlerDepthLimit.FILE, POST_ORDER); private final DepthTraversalTypeAwareCrawler projectCrawler = new DepthTraversalTypeAwareCrawler(projectVisitor); private final DepthTraversalTypeAwareCrawler directoryCrawler = new DepthTraversalTypeAwareCrawler(directoryVisitor); private final DepthTraversalTypeAwareCrawler fileCrawler = new DepthTraversalTypeAwareCrawler(fileVisitor); @Test public void visit_null_Component_throws_NPE() { assertThatThrownBy(() -> fileCrawler.visit(null)) .isInstanceOf(NullPointerException.class); } @Test public void visit_file_with_depth_FILE_calls_visit_file() { Component component = component(FILE, 1); fileCrawler.visit(component); assertThat(fileVisitor.callsRecords).containsExactly( reportCallRecord("visitAny", component), reportCallRecord("visitFile", component)); } @Test public void visit_directory_with_depth_FILE_calls_visit_directory() { Component component = component(DIRECTORY, 1); fileCrawler.visit(component); assertThat(fileVisitor.callsRecords).containsExactly( reportCallRecord("visitAny", component), reportCallRecord("visitDirectory", component)); } @Test public void visit_project_with_depth_FILE_calls_visit_project() { Component component = component(PROJECT, 1); fileCrawler.visit(component); assertThat(fileVisitor.callsRecords).containsExactly( reportCallRecord("visitAny", component), reportCallRecord("visitProject", component)); } @Test public void visit_file_with_depth_DIRECTORY_does_not_call_visit_file_nor_visitAny() { Component component = component(FILE, 1); directoryCrawler.visit(component); assertThat(directoryVisitor.callsRecords).isEmpty(); } @Test public void visit_directory_with_depth_DIRECTORY_calls_visit_directory() { Component component = component(DIRECTORY, 1); directoryCrawler.visit(component); assertThat(directoryVisitor.callsRecords).containsExactly( reportCallRecord("visitAny", component), reportCallRecord("visitDirectory", component)); } @Test public void visit_project_with_depth_DIRECTORY_calls_visit_project() { Component component = component(PROJECT, 1); directoryCrawler.visit(component); assertThat(directoryVisitor.callsRecords).containsExactly( reportCallRecord("visitAny", component), reportCallRecord("visitProject", component)); } @Test public void visit_file_with_depth_PROJECT_does_not_call_visit_file_nor_visitAny() { Component component = component(FILE, 1); projectCrawler.visit(component); assertThat(projectVisitor.callsRecords).isEmpty(); } @Test public void visit_directory_with_depth_PROJECT_does_not_call_visit_directory_nor_visitAny() { Component component = component(DIRECTORY, 1); projectCrawler.visit(component); assertThat(projectVisitor.callsRecords).isEmpty(); } @Test public void visit_project_with_depth_PROJECT_calls_visit_project() { Component component = component(PROJECT, 1); projectCrawler.visit(component); assertThat(projectVisitor.callsRecords).containsExactly( reportCallRecord("visitAny", component), reportCallRecord("visitProject", component)); } @Test public void verify_visit_call_when_visit_tree_with_depth_FILE() { fileCrawler.visit(COMPONENT_TREE); assertThat(fileVisitor.callsRecords).containsExactly( reportCallRecord("visitAny", FILE_5), reportCallRecord("visitFile", FILE_5), reportCallRecord("visitAny", FILE_6), reportCallRecord("visitFile", FILE_6), reportCallRecord("visitAny", DIRECTORY_4), reportCallRecord("visitDirectory", DIRECTORY_4), reportCallRecord("visitAny", COMPONENT_TREE), reportCallRecord("visitProject", COMPONENT_TREE)); } @Test public void verify_visit_call_when_visit_tree_with_depth_DIRECTORY() { directoryCrawler.visit(COMPONENT_TREE); assertThat(directoryVisitor.callsRecords).containsExactly( reportCallRecord("visitAny", DIRECTORY_4), reportCallRecord("visitDirectory", DIRECTORY_4), reportCallRecord("visitAny", COMPONENT_TREE), reportCallRecord("visitProject", COMPONENT_TREE)); } @Test public void verify_visit_call_when_visit_tree_with_depth_PROJECT() { projectCrawler.visit(COMPONENT_TREE); assertThat(projectVisitor.callsRecords).containsExactly( reportCallRecord("visitAny", COMPONENT_TREE), reportCallRecord("visitProject", COMPONENT_TREE)); } private static Component component(final Component.Type type, final int ref, final Component... children) { return ReportComponent.builder(type, ref).addChildren(children).build(); } private static CallRecord reportCallRecord(String methodName, Component component) { return CallRecord.reportCallRecord(methodName, component.getReportAttributes().getRef()); } }
7,029
38.273743
138
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ReportPreOrderDepthTraversalTypeAwareCrawlerTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if 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.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.ce.task.projectanalysis.component.Component.Type.DIRECTORY; import static org.sonar.ce.task.projectanalysis.component.Component.Type.FILE; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT; import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.PRE_ORDER; public class ReportPreOrderDepthTraversalTypeAwareCrawlerTest { private static final Component FILE_5 = component(FILE, 5); private static final Component FILE_6 = component(FILE, 6); private static final Component DIRECTORY_4 = component(DIRECTORY, 4, FILE_5, FILE_6); private static final Component COMPONENT_TREE = component(PROJECT, 1, DIRECTORY_4); private final CallRecorderTypeAwareVisitor projectVisitor = new CallRecorderTypeAwareVisitor(CrawlerDepthLimit.PROJECT, PRE_ORDER); private final CallRecorderTypeAwareVisitor directoryVisitor = new CallRecorderTypeAwareVisitor(CrawlerDepthLimit.DIRECTORY, PRE_ORDER); private final CallRecorderTypeAwareVisitor fileVisitor = new CallRecorderTypeAwareVisitor(CrawlerDepthLimit.FILE, PRE_ORDER); private final DepthTraversalTypeAwareCrawler projectCrawler = new DepthTraversalTypeAwareCrawler(projectVisitor); private final DepthTraversalTypeAwareCrawler directoryCrawler = new DepthTraversalTypeAwareCrawler(directoryVisitor); private final DepthTraversalTypeAwareCrawler fileCrawler = new DepthTraversalTypeAwareCrawler(fileVisitor); @Test public void visit_null_Component_throws_NPE() { assertThatThrownBy(() -> fileCrawler.visit(null)) .isInstanceOf(NullPointerException.class); } @Test public void visit_file_with_depth_FILE_calls_visit_file() { Component component = component(FILE, 1); fileCrawler.visit(component); assertThat(fileVisitor.callsRecords).containsExactly( reportCallRecord("visitAny", component), reportCallRecord("visitFile", component)); } @Test public void visit_directory_with_depth_FILE_calls_visit_directory() { Component component = component(DIRECTORY, 1); fileCrawler.visit(component); assertThat(fileVisitor.callsRecords).containsExactly( reportCallRecord("visitAny", component), reportCallRecord("visitDirectory", component)); } @Test public void visit_project_with_depth_FILE_calls_visit_project() { Component component = component(PROJECT, 1); fileCrawler.visit(component); assertThat(fileVisitor.callsRecords).containsExactly( reportCallRecord("visitAny", component), reportCallRecord("visitProject", component)); } @Test public void visit_file_with_depth_DIRECTORY_does_not_call_visit_file_nor_visitAny() { Component component = component(FILE, 1); directoryCrawler.visit(component); assertThat(directoryVisitor.callsRecords).isEmpty(); } @Test public void visit_directory_with_depth_DIRECTORY_calls_visit_directory() { Component component = component(DIRECTORY, 1); directoryCrawler.visit(component); assertThat(directoryVisitor.callsRecords).containsExactly( reportCallRecord("visitAny", component), reportCallRecord("visitDirectory", component)); } @Test public void visit_project_with_depth_DIRECTORY_calls_visit_project() { Component component = component(PROJECT, 1); directoryCrawler.visit(component); assertThat(directoryVisitor.callsRecords).containsExactly( reportCallRecord("visitAny", component), reportCallRecord("visitProject", component)); } @Test public void visit_file_with_depth_PROJECT_does_not_call_visit_file_nor_visitAny() { Component component = component(FILE, 1); projectCrawler.visit(component); assertThat(projectVisitor.callsRecords).isEmpty(); } @Test public void visit_directory_with_depth_PROJECT_does_not_call_visit_directory_nor_visitAny() { Component component = component(DIRECTORY, 1); projectCrawler.visit(component); assertThat(projectVisitor.callsRecords).isEmpty(); } @Test public void visit_project_with_depth_PROJECT_calls_visit_project_nor_visitAny() { Component component = component(PROJECT, 1); projectCrawler.visit(component); assertThat(projectVisitor.callsRecords).containsExactly( reportCallRecord("visitAny", component), reportCallRecord("visitProject", component)); } @Test public void verify_visit_call_when_visit_tree_with_depth_FILE() { fileCrawler.visit(COMPONENT_TREE); assertThat(fileVisitor.callsRecords).containsExactly( reportCallRecord("visitAny", COMPONENT_TREE), reportCallRecord("visitProject", COMPONENT_TREE), reportCallRecord("visitAny", DIRECTORY_4), reportCallRecord("visitDirectory", DIRECTORY_4), reportCallRecord("visitAny", FILE_5), reportCallRecord("visitFile", FILE_5), reportCallRecord("visitAny", FILE_6), reportCallRecord("visitFile", FILE_6)); } @Test public void verify_visit_call_when_visit_tree_with_depth_DIRECTORY() { directoryCrawler.visit(COMPONENT_TREE); assertThat(directoryVisitor.callsRecords).containsExactly( reportCallRecord("visitAny", COMPONENT_TREE), reportCallRecord("visitProject", COMPONENT_TREE), reportCallRecord("visitAny", DIRECTORY_4), reportCallRecord("visitDirectory", DIRECTORY_4)); } @Test public void verify_visit_call_when_visit_tree_with_depth_PROJECT() { projectCrawler.visit(COMPONENT_TREE); assertThat(projectVisitor.callsRecords).containsExactly( reportCallRecord("visitAny", COMPONENT_TREE), reportCallRecord("visitProject", COMPONENT_TREE)); } private static Component component(final Component.Type type, final int ref, final Component... children) { return ReportComponent.builder(type, ref).addChildren(children).build(); } private static CallRecord reportCallRecord(String methodName, Component component) { return CallRecord.reportCallRecord(methodName, component.getReportAttributes().getRef()); } }
7,038
38.105556
137
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ReportVisitorsCrawlerTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if 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 org.junit.Test; import org.mockito.InOrder; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.spy; import static org.sonar.ce.task.projectanalysis.component.Component.Type.DIRECTORY; import static org.sonar.ce.task.projectanalysis.component.Component.Type.FILE; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT; import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.POST_ORDER; import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.PRE_ORDER; public class ReportVisitorsCrawlerTest { private static final Component FILE_5 = component(FILE, 5); private static final Component DIRECTORY_4 = component(DIRECTORY, 4, FILE_5); private static final Component COMPONENT_TREE = component(PROJECT, 1, DIRECTORY_4); private final TypeAwareVisitor spyPreOrderTypeAwareVisitor = spy(new TestTypeAwareVisitor(CrawlerDepthLimit.FILE, PRE_ORDER)); private final TypeAwareVisitor spyPostOrderTypeAwareVisitor = spy(new TestTypeAwareVisitor(CrawlerDepthLimit.FILE, POST_ORDER)); private final TestPathAwareVisitor spyPathAwareVisitor = spy(new TestPathAwareVisitor(CrawlerDepthLimit.FILE, POST_ORDER)); @Test public void execute_each_visitor_on_each_level() { InOrder inOrder = inOrder(spyPostOrderTypeAwareVisitor, spyPathAwareVisitor); VisitorsCrawler underTest = new VisitorsCrawler(Arrays.asList(spyPostOrderTypeAwareVisitor, spyPathAwareVisitor)); underTest.visit(COMPONENT_TREE); inOrder.verify(spyPostOrderTypeAwareVisitor).visitAny(FILE_5); inOrder.verify(spyPostOrderTypeAwareVisitor).visitFile(FILE_5); inOrder.verify(spyPathAwareVisitor).visitAny(eq(FILE_5), any(PathAwareVisitor.Path.class)); inOrder.verify(spyPathAwareVisitor).visitFile(eq(FILE_5), any(PathAwareVisitor.Path.class)); inOrder.verify(spyPostOrderTypeAwareVisitor).visitAny(DIRECTORY_4); inOrder.verify(spyPostOrderTypeAwareVisitor).visitDirectory(DIRECTORY_4); inOrder.verify(spyPathAwareVisitor).visitAny(eq(DIRECTORY_4), any(PathAwareVisitor.Path.class)); inOrder.verify(spyPathAwareVisitor).visitDirectory(eq(DIRECTORY_4), any(PathAwareVisitor.Path.class)); inOrder.verify(spyPostOrderTypeAwareVisitor).visitAny(COMPONENT_TREE); inOrder.verify(spyPostOrderTypeAwareVisitor).visitProject(COMPONENT_TREE); inOrder.verify(spyPathAwareVisitor).visitAny(eq(COMPONENT_TREE), any(PathAwareVisitor.Path.class)); inOrder.verify(spyPathAwareVisitor).visitProject(eq(COMPONENT_TREE), any(PathAwareVisitor.Path.class)); } @Test public void execute_pre_visitor_before_post_visitor() { InOrder inOrder = inOrder(spyPreOrderTypeAwareVisitor, spyPostOrderTypeAwareVisitor); VisitorsCrawler underTest = new VisitorsCrawler(Arrays.asList(spyPreOrderTypeAwareVisitor, spyPostOrderTypeAwareVisitor)); underTest.visit(COMPONENT_TREE); inOrder.verify(spyPreOrderTypeAwareVisitor).visitProject(COMPONENT_TREE); inOrder.verify(spyPreOrderTypeAwareVisitor).visitDirectory(DIRECTORY_4); inOrder.verify(spyPreOrderTypeAwareVisitor).visitFile(FILE_5); inOrder.verify(spyPostOrderTypeAwareVisitor).visitFile(FILE_5); inOrder.verify(spyPostOrderTypeAwareVisitor).visitDirectory(DIRECTORY_4); inOrder.verify(spyPostOrderTypeAwareVisitor).visitProject(COMPONENT_TREE); } @Test public void getCumulativeDurations_returns_an_empty_map_when_computation_is_disabled_in_constructor() { VisitorsCrawler underTest = new VisitorsCrawler(Arrays.asList(spyPreOrderTypeAwareVisitor, spyPostOrderTypeAwareVisitor), false); underTest.visit(COMPONENT_TREE); assertThat(underTest.getCumulativeDurations()).isEmpty(); } @Test public void getCumulativeDurations_returns_an_non_empty_map_when_computation_is_enabled_in_constructor() { VisitorsCrawler underTest = new VisitorsCrawler(Arrays.asList(spyPreOrderTypeAwareVisitor, spyPostOrderTypeAwareVisitor), true); underTest.visit(COMPONENT_TREE); assertThat(underTest.getCumulativeDurations()).hasSize(2); } @Test public void fail_with_IAE_when_visitor_is_not_path_aware_or_type_aware() { assertThatThrownBy(() -> { ComponentVisitor componentVisitor = new ComponentVisitor() { @Override public Order getOrder() { return PRE_ORDER; } @Override public CrawlerDepthLimit getMaxDepth() { return CrawlerDepthLimit.FILE; } }; new VisitorsCrawler(Arrays.asList(componentVisitor)); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Only TypeAwareVisitor and PathAwareVisitor can be used"); } private static Component component(final Component.Type type, final int ref, final Component... children) { return ReportComponent.builder(type, ref).addChildren(children).build(); } private static class TestTypeAwareVisitor extends TypeAwareVisitorAdapter { public TestTypeAwareVisitor(CrawlerDepthLimit maxDepth, ComponentVisitor.Order order) { super(maxDepth, order); } } private static class TestPathAwareVisitor extends PathAwareVisitorAdapter<Integer> { public TestPathAwareVisitor(CrawlerDepthLimit maxDepth, ComponentVisitor.Order order) { super(maxDepth, order, new SimpleStackElementFactory<Integer>() { @Override public Integer createForAny(Component component) { return component.getReportAttributes().getRef(); } }); } } }
6,631
44.115646
133
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ReportVisitorsCrawlerWithPathAwareVisitorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if 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 java.util.Iterator; import java.util.List; import javax.annotation.Nullable; import org.junit.Test; import static com.google.common.collect.ImmutableList.of; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.ce.task.projectanalysis.component.Component.Type.DIRECTORY; import static org.sonar.ce.task.projectanalysis.component.Component.Type.FILE; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT; import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.POST_ORDER; import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.PRE_ORDER; public class ReportVisitorsCrawlerWithPathAwareVisitorTest { private static final int ROOT_REF = 1; private static final ReportComponent SOME_TREE_ROOT = ReportComponent.builder(PROJECT, ROOT_REF) .addChildren( ReportComponent.builder(DIRECTORY, 11) .addChildren( ReportComponent.builder(FILE, 111).build(), ReportComponent.builder(FILE, 112).build()) .build(), ReportComponent.builder(DIRECTORY, 12) .addChildren( ReportComponent.builder(FILE, 121).build(), ReportComponent.builder(DIRECTORY, 122) .addChildren( ReportComponent.builder(FILE, 1221).build()) .build()) .build()) .build(); @Test public void verify_preOrder_visit_call_when_visit_tree_with_depth_FILE() { CallRecorderPathAwareVisitor visitor = new CallRecorderPathAwareVisitor(CrawlerDepthLimit.FILE, PRE_ORDER); VisitorsCrawler underTest = newVisitorsCrawler(visitor); underTest.visit(SOME_TREE_ROOT); Iterator<PathAwareCallRecord> expected = of( reportCallRecord("visitAny", 1, null, of(1)), reportCallRecord("visitProject", 1, null, of(1)), reportCallRecord("visitAny", 11, 1, of(11, 1)), reportCallRecord("visitDirectory", 11, 1, of(11, 1)), reportCallRecord("visitAny", 111, 11, of(111, 11, 1)), reportCallRecord("visitFile", 111, 11, of(111, 11, 1)), reportCallRecord("visitAny", 112, 11, of(112, 11, 1)), reportCallRecord("visitFile", 112, 11, of(112, 11, 1)), reportCallRecord("visitAny", 12, 1, of(12, 1)), reportCallRecord("visitDirectory", 12, 1, of(12, 1)), reportCallRecord("visitAny", 121, 12, of(121, 12, 1)), reportCallRecord("visitFile", 121, 12, of(121, 12, 1)), reportCallRecord("visitAny", 122, 12, of(122, 12, 1)), reportCallRecord("visitDirectory", 122, 12, of(122, 12, 1)), reportCallRecord("visitAny", 1221, 122, of(1221, 122, 12, 1)), reportCallRecord("visitFile", 1221, 122, of(1221, 122, 12, 1))).iterator(); verifyCallRecords(expected, visitor.callsRecords.iterator()); } @Test public void verify_preOrder_visit_call_when_visit_tree_with_depth_DIRECTORY() { CallRecorderPathAwareVisitor visitor = new CallRecorderPathAwareVisitor(CrawlerDepthLimit.DIRECTORY, PRE_ORDER); VisitorsCrawler underTest = newVisitorsCrawler(visitor); underTest.visit(SOME_TREE_ROOT); Iterator<PathAwareCallRecord> expected = of( reportCallRecord("visitAny", 1, null, of(1)), reportCallRecord("visitProject", 1, null, of(1)), reportCallRecord("visitAny", 11, 1, of(11, 1)), reportCallRecord("visitDirectory", 11, 1, of(11, 1)), reportCallRecord("visitAny", 12, 1, of(12, 1)), reportCallRecord("visitDirectory", 12, 1, of(12, 1)), reportCallRecord("visitAny", 122, 12, of(122, 12, 1)), reportCallRecord("visitDirectory", 122, 12, of(122, 12, 1))).iterator(); verifyCallRecords(expected, visitor.callsRecords.iterator()); } @Test public void verify_preOrder_visit_call_when_visit_tree_with_depth_PROJECT() { CallRecorderPathAwareVisitor visitor = new CallRecorderPathAwareVisitor(CrawlerDepthLimit.PROJECT, PRE_ORDER); VisitorsCrawler underTest = newVisitorsCrawler(visitor); underTest.visit(SOME_TREE_ROOT); Iterator<PathAwareCallRecord> expected = of( reportCallRecord("visitAny", 1, null, of(1)), reportCallRecord("visitProject", 1, null, of(1))).iterator(); verifyCallRecords(expected, visitor.callsRecords.iterator()); } @Test public void verify_postOrder_visit_call_when_visit_tree_with_depth_FILE() { CallRecorderPathAwareVisitor visitor = new CallRecorderPathAwareVisitor(CrawlerDepthLimit.FILE, POST_ORDER); VisitorsCrawler underTest = newVisitorsCrawler(visitor); underTest.visit(SOME_TREE_ROOT); Iterator<PathAwareCallRecord> expected = of( reportCallRecord("visitAny", 111, 11, of(111, 11, 1)), reportCallRecord("visitFile", 111, 11, of(111, 11, 1)), reportCallRecord("visitAny", 112, 11, of(112, 11, 1)), reportCallRecord("visitFile", 112, 11, of(112, 11, 1)), reportCallRecord("visitAny", 11, 1, of(11, 1)), reportCallRecord("visitDirectory", 11, 1, of(11, 1)), reportCallRecord("visitAny", 121, 12, of(121, 12, 1)), reportCallRecord("visitFile", 121, 12, of(121, 12, 1)), reportCallRecord("visitAny", 1221, 122, of(1221, 122, 12, 1)), reportCallRecord("visitFile", 1221, 122, of(1221, 122, 12, 1)), reportCallRecord("visitAny", 122, 12, of(122, 12, 1)), reportCallRecord("visitDirectory", 122, 12, of(122, 12, 1)), reportCallRecord("visitAny", 12, 1, of(12, 1)), reportCallRecord("visitDirectory", 12, 1, of(12, 1)), reportCallRecord("visitAny", 1, null, of(1)), reportCallRecord("visitProject", 1, null, of(1))).iterator(); verifyCallRecords(expected, visitor.callsRecords.iterator()); } @Test public void verify_postOrder_visit_call_when_visit_tree_with_depth_DIRECTORY() { CallRecorderPathAwareVisitor visitor = new CallRecorderPathAwareVisitor(CrawlerDepthLimit.DIRECTORY, POST_ORDER); VisitorsCrawler underTest = newVisitorsCrawler(visitor); underTest.visit(SOME_TREE_ROOT); Iterator<PathAwareCallRecord> expected = of( reportCallRecord("visitAny", 11, 1, of(11, 1)), reportCallRecord("visitDirectory", 11, 1, of(11, 1)), reportCallRecord("visitAny", 122, 12, of(122, 12, 1)), reportCallRecord("visitDirectory", 122, 12, of(122, 12, 1)), reportCallRecord("visitAny", 12, 1, of(12, 1)), reportCallRecord("visitDirectory", 12, 1, of(12, 1)), reportCallRecord("visitAny", 1, null, of(1)), reportCallRecord("visitProject", 1, null, of(1))).iterator(); verifyCallRecords(expected, visitor.callsRecords.iterator()); } @Test public void verify_postOrder_visit_call_when_visit_tree_with_depth_PROJECT() { CallRecorderPathAwareVisitor visitor = new CallRecorderPathAwareVisitor(CrawlerDepthLimit.PROJECT, POST_ORDER); VisitorsCrawler underTest = newVisitorsCrawler(visitor); underTest.visit(SOME_TREE_ROOT); Iterator<PathAwareCallRecord> expected = of( reportCallRecord("visitAny", 1, null, of(1)), reportCallRecord("visitProject", 1, null, of(1))).iterator(); verifyCallRecords(expected, visitor.callsRecords.iterator()); } private static void verifyCallRecords(Iterator<PathAwareCallRecord> expected, Iterator<PathAwareCallRecord> actual) { while (expected.hasNext()) { assertThat(actual.next()).isEqualTo(expected.next()); } } private static PathAwareCallRecord reportCallRecord(String method, int currentRef, @Nullable Integer parentRef, List<Integer> path) { return PathAwareCallRecord.reportCallRecord(method, currentRef, currentRef, parentRef, ROOT_REF, path); } private static VisitorsCrawler newVisitorsCrawler(ComponentVisitor componentVisitor) { return new VisitorsCrawler(Arrays.asList(componentVisitor)); } }
8,629
46.15847
135
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ReportVisitorsCrawlerWithPostOrderTypeAwareVisitorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if 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 org.junit.Test; import org.mockito.InOrder; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.sonar.ce.task.projectanalysis.component.Component.Type.DIRECTORY; import static org.sonar.ce.task.projectanalysis.component.Component.Type.FILE; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT; import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.POST_ORDER; public class ReportVisitorsCrawlerWithPostOrderTypeAwareVisitorTest { private static final Component FILE_5 = component(FILE, 5); private static final Component FILE_6 = component(FILE, 6); private static final Component DIRECTORY_4 = component(DIRECTORY, 4, FILE_5, FILE_6); private static final Component COMPONENT_TREE = component(PROJECT, 1, DIRECTORY_4); private final TypeAwareVisitor spyProjectVisitor = spy(new TypeAwareVisitorAdapter(CrawlerDepthLimit.PROJECT, POST_ORDER) { }); private final TypeAwareVisitor spyDirectoryVisitor = spy(new TypeAwareVisitorAdapter(CrawlerDepthLimit.DIRECTORY, POST_ORDER) { }); private final TypeAwareVisitor spyFileVisitor = spy(new TypeAwareVisitorAdapter(CrawlerDepthLimit.FILE, POST_ORDER) { }); private final InOrder inOrder = inOrder(spyProjectVisitor, spyDirectoryVisitor, spyFileVisitor); @Test public void visit_null_Component_throws_NPE() { VisitorsCrawler underTest = newVisitorsCrawler(spyFileVisitor); assertThatThrownBy(() -> underTest.visit(null)) .isInstanceOf(NullPointerException.class); } @Test public void visit_file_with_depth_FILE_calls_visit_file() { Component component = component(FILE, 1); VisitorsCrawler underTest = newVisitorsCrawler(spyFileVisitor); underTest.visit(component); inOrder.verify(spyFileVisitor).visitAny(component); inOrder.verify(spyFileVisitor).visitFile(component); inOrder.verifyNoMoreInteractions(); } @Test public void visit_directory_with_depth_FILE_calls_visit_directory() { Component component = component(DIRECTORY, 1); VisitorsCrawler underTest = newVisitorsCrawler(spyFileVisitor); underTest.visit(component); inOrder.verify(spyFileVisitor).visitAny(component); inOrder.verify(spyFileVisitor).visitDirectory(component); inOrder.verifyNoMoreInteractions(); } @Test public void visit_project_with_depth_FILE_calls_visit_project() { Component component = component(PROJECT, 1); VisitorsCrawler underTest = newVisitorsCrawler(spyFileVisitor); underTest.visit(component); inOrder.verify(spyFileVisitor).visitAny(component); inOrder.verify(spyFileVisitor).visitProject(component); inOrder.verifyNoMoreInteractions(); } @Test public void visit_file_with_depth_DIRECTORY_does_not_call_visit_file_nor_visitAny() { Component component = component(FILE, 1); VisitorsCrawler underTest = newVisitorsCrawler(spyDirectoryVisitor); underTest.visit(component); inOrder.verify(spyDirectoryVisitor, never()).visitFile(component); inOrder.verify(spyDirectoryVisitor, never()).visitAny(component); } @Test public void visit_directory_with_depth_DIRECTORY_calls_visit_directory() { Component component = component(DIRECTORY, 1); VisitorsCrawler underTest = newVisitorsCrawler(spyDirectoryVisitor); underTest.visit(component); inOrder.verify(spyDirectoryVisitor).visitAny(component); inOrder.verify(spyDirectoryVisitor).visitDirectory(component); inOrder.verifyNoMoreInteractions(); } @Test public void visit_project_with_depth_DIRECTORY_calls_visit_project() { Component component = component(PROJECT, 1); VisitorsCrawler underTest = newVisitorsCrawler(spyDirectoryVisitor); underTest.visit(component); inOrder.verify(spyDirectoryVisitor).visitAny(component); inOrder.verify(spyDirectoryVisitor).visitProject(component); inOrder.verifyNoMoreInteractions(); } @Test public void visit_file_with_depth_PROJECT_does_not_call_visit_file_nor_visitAny() { Component component = component(FILE, 1); VisitorsCrawler underTest = newVisitorsCrawler(spyProjectVisitor); underTest.visit(component); inOrder.verify(spyProjectVisitor, never()).visitFile(component); inOrder.verify(spyProjectVisitor, never()).visitAny(component); } @Test public void visit_directory_with_depth_PROJECT_does_not_call_visit_directory_nor_visitAny() { Component component = component(DIRECTORY, 1); VisitorsCrawler underTest = newVisitorsCrawler(spyProjectVisitor); underTest.visit(component); inOrder.verify(spyProjectVisitor, never()).visitDirectory(component); inOrder.verify(spyProjectVisitor, never()).visitFile(component); inOrder.verify(spyProjectVisitor, never()).visitAny(component); } @Test public void visit_project_with_depth_PROJECT_calls_visit_project() { Component component = component(PROJECT, 1); VisitorsCrawler underTest = newVisitorsCrawler(spyProjectVisitor); underTest.visit(component); inOrder.verify(spyProjectVisitor).visitAny(component); inOrder.verify(spyProjectVisitor).visitProject(component); inOrder.verifyNoMoreInteractions(); } @Test public void verify_visit_call_when_visit_tree_with_depth_FILE() { VisitorsCrawler underTest = newVisitorsCrawler(spyFileVisitor); underTest.visit(COMPONENT_TREE); inOrder.verify(spyFileVisitor).visitAny(FILE_5); inOrder.verify(spyFileVisitor).visitFile(FILE_5); inOrder.verify(spyFileVisitor).visitAny(FILE_6); inOrder.verify(spyFileVisitor).visitFile(FILE_6); inOrder.verify(spyFileVisitor).visitAny(DIRECTORY_4); inOrder.verify(spyFileVisitor).visitDirectory(DIRECTORY_4); inOrder.verify(spyFileVisitor).visitAny(COMPONENT_TREE); inOrder.verify(spyFileVisitor).visitProject(COMPONENT_TREE); inOrder.verifyNoMoreInteractions(); } @Test public void verify_visit_call_when_visit_tree_with_depth_DIRECTORY() { VisitorsCrawler underTest = newVisitorsCrawler(spyDirectoryVisitor); underTest.visit(COMPONENT_TREE); inOrder.verify(spyDirectoryVisitor).visitAny(DIRECTORY_4); inOrder.verify(spyDirectoryVisitor).visitDirectory(DIRECTORY_4); inOrder.verify(spyDirectoryVisitor).visitAny(COMPONENT_TREE); inOrder.verify(spyDirectoryVisitor).visitProject(COMPONENT_TREE); inOrder.verifyNoMoreInteractions(); } @Test public void verify_visit_call_when_visit_tree_with_depth_PROJECT() { VisitorsCrawler underTest = newVisitorsCrawler(spyProjectVisitor); underTest.visit(COMPONENT_TREE); inOrder.verify(spyProjectVisitor).visitAny(COMPONENT_TREE); inOrder.verify(spyProjectVisitor).visitProject(COMPONENT_TREE); inOrder.verifyNoMoreInteractions(); } private static Component component(final Component.Type type, final int ref, final Component... children) { return ReportComponent.builder(type, ref).addChildren(children).build(); } private static VisitorsCrawler newVisitorsCrawler(ComponentVisitor componentVisitor) { return new VisitorsCrawler(Arrays.asList(componentVisitor)); } }
8,144
39.321782
129
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ReportVisitorsCrawlerWithPreOrderTypeAwareVisitorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if 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 org.junit.Test; import org.mockito.InOrder; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.sonar.ce.task.projectanalysis.component.Component.Type.DIRECTORY; import static org.sonar.ce.task.projectanalysis.component.Component.Type.FILE; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT; import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.PRE_ORDER; public class ReportVisitorsCrawlerWithPreOrderTypeAwareVisitorTest { private static final Component FILE_5 = component(FILE, 5); private static final Component FILE_6 = component(FILE, 6); private static final Component DIRECTORY_4 = component(DIRECTORY, 4, FILE_5, FILE_6); private static final Component COMPONENT_TREE = component(PROJECT, 1, DIRECTORY_4); private final TypeAwareVisitor spyProjectVisitor = spy(new TypeAwareVisitorAdapter(CrawlerDepthLimit.PROJECT, PRE_ORDER) { }); private final TypeAwareVisitor spyDirectoryVisitor = spy(new TypeAwareVisitorAdapter(CrawlerDepthLimit.DIRECTORY, PRE_ORDER) { }); private final TypeAwareVisitor spyFileVisitor = spy(new TypeAwareVisitorAdapter(CrawlerDepthLimit.FILE, PRE_ORDER) { }); private final InOrder inOrder = inOrder(spyProjectVisitor, spyDirectoryVisitor, spyFileVisitor); @Test public void visit_null_Component_throws_NPE() { VisitorsCrawler underTest = newVisitorsCrawler(spyFileVisitor); assertThatThrownBy(() -> underTest.visit(null)) .isInstanceOf(NullPointerException.class); } @Test public void visit_file_with_depth_FILE_calls_visit_file() { Component component = component(FILE, 1); VisitorsCrawler underTest = newVisitorsCrawler(spyFileVisitor); underTest.visit(component); inOrder.verify(spyFileVisitor).visitAny(component); inOrder.verify(spyFileVisitor).visitFile(component); inOrder.verifyNoMoreInteractions(); } @Test public void visit_directory_with_depth_FILE_calls_visit_directory() { Component component = component(DIRECTORY, 1); VisitorsCrawler underTest = newVisitorsCrawler(spyFileVisitor); underTest.visit(component); inOrder.verify(spyFileVisitor).visitAny(component); inOrder.verify(spyFileVisitor).visitDirectory(component); inOrder.verifyNoMoreInteractions(); } @Test public void visit_project_with_depth_FILE_calls_visit_project() { Component component = component(PROJECT, 1); VisitorsCrawler underTest = newVisitorsCrawler(spyFileVisitor); underTest.visit(component); inOrder.verify(spyFileVisitor).visitProject(component); inOrder.verifyNoMoreInteractions(); } @Test public void visit_file_with_depth_DIRECTORY_does_not_call_visit_file_nor_visitAny() { Component component = component(FILE, 1); VisitorsCrawler underTest = newVisitorsCrawler(spyDirectoryVisitor); underTest.visit(component); inOrder.verify(spyDirectoryVisitor, never()).visitFile(component); inOrder.verify(spyDirectoryVisitor, never()).visitAny(component); } @Test public void visit_directory_with_depth_DIRECTORY_calls_visit_directory() { Component component = component(DIRECTORY, 1); VisitorsCrawler underTest = newVisitorsCrawler(spyDirectoryVisitor); underTest.visit(component); inOrder.verify(spyDirectoryVisitor).visitAny(component); inOrder.verify(spyDirectoryVisitor).visitDirectory(component); inOrder.verifyNoMoreInteractions(); } @Test public void visit_project_with_depth_DIRECTORY_calls_visit_project() { Component component = component(PROJECT, 1); VisitorsCrawler underTest = newVisitorsCrawler(spyDirectoryVisitor); underTest.visit(component); inOrder.verify(spyDirectoryVisitor).visitAny(component); inOrder.verify(spyDirectoryVisitor).visitProject(component); inOrder.verifyNoMoreInteractions(); } @Test public void visit_file_with_depth_PROJECT_does_not_call_visit_file_nor_visitAny() { Component component = component(FILE, 1); VisitorsCrawler underTest = newVisitorsCrawler(spyProjectVisitor); underTest.visit(component); inOrder.verify(spyProjectVisitor, never()).visitFile(component); inOrder.verify(spyProjectVisitor, never()).visitAny(component); } @Test public void visit_directory_with_depth_PROJECT_does_not_call_visit_directory_nor_visitAny() { Component component = component(DIRECTORY, 1); VisitorsCrawler underTest = newVisitorsCrawler(spyProjectVisitor); underTest.visit(component); inOrder.verify(spyProjectVisitor, never()).visitFile(component); inOrder.verify(spyProjectVisitor, never()).visitAny(component); } @Test public void visit_project_with_depth_PROJECT_calls_visit_project_nor_visitAny() { Component component = component(PROJECT, 1); VisitorsCrawler underTest = newVisitorsCrawler(spyProjectVisitor); underTest.visit(component); inOrder.verify(spyProjectVisitor).visitAny(component); inOrder.verify(spyProjectVisitor).visitProject(component); inOrder.verifyNoMoreInteractions(); } @Test public void verify_visit_call_when_visit_tree_with_depth_FILE() { VisitorsCrawler underTest = newVisitorsCrawler(spyFileVisitor); underTest.visit(COMPONENT_TREE); inOrder.verify(spyFileVisitor).visitAny(COMPONENT_TREE); inOrder.verify(spyFileVisitor).visitProject(COMPONENT_TREE); inOrder.verify(spyFileVisitor).visitAny(DIRECTORY_4); inOrder.verify(spyFileVisitor).visitDirectory(DIRECTORY_4); inOrder.verify(spyFileVisitor).visitAny(FILE_5); inOrder.verify(spyFileVisitor).visitFile(FILE_5); inOrder.verify(spyFileVisitor).visitAny(FILE_6); inOrder.verify(spyFileVisitor).visitFile(FILE_6); inOrder.verifyNoMoreInteractions(); } @Test public void verify_visit_call_when_visit_tree_with_depth_DIRECTORY() { VisitorsCrawler underTest = newVisitorsCrawler(spyDirectoryVisitor); underTest.visit(COMPONENT_TREE); inOrder.verify(spyDirectoryVisitor).visitProject(COMPONENT_TREE); inOrder.verify(spyDirectoryVisitor).visitDirectory(DIRECTORY_4); inOrder.verify(spyProjectVisitor, never()).visitFile(FILE_5); inOrder.verify(spyProjectVisitor, never()).visitFile(FILE_6); } @Test public void verify_visit_call_when_visit_tree_with_depth_PROJECT() { VisitorsCrawler underTest = newVisitorsCrawler(spyProjectVisitor); underTest.visit(COMPONENT_TREE); inOrder.verify(spyProjectVisitor).visitAny(COMPONENT_TREE); inOrder.verify(spyProjectVisitor).visitProject(COMPONENT_TREE); } private static Component component(final Component.Type type, final int ref, final Component... children) { return ReportComponent.builder(type, ref).addChildren(children).build(); } private static VisitorsCrawler newVisitorsCrawler(ComponentVisitor componentVisitor) { return new VisitorsCrawler(Arrays.asList(componentVisitor)); } }
7,944
39.329949
128
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/TestSettingsRepository.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if 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; /** * Implementation of {@link ConfigurationRepository} that always return the * same {@link Configuration}, whatever the component. */ public class TestSettingsRepository implements ConfigurationRepository { private final Configuration config; public TestSettingsRepository(Configuration config) { this.config = config; } @Override public Configuration getConfiguration() { return config; } }
1,361
32.219512
75
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/TreeRootHolderImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if 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.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.ce.task.projectanalysis.component.Component.Type.DIRECTORY; import static org.sonar.ce.task.projectanalysis.component.Component.Type.FILE; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT_VIEW; import static org.sonar.ce.task.projectanalysis.component.Component.Type.VIEW; import static org.sonar.ce.task.projectanalysis.component.ReportComponent.DUMB_PROJECT; public class TreeRootHolderImplTest { private static final ReportComponent SOME_REPORT_COMPONENT_TREE = ReportComponent.builder(PROJECT, 1) .addChildren(ReportComponent.builder(DIRECTORY, 2) .addChildren( ReportComponent.builder(FILE, 3).build()) .build()) .build(); private static final ViewsComponent SOME_VIEWS_COMPONENT_TREE = ViewsComponent.builder(VIEW, 1) .addChildren( ViewsComponent.builder(VIEW, 2) .addChildren(ViewsComponent.builder(PROJECT_VIEW, 3).build()) .build()) .build(); private TreeRootHolderImpl underTest = new TreeRootHolderImpl(); @Test public void setRoots_throws_NPE_if_root_is_null() { assertThatThrownBy(() -> underTest.setRoots(null, DUMB_PROJECT)) .isInstanceOf(NullPointerException.class) .hasMessage("root can not be null"); } @Test public void setRoots_throws_NPE_if_reportRoot_is_null() { assertThatThrownBy(() -> underTest.setRoots(DUMB_PROJECT, null)) .isInstanceOf(NullPointerException.class) .hasMessageContaining("root can not be null"); } @Test public void setRoot_throws_ISE_when_called_twice() { underTest.setRoots(DUMB_PROJECT, DUMB_PROJECT); assertThatThrownBy(() -> underTest.setRoots(null, DUMB_PROJECT)) .isInstanceOf(IllegalStateException.class) .hasMessage("root can not be set twice in holder"); } @Test public void getRoot_throws_ISE_if_root_has_not_been_set_yet() { assertThatThrownBy(() -> underTest.getRoot()) .isInstanceOf(IllegalStateException.class) .hasMessage("Holder has not been initialized yet"); } @Test public void getComponentByRef_throws_ISE_if_root_has_not_been_set() { assertThatThrownBy(() -> underTest.getComponentByRef(12)) .isInstanceOf(IllegalStateException.class) .hasMessage("Holder has not been initialized yet"); } @Test public void getComponentByRef_returns_any_report_component_in_the_tree() { underTest.setRoots(SOME_REPORT_COMPONENT_TREE, DUMB_PROJECT); for (int i = 1; i <= 3; i++) { assertThat(underTest.getComponentByRef(i).getReportAttributes().getRef()).isEqualTo(i); } } @Test public void getOptionalComponentByRef_returns_any_report_component_in_the_tree() { underTest.setRoots(SOME_REPORT_COMPONENT_TREE, DUMB_PROJECT); for (int i = 1; i <= 3; i++) { assertThat(underTest.getOptionalComponentByRef(i).get().getReportAttributes().getRef()).isEqualTo(i); } } @Test public void getComponentByRef_throws_IAE_if_holder_does_not_contain_specified_component() { underTest.setRoots(SOME_REPORT_COMPONENT_TREE, DUMB_PROJECT); assertThatThrownBy(() -> underTest.getComponentByRef(6)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Component with ref '6' can't be found"); } @Test public void getOptionalComponentByRef_returns_empty_if_holder_does_not_contain_specified_component() { underTest.setRoots(SOME_REPORT_COMPONENT_TREE, DUMB_PROJECT); assertThat(underTest.getOptionalComponentByRef(6)).isEmpty(); } @Test public void getComponentByRef_throws_IAE_if_holder_contains_View_tree() { underTest.setRoots(SOME_VIEWS_COMPONENT_TREE, DUMB_PROJECT); assertThatThrownBy(() -> underTest.getComponentByRef(1)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Component with ref '1' can't be found"); } @Test public void verify_setRoots_getRoot() { underTest.setRoots(SOME_REPORT_COMPONENT_TREE, DUMB_PROJECT); assertThat(underTest.getRoot()).isSameAs(SOME_REPORT_COMPONENT_TREE); } @Test public void verify_setRoots_getReportRoot() { underTest.setRoots(SOME_REPORT_COMPONENT_TREE, DUMB_PROJECT); assertThat(underTest.getReportTreeRoot()).isSameAs(DUMB_PROJECT); } @Test public void getSize_throws_ISE_if_not_initialized() { assertThatThrownBy(() -> underTest.getSize()) .isInstanceOf(IllegalStateException.class) .hasMessage("Holder has not been initialized yet"); } @Test public void getSize_counts_number_of_components() { underTest.setRoots(SOME_REPORT_COMPONENT_TREE, DUMB_PROJECT); assertThat(underTest.getSize()).isEqualTo(3); } }
5,759
36.16129
107
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/TypeAwareVisitorAdapterTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if 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.junit.Test; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.POST_ORDER; public class TypeAwareVisitorAdapterTest { @Test public void non_null_max_depth_fast_fail() { assertThatThrownBy(() -> { new TypeAwareVisitorAdapter(null, POST_ORDER) { }; }) .isInstanceOf(NullPointerException.class); } }
1,336
34.184211
92
java