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-db-dao/src/main/java/org/sonar/db/component/ProjectLinkMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.component; import java.util.List; import org.apache.ibatis.annotations.Param; public interface ProjectLinkMapper { List<ProjectLinkDto> selectByProjectUuid(String projectUuid); List<ProjectLinkDto> selectByProjectUuids(@Param("projectUuids") List<String> projectUuids); ProjectLinkDto selectByUuid(@Param("uuid") String uuid); void insert(ProjectLinkDto dto); void update(ProjectLinkDto dto); void delete(String uuid); }
1,305
32.487179
94
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/component/ProjectNclocDistributionDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.component; public class ProjectNclocDistributionDto { private String kee; private String name; private long ncloc; public String getKee() { return kee; } public ProjectNclocDistributionDto setKee(String kee) { this.kee = kee; return this; } public String getName() { return name; } public ProjectNclocDistributionDto setName(String name) { this.name = name; return this; } public long getNcloc() { return ncloc; } public ProjectNclocDistributionDto setNcloc(long ncloc) { this.ncloc = ncloc; return this; } }
1,446
25.796296
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/component/ResourceDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.component; import java.util.Date; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import static org.sonar.db.component.ComponentValidator.checkComponentKey; import static org.sonar.db.component.ComponentValidator.checkComponentLongName; import static org.sonar.db.component.ComponentValidator.checkComponentName; import static org.sonar.db.component.ComponentValidator.checkDescription; public class ResourceDto { private String uuid; private String projectUuid; private String key; private String deprecatedKey; private String name; private String longName; private String path; private String scope; private String qualifier; private boolean enabled = true; private String description; private String language; private String copyComponentUuid; private Date createdAt; public String getUuid() { return uuid; } public ResourceDto setUuid(String uuid) { this.uuid = uuid; return this; } public String getProjectUuid() { return projectUuid; } public ResourceDto setProjectUuid(String projectUuid) { this.projectUuid = projectUuid; return this; } public String getName() { return name; } public ResourceDto setName(String name) { this.name = checkComponentName(name); return this; } public String getKey() { return key; } public ResourceDto setKey(String s) { this.key = checkComponentKey(s); return this; } public String getDeprecatedKey() { return deprecatedKey; } public ResourceDto setDeprecatedKey(String s) { this.deprecatedKey = s; return this; } public String getPath() { return path; } public ResourceDto setPath(String s) { this.path = s; return this; } public String getLongName() { return longName; } public ResourceDto setLongName(String longName) { this.longName = checkComponentLongName(longName); return this; } public String getScope() { return scope; } public ResourceDto setScope(String scope) { this.scope = scope; return this; } public String getQualifier() { return qualifier; } public ResourceDto setQualifier(String qualifier) { this.qualifier = qualifier; return this; } public boolean isEnabled() { return enabled; } public ResourceDto setEnabled(boolean b) { this.enabled = b; return this; } public String getDescription() { return description; } public ResourceDto setDescription(String description) { this.description = checkDescription(description); return this; } public String getLanguage() { return language; } public ResourceDto setLanguage(String language) { this.language = language; return this; } @CheckForNull public String getCopyComponentUuid() { return copyComponentUuid; } public ResourceDto setCopyComponentUuid(@Nullable String copyComponentUuid) { this.copyComponentUuid = copyComponentUuid; return this; } public Date getCreatedAt() { return createdAt; } public ResourceDto setCreatedAt(Date date) { this.createdAt = date; return this; } }
4,015
21.948571
79
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/component/ScrapAnalysisPropertyDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.component; import javax.annotation.Nullable; public class ScrapAnalysisPropertyDto extends AnalysisPropertyDto { public void setEmpty(boolean flag) { if (flag) { setValue(""); } } public void setTextValue(@Nullable String value) { if (value != null) { setValue(value); } } public void setClobValue(@Nullable String value) { if (value != null) { setValue(value); } } }
1,290
29.023256
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/component/SelectionMode.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.component; public enum SelectionMode { MANUAL_MEASURE, REGEXP, TAGS, REMAINING_PROJECTS }
963
33.428571
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/component/SnapshotDao.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.component; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Lists; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.IntStream; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.apache.ibatis.session.RowBounds; import org.sonar.db.Dao; import org.sonar.db.DbSession; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Objects.requireNonNull; import static org.sonar.db.DatabaseUtils.executeLargeInputs; public class SnapshotDao implements Dao { public static boolean isLast(SnapshotDto snapshotTested, @Nullable SnapshotDto previousLastSnapshot) { return previousLastSnapshot == null || previousLastSnapshot.getCreatedAt() < snapshotTested.getCreatedAt(); } public Optional<SnapshotDto> selectByUuid(DbSession dbSession, String analysisUuid) { List<SnapshotDto> dtos = mapper(dbSession).selectByUuids(Collections.singletonList(analysisUuid)); if (dtos.isEmpty()) { return Optional.empty(); } return Optional.of(dtos.iterator().next()); } public List<SnapshotDto> selectByUuids(DbSession dbSession, Collection<String> analysisUuids) { return executeLargeInputs(analysisUuids, mapper(dbSession)::selectByUuids); } public Optional<SnapshotDto> selectLastAnalysisByComponentUuid(DbSession session, String componentUuid) { return Optional.ofNullable(mapper(session).selectLastSnapshotByComponentUuid(componentUuid)); } /** * returns the last analysis of any branch of a project */ public Optional<Long> selectLastAnalysisDateByProject(DbSession session, String projectUuid) { return Optional.ofNullable(mapper(session).selectLastAnalysisDateByProject(projectUuid)); } /** * returns the last analysis of any branch for each existing project */ public List<ProjectLastAnalysisDateDto> selectLastAnalysisDateByProjectUuids(DbSession session, Collection<String> projectUuids) { if (projectUuids.isEmpty()) { return Collections.emptyList(); } return mapper(session).selectLastAnalysisDateByProjectUuids(projectUuids); } public Optional<SnapshotDto> selectLastAnalysisByRootComponentUuid(DbSession session, String rootComponentUuid) { return Optional.ofNullable(mapper(session).selectLastSnapshotByRootComponentUuid(rootComponentUuid)); } public List<SnapshotDto> selectLastAnalysesByRootComponentUuids(DbSession dbSession, Collection<String> rootComponentUuids) { return executeLargeInputs(rootComponentUuids, mapper(dbSession)::selectLastSnapshotsByRootComponentUuids); } public List<SnapshotDto> selectAnalysesByQuery(DbSession session, SnapshotQuery query) { return mapper(session).selectSnapshotsByQuery(query); } public Optional<SnapshotDto> selectOldestAnalysis(DbSession session, String rootComponentUuid) { return mapper(session).selectOldestSnapshots(rootComponentUuid, SnapshotDto.STATUS_PROCESSED, new RowBounds(0, 1)) .stream() .findFirst(); } /** * Returned finished analysis from a list of projects and dates. * "Finished" analysis means that the status in the CE_ACTIVITY table is SUCCESS => the goal is to be sure that the CE task is completely finished. * Note that branches analysis of projects are also returned. */ public List<SnapshotDto> selectFinishedByProjectUuidsAndFromDates(DbSession dbSession, List<String> projectUuids, List<Long> fromDates) { checkArgument(projectUuids.size() == fromDates.size(), "The number of components (%s) and from dates (%s) must be the same.", String.valueOf(projectUuids.size()), String.valueOf(fromDates.size())); List<ProjectUuidFromDatePair> projectUuidFromDatePairs = IntStream.range(0, projectUuids.size()) .mapToObj(i -> new ProjectUuidFromDatePair(projectUuids.get(i), fromDates.get(i))) .toList(); return executeLargeInputs(projectUuidFromDatePairs, partition -> mapper(dbSession).selectFinishedByProjectUuidsAndFromDates(partition), i -> i / 2); } public void switchIsLastFlagAndSetProcessedStatus(DbSession dbSession, String rootComponentUuid, String analysisUuid) { SnapshotMapper mapper = mapper(dbSession); mapper.unsetIsLastFlagForRootComponentUuid(rootComponentUuid); mapper(dbSession).setIsLastFlagForAnalysisUuid(analysisUuid); } public SnapshotDto insert(DbSession session, SnapshotDto item) { mapper(session).insert(item); return item; } @VisibleForTesting public void insert(DbSession session, Collection<SnapshotDto> items) { for (SnapshotDto item : items) { insert(session, item); } } @VisibleForTesting public void insert(DbSession session, SnapshotDto item, SnapshotDto... others) { insert(session, Lists.asList(item, others)); } public void update(DbSession dbSession, SnapshotDto analysis) { mapper(dbSession).update(analysis); } /** * Used by Governance */ @CheckForNull public ViewsSnapshotDto selectSnapshotBefore(String rootComponentUuid, long date, DbSession dbSession) { return mapper(dbSession).selectSnapshotBefore(rootComponentUuid, date).stream().findFirst().orElse(null); } private static SnapshotMapper mapper(DbSession session) { return session.getMapper(SnapshotMapper.class); } static class ProjectUuidFromDatePair implements Comparable<ProjectUuidFromDatePair> { private final String projectUuid; private final long from; ProjectUuidFromDatePair(String projectUuid, long from) { this.projectUuid = requireNonNull(projectUuid); this.from = from; } @Override public int compareTo(ProjectUuidFromDatePair other) { if (this == other) { return 0; } int c = projectUuid.compareTo(other.projectUuid); if (c == 0) { c = Long.compare(from, other.from); } return c; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ProjectUuidFromDatePair other = (ProjectUuidFromDatePair) o; return projectUuid.equals(other.projectUuid) && from == other.from; } @Override public int hashCode() { return Objects.hash(projectUuid, from); } } }
7,275
36.505155
152
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/component/SnapshotDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.component; import java.util.Objects; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkArgument; import static org.apache.commons.lang.StringUtils.trimToNull; public final class SnapshotDto { /** * This status is set on the snapshot at the beginning of the batch */ public static final String STATUS_UNPROCESSED = "U"; public static final String STATUS_PROCESSED = "P"; public static final String STATUS_LIVE_MEASURE_COMPUTED = "L"; public static final int MAX_VERSION_LENGTH = 100; public static final int MAX_BUILD_STRING_LENGTH = 100; private String uuid; private String rootComponentUuid; private Long createdAt; private Long buildDate; private String status = STATUS_UNPROCESSED; private Boolean last; // maps to "version" column in the table private String projectVersion; private String buildString; private String periodMode; private String periodParam; private Long periodDate; /** * SCM revision is provided by scanner and is optional. */ @Nullable private String revision; public SnapshotDto setUuid(String s) { this.uuid = s; return this; } public String getUuid() { return this.uuid; } public Long getBuildDate() { return buildDate; } public SnapshotDto setBuildDate(Long buildDate) { this.buildDate = buildDate; return this; } public String getRootComponentUuid() { return rootComponentUuid; } public SnapshotDto setRootComponentUuid(String rootComponentUuid) { this.rootComponentUuid = rootComponentUuid; return this; } public String getStatus() { return status; } public SnapshotDto setStatus(String status) { this.status = status; return this; } public Boolean getLast() { return last; } public SnapshotDto setLast(Boolean last) { this.last = last; return this; } private static void checkLength(int maxLength, @Nullable String s, String label) { if (s != null) { checkArgument(s.length() <= maxLength, "%s length (%s) is longer than the maximum authorized (%s). '%s' was provided.", label, s.length(), maxLength, s); } } public SnapshotDto setProjectVersion(@Nullable String projectVersion) { checkLength(MAX_VERSION_LENGTH, projectVersion, "projectVersion"); this.projectVersion = projectVersion; return this; } @CheckForNull public String getProjectVersion() { return projectVersion; } /** * Used by MyBatis */ private void setRawProjectVersion(@Nullable String projectVersion) { this.projectVersion = trimToNull(projectVersion); } @CheckForNull public String getBuildString() { return buildString; } public SnapshotDto setBuildString(@Nullable String buildString) { checkLength(MAX_BUILD_STRING_LENGTH, buildString, "buildString"); this.buildString = buildString; return this; } /** * Used by MyBatis */ private void setRawBuildString(@Nullable String buildString) { this.buildString = trimToNull(buildString); } public SnapshotDto setPeriodMode(@Nullable String p) { periodMode = p; return this; } @CheckForNull public String getPeriodMode() { return periodMode; } public SnapshotDto setPeriodParam(@Nullable String p) { periodParam = p; return this; } @CheckForNull public String getPeriodModeParameter() { return periodParam; } public SnapshotDto setPeriodDate(@Nullable Long date) { periodDate = date; return this; } @CheckForNull public Long getPeriodDate() { return periodDate; } public SnapshotDto setCreatedAt(Long createdAt) { this.createdAt = createdAt; return this; } /** * @return analysis date */ public Long getCreatedAt() { return createdAt; } @Nullable public String getRevision() { return revision; } public SnapshotDto setRevision(@Nullable String revision) { checkLength(100, revision, "revision"); this.revision = revision; return this; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SnapshotDto that = (SnapshotDto) o; return Objects.equals(uuid, that.uuid) && Objects.equals(rootComponentUuid, that.rootComponentUuid) && Objects.equals(createdAt, that.createdAt) && Objects.equals(buildDate, that.buildDate) && Objects.equals(status, that.status) && Objects.equals(last, that.last) && Objects.equals(projectVersion, that.projectVersion) && Objects.equals(buildString, that.buildString) && Objects.equals(periodMode, that.periodMode) && Objects.equals(periodParam, that.periodParam) && Objects.equals(periodDate, that.periodDate); } @Override public int hashCode() { return Objects.hash(uuid, rootComponentUuid, createdAt, buildDate, status, last, projectVersion, buildString, periodMode, periodParam, periodDate); } @Override public String toString() { return "SnapshotDto{" + "uuid='" + uuid + '\'' + ", componentUuid='" + rootComponentUuid + '\'' + ", createdAt=" + createdAt + ", buildDate=" + buildDate + ", status='" + status + '\'' + ", last=" + last + ", projectVersion='" + projectVersion + '\'' + ", buildString='" + buildString + '\'' + ", periodMode='" + periodMode + '\'' + ", periodParam='" + periodParam + '\'' + ", periodDate=" + periodDate + '}'; } }
6,460
25.479508
151
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/component/SnapshotMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.component; import java.util.Collection; import java.util.List; import javax.annotation.CheckForNull; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.session.RowBounds; import org.sonar.db.component.SnapshotDao.ProjectUuidFromDatePair; public interface SnapshotMapper { List<SnapshotDto> selectByUuids(@Param("uuids") List<String> uuids); void insert(SnapshotDto snapshot); @CheckForNull SnapshotDto selectLastSnapshotByComponentUuid(@Param("componentUuid") String componentUuid); @CheckForNull SnapshotDto selectLastSnapshotByRootComponentUuid(@Param("rootComponentUuid") String rootComponentUuid); List<SnapshotDto> selectLastSnapshotsByRootComponentUuids(@Param("rootComponentUuids") Collection<String> rootComponentUuids); List<SnapshotDto> selectSnapshotsByQuery(@Param("query") SnapshotQuery query); List<SnapshotDto> selectOldestSnapshots(@Param("rootComponentUuid") String rootComponentUuid, @Param("status") String status, RowBounds rowBounds); List<ViewsSnapshotDto> selectSnapshotBefore(@Param("rootComponentUuid") String rootComponentUuid, @Param("date") long date); void unsetIsLastFlagForRootComponentUuid(@Param("rootComponentUuid") String rootComponentUuid); void setIsLastFlagForAnalysisUuid(@Param("analysisUuid") String analysisUuid); void update(SnapshotDto analysis); List<SnapshotDto> selectFinishedByProjectUuidsAndFromDates(@Param("projectUuidFromDatePairs") List<ProjectUuidFromDatePair> pairs); @CheckForNull Long selectLastAnalysisDateByProject(String projectUuid); List<ProjectLastAnalysisDateDto> selectLastAnalysisDateByProjectUuids(@Param("projectUuids") Collection<String> projectUuids); }
2,556
40.241935
149
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/component/SnapshotQuery.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.component; import java.util.List; import javax.annotation.CheckForNull; import javax.annotation.Nullable; public final class SnapshotQuery { public enum SORT_FIELD { BY_DATE("created_at"); final String fieldName; SORT_FIELD(String fieldName) { this.fieldName = fieldName; } } public enum SORT_ORDER { ASC("asc"), DESC("desc"); final String order; SORT_ORDER(String order) { this.order = order; } } private String rootComponentUuid; private Long createdAfter; private Long createdBefore; private List<String> statuses; private String projectVersion; private Boolean isLast; private String sortField; private String sortOrder; /** * filter to return snapshots created at or after a given date */ @CheckForNull public Long getCreatedAfter() { return createdAfter; } public SnapshotQuery setCreatedAfter(@Nullable Long createdAfter) { this.createdAfter = createdAfter; return this; } /** * filter to return snapshots created before a given date */ @CheckForNull public Long getCreatedBefore() { return createdBefore; } public SnapshotQuery setCreatedBefore(@Nullable Long createdBefore) { this.createdBefore = createdBefore; return this; } @CheckForNull public Boolean getIsLast() { return isLast; } public SnapshotQuery setIsLast(@Nullable Boolean isLast) { this.isLast = isLast; return this; } @CheckForNull public String getRootComponentUuid() { return rootComponentUuid; } public SnapshotQuery setRootComponentUuid(@Nullable String rootComponentUuid) { this.rootComponentUuid = rootComponentUuid; return this; } @CheckForNull public List<String> getStatus() { return statuses; } public SnapshotQuery setStatus(@Nullable String status) { this.statuses = List.of(status); return this; } public SnapshotQuery setStatuses(@Nullable List<String> statuses) { this.statuses = statuses; return this; } @CheckForNull public String getProjectVersion() { return projectVersion; } public SnapshotQuery setProjectVersion(@Nullable String projectVersion) { this.projectVersion = projectVersion; return this; } public SnapshotQuery setSort(SORT_FIELD sortField, SORT_ORDER sortOrder) { this.sortField = sortField.fieldName; this.sortOrder = sortOrder.order; return this; } @CheckForNull public String getSortField() { return sortField; } @CheckForNull public String getSortOrder() { return sortOrder; } }
3,441
23.239437
81
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/component/UuidWithBranchUuidDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.component; public class UuidWithBranchUuidDto { private String uuid; private String branchUuid; /** * branchUuid column in the components table for this component. * It can be the UUID of a project or app branch, or the UUID of a portfolio. */ public String getBranchUuid() { return branchUuid; } public UuidWithBranchUuidDto setBranchUuid(String branchUuid) { this.branchUuid = branchUuid; return this; } public String getUuid() { return uuid; } public UuidWithBranchUuidDto setUuid(String uuid) { this.uuid = uuid; return this; } }
1,458
29.395833
79
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/component/ViewsSnapshotDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.component; import javax.annotation.CheckForNull; import javax.annotation.Nullable; public class ViewsSnapshotDto { private String uuid; private Long createdAt; private Long leakDate; public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public Long getCreatedAt() { return createdAt; } public void setCreatedAt(Long createdAt) { this.createdAt = createdAt; } @CheckForNull public Long getLeakDate() { return leakDate; } public ViewsSnapshotDto setLeakDate(@Nullable Long leakDate) { this.leakDate = leakDate; return this; } }
1,500
25.803571
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/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.db.component; import javax.annotation.ParametersAreNonnullByDefault;
963
37.56
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/duplication/DuplicationDao.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.duplication; import java.util.Collection; import java.util.List; import javax.annotation.Nullable; import org.sonar.core.util.UuidFactory; import org.sonar.db.Dao; import org.sonar.db.DbSession; import static org.sonar.db.DatabaseUtils.executeLargeInputs; public class DuplicationDao implements Dao { private final UuidFactory uuidFactory; public DuplicationDao(UuidFactory uuidFactory) { this.uuidFactory = uuidFactory; } /** * @param analysisUuid snapshot id of the project from the previous analysis (islast=true) */ public List<DuplicationUnitDto> selectCandidates(DbSession session, @Nullable String analysisUuid, String language, Collection<String> hashes) { return executeLargeInputs( hashes, partition -> session.getMapper(DuplicationMapper.class).selectCandidates(analysisUuid, language, partition)); } /** * Insert rows in the table DUPLICATIONS_INDEX. * Note that generated ids are not returned. */ public void insert(DbSession session, DuplicationUnitDto dto) { dto.setUuid(uuidFactory.create()); session.getMapper(DuplicationMapper.class).batchInsert(dto); } public List<DuplicationUnitDto> selectComponent(DbSession session, String componentUuid, String analysisUuid) { return session.getMapper(DuplicationMapper.class).selectComponent(componentUuid, analysisUuid); } }
2,226
34.919355
146
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/duplication/DuplicationMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.duplication; import java.util.Collection; import java.util.List; import javax.annotation.Nullable; import org.apache.ibatis.annotations.Param; public interface DuplicationMapper { List<DuplicationUnitDto> selectCandidates( @Nullable @Param("analysisUuid") String analysisUuid, @Param("language") String language, @Param("hashes") Collection<String> hashes); void batchInsert(DuplicationUnitDto unit); List<DuplicationUnitDto> selectComponent(@Param("componentUuid") String componentUuid, @Param("analysisUuid") String analysisUuid); }
1,422
36.447368
133
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/duplication/DuplicationUnitDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.duplication; public final class DuplicationUnitDto { private String uuid; private String analysisUuid; private String componentUuid; private String hash; private int indexInFile; private int startLine; private int endLine; // Return by join private String componentKey; public String getUuid() { return uuid; } public DuplicationUnitDto setUuid(String uuid) { this.uuid = uuid; return this; } public String getAnalysisUuid() { return analysisUuid; } public DuplicationUnitDto setAnalysisUuid(String analysisUuid) { this.analysisUuid = analysisUuid; return this; } public String getComponentUuid() { return componentUuid; } public DuplicationUnitDto setComponentUuid(String componentUuid) { this.componentUuid = componentUuid; return this; } public String getHash() { return hash; } public DuplicationUnitDto setHash(String hash) { this.hash = hash; return this; } public int getIndexInFile() { return indexInFile; } public DuplicationUnitDto setIndexInFile(int indexInFile) { this.indexInFile = indexInFile; return this; } public int getStartLine() { return startLine; } public DuplicationUnitDto setStartLine(int startLine) { this.startLine = startLine; return this; } public int getEndLine() { return endLine; } public DuplicationUnitDto setEndLine(int endLine) { this.endLine = endLine; return this; } public String getComponentKey() { return componentKey; } }
2,414
22.221154
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/duplication/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.db.duplication; import javax.annotation.ParametersAreNonnullByDefault;
965
37.64
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/entity/EntityDao.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.entity; import java.util.Collection; import java.util.List; import java.util.Optional; import org.apache.ibatis.session.ResultHandler; import org.sonar.db.Dao; import org.sonar.db.DbSession; import static java.util.Collections.emptyList; import static org.sonar.db.DatabaseUtils.executeLargeInputs; public class EntityDao implements Dao { public Optional<EntityDto> selectByUuid(DbSession dbSession, String uuid) { return Optional.ofNullable(mapper(dbSession).selectByUuid(uuid)); } public List<EntityDto> selectByUuids(DbSession dbSession, Collection<String> uuids) { if (uuids.isEmpty()) { return emptyList(); } return executeLargeInputs(uuids, partition -> mapper(dbSession).selectByUuids(partition)); } public Optional<EntityDto> selectByKey(DbSession dbSession, String key) { return Optional.ofNullable(mapper(dbSession).selectByKey(key)); } public List<EntityDto> selectByKeys(DbSession dbSession, Collection<String> keys) { if (keys.isEmpty()) { return emptyList(); } return executeLargeInputs(keys, partition -> mapper(dbSession).selectByKeys(partition)); } public Optional<EntityDto> selectByComponentUuid(DbSession dbSession, String componentUuid) { return Optional.ofNullable(mapper(dbSession).selectByComponentUuid(componentUuid)); } public void scrollForIndexing(DbSession session, ResultHandler<EntityDto> handler) { mapper(session).scrollForIndexing(handler); } private static EntityMapper mapper(DbSession session) { return session.getMapper(EntityMapper.class); } }
2,442
34.405797
95
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/entity/EntityDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.entity; import java.util.Objects; import javax.annotation.CheckForNull; import org.sonar.api.resources.Qualifiers; /** * Represents a project, an application, a portfolio or a sub-portfolio. * Entities are stored either in the projects or portfolios tables. */ public class EntityDto { protected String kee; protected String uuid; protected String name; protected String qualifier; protected String description; protected boolean isPrivate; // This field should be null for anything that is not subportfolio protected String authUuid; public String getAuthUuid() { if (Qualifiers.SUBVIEW.equals(qualifier)) { return authUuid; } return uuid; } public String getKey() { return kee; } public String getKee() { return kee; } public String getUuid() { return uuid; } /** * Can be TRK, APP, VW or SVW */ public String getQualifier() { return qualifier; } public String getName() { return name; } @CheckForNull public String getDescription() { return description; } public boolean isPrivate() { return isPrivate; } public boolean isPortfolio() { return Qualifiers.VIEW.equals(qualifier) || Qualifiers.SUBVIEW.equals(qualifier); } public boolean isProjectOrApp() { return Qualifiers.APP.equals(qualifier) || Qualifiers.PROJECT.equals(qualifier); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof EntityDto entityDto)) { return false; } return Objects.equals(uuid, entityDto.uuid); } @Override public int hashCode() { return Objects.hash(uuid); } }
2,538
23.180952
85
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/entity/EntityMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.entity; import java.util.Collection; import java.util.List; import javax.annotation.CheckForNull; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.session.ResultHandler; public interface EntityMapper { @CheckForNull EntityDto selectByUuid(String uuid); List<EntityDto> selectByUuids(@Param("uuids") Collection<String> uuids); @CheckForNull EntityDto selectByKey(String key); @CheckForNull EntityDto selectByComponentUuid(String componentUuid); List<EntityDto> selectByKeys(@Param("keys") Collection<String> keys); void scrollForIndexing(ResultHandler<EntityDto> handler); }
1,483
32.727273
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/entity/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.db.entity; import javax.annotation.ParametersAreNonnullByDefault;
960
37.44
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/es/EsQueueDao.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.es; import java.util.Collection; import java.util.List; import java.util.Objects; import org.sonar.api.utils.System2; import org.sonar.core.util.UuidFactory; import org.sonar.db.Dao; import org.sonar.db.DbSession; import static java.util.Collections.singletonList; import static org.sonar.db.DatabaseUtils.executeLargeUpdates; public class EsQueueDao implements Dao { private final System2 system2; private final UuidFactory uuidFactory; public EsQueueDao(System2 system2, UuidFactory uuidFactory) { this.system2 = system2; this.uuidFactory = uuidFactory; } public EsQueueDto insert(DbSession dbSession, EsQueueDto item) { insert(dbSession, singletonList(item)); return item; } public Collection<EsQueueDto> insert(DbSession dbSession, Collection<EsQueueDto> items) { long now = system2.now(); EsQueueMapper mapper = mapper(dbSession); items.forEach(item -> { item.setUuid(uuidFactory.create()); mapper.insert(item, now); }); return items; } public void delete(DbSession dbSession, EsQueueDto item) { delete(dbSession, singletonList(item)); } public void delete(DbSession dbSession, Collection<EsQueueDto> items) { EsQueueMapper mapper = mapper(dbSession); List<String> uuids = items.stream() .map(EsQueueDto::getUuid) .filter(Objects::nonNull) .toList(); executeLargeUpdates(uuids, mapper::delete); } public Collection<EsQueueDto> selectForRecovery(DbSession dbSession, long beforeDate, long limit) { return mapper(dbSession).selectForRecovery(beforeDate, limit); } private static EsQueueMapper mapper(DbSession dbSession) { return dbSession.getMapper(EsQueueMapper.class); } }
2,576
31.620253
101
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/es/EsQueueDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.es; import javax.annotation.CheckForNull; import javax.annotation.Nullable; public final class EsQueueDto { private String uuid; private String docType; private String docId; private String docIdType; private String docRouting; public String getUuid() { return uuid; } EsQueueDto setUuid(String uuid) { this.uuid = uuid; return this; } public String getDocType() { return docType; } private EsQueueDto setDocType(String t) { this.docType = t; return this; } public String getDocId() { return docId; } private EsQueueDto setDocId(String s) { this.docId = s; return this; } @CheckForNull public String getDocIdType() { return docIdType; } private EsQueueDto setDocIdType(@Nullable String s) { this.docIdType = s; return this; } @CheckForNull public String getDocRouting() { return docRouting; } private EsQueueDto setDocRouting(@Nullable String s) { this.docRouting = s; return this; } @Override public String toString() { StringBuilder sb = new StringBuilder("EsQueueDto{"); sb.append("uuid='").append(uuid).append('\''); sb.append(", docType=").append(docType); sb.append(", docId='").append(docId).append('\''); sb.append(", docIdType='").append(docIdType).append('\''); sb.append(", docRouting='").append(docRouting).append('\''); sb.append('}'); return sb.toString(); } public static EsQueueDto create(String docType, String docUuid) { return new EsQueueDto().setDocType(docType).setDocId(docUuid); } public static EsQueueDto create(String docType, String docId, @Nullable String docIdType, @Nullable String docRouting) { return new EsQueueDto().setDocType(docType) .setDocId(docId).setDocIdType(docIdType).setDocRouting(docRouting); } }
2,695
25.693069
122
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/es/EsQueueMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.es; import java.util.Collection; import java.util.List; import org.apache.ibatis.annotations.Param; public interface EsQueueMapper { void insert(@Param("dto") EsQueueDto dto, @Param("now") long now); void delete(@Param("uuids") List<String> uuids); Collection<EsQueueDto> selectForRecovery(@Param("beforeDate") long beforeDate, @Param("limit") long limit); }
1,234
35.323529
109
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/es/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.db.es; import javax.annotation.ParametersAreNonnullByDefault;
956
37.28
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/event/EventComponentChangeDao.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.event; import java.util.List; import org.sonar.api.utils.System2; import org.sonar.db.Dao; import org.sonar.db.DbSession; import static org.sonar.db.DatabaseUtils.executeLargeInputs; public class EventComponentChangeDao implements Dao { private final System2 system2; public EventComponentChangeDao(System2 system2) { this.system2 = system2; } public List<EventComponentChangeDto> selectByEventUuid(DbSession dbSession, String eventUuid) { return getMapper(dbSession).selectByEventUuid(eventUuid); } public List<EventComponentChangeDto> selectByAnalysisUuids(DbSession dbSession, List<String> analyses) { return executeLargeInputs(analyses, getMapper(dbSession)::selectByAnalysisUuids); } public void insert(DbSession dbSession, EventComponentChangeDto dto, EventPurgeData eventPurgeData) { getMapper(dbSession) .insert(dto, eventPurgeData, system2.now()); } private static EventComponentChangeMapper getMapper(DbSession dbSession) { return dbSession.getMapper(EventComponentChangeMapper.class); } }
1,921
34.592593
106
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/event/EventComponentChangeDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.event; import java.util.Arrays; import java.util.Optional; import javax.annotation.Nullable; public class EventComponentChangeDto { private String uuid; private String eventUuid; private ChangeCategory category; private String componentUuid; private String componentKey; private String componentName; @Nullable private String componentBranchKey; /**read-only*/ private long createdAt; public enum ChangeCategory { FAILED_QUALITY_GATE("FAILED_QG"), ADDED("ADDED"), REMOVED("REMOVED"); private final String dbValue; ChangeCategory(String dbValue) { this.dbValue = dbValue; } public static Optional<ChangeCategory> fromDbValue(String dbValue) { return Arrays.stream(values()) .filter(t -> t.dbValue.equals(dbValue)) .findAny(); } } public String getUuid() { return uuid; } public EventComponentChangeDto setUuid(String uuid) { this.uuid = uuid; return this; } public String getEventUuid() { return eventUuid; } public EventComponentChangeDto setEventUuid(String eventUuid) { this.eventUuid = eventUuid; return this; } public ChangeCategory getCategory() { return category; } public EventComponentChangeDto setCategory(ChangeCategory category) { this.category = category; return this; } /** * Used by MyBatis through reflection. */ private String getChangeCategory() { return category == null ? null : category.dbValue; } /** * Used by MyBatis through reflection. * * @throws IllegalArgumentException if not a support change category DB value */ private EventComponentChangeDto setChangeCategory(String changeCategory) { this.category = ChangeCategory.fromDbValue(changeCategory) .orElseThrow(() -> new IllegalArgumentException("Unsupported changeCategory DB value: " + changeCategory)); return this; } public String getComponentUuid() { return componentUuid; } public EventComponentChangeDto setComponentUuid(String componentUuid) { this.componentUuid = componentUuid; return this; } public String getComponentKey() { return componentKey; } public EventComponentChangeDto setComponentKey(String componentKey) { this.componentKey = componentKey; return this; } public String getComponentName() { return componentName; } public EventComponentChangeDto setComponentName(String componentName) { this.componentName = componentName; return this; } @Nullable public String getComponentBranchKey() { return componentBranchKey; } public EventComponentChangeDto setComponentBranchKey(@Nullable String componentBranchKey) { this.componentBranchKey = componentBranchKey; return this; } public long getCreatedAt() { return createdAt; } /** * Used by MyBatis through reflection. */ private void setCreatedAt(long createdAt) { this.createdAt = createdAt; } }
3,819
24.986395
113
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/event/EventComponentChangeMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.event; import java.util.List; import org.apache.ibatis.annotations.Param; public interface EventComponentChangeMapper { List<EventComponentChangeDto> selectByEventUuid(@Param("eventUuid") String eventUuid); List<EventComponentChangeDto> selectByAnalysisUuids(@Param("analysisUuids") List<String> analysisUuids); void insert(@Param("dto") EventComponentChangeDto dto, @Param("purgeData") EventPurgeData eventPurgeData, @Param("createdAt") long createdAt); }
1,331
40.625
144
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/event/EventDao.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.event; import java.util.List; import java.util.Optional; import javax.annotation.Nullable; import org.sonar.db.Dao; import org.sonar.db.DbSession; import static org.sonar.db.DatabaseUtils.executeLargeInputs; public class EventDao implements Dao { public Optional<EventDto> selectByUuid(DbSession dbSession, String uuid) { return Optional.ofNullable(mapper(dbSession).selectByUuid(uuid)); } public List<EventDto> selectByComponentUuid(DbSession session, String componentUuid) { return session.getMapper(EventMapper.class).selectByComponentUuid(componentUuid); } public List<EventDto> selectByAnalysisUuid(DbSession dbSession, String uuid) { return mapper(dbSession).selectByAnalysisUuid(uuid); } public List<EventDto> selectByAnalysisUuids(DbSession dbSession, List<String> analyses) { return executeLargeInputs(analyses, mapper(dbSession)::selectByAnalysisUuids); } public List<EventDto> selectVersionsByMostRecentFirst(DbSession session, String componentUuid) { return mapper(session).selectVersions(componentUuid); } public EventDto insert(DbSession session, EventDto dto) { mapper(session).insert(dto); return dto; } public void update(DbSession dbSession, String uuid, @Nullable String name, @Nullable String description) { mapper(dbSession).update(uuid, name, description); } public void delete(DbSession session, String uuid) { mapper(session).deleteByUuid(uuid); } private static EventMapper mapper(DbSession session) { return session.getMapper(EventMapper.class); } }
2,429
33.714286
109
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/event/EventDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.event; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import static org.sonar.db.event.EventValidator.checkEventCategory; import static org.sonar.db.event.EventValidator.checkEventDescription; import static org.sonar.db.event.EventValidator.checkEventName; public class EventDto { public static final String CATEGORY_VERSION = "Version"; public static final String CATEGORY_ALERT = "Alert"; public static final String CATEGORY_PROFILE = "Profile"; public static final String CATEGORY_DEFINITION_CHANGE = "Definition change"; private String uuid; private String analysisUuid; private String componentUuid; private String name; private String description; private String category; private Long date; private Long createdAt; private String data; public String getUuid() { return uuid; } public EventDto setUuid(String uuid) { this.uuid = uuid; return this; } public String getAnalysisUuid() { return analysisUuid; } public EventDto setAnalysisUuid(String analysisUuid) { this.analysisUuid = analysisUuid; return this; } public String getComponentUuid() { return componentUuid; } public EventDto setComponentUuid(String componentUuid) { this.componentUuid = componentUuid; return this; } @CheckForNull public String getName() { return name; } /** * The name of an event should not be null, but we must accept null values as the DB column is not nullable */ public EventDto setName(@Nullable String name) { this.name = checkEventName(name); return this; } @CheckForNull public String getCategory() { return category; } /** * The category of an event should not be null, but we must accept null values as the DB column is not nullable */ public EventDto setCategory(@Nullable String category) { this.category = checkEventCategory(category); return this; } public Long getCreatedAt() { return createdAt; } public EventDto setCreatedAt(Long createdAt) { this.createdAt = createdAt; return this; } @CheckForNull public String getData() { return data; } public EventDto setData(@Nullable String data) { this.data = data; return this; } public Long getDate() { return date; } public EventDto setDate(Long date) { this.date = date; return this; } @CheckForNull public String getDescription() { return description; } public EventDto setDescription(@Nullable String description) { this.description = checkEventDescription(description); return this; } }
3,482
24.23913
113
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/event/EventMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.event; import java.util.List; import javax.annotation.Nullable; import org.apache.ibatis.annotations.Param; public interface EventMapper { EventDto selectByUuid(String uuid); List<EventDto> selectByComponentUuid(String componentUuid); List<EventDto> selectByAnalysisUuid(String analysisUuid); List<EventDto> selectByAnalysisUuids(@Param("analysisUuids") List<String> list); List<EventDto> selectVersions(@Param("componentUuid") String componentUuid); void insert(EventDto dto); void update(@Param("uuid") String uuid, @Param("name") @Nullable String name, @Param("description") @Nullable String description); void deleteByUuid(String uuid); }
1,533
33.863636
132
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/event/EventPurgeData.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.event; import static java.util.Objects.requireNonNull; public record EventPurgeData(String componentUuid, String analysisUuid) { public EventPurgeData(String componentUuid, String analysisUuid) { this.componentUuid = requireNonNull(componentUuid); this.analysisUuid = requireNonNull(analysisUuid); } }
1,180
38.366667
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/event/EventValidator.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.event; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkArgument; public class EventValidator { public static final int MAX_NAME_LENGTH = 400; private static final int MAX_CATEGORY_LENGTH = 50; private static final int MAX_DESCRIPTION_LENGTH = 4000; private EventValidator() { // prevent instantiation } @CheckForNull static String checkEventName(@Nullable String name) { if (name == null) { return null; } checkArgument(name.length() <= MAX_NAME_LENGTH, "Event name length (%s) is longer than the maximum authorized (%s). '%s' was provided.", name.length(), MAX_NAME_LENGTH, name); return name; } @CheckForNull static String checkEventCategory(@Nullable String category) { if (category == null) { return null; } checkArgument(category.length() <= MAX_CATEGORY_LENGTH, "Event category length (%s) is longer than the maximum authorized (%s). '%s' was provided.", category.length(), MAX_CATEGORY_LENGTH, category); return category; } @CheckForNull static String checkEventDescription(@Nullable String description) { if (description == null) { return null; } checkArgument(description.length() <= MAX_DESCRIPTION_LENGTH, "Event description length (%s) is longer than the maximum authorized (%s). '%s' was provided.", description.length(), MAX_DESCRIPTION_LENGTH, description); return description; } }
2,364
34.833333
161
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/event/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.db.event; import javax.annotation.ParametersAreNonnullByDefault;
959
37.4
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/issue/HotspotGroupDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.issue; public class HotspotGroupDto { private String status; private long count; private boolean inLeak; public String getStatus() { return status; } public HotspotGroupDto setStatus(String status) { this.status = status; return this; } public long getCount() { return count; } public HotspotGroupDto setCount(long count) { this.count = count; return this; } public boolean isInLeak() { return inLeak; } public HotspotGroupDto setInLeak(boolean inLeak) { this.inLeak = inLeak; return this; } }
1,431
25.518519
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/issue/IssueChangeDao.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.issue; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.Set; import org.apache.ibatis.session.ResultHandler; import org.sonar.core.issue.FieldDiffs; import org.sonar.db.Dao; import org.sonar.db.DbSession; import static java.util.Collections.singletonList; import static org.sonar.db.DatabaseUtils.executeLargeInputs; import static org.sonar.db.DatabaseUtils.executeLargeInputsWithoutOutput; import static org.sonar.db.DatabaseUtils.executeLargeUpdates; public class IssueChangeDao implements Dao { public List<FieldDiffs> selectChangelogByIssue(DbSession session, String issueKey) { return selectByTypeAndIssueKeys(session, singletonList(issueKey), IssueChangeDto.TYPE_FIELD_CHANGE) .stream() .map(IssueChangeDto::toFieldDiffs) .toList(); } public List<IssueChangeDto> selectByTypeAndIssueKeys(DbSession session, Collection<String> issueKeys, String changeType) { return executeLargeInputs(issueKeys, issueKeys1 -> mapper(session).selectByIssuesAndType(issueKeys1, changeType)); } public List<IssueChangeDto> selectByIssueKeys(DbSession session, Collection<String> issueKeys) { return executeLargeInputs(issueKeys, issueKeys1 -> mapper(session).selectByIssues(issueKeys1)); } public Optional<IssueChangeDto> selectCommentByKey(DbSession session, String commentKey) { return Optional.ofNullable(mapper(session).selectByKeyAndType(commentKey, IssueChangeDto.TYPE_COMMENT)); } public void scrollDiffChangesOfIssues(DbSession dbSession, Collection<String> issueKeys, ResultHandler<IssueChangeDto> handler) { if (issueKeys.isEmpty()) { return; } executeLargeInputsWithoutOutput(issueKeys, issueKeySubList -> mapper(dbSession).scrollDiffChangesOfIssues(issueKeySubList, handler)); } public void insert(DbSession session, IssueChangeDto change) { mapper(session).insert(change); } public boolean deleteByKey(DbSession session, String key) { IssueChangeMapper mapper = mapper(session); int count = mapper.delete(key); session.commit(); return count == 1; } public void deleteByUuids(DbSession session, Set<String> uuids) { IssueChangeMapper mapper = mapper(session); executeLargeUpdates(uuids, mapper::deleteByUuids); } public boolean update(DbSession dbSession, IssueChangeDto change) { int count = mapper(dbSession).update(change); return count == 1; } private static IssueChangeMapper mapper(DbSession session) { return session.getMapper(IssueChangeMapper.class); } }
3,420
37.011111
137
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/issue/IssueChangeDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.issue; import java.io.Serializable; import java.util.Date; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import org.sonar.api.utils.System2; import org.sonar.core.issue.DefaultIssueComment; import org.sonar.core.issue.FieldDiffs; import static com.google.common.base.Preconditions.checkNotNull; import static java.util.Objects.requireNonNull; /** * @since 3.6 */ public final class IssueChangeDto implements Serializable { public static final String TYPE_FIELD_CHANGE = "diff"; public static final String TYPE_COMMENT = "comment"; private String uuid; private String kee; private String issueKey; private String projectUuid; /** * The column USER_LOGIN hasn't been renamed to USER_UUID because we don't know yet the cost of renaming a column on a table that can contain huge number of data */ private String userUuid; private String changeType; private String changeData; // technical dates private Long createdAt; private Long updatedAt; // functional date @Nullable private Long issueChangeCreationDate; public IssueChangeDto() { // nothing to do } public static IssueChangeDto of(DefaultIssueComment comment, String projectUuid) { IssueChangeDto dto = newDto(comment.issueKey()); dto.setKey(comment.key()); dto.setChangeType(IssueChangeDto.TYPE_COMMENT); dto.setChangeData(comment.markdownText()); dto.setUserUuid(comment.userUuid()); Date createdAt = requireNonNull(comment.createdAt(), "Comment created at must not be null"); dto.setIssueChangeCreationDate(createdAt.getTime()); dto.setProjectUuid(projectUuid); return dto; } public static IssueChangeDto of(String issueKey, FieldDiffs diffs, String projectUuid) { IssueChangeDto dto = newDto(issueKey); dto.setChangeType(IssueChangeDto.TYPE_FIELD_CHANGE); dto.setChangeData(diffs.toEncodedString()); dto.setUserUuid(diffs.userUuid().orElse(null)); Date createdAt = requireNonNull(diffs.creationDate(), "Diffs created at must not be null"); dto.setIssueChangeCreationDate(createdAt.getTime()); dto.setProjectUuid(projectUuid); return dto; } private static IssueChangeDto newDto(String issueKey) { IssueChangeDto dto = new IssueChangeDto(); dto.setIssueKey(issueKey); // technical dates - do not use the context date dto.setCreatedAt(System2.INSTANCE.now()); dto.setUpdatedAt(System2.INSTANCE.now()); return dto; } public String getUuid() { return uuid; } public IssueChangeDto setUuid(String uuid) { this.uuid = uuid; return this; } @CheckForNull public String getKey() { return kee; } public IssueChangeDto setKey(@Nullable String key) { this.kee = key; return this; } public String getIssueKey() { return issueKey; } public IssueChangeDto setIssueKey(String s) { this.issueKey = s; return this; } @CheckForNull public String getUserUuid() { return userUuid; } public IssueChangeDto setUserUuid(@Nullable String userUuid) { this.userUuid = userUuid; return this; } public String getChangeType() { return changeType; } public IssueChangeDto setChangeType(String changeType) { this.changeType = changeType; return this; } public String getChangeData() { return changeData; } public IssueChangeDto setChangeData(String changeData) { this.changeData = changeData; return this; } public Long getCreatedAt() { return createdAt; } public IssueChangeDto setCreatedAt(Long createdAt) { this.createdAt = checkNotNull(createdAt); return this; } public Long getUpdatedAt() { return updatedAt; } public IssueChangeDto setUpdatedAt(@Nullable Long updatedAt) { this.updatedAt = updatedAt; return this; } public Long getIssueChangeCreationDate() { // Old comments do not have functional creation date as this column has been added later return issueChangeCreationDate == null ? createdAt : issueChangeCreationDate; } public IssueChangeDto setIssueChangeCreationDate(long issueChangeCreationDate) { this.issueChangeCreationDate = issueChangeCreationDate; return this; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); } public DefaultIssueComment toComment() { return new DefaultIssueComment() .setMarkdownText(changeData) .setKey(kee) .setCreatedAt(new Date(getIssueChangeCreationDate())) .setUpdatedAt(updatedAt == null ? null : new Date(updatedAt)) .setUserUuid(userUuid) .setIssueKey(issueKey) .setNew(false); } public FieldDiffs toFieldDiffs() { return FieldDiffs.parse(changeData) .setUserUuid(userUuid) .setCreationDate(new Date(getIssueChangeCreationDate())) .setIssueKey(issueKey); } public String getProjectUuid() { return projectUuid; } public IssueChangeDto setProjectUuid(String projectUuid) { this.projectUuid = projectUuid; return this; } }
6,050
26.884793
163
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/issue/IssueChangeMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.issue; import java.util.Collection; import java.util.List; import javax.annotation.CheckForNull; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.session.ResultHandler; public interface IssueChangeMapper { void insert(IssueChangeDto dto); int delete(String key); void deleteByUuids(@Param("changeUuids") Collection<String> uuids); int update(IssueChangeDto change); @CheckForNull IssueChangeDto selectByKeyAndType(@Param("key") String key, @Param("changeType") String type); /** * Issue changes by chronological date of creation */ List<IssueChangeDto> selectByIssuesAndType(@Param("issueKeys") List<String> issueKeys, @Param("changeType") String changeType); /** * Scrolls through all changes with type {@link IssueChangeDto#TYPE_FIELD_CHANGE diff}, sorted by issue key and * then change creation date. */ void scrollDiffChangesOfIssues(@Param("issueKeys") List<String> issueKeys, ResultHandler<IssueChangeDto> handler); List<IssueChangeDto> selectByIssues(@Param("issueKeys") List<String> issueKeys); }
1,936
34.87037
129
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/issue/IssueDao.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.issue; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.Set; import org.sonar.db.Dao; import org.sonar.db.DbSession; import org.sonar.db.Pagination; import org.sonar.db.RowNotFoundException; import org.sonar.db.component.ComponentDto; import static org.sonar.db.DatabaseUtils.executeLargeInputs; public class IssueDao implements Dao { public static final int DEFAULT_PAGE_SIZE = 1000; public static final int BIG_PAGE_SIZE = 1000000; public Optional<IssueDto> selectByKey(DbSession session, String key) { return Optional.ofNullable(mapper(session).selectByKey(key)); } public IssueDto selectOrFailByKey(DbSession session, String key) { Optional<IssueDto> issue = selectByKey(session, key); if (issue.isEmpty()) { throw new RowNotFoundException(String.format("Issue with key '%s' does not exist", key)); } return issue.get(); } /** * Gets a list issues by their keys. The result does NOT contain {@code null} values for issues not found, so * the size of result may be less than the number of keys. A single issue is returned * if input keys contain multiple occurrences of a key. * <p>Results may be in a different order as input keys.</p> */ public List<IssueDto> selectByKeys(DbSession session, Collection<String> keys) { return executeLargeInputs(keys, mapper(session)::selectByKeys); } public Set<String> selectIssueKeysByComponentUuid(DbSession session, String componentUuid) { return mapper(session).selectIssueKeysByComponentUuid(componentUuid); } public Set<String> selectIssueKeysByComponentUuid(DbSession session, String componentUuid, List<String> includingRepositories, List<String> excludingRepositories, List<String> languages, int page) { return mapper(session).selectIssueKeysByComponentUuidWithFilters(componentUuid, includingRepositories, excludingRepositories, languages, Pagination.forPage(page).andSize(BIG_PAGE_SIZE)); } public Set<String> selectIssueKeysByComponentUuidAndChangedSinceDate(DbSession session, String componentUuid, long changedSince, List<String> includingRepositories, List<String> excludingRepositories, List<String> languages, int page) { return mapper(session).selectIssueKeysByComponentUuidAndChangedSinceDate(componentUuid, changedSince, includingRepositories, excludingRepositories, languages, Pagination.forPage(page).andSize(BIG_PAGE_SIZE)); } public List<IssueDto> selectByComponentUuidPaginated(DbSession session, String componentUuid, int page) { return mapper(session).selectByComponentUuidPaginated(componentUuid, Pagination.forPage(page).andSize(DEFAULT_PAGE_SIZE)); } public Set<String> selectComponentUuidsOfOpenIssuesForProjectUuid(DbSession session, String projectUuid) { return mapper(session).selectComponentUuidsOfOpenIssuesForProjectUuid(projectUuid); } public List<PrIssueDto> selectOpenByComponentUuids(DbSession dbSession, Collection<String> componentUuids) { return executeLargeInputs(componentUuids, mapper(dbSession)::selectOpenByComponentUuids); } public Collection<IssueGroupDto> selectIssueGroupsByComponent(DbSession dbSession, ComponentDto component, long leakPeriodBeginningDate) { return mapper(dbSession).selectIssueGroupsByComponent(component, leakPeriodBeginningDate); } public void insert(DbSession session, IssueDto dto) { mapper(session).insert(dto); } public void insert(DbSession session, IssueDto dto, IssueDto... others) { IssueMapper mapper = mapper(session); mapper.insert(dto); for (IssueDto other : others) { mapper.insert(other); } } public void update(DbSession session, IssueDto dto) { mapper(session).update(dto); } public void insertAsNewCodeOnReferenceBranch(DbSession session, NewCodeReferenceIssueDto dto) { mapper(session).insertAsNewCodeOnReferenceBranch(dto); } public void deleteAsNewCodeOnReferenceBranch(DbSession session, String issueKey) { mapper(session).deleteAsNewCodeOnReferenceBranch(issueKey); } private static IssueMapper mapper(DbSession session) { return session.getMapper(IssueMapper.class); } public List<IssueDto> selectByBranch(DbSession dbSession, Set<String> issueKeysSnapshot, IssueQueryParams issueQueryParams) { return mapper(dbSession).selectByBranch(issueKeysSnapshot, issueQueryParams.getChangedSince()); } public List<String> selectRecentlyClosedIssues(DbSession dbSession, IssueQueryParams issueQueryParams) { return mapper(dbSession).selectRecentlyClosedIssues(issueQueryParams); } }
5,473
41.107692
140
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/issue/IssueDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.issue; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableSet; import com.google.protobuf.InvalidProtocolBufferException; import java.io.Serializable; import java.util.Collection; import java.util.Date; import java.util.Optional; import java.util.Set; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import org.sonar.api.rule.RuleKey; import org.sonar.api.rules.RuleType; import org.sonar.api.utils.Duration; import org.sonar.core.issue.DefaultIssue; import org.sonar.db.component.ComponentDto; import org.sonar.db.protobuf.DbIssues; import org.sonar.db.rule.RuleDto; import static com.google.common.base.Preconditions.checkArgument; import static org.sonar.api.utils.DateUtils.dateToLong; import static org.sonar.api.utils.DateUtils.longToDate; public final class IssueDto implements Serializable { public static final int AUTHOR_MAX_SIZE = 255; private static final char STRING_LIST_SEPARATOR = ','; private static final Joiner STRING_LIST_JOINER = Joiner.on(STRING_LIST_SEPARATOR).skipNulls(); private static final Splitter STRING_LIST_SPLITTER = Splitter.on(STRING_LIST_SEPARATOR).trimResults().omitEmptyStrings(); private int type; private String kee; private String componentUuid; private String projectUuid; private String ruleUuid; private String severity; private boolean manualSeverity; private String message; private byte[] messageFormattings; private Integer line; private Double gap; private Long effort; private String status; private String resolution; private String checksum; private String assigneeUuid; private String assigneeLogin; private String authorLogin; private String securityStandards; private byte[] locations; private long createdAt; private long updatedAt; private boolean quickFixAvailable; private boolean isNewCodeReferenceIssue; private String ruleDescriptionContextKey; // functional dates stored as Long private Long issueCreationDate; private Long issueUpdateDate; private Long issueCloseDate; /** * Temporary date used only during scan */ private Long selectedAt; // joins private String ruleKey; private String ruleRepo; private boolean isExternal; private String language; private String componentKey; private String projectKey; private String filePath; private String tags; private String codeVariants; // populate only when retrieving closed issue for issue tracking private String closedChangeData; public IssueDto() { // nothing to do } /** * On batch side, component keys and uuid are useless */ public static IssueDto toDtoForComputationInsert(DefaultIssue issue, String ruleUuid, long now) { return new IssueDto() .setKee(issue.key()) .setType(issue.type()) .setLine(issue.line()) .setLocations((DbIssues.Locations) issue.getLocations()) .setMessage(issue.message()) .setMessageFormattings((DbIssues.MessageFormattings) issue.getMessageFormattings()) .setGap(issue.gap()) .setEffort(issue.effortInMinutes()) .setResolution(issue.resolution()) .setStatus(issue.status()) .setSeverity(issue.severity()) .setManualSeverity(issue.manualSeverity()) .setChecksum(issue.checksum()) .setAssigneeUuid(issue.assignee()) .setRuleUuid(ruleUuid) .setRuleKey(issue.ruleKey().repository(), issue.ruleKey().rule()) .setExternal(issue.isFromExternalRuleEngine()) .setTags(issue.tags()) .setRuleDescriptionContextKey(issue.getRuleDescriptionContextKey().orElse(null)) .setComponentUuid(issue.componentUuid()) .setComponentKey(issue.componentKey()) .setProjectUuid(issue.projectUuid()) .setProjectKey(issue.projectKey()) .setAuthorLogin(issue.authorLogin()) .setIssueCreationDate(issue.creationDate()) .setIssueCloseDate(issue.closeDate()) .setIssueUpdateDate(issue.updateDate()) .setSelectedAt(issue.selectedAt()) .setQuickFixAvailable(issue.isQuickFixAvailable()) .setIsNewCodeReferenceIssue(issue.isNewCodeReferenceIssue()) .setCodeVariants(issue.codeVariants()) // technical dates .setCreatedAt(now) .setUpdatedAt(now); } /** * On server side, we need component keys and uuid */ public static IssueDto toDtoForServerInsert(DefaultIssue issue, ComponentDto component, ComponentDto project, String ruleUuid, long now) { return toDtoForComputationInsert(issue, ruleUuid, now) .setComponent(component) .setProject(project); } public static IssueDto toDtoForUpdate(DefaultIssue issue, long now) { // Invariant fields, like key and rule, can't be updated return new IssueDto() .setKee(issue.key()) .setType(issue.type()) .setLine(issue.line()) .setLocations((DbIssues.Locations) issue.getLocations()) .setMessage(issue.message()) .setMessageFormattings((DbIssues.MessageFormattings) issue.getMessageFormattings()) .setGap(issue.gap()) .setEffort(issue.effortInMinutes()) .setResolution(issue.resolution()) .setStatus(issue.status()) .setSeverity(issue.severity()) .setChecksum(issue.checksum()) .setManualSeverity(issue.manualSeverity()) .setAssigneeUuid(issue.assignee()) .setAuthorLogin(issue.authorLogin()) .setRuleKey(issue.ruleKey().repository(), issue.ruleKey().rule()) .setExternal(issue.isFromExternalRuleEngine()) .setTags(issue.tags()) .setRuleDescriptionContextKey(issue.getRuleDescriptionContextKey().orElse(null)) .setComponentUuid(issue.componentUuid()) .setComponentKey(issue.componentKey()) .setProjectUuid(issue.projectUuid()) .setProjectKey(issue.projectKey()) .setIssueCreationDate(issue.creationDate()) .setIssueCloseDate(issue.closeDate()) .setIssueUpdateDate(issue.updateDate()) .setSelectedAt(issue.selectedAt()) .setQuickFixAvailable(issue.isQuickFixAvailable()) .setIsNewCodeReferenceIssue(issue.isNewCodeReferenceIssue()) .setCodeVariants(issue.codeVariants()) // technical date .setUpdatedAt(now); } public String getKey() { return getKee(); } public String getKee() { return kee; } public IssueDto setKee(String s) { this.kee = s; return this; } public IssueDto setComponent(ComponentDto component) { this.componentKey = component.getKey(); this.componentUuid = component.uuid(); this.filePath = component.path(); return this; } /** * The project branch where the issue is located. * Note that the name is misleading - it should be branch. */ public IssueDto setProject(ComponentDto project) { this.projectKey = project.getKey(); this.projectUuid = project.uuid(); return this; } public String getRuleUuid() { return ruleUuid; } /** * please use setRule(RuleDto rule) */ public IssueDto setRuleUuid(String ruleUuid) { this.ruleUuid = ruleUuid; return this; } @CheckForNull public String getSeverity() { return severity; } public IssueDto setSeverity(@Nullable String s) { checkArgument(s == null || s.length() <= 10, "Value is too long for issue severity: %s", s); this.severity = s; return this; } public boolean isManualSeverity() { return manualSeverity; } public IssueDto setManualSeverity(boolean manualSeverity) { this.manualSeverity = manualSeverity; return this; } @CheckForNull public String getMessage() { return message; } public IssueDto setMessage(@Nullable String s) { checkArgument(s == null || s.length() <= 4000, "Value is too long for issue message: %s", s); this.message = s; return this; } public byte[] getMessageFormattings() { return messageFormattings; } public IssueDto setMessageFormattings(byte[] messageFormattings) { this.messageFormattings = messageFormattings; return this; } public IssueDto setMessageFormattings(@Nullable DbIssues.MessageFormattings messageFormattings) { if (messageFormattings == null) { this.messageFormattings = null; } else { this.messageFormattings = messageFormattings.toByteArray(); } return this; } @CheckForNull public DbIssues.MessageFormattings parseMessageFormattings() { if (messageFormattings != null) { try { return DbIssues.MessageFormattings.parseFrom(messageFormattings); } catch (InvalidProtocolBufferException e) { throw new IllegalStateException(String.format("Fail to read ISSUES.MESSAGE_FORMATTINGS [KEE=%s]", kee), e); } } return null; } @CheckForNull public Integer getLine() { return line; } public IssueDto setLine(@Nullable Integer i) { checkArgument(i == null || i >= 0, "Value of issue line must be positive: %d", i); this.line = i; return this; } @CheckForNull public Double getGap() { return gap; } public IssueDto setGap(@Nullable Double d) { checkArgument(d == null || d >= 0, "Value of issue gap must be positive: %d", d); this.gap = d; return this; } @CheckForNull public Long getEffort() { return effort; } public IssueDto setEffort(@Nullable Long l) { checkArgument(l == null || l >= 0, "Value of issue effort must be positive: %d", l); this.effort = l; return this; } public String getStatus() { return status; } public IssueDto setStatus(@Nullable String s) { checkArgument(s == null || s.length() <= 20, "Value is too long for issue status: %s", s); this.status = s; return this; } @CheckForNull public String getResolution() { return resolution; } public IssueDto setResolution(@Nullable String s) { checkArgument(s == null || s.length() <= 20, "Value is too long for issue resolution: %s", s); this.resolution = s; return this; } @CheckForNull public String getChecksum() { return checksum; } public IssueDto setChecksum(@Nullable String s) { checkArgument(s == null || s.length() <= 1000, "Value is too long for issue checksum: %s", s); this.checksum = s; return this; } @CheckForNull public String getAssigneeUuid() { return assigneeUuid; } public IssueDto setAssigneeUuid(@Nullable String s) { checkArgument(s == null || s.length() <= 255, "Value is too long for issue assigneeUuid: %s", s); this.assigneeUuid = s; return this; } @CheckForNull public String getAssigneeLogin() { return assigneeLogin; } public IssueDto setAssigneeLogin(@Nullable String s) { this.assigneeLogin = s; return this; } @CheckForNull public String getAuthorLogin() { return authorLogin; } public IssueDto setAuthorLogin(@Nullable String s) { checkArgument(s == null || s.length() <= AUTHOR_MAX_SIZE, "Value is too long for issue author login: %s", s); this.authorLogin = s; return this; } public IssueDto setSecurityStandards(@Nullable String s) { this.securityStandards = s; return this; } public Set<String> getSecurityStandards() { return RuleDto.deserializeSecurityStandardsString(securityStandards); } /** * Technical date */ public long getCreatedAt() { return createdAt; } public IssueDto setCreatedAt(long createdAt) { this.createdAt = createdAt; return this; } /** * Technical date */ public long getUpdatedAt() { return updatedAt; } public IssueDto setUpdatedAt(long updatedAt) { this.updatedAt = updatedAt; return this; } public Long getIssueCreationTime() { return issueCreationDate; } public IssueDto setIssueCreationTime(Long time) { this.issueCreationDate = time; return this; } public Date getIssueCreationDate() { return longToDate(issueCreationDate); } public IssueDto setIssueCreationDate(@Nullable Date d) { this.issueCreationDate = dateToLong(d); return this; } public Long getIssueUpdateTime() { return issueUpdateDate; } public IssueDto setIssueUpdateTime(Long time) { this.issueUpdateDate = time; return this; } public Date getIssueUpdateDate() { return longToDate(issueUpdateDate); } public IssueDto setIssueUpdateDate(@Nullable Date d) { this.issueUpdateDate = dateToLong(d); return this; } public Long getIssueCloseTime() { return issueCloseDate; } public IssueDto setIssueCloseTime(Long time) { this.issueCloseDate = time; return this; } public Date getIssueCloseDate() { return longToDate(issueCloseDate); } public IssueDto setIssueCloseDate(@Nullable Date d) { this.issueCloseDate = dateToLong(d); return this; } public String getRule() { return ruleKey; } public IssueDto setRule(RuleDto rule) { Preconditions.checkNotNull(rule.getUuid(), "Rule must be persisted."); this.ruleUuid = rule.getUuid(); this.ruleKey = rule.getRuleKey(); this.ruleRepo = rule.getRepositoryKey(); this.language = rule.getLanguage(); this.isExternal = rule.isExternal(); return this; } public String getRuleRepo() { return ruleRepo; } public RuleKey getRuleKey() { return RuleKey.of(ruleRepo, ruleKey); } public String getLanguage() { return language; } /** * Should only be used to persist in E/S * <p/> * Please use {@link #setRule(RuleDto)} instead */ public IssueDto setLanguage(String language) { this.language = language; return this; } public boolean isExternal() { return isExternal; } public IssueDto setExternal(boolean external) { isExternal = external; return this; } public String getComponentKey() { return componentKey; } /** * Should only be used to persist in E/S * <p/> * Please use {@link #setComponent(ComponentDto)} instead */ public IssueDto setComponentKey(String componentKey) { this.componentKey = componentKey; return this; } /** * Can be null on Views or Devs */ @CheckForNull public String getComponentUuid() { return componentUuid; } /** * Should only be used to persist in E/S * <p/> * Please use {@link #setComponent(ComponentDto)} instead */ public IssueDto setComponentUuid(@Nullable String s) { checkArgument(s == null || s.length() <= 50, "Value is too long for column ISSUES.COMPONENT_UUID: %s", s); this.componentUuid = s; return this; } /** * Used by the issue tracking mechanism, but it should used the component uuid instead */ public String getProjectKey() { return projectKey; } /** * Should only be used to persist in E/S * <p/> * Please use {@link #setProject(ComponentDto)} instead */ public IssueDto setProjectKey(String projectKey) { this.projectKey = projectKey; return this; } /** * The project branch where the issue is located. * Note that the name is misleading - it should be 'branchUuid'. */ public String getProjectUuid() { return projectUuid; } /** * Should only be used to persist in E/S * <p/> * Please use {@link #setProject(ComponentDto)} instead */ public IssueDto setProjectUuid(String s) { checkArgument(s.length() <= 50, "Value is too long for column ISSUES.PROJECT_UUID: %s", s); this.projectUuid = s; return this; } @CheckForNull public Long getSelectedAt() { return selectedAt; } public IssueDto setSelectedAt(@Nullable Long d) { this.selectedAt = d; return this; } /** * Should only be used to persist in E/S * <p/> * Please use {@link #setRule(RuleDto)} instead */ public IssueDto setRuleKey(String repo, String rule) { this.ruleRepo = repo; this.ruleKey = rule; return this; } /** * Should only be used to persist in E/S * <p/> * Please use {@link #setProject(ComponentDto)} instead */ public String getFilePath() { return filePath; } /** * Should only be used to persist in E/S * <p/> * Please use {@link #setProject(ComponentDto)} instead */ public IssueDto setFilePath(String filePath) { this.filePath = filePath; return this; } public Set<String> getTags() { return ImmutableSet.copyOf(STRING_LIST_SPLITTER.split(tags == null ? "" : tags)); } public IssueDto setTags(@Nullable Collection<String> tags) { if (tags == null || tags.isEmpty()) { setTagsString(null); } else { setTagsString(STRING_LIST_JOINER.join(tags)); } return this; } public IssueDto setTagsString(@Nullable String s) { checkArgument(s == null || s.length() <= 4000, "Value is too long for column ISSUES.TAGS: %s", s); this.tags = s; return this; } public String getTagsString() { return tags; } public Set<String> getCodeVariants() { return ImmutableSet.copyOf(STRING_LIST_SPLITTER.split(codeVariants == null ? "" : codeVariants)); } public String getCodeVariantsString() { return codeVariants; } public IssueDto setCodeVariants(@Nullable Collection<String> codeVariants) { if (codeVariants == null || codeVariants.isEmpty()) { setCodeVariantsString(null); } else { setCodeVariantsString(STRING_LIST_JOINER.join(codeVariants)); } return this; } public IssueDto setCodeVariantsString(@Nullable String codeVariants) { checkArgument(codeVariants == null || codeVariants.length() <= 4000, "Value is too long for column ISSUES.CODE_VARIANTS: %codeVariants", codeVariants); this.codeVariants = codeVariants; return this; } @CheckForNull public byte[] getLocations() { return locations; } @CheckForNull public DbIssues.Locations parseLocations() { if (locations != null) { try { return DbIssues.Locations.parseFrom(locations); } catch (InvalidProtocolBufferException e) { throw new IllegalStateException(String.format("Fail to read ISSUES.LOCATIONS [KEE=%s]", kee), e); } } return null; } public IssueDto setLocations(@Nullable byte[] locations) { this.locations = locations; return this; } public IssueDto setLocations(@Nullable DbIssues.Locations locations) { if (locations == null) { this.locations = null; } else { this.locations = locations.toByteArray(); } return this; } public boolean isQuickFixAvailable() { return quickFixAvailable; } public IssueDto setQuickFixAvailable(boolean quickFixAvailable) { this.quickFixAvailable = quickFixAvailable; return this; } public boolean isNewCodeReferenceIssue() { return isNewCodeReferenceIssue; } public IssueDto setIsNewCodeReferenceIssue(boolean isNewCodeReferenceIssue) { this.isNewCodeReferenceIssue = isNewCodeReferenceIssue; return this; } public int getType() { return type; } public IssueDto setType(int type) { this.type = type; return this; } public IssueDto setType(RuleType type) { this.type = type.getDbConstant(); return this; } public Optional<String> getClosedChangeData() { return Optional.ofNullable(closedChangeData); } public Optional<String> getOptionalRuleDescriptionContextKey() { return Optional.ofNullable(ruleDescriptionContextKey); } public IssueDto setRuleDescriptionContextKey(@Nullable String ruleDescriptionContextKey) { this.ruleDescriptionContextKey = ruleDescriptionContextKey; return this; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); } public DefaultIssue toDefaultIssue() { DefaultIssue issue = new DefaultIssue(); issue.setKey(kee); issue.setType(RuleType.valueOf(type)); issue.setStatus(status); issue.setResolution(resolution); issue.setMessage(message); issue.setMessageFormattings(parseMessageFormattings()); issue.setGap(gap); issue.setEffort(effort != null ? Duration.create(effort) : null); issue.setLine(line); issue.setChecksum(checksum); issue.setSeverity(severity); issue.setAssigneeUuid(assigneeUuid); issue.setAssigneeLogin(assigneeLogin); issue.setComponentKey(componentKey); issue.setComponentUuid(componentUuid); issue.setProjectUuid(projectUuid); issue.setProjectKey(projectKey); issue.setManualSeverity(manualSeverity); issue.setRuleKey(getRuleKey()); issue.setTags(getTags()); issue.setRuleDescriptionContextKey(ruleDescriptionContextKey); issue.setLanguage(language); issue.setAuthorLogin(authorLogin); issue.setNew(false); issue.setCreationDate(longToDate(issueCreationDate)); issue.setCloseDate(longToDate(issueCloseDate)); issue.setUpdateDate(longToDate(issueUpdateDate)); issue.setSelectedAt(selectedAt); issue.setLocations(parseLocations()); issue.setIsFromExternalRuleEngine(isExternal); issue.setQuickFixAvailable(quickFixAvailable); issue.setIsNewCodeReferenceIssue(isNewCodeReferenceIssue); issue.setCodeVariants(getCodeVariants()); return issue; } }
22,180
26.588308
140
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/issue/IssueGroupDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.issue; import javax.annotation.CheckForNull; import javax.annotation.Nullable; public class IssueGroupDto { private int ruleType; private String severity; @Nullable private String resolution; private String status; private double effort; private long count; private boolean inLeak; public int getRuleType() { return ruleType; } public String getSeverity() { return severity; } @CheckForNull public String getResolution() { return resolution; } public String getStatus() { return status; } public double getEffort() { return effort; } public long getCount() { return count; } public boolean isInLeak() { return inLeak; } public IssueGroupDto setRuleType(int ruleType) { this.ruleType = ruleType; return this; } public IssueGroupDto setSeverity(String severity) { this.severity = severity; return this; } public IssueGroupDto setResolution(@Nullable String resolution) { this.resolution = resolution; return this; } public IssueGroupDto setStatus(String status) { this.status = status; return this; } public IssueGroupDto setEffort(double effort) { this.effort = effort; return this; } public IssueGroupDto setCount(long count) { this.count = count; return this; } public IssueGroupDto setInLeak(boolean inLeak) { this.inLeak = inLeak; return this; } }
2,289
22.131313
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/issue/IssueMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.issue; import java.util.Collection; import java.util.List; import java.util.Set; import javax.annotation.Nullable; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.session.ResultHandler; import org.sonar.db.Pagination; import org.sonar.db.component.ComponentDto; public interface IssueMapper { IssueDto selectByKey(String key); Set<String> selectComponentUuidsOfOpenIssuesForProjectUuid(String projectUuid); List<IssueDto> selectByKeys(List<String> keys); Set<String> selectIssueKeysByComponentUuid(@Param("componentUuid") String componentUuid); Set<String> selectIssueKeysByComponentUuidWithFilters(@Param("componentUuid") String componentUuid, @Param("includingRepositories") List<String> includingRepositories, @Param("excludingRepositories") List<String> excludingRepositories, @Param("languages") List<String> languages, @Param("pagination") Pagination pagination); Set<String> selectIssueKeysByComponentUuidAndChangedSinceDate(@Param("componentUuid") String componentUuid, @Param("changedSince") long changedSince, @Param("includingRepositories") List<String> includingRepositories, @Param("excludingRepositories") List<String> excludingRepositories, @Param("languages") List<String> languages, @Param("pagination") Pagination pagination); List<IssueDto> selectByComponentUuidPaginated(@Param("componentUuid") String componentUuid, @Param("pagination") Pagination pagination); List<IssueDto> selectByKeysIfNotUpdatedAt(@Param("keys") List<String> keys, @Param("updatedAt") long updatedAt); List<PrIssueDto> selectOpenByComponentUuids(List<String> componentUuids); void insert(IssueDto issue); int update(IssueDto issue); void insertAsNewCodeOnReferenceBranch(NewCodeReferenceIssueDto issue); void deleteAsNewCodeOnReferenceBranch(String issueKey); int updateIfBeforeSelectedDate(IssueDto issue); void scrollNonClosedByComponentUuid(@Param("componentUuid") String componentUuid, ResultHandler<IssueDto> handler); void scrollClosedByComponentUuid(@Param("componentUuid") String componentUuid, @Param("closeDateAfter") long closeDateAfter, ResultHandler<IssueDto> handler); Collection<IssueGroupDto> selectIssueGroupsByComponent(@Param("component") ComponentDto component, @Param("leakPeriodBeginningDate") long leakPeriodBeginningDate); List<IssueDto> selectByBranch(@Param("keys") Set<String> keys, @Nullable @Param("changedSince") Long changedSince); List<String> selectRecentlyClosedIssues(@Param("queryParams") IssueQueryParams issueQueryParams); }
3,433
41.925
165
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/issue/IssueQueryParams.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.issue; import java.util.List; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import static java.util.Collections.emptyList; import static java.util.Objects.requireNonNullElse; public class IssueQueryParams { private final String branchUuid; private final List<String> languages; private final boolean resolvedOnly; private final Long changedSince; private final List<String> ruleRepositories; private final List<String> excludingRuleRepositories; public IssueQueryParams(String branchUuid, @Nullable List<String> languages, @Nullable List<String> ruleRepositories, @Nullable List<String> excludingRuleRepositories, boolean resolvedOnly, @Nullable Long changedSince) { this.branchUuid = branchUuid; this.languages = requireNonNullElse(languages, emptyList()); this.ruleRepositories = requireNonNullElse(ruleRepositories, emptyList()); this.excludingRuleRepositories = requireNonNullElse(excludingRuleRepositories, emptyList()); this.resolvedOnly = resolvedOnly; this.changedSince = changedSince; } public String getBranchUuid() { return branchUuid; } public List<String> getLanguages() { return languages; } public List<String> getRuleRepositories() { return ruleRepositories; } public List<String> getExcludingRuleRepositories() { return excludingRuleRepositories; } public boolean isResolvedOnly() { return resolvedOnly; } @CheckForNull public Long getChangedSince() { return changedSince; } }
2,389
31.739726
119
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/issue/IssueTesting.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.issue; import java.util.Date; import org.apache.commons.lang.math.RandomUtils; import org.sonar.api.issue.Issue; import org.sonar.api.resources.Qualifiers; import org.sonar.api.rule.Severity; import org.sonar.core.util.UuidFactoryFast; import org.sonar.core.util.Uuids; import org.sonar.db.component.BranchDto; import org.sonar.db.component.ComponentDto; import org.sonar.db.rule.RuleDto; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.collect.Sets.newHashSet; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.apache.commons.lang.math.RandomUtils.nextInt; import static org.apache.commons.lang.math.RandomUtils.nextLong; public class IssueTesting { private IssueTesting() { // only statics } public static IssueDto newIssue(RuleDto rule, ComponentDto branch, ComponentDto file) { checkArgument(branch.qualifier().equals(Qualifiers.PROJECT), "Second parameter should be a branch that belongs to a project"); return newIssue(rule, branch.uuid(), branch.getKey(), file); } public static IssueDto newIssue(RuleDto rule, BranchDto branch, ComponentDto file) { return newIssue(rule, branch.getUuid(), branch.getKey(), file); } public static IssueDto newIssue(RuleDto rule, String branchUuid, String projectKey, ComponentDto file) { //checkArgument(file.branchUuid().equals(branchUuid), "The file doesn't belong to the project"); return new IssueDto() .setKee("uuid_" + randomAlphabetic(5)) .setRule(rule) .setType(rule.getType()) .setProjectUuid(branchUuid) .setProjectKey(projectKey) .setComponent(file) .setStatus(Issue.STATUS_OPEN) .setResolution(null) .setSeverity(Severity.ALL.get(nextInt(Severity.ALL.size()))) .setEffort((long) RandomUtils.nextInt(10)) .setAssigneeUuid("assignee-uuid_" + randomAlphabetic(26)) .setAuthorLogin("author_" + randomAlphabetic(5)) // Adding one to the generated random value in order to never get 0 (as it's a forbidden value) .setLine(nextInt(1_000) + 1) .setMessage("message_" + randomAlphabetic(5)) .setChecksum("checksum_" + randomAlphabetic(5)) .setTags(newHashSet("tag_" + randomAlphanumeric(5), "tag_" + randomAlphanumeric(5))) .setRuleDescriptionContextKey("context_" + randomAlphabetic(5)) .setIssueCreationDate(new Date(System.currentTimeMillis() - 2_000)) .setIssueUpdateDate(new Date(System.currentTimeMillis() - 1_500)) .setCreatedAt(System.currentTimeMillis() - 1_000) .setUpdatedAt(System.currentTimeMillis() - 500); } public static IssueChangeDto newIssueChangeDto(IssueDto issue) { return new IssueChangeDto() .setUuid(UuidFactoryFast.getInstance().create()) .setKey(UuidFactoryFast.getInstance().create()) .setIssueKey(issue.getKey()) .setChangeData("data_" + randomAlphanumeric(40)) .setChangeType(IssueChangeDto.TYPE_FIELD_CHANGE) .setUserUuid("userUuid_" + randomAlphanumeric(40)) .setProjectUuid(issue.getProjectUuid()) .setIssueChangeCreationDate(nextLong()) .setCreatedAt(nextLong()) .setUpdatedAt(nextLong()); } public static NewCodeReferenceIssueDto newCodeReferenceIssue(IssueDto issue) { return new NewCodeReferenceIssueDto() .setUuid(Uuids.createFast()) .setIssueKey(issue.getKey()) .setCreatedAt(1_400_000_000_000L); } }
4,392
40.838095
130
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/issue/NewCodeReferenceIssueDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.issue; import java.io.Serializable; import org.sonar.core.util.UuidFactory; public final class NewCodeReferenceIssueDto implements Serializable { private String uuid; private String issueKey; // technical date private Long createdAt; public NewCodeReferenceIssueDto() { // nothing to do } public String getUuid() { return uuid; } public NewCodeReferenceIssueDto setUuid(String uuid) { this.uuid = uuid; return this; } public String getIssueKey() { return issueKey; } public NewCodeReferenceIssueDto setIssueKey(String issueKey) { this.issueKey = issueKey; return this; } public Long getCreatedAt() { return createdAt; } public NewCodeReferenceIssueDto setCreatedAt(Long createdAt) { this.createdAt = createdAt; return this; } public static NewCodeReferenceIssueDto fromIssueDto(IssueDto issue, long now, UuidFactory uuidFactory) { return new NewCodeReferenceIssueDto() .setUuid(uuidFactory.create()) .setIssueKey(issue.getKey()) .setCreatedAt(now); } public static NewCodeReferenceIssueDto fromIssueKey(String issueKey, long now, UuidFactory uuidFactory) { return new NewCodeReferenceIssueDto() .setUuid(uuidFactory.create()) .setIssueKey(issueKey) .setCreatedAt(now); } }
2,177
27.285714
107
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/issue/PrIssueDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.issue; import java.io.Serializable; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import org.sonar.api.rule.RuleKey; import org.sonar.db.component.BranchType; public final class PrIssueDto implements Serializable { private String kee; private String message; private Integer line; private String checksum; private String status; private Long issueUpdateDate; // joins private String ruleKey; private String ruleRepo; private String branchKey; private BranchType branchType; public String getKey() { return kee; } public PrIssueDto setKee(String s) { this.kee = s; return this; } @CheckForNull public String getMessage() { return message; } public PrIssueDto setMessage(@Nullable String s) { this.message = s; return this; } @CheckForNull public Integer getLine() { return line; } public PrIssueDto setLine(@Nullable Integer i) { this.line = i; return this; } /** * Branch name for BRANCH, PR key for PR */ public String getBranchKey() { return branchKey; } public PrIssueDto setBranchKey(String s) { this.branchKey = s; return this; } public BranchType getBranchType() { return branchType; } public PrIssueDto setBranchType(BranchType s) { this.branchType = s; return this; } public String getStatus() { return status; } public PrIssueDto setStatus(@Nullable String s) { this.status = s; return this; } @CheckForNull public String getChecksum() { return checksum; } public PrIssueDto setChecksum(@Nullable String s) { this.checksum = s; return this; } public void setRuleRepo(String ruleRepo) { this.ruleRepo = ruleRepo; } public void setRuleKey(String ruleKey) { this.ruleKey = ruleKey; } public RuleKey getRuleKey() { return RuleKey.of(ruleRepo, ruleKey); } public Long getIssueUpdateDate() { return issueUpdateDate; } public PrIssueDto setIssueUpdateDate(Long issueUpdateDate) { this.issueUpdateDate = issueUpdateDate; return this; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); } }
3,216
21.815603
86
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/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.db.issue; import javax.annotation.ParametersAreNonnullByDefault;
959
37.4
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/measure/LargestBranchNclocDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.measure; public class LargestBranchNclocDto { private String projectUuid; private String projectName; private String projectKey; private long loc; private String branchName; private String branchType; public String getProjectUuid() { return projectUuid; } public LargestBranchNclocDto setProjectUuid(String projectUuid) { this.projectUuid = projectUuid; return this; } public String getProjectName() { return projectName; } public LargestBranchNclocDto setProjectName(String projectName) { this.projectName = projectName; return this; } public String getProjectKey() { return projectKey; } public LargestBranchNclocDto setProjectKey(String projectKey) { this.projectKey = projectKey; return this; } public String getBranchName() { return branchName; } public LargestBranchNclocDto setBranchName(String branchName) { this.branchName = branchName; return this; } public String getBranchType() { return branchType; } public LargestBranchNclocDto setBranchType(String branchType) { this.branchType = branchType; return this; } public long getLoc() { return loc; } public LargestBranchNclocDto setLoc(long loc) { this.loc = loc; return this; } }
2,151
24.317647
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/measure/LiveMeasureComparator.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.measure; import java.util.Comparator; public enum LiveMeasureComparator implements Comparator<LiveMeasureDto> { INSTANCE; @Override public int compare(LiveMeasureDto o1, LiveMeasureDto o2) { int componentUuidComp = o1.getComponentUuid().compareTo(o2.getComponentUuid()); if (componentUuidComp != 0) { return componentUuidComp; } return o1.getMetricUuid().compareTo(o2.getMetricUuid()); } }
1,287
34.777778
83
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/measure/LiveMeasureDao.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.measure; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Optional; import org.apache.ibatis.session.ResultHandler; import org.sonar.api.utils.System2; import org.sonar.core.util.Uuids; import org.sonar.db.Dao; import org.sonar.db.DbSession; import org.sonar.db.component.ComponentDto; import org.sonar.db.dialect.Dialect; import static org.sonar.api.measures.CoreMetrics.NCLOC_KEY; import static org.sonar.db.DatabaseUtils.executeLargeInputs; public class LiveMeasureDao implements Dao { private final System2 system2; public LiveMeasureDao(System2 system2) { this.system2 = system2; } public List<LiveMeasureDto> selectByComponentUuidsAndMetricUuids(DbSession dbSession, Collection<String> largeComponentUuids, Collection<String> metricUuids) { if (largeComponentUuids.isEmpty() || metricUuids.isEmpty()) { return Collections.emptyList(); } return executeLargeInputs( largeComponentUuids, componentUuids -> mapper(dbSession).selectByComponentUuidsAndMetricUuids(componentUuids, metricUuids)); } public List<ProjectMainBranchLiveMeasureDto> selectForProjectMainBranchesByMetricUuids(DbSession dbSession, Collection<String> metricUuids) { return mapper(dbSession).selectForProjectMainBranchesByMetricUuids(metricUuids); } public void scrollSelectByComponentUuidAndMetricKeys(DbSession dbSession, String componentUuid, Collection<String> metricKeys, ResultHandler<LiveMeasureDto> handler) { if (metricKeys.isEmpty()) { return; } mapper(dbSession).scrollSelectByComponentUuidAndMetricKeys(componentUuid, metricKeys, handler); } public List<LiveMeasureDto> selectByComponentUuidsAndMetricKeys(DbSession dbSession, Collection<String> largeComponentUuids, Collection<String> metricKeys) { if (largeComponentUuids.isEmpty() || metricKeys.isEmpty()) { return Collections.emptyList(); } return executeLargeInputs( largeComponentUuids, componentUuids -> mapper(dbSession).selectByComponentUuidsAndMetricKeys(componentUuids, metricKeys)); } public List<LiveMeasureDto> selectByComponentUuidAndMetricKeys(DbSession dbSession, String componentUuid, Collection<String> metricKeys) { if (metricKeys.isEmpty()) { return Collections.emptyList(); } return mapper(dbSession).selectByComponentUuidAndMetricKeys(componentUuid, metricKeys); } public Optional<LiveMeasureDto> selectMeasure(DbSession dbSession, String componentUuid, String metricKey) { LiveMeasureDto liveMeasureDto = mapper(dbSession).selectByComponentUuidAndMetricKey(componentUuid, metricKey); return Optional.ofNullable(liveMeasureDto); } public void selectTreeByQuery(DbSession dbSession, ComponentDto baseComponent, MeasureTreeQuery query, ResultHandler<LiveMeasureDto> resultHandler) { if (query.returnsEmpty()) { return; } mapper(dbSession).selectTreeByQuery(query, baseComponent.uuid(), query.getUuidPath(baseComponent), resultHandler); } public long sumNclocOfBiggestBranchForProject(DbSession dbSession, String projectUuid){ Long ncloc = mapper(dbSession).sumNclocOfBiggestBranchForProject(projectUuid, NCLOC_KEY); return ncloc == null ? 0L : ncloc; } public List<LargestBranchNclocDto> getLargestBranchNclocPerProject(DbSession dbSession, String nclocMetricUuid) { return mapper(dbSession).getLargestBranchNclocPerProject(nclocMetricUuid); } public List<ProjectLocDistributionDto> selectLargestBranchesLocDistribution(DbSession session, String nclocUuid, String nclocDistributionUuid) { return mapper(session).selectLargestBranchesLocDistribution(nclocUuid, nclocDistributionUuid); } public long countProjectsHavingMeasure(DbSession dbSession, String metric) { return mapper(dbSession).countProjectsHavingMeasure(metric); } public void insert(DbSession dbSession, LiveMeasureDto dto) { mapper(dbSession).insert(dto, Uuids.create(), system2.now()); } public void insertOrUpdate(DbSession dbSession, LiveMeasureDto dto) { LiveMeasureMapper mapper = mapper(dbSession); long now = system2.now(); if (mapper.update(dto, now) == 0) { mapper.insert(dto, Uuids.create(), now); } } public void deleteByComponent(DbSession dbSession, String componentUuid) { mapper(dbSession).deleteByComponent(componentUuid); } /** * Similar to {@link #insertOrUpdate(DbSession, LiveMeasureDto)}, except that it triggers a single SQL request * <strong>This method should not be called unless {@link Dialect#supportsUpsert()} is true</strong> */ public int upsert(DbSession dbSession, LiveMeasureDto dto) { dto.setUuidForUpsert(Uuids.create()); return mapper(dbSession).upsert(dto, system2.now()); } public void deleteByComponentUuidExcludingMetricUuids(DbSession dbSession, String componentUuid, List<String> excludedMetricUuids) { mapper(dbSession).deleteByComponentUuidExcludingMetricUuids(componentUuid, excludedMetricUuids); } private static LiveMeasureMapper mapper(DbSession dbSession) { return dbSession.getMapper(LiveMeasureMapper.class); } }
6,003
39.843537
169
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/measure/LiveMeasureDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.measure; import java.nio.charset.StandardCharsets; import java.util.Arrays; import javax.annotation.CheckForNull; import javax.annotation.Nullable; public class LiveMeasureDto { private static final int MAX_TEXT_VALUE_LENGTH = 4000; /** * UUID generated only for UPSERT statements in PostgreSQL. It's never used * in SELECT or regular INSERT/UPDATE. */ @Nullable private String uuidForUpsert; private String componentUuid; private String projectUuid; private String metricUuid; @Nullable private Double value; @Nullable private String textValue; @Nullable private byte[] data; void setUuidForUpsert(@Nullable String s) { this.uuidForUpsert = s; } public String getComponentUuid() { return componentUuid; } public LiveMeasureDto setComponentUuid(String s) { this.componentUuid = s; return this; } public String getProjectUuid() { return projectUuid; } public LiveMeasureDto setProjectUuid(String s) { this.projectUuid = s; return this; } public String getMetricUuid() { return metricUuid; } public LiveMeasureDto setMetricUuid(String uuid) { this.metricUuid = uuid; return this; } @CheckForNull public Double getValue() { return value; } public LiveMeasureDto setValue(@Nullable Double value) { this.value = value; return this; } @CheckForNull public String getTextValue() { return textValue; } @CheckForNull public byte[] getData() { return data; } @CheckForNull public String getDataAsString() { if (data != null) { return new String(data, StandardCharsets.UTF_8); } return textValue; } public LiveMeasureDto setData(@Nullable String data) { if (data == null) { this.textValue = null; this.data = null; } else if (data.length() > MAX_TEXT_VALUE_LENGTH) { this.textValue = null; this.data = data.getBytes(StandardCharsets.UTF_8); } else { this.textValue = data; this.data = null; } return this; } public LiveMeasureDto setData(@Nullable byte[] data) { this.textValue = null; this.data = data; return this; } @Override public String toString() { StringBuilder sb = new StringBuilder("LiveMeasureDto{"); sb.append("componentUuid='").append(componentUuid).append('\''); sb.append(", projectUuid='").append(projectUuid).append('\''); sb.append(", metricUuid=").append(metricUuid); sb.append(", value=").append(value); sb.append(", textValue='").append(textValue).append('\''); sb.append(", data=").append(Arrays.toString(data)); sb.append('}'); return sb.toString(); } }
3,538
24.278571
77
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/measure/LiveMeasureMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.measure; import java.util.Collection; import java.util.List; import javax.annotation.CheckForNull; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.session.ResultHandler; public interface LiveMeasureMapper { List<LiveMeasureDto> selectByComponentUuidsAndMetricUuids( @Param("componentUuids") Collection<String> componentUuids, @Param("metricUuids") Collection<String> metricUuids); List<ProjectMainBranchLiveMeasureDto> selectForProjectMainBranchesByMetricUuids( @Param("metricUuids") Collection<String> metricUuids); List<LiveMeasureDto> selectByComponentUuidsAndMetricKeys( @Param("componentUuids") Collection<String> componentUuids, @Param("metricKeys") Collection<String> metricKeys); List<LiveMeasureDto> selectByComponentUuidAndMetricKeys( @Param("componentUuid") String componentUuid, @Param("metricKeys") Collection<String> metricKeys); void scrollSelectByComponentUuidAndMetricKeys( @Param("componentUuid") String componentUuid, @Param("metricKeys") Collection<String> metricKeys, ResultHandler<LiveMeasureDto> handler); LiveMeasureDto selectByComponentUuidAndMetricKey( @Param("componentUuid") String componentUuid, @Param("metricKey") String metricKey); void selectTreeByQuery( @Param("query") MeasureTreeQuery measureQuery, @Param("baseUuid") String baseUuid, @Param("baseUuidPath") String baseUuidPath, ResultHandler<LiveMeasureDto> resultHandler); @CheckForNull Long sumNclocOfBiggestBranchForProject(@Param("projectUuid") String projectUuid, @Param("ncloc") String nclocKey); List<LargestBranchNclocDto> getLargestBranchNclocPerProject(@Param("nclocUuid") String nclocUuid); List<ProjectLocDistributionDto> selectLargestBranchesLocDistribution(@Param("nclocUuid") String nclocUuid, @Param("nclocDistributionUuid") String nclocDistributionUuid); Long countProjectsHavingMeasure( @Param("metric") String metric); void insert( @Param("dto") LiveMeasureDto dto, @Param("uuid") String uuid, @Param("now") long now); int update( @Param("dto") LiveMeasureDto dto, @Param("now") long now); int upsert( @Param("dto") LiveMeasureDto dto, @Param("now") long now); void deleteByComponentUuidExcludingMetricUuids( @Param("componentUuid") String componentUuid, @Param("excludedMetricUuids") List<String> excludedMetricUuids); void deleteByComponent(@Param("componentUuid") String componentUuid); }
3,340
36.122222
171
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/measure/MeasureDao.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.measure; import com.google.common.collect.Lists; import java.util.Collection; import java.util.List; import java.util.Optional; import org.sonar.core.util.UuidFactory; import org.sonar.db.Dao; import org.sonar.db.DbSession; public class MeasureDao implements Dao { private final UuidFactory uuidFactory; public MeasureDao(UuidFactory uuidFactory) { this.uuidFactory = uuidFactory; } public Optional<MeasureDto> selectLastMeasure(DbSession dbSession, String componentUuid, String metricKey) { return Optional.ofNullable(mapper(dbSession).selectLastMeasure(componentUuid, metricKey)); } public Optional<MeasureDto> selectMeasure(DbSession dbSession, String analysisUuid, String componentUuid, String metricKey) { return Optional.ofNullable(mapper(dbSession).selectMeasure(analysisUuid, componentUuid, metricKey)); } /** * Select measures of: * - one component * - for a list of metrics * - with analysis from a date (inclusive) - optional * - with analysis to a date (exclusive) - optional * * If no constraints on dates, all the history is returned */ public List<MeasureDto> selectPastMeasures(DbSession dbSession, PastMeasureQuery query) { return mapper(dbSession).selectPastMeasuresOnSeveralAnalyses(query); } public void insert(DbSession session, MeasureDto measureDto) { measureDto.setUuid(uuidFactory.create()); mapper(session).insert(measureDto); } public void insert(DbSession session, Collection<MeasureDto> items) { for (MeasureDto item : items) { item.setUuid(uuidFactory.create()); insert(session, item); } } public void insert(DbSession session, MeasureDto item, MeasureDto... others) { insert(session, Lists.asList(item, others)); } private static MeasureMapper mapper(DbSession session) { return session.getMapper(MeasureMapper.class); } }
2,742
33.2875
127
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/measure/MeasureDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.measure; import com.google.common.base.MoreObjects; import java.nio.charset.StandardCharsets; import javax.annotation.CheckForNull; import javax.annotation.Nullable; public class MeasureDto { private static final int MAX_TEXT_VALUE_LENGTH = 4000; private String uuid; private Double value; private String textValue; private byte[] dataValue; private String alertStatus; private String alertText; private String componentUuid; private String analysisUuid; private String metricUuid; public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } @CheckForNull public Double getValue() { return value; } public MeasureDto setValue(@Nullable Double value) { this.value = value; return this; } public String getComponentUuid() { return componentUuid; } public MeasureDto setComponentUuid(String s) { this.componentUuid = s; return this; } @CheckForNull public String getData() { if (dataValue != null) { return new String(dataValue, StandardCharsets.UTF_8); } return textValue; } public MeasureDto setData(@Nullable String data) { if (data == null) { this.textValue = null; this.dataValue = null; } else if (data.length() > MAX_TEXT_VALUE_LENGTH) { this.textValue = null; this.dataValue = data.getBytes(StandardCharsets.UTF_8); } else { this.textValue = data; this.dataValue = null; } return this; } @CheckForNull public String getAlertStatus() { return alertStatus; } public MeasureDto setAlertStatus(@Nullable String alertStatus) { this.alertStatus = alertStatus; return this; } @CheckForNull public String getAlertText() { return alertText; } public MeasureDto setAlertText(@Nullable String alertText) { this.alertText = alertText; return this; } public String getMetricUuid() { return metricUuid; } public MeasureDto setMetricUuid(String metricUuid) { this.metricUuid = metricUuid; return this; } public String getAnalysisUuid() { return analysisUuid; } public MeasureDto setAnalysisUuid(String s) { this.analysisUuid = s; return this; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("value", value) .add("textValue", textValue) .add("dataValue", dataValue) .add("alertStatus", alertStatus) .add("alertText", alertText) .add("componentUuid", componentUuid) .add("analysisUuid", analysisUuid) .add("metricUuid", metricUuid) .toString(); } }
3,504
23.683099
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/measure/MeasureMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.measure; import java.util.List; import javax.annotation.CheckForNull; import org.apache.ibatis.annotations.Param; public interface MeasureMapper { @CheckForNull MeasureDto selectLastMeasure( @Param("componentUuid") String componentUuid, @Param("metricKey") String metricKey ); @CheckForNull MeasureDto selectMeasure( @Param("analysisUuid") String analysisUuid, @Param("componentUuid") String componentUuid, @Param("metricKey") String metricKey ); List<MeasureDto> selectPastMeasuresOnSeveralAnalyses(@Param("query") PastMeasureQuery query); void insert(MeasureDto measureDto); }
1,486
31.326087
95
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/measure/MeasureTreeQuery.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.measure; import java.util.Collection; import java.util.Locale; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.db.WildcardPosition; import org.sonar.db.component.ComponentDto; import static com.google.common.collect.Lists.newArrayList; import static java.util.Objects.requireNonNull; import static org.sonar.db.DaoUtils.buildLikeValue; import static org.sonar.db.WildcardPosition.BEFORE_AND_AFTER; public class MeasureTreeQuery { public enum Strategy { CHILDREN, LEAVES } @CheckForNull private final String nameOrKeyQuery; // SONAR-7681 a public implementation of List must be used in MyBatis - potential concurrency exceptions otherwise @CheckForNull private final Collection<String> qualifiers; private final Strategy strategy; @CheckForNull private final Collection<String> metricUuids; private MeasureTreeQuery(Builder builder) { this.nameOrKeyQuery = builder.nameOrKeyQuery; this.qualifiers = builder.qualifiers == null ? null : newArrayList(builder.qualifiers); this.strategy = requireNonNull(builder.strategy); this.metricUuids = builder.metricUuids; } @CheckForNull public String getNameOrKeyQuery() { return nameOrKeyQuery; } /** * Used by MyBatis mapper */ @CheckForNull public String getNameOrKeyUpperLikeQuery() { return nameOrKeyQuery == null ? null : buildLikeValue(nameOrKeyQuery, BEFORE_AND_AFTER).toUpperCase(Locale.ENGLISH); } @CheckForNull public Collection<String> getQualifiers() { return qualifiers; } public Strategy getStrategy() { return strategy; } @CheckForNull public Collection<String> getMetricUuids() { return metricUuids; } public String getUuidPath(ComponentDto component) { switch (strategy) { case CHILDREN: return component.getUuidPath() + component.uuid() + "."; case LEAVES: return buildLikeValue(component.getUuidPath() + component.uuid() + ".", WildcardPosition.AFTER); default: throw new IllegalArgumentException("Unknown strategy : " + strategy); } } public boolean returnsEmpty() { return (metricUuids != null && metricUuids.isEmpty()) || (qualifiers != null && qualifiers.isEmpty()); } public static Builder builder() { return new Builder(); } public static final class Builder { @CheckForNull private String nameOrKeyQuery; @CheckForNull private Collection<String> qualifiers; private Strategy strategy; @CheckForNull private Collection<String> metricUuids; private Builder() { } public Builder setNameOrKeyQuery(@Nullable String nameOrKeyQuery) { this.nameOrKeyQuery = nameOrKeyQuery; return this; } public Builder setQualifiers(Collection<String> qualifiers) { this.qualifiers = qualifiers; return this; } public Builder setStrategy(Strategy strategy) { this.strategy = requireNonNull(strategy); return this; } /** * All the measures are returned if parameter is {@code null}. */ public Builder setMetricUuids(@Nullable Collection<String> metricUuids) { this.metricUuids = metricUuids; return this; } public MeasureTreeQuery build() { return new MeasureTreeQuery(this); } } }
4,170
27.765517
120
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/measure/PastMeasureDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.measure; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import static java.util.Objects.requireNonNull; public class PastMeasureDto { private String metricUuid; @CheckForNull private Double value; public double getValue() { requireNonNull(value); return value; } PastMeasureDto setValue(@Nullable Double value) { this.value = value; return this; } public boolean hasValue() { return value != null; } public String getMetricUuid() { return metricUuid; } PastMeasureDto setMetricUuid(String i) { this.metricUuid = i; return this; } }
1,489
25.140351
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/measure/PastMeasureQuery.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.measure; import java.util.List; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.db.component.SnapshotDto; import static java.util.Objects.requireNonNull; public class PastMeasureQuery { private final String componentUuid; private final List<String> metricUuids; private final Long from; private final Long to; private final String status; public PastMeasureQuery(String componentUuid, List<String> metricUuids, @Nullable Long from, @Nullable Long to) { this.componentUuid = requireNonNull(componentUuid); this.metricUuids = requireNonNull(metricUuids); this.from = from; this.to = to; this.status = SnapshotDto.STATUS_PROCESSED; } public String getComponentUuid() { return componentUuid; } public List<String> getMetricUuids() { return metricUuids; } @CheckForNull public Long getFrom() { return from; } @CheckForNull public Long getTo() { return to; } public String getStatus() { return status; } }
1,892
27.681818
115
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/measure/ProjectLocDistributionDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.measure; /** * Loc distribution per language for the largest branch in a project. */ public record ProjectLocDistributionDto(String projectUuid, String branchUuid, String locDistribution) { }
1,060
36.892857
104
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/measure/ProjectMainBranchLiveMeasureDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.measure; import javax.annotation.Nullable; public class ProjectMainBranchLiveMeasureDto { private String projectUuid; private String metricUuid; @Nullable private Double value; @Nullable private String textValue; public String getProjectUuid() { return projectUuid; } @Nullable public Double getValue() { return value; } @Nullable public String getTextValue() { return textValue; } public String getMetricUuid() { return metricUuid; } }
1,355
26.12
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/measure/ProjectMeasuresIndexerIterator.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.measure; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSortedSet; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.stream.Collectors; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; import org.sonar.api.measures.CoreMetrics; import org.sonar.api.resources.Qualifiers; import org.sonar.core.util.CloseableIterator; import org.sonar.db.DatabaseUtils; import org.sonar.db.DbSession; import static org.sonar.api.measures.CoreMetrics.ALERT_STATUS_KEY; import static org.sonar.api.measures.CoreMetrics.NCLOC_LANGUAGE_DISTRIBUTION_KEY; import static org.sonar.api.utils.KeyValueFormat.parseStringInt; import static org.sonar.db.component.DbTagsReader.readDbTags; public class ProjectMeasuresIndexerIterator extends CloseableIterator<ProjectMeasuresIndexerIterator.ProjectMeasures> { public static final Set<String> METRIC_KEYS = ImmutableSortedSet.of( CoreMetrics.NCLOC_KEY, CoreMetrics.LINES_KEY, CoreMetrics.DUPLICATED_LINES_DENSITY_KEY, CoreMetrics.COVERAGE_KEY, CoreMetrics.SQALE_RATING_KEY, CoreMetrics.RELIABILITY_RATING_KEY, CoreMetrics.SECURITY_RATING_KEY, CoreMetrics.SECURITY_HOTSPOTS_REVIEWED_KEY, CoreMetrics.SECURITY_REVIEW_RATING_KEY, CoreMetrics.NCLOC_LANGUAGE_DISTRIBUTION_KEY, CoreMetrics.ALERT_STATUS_KEY, CoreMetrics.NEW_SECURITY_RATING_KEY, CoreMetrics.NEW_SECURITY_HOTSPOTS_REVIEWED_KEY, CoreMetrics.NEW_SECURITY_REVIEW_RATING_KEY, CoreMetrics.NEW_MAINTAINABILITY_RATING_KEY, CoreMetrics.NEW_COVERAGE_KEY, CoreMetrics.NEW_DUPLICATED_LINES_DENSITY_KEY, CoreMetrics.NEW_LINES_KEY, CoreMetrics.NEW_RELIABILITY_RATING_KEY); private static final String SQL_PROJECTS = "SELECT p.uuid, p.kee, p.name, s.created_at, p.tags, p.qualifier " + "FROM projects p " + "INNER JOIN project_branches pb ON pb.project_uuid = p.uuid AND pb.is_main = ? " + "LEFT OUTER JOIN snapshots s ON s.root_component_uuid=pb.uuid AND s.islast=? " + "WHERE p.qualifier in (?, ?)"; private static final String PROJECT_FILTER = " AND pb.project_uuid=?"; private static final String SQL_MEASURES = """ SELECT m.name, pm.value, pm.text_value FROM live_measures pm INNER JOIN metrics m ON m.uuid = pm.metric_uuid INNER JOIN project_branches pb ON pb.uuid = pm.component_uuid WHERE pb.project_uuid = ? AND pb.is_main = ? AND m.name IN ({metricNames}) AND (pm.value IS NOT NULL OR pm.text_value IS NOT NULL) AND m.enabled = ?"""; private static final String SQL_NCLOC_LANGUAGE_DISTRIBUTION = """ SELECT m.name, pm.value, pm.text_value FROM live_measures pm INNER JOIN metrics m ON m.uuid = pm.metric_uuid WHERE pm.component_uuid = ? AND m.name = ? AND (pm.value IS NOT NULL OR pm.text_value IS NOT NULL) AND m.enabled = ?"""; private static final String SQL_BIGGEST_NCLOC_VALUE = """ SELECT max(lm.value) FROM metrics m INNER JOIN live_measures lm ON m.uuid = lm.metric_uuid INNER JOIN project_branches pb ON lm.component_uuid = pb.uuid WHERE pb.project_uuid = ? AND m.name = ? AND lm.value IS NOT NULL AND m.enabled = ? """; private static final String SQL_BRANCH_BY_NCLOC = """ SELECT lm.component_uuid FROM metrics m INNER JOIN live_measures lm ON m.uuid = lm.metric_uuid INNER JOIN project_branches pb ON lm.component_uuid = pb.uuid WHERE pb.project_uuid = ? AND m.name = ? AND lm.value = ? AND m.enabled = ?"""; private static final boolean ENABLED = true; private static final int FIELD_METRIC_NAME = 1; private static final int FIELD_MEASURE_VALUE = 2; private static final int FIELD_MEASURE_TEXT_VALUE = 3; private final DbSession dbSession; private final PreparedStatement measuresStatement; private final Iterator<Project> projects; private ProjectMeasuresIndexerIterator(DbSession dbSession, PreparedStatement measuresStatement, List<Project> projects) { this.dbSession = dbSession; this.measuresStatement = measuresStatement; this.projects = projects.iterator(); } public static ProjectMeasuresIndexerIterator create(DbSession session, @Nullable String projectUuid) { List<Project> projects = selectProjects(session, projectUuid); PreparedStatement projectsStatement = createMeasuresStatement(session); return new ProjectMeasuresIndexerIterator(session, projectsStatement, projects); } private static List<Project> selectProjects(DbSession session, @Nullable String projectUuid) { List<Project> projects = new ArrayList<>(); try (PreparedStatement stmt = createProjectsStatement(session, projectUuid); ResultSet rs = stmt.executeQuery()) { while (rs.next()) { String uuid = rs.getString(1); String key = rs.getString(2); String name = rs.getString(3); Long analysisDate = DatabaseUtils.getLong(rs, 4); List<String> tags = readDbTags(DatabaseUtils.getString(rs, 5)); String qualifier = rs.getString(6); Project project = new Project(uuid, key, name, qualifier, tags, analysisDate); projects.add(project); } return projects; } catch (SQLException e) { throw new IllegalStateException("Fail to execute request to select all projects", e); } } private static PreparedStatement createProjectsStatement(DbSession session, @Nullable String projectUuid) { try { StringBuilder sql = new StringBuilder(SQL_PROJECTS); if (projectUuid != null) { sql.append(PROJECT_FILTER); } PreparedStatement stmt = session.getConnection().prepareStatement(sql.toString()); stmt.setBoolean(1, true); stmt.setBoolean(2, true); stmt.setString(3, Qualifiers.PROJECT); stmt.setString(4, Qualifiers.APP); if (projectUuid != null) { stmt.setString(5, projectUuid); } return stmt; } catch (SQLException e) { throw new IllegalStateException("Fail to prepare SQL request to select all project measures", e); } } private static PreparedStatement createMeasuresStatement(DbSession session) { try { String metricNameQuestionMarks = METRIC_KEYS.stream() .filter(m -> !m.equals(NCLOC_LANGUAGE_DISTRIBUTION_KEY)) .map(x -> "?").collect(Collectors.joining(",")); String sql = StringUtils.replace(SQL_MEASURES, "{metricNames}", metricNameQuestionMarks); return session.getConnection().prepareStatement(sql); } catch (SQLException e) { throw new IllegalStateException("Fail to prepare SQL request to select measures", e); } } @Override @CheckForNull protected ProjectMeasures doNext() { if (!projects.hasNext()) { return null; } Project project = projects.next(); Measures measures = selectMeasures(project.getUuid()); return new ProjectMeasures(project, measures); } private Measures selectMeasures(String projectUuid) { try { Measures measures = new Measures(); prepareMeasuresStatement(projectUuid); try (ResultSet rs = measuresStatement.executeQuery()) { while (rs.next()) { readMeasure(rs, measures); } } String biggestBranch = selectProjectBiggestNcloc(dbSession, projectUuid) .flatMap(ncloc -> selectProjectBranchForNcloc(dbSession, projectUuid, ncloc)) .orElse(""); try (PreparedStatement prepareNclocByLanguageStatement = prepareNclocByLanguageStatement(dbSession, biggestBranch)) { try (ResultSet rs = prepareNclocByLanguageStatement.executeQuery()) { if (rs.next()) { readMeasure(rs, measures); } } } return measures; } catch (Exception e) { throw new IllegalStateException(String.format("Fail to execute request to select measures of project %s", projectUuid), e); } } private void prepareMeasuresStatement(String projectUuid) throws SQLException { AtomicInteger index = new AtomicInteger(1); measuresStatement.setString(index.getAndIncrement(), projectUuid); measuresStatement.setBoolean(index.getAndIncrement(), true); METRIC_KEYS .stream() .filter(m -> !m.equals(NCLOC_LANGUAGE_DISTRIBUTION_KEY)) .forEach(DatabaseUtils.setStrings(measuresStatement, index::getAndIncrement)); measuresStatement.setBoolean(index.getAndIncrement(), ENABLED); } private static PreparedStatement prepareNclocByLanguageStatement(DbSession session, String branchUuid) { try { PreparedStatement stmt = session.getConnection().prepareStatement(SQL_NCLOC_LANGUAGE_DISTRIBUTION); AtomicInteger index = new AtomicInteger(1); stmt.setString(index.getAndIncrement(), branchUuid); stmt.setString(index.getAndIncrement(), NCLOC_LANGUAGE_DISTRIBUTION_KEY); stmt.setBoolean(index.getAndIncrement(), ENABLED); return stmt; } catch (SQLException e) { throw new IllegalStateException("Fail to execute request to select ncloc_language_distribution measure", e); } } private static Optional<Long> selectProjectBiggestNcloc(DbSession session, String projectUuid) { try (PreparedStatement nclocStatement = session.getConnection().prepareStatement(SQL_BIGGEST_NCLOC_VALUE)) { AtomicInteger index = new AtomicInteger(1); nclocStatement.setString(index.getAndIncrement(), projectUuid); nclocStatement.setString(index.getAndIncrement(), CoreMetrics.NCLOC_KEY); nclocStatement.setBoolean(index.getAndIncrement(), ENABLED); try (ResultSet rs = nclocStatement.executeQuery()) { if (rs.next()) { return Optional.of(rs.getLong(1)); } return Optional.empty(); } } catch (SQLException e) { throw new IllegalStateException("Fail to execute request to select the project biggest ncloc", e); } } private static Optional<String> selectProjectBranchForNcloc(DbSession session, String projectUuid, long ncloc) { try (PreparedStatement nclocStatement = session.getConnection().prepareStatement(SQL_BRANCH_BY_NCLOC)) { AtomicInteger index = new AtomicInteger(1); nclocStatement.setString(index.getAndIncrement(), projectUuid); nclocStatement.setString(index.getAndIncrement(), CoreMetrics.NCLOC_KEY); nclocStatement.setLong(index.getAndIncrement(), ncloc); nclocStatement.setBoolean(index.getAndIncrement(), ENABLED); try (ResultSet rs = nclocStatement.executeQuery()) { if (rs.next()) { return Optional.of(rs.getString(1)); } } return Optional.empty(); } catch (SQLException e) { throw new IllegalStateException("Fail to execute request to select the project biggest branch", e); } } private static void readMeasure(ResultSet rs, Measures measures) throws SQLException { String metricKey = rs.getString(FIELD_METRIC_NAME); Optional<Double> value = getDouble(rs, FIELD_MEASURE_VALUE); if (value.isPresent()) { measures.addNumericMeasure(metricKey, value.get()); return; } if (ALERT_STATUS_KEY.equals(metricKey)) { readTextValue(rs, measures::setQualityGateStatus); return; } if (NCLOC_LANGUAGE_DISTRIBUTION_KEY.equals(metricKey)) { readTextValue(rs, measures::setNclocByLanguages); } } private static void readTextValue(ResultSet rs, Consumer<String> action) throws SQLException { String textValue = rs.getString(FIELD_MEASURE_TEXT_VALUE); if (!rs.wasNull()) { action.accept(textValue); } } @Override protected void doClose() throws Exception { measuresStatement.close(); } private static Optional<Double> getDouble(ResultSet rs, int index) { try { Double value = rs.getDouble(index); if (!rs.wasNull()) { return Optional.of(value); } return Optional.empty(); } catch (SQLException e) { throw new IllegalStateException("Fail to get double value", e); } } public static class Project { private final String uuid; private final String key; private final String name; private final String qualifier; private final Long analysisDate; private final List<String> tags; public Project(String uuid, String key, String name, String qualifier, List<String> tags, @Nullable Long analysisDate) { this.uuid = uuid; this.key = key; this.name = name; this.qualifier = qualifier; this.tags = tags; this.analysisDate = analysisDate; } public String getUuid() { return uuid; } public String getKey() { return key; } public String getName() { return name; } public String getQualifier() { return qualifier; } public List<String> getTags() { return tags; } @CheckForNull public Long getAnalysisDate() { return analysisDate; } } public static class Measures { private final Map<String, Double> numericMeasures = new HashMap<>(); private String qualityGateStatus; private Map<String, Integer> nclocByLanguages = new LinkedHashMap<>(); Measures addNumericMeasure(String metricKey, double value) { numericMeasures.put(metricKey, value); return this; } public Map<String, Double> getNumericMeasures() { return numericMeasures; } Measures setQualityGateStatus(@Nullable String qualityGateStatus) { this.qualityGateStatus = qualityGateStatus; return this; } @CheckForNull public String getQualityGateStatus() { return qualityGateStatus; } Measures setNclocByLanguages(String nclocByLangues) { this.nclocByLanguages = ImmutableMap.copyOf(parseStringInt(nclocByLangues)); return this; } public Map<String, Integer> getNclocByLanguages() { return nclocByLanguages; } } public static class ProjectMeasures { private final Project project; private final Measures measures; public ProjectMeasures(Project project, Measures measures) { this.project = project; this.measures = measures; } public Project getProject() { return project; } public Measures getMeasures() { return measures; } } }
15,433
35.230047
129
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/measure/SumNclocDbQuery.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.measure; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkNotNull; public class SumNclocDbQuery { private final String projectUuidToExclude; private final Boolean onlyPrivateProjects; public SumNclocDbQuery(Builder builder) { projectUuidToExclude = builder.projectUuidToExclude; onlyPrivateProjects = builder.onlyPrivateProjects; } @CheckForNull public String getProjectUuidToExclude() { return projectUuidToExclude; } public Boolean getOnlyPrivateProjects() { return onlyPrivateProjects; } public static Builder builder() { return new Builder(); } public static class Builder { private String projectUuidToExclude; private Boolean onlyPrivateProjects; private Builder() { // to enforce use of builder() } public Builder setProjectUuidToExclude(@Nullable String projectUuidToExclude) { this.projectUuidToExclude = projectUuidToExclude; return this; } public Builder setOnlyPrivateProjects(Boolean onlyPrivateProjects) { this.onlyPrivateProjects = onlyPrivateProjects; return this; } public SumNclocDbQuery build() { checkNotNull(onlyPrivateProjects); return new SumNclocDbQuery(this); } } }
2,175
28.405405
83
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/measure/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.db.measure; import javax.annotation.ParametersAreNonnullByDefault;
961
37.48
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/metric/MetricDao.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.metric; import com.google.common.collect.Lists; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Set; import javax.annotation.CheckForNull; import org.apache.ibatis.session.RowBounds; import org.sonar.db.Dao; import org.sonar.db.DbSession; import org.sonar.db.RowNotFoundException; import static org.sonar.db.DatabaseUtils.executeLargeInputs; public class MetricDao implements Dao { @CheckForNull public MetricDto selectByKey(DbSession session, String key) { return mapper(session).selectByKey(key); } public List<MetricDto> selectByKeys(final DbSession session, Collection<String> keys) { return executeLargeInputs(keys, mapper(session)::selectByKeys); } public MetricDto selectOrFailByKey(DbSession session, String key) { MetricDto metric = selectByKey(session, key); if (metric == null) { throw new RowNotFoundException(String.format("Metric key '%s' not found", key)); } return metric; } public List<MetricDto> selectAll(DbSession session) { return mapper(session).selectAll(); } public List<MetricDto> selectEnabled(DbSession session) { return mapper(session).selectAllEnabled(); } public List<MetricDto> selectEnabled(DbSession session, int offset, int limit) { return mapper(session).selectAllEnabled(new RowBounds(offset, limit)); } public int countEnabled(DbSession session) { return mapper(session).countEnabled(); } public MetricDto insert(DbSession session, MetricDto dto) { mapper(session).insert(dto); return dto; } public void insert(DbSession session, Collection<MetricDto> items) { for (MetricDto item : items) { insert(session, item); } } public void insert(DbSession session, MetricDto item, MetricDto... others) { insert(session, Lists.asList(item, others)); } public List<MetricDto> selectByUuids(DbSession session, Set<String> uuidsSet) { return executeLargeInputs(new ArrayList<>(uuidsSet), mapper(session)::selectByUuids); } private static MetricMapper mapper(DbSession session) { return session.getMapper(MetricMapper.class); } /** * Disable a metric and return {@code false} if the metric does not exist * or is already disabled. */ public boolean disableByKey(DbSession session, String key) { return mapper(session).disableByKey(key) == 1; } public void update(DbSession session, MetricDto metric) { mapper(session).update(metric); } @CheckForNull public MetricDto selectByUuid(DbSession session, String uuid) { return mapper(session).selectByUuid(uuid); } }
3,485
30.125
89
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/metric/MetricDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.metric; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import static org.sonar.db.metric.MetricValidator.checkMetricDescription; import static org.sonar.db.metric.MetricValidator.checkMetricDomain; import static org.sonar.db.metric.MetricValidator.checkMetricKey; import static org.sonar.db.metric.MetricValidator.checkMetricName; public class MetricDto { private String uuid; private String kee; private String shortName; private String valueType; private String description; private String domain; private int direction; private boolean qualitative; private Double worstValue; private Double bestValue; private boolean optimizedBestValue; private boolean hidden; private boolean deleteHistoricalData; private boolean enabled; private Integer decimalScale; public String getUuid() { return uuid; } public MetricDto setUuid(String uuid) { this.uuid = uuid; return this; } public String getKey() { return kee; } public MetricDto setKey(String key) { this.kee = checkMetricKey(key); return this; } public String getShortName() { return shortName; } public MetricDto setShortName(String shortName) { this.shortName = checkMetricName(shortName); return this; } public String getValueType() { return valueType; } public MetricDto setValueType(String valueType) { this.valueType = valueType; return this; } /** * @return null for manual metrics */ @CheckForNull public String getDescription() { return description; } public MetricDto setDescription(@Nullable String description) { this.description = checkMetricDescription(description); return this; } @CheckForNull public String getDomain() { return domain; } public MetricDto setDomain(@Nullable String domain) { this.domain = checkMetricDomain(domain); return this; } public int getDirection() { return direction; } public MetricDto setDirection(int direction) { this.direction = direction; return this; } public boolean isQualitative() { return qualitative; } public MetricDto setQualitative(boolean qualitative) { this.qualitative = qualitative; return this; } @CheckForNull public Double getWorstValue() { return worstValue; } public MetricDto setWorstValue(@Nullable Double worstValue) { this.worstValue = worstValue; return this; } @CheckForNull public Double getBestValue() { return bestValue; } public MetricDto setBestValue(@Nullable Double bestValue) { this.bestValue = bestValue; return this; } public boolean isOptimizedBestValue() { return optimizedBestValue; } public MetricDto setOptimizedBestValue(boolean optimizedBestValue) { this.optimizedBestValue = optimizedBestValue; return this; } public boolean isHidden() { return hidden; } public MetricDto setHidden(boolean hidden) { this.hidden = hidden; return this; } public boolean isDeleteHistoricalData() { return deleteHistoricalData; } public MetricDto setDeleteHistoricalData(boolean deleteHistoricalData) { this.deleteHistoricalData = deleteHistoricalData; return this; } public boolean isEnabled() { return enabled; } public MetricDto setEnabled(boolean enabled) { this.enabled = enabled; return this; } @CheckForNull public Integer getDecimalScale() { return decimalScale; } public MetricDto setDecimalScale(@Nullable Integer i) { this.decimalScale = i; return this; } }
4,476
20.73301
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/metric/MetricDtoFunctions.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.metric; import java.util.function.Predicate; /** * Common functions on MetricDto */ public class MetricDtoFunctions { private MetricDtoFunctions() { // prevents instantiation } public static Predicate<MetricDto> isOptimizedForBestValue() { return m -> m != null && m.isOptimizedBestValue() && m.getBestValue() != null; } }
1,209
31.702703
82
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/metric/MetricMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.metric; import java.util.List; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.session.RowBounds; public interface MetricMapper { MetricDto selectByUuid(String uuid); List<MetricDto> selectByUuids(@Param("uuids") List<String> uuids); MetricDto selectByKey(@Param("key") String key); List<MetricDto> selectByKeys(@Param("keys") List<String> keys); List<MetricDto> selectAll(); List<MetricDto> selectAllEnabled(); List<MetricDto> selectAllEnabled(RowBounds rowBounds); void insert(MetricDto dto); int disableByKey(@Param("key") String key); int countEnabled(); void update(MetricDto metric); }
1,512
29.26
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/metric/MetricValidator.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.metric; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Strings.isNullOrEmpty; public class MetricValidator { public static final int MAX_KEY_LENGTH = 64; public static final int MAX_NAME_LENGTH = 64; public static final int MAX_DOMAIN_LENGTH = 64; public static final int MAX_DESCRIPTION_LENGTH = 255; private MetricValidator() { // static utility methods only } public static String checkMetricKey(String key) { checkArgument(!isNullOrEmpty(key), "Metric key cannot be empty"); checkArgument(key.length() <= MAX_NAME_LENGTH, "Metric key length (%s) is longer than the maximum authorized (%s). '%s' was provided.", key.length(), MAX_KEY_LENGTH, key); return key; } public static String checkMetricName(String name) { checkArgument(!isNullOrEmpty(name), "Metric name cannot be empty"); checkArgument(name.length() <= MAX_NAME_LENGTH, "Metric name length (%s) is longer than the maximum authorized (%s). '%s' was provided.", name.length(), MAX_NAME_LENGTH, name); return name; } @CheckForNull public static String checkMetricDescription(@Nullable String description) { if (description == null) { return null; } checkArgument(description.length() <= MAX_DESCRIPTION_LENGTH, "Metric description length (%s) is longer than the maximum authorized (%s). '%s' was provided.", description.length(), MAX_DESCRIPTION_LENGTH, description); return description; } @CheckForNull public static String checkMetricDomain(@Nullable String domain) { if (domain == null) { return null; } checkArgument(domain.length() <= MAX_DOMAIN_LENGTH, "Metric domain length (%s) is longer than the maximum authorized (%s). '%s' was provided.", domain.length(), MAX_DOMAIN_LENGTH, domain); return domain; } }
2,807
35.947368
162
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/metric/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.db.metric; import javax.annotation.ParametersAreNonnullByDefault;
960
37.44
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/newcodeperiod/NewCodePeriodDao.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.newcodeperiod; import java.util.List; import java.util.Optional; import java.util.Set; import javax.annotation.Nullable; import org.sonar.api.utils.System2; import org.sonar.core.util.UuidFactory; import org.sonar.db.Dao; import org.sonar.db.DbSession; import static java.util.Objects.requireNonNull; import static java.util.Optional.ofNullable; import static org.sonar.api.utils.Preconditions.checkArgument; public class NewCodePeriodDao implements Dao { private static final String MSG_PROJECT_UUID_NOT_SPECIFIED = "Project uuid must be specified."; private final System2 system2; private final UuidFactory uuidFactory; public NewCodePeriodDao(System2 system2, UuidFactory uuidFactory) { this.system2 = system2; this.uuidFactory = uuidFactory; } public Optional<NewCodePeriodDto> selectByUuid(DbSession dbSession, String uuid) { return mapper(dbSession).selectByUuid(uuid); } public Optional<NewCodePeriodDto> selectGlobal(DbSession dbSession) { return ofNullable(mapper(dbSession).selectGlobal()); } public void insert(DbSession dbSession, NewCodePeriodDto dto) { requireNonNull(dto.getType(), "Type of NewCodePeriod must be specified."); long currentTime = system2.now(); mapper(dbSession).insert(dto.setCreatedAt(currentTime) .setUpdatedAt(currentTime) .setUuid(ofNullable(dto.getUuid()).orElse(uuidFactory.create()))); } public void upsert(DbSession dbSession, NewCodePeriodDto dto) { NewCodePeriodMapper mapper = mapper(dbSession); long currentTime = system2.now(); dto.setUpdatedAt(currentTime); if (mapper.update(dto) == 0) { dto.setCreatedAt(currentTime); dto.setUuid(uuidFactory.create()); mapper.insert(dto); } } public void update(DbSession dbSession, NewCodePeriodDto dto) { requireNonNull(dto.getUuid(), "Uuid of NewCodePeriod must be specified."); mapper(dbSession).update(dto.setUpdatedAt(system2.now())); } public Optional<NewCodePeriodDto> selectByProject(DbSession dbSession, String projectUuid) { requireNonNull(projectUuid, MSG_PROJECT_UUID_NOT_SPECIFIED); return ofNullable(mapper(dbSession).selectByProject(projectUuid)); } public List<NewCodePeriodDto> selectAllByProject(DbSession dbSession, String projectUuid) { requireNonNull(projectUuid, MSG_PROJECT_UUID_NOT_SPECIFIED); return mapper(dbSession).selectAllByProject(projectUuid); } public Optional<NewCodePeriodDto> selectByBranch(DbSession dbSession, String projectUuid, String branchUuid) { requireNonNull(projectUuid, MSG_PROJECT_UUID_NOT_SPECIFIED); requireNonNull(branchUuid, "Branch uuid must be specified."); return ofNullable(mapper(dbSession).selectByBranch(projectUuid, branchUuid)); } public Set<String> selectBranchesReferencing(DbSession dbSession, String projectUuid, String referenceBranchName) { return mapper(dbSession).selectBranchesReferencing(projectUuid, referenceBranchName); } public boolean existsByProjectAnalysisUuid(DbSession dbSession, String projectAnalysisUuid) { requireNonNull(projectAnalysisUuid, MSG_PROJECT_UUID_NOT_SPECIFIED); return mapper(dbSession).countByProjectAnalysis(projectAnalysisUuid) > 0; } /** * Deletes an entry. It can be the global setting or a specific project or branch setting. * Note that deleting project's setting doesn't delete the settings of the branches belonging to that project. */ public void delete(DbSession dbSession, @Nullable String projectUuid, @Nullable String branchUuid) { checkArgument(branchUuid == null || projectUuid != null, "branchUuid must be null if projectUuid is null"); mapper(dbSession).delete(projectUuid, branchUuid); } private static NewCodePeriodMapper mapper(DbSession session) { return session.getMapper(NewCodePeriodMapper.class); } public List<NewCodePeriodDto> selectAll(DbSession dbSession) { return mapper(dbSession).selectAll(); } }
4,806
39.394958
117
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/newcodeperiod/NewCodePeriodDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.newcodeperiod; import javax.annotation.CheckForNull; import javax.annotation.Nullable; public class NewCodePeriodDto { private String uuid = null; private String projectUuid = null; private String branchUuid = null; private NewCodePeriodType type = null; private String value = null; private long updatedAt = 0L; private long createdAt = 0L; public static NewCodePeriodDto defaultInstance() { return new NewCodePeriodDto().setType(NewCodePeriodType.PREVIOUS_VERSION); } public long getCreatedAt() { return createdAt; } public NewCodePeriodDto setCreatedAt(long createdAt) { this.createdAt = createdAt; return this; } public long getUpdatedAt() { return updatedAt; } public NewCodePeriodDto setUpdatedAt(long updatedAt) { this.updatedAt = updatedAt; return this; } public String getUuid() { return uuid; } public NewCodePeriodDto setUuid(String uuid) { this.uuid = uuid; return this; } @CheckForNull public String getProjectUuid() { return projectUuid; } public NewCodePeriodDto setProjectUuid(@Nullable String projectUuid) { this.projectUuid = projectUuid; return this; } @CheckForNull public String getBranchUuid() { return branchUuid; } public NewCodePeriodDto setBranchUuid(@Nullable String branchUuid) { this.branchUuid = branchUuid; return this; } public NewCodePeriodType getType() { return type; } public NewCodePeriodDto setType(NewCodePeriodType type) { this.type = type; return this; } @CheckForNull public String getValue() { return value; } public NewCodePeriodDto setValue(@Nullable String value) { this.value = value; return this; } }
2,598
23.990385
78
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/newcodeperiod/NewCodePeriodMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.newcodeperiod; import java.util.List; import java.util.Optional; import java.util.Set; import org.apache.ibatis.annotations.Param; public interface NewCodePeriodMapper { Optional<NewCodePeriodDto> selectByUuid(String uuid); NewCodePeriodDto selectGlobal(); void insert(NewCodePeriodDto dto); int update(NewCodePeriodDto dto); NewCodePeriodDto selectByProject(String projectUuid); void delete(@Param("projectUuid") String projectUuid, @Param("branchUuid") String branchUuid); NewCodePeriodDto selectByBranch(@Param("projectUuid") String projectUuid, @Param("branchUuid") String branchUuid); Set<String> selectBranchesReferencing(@Param("projectUuid") String projectUuid, @Param("referenceBranchName") String referenceBranchName); long countByProjectAnalysis(String projectAnalysisUuid); List<NewCodePeriodDto> selectAllByProject(String projectUuid); List<NewCodePeriodDto> selectAll(); }
1,786
34.039216
140
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/newcodeperiod/NewCodePeriodParser.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.newcodeperiod; public class NewCodePeriodParser { private NewCodePeriodParser() { // static only } public static int parseDays(String value) { return Integer.parseInt(value); } }
1,061
33.258065
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/newcodeperiod/NewCodePeriodType.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.newcodeperiod; public enum NewCodePeriodType { PREVIOUS_VERSION, NUMBER_OF_DAYS, SPECIFIC_ANALYSIS, REFERENCE_BRANCH }
992
34.464286
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/newcodeperiod/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.db.newcodeperiod; import javax.annotation.ParametersAreNonnullByDefault;
967
37.72
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/notification/NotificationQueueDao.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.notification; import java.util.Collections; import java.util.List; import org.sonar.api.utils.System2; import org.sonar.core.util.UuidFactory; import org.sonar.db.Dao; import org.sonar.db.DbSession; import org.sonar.db.MyBatis; public class NotificationQueueDao implements Dao { private final MyBatis mybatis; private System2 system2; private UuidFactory uuidFactory; public NotificationQueueDao(MyBatis mybatis, System2 system2, UuidFactory uuidFactory) { this.mybatis = mybatis; this.system2 = system2; this.uuidFactory = uuidFactory; } public void insert(List<NotificationQueueDto> dtos) { try (DbSession session = mybatis.openSession(true)) { NotificationQueueMapper mapper = session.getMapper(NotificationQueueMapper.class); for (NotificationQueueDto dto : dtos) { dto.setUuid(uuidFactory.create()); dto.setCreatedAt(system2.now()); mapper.insert(dto); } session.commit(); } } public void delete(List<NotificationQueueDto> dtos) { try (DbSession session = mybatis.openSession(true)) { NotificationQueueMapper mapper = session.getMapper(NotificationQueueMapper.class); for (NotificationQueueDto dto : dtos) { mapper.delete(dto.getUuid()); } session.commit(); } } public List<NotificationQueueDto> selectOldest(int count) { if (count < 1) { return Collections.emptyList(); } try (DbSession session = mybatis.openSession(false)) { return session.getMapper(NotificationQueueMapper.class).findOldest(count); } } public long count() { try (DbSession session = mybatis.openSession(false)) { return session.getMapper(NotificationQueueMapper.class).count(); } } }
2,608
32.025316
90
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/notification/NotificationQueueDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.notification; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import org.sonar.api.notifications.Notification; import org.sonar.api.utils.SonarException; /** * @since 3.7.1 */ public class NotificationQueueDto { private String uuid; private byte[] data; private long createdAt; public String getUuid() { return uuid; } NotificationQueueDto setUuid(String uuid) { this.uuid = uuid; return this; } public byte[] getData() { return data; } public NotificationQueueDto setData(byte[] data) { this.data = data; return this; } public long getCreatedAt() { return createdAt; } NotificationQueueDto setCreatedAt(long createdAt) { this.createdAt = createdAt; return this; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); } public static <T extends Notification> NotificationQueueDto toNotificationQueueDto(T notification) { try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) { objectOutputStream.writeObject(notification); objectOutputStream.close(); return new NotificationQueueDto().setData(byteArrayOutputStream.toByteArray()); } catch (IOException e) { throw new SonarException("Unable to write notification", e); } } public <T extends Notification> T toNotification() throws IOException, ClassNotFoundException { if (this.data == null) { return null; } try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(this.data); ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)) { Object result = objectInputStream.readObject(); objectInputStream.close(); return (T) result; } } }
2,996
29.272727
102
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/notification/NotificationQueueMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.notification; import java.util.List; /** * @since 3.7.1 */ public interface NotificationQueueMapper { void insert(NotificationQueueDto actionPlanDto); void delete(String uuid); List<NotificationQueueDto> findOldest(int count); long count(); }
1,124
28.605263
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/notification/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.db.notification; import javax.annotation.ParametersAreNonnullByDefault;
966
37.68
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/permission/AuthorizationDao.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.permission; import java.util.Collection; import java.util.List; import java.util.Set; import javax.annotation.Nullable; import org.sonar.db.Dao; import org.sonar.db.DbSession; import org.sonar.db.EmailSubscriberDto; import static org.sonar.db.DatabaseUtils.executeLargeInputs; import static org.sonar.db.DatabaseUtils.executeLargeInputsIntoSet; import static org.sonar.db.permission.GlobalPermission.ADMINISTER; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES; /** * The SQL requests used to verify authorization (the permissions * granted to users) * * @see GroupPermissionDao for CRUD of table group_roles * @see UserPermissionDao for CRUD of table user_roles */ public class AuthorizationDao implements Dao { /** * Loads all the global permissions granted to user */ public Set<String> selectGlobalPermissions(DbSession dbSession, String userUuid) { return mapper(dbSession).selectGlobalPermissions(userUuid); } /** * Loads all the permissions granted to anonymous user */ public Set<String> selectGlobalPermissionsOfAnonymous(DbSession dbSession) { return mapper(dbSession).selectGlobalPermissionsOfAnonymous(); } /** * Loads all the permissions granted to logged-in user for the specified entity <strong>stored in *_ROLES * tables</strong>. * An empty Set is returned if user has no permissions on the entity. * * <strong>This method does not support public components</strong> */ public Set<String> selectEntityPermissions(DbSession dbSession, String entityUuid, String userUuid) { return mapper(dbSession).selectEntityPermissions(entityUuid, userUuid); } /** * Loads all the permissions granted to anonymous for the specified entity <strong>stored in *_ROLES * tables</strong>. * An empty Set is returned if anonymous user has no permissions on the entity. * * <strong>This method does not support public components</strong> */ public Set<String> selectEntityPermissionsOfAnonymous(DbSession dbSession, String entityUuid) { return mapper(dbSession).selectEntityPermissionsOfAnonymous(entityUuid); } /** * The number of users who will still have the permission if the group {@code excludedGroupUuid} * is deleted. The anyone virtual group is not taken into account. */ public int countUsersWithGlobalPermissionExcludingGroup(DbSession dbSession, String permission, String excludedGroupUuid) { return mapper(dbSession).countUsersWithGlobalPermissionExcludingGroup(permission, excludedGroupUuid); } /** * The number of users who will still have the permission if the user {@code excludedUserId} * is deleted. The anyone virtual group is not taken into account. */ public int countUsersWithGlobalPermissionExcludingUser(DbSession dbSession, String permission, String excludedUserUuid) { return mapper(dbSession).countUsersWithGlobalPermissionExcludingUser(permission, excludedUserUuid); } /** * The list of users who have the global permission. * The anyone virtual group is not taken into account. */ public List<String> selectUserUuidsWithGlobalPermission(DbSession dbSession, String permission) { return mapper(dbSession).selectUserUuidsWithGlobalPermission(permission); } /** * The number of users who will still have the permission if the user {@code userId} * is removed from group {@code groupUuid}. The anyone virtual group is not taken into account. * Contrary to {@link #countUsersWithGlobalPermissionExcludingUser(DbSession, String, String)}, user * still exists and may have the permission directly or through other groups. */ public int countUsersWithGlobalPermissionExcludingGroupMember(DbSession dbSession, String permission, String groupUuid, String userUuid) { return mapper(dbSession).countUsersWithGlobalPermissionExcludingGroupMember(permission, groupUuid, userUuid); } /** * The number of users who will still have the permission if the permission {@code permission} * is removed from user {@code userId}. The anyone virtual group is not taken into account. * Contrary to {@link #countUsersWithGlobalPermissionExcludingUser(DbSession, String, String)}, user * still exists and may have the permission through groups. */ public int countUsersWithGlobalPermissionExcludingUserPermission(DbSession dbSession, String permission, String userUuid) { return mapper(dbSession).countUsersWithGlobalPermissionExcludingUserPermission(permission, userUuid); } public Set<String> keepAuthorizedEntityUuids(DbSession dbSession, Collection<String> entityUuids, @Nullable String userUuid, String permission) { return executeLargeInputsIntoSet( entityUuids, partition -> { if (userUuid == null) { return mapper(dbSession).keepAuthorizedEntityUuidsForAnonymous(permission, partition); } return mapper(dbSession).keepAuthorizedEntityUuidsForUser(userUuid, permission, partition); }, partitionSize -> partitionSize / 2); } /** * Keep only authorized user that have the given permission on a given entity. * Please Note that if the permission is 'Anyone' is NOT taking into account by this method. */ public Collection<String> keepAuthorizedUsersForRoleAndEntity(DbSession dbSession, Collection<String> userUuids, String role, String entityUuid) { return executeLargeInputs( userUuids, partitionOfIds -> mapper(dbSession).keepAuthorizedUsersForRoleAndEntity(role, entityUuid, partitionOfIds), partitionSize -> partitionSize / 3); } public Set<EmailSubscriberDto> selectQualityProfileAdministratorLogins(DbSession dbSession) { return mapper(dbSession).selectEmailSubscribersWithGlobalPermission(ADMINISTER_QUALITY_PROFILES.getKey()); } public Set<EmailSubscriberDto> selectGlobalAdministerEmailSubscribers(DbSession dbSession) { return mapper(dbSession).selectEmailSubscribersWithGlobalPermission(ADMINISTER.getKey()); } public Set<String> keepAuthorizedLoginsOnEntity(DbSession dbSession, Set<String> logins, String entityKey, String permission) { return executeLargeInputsIntoSet( logins, partitionOfLogins -> mapper(dbSession).keepAuthorizedLoginsOnEntity(partitionOfLogins, entityKey, permission), partitionSize -> partitionSize / 3); } private static AuthorizationMapper mapper(DbSession dbSession) { return dbSession.getMapper(AuthorizationMapper.class); } }
7,338
43.210843
148
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/permission/AuthorizationMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.permission; import java.util.Collection; import java.util.List; import java.util.Set; import org.apache.ibatis.annotations.Param; import org.sonar.db.EmailSubscriberDto; /** * @see AuthorizationDao */ public interface AuthorizationMapper { Set<String> selectGlobalPermissions(@Param("userUuid") String userUuid); Set<String> selectGlobalPermissionsOfAnonymous(); int countUsersWithGlobalPermissionExcludingGroup(@Param("permission") String permission, @Param("excludedGroupUuid") String excludedGroupUuid); int countUsersWithGlobalPermissionExcludingUser(@Param("permission") String permission, @Param("excludedUserUuid") String excludedUserUuid); List<String> selectUserUuidsWithGlobalPermission(@Param("permission") String permission); int countUsersWithGlobalPermissionExcludingGroupMember(@Param("permission") String permission, @Param("groupUuid") String groupUuid, @Param("userUuid") String userUuid); int countUsersWithGlobalPermissionExcludingUserPermission(@Param("permission") String permission, @Param("userUuid") String userUuid); List<String> keepAuthorizedUsersForRoleAndEntity(@Param("role") String role, @Param("entityUuid") String entityUuid, @Param("userUuids") List<String> userUuids); Set<String> keepAuthorizedEntityUuidsForUser(@Param("userUuid") String userUuid, @Param("role") String role, @Param("entityUuids") Collection<String> entityUuids); Set<String> keepAuthorizedEntityUuidsForAnonymous(@Param("role") String role, @Param("entityUuids") Collection<String> entityUuids); Set<String> selectEntityPermissions(@Param("entityUuid") String entityUuid, @Param("userUuid") String userUuid); Set<String> selectEntityPermissionsOfAnonymous(@Param("entityUuid") String entityUuid); Set<String> keepAuthorizedLoginsOnEntity(@Param("logins") List<String> logins, @Param("entityKey") String projectKey, @Param("permission") String permission); Set<EmailSubscriberDto> selectEmailSubscribersWithGlobalPermission(@Param("permission") String permission); }
2,886
45.564516
171
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/permission/CountPerEntityPermission.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.permission; import com.google.common.annotations.VisibleForTesting; /** * Count the number of users or groups for a given project and permission */ public class CountPerEntityPermission { private String entityUuid; private String permission; private int count; public CountPerEntityPermission() { // used by MyBatis } @VisibleForTesting CountPerEntityPermission(String entityUuid, String permission, int count) { this.entityUuid = entityUuid; this.permission = permission; this.count = count; } public String getEntityUuid() { return entityUuid; } public String getPermission() { return permission; } public int getCount() { return count; } }
1,572
27.6
77
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/permission/GlobalPermission.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.permission; import java.util.Arrays; import java.util.stream.Collectors; public enum GlobalPermission { ADMINISTER("admin"), ADMINISTER_QUALITY_GATES("gateadmin"), ADMINISTER_QUALITY_PROFILES("profileadmin"), PROVISION_PROJECTS("provisioning"), SCAN("scan"), /** * @since 7.4 */ APPLICATION_CREATOR("applicationcreator"), PORTFOLIO_CREATOR("portfoliocreator"); public static final String ALL_ON_ONE_LINE = Arrays.stream(values()).map(GlobalPermission::getKey).collect(Collectors.joining(", ")); private final String key; GlobalPermission(String key) { this.key = key; } public String getKey() { return key; } @Override public String toString() { return key; } public static GlobalPermission fromKey(String key) { for (GlobalPermission p : values()) { if (p.getKey().equals(key)) { return p; } } throw new IllegalArgumentException("Unsupported permission: " + key); } public static boolean contains(String key) { return Arrays.stream(values()).anyMatch(v -> v.getKey().equals(key)); } }
1,957
27.376812
135
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/permission/GroupPermissionDao.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.permission; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import org.sonar.api.security.DefaultGroups; import org.sonar.db.Dao; import org.sonar.db.DbSession; import org.sonar.db.audit.AuditPersister; import org.sonar.db.audit.model.GroupPermissionNewValue; import org.sonar.db.entity.EntityDto; import org.sonar.db.permission.template.PermissionTemplateDto; import static org.sonar.db.DatabaseUtils.executeLargeInputs; import static org.sonar.db.DatabaseUtils.executeLargeInputsWithoutOutput; public class GroupPermissionDao implements Dao { private static final String ANYONE_GROUP_PARAMETER = "anyoneGroup"; private final AuditPersister auditPersister; public GroupPermissionDao(AuditPersister auditPersister) { this.auditPersister = auditPersister; } /** * Returns the names of the groups that match the given query. * The virtual group "Anyone" may be returned as the value {@link DefaultGroups#ANYONE}. * * @return group names, sorted in alphabetical order */ public List<String> selectGroupNamesByQuery(DbSession dbSession, PermissionQuery query) { return mapper(dbSession).selectGroupNamesByQuery(query, new RowBounds(query.getPageOffset(), query.getPageSize())); } /** * Count the number of groups returned by {@link #selectGroupNamesByQuery(DbSession, PermissionQuery)}, * without applying pagination. */ public int countGroupsByQuery(DbSession dbSession, PermissionQuery query) { return mapper(dbSession).countGroupsByQuery(query); } /** * Select global or entity permission of given groups. Anyone virtual group is supported * through the value "zero" (0L) in {@code groupUuids}. */ public List<GroupPermissionDto> selectByGroupUuids(DbSession dbSession, List<String> groupUuids, @Nullable String entityUuid) { return executeLargeInputs(groupUuids, groups -> mapper(dbSession).selectByGroupUuids(groups, entityUuid)); } public List<String> selectProjectKeysWithAnyonePermissions(DbSession dbSession, int max) { return mapper(dbSession).selectProjectKeysWithAnyonePermissions(max); } public int countEntitiesWithAnyonePermissions(DbSession dbSession) { return mapper(dbSession).countEntitiesWithAnyonePermissions(); } /** * Select global and project permissions of a given group (Anyone group is NOT supported) * Each row returns a {@link GroupPermissionDto} */ public void selectAllPermissionsByGroupUuid(DbSession dbSession, String groupUuid, ResultHandler<GroupPermissionDto> resultHandler) { mapper(dbSession).selectAllPermissionsByGroupUuid(groupUuid, resultHandler); } /** * Each row returns a {@link CountPerEntityPermission} */ public void groupsCountByComponentUuidAndPermission(DbSession dbSession, List<String> entityUuids, ResultHandler<CountPerEntityPermission> resultHandler) { Map<String, Object> parameters = new HashMap<>(2); parameters.put(ANYONE_GROUP_PARAMETER, DefaultGroups.ANYONE); executeLargeInputsWithoutOutput( entityUuids, partitionedComponentUuids -> { parameters.put("entityUuids", partitionedComponentUuids); mapper(dbSession).groupsCountByEntityUuidAndPermission(parameters, resultHandler); }); } /** * Selects the global permissions granted to group. An empty list is returned if the * group does not exist. */ public List<String> selectGlobalPermissionsOfGroup(DbSession session, @Nullable String groupUuid) { return mapper(session).selectGlobalPermissionsOfGroup(groupUuid); } /** * Selects the permissions granted to group and entity. An empty list is returned if the * group or entity do not exist. */ public List<String> selectEntityPermissionsOfGroup(DbSession session, @Nullable String groupUuid, String entityUuid) { return mapper(session).selectEntityPermissionsOfGroup(groupUuid, entityUuid); } /** * Lists uuid of groups with at least one permission on the specified entity but which do not have the specified * permission, <strong>excluding group "AnyOne"</strong> (which implies the returned {@code Sett} can't contain * {@code null}). */ public Set<String> selectGroupUuidsWithPermissionOnEntityBut(DbSession session, String entityUuid, String permission) { return mapper(session).selectGroupUuidsWithPermissionOnEntityBut(entityUuid, permission); } /** * Lists group uuids that have the selected permission on the specified entity. */ public Set<String> selectGroupUuidsWithPermissionOnEntity(DbSession session, String entityUuid, String permission) { return mapper(session).selectGroupUuidsWithPermissionOnEntity(entityUuid, permission); } public void insert(DbSession dbSession, GroupPermissionDto groupPermissionDto, @Nullable EntityDto entityDto, @Nullable PermissionTemplateDto permissionTemplateDto) { mapper(dbSession).insert(groupPermissionDto); String componentKey = (entityDto != null) ? entityDto.getKey() : null; String qualifier = (entityDto != null) ? entityDto.getQualifier() : null; auditPersister.addGroupPermission(dbSession, new GroupPermissionNewValue(groupPermissionDto, componentKey, qualifier, permissionTemplateDto)); } /** * Delete all the permissions associated to a entity */ public void deleteByEntityUuid(DbSession dbSession, EntityDto entityDto) { int deletedRecords = mapper(dbSession).deleteByEntityUuid(entityDto.getUuid()); if (deletedRecords > 0) { auditPersister.deleteGroupPermission(dbSession, new GroupPermissionNewValue(entityDto.getUuid(), entityDto.getKey(), entityDto.getName(), null, null, null, entityDto.getQualifier())); } } /** * Delete all permissions of the specified group (group "AnyOne" if {@code groupUuid} is {@code null}) for the specified * entity. */ public int deleteByEntityAndGroupUuid(DbSession dbSession, @Nullable String groupUuid, EntityDto entityDto) { int deletedRecords = mapper(dbSession).deleteByEntityUuidAndGroupUuid(entityDto.getUuid(), groupUuid); if (deletedRecords > 0) { auditPersister.deleteGroupPermission(dbSession, new GroupPermissionNewValue(entityDto.getUuid(), entityDto.getKey(), entityDto.getName(), null, groupUuid, "", entityDto.getQualifier())); } return deletedRecords; } public int deleteByEntityUuidForAnyOne(DbSession dbSession, EntityDto entity) { int deletedRecords = mapper(dbSession).deleteByEntityUuidAndGroupUuid(entity.getUuid(), null); if (deletedRecords > 0) { auditPersister.deleteGroupPermission(dbSession, new GroupPermissionNewValue(entity.getUuid(), entity.getKey(), entity.getName(), null, null, null, entity.getQualifier())); } return deletedRecords; } /** * Delete the specified permission for the specified entity for any group (including group AnyOne). */ public int deleteByEntityAndPermission(DbSession dbSession, String permission, EntityDto entity) { int deletedRecords = mapper(dbSession).deleteByEntityUuidAndPermission(entity.getUuid(), permission); if (deletedRecords > 0) { auditPersister.deleteGroupPermission(dbSession, new GroupPermissionNewValue(entity.getUuid(), entity.getKey(), entity.getName(), permission, null, null, entity.getQualifier())); } return deletedRecords; } /** * Delete a single permission. It can be: * <ul> * <li>a global permission granted to a group</li> * <li>a global permission granted to anyone</li> * <li>a permission granted to a group for a entity</li> * <li>a permission granted to anyone for a entity</li> * </ul> * * @param dbSession * @param permission the kind of permission * @param groupUuid if null, then anyone, else uuid of group * @param entityDto if null, then global permission, otherwise the uuid of entity */ public void delete(DbSession dbSession, String permission, @Nullable String groupUuid, @Nullable String groupName, @Nullable EntityDto entityDto) { int deletedRecords = mapper(dbSession).delete(permission, groupUuid, entityDto != null ? entityDto.getUuid() : null); if (deletedRecords > 0) { String entityUuid = (entityDto != null) ? entityDto.getUuid() : null; String qualifier = (entityDto != null) ? entityDto.getQualifier() : null; String componentKey = (entityDto != null) ? entityDto.getKey() : null; String componentName = (entityDto != null) ? entityDto.getName() : null; auditPersister.deleteGroupPermission(dbSession, new GroupPermissionNewValue(entityUuid, componentKey, componentName, permission, groupUuid, groupName, qualifier)); } } private static GroupPermissionMapper mapper(DbSession session) { return session.getMapper(GroupPermissionMapper.class); } }
9,841
41.606061
168
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/permission/GroupPermissionDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.permission; import javax.annotation.Nullable; public class GroupPermissionDto { private String uuid; private String role; private String groupUuid; private String groupName; private String entityUuid; private String entityName; public String getUuid() { return uuid; } public GroupPermissionDto setUuid(String uuid) { this.uuid = uuid; return this; } public String getGroupUuid() { return groupUuid; } /** * Null when Anyone */ public GroupPermissionDto setGroupUuid(@Nullable String groupUuid) { this.groupUuid = groupUuid; return this; } @Nullable public String getEntityUuid() { return entityUuid; } public GroupPermissionDto setEntityUuid(@Nullable String entityUuid) { this.entityUuid = entityUuid; return this; } public String getRole() { return role; } public GroupPermissionDto setRole(String role) { this.role = role; return this; } @Nullable public String getGroupName() { return groupName; } public GroupPermissionDto setGroupName(@Nullable String groupName) { this.groupName = groupName; return this; } @Nullable public String getEntityName() { return entityName; } public GroupPermissionDto setEntityName(@Nullable String entityName) { this.entityName = entityName; return this; } }
2,220
23.141304
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/permission/GroupPermissionMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.permission; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; public interface GroupPermissionMapper { List<String> selectGroupNamesByQuery(@Param("query") PermissionQuery query, RowBounds rowBounds); int countGroupsByQuery(@Param("query") PermissionQuery query); List<GroupPermissionDto> selectByGroupUuids(@Param("groupUuids") List<String> groupUuids, @Nullable @Param("entityUuid") String entityUuid); void groupsCountByEntityUuidAndPermission(Map<String, Object> parameters, ResultHandler<CountPerEntityPermission> resultHandler); List<String> selectProjectKeysWithAnyonePermissions(int max); int countEntitiesWithAnyonePermissions(); void insert(GroupPermissionDto dto); int delete(@Param("permission") String permission, @Nullable @Param("groupUuid") String groupUuid, @Nullable @Param("entityUuid") String entityUuid); List<String> selectGlobalPermissionsOfGroup(@Nullable @Param("groupUuid") String groupUuid); List<String> selectEntityPermissionsOfGroup(@Nullable @Param("groupUuid") String groupUuid, @Param("entityUuid") String entityUuid); void selectAllPermissionsByGroupUuid(@Param("groupUuid") String groupUuid, ResultHandler<GroupPermissionDto> resultHandler); /** * Lists uuid of groups with at least one permission on the specified entity but which do not have the specified * permission, <strong>excluding group "AnyOne"</strong> (which implies the returned {@code Set} can't contain * {@code null}). */ Set<String> selectGroupUuidsWithPermissionOnEntityBut(@Param("entityUuid") String entityUuid, @Param("role") String permission); Set<String> selectGroupUuidsWithPermissionOnEntity(@Param("entityUuid") String entityUuid, @Param("role") String permission); int deleteByEntityUuid(@Param("entityUuid") String entityUuid); int deleteByEntityUuidAndGroupUuid(@Param("entityUuid") String entityUuid, @Nullable @Param("groupUuid") String groupUuid); int deleteByEntityUuidAndPermission(@Param("entityUuid") String entityUuid, @Param("permission") String permission); }
3,100
43.942029
151
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/permission/PermissionQuery.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.permission; import java.util.Locale; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import org.sonar.db.WildcardPosition; import org.sonar.db.component.ComponentDto; import org.sonar.db.entity.EntityDto; import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.base.Preconditions.checkArgument; import static org.apache.commons.lang.StringUtils.defaultIfBlank; import static org.sonar.api.utils.Paging.offset; import static org.sonar.db.DaoUtils.buildLikeValue; /** * Query used to get users and groups permissions */ @Immutable public class PermissionQuery { public static final int RESULTS_MAX_SIZE = 100; public static final int SEARCH_QUERY_MIN_LENGTH = 3; public static final int DEFAULT_PAGE_SIZE = 20; public static final int DEFAULT_PAGE_INDEX = 1; // filter: return only the users or groups who have this permission private final String permission; // filter on project, else filter org permissions private final String entityUuid; // filter on login, email or name of users or groups private final String searchQuery; private final String searchQueryToSql; private final String searchQueryToSqlLowercase; // filter users or groups who have at least one permission. It does make // sense when the filter "permission" is set. private final boolean withAtLeastOnePermission; private final int pageSize; private final int pageOffset; private PermissionQuery(Builder builder) { this.permission = builder.permission; this.withAtLeastOnePermission = builder.withAtLeastOnePermission; this.entityUuid = builder.entityUuid; this.searchQuery = builder.searchQuery; this.searchQueryToSql = builder.searchQuery == null ? null : buildLikeValue(builder.searchQuery, WildcardPosition.BEFORE_AND_AFTER); this.searchQueryToSqlLowercase = searchQueryToSql == null ? null : searchQueryToSql.toLowerCase(Locale.ENGLISH); this.pageSize = builder.pageSize; this.pageOffset = offset(builder.pageIndex, builder.pageSize); } @CheckForNull public String getPermission() { return permission; } public boolean withAtLeastOnePermission() { return withAtLeastOnePermission; } @CheckForNull public String getEntityUuid() { return entityUuid; } @CheckForNull public String getSearchQuery() { return searchQuery; } @CheckForNull public String getSearchQueryToSql() { return searchQueryToSql; } @CheckForNull public String getSearchQueryToSqlLowercase() { return searchQueryToSqlLowercase; } public int getPageSize() { return pageSize; } public int getPageOffset() { return pageOffset; } public static Builder builder() { return new Builder(); } public static class Builder { private String permission; private String entityUuid; private String searchQuery; private boolean withAtLeastOnePermission; private Integer pageIndex; private Integer pageSize; private Builder() { // enforce method constructor } public Builder setPermission(@Nullable String permission) { this.withAtLeastOnePermission = permission != null; this.permission = permission; return this; } public Builder setEntity(ComponentDto component) { return setEntityUuid(component.uuid()); } public Builder setEntity(EntityDto entity) { return setEntityUuid(entity.getUuid()); } public Builder setEntityUuid(String entityUuid) { this.entityUuid = entityUuid; return this; } public Builder setSearchQuery(@Nullable String s) { this.searchQuery = defaultIfBlank(s, null); return this; } public Builder setPageIndex(@Nullable Integer i) { this.pageIndex = i; return this; } public Builder setPageSize(@Nullable Integer i) { this.pageSize = i; return this; } public Builder withAtLeastOnePermission() { this.withAtLeastOnePermission = true; return this; } public PermissionQuery build() { this.pageIndex = firstNonNull(pageIndex, DEFAULT_PAGE_INDEX); this.pageSize = firstNonNull(pageSize, DEFAULT_PAGE_SIZE); checkArgument(searchQuery == null || searchQuery.length() >= SEARCH_QUERY_MIN_LENGTH, "Search query should contains at least %s characters", SEARCH_QUERY_MIN_LENGTH); return new PermissionQuery(this); } } }
5,336
29.497143
172
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/permission/UserPermissionDao.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.permission; import com.google.common.annotations.VisibleForTesting; import java.util.Collection; import java.util.List; import java.util.Set; import javax.annotation.Nullable; import org.sonar.db.Dao; import org.sonar.db.DatabaseUtils; import org.sonar.db.DbSession; import org.sonar.db.audit.AuditPersister; import org.sonar.db.audit.model.UserPermissionNewValue; import org.sonar.db.entity.EntityDto; import org.sonar.db.permission.template.PermissionTemplateDto; import org.sonar.db.user.UserId; import org.sonar.db.user.UserIdDto; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Collections.emptyList; import static org.sonar.db.DatabaseUtils.executeLargeInputs; public class UserPermissionDao implements Dao { private final AuditPersister auditPersister; public UserPermissionDao(AuditPersister auditPersister) { this.auditPersister = auditPersister; } /** * List of user permissions ordered by alphabetical order of user names. * Pagination is NOT applied. * No sort is done. * * @param query non-null query including optional filters. * @param userUuids Filter on user ids, including disabled users. Must not be empty and maximum size is {@link DatabaseUtils#PARTITION_SIZE_FOR_ORACLE}. */ public List<UserPermissionDto> selectUserPermissionsByQuery(DbSession dbSession, PermissionQuery query, Collection<String> userUuids) { if (userUuids.isEmpty()) { return emptyList(); } checkArgument(userUuids.size() <= DatabaseUtils.PARTITION_SIZE_FOR_ORACLE, "Maximum 1'000 users are accepted"); return mapper(dbSession).selectUserPermissionsByQueryAndUserUuids(query, userUuids); } public List<String> selectUserUuidsByQuery(DbSession dbSession, PermissionQuery query) { return paginate(mapper(dbSession).selectUserUuidsByQuery(query), query); } public List<String> selectUserUuidsByQueryAndScope(DbSession dbSession, PermissionQuery query) { return paginate(mapper(dbSession).selectUserUuidsByQueryAndScope(query), query); } private static List<String> paginate(List<String> results, PermissionQuery query) { return results .stream() // Pagination is done in Java because it's too complex to use SQL pagination in Oracle and MsSQL with the distinct .skip(query.getPageOffset()) .limit(query.getPageSize()) .toList(); } public int countUsersByQuery(DbSession dbSession, PermissionQuery query) { return mapper(dbSession).countUsersByQuery(query); } /** * Count the number of users per permission for a given list of entities * * @param entityUuids a non-null list of entity uuids to filter on. If empty then an empty list is returned. */ @VisibleForTesting List<CountPerEntityPermission> countUsersByEntityPermission(DbSession dbSession, Collection<String> entityUuids) { return executeLargeInputs(entityUuids, mapper(dbSession)::countUsersByEntityPermission); } /** * Gets all the global permissions granted to user * * @return the global permissions. An empty list is returned if user do not exist. */ public List<String> selectGlobalPermissionsOfUser(DbSession dbSession, String userUuid) { return mapper(dbSession).selectGlobalPermissionsOfUser(userUuid); } /** * Gets all the entity permissions granted to user for the specified entity. * * @return the entity permissions. An empty list is returned if entity or user do not exist. */ public List<String> selectEntityPermissionsOfUser(DbSession dbSession, String userUuid, String entityUuid) { return mapper(dbSession).selectEntityPermissionsOfUser(userUuid, entityUuid); } public Set<UserIdDto> selectUserIdsWithPermissionOnEntityBut(DbSession session, String entityUuid, String permission) { return mapper(session).selectUserIdsWithPermissionOnEntityBut(entityUuid, permission); } public void insert(DbSession dbSession, UserPermissionDto dto, @Nullable EntityDto entityDto, @Nullable UserId userId, @Nullable PermissionTemplateDto templateDto) { mapper(dbSession).insert(dto); String entityName = (entityDto != null) ? entityDto.getName() : null; String entityKey = (entityDto != null) ? entityDto.getKey() : null; String entityQualifier = (entityDto != null) ? entityDto.getQualifier() : null; auditPersister.addUserPermission(dbSession, new UserPermissionNewValue(dto, entityKey, entityName, userId, entityQualifier, templateDto)); } /** * Removes a single global permission from user */ public void deleteGlobalPermission(DbSession dbSession, UserId user, String permission) { int deletedRows = mapper(dbSession).deleteGlobalPermission(user.getUuid(), permission); if (deletedRows > 0) { auditPersister.deleteUserPermission(dbSession, new UserPermissionNewValue(permission, null, null, null, user, null)); } } /** * Removes a single entity permission from user */ public void deleteEntityPermission(DbSession dbSession, UserId user, String permission, EntityDto entity) { int deletedRows = mapper(dbSession).deleteEntityPermission(user.getUuid(), permission, entity.getUuid()); if (deletedRows > 0) { auditPersister.deleteUserPermission(dbSession, new UserPermissionNewValue(permission, entity.getUuid(), entity.getKey(), entity.getName(), user, entity.getQualifier())); } } /** * Deletes all the permissions defined on an entity */ public void deleteEntityPermissions(DbSession dbSession, EntityDto entity) { int deletedRows = mapper(dbSession).deleteEntityPermissions(entity.getUuid()); if (deletedRows > 0) { auditPersister.deleteUserPermission(dbSession, new UserPermissionNewValue(null, entity.getUuid(), entity.getKey(), entity.getName(), null, entity.getQualifier())); } } /** * Deletes the specified permission on the specified entity for any user. */ public int deleteEntityPermissionOfAnyUser(DbSession dbSession, String permission, EntityDto entity) { int deletedRows = mapper(dbSession).deleteEntityPermissionOfAnyUser(entity.getUuid(), permission); if (deletedRows > 0) { auditPersister.deleteUserPermission(dbSession, new UserPermissionNewValue(permission, entity.getUuid(), entity.getKey(), entity.getName(), null, entity.getQualifier())); } return deletedRows; } public void deleteByUserUuid(DbSession dbSession, UserId userId) { int deletedRows = mapper(dbSession).deleteByUserUuid(userId.getUuid()); if (deletedRows > 0) { auditPersister.deleteUserPermission(dbSession, new UserPermissionNewValue(userId, null)); } } private static UserPermissionMapper mapper(DbSession dbSession) { return dbSession.getMapper(UserPermissionMapper.class); } }
7,653
39.712766
175
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/permission/UserPermissionDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.permission; import javax.annotation.CheckForNull; import javax.annotation.Nullable; public class UserPermissionDto { private String uuid; private String permission; private String userUuid; private String entityUuid; public UserPermissionDto() { // used by MyBatis } public UserPermissionDto(String uuid, String permission, String userUuid, @Nullable String entityUuid) { this.uuid = uuid; this.permission = permission; this.userUuid = userUuid; this.entityUuid = entityUuid; } public String getUuid() { return uuid; } public String getPermission() { return permission; } public String getUserUuid() { return userUuid; } /** * @return {@code null} if it's a global permission, otherwise return the entity uiid. */ @CheckForNull public String getEntityUuid() { return entityUuid; } @Override public String toString() { StringBuilder sb = new StringBuilder("UserPermissionDto{"); sb.append("permission='").append(permission).append('\''); sb.append(", userUuid=").append(userUuid); sb.append(", entityUuid=").append(entityUuid); sb.append('}'); return sb.toString(); } }
2,050
27.486111
106
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/permission/UserPermissionMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.permission; import java.util.Collection; import java.util.List; import java.util.Set; import org.apache.ibatis.annotations.Param; import org.sonar.db.user.UserIdDto; public interface UserPermissionMapper { List<UserPermissionDto> selectUserPermissionsByQueryAndUserUuids(@Param("query") PermissionQuery query, @Param("userUuids") Collection<String> userUuids); List<String> selectUserUuidsByQuery(@Param("query") PermissionQuery query); /** * Fetch user ids based on permission query and only in a specific scope (global permissions only or entity permissions only) */ List<String> selectUserUuidsByQueryAndScope(@Param("query") PermissionQuery query); /** * Count the number of distinct users returned by {@link #selectUserUuidsByQuery(PermissionQuery)} * {@link PermissionQuery#getPageOffset()} and {@link PermissionQuery#getPageSize()} are ignored. */ int countUsersByQuery(@Param("query") PermissionQuery query); /** * Count the number of users per permission for a given list of entities. * @param entityUuids a non-null and non-empty list of entities uuids */ List<CountPerEntityPermission> countUsersByEntityPermission(@Param("entityUuids") List<String> entityUuids); /** * select id of users with at least one permission on the specified entity but which do not have the specified permission. */ Set<UserIdDto> selectUserIdsWithPermissionOnEntityBut(@Param("entityUuid") String entityUuid, @Param("permission") String permission); void insert(@Param("dto")UserPermissionDto dto); int deleteGlobalPermission(@Param("userUuid") String userUuid, @Param("permission") String permission); int deleteEntityPermission(@Param("userUuid") String userUuid, @Param("permission") String permission, @Param("entityUuid") String entityUuid); int deleteEntityPermissions(@Param("entityUuid") String entityUuid); int deleteEntityPermissionOfAnyUser(@Param("entityUuid") String entityUuid, @Param("permission") String permission); List<String> selectGlobalPermissionsOfUser(@Param("userUuid") String userUuid); List<String> selectEntityPermissionsOfUser(@Param("userUuid") String userUuid, @Param("entityUuid") String entityUuid); int deleteByUserUuid(@Param("userUuid") String userUuid); }
3,132
41.917808
156
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/permission/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.db.permission; import javax.annotation.ParametersAreNonnullByDefault;
964
37.6
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/permission/template/CountByTemplateAndPermissionDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.permission.template; public class CountByTemplateAndPermissionDto { private String templateUuid; private String permission; private int count; public String getTemplateUuid() { return templateUuid; } public void setTemplateUuid(String templateUuid) { this.templateUuid = templateUuid; } public String getPermission() { return permission; } public void setPermission(String permission) { this.permission = permission; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } }
1,442
27.294118
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/permission/template/DefaultTemplates.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.permission.template; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import static java.util.Objects.requireNonNull; public class DefaultTemplates { // Hold the template uuid for new projects private String projectUuid; // Hold the template uuid for new applications private String applicationsUuid; // Hold the template uuid for new portfolios private String portfoliosUuid; public DefaultTemplates() { // nothing to do here } public String getProjectUuid() { checkProjectNotNull(this.projectUuid); return this.projectUuid; } public DefaultTemplates setProjectUuid(String projectUuid) { checkProjectNotNull(projectUuid); this.projectUuid = projectUuid; return this; } private static void checkProjectNotNull(String project) { requireNonNull(project, "defaultTemplates.project can't be null"); } @CheckForNull public String getApplicationsUuid() { return applicationsUuid; } public DefaultTemplates setApplicationsUuid(@Nullable String applicationsUuid) { this.applicationsUuid = applicationsUuid; return this; } @CheckForNull public String getPortfoliosUuid() { return portfoliosUuid; } public DefaultTemplates setPortfoliosUuid(@Nullable String portfoliosUuid) { this.portfoliosUuid = portfoliosUuid; return this; } @Override public String toString() { return "DefaultTemplates{" + "projectUuid='" + projectUuid + '\'' + ", portfoliosUuid='" + portfoliosUuid + '\'' + ", applicationsUuid='" + applicationsUuid + '\'' + '}'; } }
2,464
28.698795
82
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/permission/template/PermissionTemplateCharacteristicDao.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.permission.template; import java.util.List; import java.util.Optional; import org.sonar.db.Dao; import org.sonar.db.DbSession; import org.sonar.db.audit.AuditPersister; import org.sonar.db.audit.model.PermissionTemplateNewValue; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Objects.requireNonNull; import static org.sonar.db.DatabaseUtils.executeLargeInputs; public class PermissionTemplateCharacteristicDao implements Dao { private final AuditPersister auditPersister; public PermissionTemplateCharacteristicDao(AuditPersister auditPersister) { this.auditPersister = auditPersister; } public List<PermissionTemplateCharacteristicDto> selectByTemplateUuids(DbSession dbSession, List<String> templateUuids) { return executeLargeInputs(templateUuids, partitionOfTemplateUuids -> mapper(dbSession).selectByTemplateUuids(partitionOfTemplateUuids)); } public Optional<PermissionTemplateCharacteristicDto> selectByPermissionAndTemplateId(DbSession dbSession, String permission, String templateUuid) { PermissionTemplateCharacteristicDto dto = mapper(dbSession).selectByPermissionAndTemplateUuid(permission, templateUuid); return Optional.ofNullable(dto); } public PermissionTemplateCharacteristicDto insert(DbSession dbSession, PermissionTemplateCharacteristicDto dto, String templateName) { checkArgument(dto.getCreatedAt() != 0L && dto.getUpdatedAt() != 0L); mapper(dbSession).insert(dto); auditPersister.addCharacteristicToPermissionTemplate(dbSession, new PermissionTemplateNewValue(dto.getTemplateUuid(), dto.getPermission(), templateName, dto.getWithProjectCreator())); return dto; } public PermissionTemplateCharacteristicDto update(DbSession dbSession, PermissionTemplateCharacteristicDto templatePermissionDto, String templateName) { requireNonNull(templatePermissionDto.getUuid()); mapper(dbSession).update(templatePermissionDto); auditPersister.updateCharacteristicInPermissionTemplate(dbSession, new PermissionTemplateNewValue(templatePermissionDto.getTemplateUuid(), templatePermissionDto.getPermission(), templateName, templatePermissionDto.getWithProjectCreator())); return templatePermissionDto; } private static PermissionTemplateCharacteristicMapper mapper(DbSession dbSession) { return dbSession.getMapper(PermissionTemplateCharacteristicMapper.class); } }
3,286
43.418919
149
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/permission/template/PermissionTemplateCharacteristicDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.permission.template; import static com.google.common.base.Preconditions.checkArgument; public class PermissionTemplateCharacteristicDto { private static final int MAX_PERMISSION_KEY_LENGTH = 64; private String uuid; private String templateUuid; private String permission; private boolean withProjectCreator; private long createdAt; private long updatedAt; public String getUuid() { return uuid; } public PermissionTemplateCharacteristicDto setUuid(String uuid) { this.uuid = uuid; return this; } public String getTemplateUuid() { return templateUuid; } public PermissionTemplateCharacteristicDto setTemplateUuid(String templateUuid) { this.templateUuid = templateUuid; return this; } public String getPermission() { return permission; } public PermissionTemplateCharacteristicDto setPermission(String permission) { checkArgument(permission.length() <= MAX_PERMISSION_KEY_LENGTH, "Permission key length (%s) is longer than the maximum authorized (%s). '%s' was provided.", permission.length(), MAX_PERMISSION_KEY_LENGTH, permission); this.permission = permission; return this; } public boolean getWithProjectCreator() { return withProjectCreator; } public PermissionTemplateCharacteristicDto setWithProjectCreator(boolean withProjectCreator) { this.withProjectCreator = withProjectCreator; return this; } public long getCreatedAt() { return createdAt; } public PermissionTemplateCharacteristicDto setCreatedAt(long createdAt) { this.createdAt = createdAt; return this; } public long getUpdatedAt() { return updatedAt; } public PermissionTemplateCharacteristicDto setUpdatedAt(long updatedAt) { this.updatedAt = updatedAt; return this; } }
2,662
28.263736
160
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/permission/template/PermissionTemplateCharacteristicMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.permission.template; import java.util.List; import org.apache.ibatis.annotations.Param; public interface PermissionTemplateCharacteristicMapper { PermissionTemplateCharacteristicDto selectByUuid(@Param("uuid") String uuid); List<PermissionTemplateCharacteristicDto> selectByTemplateUuids(@Param("templateUuids") List<String> templateUuids); PermissionTemplateCharacteristicDto selectByPermissionAndTemplateUuid(@Param("permission") String permission, @Param("templateUuid") String templateUuid); void insert(PermissionTemplateCharacteristicDto templatePermissionDto); void update(PermissionTemplateCharacteristicDto templatePermissionDto); void deleteByTemplateUuid(String uuid); void deleteByTemplateUuids(@Param("templateUuids") List<String> subList); }
1,643
39.097561
156
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/permission/template/PermissionTemplateDao.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.permission.template; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import org.sonar.api.utils.System2; import org.sonar.core.util.UuidFactory; import org.sonar.db.Dao; import org.sonar.db.DbSession; import org.sonar.db.audit.AuditPersister; import org.sonar.db.audit.model.PermissionTemplateNewValue; import org.sonar.db.permission.CountPerEntityPermission; import org.sonar.db.permission.PermissionQuery; import static java.lang.String.format; import static org.sonar.api.security.DefaultGroups.ANYONE; import static org.sonar.db.DatabaseUtils.executeLargeInputs; import static org.sonar.db.DatabaseUtils.executeLargeInputsWithoutOutput; public class PermissionTemplateDao implements Dao { private static final String ANYONE_GROUP_PARAMETER = "anyoneGroup"; private final System2 system; private final UuidFactory uuidFactory; private final AuditPersister auditPersister; public PermissionTemplateDao(UuidFactory uuidFactory, System2 system, AuditPersister auditPersister) { this.uuidFactory = uuidFactory; this.system = system; this.auditPersister = auditPersister; } /** * @return a paginated list of user logins. */ public List<String> selectUserLoginsByQueryAndTemplate(DbSession session, PermissionQuery query, String templateUuid) { return mapper(session).selectUserLoginsByQueryAndTemplate(query, templateUuid, new RowBounds(query.getPageOffset(), query.getPageSize())); } public int countUserLoginsByQueryAndTemplate(DbSession session, PermissionQuery query, String templateUuid) { return mapper(session).countUserLoginsByQueryAndTemplate(query, templateUuid); } public List<PermissionTemplateUserDto> selectUserPermissionsByTemplateIdAndUserLogins(DbSession dbSession, String templateUuid, List<String> logins) { return executeLargeInputs(logins, l -> mapper(dbSession).selectUserPermissionsByTemplateUuidAndUserLogins(templateUuid, l)); } public List<PermissionTemplateUserDto> selectUserPermissionsByTemplateId(DbSession dbSession, String templateUuid) { return mapper(dbSession).selectUserPermissionsByTemplateUuidAndUserLogins(templateUuid, Collections.emptyList()); } public List<String> selectGroupNamesByQueryAndTemplate(DbSession session, PermissionQuery query, String templateUuid) { return mapper(session).selectGroupNamesByQueryAndTemplate(templateUuid, query, new RowBounds(query.getPageOffset(), query.getPageSize())); } public int countGroupNamesByQueryAndTemplate(DbSession session, PermissionQuery query, String templateUuid) { return mapper(session).countGroupNamesByQueryAndTemplate(query, templateUuid); } public List<PermissionTemplateGroupDto> selectGroupPermissionsByTemplateIdAndGroupNames(DbSession dbSession, String templateUuid, List<String> groups) { return executeLargeInputs(groups, g -> mapper(dbSession).selectGroupPermissionsByTemplateUuidAndGroupNames(templateUuid, g)); } public List<PermissionTemplateGroupDto> selectGroupPermissionsByTemplateUuid(DbSession dbSession, String templateUuid) { return mapper(dbSession).selectGroupPermissionsByTemplateUuidAndGroupNames(templateUuid, Collections.emptyList()); } /** * @return {@code true} if template contains groups that are granted with {@code permission}, else {@code false} */ public boolean hasGroupsWithPermission(DbSession dbSession, String templateUuid, String permission, @Nullable String groupUuid) { return mapper(dbSession).countGroupsWithPermission(templateUuid, permission, groupUuid) > 0; } @CheckForNull public PermissionTemplateDto selectByUuid(DbSession session, String templateUuid) { return mapper(session).selectByUuid(templateUuid); } public List<PermissionTemplateDto> selectAll(DbSession session, @Nullable String nameMatch) { String upperCaseNameLikeSql = nameMatch != null ? toUppercaseSqlQuery(nameMatch) : null; return mapper(session).selectAll(upperCaseNameLikeSql); } private static String toUppercaseSqlQuery(String nameMatch) { String wildcard = "%"; return format("%s%s%s", wildcard, nameMatch.toUpperCase(Locale.ENGLISH), wildcard); } public PermissionTemplateDto insert(DbSession session, PermissionTemplateDto dto) { if (dto.getUuid() == null) { dto.setUuid(uuidFactory.create()); } mapper(session).insert(dto); auditPersister.addPermissionTemplate(session, new PermissionTemplateNewValue(dto.getUuid(), dto.getName())); return dto; } /** * Each row returns a #{@link CountPerEntityPermission} */ public void usersCountByTemplateUuidAndPermission(DbSession dbSession, List<String> templateUuids, ResultHandler<CountByTemplateAndPermissionDto> resultHandler) { Map<String, Object> parameters = new HashMap<>(1); executeLargeInputsWithoutOutput( templateUuids, partitionedTemplateUuids -> { parameters.put("templateUuids", partitionedTemplateUuids); mapper(dbSession).usersCountByTemplateUuidAndPermission(parameters, resultHandler); }); } /** * Each row returns a #{@link CountPerEntityPermission} */ public void groupsCountByTemplateUuidAndPermission(DbSession dbSession, List<String> templateUuids, ResultHandler<CountByTemplateAndPermissionDto> resultHandler) { Map<String, Object> parameters = new HashMap<>(2); parameters.put(ANYONE_GROUP_PARAMETER, ANYONE); executeLargeInputsWithoutOutput( templateUuids, partitionedTemplateUuids -> { parameters.put("templateUuids", partitionedTemplateUuids); mapper(dbSession).groupsCountByTemplateUuidAndPermission(parameters, resultHandler); }); } public List<PermissionTemplateGroupDto> selectAllGroupPermissionTemplatesByGroupUuid(DbSession dbSession, String groupUuid) { return mapper(dbSession).selectAllGroupPermissionTemplatesByGroupUuid(groupUuid); } public void deleteByUuid(DbSession session, String templateUuid, String templateName) { PermissionTemplateMapper mapper = mapper(session); mapper.deleteUserPermissionsByTemplateUuid(templateUuid); mapper.deleteGroupPermissionsByTemplateUuid(templateUuid); session.getMapper(PermissionTemplateCharacteristicMapper.class).deleteByTemplateUuid(templateUuid); int deletedRows = mapper.deleteByUuid(templateUuid); if (deletedRows > 0) { auditPersister.deletePermissionTemplate(session, new PermissionTemplateNewValue(templateUuid, templateName)); } } public PermissionTemplateDto update(DbSession session, PermissionTemplateDto permissionTemplate) { mapper(session).update(permissionTemplate); auditPersister.updatePermissionTemplate(session, new PermissionTemplateNewValue(permissionTemplate)); return permissionTemplate; } public void insertUserPermission(DbSession session, String templateUuid, String userUuid, String permission, String templateName, String userLogin) { PermissionTemplateUserDto permissionTemplateUser = new PermissionTemplateUserDto() .setUuid(uuidFactory.create()) .setTemplateUuid(templateUuid) .setUserUuid(userUuid) .setPermission(permission) .setCreatedAt(now()) .setUpdatedAt(now()); mapper(session).insertUserPermission(permissionTemplateUser); auditPersister.addUserToPermissionTemplate(session, new PermissionTemplateNewValue(templateUuid, templateName, permission, userUuid, userLogin, null, null)); session.commit(); } public void deleteUserPermission(DbSession session, String templateUuid, String userUuid, String permission, String templateName, String userLogin) { PermissionTemplateUserDto permissionTemplateUser = new PermissionTemplateUserDto() .setTemplateUuid(templateUuid) .setPermission(permission) .setUserUuid(userUuid); int deletedRows = mapper(session).deleteUserPermission(permissionTemplateUser); if (deletedRows > 0) { auditPersister.deleteUserFromPermissionTemplate(session, new PermissionTemplateNewValue(templateUuid, templateName, permission, userUuid, userLogin, null, null)); } session.commit(); } public void deleteUserPermissionsByUserUuid(DbSession dbSession, String userUuid, String userLogin) { int deletedRows = mapper(dbSession).deleteUserPermissionsByUserUuid(userUuid); if (deletedRows > 0) { auditPersister.deleteUserFromPermissionTemplate(dbSession, new PermissionTemplateNewValue(null, null, null, userUuid, userLogin, null, null)); } } public void insertGroupPermission(DbSession session, String templateUuid, @Nullable String groupUuid, String permission, String templateName, @Nullable String groupName) { PermissionTemplateGroupDto permissionTemplateGroup = new PermissionTemplateGroupDto() .setUuid(uuidFactory.create()) .setTemplateUuid(templateUuid) .setPermission(permission) .setGroupUuid(groupUuid) .setCreatedAt(now()) .setUpdatedAt(now()); mapper(session).insertGroupPermission(permissionTemplateGroup); auditPersister.addGroupToPermissionTemplate(session, new PermissionTemplateNewValue(templateUuid, templateName, permission, null, null, groupUuid, groupName)); } public void insertGroupPermission(DbSession session, PermissionTemplateGroupDto permissionTemplateGroup, String templateName) { mapper(session).insertGroupPermission(permissionTemplateGroup); auditPersister.addGroupToPermissionTemplate(session, new PermissionTemplateNewValue(permissionTemplateGroup.getTemplateUuid(), templateName, permissionTemplateGroup.getPermission(), null, null, permissionTemplateGroup.getGroupUuid(), permissionTemplateGroup.getGroupName())); } public void deleteGroupPermission(DbSession session, String templateUuid, @Nullable String groupUuid, String permission, String templateName, @Nullable String groupName) { PermissionTemplateGroupDto permissionTemplateGroup = new PermissionTemplateGroupDto() .setTemplateUuid(templateUuid) .setPermission(permission) .setGroupUuid(groupUuid); int deletedRows = mapper(session).deleteGroupPermission(permissionTemplateGroup); if (deletedRows > 0) { auditPersister.deleteGroupFromPermissionTemplate(session, new PermissionTemplateNewValue(permissionTemplateGroup.getTemplateUuid(), templateName, permissionTemplateGroup.getPermission(), null, null, permissionTemplateGroup.getGroupUuid(), groupName)); } session.commit(); } public PermissionTemplateDto selectByName(DbSession dbSession, String name) { return mapper(dbSession).selectByName(name.toUpperCase(Locale.ENGLISH)); } public List<String> selectPotentialPermissionsByUserUuidAndTemplateUuid(DbSession dbSession, @Nullable String currentUserUuid, String templateUuid) { return mapper(dbSession).selectPotentialPermissionsByUserUuidAndTemplateUuid(currentUserUuid, templateUuid); } /** * Remove a group from all templates (used when removing a group) */ public void deleteByGroup(DbSession session, String groupUuid, String groupName) { int deletedRows = session.getMapper(PermissionTemplateMapper.class).deleteByGroupUuid(groupUuid); if (deletedRows > 0) { auditPersister.deleteGroupFromPermissionTemplate(session, new PermissionTemplateNewValue(null, null, null, null, null, groupUuid, groupName)); } } private Date now() { return new Date(system.now()); } private static PermissionTemplateMapper mapper(DbSession session) { return session.getMapper(PermissionTemplateMapper.class); } }
12,645
43.843972
168
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/permission/template/PermissionTemplateDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.permission.template; import java.util.Date; import javax.annotation.CheckForNull; import javax.annotation.Nullable; public class PermissionTemplateDto { private String name; private String uuid; private String description; private String keyPattern; private Date createdAt; private Date updatedAt; public String getName() { return name; } public PermissionTemplateDto setName(String name) { this.name = name; return this; } /** * @since 5.2 the kee column is a proper uuid. Before that it was build on the name + timestamp */ public String getUuid() { return uuid; } /** * @since 5.2 the kee column is a proper uuid. Before it was build on the name + timestamp */ public PermissionTemplateDto setUuid(String uuid) { this.uuid = uuid; return this; } @CheckForNull public String getDescription() { return description; } public PermissionTemplateDto setDescription(@Nullable String description) { this.description = description; return this; } @CheckForNull public String getKeyPattern() { return keyPattern; } public PermissionTemplateDto setKeyPattern(@Nullable String regexp) { this.keyPattern = regexp; return this; } public Date getCreatedAt() { return createdAt; } public PermissionTemplateDto setCreatedAt(Date createdAt) { this.createdAt = createdAt; return this; } public Date getUpdatedAt() { return updatedAt; } public PermissionTemplateDto setUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; return this; } }
2,455
24.583333
97
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/permission/template/PermissionTemplateGroupDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.permission.template; import java.util.Date; import javax.annotation.Nullable; public class PermissionTemplateGroupDto { private String uuid; private String templateUuid; private String groupUuid; private String permission; private String groupName; private Date createdAt; private Date updatedAt; public String getUuid() { return uuid; } public PermissionTemplateGroupDto setUuid(String uuid) { this.uuid = uuid; return this; } public String getTemplateUuid() { return templateUuid; } public PermissionTemplateGroupDto setTemplateUuid(String templateUuid) { this.templateUuid = templateUuid; return this; } public String getGroupUuid() { return groupUuid; } public PermissionTemplateGroupDto setGroupUuid(@Nullable String groupUuid) { this.groupUuid = groupUuid; return this; } public String getPermission() { return permission; } public PermissionTemplateGroupDto setPermission(String permission) { this.permission = permission; return this; } public String getGroupName() { return groupName; } public PermissionTemplateGroupDto setGroupName(String groupName) { this.groupName = groupName; return this; } public Date getCreatedAt() { return createdAt; } public PermissionTemplateGroupDto setCreatedAt(Date createdAt) { this.createdAt = createdAt; return this; } public Date getUpdatedAt() { return updatedAt; } public PermissionTemplateGroupDto setUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; return this; } }
2,456
24.329897
78
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/permission/template/PermissionTemplateMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.permission.template; import java.util.List; import java.util.Map; import javax.annotation.Nullable; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import org.sonar.db.permission.PermissionQuery; /** * @since 3.7 */ public interface PermissionTemplateMapper { void insert(PermissionTemplateDto permissionTemplate); void update(PermissionTemplateDto permissionTemplate); int deleteByUuid(String templateUuid); void deleteUserPermissionsByTemplateUuid(String templateUuid); int deleteUserPermissionsByUserUuid(@Param("userUuid") String userUuid); int deleteUserPermission(PermissionTemplateUserDto permissionTemplateUser); void deleteGroupPermissionsByTemplateUuid(String templateUuid); int deleteGroupPermission(PermissionTemplateGroupDto permissionTemplateGroup); PermissionTemplateDto selectByUuid(String templateUuid); List<PermissionTemplateUserDto> selectUserPermissionsByTemplateUuidAndUserLogins(@Param("templateUuid") String templateUuid, @Param("logins") List<String> logins); List<PermissionTemplateGroupDto> selectGroupPermissionsByTemplateUuidAndGroupNames(@Param("templateUuid") String templateUuid, @Param("groups") List<String> groups); void insertUserPermission(PermissionTemplateUserDto permissionTemplateUser); void insertGroupPermission(PermissionTemplateGroupDto permissionTemplateGroup); int deleteByGroupUuid(String groupUuid); PermissionTemplateDto selectByName(@Param("name") String name); List<String> selectUserLoginsByQueryAndTemplate(@Param("query") PermissionQuery query, @Param("templateUuid") String templateUuid, RowBounds rowBounds); int countUserLoginsByQueryAndTemplate(@Param("query") PermissionQuery query, @Param("templateUuid") String templateUuid); List<String> selectGroupNamesByQueryAndTemplate(@Param("templateUuid") String templateUuid, @Param("query") PermissionQuery query, RowBounds rowBounds); int countGroupNamesByQueryAndTemplate(@Param("query") PermissionQuery query, @Param("templateUuid") String templateUuid); List<PermissionTemplateDto> selectAll(@Nullable @Param("upperCaseNameLikeSql") String upperCaseNameLikeSql); void usersCountByTemplateUuidAndPermission(Map<String, Object> parameters, ResultHandler<CountByTemplateAndPermissionDto> resultHandler); void groupsCountByTemplateUuidAndPermission(Map<String, Object> parameters, ResultHandler<CountByTemplateAndPermissionDto> resultHandler); List<String> selectPotentialPermissionsByUserUuidAndTemplateUuid(@Param("userUuid") @Nullable String currentUserUuid, @Param("templateUuid") String templateUuid); int countGroupsWithPermission(@Param("templateUuid") String templateUuid, @Param("permission") String permission, @Nullable @Param("groupUuid") String groupUuid); List<PermissionTemplateGroupDto> selectAllGroupPermissionTemplatesByGroupUuid(@Param("groupUuid") String groupUuid); }
3,826
43.5
167
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/permission/template/PermissionTemplateUserDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.db.permission.template; import java.util.Date; public class PermissionTemplateUserDto { private String uuid; private String templateUuid; private String userUuid; private String permission; private String userName; private String userLogin; private Date createdAt; private Date updatedAt; public String getUuid() { return uuid; } public PermissionTemplateUserDto setUuid(String uuid) { this.uuid = uuid; return this; } public String getTemplateUuid() { return templateUuid; } public PermissionTemplateUserDto setTemplateUuid(String templateUuid) { this.templateUuid = templateUuid; return this; } public String getUserUuid() { return userUuid; } public PermissionTemplateUserDto setUserUuid(String userUuid) { this.userUuid = userUuid; return this; } public String getUserName() { return userName; } public PermissionTemplateUserDto setUserName(String userName) { this.userName = userName; return this; } public String getUserLogin() { return userLogin; } public PermissionTemplateUserDto setUserLogin(String userLogin) { this.userLogin = userLogin; return this; } public String getPermission() { return permission; } public PermissionTemplateUserDto setPermission(String permission) { this.permission = permission; return this; } public Date getCreatedAt() { return createdAt; } public PermissionTemplateUserDto setCreatedAt(Date createdAt) { this.createdAt = createdAt; return this; } public Date getUpdatedAt() { return updatedAt; } public PermissionTemplateUserDto setUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; return this; } }
2,600
23.537736
75
java