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/permission/template/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.template; import javax.annotation.ParametersAreNonnullByDefault;
973
37.96
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/plugin/PluginDao.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.plugin; 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.PluginNewValue; public class PluginDao implements Dao { private final AuditPersister auditPersister; public PluginDao(AuditPersister auditPersister) { this.auditPersister = auditPersister; } /** * It may return plugins that are no longer installed. */ public List<PluginDto> selectAll(DbSession dbSession) { return mapper(dbSession).selectAll(); } /** * It may return a plugin that is no longer installed. */ public Optional<PluginDto> selectByKey(DbSession dbSession, String key) { return Optional.ofNullable(mapper(dbSession).selectByKey(key)); } public void insert(DbSession dbSession, PluginDto dto) { mapper(dbSession).insert(dto); auditPersister.addPlugin(dbSession, new PluginNewValue(dto)); } public void update(DbSession dbSession, PluginDto dto) { mapper(dbSession).update(dto); auditPersister.updatePlugin(dbSession, new PluginNewValue(dto)); } private static PluginMapper mapper(DbSession dbSession) { return dbSession.getMapper(PluginMapper.class); } }
2,100
31.828125
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/plugin/PluginDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.plugin; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.apache.commons.lang.builder.ToStringBuilder; public class PluginDto { /** Technical unique identifier, can't be null */ private String uuid = null; /** Plugin key, unique, can't be null */ private String kee = null; /** Base plugin key, can be null */ private String basePluginKey = null; /** JAR file MD5 checksum, can't be null */ private String fileHash = null; // core feature or not private Type type = null; /** whether the plugin has been removed **/ private boolean removed = false; /** Time plugin was first installed */ private long createdAt = 0L; /** Time of last plugin update (=md5 change) */ private long updatedAt = 0L; public String getUuid() { return uuid; } public PluginDto setUuid(String s) { this.uuid = s; return this; } public String getKee() { return kee; } public PluginDto setKee(String s) { this.kee = s; return this; } @CheckForNull public String getBasePluginKey() { return basePluginKey; } public PluginDto setBasePluginKey(@Nullable String s) { this.basePluginKey = s; return this; } public String getFileHash() { return fileHash; } public PluginDto setFileHash(String s) { this.fileHash = s; return this; } public long getCreatedAt() { return createdAt; } public PluginDto setCreatedAt(long l) { this.createdAt = l; return this; } public long getUpdatedAt() { return updatedAt; } public PluginDto setUpdatedAt(long l) { this.updatedAt = l; return this; } public Type getType() { return type; } public PluginDto setType(Type type) { this.type = type; return this; } public boolean isRemoved() { return removed; } public PluginDto setRemoved(boolean removed) { this.removed = removed; return this; } public enum Type { BUNDLED, EXTERNAL } @Override public String toString() { return new ToStringBuilder(this) .append("uuid", uuid) .append("key", kee) .append("basePluginKey", basePluginKey) .append("fileHash", fileHash) .append("removed", removed) .append("createdAt", createdAt) .append("updatedAt", updatedAt) .toString(); } }
3,200
22.711111
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/plugin/PluginMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.plugin; import java.util.List; import javax.annotation.CheckForNull; import org.apache.ibatis.annotations.Param; public interface PluginMapper { List<PluginDto> selectAll(); @CheckForNull PluginDto selectByKey(@Param("key") String key); void insert(PluginDto dto); void update(PluginDto dto); }
1,176
29.973684
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/plugin/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.plugin; import javax.annotation.ParametersAreNonnullByDefault;
960
37.44
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/portfolio/PortfolioDao.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.portfolio; import java.util.List; import java.util.Optional; import java.util.Set; import javax.annotation.CheckForNull; import org.sonar.api.resources.Qualifiers; 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.ComponentNewValue; import org.sonar.db.component.KeyWithUuidDto; import org.sonar.db.project.ApplicationProjectDto; import static com.google.common.base.Preconditions.checkArgument; import static java.lang.String.format; import static java.util.Collections.emptyList; import static java.util.Collections.singleton; import static org.sonar.db.DatabaseUtils.executeLargeInputs; public class PortfolioDao implements Dao { private final System2 system2; private final UuidFactory uuidFactory; private final AuditPersister auditPersister; public PortfolioDao(System2 system2, UuidFactory uuidFactory, AuditPersister auditPersister) { this.system2 = system2; this.uuidFactory = uuidFactory; this.auditPersister = auditPersister; } /* * Select portfolios */ public List<PortfolioDto> selectAllRoots(DbSession dbSession) { return mapper(dbSession).selectAllRoots(); } /** * select all application projects belong to the hierarchy of a portfolio */ public List<ApplicationProjectDto> selectAllApplicationProjects(DbSession dbSession, String rootPortfolioUuid) { return mapper(dbSession).selectAllApplicationProjects(rootPortfolioUuid); } public List<PortfolioDto> selectAll(DbSession dbSession) { return mapper(dbSession).selectAll(); } public List<PortfolioDto> selectTree(DbSession dbSession, String portfolioUuid) { return mapper(dbSession).selectTree(portfolioUuid); } public Optional<PortfolioDto> selectByKey(DbSession dbSession, String key) { return Optional.ofNullable(mapper(dbSession).selectByKey(key)); } public List<PortfolioDto> selectByKeys(DbSession dbSession, Set<String> portfolioDbKeys) { return executeLargeInputs(portfolioDbKeys, input -> mapper(dbSession).selectByKeys(input)); } public Optional<PortfolioDto> selectByUuid(DbSession dbSession, String uuid) { return Optional.ofNullable(mapper(dbSession).selectByUuid(uuid)); } public List<PortfolioDto> selectByUuids(DbSession dbSession, Set<String> uuids) { if (uuids.isEmpty()) { return emptyList(); } return mapper(dbSession).selectByUuids(uuids); } public List<KeyWithUuidDto> selectUuidsByKey(DbSession dbSession, String rootKey) { return mapper(dbSession).selectUuidsByKey(rootKey); } /* * Modify portfolios */ public void insert(DbSession dbSession, PortfolioDto portfolio) { checkArgument(portfolio.isRoot() == (portfolio.getUuid().equals(portfolio.getRootUuid()))); mapper(dbSession).insert(portfolio); auditPersister.addComponent(dbSession, toComponentNewValue(portfolio)); } public void delete(DbSession dbSession, PortfolioDto portfolio) { mapper(dbSession).deleteReferencesByPortfolioOrReferenceUuids(singleton(portfolio.getUuid())); mapper(dbSession).deletePortfolio(portfolio.getUuid()); auditPersister.deleteComponent(dbSession, toComponentNewValue(portfolio)); } /** * Does NOT delete related references and project/branch selections! */ public void deleteAllDescendantPortfolios(DbSession dbSession, String rootUuid) { // not audited but it's part of DefineWs mapper(dbSession).deleteAllDescendantPortfolios(rootUuid); } public void update(DbSession dbSession, PortfolioDto portfolio) { checkArgument(portfolio.isRoot() == (portfolio.getUuid().equals(portfolio.getRootUuid()))); portfolio.setUpdatedAt(system2.now()); mapper(dbSession).update(portfolio); auditPersister.updateComponent(dbSession, toComponentNewValue(portfolio)); } public void updateVisibilityByPortfolioUuid(DbSession dbSession, String uuid, boolean newIsPrivate) { mapper(dbSession).updateVisibilityByPortfolioUuid(uuid, newIsPrivate); } /* * Portfolio references */ public void addReferenceBranch(DbSession dbSession, String portfolioUuid, String referenceUuid, String branchUuid) { mapper(dbSession).insertReference(uuidFactory.create(), portfolioUuid, referenceUuid, branchUuid, system2.now()); } public void addReference(DbSession dbSession, String portfolioUuid, String referenceUuid) { PortfolioDto portfolio = mapper(dbSession).selectByUuid(referenceUuid); if (portfolio == null) { throw new IllegalArgumentException("Reference must be a portfolio"); } else { mapper(dbSession).insertReference(uuidFactory.create(), portfolioUuid, referenceUuid, null, system2.now()); } } public List<ReferenceDto> selectAllReferencesToPortfolios(DbSession dbSession) { return mapper(dbSession).selectAllReferencesToPortfolios(); } public List<ReferenceDto> selectAllReferencesToApplications(DbSession dbSession) { return mapper(dbSession).selectAllReferencesToApplications(); } public List<ReferenceDto> selectAllReferencesToPortfoliosInHierarchy(DbSession dbSession, String rootUuid) { return mapper(dbSession).selectAllReferencesToPortfoliosInHierarchy(rootUuid); } public List<ReferenceDto> selectAllReferencesToApplicationsInHierarchy(DbSession dbSession, String rootUuid) { return mapper(dbSession).selectAllReferencesToApplicationsInHierarchy(rootUuid); } public List<String> selectApplicationReferenceUuids(DbSession dbSession, String portfolioUuid) { return mapper(dbSession).selectApplicationReferenceUuids(portfolioUuid); } public Set<String> selectReferenceUuids(DbSession dbSession, String portfolioUuid) { return mapper(dbSession).selectReferenceUuids(portfolioUuid); } public List<PortfolioDto> selectReferencers(DbSession dbSession, String referenceUuid) { return mapper(dbSession).selectReferencers(referenceUuid); } public List<PortfolioDto> selectRootOfReferencers(DbSession dbSession, String referenceUuid) { return mapper(dbSession).selectRootOfReferencers(referenceUuid); } public List<PortfolioDto> selectRootOfReferencersToMainBranch(DbSession dbSession, String referenceUuid) { return mapper(dbSession).selectRootOfReferencersToMainBranch(referenceUuid); } public List<PortfolioDto> selectRootOfReferencersToAppBranch(DbSession dbSession, String appUuid, String appBranchKey) { return mapper(dbSession).selectRootOfReferencersToAppBranch(appUuid, appBranchKey); } public void deleteReferencesTo(DbSession dbSession, String referenceUuid) { mapper(dbSession).deleteReferencesTo(referenceUuid); } public void deleteAllReferences(DbSession dbSession) { mapper(dbSession).deleteAllReferences(); } public int deleteReferenceBranch(DbSession dbSession, String portfolioUuid, String referenceUuid, String branchUuid) { return mapper(dbSession).deleteReferenceBranch(portfolioUuid, referenceUuid, branchUuid); } public int deleteReference(DbSession dbSession, String portfolioUuid, String referenceUuid) { return mapper(dbSession).deleteReference(portfolioUuid, referenceUuid); } @CheckForNull public ReferenceDto selectReference(DbSession dbSession, String portfolioUuid, String referenceKey) { return selectReferenceToApp(dbSession, portfolioUuid, referenceKey) .or(() -> selectReferenceToPortfolio(dbSession, portfolioUuid, referenceKey)) .orElse(null); } public Optional<ReferenceDto> selectReferenceToApp(DbSession dbSession, String portfolioUuid, String referenceKey) { return Optional.ofNullable(mapper(dbSession).selectReferenceToApplication(portfolioUuid, referenceKey)); } public Optional<ReferenceDto> selectReferenceToPortfolio(DbSession dbSession, String portfolioUuid, String referenceKey) { return Optional.ofNullable(mapper(dbSession).selectReferenceToPortfolio(portfolioUuid, referenceKey)); } /* * Manual selection of projects */ public List<PortfolioProjectDto> selectPortfolioProjects(DbSession dbSession, String portfolioUuid) { return mapper(dbSession).selectPortfolioProjects(portfolioUuid); } public List<PortfolioProjectDto> selectAllProjectsInHierarchy(DbSession dbSession, String rootUuid) { return mapper(dbSession).selectAllProjectsInHierarchy(rootUuid); } public List<PortfolioProjectDto> selectAllPortfolioProjects(DbSession dbSession) { return mapper(dbSession).selectAllPortfolioProjects(); } public PortfolioProjectDto selectPortfolioProjectOrFail(DbSession dbSession, String portfolioUuid, String projectUuid) { return Optional.ofNullable(mapper(dbSession).selectPortfolioProject(portfolioUuid, projectUuid)) .orElseThrow(() -> new IllegalArgumentException(format("Project '%s' not selected in portfolio '%s'", projectUuid, portfolioUuid))); } public String addProject(DbSession dbSession, String portfolioUuid, String projectUuid) { String uuid = uuidFactory.create(); mapper(dbSession).insertProject(uuid, portfolioUuid, projectUuid, system2.now()); return uuid; } public void deleteProjects(DbSession dbSession, String portfolioUuid) { mapper(dbSession).deleteProjects(portfolioUuid); } public void deleteProject(DbSession dbSession, String portfolioUuid, String projectUuid) { mapper(dbSession).deleteProject(portfolioUuid, projectUuid); } public void deleteAllProjects(DbSession dbSession) { mapper(dbSession).deleteAllProjects(); } public void addBranch(DbSession dbSession, String portfolioProjectUuid, String branchUuid) { mapper(dbSession).insertBranch(uuidFactory.create(), portfolioProjectUuid, branchUuid, system2.now()); } public void deleteBranch(DbSession dbSession, String portfolioUuid, String projectUuid, String branchUuid) { mapper(dbSession).deleteBranch(portfolioUuid, projectUuid, branchUuid); } /* * Utils */ private static PortfolioMapper mapper(DbSession session) { return session.getMapper(PortfolioMapper.class); } private static ComponentNewValue toComponentNewValue(PortfolioDto portfolio) { return new ComponentNewValue(portfolio.getUuid(), portfolio.isPrivate(), portfolio.getName(), portfolio.getKey(), portfolio.getDescription(), qualifier(portfolio)); } private static String qualifier(PortfolioDto portfolioDto) { return portfolioDto.isRoot() ? Qualifiers.VIEW : Qualifiers.SUBVIEW; } }
11,342
39.510714
168
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/portfolio/PortfolioDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.portfolio; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.resources.Qualifiers; import org.sonar.db.entity.EntityDto; public class PortfolioDto extends EntityDto { public enum SelectionMode { NONE, MANUAL, REGEXP, REST, TAGS } private String branchKey; private String rootUuid; private String parentUuid; private String selectionMode; private String selectionExpression; private long createdAt; private long updatedAt; public String getRootUuid() { return rootUuid; } public PortfolioDto setRootUuid(String rootUuid) { this.rootUuid = rootUuid; return this; } @CheckForNull public String getParentUuid() { return parentUuid; } public boolean isRoot() { return parentUuid == null; } public PortfolioDto setParentUuid(@Nullable String parentUuid) { this.parentUuid = parentUuid; return this; } @CheckForNull public String getBranchKey() { return branchKey; } public void setBranchKey(@Nullable String branchKey) { this.branchKey = branchKey; } @Override public String getQualifier() { if (isRoot()) { return Qualifiers.VIEW; } return Qualifiers.SUBVIEW; } public String getSelectionMode() { return selectionMode; } public PortfolioDto setSelectionMode(String selectionMode) { this.selectionMode = selectionMode; return this; } public PortfolioDto setSelectionMode(SelectionMode selectionMode) { this.selectionMode = selectionMode.name(); return this; } @CheckForNull public String getSelectionExpression() { return selectionExpression; } public PortfolioDto setSelectionExpression(@Nullable String selectionExpression) { this.selectionExpression = selectionExpression; return this; } public long getCreatedAt() { return createdAt; } public PortfolioDto setCreatedAt(long createdAt) { this.createdAt = createdAt; return this; } public long getUpdatedAt() { return updatedAt; } public PortfolioDto setUpdatedAt(long updatedAt) { this.updatedAt = updatedAt; return this; } public PortfolioDto setUuid(String uuid) { this.uuid = uuid; return this; } /** * This is the setter used by MyBatis mapper. */ public PortfolioDto setKee(String kee) { this.kee = kee; return this; } public PortfolioDto setKey(String key) { return setKee(key); } public PortfolioDto setPrivate(boolean aPrivate) { isPrivate = aPrivate; return this; } public PortfolioDto setName(String name) { this.name = name; return this; } public PortfolioDto setDescription(@Nullable String description) { this.description = description; return this; } }
3,633
22.294872
84
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/portfolio/PortfolioMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.portfolio; import java.util.Collection; import java.util.List; import java.util.Set; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.apache.ibatis.annotations.Param; import org.sonar.db.component.KeyWithUuidDto; import org.sonar.db.project.ApplicationProjectDto; public interface PortfolioMapper { @CheckForNull PortfolioDto selectByKey(String key); List<PortfolioDto> selectByKeys(@Param("keys") List<String> keys); @CheckForNull PortfolioDto selectByUuid(String uuid); void insert(PortfolioDto portfolio); void deletePortfolio(@Param("uuid") String uuid); void deleteReferencesByPortfolioOrReferenceUuids(@Param("uuids") Set<String> uuids); void insertReference(@Param("uuid") String uuid, @Param("portfolioUuid") String portfolioUuid, @Param("referenceUuid") String referenceUuid, @Nullable @Param("branchUuid") String branchUuid, @Param("createdAt") long createdAt); void insertProject(@Param("uuid") String uuid, @Param("portfolioUuid") String portfolioUuid, @Param("projectUuid") String projectUuid, @Param("createdAt") long createdAt); List<PortfolioDto> selectTree(String portfolioUuid); Set<String> selectReferenceUuids(String portfolioUuid); List<PortfolioDto> selectReferencers(String referenceUuid); List<PortfolioProjectDto> selectPortfolioProjects(String portfolioUuid); PortfolioProjectDto selectPortfolioProject(@Param("portfolioUuid") String portfolioUuid, @Param("projectUuid") String projectUuid); List<ReferenceDto> selectAllReferencesToPortfolios(); List<ReferenceDto> selectAllReferencesToApplications(); List<PortfolioProjectDto> selectAllProjectsInHierarchy(String rootUuid); List<PortfolioDto> selectByUuids(@Param("uuids") Collection<String> uuids); void update(PortfolioDto portfolio); void updateVisibilityByPortfolioUuid(@Param("uuid") String uuid, @Param("newIsPrivate") boolean newIsPrivate); List<PortfolioDto> selectAllRoots(); List<ApplicationProjectDto> selectAllApplicationProjects(String rootPortfolioUuid); List<PortfolioDto> selectAll(); List<PortfolioDto> selectRootOfReferencers(String referenceUuid); List<PortfolioDto> selectRootOfReferencersToMainBranch(String referenceUuid); void deleteReferencesTo(String referenceUuid); void deleteProjects(String portfolioUuid); void deleteProject(@Param("portfolioUuid") String portfolioUuid, @Param("projectUuid") String projectUuid); void deleteAllDescendantPortfolios(String rootUuid); void deleteAllReferences(); int deleteReference(@Param("portfolioUuid") String portfolioUuid, @Param("referenceUuid") String referenceUuid); ReferenceDto selectReferenceToPortfolio(@Param("portfolioUuid") String portfolioUuid, @Param("referenceKey") String referenceKey); ReferenceDto selectReferenceToApplication(@Param("portfolioUuid") String portfolioUuid, @Param("referenceKey") String referenceKey); void deleteAllProjects(); List<PortfolioProjectDto> selectAllPortfolioProjects(); void deleteBranch(@Param("portfolioUuid") String portfolioUuid, @Param("projectUuid") String projectUuid, @Param("branchUuid") String branchUuid); void insertBranch(@Param("uuid") String uuid, @Param("portfolioProjectUuid") String portfolioProjectUuid, @Param("branchUuid") String branchUuid, @Param("createdAt") long createdAt); List<String> selectApplicationReferenceUuids(@Param("portfolioUuid") String portfolioUuid); int deleteReferenceBranch(@Param("portfolioUuid") String portfolioUuid, @Param("referenceUuid") String referenceUuid, @Param("branchUuid") String branchUuid); List<ReferenceDto> selectAllReferencesToPortfoliosInHierarchy(String rootUuid); List<ReferenceDto> selectAllReferencesToApplicationsInHierarchy(String rootUuid); List<PortfolioDto> selectRootOfReferencersToAppBranch(@Param("appUuid") String appUuid, @Param("appBranchKey") String appBranchKey); List<KeyWithUuidDto> selectUuidsByKey(@Param("rootKey") String rootKey); }
4,848
39.408333
173
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/portfolio/PortfolioProjectDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.portfolio; import java.util.Set; public class PortfolioProjectDto { private String uuid; private String portfolioUuid; private String portfolioKey; private String projectUuid; private String projectKey; private Set<String> branchUuids; private String mainBranchUuid; private long createdAt; public String getUuid() { return uuid; } public PortfolioProjectDto setUuid(String uuid) { this.uuid = uuid; return this; } public String getMainBranchUuid() { return mainBranchUuid; } public void setMainBranchUuid(String mainBranchUuid) { this.mainBranchUuid = mainBranchUuid; } public String getPortfolioUuid() { return portfolioUuid; } public PortfolioProjectDto setPortfolioUuid(String portfolioUuid) { this.portfolioUuid = portfolioUuid; return this; } public String getProjectUuid() { return projectUuid; } public PortfolioProjectDto setProjectUuid(String projectUuid) { this.projectUuid = projectUuid; return this; } public long getCreatedAt() { return createdAt; } public PortfolioProjectDto setCreatedAt(long createdAt) { this.createdAt = createdAt; return this; } public String getPortfolioKey() { return portfolioKey; } public PortfolioProjectDto setPortfolioKey(String portfolioKey) { this.portfolioKey = portfolioKey; return this; } public String getProjectKey() { return projectKey; } public PortfolioProjectDto setProjectKey(String projectKey) { this.projectKey = projectKey; return this; } public Set<String> getBranchUuids() { return branchUuids; } public void setBranchUuids(Set<String> branchUuids) { this.branchUuids = branchUuids; } }
2,597
23.980769
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/portfolio/ReferenceDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.portfolio; import java.util.Set; public class ReferenceDto { private String sourceUuid; private String sourceRootUuid; private String targetUuid; private String targetRootUuid; private String targetName; private String targetKey; private Set<String> branchUuids; public String getTargetName() { return targetName; } public ReferenceDto setTargetName(String targetName) { this.targetName = targetName; return this; } public String getTargetKey() { return targetKey; } public ReferenceDto setTargetKey(String targetKey) { this.targetKey = targetKey; return this; } public Set<String> getBranchUuids() { return branchUuids; } public ReferenceDto setBranchUuids(Set<String> branchUuids) { this.branchUuids = branchUuids; return this; } public String getSourceUuid() { return sourceUuid; } public void setSourceUuid(String sourceUuid) { this.sourceUuid = sourceUuid; } public String getSourceRootUuid() { return sourceRootUuid; } public void setSourceRootUuid(String sourceRootUuid) { this.sourceRootUuid = sourceRootUuid; } public String getTargetUuid() { return targetUuid; } public void setTargetUuid(String targetUuid) { this.targetUuid = targetUuid; } public String getTargetRootUuid() { return targetRootUuid; } public void setTargetRootUuid(String targetRootUuid) { this.targetRootUuid = targetRootUuid; } }
2,329
24.053763
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/portfolio/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.portfolio; import javax.annotation.ParametersAreNonnullByDefault;
963
37.56
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/project/ApplicationProjectDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.project; public class ApplicationProjectDto { private String appUuid; private String appKey; private String projectUuid; public ApplicationProjectDto() { // Do Nothing } public String getAppUuid() { return appUuid; } public String getAppKey() { return appKey; } public String getProjectUuid() { return projectUuid; } }
1,227
26.909091
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/project/ProjectBadgeTokenDao.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.project; import javax.annotation.CheckForNull; 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.ProjectBadgeTokenNewValue; public class ProjectBadgeTokenDao implements Dao { private final System2 system2; private final AuditPersister auditPersister; private final UuidFactory uuidFactory; public ProjectBadgeTokenDao(System2 system2, AuditPersister auditPersister, UuidFactory uuidFactory) { this.system2 = system2; this.auditPersister = auditPersister; this.uuidFactory = uuidFactory; } public ProjectBadgeTokenDto insert(DbSession session, String token, ProjectDto projectDto, String userUuid, String userLogin) { ProjectBadgeTokenDto projectBadgeTokenDto = new ProjectBadgeTokenDto(uuidFactory.create(), token, projectDto.getUuid(), system2.now(), system2.now()); auditPersister.addProjectBadgeToken(session, new ProjectBadgeTokenNewValue(projectDto.getKey(), userUuid, userLogin)); mapper(session).insert(projectBadgeTokenDto); return projectBadgeTokenDto; } public void upsert(DbSession session, String token, ProjectDto projectDto, String userUuid, String userLogin) { if(selectTokenByProject(session, projectDto) == null) { insert(session, token, projectDto, userUuid, userLogin); } else { mapper(session).update(token, projectDto.getUuid(), system2.now()); auditPersister.updateProjectBadgeToken(session, new ProjectBadgeTokenNewValue(projectDto.getKey(), userUuid, userLogin)); } } private static ProjectBadgeTokenMapper mapper(DbSession session) { return session.getMapper(ProjectBadgeTokenMapper.class); } @CheckForNull public ProjectBadgeTokenDto selectTokenByProject(DbSession session, ProjectDto projectDto) { return mapper(session).selectTokenByProjectUuid(projectDto.getUuid()); } }
2,834
38.929577
127
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/project/ProjectBadgeTokenDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.project; public class ProjectBadgeTokenDto { private String uuid; private String token; private String projectUuid; private long createdAt; private long updatedAt; public ProjectBadgeTokenDto() { // to keep for mybatis } public ProjectBadgeTokenDto(String uuid, String token, String projectUuid, long createdAt, long updatedAt) { this.uuid = uuid; this.token = token; this.projectUuid = projectUuid; this.createdAt = createdAt; this.updatedAt = updatedAt; } public String getUuid() { return uuid; } public ProjectBadgeTokenDto setUuid(String uuid) { this.uuid = uuid; return this; } public String getToken() { return token; } public ProjectBadgeTokenDto setToken(String token) { this.token = token; return this; } public String getProjectUuid() { return projectUuid; } public ProjectBadgeTokenDto setProjectUuid(String projectUuid) { this.projectUuid = projectUuid; return this; } public long getCreatedAt() { return createdAt; } public ProjectBadgeTokenDto setCreatedAt(long createdAt) { this.createdAt = createdAt; return this; } public long getUpdatedAt() { return updatedAt; } public ProjectBadgeTokenDto setUpdatedAt(long updatedAt) { this.updatedAt = updatedAt; return this; } }
2,205
24.356322
110
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/project/ProjectBadgeTokenMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.project; import javax.annotation.CheckForNull; import org.apache.ibatis.annotations.Param; public interface ProjectBadgeTokenMapper { void insert(ProjectBadgeTokenDto projectBadgeTokenDto); int update(@Param("token") String token, @Param("projectUuid") String projectUuid, @Param("updatedAt") long updatedAt); @CheckForNull ProjectBadgeTokenDto selectTokenByProjectUuid(@Param("projectUuid") String projectUuid); }
1,292
37.029412
121
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/project/ProjectDao.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.project; import java.util.Collection; 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.db.Dao; import org.sonar.db.DbSession; import org.sonar.db.Pagination; import org.sonar.db.audit.AuditPersister; import org.sonar.db.audit.model.ComponentNewValue; import static java.util.Collections.emptyList; import static org.sonar.db.DatabaseUtils.executeLargeInputs; public class ProjectDao implements Dao { private final System2 system2; private final AuditPersister auditPersister; public ProjectDao(System2 system2, AuditPersister auditPersister) { this.system2 = system2; this.auditPersister = auditPersister; } public void insert(DbSession session, ProjectDto project) { this.insert(session, project, false); } public void insert(DbSession session, ProjectDto project, boolean track) { if (track) { auditPersister.addComponent(session, new ComponentNewValue(project)); } mapper(session).insert(project); } public Optional<ProjectDto> selectProjectByKey(DbSession session, String key) { return Optional.ofNullable(mapper(session).selectProjectByKey(key)); } public Optional<ProjectDto> selectApplicationByKey(DbSession session, String key) { return Optional.ofNullable(mapper(session).selectApplicationByKey(key)); } public Optional<ProjectDto> selectProjectOrAppByKey(DbSession session, String key) { return Optional.ofNullable(mapper(session).selectProjectOrAppByKey(key)); } public List<ProjectDto> selectAllApplications(DbSession session) { return mapper(session).selectAllApplications(); } public List<ProjectDto> selectProjectsByKeys(DbSession session, Collection<String> keys) { if (keys.isEmpty()) { return emptyList(); } return mapper(session).selectProjectsByKeys(keys); } public List<ProjectDto> selectApplicationsByKeys(DbSession session, Set<String> keys) { if (keys.isEmpty()) { return emptyList(); } return executeLargeInputs(keys, partition -> mapper(session).selectApplicationsByKeys(partition)); } public Optional<ProjectDto> selectByBranchUuid(DbSession dbSession, String branchUuid) { return Optional.ofNullable(mapper(dbSession).selectByBranchUuid(branchUuid)); } public List<ProjectDto> selectProjects(DbSession session) { return mapper(session).selectProjects(); } public Optional<ProjectDto> selectByUuid(DbSession session, String uuid) { return Optional.ofNullable(mapper(session).selectByUuid(uuid)); } public List<ProjectDto> selectAll(DbSession session) { return mapper(session).selectAll(); } public List<ProjectDto> selectByUuids(DbSession session, Set<String> uuids) { if (uuids.isEmpty()) { return emptyList(); } return executeLargeInputs(uuids, partition -> mapper(session).selectByUuids(partition)); } public List<ProjectDto> selectByUuids(DbSession session, Set<String> uuids, Pagination pagination) { if (uuids.isEmpty()) { return emptyList(); } return mapper(session).selectByUuidsWithPagination(uuids, pagination); } public void updateVisibility(DbSession session, String uuid, boolean isPrivate) { mapper(session).updateVisibility(uuid, isPrivate, system2.now()); } public void updateTags(DbSession session, ProjectDto project) { mapper(session).updateTags(project); } public void update(DbSession session, ProjectDto project) { auditPersister.updateComponent(session, new ComponentNewValue(project)); mapper(session).update(project); } private static ProjectMapper mapper(DbSession session) { return session.getMapper(ProjectMapper.class); } public List<String> selectAllProjectUuids(DbSession session) { return mapper(session).selectAllProjectUuids(); } public Set<String> selectProjectUuidsAssociatedToDefaultQualityProfileByLanguage(DbSession session, String language) { Set<String> languageFilters = Set.of(language + "=%", "%;" + language + "=%"); return mapper(session).selectProjectUuidsAssociatedToDefaultQualityProfileByLanguage(languageFilters); } public void updateNcloc(DbSession dbSession, String projectUuid, long ncloc) { mapper(dbSession).updateNcloc(projectUuid, ncloc); } public long getNclocSum(DbSession dbSession) { return getNclocSum(dbSession, null); } public long getNclocSum(DbSession dbSession, @Nullable String projectUuidToExclude) { return Optional.ofNullable(mapper(dbSession).getNclocSum(projectUuidToExclude)).orElse(0L); } }
5,474
34.096154
120
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/project/ProjectDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.project; import java.util.List; import java.util.stream.Collectors; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.db.entity.EntityDto; import static org.apache.commons.lang.StringUtils.trimToNull; import static org.sonar.db.component.DbTagsReader.readDbTags; public class ProjectDto extends EntityDto { private static final String TAGS_SEPARATOR = ","; private String tags; private long createdAt; private long updatedAt; public long getCreatedAt() { return createdAt; } public ProjectDto setCreatedAt(long createdAt) { this.createdAt = createdAt; return this; } public long getUpdatedAt() { return updatedAt; } public ProjectDto setUpdatedAt(long updatedAt) { this.updatedAt = updatedAt; return this; } public ProjectDto setUuid(String uuid) { this.uuid = uuid; return this; } /** * This is the setter used by MyBatis mapper. */ public ProjectDto setKee(String kee) { this.kee = kee; return this; } public ProjectDto setKey(String key) { return setKee(key); } public ProjectDto setPrivate(boolean aPrivate) { isPrivate = aPrivate; return this; } public List<String> getTags() { return readDbTags(tags); } public ProjectDto setTags(List<String> tags) { setTagsString(tags.stream() .filter(t -> !t.isEmpty()) .collect(Collectors.joining(TAGS_SEPARATOR))); return this; } /** * Used by MyBatis */ @CheckForNull public String getTagsString() { return tags; } public ProjectDto setTagsString(@Nullable String tags) { this.tags = trimToNull(tags); return this; } public ProjectDto setName(String name) { this.name = name; return this; } public ProjectDto setDescription(@Nullable String description) { this.description = description; return this; } public ProjectDto setQualifier(String qualifier) { this.qualifier = qualifier; return this; } }
2,863
23.689655
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/project/ProjectExportMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.project; import java.util.List; import org.apache.ibatis.annotations.Param; import org.sonar.db.component.BranchDto; import org.sonar.db.component.ProjectLinkDto; import org.sonar.db.newcodeperiod.NewCodePeriodDto; import org.sonar.db.property.PropertyDto; public interface ProjectExportMapper { List<BranchDto> selectBranchesForExport(@Param("projectUuid") String projectUuid); List<PropertyDto> selectPropertiesForExport(@Param("projectUuid") String projectUuid); List<ProjectLinkDto> selectLinksForExport(@Param("projectUuid") String projectUuid); List<NewCodePeriodDto> selectNewCodePeriodsForExport(@Param("projectUuid") String projectUuid); }
1,527
38.179487
97
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/project/ProjectMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.project; import java.util.Collection; import java.util.List; import java.util.Set; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.apache.ibatis.annotations.Param; import org.sonar.db.Pagination; public interface ProjectMapper { void insert(ProjectDto project); @CheckForNull ProjectDto selectProjectByKey(String key); @CheckForNull ProjectDto selectApplicationByKey(String key); @CheckForNull ProjectDto selectProjectOrAppByKey(String key); List<ProjectDto> selectProjectsByKeys(@Param("kees") Collection<String> kees); @CheckForNull ProjectDto selectByUuid(String uuid); List<ProjectDto> selectByUuids(@Param("uuids") Collection<String> uuids); List<ProjectDto> selectByUuidsWithPagination(@Param("uuids") Collection<String> uuids, @Param("pagination") Pagination pagination); List<ProjectDto> selectAll(); void updateTags(ProjectDto project); void update(ProjectDto project); List<ProjectDto> selectProjects(); void updateVisibility(@Param("uuid") String uuid, @Param("isPrivate") boolean isPrivate, @Param("updatedAt") long updatedAt); List<ProjectDto> selectAllApplications(); List<ProjectDto> selectApplicationsByKeys(@Param("kees") Collection<String> kees); @CheckForNull ProjectDto selectByBranchUuid(String branchUuid); List<String> selectAllProjectUuids(); Set<String> selectProjectUuidsAssociatedToDefaultQualityProfileByLanguage(@Param("languageFilters") Set<String> languageFilters); void updateNcloc(@Param("projectUuid") String projectUuid, @Param("ncloc") long ncloc); @CheckForNull Long getNclocSum(@Nullable @Param("projectUuidToExclude") String projectUuidToExclude); }
2,562
31.858974
133
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/project/ProjectQuery.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.project; import java.util.Date; import java.util.Locale; import java.util.Set; import java.util.stream.Stream; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.db.WildcardPosition; import static com.google.common.base.Preconditions.checkArgument; import static org.sonar.db.DaoUtils.buildLikeValue; public class ProjectQuery { private final String nameOrKeyQuery; private final boolean partialMatchOnKey; private final Boolean isPrivate; private final Set<String> projectUuids; private final Set<String> projectKeys; private final Long analyzedBefore; private final Long anyBranchAnalyzedBefore; private final Long anyBranchAnalyzedAfter; private final Date createdAfter; private final boolean onProvisionedOnly; private ProjectQuery(ProjectQuery.Builder builder) { this.nameOrKeyQuery = builder.nameOrKeyQuery; this.partialMatchOnKey = builder.partialMatchOnKey != null && builder.partialMatchOnKey; this.projectUuids = builder.projectUuids; this.projectKeys = builder.projectKeys; this.isPrivate = builder.isPrivate; this.analyzedBefore = builder.analyzedBefore; this.anyBranchAnalyzedBefore = builder.anyBranchAnalyzedBefore; this.anyBranchAnalyzedAfter = builder.anyBranchAnalyzedAfter; this.createdAfter = builder.createdAfter; this.onProvisionedOnly = builder.onProvisionedOnly; } @CheckForNull public String getNameOrKeyQuery() { return nameOrKeyQuery; } /** * Used by MyBatis mapper */ @CheckForNull public String getNameOrKeyUpperLikeQuery() { return buildLikeValue(nameOrKeyQuery, WildcardPosition.BEFORE_AND_AFTER).toUpperCase(Locale.ENGLISH); } /** * Used by MyBatis mapper */ public boolean isPartialMatchOnKey() { return partialMatchOnKey; } @CheckForNull public Set<String> getProjectUuids() { return projectUuids; } @CheckForNull public Set<String> getProjectKeys() { return projectKeys; } @CheckForNull public Boolean getPrivate() { return isPrivate; } @CheckForNull public Long getAnalyzedBefore() { return analyzedBefore; } @CheckForNull public Long getAnyBranchAnalyzedBefore() { return anyBranchAnalyzedBefore; } @CheckForNull public Long getAnyBranchAnalyzedAfter() { return anyBranchAnalyzedAfter; } @CheckForNull public Date getCreatedAfter() { return createdAfter; } public boolean isOnProvisionedOnly() { return onProvisionedOnly; } boolean hasEmptySetOfProjects() { return Stream.of(projectKeys, projectUuids) .anyMatch(list -> list != null && list.isEmpty()); } public static ProjectQuery.Builder builder() { return new ProjectQuery.Builder(); } public static class Builder { private String nameOrKeyQuery; private Boolean partialMatchOnKey; private Boolean isPrivate; private Set<String> projectUuids; private Set<String> projectKeys; private Set<String> qualifiers; private Long analyzedBefore; private Long anyBranchAnalyzedBefore; private Long anyBranchAnalyzedAfter; private Date createdAfter; private boolean onProvisionedOnly = false; public ProjectQuery.Builder setNameOrKeyQuery(@Nullable String nameOrKeyQuery) { this.nameOrKeyQuery = nameOrKeyQuery; return this; } /** * Beware, can be resource intensive! Should be used with precautions. */ public ProjectQuery.Builder setPartialMatchOnKey(@Nullable Boolean partialMatchOnKey) { this.partialMatchOnKey = partialMatchOnKey; return this; } public ProjectQuery.Builder setProjectUuids(@Nullable Set<String> projectUuids) { this.projectUuids = projectUuids; return this; } public ProjectQuery.Builder setProjectKeys(@Nullable Set<String> projectKeys) { this.projectKeys = projectKeys; return this; } public Set<String> getQualifiers() { return qualifiers; } public ProjectQuery.Builder setQualifiers(Set<String> qualifiers) { this.qualifiers = qualifiers; return this; } public ProjectQuery.Builder setPrivate(@Nullable Boolean isPrivate) { this.isPrivate = isPrivate; return this; } public ProjectQuery.Builder setAnalyzedBefore(@Nullable Long l) { this.analyzedBefore = l; return this; } public ProjectQuery.Builder setAnyBranchAnalyzedBefore(@Nullable Long l) { this.anyBranchAnalyzedBefore = l; return this; } /** * Filter on date of last analysis. On projects, all branches and pull requests are taken into * account. For example the analysis of a branch is included in the filter * even if the main branch has never been analyzed. */ public ProjectQuery.Builder setAnyBranchAnalyzedAfter(@Nullable Long l) { this.anyBranchAnalyzedAfter = l; return this; } public ProjectQuery.Builder setCreatedAfter(@Nullable Date l) { this.createdAfter = l; return this; } public ProjectQuery.Builder setOnProvisionedOnly(boolean onProvisionedOnly) { this.onProvisionedOnly = onProvisionedOnly; return this; } public ProjectQuery build() { checkArgument(nameOrKeyQuery != null || partialMatchOnKey == null, "A query must be provided if a partial match on key is specified."); return new ProjectQuery(this); } } }
6,273
28.59434
141
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/project/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.project; import javax.annotation.ParametersAreNonnullByDefault;
961
37.48
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/property/InternalComponentPropertiesDao.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.property; import java.util.Optional; import java.util.Set; import org.sonar.api.utils.System2; import org.sonar.core.util.UuidFactory; import org.sonar.db.Dao; import org.sonar.db.DbSession; /** * A simple key-value store per component. */ public class InternalComponentPropertiesDao implements Dao { private final System2 system2; private final UuidFactory uuidFactory; public InternalComponentPropertiesDao(System2 system2, UuidFactory uuidFactory) { this.system2 = system2; this.uuidFactory = uuidFactory; } private void insertOrUpdate(DbSession dbSession, InternalComponentPropertyDto dto) { InternalComponentPropertiesMapper mapper = getMapper(dbSession); dto.setUpdatedAt(system2.now()); if (mapper.update(dto) == 1) { return; } dto.setUuid(uuidFactory.create()); dto.setCreatedAt(system2.now()); mapper.insert(dto); } /** * For the given component uuid, update the value of the specified key, if exists, * otherwise insert it. */ public void insertOrUpdate(DbSession dbSession, String componentUuid, String key, String value) { insertOrUpdate(dbSession, new InternalComponentPropertyDto().setComponentUuid(componentUuid).setKey(key).setValue(value)); } /** * For the given component uuid, replace the value of the specified key "atomically": * only replace if the old value is still the same as the current value. */ public void replaceValue(DbSession dbSession, String componentUuid, String key, String oldValue, String newValue) { getMapper(dbSession).replaceValue(componentUuid, key, oldValue, newValue, system2.now()); } public Optional<InternalComponentPropertyDto> selectByComponentUuidAndKey(DbSession dbSession, String componentUuid, String key) { return getMapper(dbSession).selectByComponentUuidAndKey(componentUuid, key); } public int deleteByComponentUuid(DbSession dbSession, String componentUuid) { return getMapper(dbSession).deleteByComponentUuidAndKey(componentUuid); } /** * Select the projects.kee values for internal component properties having specified key and value. */ public Set<String> selectDbKeys(DbSession dbSession, String key, String value) { return getMapper(dbSession).selectDbKeys(key, value); } private static InternalComponentPropertiesMapper getMapper(DbSession dbSession) { return dbSession.getMapper(InternalComponentPropertiesMapper.class); } }
3,304
35.318681
132
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/property/InternalComponentPropertiesMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.property; import java.util.Optional; import java.util.Set; import org.apache.ibatis.annotations.Param; public interface InternalComponentPropertiesMapper { Optional<InternalComponentPropertyDto> selectByComponentUuidAndKey(@Param("componentUuid") String componentUuid, @Param("key") String key); void insert(@Param("dto") InternalComponentPropertyDto dto); int update(@Param("dto") InternalComponentPropertyDto dto); /** * Replace value (and update updated_at) only if current value matches oldValue */ void replaceValue(@Param("componentUuid") String componentUuid, @Param("key") String key, @Param("oldValue") String oldValue, @Param("newValue") String newValue, @Param("updatedAt") Long updatedAt); int deleteByComponentUuidAndKey(@Param("componentUuid") String componentUuid); Set<String> selectDbKeys(@Param("key") String key, @Param("value") String value); }
1,761
39.045455
163
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/property/InternalComponentPropertyDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.property; import com.google.common.base.MoreObjects; import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkArgument; public class InternalComponentPropertyDto { private static final int MAX_KEY_LENGTH = 512; private static final int MAX_VALUE_LENGTH = 4000; private String uuid; private String key; private String value; private String componentUuid; private Long createdAt; private Long updatedAt; public String getUuid() { return uuid; } public InternalComponentPropertyDto setUuid(String uuid) { this.uuid = uuid; return this; } public String getKey() { return key; } public InternalComponentPropertyDto setKey(String key) { checkArgument(key != null && !key.isEmpty(), "key can't be null nor empty"); checkArgument(key.length() <= MAX_KEY_LENGTH, "key length (%s) is longer than the maximum authorized (%s). '%s' was provided", key.length(), MAX_KEY_LENGTH, key); this.key = key; return this; } public String getValue() { return value; } public InternalComponentPropertyDto setValue(@Nullable String value) { if (value != null) { checkArgument(value.length() <= MAX_VALUE_LENGTH, "value length (%s) is longer than the maximum authorized (%s). '%s' was provided", value.length(), MAX_VALUE_LENGTH, value); } this.value = value; return this; } public String getComponentUuid() { return componentUuid; } public InternalComponentPropertyDto setComponentUuid(String componentUuid) { this.componentUuid = componentUuid; return this; } public Long getCreatedAt() { return createdAt; } public InternalComponentPropertyDto setCreatedAt(Long createdAt) { this.createdAt = createdAt; return this; } public Long getUpdatedAt() { return updatedAt; } public InternalComponentPropertyDto setUpdatedAt(Long updatedAt) { this.updatedAt = updatedAt; return this; } @Override public String toString() { return MoreObjects.toStringHelper("InternalComponentPropertyDto") .add("uuid", this.uuid) .add("key", this.key) .add("value", this.value) .add("componentUuid", this.componentUuid) .add("updatedAt", this.updatedAt) .add("createdAt", this.createdAt) .toString(); } }
3,180
28.183486
180
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/property/InternalPropertiesDao.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.property; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.utils.System2; import org.slf4j.LoggerFactory; import org.sonar.db.Dao; import org.sonar.db.DbSession; import org.sonar.db.audit.AuditPersister; import org.sonar.db.audit.model.PropertyNewValue; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static java.util.Collections.singletonList; public class InternalPropertiesDao implements Dao { /** * A common prefix used by locks. {@see InternalPropertiesDao#tryLock} */ private static final String LOCK_PREFIX = "lock."; private static final int KEY_MAX_LENGTH = 40; public static final int LOCK_NAME_MAX_LENGTH = KEY_MAX_LENGTH - LOCK_PREFIX.length(); private static final int TEXT_VALUE_MAX_LENGTH = 4000; private static final Optional<String> OPTIONAL_OF_EMPTY_STRING = Optional.of(""); private final System2 system2; private final AuditPersister auditPersister; public InternalPropertiesDao(System2 system2, AuditPersister auditPersister) { this.system2 = system2; this.auditPersister = auditPersister; } /** * Save a property which value is not empty. * <p>Value can't be {@code null} but can have any size except 0.</p> * * @throws IllegalArgumentException if {@code key} or {@code value} is {@code null} or empty. * * @see #saveAsEmpty(DbSession, String) */ public void save(DbSession dbSession, String key, String value) { checkKey(key); checkArgument(value != null && !value.isEmpty(), "value can't be null nor empty"); InternalPropertiesMapper mapper = getMapper(dbSession); int deletedRows = mapper.deleteByKey(key); long now = system2.now(); if (mustsBeStoredInClob(value)) { mapper.insertAsClob(key, value, now); } else { mapper.insertAsText(key, value, now); } if (auditPersister.isTrackedProperty(key)) { if (deletedRows > 0) { auditPersister.updateProperty(dbSession, new PropertyNewValue(key, value), false); } else { auditPersister.addProperty(dbSession, new PropertyNewValue(key, value), false); } } } private static boolean mustsBeStoredInClob(String value) { return value.length() > TEXT_VALUE_MAX_LENGTH; } /** * Save a property which value is empty. */ public void saveAsEmpty(DbSession dbSession, String key) { checkKey(key); InternalPropertiesMapper mapper = getMapper(dbSession); int deletedRows = mapper.deleteByKey(key); mapper.insertAsEmpty(key, system2.now()); if (auditPersister.isTrackedProperty(key)) { if (deletedRows > 0) { auditPersister.updateProperty(dbSession, new PropertyNewValue(key, ""), false); } else { auditPersister.addProperty(dbSession, new PropertyNewValue(key, ""), false); } } } public void delete(DbSession dbSession, String key) { int deletedRows = getMapper(dbSession).deleteByKey(key); if (deletedRows > 0 && auditPersister.isTrackedProperty(key)) { auditPersister.deleteProperty(dbSession, new PropertyNewValue(key), false); } } /** * @return a Map with an {link Optional<String>} for each String in {@code keys}. */ public Map<String, Optional<String>> selectByKeys(DbSession dbSession, @Nullable Set<String> keys) { if (keys == null || keys.isEmpty()) { return Collections.emptyMap(); } if (keys.size() == 1) { String key = keys.iterator().next(); return ImmutableMap.of(key, selectByKey(dbSession, key)); } keys.forEach(InternalPropertiesDao::checkKey); InternalPropertiesMapper mapper = getMapper(dbSession); List<InternalPropertyDto> res = mapper.selectAsText(ImmutableList.copyOf(keys)); Map<String, Optional<String>> builder = new HashMap<>(keys.size()); res.forEach(internalPropertyDto -> { String key = internalPropertyDto.getKey(); if (internalPropertyDto.isEmpty()) { builder.put(key, OPTIONAL_OF_EMPTY_STRING); } if (internalPropertyDto.getValue() != null) { builder.put(key, Optional.of(internalPropertyDto.getValue())); } }); // return Optional.empty() for all keys without a DB entry Sets.difference(keys, res.stream().map(InternalPropertyDto::getKey).collect(Collectors.toSet())) .forEach(key -> builder.put(key, Optional.empty())); // keys for which there isn't a text or empty value found yet List<String> keyWithClobValue = ImmutableList.copyOf(Sets.difference(keys, builder.keySet())); if (keyWithClobValue.isEmpty()) { return ImmutableMap.copyOf(builder); } // retrieve properties with a clob value res = mapper.selectAsClob(keyWithClobValue); res.forEach(internalPropertyDto -> builder.put(internalPropertyDto.getKey(), Optional.of(internalPropertyDto.getValue()))); // return Optional.empty() for all key with a DB entry which neither has text value, nor is empty nor has clob value Sets.difference(ImmutableSet.copyOf(keyWithClobValue), builder.keySet()).forEach(key -> builder.put(key, Optional.empty())); return ImmutableMap.copyOf(builder); } /** * No streaming of value */ public Optional<String> selectByKey(DbSession dbSession, String key) { checkKey(key); InternalPropertiesMapper mapper = getMapper(dbSession); InternalPropertyDto res = enforceSingleElement(key, mapper.selectAsText(singletonList(key))); if (res == null) { return Optional.empty(); } if (res.isEmpty()) { return OPTIONAL_OF_EMPTY_STRING; } if (res.getValue() != null) { return Optional.of(res.getValue()); } res = enforceSingleElement(key, mapper.selectAsClob(singletonList(key))); if (res == null) { LoggerFactory.getLogger(InternalPropertiesDao.class) .debug("Internal property {} has been found in db but has neither text value nor is empty. " + "Still it couldn't be retrieved with clob value. Ignoring the property.", key); return Optional.empty(); } return Optional.of(res.getValue()); } @CheckForNull private static InternalPropertyDto enforceSingleElement(String key, List<InternalPropertyDto> rows) { if (rows.isEmpty()) { return null; } int size = rows.size(); checkState(size <= 1, "%s rows retrieved for single property %s", size, key); return rows.iterator().next(); } /** * Try to acquire a lock with the specified name, for specified duration. * * Returns false if the lock exists with a timestamp > now - duration, * or if the atomic replacement of the timestamp fails (another process replaced first). * * Returns true if the lock does not exist, or if exists with a timestamp <= now - duration, * and the atomic replacement of the timestamp succeeds. * * The lock is considered released when the specified duration has elapsed. * * @throws IllegalArgumentException if name's length is > {@link #LOCK_NAME_MAX_LENGTH} * @throws IllegalArgumentException if maxAgeInSeconds is <= 0 */ public boolean tryLock(DbSession dbSession, String name, int maxAgeInSeconds) { if (name.isEmpty()) { throw new IllegalArgumentException("lock name can't be empty"); } if (name.length() > LOCK_NAME_MAX_LENGTH) { throw new IllegalArgumentException("lock name is too long"); } if (maxAgeInSeconds <= 0) { throw new IllegalArgumentException("maxAgeInSeconds must be > 0"); } String key = LOCK_PREFIX + name; long now = system2.now(); Optional<String> timestampAsStringOpt = selectByKey(dbSession, key); if (!timestampAsStringOpt.isPresent()) { return tryCreateLock(dbSession, key, String.valueOf(now)); } String oldTimestampString = timestampAsStringOpt.get(); long oldTimestamp = Long.parseLong(oldTimestampString); if (oldTimestamp > now - maxAgeInSeconds * 1000) { return false; } return getMapper(dbSession).replaceValue(key, oldTimestampString, String.valueOf(now)) == 1; } private boolean tryCreateLock(DbSession dbSession, String name, String value) { try { getMapper(dbSession).insertAsText(name, value, system2.now()); return true; } catch (Exception ignored) { return false; } } private static void checkKey(@Nullable String key) { checkArgument(key != null && !key.isEmpty(), "key can't be null nor empty"); } private static InternalPropertiesMapper getMapper(DbSession dbSession) { return dbSession.getMapper(InternalPropertiesMapper.class); } }
9,868
35.824627
128
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/property/InternalPropertiesMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.property; import java.util.List; import org.apache.ibatis.annotations.Param; public interface InternalPropertiesMapper { List<InternalPropertyDto> selectAsText(@Param("keys") List<String> key); List<InternalPropertyDto> selectAsClob(@Param("keys") List<String> key); void insertAsEmpty(@Param("key") String key, @Param("createdAt") long createdAt); void insertAsText(@Param("key") String key, @Param("value") String value, @Param("createdAt") long createdAt); void insertAsClob(@Param("key") String key, @Param("value") String value, @Param("createdAt") long createdAt); int deleteByKey(@Param("key") String key); /** * Replace the value of the specified key, only if the existing value matches the expected old value. * Returns 1 if the replacement succeeded, or 0 if failed (old value different, or record does not exist). */ int replaceValue(@Param("key") String key, @Param("oldValue") String oldValue, @Param("newValue") String newValue); }
1,843
40.909091
117
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/property/InternalPropertyDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.property; public final class InternalPropertyDto { private String key; private boolean empty; private String value; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public boolean isEmpty() { return empty; } public void setEmpty(boolean empty) { this.empty = empty; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
1,338
25.254902
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/property/PropertiesDao.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.property; import com.google.common.base.Strings; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; import javax.annotation.CheckForNull; 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 org.sonar.db.EmailSubscriberDto; import org.sonar.db.MyBatis; import org.sonar.db.audit.AuditPersister; import org.sonar.db.audit.model.PropertyNewValue; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Collections.singletonList; import static org.apache.commons.lang.StringUtils.repeat; import static org.sonar.db.DatabaseUtils.executeLargeInputs; import static org.sonar.db.DatabaseUtils.executeLargeInputsIntoSet; public class PropertiesDao implements Dao { private static final String NOTIFICATION_PREFIX = "notification."; private static final int VARCHAR_MAXSIZE = 4000; private final MyBatis mybatis; private final System2 system2; private final UuidFactory uuidFactory; private final AuditPersister auditPersister; public PropertiesDao(MyBatis mybatis, System2 system2, UuidFactory uuidFactory, AuditPersister auditPersister) { this.mybatis = mybatis; this.system2 = system2; this.uuidFactory = uuidFactory; this.auditPersister = auditPersister; } public Set<EmailSubscriberDto> findEmailSubscribersForNotification(DbSession dbSession, String notificationDispatcherKey, String notificationChannelKey, @Nullable String projectKey) { return getMapper(dbSession).findEmailRecipientsForNotification(NOTIFICATION_PREFIX + notificationDispatcherKey + "." + notificationChannelKey, projectKey, null); } public Set<EmailSubscriberDto> findEmailSubscribersForNotification(DbSession dbSession, String notificationDispatcherKey, String notificationChannelKey, @Nullable String projectKey, Set<String> logins) { if (logins.isEmpty()) { return Collections.emptySet(); } return executeLargeInputsIntoSet( logins, loginsPartition -> { String notificationKey = NOTIFICATION_PREFIX + notificationDispatcherKey + "." + notificationChannelKey; return getMapper(dbSession).findEmailRecipientsForNotification(notificationKey, projectKey, loginsPartition); }, partitionSize -> projectKey == null ? partitionSize : (partitionSize / 2)); } public boolean hasProjectNotificationSubscribersForDispatchers(String projectUuid, Collection<String> dispatcherKeys) { if (dispatcherKeys.isEmpty()) { return false; } try (DbSession session = mybatis.openSession(false); Connection connection = session.getConnection(); PreparedStatement pstmt = createStatement(projectUuid, dispatcherKeys, connection); ResultSet rs = pstmt.executeQuery()) { return rs.next() && rs.getInt(1) > 0; } catch (SQLException e) { throw new IllegalStateException("Fail to execute SQL for hasProjectNotificationSubscribersForDispatchers", e); } } private static PreparedStatement createStatement(String projectUuid, Collection<String> dispatcherKeys, Connection connection) throws SQLException { String sql = "SELECT count(1) FROM properties pp " + "where pp.user_uuid is not null and (pp.entity_uuid is null or pp.entity_uuid=?) " + "and (" + repeat("pp.prop_key like ?", " or ", dispatcherKeys.size()) + ")"; PreparedStatement res = connection.prepareStatement(sql); res.setString(1, projectUuid); int index = 2; for (String dispatcherKey : dispatcherKeys) { res.setString(index, NOTIFICATION_PREFIX + dispatcherKey + ".%"); index++; } return res; } public List<PropertyDto> selectGlobalProperties(DbSession session) { return getMapper(session).selectGlobalProperties(); } @CheckForNull public PropertyDto selectGlobalProperty(DbSession session, String propertyKey) { return getMapper(session).selectByKey(new PropertyDto().setKey(propertyKey)); } @CheckForNull public PropertyDto selectGlobalProperty(String propertyKey) { try (DbSession session = mybatis.openSession(false)) { return selectGlobalProperty(session, propertyKey); } } public List<PropertyDto> selectEntityProperties(DbSession session, String entityUuid) { return getMapper(session).selectByEntityUuids(singletonList(entityUuid)); } @CheckForNull public PropertyDto selectProjectProperty(DbSession dbSession, String projectUuid, String propertyKey) { return getMapper(dbSession).selectByKey(new PropertyDto().setKey(propertyKey).setEntityUuid(projectUuid)); } public List<PropertyDto> selectByQuery(PropertyQuery query, DbSession session) { return getMapper(session).selectByQuery(query); } public List<PropertyDto> selectGlobalPropertiesByKeys(DbSession session, Collection<String> keys) { return executeLargeInputs(keys, partitionKeys -> getMapper(session).selectByKeys(partitionKeys)); } public List<PropertyDto> selectPropertiesByKeysAndEntityUuids(DbSession session, Collection<String> keys, Collection<String> entityUuids) { return executeLargeInputs(keys, partitionKeys -> executeLargeInputs(entityUuids, partitionEntityUuids -> getMapper(session).selectByKeysAndEntityUuids(partitionKeys, partitionEntityUuids))); } public List<PropertyDto> selectByKeyAndMatchingValue(DbSession session, String key, String value) { return getMapper(session).selectByKeyAndMatchingValue(key, value); } public List<PropertyDto> selectEntityPropertyByKeyAndUserUuid(DbSession session, String key, String userUuid) { return getMapper(session).selectEntityPropertyByKeyAndUserUuid(key, userUuid); } /** * Saves the specified property and its value. * <p> * If {@link PropertyDto#getValue()} is {@code null} or empty, the properties is persisted as empty. * </p> * * @throws IllegalArgumentException if {@link PropertyDto#getKey()} is {@code null} or empty */ public void saveProperty(DbSession session, PropertyDto property) { saveProperty(session, property, null, null, null, null); } public void saveProperty(DbSession session, PropertyDto property, @Nullable String userLogin, @Nullable String projectKey, @Nullable String projectName, @Nullable String qualifier) { int affectedRows = save(getMapper(session), property.getKey(), property.getUserUuid(), property.getEntityUuid(), property.getValue()); if (affectedRows > 0) { auditPersister.updateProperty(session, new PropertyNewValue(property, userLogin, projectKey, projectName, qualifier), false); } else { auditPersister.addProperty(session, new PropertyNewValue(property, userLogin, projectKey, projectName, qualifier), false); } } private int save(PropertiesMapper mapper, String key, @Nullable String userUuid, @Nullable String entityUuids, @Nullable String value) { checkKey(key); long now = system2.now(); int affectedRows = mapper.delete(key, userUuid, entityUuids); String uuid = uuidFactory.create(); if (isEmpty(value)) { mapper.insertAsEmpty(uuid, key, userUuid, entityUuids, now); } else if (mustBeStoredInClob(value)) { mapper.insertAsClob(uuid, key, userUuid, entityUuids, value, now); } else { mapper.insertAsText(uuid, key, userUuid, entityUuids, value, now); } return affectedRows; } private static boolean mustBeStoredInClob(String value) { return value.length() > VARCHAR_MAXSIZE; } private static void checkKey(@Nullable String key) { checkArgument(!isEmpty(key), "key can't be null nor empty"); } private static boolean isEmpty(@Nullable String str) { return str == null || str.isEmpty(); } public void saveProperty(PropertyDto property) { try (DbSession session = mybatis.openSession(false)) { saveProperty(session, property); session.commit(); } } /** * Delete either global, user, entity or entity per user properties. * <p>Behaves in exactly the same way as {@link #selectByQuery(PropertyQuery, DbSession)} but deletes rather than * selects</p> * Used by Governance. */ public int deleteByQuery(DbSession dbSession, PropertyQuery query) { int deletedRows = getMapper(dbSession).deleteByQuery(query); if (deletedRows > 0 && query.key() != null) { auditPersister.deleteProperty(dbSession, new PropertyNewValue(query.key(), query.entityUuid(), null, null, null, query.userUuid()), false); } return deletedRows; } public int delete(DbSession dbSession, PropertyDto dto, @Nullable String userLogin, @Nullable String projectKey, @Nullable String projectName, @Nullable String qualifier) { int deletedRows = getMapper(dbSession).delete(dto.getKey(), dto.getUserUuid(), dto.getEntityUuid()); if (deletedRows > 0) { auditPersister.deleteProperty(dbSession, new PropertyNewValue(dto, userLogin, projectKey, projectName, qualifier), false); } return deletedRows; } public void deleteProjectProperty(DbSession session, String key, String projectUuid, String projectKey, String projectName, String qualifier) { int deletedRows = getMapper(session).deleteProjectProperty(key, projectUuid); if (deletedRows > 0) { auditPersister.deleteProperty(session, new PropertyNewValue(key, projectUuid, projectKey, projectName, qualifier, null), false); } } public void deleteGlobalProperty(String key, DbSession session) { int deletedRows = getMapper(session).deleteGlobalProperty(key); if (deletedRows > 0) { auditPersister.deleteProperty(session, new PropertyNewValue(key), false); } } public void deleteByKeyAndValue(DbSession dbSession, String key, String value) { int deletedRows = getMapper(dbSession).deleteByKeyAndValue(key, value); if (deletedRows > 0) { auditPersister.deleteProperty(dbSession, new PropertyNewValue(key, value), false); } } public void renamePropertyKey(String oldKey, String newKey) { checkArgument(!Strings.isNullOrEmpty(oldKey), "Old property key must not be empty"); checkArgument(!Strings.isNullOrEmpty(newKey), "New property key must not be empty"); if (!newKey.equals(oldKey)) { try (DbSession session = mybatis.openSession(false)) { getMapper(session).renamePropertyKey(oldKey, newKey); session.commit(); } } } private static PropertiesMapper getMapper(DbSession session) { return session.getMapper(PropertiesMapper.class); } }
11,561
39.568421
165
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/property/PropertiesMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.property; import java.util.List; import java.util.Set; import javax.annotation.Nullable; import org.apache.ibatis.annotations.Param; import org.sonar.db.EmailSubscriberDto; public interface PropertiesMapper { Set<EmailSubscriberDto> findEmailRecipientsForNotification(@Param("notifKey") String notificationKey, @Nullable @Param("projectKey") String projectKey, @Nullable @Param("logins") List<String> logins); List<PropertyDto> selectGlobalProperties(); PropertyDto selectByKey(PropertyDto key); List<PropertyDto> selectByKeys(@Param("keys") List<String> keys); List<PropertyDto> selectByKeysAndEntityUuids(@Param("keys") List<String> keys, @Param("entityUuids") List<String> entityUuids); List<PropertyDto> selectEntityPropertyByKeyAndUserUuid(@Param("key") String key, @Param("userUuid") String userUuid); List<PropertyDto> selectByEntityUuids(@Param("entityUuids") List<String> entityUuids); List<PropertyDto> selectByQuery(@Param("query") PropertyQuery query); List<PropertyDto> selectByKeyAndMatchingValue(@Param("key") String key, @Param("value") String value); void insertAsEmpty(@Param("uuid") String uuid, @Param("key") String key, @Nullable @Param("userUuid") String userUuid, @Nullable @Param("entityUuid") String entityUuid, @Param("now") long now); void insertAsText(@Param("uuid") String uuid, @Param("key") String key, @Nullable @Param("userUuid") String userUuid, @Nullable @Param("entityUuid") String entityUuid, @Param("value") String value, @Param("now") long now); void insertAsClob(@Param("uuid") String uuid, @Param("key") String key, @Nullable @Param("userUuid") String userUuid, @Nullable @Param("entityUuid") String entityUuid, @Param("value") String value, @Param("now") long now); int delete(@Param("key") String key, @Nullable @Param("userUuid") String userUuid, @Nullable @Param("entityUuid") String entityUuid); int deleteProjectProperty(@Param("key") String key, @Param("entityUuid") String entityUuid); int deleteGlobalProperty(@Param("key") String key); int deleteByQuery(@Param("query") PropertyQuery query); void deleteByUuids(@Param("uuids") List<String> uuids); int deleteByKeyAndValue(@Param("key") String key, @Param("value") String value); List<PropertyDto> selectByUuids(@Param("uuids") List<String> uuids); int renamePropertyKey(@Param("oldKey") String oldKey, @Param("newKey") String newKey); }
3,281
42.76
170
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/property/PropertyDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.property; import com.google.common.base.MoreObjects; import java.util.Objects; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkArgument; public class PropertyDto { private static final int MAX_KEY_LENGTH = 512; private String uuid; private String key; private String value; private String entityUuid; private String userUuid; String getUuid() { return uuid; } PropertyDto setUuid(String uuid) { this.uuid = uuid; return this; } public String getKey() { return key; } public PropertyDto setKey(String key) { checkArgument(key.length() <= MAX_KEY_LENGTH, "Setting key length (%s) is longer than the maximum authorized (%s). '%s' was provided", key.length(), MAX_KEY_LENGTH, key); this.key = key; return this; } public String getValue() { return value; } public PropertyDto setValue(@Nullable String value) { this.value = value; return this; } @CheckForNull public String getEntityUuid() { return entityUuid; } public PropertyDto setEntityUuid(@Nullable String entityUuid) { this.entityUuid = entityUuid; return this; } @CheckForNull public String getUserUuid() { return userUuid; } public PropertyDto setUserUuid(@Nullable String userUuid) { this.userUuid = userUuid; return this; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } PropertyDto other = (PropertyDto) obj; return Objects.equals(this.key, other.key) && Objects.equals(this.userUuid, other.userUuid) && Objects.equals(this.entityUuid, other.entityUuid) && Objects.equals(this.value, other.value); } @Override public int hashCode() { return Objects.hash(this.key, this.value, this.entityUuid, this.userUuid); } @Override public String toString() { return MoreObjects.toStringHelper(this) .addValue(this.key) .addValue(this.value) .addValue(this.entityUuid) .addValue(this.userUuid) .toString(); } }
3,034
25.163793
174
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/property/PropertyQuery.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.property; import javax.annotation.Nullable; public class PropertyQuery { private final String key; private final String entityUuid; private final String userUuid; private PropertyQuery(Builder builder) { this.key = builder.key; this.entityUuid = builder.entityUuid; this.userUuid = builder.userUuid; } public String key() { return key; } public String entityUuid() { return entityUuid; } public String userUuid() { return userUuid; } public static Builder builder() { return new Builder(); } public static class Builder { private String key; private String entityUuid; private String userUuid; public Builder setKey(String key) { this.key = key; return this; } public Builder setEntityUuid(@Nullable String entityUuid) { this.entityUuid = entityUuid; return this; } public Builder setUserUuid(String userUuid) { this.userUuid = userUuid; return this; } public PropertyQuery build() { return new PropertyQuery(this); } } }
1,944
23.935897
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/property/ScrapPropertyDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.property; import javax.annotation.Nullable; public class ScrapPropertyDto extends PropertyDto { 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,274
27.977273
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/property/Subscriber.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.property; import java.util.Objects; public class Subscriber { private String login; private boolean global; /** * Used by MyBatis */ public Subscriber() { } public Subscriber(String login, boolean global) { this.login = login; this.global = global; } public String getLogin() { return login; } void setLogin(String login) { this.login = login; } public boolean isGlobal() { return global; } void setGlobal(boolean global) { this.global = global; } @Override public String toString() { return "Subscriber{" + "login='" + login + '\'' + ", global=" + global + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Subscriber that = (Subscriber) o; return global == that.global && Objects.equals(login, that.login); } @Override public int hashCode() { return Objects.hash(login, global); } }
1,896
22.7125
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/property/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.property; import javax.annotation.ParametersAreNonnullByDefault;
962
37.52
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/purge/PurgeCommands.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.purge; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Lists; import java.util.Collection; import java.util.List; import javax.annotation.Nullable; import org.sonar.api.utils.System2; import org.sonar.db.DbSession; import static org.sonar.db.DatabaseUtils.executeLargeInputs; class PurgeCommands { private static final int MAX_SNAPSHOTS_PER_QUERY = 1000; private static final int MAX_RESOURCES_PER_QUERY = 1000; private static final String[] UNPROCESSED_STATUS = new String[]{"U"}; private final DbSession session; private final PurgeMapper purgeMapper; private final PurgeProfiler profiler; private final System2 system2; PurgeCommands(DbSession session, PurgeMapper purgeMapper, PurgeProfiler profiler, System2 system2) { this.session = session; this.purgeMapper = purgeMapper; this.profiler = profiler; this.system2 = system2; } PurgeCommands(DbSession session, PurgeProfiler profiler, System2 system2) { this(session, session.getMapper(PurgeMapper.class), profiler, system2); } List<String> selectSnapshotUuids(PurgeSnapshotQuery query) { return purgeMapper.selectAnalysisUuids(query); } void deleteAnalyses(String rootComponentUuid) { profiler.start("deleteAnalyses (event_component_changes)"); purgeMapper.deleteEventComponentChangesByComponentUuid(rootComponentUuid); session.commit(); profiler.stop(); profiler.start("deleteAnalyses (events)"); purgeMapper.deleteEventsByComponentUuid(rootComponentUuid); session.commit(); profiler.stop(); List<List<String>> analysisUuidsPartitions = Lists.partition(purgeMapper.selectAnalysisUuids(new PurgeSnapshotQuery(rootComponentUuid)), MAX_SNAPSHOTS_PER_QUERY); deleteAnalysisDuplications(analysisUuidsPartitions); profiler.start("deleteAnalyses (project_measures)"); analysisUuidsPartitions.forEach(purgeMapper::deleteAnalysisMeasures); session.commit(); profiler.stop(); profiler.start("deleteAnalyses (analysis_properties)"); analysisUuidsPartitions.forEach(purgeMapper::deleteAnalysisProperties); session.commit(); profiler.stop(); profiler.start("deleteAnalyses (snapshots)"); analysisUuidsPartitions.forEach(purgeMapper::deleteAnalyses); session.commit(); profiler.stop(); } void deleteAbortedAnalyses(String rootUuid) { PurgeSnapshotQuery query = new PurgeSnapshotQuery(rootUuid) .setIslast(false) .setStatus(UNPROCESSED_STATUS); deleteAnalyses(purgeMapper.selectAnalysisUuids(query)); } @VisibleForTesting void deleteAnalyses(List<String> analysisIdUuids) { List<List<String>> analysisUuidsPartitions = Lists.partition(analysisIdUuids, MAX_SNAPSHOTS_PER_QUERY); deleteAnalysisDuplications(analysisUuidsPartitions); profiler.start("deleteAnalyses (event_component_changes)"); analysisUuidsPartitions.forEach(purgeMapper::deleteAnalysisEventComponentChanges); session.commit(); profiler.stop(); profiler.start("deleteAnalyses (events)"); analysisUuidsPartitions.forEach(purgeMapper::deleteAnalysisEvents); session.commit(); profiler.stop(); profiler.start("deleteAnalyses (project_measures)"); analysisUuidsPartitions.forEach(purgeMapper::deleteAnalysisMeasures); session.commit(); profiler.stop(); profiler.start("deleteAnalyses (analysis_properties)"); analysisUuidsPartitions.forEach(purgeMapper::deleteAnalysisProperties); session.commit(); profiler.stop(); profiler.start("deleteAnalyses (snapshots)"); analysisUuidsPartitions.forEach(purgeMapper::deleteAnalyses); session.commit(); profiler.stop(); } void purgeAnalyses(List<String> analysisUuids) { List<List<String>> analysisUuidsPartitions = Lists.partition(analysisUuids, MAX_SNAPSHOTS_PER_QUERY); deleteAnalysisDuplications(analysisUuidsPartitions); profiler.start("updatePurgeStatusToOne (snapshots)"); analysisUuidsPartitions.forEach(purgeMapper::updatePurgeStatusToOne); session.commit(); profiler.stop(); } void purgeDisabledComponents(String rootComponentUuid, Collection<String> disabledComponentUuids, PurgeListener listener) { profiler.start("purgeDisabledComponents (file_sources)"); executeLargeInputs( purgeMapper.selectDisabledComponentsWithFileSource(rootComponentUuid), input -> { purgeMapper.deleteFileSourcesByFileUuid(input); return input; }); profiler.stop(); profiler.start("purgeDisabledComponents (unresolved_issues)"); executeLargeInputs( purgeMapper.selectDisabledComponentsWithUnresolvedIssues(rootComponentUuid), input -> { purgeMapper.resolveComponentIssuesNotAlreadyResolved(input, system2.now()); return input; }); profiler.stop(); profiler.start("purgeDisabledComponents (live_measures)"); executeLargeInputs( purgeMapper.selectDisabledComponentsWithLiveMeasures(rootComponentUuid), input -> { purgeMapper.deleteLiveMeasuresByComponentUuids(input); return input; }); profiler.stop(); session.commit(); } private void deleteAnalysisDuplications(List<List<String>> snapshotUuidsPartitions) { profiler.start("deleteAnalysisDuplications (duplications_index)"); snapshotUuidsPartitions.forEach(purgeMapper::deleteAnalysisDuplications); session.commit(); profiler.stop(); } void deletePermissions(String entityUuid) { profiler.start("deletePermissions (group_roles)"); purgeMapper.deleteGroupRolesByEntityUuid(entityUuid); session.commit(); profiler.stop(); profiler.start("deletePermissions (user_roles)"); purgeMapper.deleteUserRolesByEntityUuid(entityUuid); session.commit(); profiler.stop(); } void deleteIssues(String rootUuid) { profiler.start("deleteIssues (issue_changes)"); purgeMapper.deleteIssueChangesByProjectUuid(rootUuid); session.commit(); profiler.stop(); profiler.start("deleteIssues (new_code_reference_issues)"); purgeMapper.deleteNewCodeReferenceIssuesByProjectUuid(rootUuid); session.commit(); profiler.stop(); profiler.start("deleteIssues (issues)"); purgeMapper.deleteIssuesByProjectUuid(rootUuid); session.commit(); profiler.stop(); } void deleteLinks(String rootUuid) { profiler.start("deleteLinks (project_links)"); purgeMapper.deleteProjectLinksByProjectUuid(rootUuid); session.commit(); profiler.stop(); } void deleteByRootAndSubviews(List<String> rootAndSubviewsUuids) { if (rootAndSubviewsUuids.isEmpty()) { return; } List<List<String>> uuidsPartitions = Lists.partition(rootAndSubviewsUuids, MAX_RESOURCES_PER_QUERY); profiler.start("deleteByRootAndSubviews (properties)"); uuidsPartitions.forEach(purgeMapper::deletePropertiesByEntityUuids); session.commit(); profiler.stop(); profiler.start("deleteByRootAndSubviews (report_schedules)"); uuidsPartitions.forEach(purgeMapper::deleteReportSchedulesByPortfolioUuids); session.commit(); profiler.stop(); profiler.start("deleteByRootAndSubviews (report_subscriptions)"); uuidsPartitions.forEach(purgeMapper::deleteReportSubscriptionsByPortfolioUuids); session.commit(); profiler.stop(); } void deleteDisabledComponentsWithoutIssues(List<String> disabledComponentsWithoutIssue) { if (disabledComponentsWithoutIssue.isEmpty()) { return; } List<List<String>> uuidsPartitions = Lists.partition(disabledComponentsWithoutIssue, MAX_RESOURCES_PER_QUERY); profiler.start("deleteDisabledComponentsWithoutIssues (properties)"); uuidsPartitions.forEach(purgeMapper::deletePropertiesByEntityUuids); session.commit(); profiler.stop(); profiler.start("deleteDisabledComponentsWithoutIssues (projects)"); uuidsPartitions.forEach(purgeMapper::deleteComponentsByUuids); session.commit(); profiler.stop(); } void deleteOutdatedProperties(String branchUuid) { profiler.start("deleteOutdatedProperties (properties)"); purgeMapper.deletePropertiesByEntityUuids(List.of(branchUuid)); session.commit(); profiler.stop(); } void deleteComponents(String rootUuid) { profiler.start("deleteComponents (projects)"); purgeMapper.deleteComponentsByBranchUuid(rootUuid); session.commit(); profiler.stop(); } void deleteNonMainBranchComponentsByProjectUuid(String uuid) { profiler.start("deleteNonMainBranchComponentsByProjectUuid (projects)"); purgeMapper.deleteNonMainBranchComponentsByProjectUuid(uuid); session.commit(); profiler.stop(); } void deleteProject(String projectUuid) { profiler.start("deleteProject (projects)"); purgeMapper.deleteProjectsByProjectUuid(projectUuid); session.commit(); profiler.stop(); } void deleteComponents(List<String> componentUuids) { if (componentUuids.isEmpty()) { return; } profiler.start("deleteComponents (projects)"); Lists.partition(componentUuids, MAX_RESOURCES_PER_QUERY).forEach(purgeMapper::deleteComponentsByUuids); session.commit(); profiler.stop(); } void deleteComponentMeasures(List<String> componentUuids) { if (componentUuids.isEmpty()) { return; } profiler.start("deleteComponentMeasures (project_measures)"); Lists.partition(componentUuids, MAX_RESOURCES_PER_QUERY).forEach(purgeMapper::fullDeleteComponentMeasures); session.commit(); profiler.stop(); } void deleteFileSources(String rootUuid) { profiler.start("deleteFileSources (file_sources)"); purgeMapper.deleteFileSourcesByProjectUuid(rootUuid); session.commit(); profiler.stop(); } void deleteCeActivity(String rootUuid) { profiler.start("deleteCeActivity (ce_scanner_context)"); purgeMapper.deleteCeScannerContextOfCeActivityByRootUuidOrBefore(rootUuid, null, null); session.commit(); profiler.stop(); profiler.start("deleteCeActivity (ce_task_characteristics)"); purgeMapper.deleteCeTaskCharacteristicsOfCeActivityByRootUuidOrBefore(rootUuid, null, null); session.commit(); profiler.stop(); profiler.start("deleteCeActivity (ce_task_input)"); purgeMapper.deleteCeTaskInputOfCeActivityByRootUuidOrBefore(rootUuid, null, null); session.commit(); profiler.stop(); profiler.start("deleteCeActivity (ce_task_message)"); purgeMapper.deleteCeTaskMessageOfCeActivityByRootUuidOrBefore(rootUuid, null, null); session.commit(); profiler.stop(); profiler.start("deleteCeActivity (ce_activity)"); purgeMapper.deleteCeActivityByRootUuidOrBefore(rootUuid, null, null); session.commit(); profiler.stop(); } void deleteCeActivityBefore(@Nullable String rootUuid, @Nullable String entityUuidToPurge, long createdAt) { profiler.start("deleteCeActivityBefore (ce_scanner_context)"); purgeMapper.deleteCeScannerContextOfCeActivityByRootUuidOrBefore(rootUuid, entityUuidToPurge, createdAt); session.commit(); profiler.stop(); profiler.start("deleteCeActivityBefore (ce_task_characteristics)"); purgeMapper.deleteCeTaskCharacteristicsOfCeActivityByRootUuidOrBefore(rootUuid, entityUuidToPurge, createdAt); session.commit(); profiler.stop(); profiler.start("deleteCeActivityBefore (ce_task_input)"); purgeMapper.deleteCeTaskInputOfCeActivityByRootUuidOrBefore(rootUuid, entityUuidToPurge, createdAt); session.commit(); profiler.stop(); profiler.start("deleteCeActivityBefore (ce_task_message)"); purgeMapper.deleteCeTaskMessageOfCeActivityByRootUuidOrBefore(rootUuid, entityUuidToPurge, createdAt); session.commit(); profiler.stop(); profiler.start("deleteCeActivityBefore (ce_activity)"); purgeMapper.deleteCeActivityByRootUuidOrBefore(rootUuid, entityUuidToPurge, createdAt); session.commit(); profiler.stop(); } void deleteCeScannerContextBefore(@Nullable String rootUuid, @Nullable String entityUuidToPurge, long createdAt) { // assuming CeScannerContext of rows in table CE_QUEUE can't be older than createdAt profiler.start("deleteCeScannerContextBefore"); purgeMapper.deleteCeScannerContextOfCeActivityByRootUuidOrBefore(rootUuid, entityUuidToPurge, createdAt); session.commit(); } void deleteCeQueue(String rootUuid) { profiler.start("deleteCeQueue (ce_scanner_context)"); purgeMapper.deleteCeScannerContextOfCeQueueByRootUuid(rootUuid); session.commit(); profiler.stop(); profiler.start("deleteCeQueue (ce_task_characteristics)"); purgeMapper.deleteCeTaskCharacteristicsOfCeQueueByRootUuid(rootUuid); session.commit(); profiler.stop(); profiler.start("deleteCeQueue (ce_task_input)"); purgeMapper.deleteCeTaskInputOfCeQueueByRootUuid(rootUuid); session.commit(); profiler.stop(); profiler.start("deleteCeQueue (ce_task_message)"); purgeMapper.deleteCeTaskMessageOfCeQueueByRootUuid(rootUuid); session.commit(); profiler.stop(); profiler.start("deleteCeQueue (ce_queue)"); purgeMapper.deleteCeQueueByRootUuid(rootUuid); session.commit(); profiler.stop(); } void deleteWebhooks(String rootUuid) { profiler.start("deleteWebhooks (webhooks)"); purgeMapper.deleteWebhooksByProjectUuid(rootUuid); session.commit(); profiler.stop(); } void deleteWebhookDeliveries(String rootUuid) { profiler.start("deleteWebhookDeliveries (webhook_deliveries)"); purgeMapper.deleteWebhookDeliveriesByProjectUuid(rootUuid); session.commit(); profiler.stop(); } void deleteApplicationProjectsByProject(String projectUuid) { profiler.start("deleteApplicationProjectsByProject (app_projects)"); purgeMapper.deleteAppBranchProjectBranchesByProjectUuid(projectUuid); purgeMapper.deleteAppProjectsByProjectUuid(projectUuid); session.commit(); profiler.stop(); } void deleteApplicationProjects(String applicationUuid) { profiler.start("deleteApplicationProjects (app_projects)"); purgeMapper.deleteAppBranchProjectBranchesByAppUuid(applicationUuid); purgeMapper.deleteAppProjectsByAppUuid(applicationUuid); session.commit(); profiler.stop(); } void deleteApplicationBranchProjects(String applicationBranchUuid) { profiler.start("deleteApplicationBranchProjects (app_branch_project_branch)"); purgeMapper.deleteAppBranchProjectsByAppBranchUuid(applicationBranchUuid); session.commit(); profiler.stop(); } public void deleteProjectAlmSettings(String rootUuid) { profiler.start("deleteProjectAlmSettings (project_alm_settings)"); purgeMapper.deleteProjectAlmSettingsByProjectUuid(rootUuid); session.commit(); profiler.stop(); } public void deleteProjectBadgeToken(String rootUuid) { profiler.start("deleteProjectBadgeToken (project_badge_token)"); purgeMapper.deleteProjectBadgeTokenByProjectUuid(rootUuid); session.commit(); profiler.stop(); } void deleteBranch(String rootUuid) { profiler.start("deleteBranch (project_branches)"); purgeMapper.deleteAppBranchProjectBranchesByProjectBranchUuid(rootUuid); purgeMapper.deleteBranchByUuid(rootUuid); session.commit(); profiler.stop(); } void deleteLiveMeasures(String rootUuid) { profiler.start("deleteLiveMeasures (live_measures)"); purgeMapper.deleteLiveMeasuresByProjectUuid(rootUuid); session.commit(); profiler.stop(); } void deleteNewCodePeriods(String rootUuid) { profiler.start("deleteNewCodePeriods (new_code_periods)"); purgeMapper.deleteNewCodePeriodsByRootUuid(rootUuid); session.commit(); profiler.stop(); } void deleteUserDismissedMessages(String projectUuid) { profiler.start("deleteUserDismissedMessages (user_dismissed_messages)"); purgeMapper.deleteUserDismissedMessagesByProjectUuid(projectUuid); session.commit(); profiler.stop(); } public void deleteProjectInPortfolios(String rootUuid) { profiler.start("deleteProjectInPortfolios (portfolio_projects)"); // delete selected project if it's only selecting a single branch corresponding to rootUuid purgeMapper.deletePortfolioProjectsByBranchUuid(rootUuid); // delete selected branches if branch is rootUuid or if it's part of a project that is rootUuid purgeMapper.deletePortfolioProjectBranchesByBranchUuid(rootUuid); // delete selected project if project is rootUuid purgeMapper.deletePortfolioProjectsByProjectUuid(rootUuid); session.commit(); profiler.stop(); } public void deleteScannerCache(String rootUuid) { profiler.start("deleteScannerCache (scanner_analysis_cache)"); purgeMapper.deleteScannerAnalysisCacheByBranchUuid(rootUuid); session.commit(); profiler.stop(); } public void deleteReportSchedules(String rootUuid) { profiler.start("deleteReportSchedules (report_schedules)"); purgeMapper.deleteReportSchedulesByBranchUuid(rootUuid); session.commit(); profiler.stop(); } public void deleteReportSubscriptions(String rootUuid) { profiler.start("deleteReportSubscriptions (report_subscriptions)"); purgeMapper.deleteReportSubscriptionsByBranchUuid(rootUuid); session.commit(); profiler.stop(); } }
18,157
35.171315
166
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/purge/PurgeConfiguration.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.purge; import com.google.common.annotations.VisibleForTesting; import java.util.Date; import java.util.Optional; import java.util.Set; import javax.annotation.CheckForNull; import org.sonar.api.config.Configuration; import org.sonar.api.utils.DateUtils; import org.sonar.api.utils.System2; import org.sonar.core.config.PurgeConstants; public class PurgeConfiguration { private final String rootUuid; private final String projectUuid; private final int maxAgeInDaysOfClosedIssues; private final Optional<Integer> maxAgeInDaysOfInactiveBranches; private final System2 system2; private final Set<String> disabledComponentUuids; public PurgeConfiguration(String rootUuid, String projectUuid, int maxAgeInDaysOfClosedIssues, Optional<Integer> maxAgeInDaysOfInactiveBranches, System2 system2, Set<String> disabledComponentUuids) { this.rootUuid = rootUuid; this.projectUuid = projectUuid; this.maxAgeInDaysOfClosedIssues = maxAgeInDaysOfClosedIssues; this.system2 = system2; this.disabledComponentUuids = disabledComponentUuids; this.maxAgeInDaysOfInactiveBranches = maxAgeInDaysOfInactiveBranches; } public static PurgeConfiguration newDefaultPurgeConfiguration(Configuration config, String rootUuid, String projectUuid, Set<String> disabledComponentUuids) { return new PurgeConfiguration(rootUuid, projectUuid, config.getInt(PurgeConstants.DAYS_BEFORE_DELETING_CLOSED_ISSUES).get(), config.getInt(PurgeConstants.DAYS_BEFORE_DELETING_INACTIVE_BRANCHES_AND_PRS), System2.INSTANCE, disabledComponentUuids); } /** * UUID of the branch being analyzed (root of the component tree). Will be the same as {@link #projectUuid} * if it's the main branch. * Can also be a view. */ public String rootUuid() { return rootUuid; } /** * @return UUID of the main branch of the project */ public String projectUuid() { return projectUuid; } public Set<String> getDisabledComponentUuids() { return disabledComponentUuids; } @CheckForNull public Date maxLiveDateOfClosedIssues() { return maxLiveDateOfClosedIssues(new Date(system2.now())); } public Optional<Date> maxLiveDateOfInactiveBranches() { return maxAgeInDaysOfInactiveBranches.map(age -> DateUtils.addDays(new Date(system2.now()), -age)); } @VisibleForTesting @CheckForNull Date maxLiveDateOfClosedIssues(Date now) { if (maxAgeInDaysOfClosedIssues > 0) { return DateUtils.addDays(now, -maxAgeInDaysOfClosedIssues); } // delete all closed issues return null; } }
3,425
34.6875
160
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/purge/PurgeDao.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.purge; import java.util.Collection; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.utils.DateUtils; import org.sonar.api.utils.System2; import org.sonar.api.utils.TimeUtils; import org.sonar.db.Dao; import org.sonar.db.DbSession; import org.sonar.db.audit.AuditPersister; import org.sonar.db.audit.model.ComponentNewValue; import org.sonar.db.component.BranchDto; import org.sonar.db.component.BranchMapper; import org.sonar.db.component.ComponentDto; import static java.util.Collections.emptyList; import static java.util.Optional.ofNullable; import static org.sonar.api.utils.DateUtils.dateToLong; import static org.sonar.db.DatabaseUtils.executeLargeInputs; public class PurgeDao implements Dao { private static final Logger LOG = LoggerFactory.getLogger(PurgeDao.class); private static final Set<String> QUALIFIERS_PROJECT_VIEW = Set.of("TRK", "VW"); private static final Set<String> QUALIFIER_SUBVIEW = Set.of("SVW"); private static final String SCOPE_PROJECT = "PRJ"; private final System2 system2; private final AuditPersister auditPersister; public PurgeDao(System2 system2, AuditPersister auditPersister) { this.system2 = system2; this.auditPersister = auditPersister; } public void purge(DbSession session, PurgeConfiguration conf, PurgeListener listener, PurgeProfiler profiler) { PurgeMapper mapper = session.getMapper(PurgeMapper.class); PurgeCommands commands = new PurgeCommands(session, mapper, profiler, system2); String rootUuid = conf.rootUuid(); deleteAbortedAnalyses(rootUuid, commands); purgeAnalyses(commands, rootUuid); purgeDisabledComponents(commands, conf, listener); deleteOldClosedIssues(conf, mapper, listener); deleteOrphanIssues(mapper, rootUuid); purgeOldCeActivities(session, rootUuid, commands); purgeOldCeScannerContexts(session, rootUuid, commands); deleteOldDisabledComponents(commands, mapper, rootUuid); purgeStaleBranches(commands, conf, mapper, rootUuid); } private static void purgeStaleBranches(PurgeCommands commands, PurgeConfiguration conf, PurgeMapper mapper, String rootUuid) { Optional<Date> maxDate = conf.maxLiveDateOfInactiveBranches(); if (maxDate.isEmpty()) { // not available if branch plugin is not installed return; } LOG.debug("<- Purge stale branches"); Long maxDateValue = ofNullable(dateToLong(maxDate.get())).orElseThrow(IllegalStateException::new); List<String> branchUuids = mapper.selectStaleBranchesAndPullRequests(conf.projectUuid(), maxDateValue); for (String branchUuid : branchUuids) { if (!rootUuid.equals(branchUuid)) { deleteRootComponent(branchUuid, mapper, commands); } } } private static void purgeAnalyses(PurgeCommands commands, String rootUuid) { List<String> analysisUuids = commands.selectSnapshotUuids( new PurgeSnapshotQuery(rootUuid) .setIslast(false) .setNotPurged(true)); commands.purgeAnalyses(analysisUuids); } private static void purgeDisabledComponents(PurgeCommands commands, PurgeConfiguration conf, PurgeListener listener) { String rootUuid = conf.rootUuid(); commands.purgeDisabledComponents(rootUuid, conf.getDisabledComponentUuids(), listener); } private static void deleteOrphanIssues(PurgeMapper mapper, String rootUuid) { LOG.debug("<- Delete orphan issues"); List<String> issueKeys = mapper.selectBranchOrphanIssues(rootUuid); deleteIssues(mapper, issueKeys); } private static void deleteOldClosedIssues(PurgeConfiguration conf, PurgeMapper mapper, PurgeListener listener) { Date toDate = conf.maxLiveDateOfClosedIssues(); String rootUuid = conf.rootUuid(); List<String> issueKeys = mapper.selectOldClosedIssueKeys(rootUuid, dateToLong(toDate)); deleteIssues(mapper, issueKeys); listener.onIssuesRemoval(rootUuid, issueKeys); } private static void deleteIssues(PurgeMapper mapper, Collection<String> issueKeys) { executeLargeInputs(issueKeys, input -> { mapper.deleteIssueChangesFromIssueKeys(input); return emptyList(); }); executeLargeInputs(issueKeys, input -> { mapper.deleteNewCodeReferenceIssuesFromKeys(input); return emptyList(); }); executeLargeInputs(issueKeys, input -> { mapper.deleteIssuesFromKeys(input); return emptyList(); }); } private static void deleteAbortedAnalyses(String rootUuid, PurgeCommands commands) { LOG.debug("<- Delete aborted builds"); commands.deleteAbortedAnalyses(rootUuid); } private static void deleteOldDisabledComponents(PurgeCommands commands, PurgeMapper mapper, String rootUuid) { List<String> disabledComponentsWithoutIssue = mapper.selectDisabledComponentsWithoutIssues(rootUuid); commands.deleteDisabledComponentsWithoutIssues(disabledComponentsWithoutIssue); } public List<PurgeableAnalysisDto> selectPurgeableAnalyses(String componentUuid, DbSession session) { PurgeMapper mapper = mapper(session); return mapper.selectPurgeableAnalyses(componentUuid).stream() .filter(new NewCodePeriodAnalysisFilter(mapper, componentUuid)) .sorted() .toList(); } public void purgeCeActivities(DbSession session, PurgeProfiler profiler) { PurgeMapper mapper = session.getMapper(PurgeMapper.class); PurgeCommands commands = new PurgeCommands(session, mapper, profiler, system2); purgeOldCeActivities(session, null, commands); } private void purgeOldCeActivities(DbSession session, @Nullable String rootUuid, PurgeCommands commands) { String entityUuidToPurge = getEntityUuidToPurge(session, rootUuid); Date sixMonthsAgo = DateUtils.addDays(new Date(system2.now()), -180); commands.deleteCeActivityBefore(rootUuid, entityUuidToPurge, sixMonthsAgo.getTime()); } /** * When the rootUuid is the main branch of a project, we also want to clean the old activities and context of other branches. * This is probably to ensure that the cleanup happens regularly on branch that are not as active as the main branch. */ @Nullable private static String getEntityUuidToPurge(DbSession session, @Nullable String rootUuid) { if (rootUuid == null) { return null; } BranchDto branch = session.getMapper(BranchMapper.class).selectByUuid(rootUuid); String entityUuidToPurge = null; if (branch != null && branch.isMain()) { entityUuidToPurge = branch.getProjectUuid(); } return entityUuidToPurge; } public void purgeCeScannerContexts(DbSession session, PurgeProfiler profiler) { PurgeMapper mapper = session.getMapper(PurgeMapper.class); PurgeCommands commands = new PurgeCommands(session, mapper, profiler, system2); purgeOldCeScannerContexts(session, null, commands); } private void purgeOldCeScannerContexts(DbSession session, @Nullable String rootUuid, PurgeCommands commands) { Date fourWeeksAgo = DateUtils.addDays(new Date(system2.now()), -28); String entityUuidToPurge = getEntityUuidToPurge(session, rootUuid); commands.deleteCeScannerContextBefore(rootUuid, entityUuidToPurge, fourWeeksAgo.getTime()); } private static final class NewCodePeriodAnalysisFilter implements Predicate<PurgeableAnalysisDto> { @Nullable private final String analysisUuid; private NewCodePeriodAnalysisFilter(PurgeMapper mapper, String componentUuid) { this.analysisUuid = mapper.selectSpecificAnalysisNewCodePeriod(componentUuid); } @Override public boolean test(PurgeableAnalysisDto purgeableAnalysisDto) { return analysisUuid == null || !analysisUuid.equals(purgeableAnalysisDto.getAnalysisUuid()); } } public void deleteBranch(DbSession session, String uuid) { PurgeProfiler profiler = new PurgeProfiler(); PurgeMapper purgeMapper = mapper(session); PurgeCommands purgeCommands = new PurgeCommands(session, profiler, system2); deleteRootComponent(uuid, purgeMapper, purgeCommands); } public void deleteProject(DbSession session, String uuid, String qualifier, String name, String key) { PurgeProfiler profiler = new PurgeProfiler(); PurgeMapper purgeMapper = mapper(session); PurgeCommands purgeCommands = new PurgeCommands(session, profiler, system2); long start = System2.INSTANCE.now(); List<String> branchUuids = session.getMapper(BranchMapper.class).selectByProjectUuid(uuid).stream() // Main branch is deleted last .sorted(Comparator.comparing(BranchDto::isMain)) .map(BranchDto::getUuid) .toList(); branchUuids.forEach(id -> deleteRootComponent(id, purgeMapper, purgeCommands)); deleteRootComponent(uuid, purgeMapper, purgeCommands); auditPersister.deleteComponent(session, new ComponentNewValue(uuid, name, key, qualifier)); logProfiling(profiler, start); } private static void logProfiling(PurgeProfiler profiler, long start) { if (!LOG.isDebugEnabled()) { return; } long duration = System.currentTimeMillis() - start; LOG.debug(""); LOG.atDebug().setMessage(" -------- Profiling for project deletion: {} --------").addArgument(() -> TimeUtils.formatDuration(duration)).log(); LOG.debug(""); for (String line : profiler.getProfilingResult(duration)) { LOG.debug(line); } LOG.debug(""); LOG.debug(" -------- End of profiling for project deletion--------"); LOG.debug(""); } private static void deleteRootComponent(String rootUuid, PurgeMapper mapper, PurgeCommands commands) { List<String> rootAndSubviews = mapper.selectRootAndSubviewsByProjectUuid(rootUuid); commands.deleteLinks(rootUuid); commands.deleteScannerCache(rootUuid); commands.deleteAnalyses(rootUuid); commands.deleteByRootAndSubviews(rootAndSubviews); commands.deleteIssues(rootUuid); commands.deleteFileSources(rootUuid); commands.deleteCeActivity(rootUuid); commands.deleteCeQueue(rootUuid); commands.deleteWebhooks(rootUuid); commands.deleteWebhookDeliveries(rootUuid); commands.deleteLiveMeasures(rootUuid); commands.deleteProjectAlmSettings(rootUuid); commands.deletePermissions(rootUuid); commands.deleteNewCodePeriods(rootUuid); commands.deleteBranch(rootUuid); commands.deleteApplicationBranchProjects(rootUuid); commands.deleteApplicationProjects(rootUuid); commands.deleteApplicationProjectsByProject(rootUuid); commands.deleteProjectInPortfolios(rootUuid); commands.deleteComponents(rootUuid); commands.deleteNonMainBranchComponentsByProjectUuid(rootUuid); commands.deleteProjectBadgeToken(rootUuid); commands.deleteProject(rootUuid); commands.deleteUserDismissedMessages(rootUuid); commands.deleteOutdatedProperties(rootUuid); commands.deleteReportSchedules(rootUuid); commands.deleteReportSubscriptions(rootUuid); } /** * Delete the non root components (ie. sub-view, application or project copy) from the specified collection of {@link ComponentDto} * and data from their child tables. * <p> * This method has no effect when passed an empty collection or only root components. * </p> */ public void deleteNonRootComponentsInView(DbSession dbSession, Collection<ComponentDto> components) { Set<ComponentDto> nonRootComponents = components.stream().filter(PurgeDao::isNotRoot).collect(Collectors.toSet()); if (nonRootComponents.isEmpty()) { return; } PurgeProfiler profiler = new PurgeProfiler(); PurgeCommands purgeCommands = new PurgeCommands(dbSession, profiler, system2); deleteNonRootComponentsInView(nonRootComponents, purgeCommands); } private static void deleteNonRootComponentsInView(Set<ComponentDto> nonRootComponents, PurgeCommands purgeCommands) { List<String> subviewsOrProjectCopies = nonRootComponents.stream() .filter(PurgeDao::isSubview) .map(ComponentDto::uuid) .toList(); purgeCommands.deleteByRootAndSubviews(subviewsOrProjectCopies); List<String> nonRootComponentUuids = nonRootComponents.stream().map(ComponentDto::uuid).toList(); purgeCommands.deleteComponentMeasures(nonRootComponentUuids); purgeCommands.deleteComponents(nonRootComponentUuids); } private static boolean isNotRoot(ComponentDto dto) { return !(SCOPE_PROJECT.equals(dto.scope()) && QUALIFIERS_PROJECT_VIEW.contains(dto.qualifier())); } private static boolean isSubview(ComponentDto dto) { return SCOPE_PROJECT.equals(dto.scope()) && QUALIFIER_SUBVIEW.contains(dto.qualifier()); } public void deleteAnalyses(DbSession session, PurgeProfiler profiler, List<String> analysisUuids) { new PurgeCommands(session, profiler, system2).deleteAnalyses(analysisUuids); } private static PurgeMapper mapper(DbSession session) { return session.getMapper(PurgeMapper.class); } }
13,911
40.777778
146
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/purge/PurgeListener.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.purge; import java.util.List; public interface PurgeListener { PurgeListener EMPTY = new PurgeListener() { @Override public void onIssuesRemoval(String projectUuid, List<String> issueKeys) { // do nothing } }; void onIssuesRemoval(String projectUuid, List<String> issueKeys); }
1,170
32.457143
77
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/purge/PurgeMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.purge; import java.util.List; import java.util.Set; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.apache.ibatis.annotations.Param; public interface PurgeMapper { List<String> selectAnalysisUuids(PurgeSnapshotQuery query); /** * Returns the list of subviews and the application/view/project for the specified project_uuid. */ List<String> selectRootAndSubviewsByProjectUuid(@Param("rootUuid") String rootUuid); Set<String> selectDisabledComponentsWithFileSource(@Param("branchUuid") String branchUuid); Set<String> selectDisabledComponentsWithUnresolvedIssues(@Param("branchUuid") String branchUuid); Set<String> selectDisabledComponentsWithLiveMeasures(@Param("branchUuid") String branchUuid); void deleteAnalyses(@Param("analysisUuids") List<String> analysisUuids); void deleteAnalysisProperties(@Param("analysisUuids") List<String> analysisUuids); void deleteAnalysisDuplications(@Param("analysisUuids") List<String> analysisUuids); void deleteAnalysisEvents(@Param("analysisUuids") List<String> analysisUuids); void deleteAnalysisEventComponentChanges(@Param("analysisUuids") List<String> analysisUuids); void deleteAnalysisMeasures(@Param("analysisUuids") List<String> analysisUuids); void fullDeleteComponentMeasures(@Param("componentUuids") List<String> componentUuids); /** * Purge status flag is used to not attempt to remove duplications & historical data of analyses * for which we already removed them. */ void updatePurgeStatusToOne(@Param("analysisUuids") List<String> analysisUuid); void resolveComponentIssuesNotAlreadyResolved(@Param("componentUuids") List<String> componentUuids, @Param("dateAsLong") Long dateAsLong); void deleteProjectLinksByProjectUuid(@Param("rootUuid") String rootUuid); void deletePropertiesByEntityUuids(@Param("entityUuids") List<String> entityUuids); void deleteComponentsByBranchUuid(@Param("rootUuid") String rootUuid); void deleteNonMainBranchComponentsByProjectUuid(@Param("uuid") String uuid); void deleteProjectsByProjectUuid(@Param("projectUuid") String projectUuid); void deleteComponentsByUuids(@Param("componentUuids") List<String> componentUuids); void deleteGroupRolesByEntityUuid(@Param("entityUuid") String entityUuid); void deleteUserRolesByEntityUuid(@Param("entityUuid") String entityUuid); void deleteEventsByComponentUuid(@Param("componentUuid") String componentUuid); void deleteEventComponentChangesByComponentUuid(@Param("componentUuid") String componentUuid); List<PurgeableAnalysisDto> selectPurgeableAnalyses(@Param("componentUuid") String componentUuid); void deleteIssuesByProjectUuid(@Param("projectUuid") String projectUuid); void deleteIssueChangesByProjectUuid(@Param("projectUuid") String projectUuid); List<String> selectBranchOrphanIssues(@Param("branchUuid") String branchUuid); void deleteNewCodeReferenceIssuesByProjectUuid(@Param("projectUuid") String projectUuid); List<String> selectOldClosedIssueKeys(@Param("projectUuid") String projectUuid, @Nullable @Param("toDate") Long toDate); List<String> selectStaleBranchesAndPullRequests(@Param("projectUuid") String projectUuid, @Param("toDate") Long toDate); @CheckForNull String selectSpecificAnalysisNewCodePeriod(@Param("projectUuid") String projectUuid); List<String> selectDisabledComponentsWithoutIssues(@Param("branchUuid") String branchUuid); void deleteIssuesFromKeys(@Param("keys") List<String> keys); void deleteIssueChangesFromIssueKeys(@Param("issueKeys") List<String> issueKeys); void deleteNewCodeReferenceIssuesFromKeys(@Param("issueKeys") List<String> keys); void deleteFileSourcesByProjectUuid(String rootProjectUuid); void deleteFileSourcesByFileUuid(@Param("fileUuids") List<String> fileUuids); void deleteCeTaskCharacteristicsOfCeActivityByRootUuidOrBefore(@Nullable @Param("rootUuid") String rootUuid, @Nullable @Param("entityUuidToPurge") String entityUuidToPurge, @Nullable @Param("createdAtBefore") Long createdAtBefore); void deleteCeTaskInputOfCeActivityByRootUuidOrBefore(@Nullable @Param("rootUuid") String rootUuid, @Nullable @Param("entityUuidToPurge") String entityUuidToPurge, @Nullable @Param("createdAtBefore") Long createdAtBefore); void deleteCeScannerContextOfCeActivityByRootUuidOrBefore(@Nullable @Param("rootUuid") String rootUuid, @Nullable @Param("entityUuidToPurge") String entityUuidToPurge, @Nullable @Param("createdAtBefore") Long createdAtBefore); void deleteCeTaskMessageOfCeActivityByRootUuidOrBefore(@Nullable @Param("rootUuid") String rootUuid, @Nullable @Param("entityUuidToPurge") String entityUuidToPurge, @Nullable @Param("createdAtBefore") Long createdAtBefore); /** * Delete rows in CE_ACTIVITY of tasks of the specified component and/or created before specified date. */ void deleteCeActivityByRootUuidOrBefore(@Nullable @Param("rootUuid") String rootUuid, @Nullable @Param("entityUuidToPurge") String entityUuidToPurge, @Nullable @Param("createdAtBefore") Long createdAtBefore); void deleteCeScannerContextOfCeQueueByRootUuid(@Param("rootUuid") String rootUuid); void deleteCeTaskCharacteristicsOfCeQueueByRootUuid(@Param("rootUuid") String rootUuid); void deleteCeTaskInputOfCeQueueByRootUuid(@Param("rootUuid") String rootUuid); void deleteCeTaskMessageOfCeQueueByRootUuid(@Param("rootUuid") String rootUuid); void deleteCeQueueByRootUuid(@Param("rootUuid") String rootUuid); void deleteWebhooksByProjectUuid(@Param("projectUuid") String projectUuid); void deleteWebhookDeliveriesByProjectUuid(@Param("projectUuid") String projectUuid); void deleteAppProjectsByAppUuid(@Param("applicationUuid") String applicationUuid); void deleteAppProjectsByProjectUuid(@Param("projectUuid") String projectUuid); void deleteAppBranchProjectBranchesByAppUuid(@Param("applicationUuid") String applicationUuid); void deleteAppBranchProjectBranchesByProjectUuid(@Param("projectUuid") String projectUuid); void deleteAppBranchProjectsByAppBranchUuid(@Param("branchUuid") String applicationBranchUuid); void deleteAppBranchProjectBranchesByProjectBranchUuid(@Param("projectBranchUuid") String projectBranchUuid); void deletePortfolioProjectsByBranchUuid(@Param("branchUuid") String branchUuid); void deletePortfolioProjectsByProjectUuid(@Param("projectUuid") String projectUuid); void deletePortfolioProjectBranchesByBranchUuid(@Param("branchUuid") String branchUuid); void deleteBranchByUuid(@Param("uuid") String uuid); void deleteLiveMeasuresByProjectUuid(@Param("projectUuid") String projectUuid); void deleteLiveMeasuresByComponentUuids(@Param("componentUuids") List<String> componentUuids); void deleteNewCodePeriodsByRootUuid(String rootUuid); void deleteProjectAlmSettingsByProjectUuid(@Param("projectUuid") String projectUuid); void deleteProjectBadgeTokenByProjectUuid(@Param("projectUuid") String rootUuid); void deleteUserDismissedMessagesByProjectUuid(@Param("projectUuid") String projectUuid); void deleteScannerAnalysisCacheByBranchUuid(@Param("branchUuid") String branchUuid); void deleteReportSchedulesByBranchUuid(@Param("branchUuid") String branchUuid); void deleteReportSubscriptionsByBranchUuid(@Param("branchUuid") String branchUuid); void deleteReportSchedulesByPortfolioUuids(@Param("portfolioUuids") List<String> portfolioUuids); void deleteReportSubscriptionsByPortfolioUuids(@Param("portfolioUuids") List<String> portfolioUuids); }
8,396
43.664894
140
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/purge/PurgeProfiler.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.purge; import com.google.common.annotations.VisibleForTesting; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.sonar.api.utils.TimeUtils; public class PurgeProfiler { private final Map<String, Long> durations = new HashMap<>(); private long startTime; private String currentTable; private final Clock clock; public PurgeProfiler() { this(new Clock()); } @VisibleForTesting PurgeProfiler(Clock clock) { this.clock = clock; } public void reset() { durations.clear(); } void start(String table) { this.startTime = clock.now(); this.currentTable = table; } void stop() { Long cumulatedDuration = durations.getOrDefault(currentTable, 0L); durations.put(currentTable, cumulatedDuration + (clock.now() - startTime)); } public List<String> getProfilingResult(long totalTime) { List<Entry<String, Long>> data = new ArrayList<>(durations.entrySet()); data.sort((o1, o2) -> o2.getValue().compareTo(o1.getValue())); double percent = totalTime / 100.0; return truncateList(data).stream().map( entry -> " o " + entry.getKey() + ": " + TimeUtils.formatDuration(entry.getValue()) + " (" + (int) (entry.getValue() / percent) + "%)" ).toList(); } private static List<Entry<String, Long>> truncateList(List<Entry<String, Long>> sortedFullList) { int maxSize = 10; List<Entry<String, Long>> result = new ArrayList<>(maxSize); int i = 0; for (Entry<String, Long> item : sortedFullList) { if (i++ >= maxSize || item.getValue() == 0) { return result; } result.add(item); } return result; } static class Clock { public long now() { return System.currentTimeMillis(); } } }
2,685
28.844444
99
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/purge/PurgeSnapshotQuery.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.purge; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import static java.util.Objects.requireNonNull; public final class PurgeSnapshotQuery { private final String componentUuid; private String[] status; private Boolean islast; /** * If {@code true}, selects only analysis which have not been purged from historical and duplication data before. */ private Boolean notPurged; public PurgeSnapshotQuery(String componentUuid) { this.componentUuid = requireNonNull(componentUuid, "componentUuid can't be null"); } public String getComponentUuid() { return componentUuid; } public String[] getStatus() { return status; } public PurgeSnapshotQuery setStatus(String[] status) { this.status = status; return this; } @CheckForNull public Boolean getIslast() { return islast; } public PurgeSnapshotQuery setIslast(@Nullable Boolean islast) { this.islast = islast; return this; } @CheckForNull public Boolean getNotPurged() { return notPurged; } public PurgeSnapshotQuery setNotPurged(@Nullable Boolean notPurged) { this.notPurged = notPurged; return this; } }
2,046
26.662162
115
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/purge/PurgeableAnalysisDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.purge; import java.util.Date; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.apache.commons.lang.builder.ReflectionToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; /** * Represents an analysis, aka. root snapshot, aka. snapshot of a project or portfolio */ public class PurgeableAnalysisDto implements Comparable<PurgeableAnalysisDto> { private Date date; private String analysisUuid; private String version; private boolean hasEvents; private boolean isLast; public Date getDate() { return date; } public PurgeableAnalysisDto setDate(Long aLong) { this.date = new Date(aLong); return this; } public String getAnalysisUuid() { return analysisUuid; } public PurgeableAnalysisDto setAnalysisUuid(String analysisUuid) { this.analysisUuid = analysisUuid; return this; } public boolean hasEvents() { return hasEvents; } public PurgeableAnalysisDto setHasEvents(boolean b) { this.hasEvents = b; return this; } public boolean isLast() { return isLast; } public PurgeableAnalysisDto setLast(boolean last) { isLast = last; return this; } @CheckForNull public String getVersion() { return version; } public PurgeableAnalysisDto setVersion(@Nullable String version) { this.version = version; return this; } @Override public int compareTo(PurgeableAnalysisDto other) { return date.compareTo(other.date); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PurgeableAnalysisDto that = (PurgeableAnalysisDto) o; return analysisUuid.equals(that.analysisUuid); } @Override public int hashCode() { return analysisUuid.hashCode(); } @Override public String toString() { return new ReflectionToStringBuilder(this, ToStringStyle.SIMPLE_STYLE).toString(); } }
2,852
24.702703
86
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/purge/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.db.purge; import javax.annotation.ParametersAreNonnullByDefault;
959
37.4
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/purge/period/DefaultPeriodCleaner.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.purge.period; import com.google.common.annotations.VisibleForTesting; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.config.Configuration; import org.sonar.api.utils.DateUtils; import org.sonar.db.DbSession; import org.sonar.db.purge.PurgeDao; import org.sonar.db.purge.PurgeProfiler; import org.sonar.db.purge.PurgeableAnalysisDto; public class DefaultPeriodCleaner { private static final Logger LOG = LoggerFactory.getLogger(DefaultPeriodCleaner.class); private final PurgeDao purgeDao; private final PurgeProfiler profiler; public DefaultPeriodCleaner(PurgeDao purgeDao, PurgeProfiler profiler) { this.purgeDao = purgeDao; this.profiler = profiler; } public void clean(DbSession session, String rootUuid, Configuration config) { doClean(rootUuid, new Filters(config).all(), session); } @VisibleForTesting void doClean(String rootUuid, List<Filter> filters, DbSession session) { List<PurgeableAnalysisDto> history = new ArrayList<>(selectAnalysesOfComponent(rootUuid, session)); for (Filter filter : filters) { filter.log(); List<PurgeableAnalysisDto> toDelete = filter.filter(history); List<PurgeableAnalysisDto> deleted = delete(rootUuid, toDelete, session); history.removeAll(deleted); } } private List<PurgeableAnalysisDto> delete(String rootUuid, List<PurgeableAnalysisDto> snapshots, DbSession session) { if (LOG.isDebugEnabled()) { LOG.debug("<- Delete analyses of component {}: {}", rootUuid, snapshots.stream().map(snapshot -> snapshot.getAnalysisUuid() + "@" + DateUtils.formatDateTime(snapshot.getDate())) .collect(Collectors.joining(", "))); } purgeDao.deleteAnalyses( session, profiler, snapshots.stream().map(PurgeableAnalysisDto::getAnalysisUuid).toList()); return snapshots; } private List<PurgeableAnalysisDto> selectAnalysesOfComponent(String componentUuid, DbSession session) { return purgeDao.selectPurgeableAnalyses(componentUuid, session); } }
2,998
37.448718
123
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/purge/period/DeleteAllFilter.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.purge.period; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.sonar.api.utils.DateUtils; import org.slf4j.LoggerFactory; import org.sonar.db.purge.PurgeableAnalysisDto; class DeleteAllFilter implements Filter { private final Date before; public DeleteAllFilter(Date before) { this.before = before; } @Override public List<PurgeableAnalysisDto> filter(List<PurgeableAnalysisDto> history) { List<PurgeableAnalysisDto> result = new ArrayList<>(); for (PurgeableAnalysisDto snapshot : history) { if (snapshot.getDate().before(before)) { result.add(snapshot); } } return result; } @Override public void log() { LoggerFactory.getLogger(getClass()).debug("-> Delete data prior to: {}", DateUtils.formatDate(before)); } }
1,682
31.365385
107
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/purge/period/Filter.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.purge.period; import java.util.List; import org.sonar.db.purge.PurgeableAnalysisDto; interface Filter { List<PurgeableAnalysisDto> filter(List<PurgeableAnalysisDto> snapshots); void log(); }
1,062
34.433333
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/purge/period/Filters.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.purge.period; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import org.apache.commons.lang.time.DateUtils; import org.sonar.api.config.Configuration; import org.sonar.core.config.PurgeConstants; class Filters { private final List<Filter> all = new ArrayList<>(); Filters(Configuration config) { Date dateToStartKeepingOneSnapshotByDay = getDateFromHours(config, PurgeConstants.HOURS_BEFORE_KEEPING_ONLY_ONE_SNAPSHOT_BY_DAY); Date dateToStartKeepingOneSnapshotByWeek = getDateFromWeeks(config, PurgeConstants.WEEKS_BEFORE_KEEPING_ONLY_ONE_SNAPSHOT_BY_WEEK); Date dateToStartKeepingOneSnapshotByMonth = getDateFromWeeks(config, PurgeConstants.WEEKS_BEFORE_KEEPING_ONLY_ONE_SNAPSHOT_BY_MONTH); Date dateToStartKeepingOnlyAnalysisWithVersion = getDateFromWeeks(config, PurgeConstants.WEEKS_BEFORE_KEEPING_ONLY_ANALYSES_WITH_VERSION); Date dateToStartDeletingAllSnapshots = getDateFromWeeks(config, PurgeConstants.WEEKS_BEFORE_DELETING_ALL_SNAPSHOTS); all.add(new KeepOneFilter(dateToStartKeepingOneSnapshotByWeek, dateToStartKeepingOneSnapshotByDay, Calendar.DAY_OF_YEAR, "day")); all.add(new KeepOneFilter(dateToStartKeepingOneSnapshotByMonth, dateToStartKeepingOneSnapshotByWeek, Calendar.WEEK_OF_YEAR, "week")); all.add(new KeepOneFilter(dateToStartDeletingAllSnapshots, dateToStartKeepingOneSnapshotByMonth, Calendar.MONTH, "month")); all.add(new KeepWithVersionFilter(dateToStartKeepingOnlyAnalysisWithVersion)); all.add(new DeleteAllFilter(dateToStartDeletingAllSnapshots)); } static Date getDateFromWeeks(Configuration config, String propertyKey) { int weeks = config.getInt(propertyKey).get(); return DateUtils.addWeeks(new Date(), -weeks); } static Date getDateFromHours(Configuration config, String propertyKey) { int hours = config.getInt(propertyKey).get(); return DateUtils.addHours(new Date(), -hours); } List<Filter> all() { return all; } }
2,856
45.836066
142
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/purge/period/Interval.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.purge.period; import com.google.common.collect.Lists; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import org.apache.commons.lang.time.DateUtils; import org.sonar.db.purge.PurgeableAnalysisDto; final class Interval { List<PurgeableAnalysisDto> snapshots = Lists.newArrayList(); void add(PurgeableAnalysisDto snapshot) { snapshots.add(snapshot); } List<PurgeableAnalysisDto> get() { return snapshots; } int count() { return snapshots.size(); } static List<Interval> group(List<PurgeableAnalysisDto> snapshots, Date start, Date end, int calendarField) { List<Interval> intervals = Lists.newArrayList(); GregorianCalendar calendar = new GregorianCalendar(); int lastYear = -1; int lastFieldValue = -1; Interval currentInterval = null; for (PurgeableAnalysisDto snapshot : snapshots) { if (!DateUtils.isSameDay(start, snapshot.getDate()) && snapshot.getDate().after(start) && (snapshot.getDate().before(end) || DateUtils.isSameDay(end, snapshot.getDate()))) { calendar.setTime(snapshot.getDate()); int currentFieldValue = calendar.get(calendarField); int currentYear = calendar.get(Calendar.YEAR); if (lastYear != currentYear || lastFieldValue != currentFieldValue) { currentInterval = new Interval(); intervals.add(currentInterval); } lastFieldValue = currentFieldValue; lastYear = currentYear; if (currentInterval != null) { currentInterval.add(snapshot); } } } return intervals; } }
2,502
33.287671
110
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/purge/period/KeepOneFilter.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.purge.period; import com.google.common.annotations.VisibleForTesting; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.sonar.api.utils.DateUtils; import org.slf4j.LoggerFactory; import org.sonar.db.purge.PurgeableAnalysisDto; class KeepOneFilter implements Filter { private final Date start; private final Date end; private final int dateField; private final String label; KeepOneFilter(Date start, Date end, int calendarField, String label) { this.start = start; this.end = end; this.dateField = calendarField; this.label = label; } @Override public List<PurgeableAnalysisDto> filter(List<PurgeableAnalysisDto> history) { List<Interval> intervals = Interval.group(history, start, end, dateField); List<PurgeableAnalysisDto> result = new ArrayList<>(); for (Interval interval : intervals) { appendSnapshotsToDelete(interval, result); } return result; } @Override public void log() { LoggerFactory.getLogger(getClass()).debug("-> Keep one snapshot per {} between {} and {}", label, DateUtils.formatDate(start), DateUtils.formatDate(end)); } private static void appendSnapshotsToDelete(Interval interval, List<PurgeableAnalysisDto> toDelete) { if (interval.count() > 1) { List<PurgeableAnalysisDto> deletables = new ArrayList<>(); List<PurgeableAnalysisDto> toKeep = new ArrayList<>(); for (PurgeableAnalysisDto snapshot : interval.get()) { if (isDeletable(snapshot)) { deletables.add(snapshot); } else { toKeep.add(snapshot); } } if (!toKeep.isEmpty()) { toDelete.addAll(deletables); } else if (deletables.size() > 1) { // keep last snapshot toDelete.addAll(deletables.subList(0, deletables.size() - 1)); } } } @VisibleForTesting static boolean isDeletable(PurgeableAnalysisDto snapshot) { return !snapshot.isLast() && !snapshot.hasEvents(); } }
2,859
31.5
158
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/purge/period/KeepWithVersionFilter.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.purge.period; import com.google.common.base.Strings; import java.util.Date; import java.util.List; import org.slf4j.LoggerFactory; import org.sonar.api.utils.DateUtils; import org.sonar.db.purge.PurgeableAnalysisDto; class KeepWithVersionFilter implements Filter { private final Date before; KeepWithVersionFilter(Date before) { this.before = before; } @Override public List<PurgeableAnalysisDto> filter(List<PurgeableAnalysisDto> history) { return history.stream() .filter(analysis -> analysis.getDate().before(before)) .filter(KeepWithVersionFilter::isDeletable) .toList(); } @Override public void log() { LoggerFactory.getLogger(getClass()).debug("-> Keep analyses with a version prior to {}", DateUtils.formatDate(before)); } private static boolean isDeletable(PurgeableAnalysisDto snapshot) { return !snapshot.isLast() && Strings.isNullOrEmpty(snapshot.getVersion()); } }
1,805
31.836364
123
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/purge/period/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.db.purge.period; import javax.annotation.ParametersAreNonnullByDefault;
966
37.68
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/pushevent/PushEventDao.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.pushevent; import java.util.Deque; import java.util.Set; import org.sonar.api.utils.System2; import org.sonar.core.util.UuidFactory; import org.sonar.db.Dao; import org.sonar.db.DbSession; import static org.sonar.db.DatabaseUtils.executeLargeUpdates; public class PushEventDao implements Dao { private final UuidFactory uuidFactory; private final System2 system2; public PushEventDao(System2 system2, UuidFactory uuidFactory) { this.system2 = system2; this.uuidFactory = uuidFactory; } public PushEventDto insert(DbSession dbSession, PushEventDto event) { if (event.getUuid() == null) { event.setUuid(uuidFactory.create()); } if (event.getCreatedAt() == null) { event.setCreatedAt(system2.now()); } mapper(dbSession).insert(event); return event; } public PushEventDto selectByUuid(DbSession dbSession, String uuid) { return mapper(dbSession).selectByUuid(uuid); } public Set<String> selectUuidsOfExpiredEvents(DbSession dbSession, long timestamp) { return mapper(dbSession).selectUuidsOfExpiredEvents(timestamp); } public void deleteByUuids(DbSession dbSession, Set<String> pushEventUuids) { executeLargeUpdates(pushEventUuids, mapper(dbSession)::deleteByUuids); } private static PushEventMapper mapper(DbSession session) { return session.getMapper(PushEventMapper.class); } public Deque<PushEventDto> selectChunkByProjectUuids(DbSession dbSession, Set<String> projectUuids, Long lastPullTimestamp, String lastSeenUuid, long count) { return mapper(dbSession).selectChunkByProjectUuids(projectUuids, lastPullTimestamp, lastSeenUuid, count); } }
2,522
32.197368
109
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/pushevent/PushEventDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.pushevent; import javax.annotation.CheckForNull; import javax.annotation.Nullable; public class PushEventDto { private String uuid; private String name; private String projectUuid; private String language; private byte[] payload; private Long createdAt; public PushEventDto() { // nothing to do } public String getUuid() { return uuid; } public PushEventDto setUuid(String uuid) { this.uuid = uuid; return this; } public String getName() { return name; } public PushEventDto setName(String name) { this.name = name; return this; } public String getProjectUuid() { return projectUuid; } public PushEventDto setProjectUuid(String projectUuid) { this.projectUuid = projectUuid; return this; } @CheckForNull public String getLanguage() { return language; } public PushEventDto setLanguage(@Nullable String language) { this.language = language; return this; } public byte[] getPayload() { return payload; } public PushEventDto setPayload(byte[] payload) { this.payload = payload; return this; } @CheckForNull public Long getCreatedAt() { return createdAt; } public PushEventDto setCreatedAt(long createdAt) { this.createdAt = createdAt; return this; } }
2,172
22.365591
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/pushevent/PushEventMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.pushevent; import java.util.LinkedList; import java.util.List; import java.util.Set; import javax.annotation.CheckForNull; import org.apache.ibatis.annotations.Param; public interface PushEventMapper { void insert(PushEventDto event); @CheckForNull PushEventDto selectByUuid(String uuid); Set<String> selectUuidsOfExpiredEvents(@Param("timestamp") long timestamp); void deleteByUuids(@Param("pushEventUuids") List<String> pushEventUuids); LinkedList<PushEventDto> selectChunkByProjectUuids(@Param("projectUuids") Set<String> projectUuids, @Param("lastPullTimestamp") Long lastPullTimestamp, @Param("lastSeenUuid") String lastSeenUuid, @Param("count") long count); }
1,557
35.232558
101
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/pushevent/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.db.pushevent; import javax.annotation.ParametersAreNonnullByDefault;
963
37.56
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualitygate/ProjectQgateAssociationDao.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualitygate; import java.util.List; import java.util.Optional; import org.sonar.db.Dao; import org.sonar.db.DbSession; public class ProjectQgateAssociationDao implements Dao { public List<ProjectQgateAssociationDto> selectProjects(DbSession dbSession, ProjectQgateAssociationQuery query) { return mapper(dbSession).selectProjects(query); } public List<ProjectQgateAssociationDto> selectAll(DbSession dbSession) { return mapper(dbSession).selectAll(); } /** * @return quality gate uuid if a specific Quality Gate has been defined for the given project uuid. <br> * Returns <code>{@link Optional#empty()}</code> otherwise (ex: default quality gate applies) */ public Optional<String> selectQGateUuidByProjectUuid(DbSession dbSession, String projectUuid) { String uuid = mapper(dbSession).selectQGateUuidByProjectUuid(projectUuid); return Optional.ofNullable(uuid); } private static ProjectQgateAssociationMapper mapper(DbSession session) { return session.getMapper(ProjectQgateAssociationMapper.class); } public void deleteByProjectUuid(DbSession dbSession, String projectUuid) { mapper(dbSession).deleteByProjectUuid(projectUuid); } public void deleteByQGateUuid(DbSession dbSession, String qGateUuid) { mapper(dbSession).deleteByQGateUuid(qGateUuid); } public void insertProjectQGateAssociation(DbSession dbSession, String projectUuid, String qGateUuid) { mapper(dbSession).insertProjectQGateAssociation(projectUuid, qGateUuid); } public void updateProjectQGateAssociation(DbSession dbSession, String projectUuid, String qGateUuid) { mapper(dbSession).updateProjectQGateAssociation(projectUuid, qGateUuid); } }
2,564
37.863636
115
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualitygate/ProjectQgateAssociationDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualitygate; import javax.annotation.CheckForNull; import javax.annotation.Nullable; /** * @since 4.3 */ public class ProjectQgateAssociationDto { private String uuid; private String key; private String name; private String gateUuid; public String getUuid() { return uuid; } public ProjectQgateAssociationDto setUuid(String uuid) { this.uuid = uuid; return this; } public String getKey() { return key; } public ProjectQgateAssociationDto setKey(String key) { this.key = key; return this; } public String getName() { return name; } public ProjectQgateAssociationDto setName(String name) { this.name = name; return this; } @CheckForNull public String getGateUuid() { return gateUuid; } public ProjectQgateAssociationDto setGateUuid(@Nullable String gateUuid) { this.gateUuid = gateUuid; return this; } }
1,770
23.260274
76
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualitygate/ProjectQgateAssociationMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualitygate; import java.util.List; import javax.annotation.CheckForNull; import org.apache.ibatis.annotations.Param; public interface ProjectQgateAssociationMapper { List<ProjectQgateAssociationDto> selectProjects(@Param("query") ProjectQgateAssociationQuery query); List<ProjectQgateAssociationDto> selectAll(); @CheckForNull String selectQGateUuidByProjectUuid(String projectUuid); void deleteByProjectUuid(String projectUuid); void insertProjectQGateAssociation(@Param("projectUuid") String projectUuid, @Param("qGateUuid") String qGateUuid); void deleteByQGateUuid(String qGateUuid); void updateProjectQGateAssociation(@Param("projectUuid") String projectUuid, @Param("qGateUuid") String qGateUuid); }
1,597
35.318182
117
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualitygate/ProjectQgateAssociationQuery.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualitygate; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import java.util.Locale; import java.util.Set; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; import org.sonar.db.DaoUtils; import org.sonar.db.WildcardPosition; public class ProjectQgateAssociationQuery { public static final int DEFAULT_PAGE_INDEX = 1; public static final int DEFAULT_PAGE_SIZE = 100; public static final String ANY = "all"; public static final String IN = "selected"; public static final String OUT = "deselected"; public static final Set<String> AVAILABLE_MEMBERSHIP = ImmutableSet.of(ANY, IN, OUT); private final String gateUuid; private final String membership; private final String projectSearch; // for internal use in MyBatis private final String projectSearchUpperLikeSql; // max results per page private final int pageSize; // index of selected page. Start with 1. private final int pageIndex; private ProjectQgateAssociationQuery(Builder builder) { this.gateUuid = builder.qualityGate.getUuid(); this.membership = builder.membership; this.projectSearch = builder.projectSearch; if (this.projectSearch == null) { this.projectSearchUpperLikeSql = null; } else { this.projectSearchUpperLikeSql = DaoUtils.buildLikeValue(projectSearch.toUpperCase(Locale.ENGLISH), WildcardPosition.BEFORE_AND_AFTER); } this.pageSize = builder.pageSize; this.pageIndex = builder.pageIndex; } public String gateUuid() { return gateUuid; } @CheckForNull public String membership() { return membership; } /** * Search for projects containing a given string */ @CheckForNull public String projectSearch() { return projectSearch; } public int pageSize() { return pageSize; } public int pageIndex() { return pageIndex; } public static Builder builder() { return new Builder(); } public static class Builder { private QualityGateDto qualityGate; private String membership; private String projectSearch; private Integer pageIndex = DEFAULT_PAGE_INDEX; private Integer pageSize = DEFAULT_PAGE_SIZE; private Builder() { } public Builder qualityGate(QualityGateDto qualityGate) { this.qualityGate = qualityGate; return this; } public Builder membership(@Nullable String membership) { this.membership = membership; return this; } public Builder projectSearch(@Nullable String s) { this.projectSearch = StringUtils.defaultIfBlank(s, null); return this; } public Builder pageSize(@Nullable Integer i) { this.pageSize = i; return this; } public Builder pageIndex(@Nullable Integer i) { this.pageIndex = i; return this; } private void initMembership() { if (membership == null) { membership = ProjectQgateAssociationQuery.ANY; } else { Preconditions.checkArgument(AVAILABLE_MEMBERSHIP.contains(membership), "Membership is not valid (got " + membership + "). Available values are " + AVAILABLE_MEMBERSHIP); } } private void initPageSize() { if (pageSize == null) { pageSize = DEFAULT_PAGE_SIZE; } } private void initPageIndex() { if (pageIndex == null) { pageIndex = DEFAULT_PAGE_INDEX; } Preconditions.checkArgument(pageIndex > 0, "Page index must be greater than 0 (got " + pageIndex + ")"); } public ProjectQgateAssociationQuery build() { initMembership(); initPageIndex(); initPageSize(); return new ProjectQgateAssociationQuery(this); } } }
4,618
26.993939
141
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualitygate/QualityGateConditionDao.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualitygate; import java.util.Collection; import java.util.Date; import org.sonar.db.Dao; import org.sonar.db.DbSession; public class QualityGateConditionDao implements Dao { public void insert(QualityGateConditionDto newQualityGate, DbSession session) { mapper(session).insert(newQualityGate.setCreatedAt(new Date())); } public Collection<QualityGateConditionDto> selectForQualityGate(DbSession session, String qGateUuid) { return mapper(session).selectForQualityGate(qGateUuid); } public QualityGateConditionDto selectByUuid(String uuid, DbSession session) { return mapper(session).selectByUuid(uuid); } public void delete(QualityGateConditionDto qGate, DbSession session) { mapper(session).delete(qGate.getUuid()); } public void update(QualityGateConditionDto qGate, DbSession session) { mapper(session).update(qGate.setUpdatedAt(new Date())); } public void deleteConditionsWithInvalidMetrics(DbSession session) { mapper(session).deleteConditionsWithInvalidMetrics(); } private static QualityGateConditionMapper mapper(DbSession session) { return session.getMapper(QualityGateConditionMapper.class); } }
2,036
34.736842
104
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualitygate/QualityGateConditionDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualitygate; import java.util.Date; import javax.annotation.CheckForNull; import javax.annotation.Nullable; /** * @since 4.3 */ public class QualityGateConditionDto { public static final String OPERATOR_GREATER_THAN = "GT"; public static final String OPERATOR_LESS_THAN = "LT"; private String uuid; private String qualityGateUuid; private String metricUuid; private String metricKey; private String operator; private String errorThreshold; private Date createdAt; private Date updatedAt; public String getUuid() { return uuid; } public QualityGateConditionDto setUuid(String uuid) { this.uuid = uuid; return this; } public String getQualityGateUuid() { return qualityGateUuid; } public QualityGateConditionDto setQualityGateUuid(String qualityGateUuid) { this.qualityGateUuid = qualityGateUuid; return this; } public String getMetricUuid() { return metricUuid; } public QualityGateConditionDto setMetricUuid(String metricUuid) { this.metricUuid = metricUuid; return this; } @CheckForNull public String getMetricKey() { return metricKey; } public QualityGateConditionDto setMetricKey(@Nullable String metricKey) { this.metricKey = metricKey; return this; } public String getOperator() { return operator; } public QualityGateConditionDto setOperator(String operator) { this.operator = operator; return this; } public String getErrorThreshold() { return errorThreshold; } public QualityGateConditionDto setErrorThreshold(String errorThreshold) { this.errorThreshold = errorThreshold; return this; } public Date getCreatedAt() { return createdAt; } public QualityGateConditionDto setCreatedAt(Date createdAt) { this.createdAt = createdAt; return this; } public Date getUpdatedAt() { return updatedAt; } public QualityGateConditionDto setUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; return this; } }
2,882
22.25
77
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualitygate/QualityGateConditionMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualitygate; import java.util.List; public interface QualityGateConditionMapper { void insert(QualityGateConditionDto newCondition); List<QualityGateConditionDto> selectForQualityGate(String qGateUuid); void update(QualityGateConditionDto newCondition); QualityGateConditionDto selectByUuid(String uuid); void delete(String uuid); void deleteConditionsWithInvalidMetrics(); }
1,260
32.184211
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualitygate/QualityGateDao.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualitygate; import java.util.Collection; import java.util.Date; import javax.annotation.CheckForNull; import org.apache.ibatis.session.ResultHandler; import org.sonar.core.util.UuidFactory; import org.sonar.db.Dao; import org.sonar.db.DatabaseUtils; import org.sonar.db.DbSession; public class QualityGateDao implements Dao { private final UuidFactory uuidFactory; public QualityGateDao(UuidFactory uuidFactory) { this.uuidFactory = uuidFactory; } public QualityGateDto insert(DbSession session, QualityGateDto newQualityGate) { newQualityGate.setUuid(uuidFactory.create()); mapper(session).insertQualityGate(newQualityGate.setCreatedAt(new Date())); return newQualityGate; } public Collection<QualityGateDto> selectAll(DbSession session) { return mapper(session).selectAll(); } @CheckForNull public QualityGateDto selectByName(DbSession session, String name) { return mapper(session).selectByName(name); } @CheckForNull public QualityGateDto selectByUuid(DbSession session, String uuid) { return mapper(session).selectByUuid(uuid); } @CheckForNull public QualityGateDto selectDefault(DbSession session) { return mapper(session).selectDefault(); } public void delete(QualityGateDto qGate, DbSession session) { mapper(session).delete(qGate.getUuid()); } public void deleteByUuids(DbSession session, Collection<String> uuids) { QualityGateMapper mapper = mapper(session); DatabaseUtils.executeLargeUpdates(uuids, mapper::deleteByUuids); } public void update(QualityGateDto qGate, DbSession session) { mapper(session).update(qGate.setUpdatedAt(new Date())); } public void ensureOneBuiltInQualityGate(DbSession dbSession, String builtInName) { mapper(dbSession).ensureOneBuiltInQualityGate(builtInName); } public void selectQualityGateFindings(DbSession dbSession, String qualityGateUuid, ResultHandler<QualityGateFindingDto> handler) { mapper(dbSession).selectQualityGateFindings(qualityGateUuid, handler); } public QualityGateDto selectBuiltIn(DbSession dbSession) { return mapper(dbSession).selectBuiltIn(); } private static QualityGateMapper mapper(DbSession session) { return session.getMapper(QualityGateMapper.class); } @CheckForNull public QualityGateDto selectByProjectUuid(DbSession dbSession, String projectUuid) { return mapper(dbSession).selectByProjectUuid(projectUuid); } }
3,302
32.363636
132
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualitygate/QualityGateDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualitygate; import java.util.Date; /** * @since 4.3 */ public class QualityGateDto { private String name; private String uuid; private boolean isBuiltIn; private Date createdAt; private Date updatedAt; public String getUuid() { return uuid; } public QualityGateDto setUuid(String uuid) { this.uuid = uuid; return this; } public String getName() { return name; } public QualityGateDto setName(String name) { this.name = name; return this; } public boolean isBuiltIn() { return isBuiltIn; } public QualityGateDto setBuiltIn(boolean builtIn) { isBuiltIn = builtIn; return this; } public Date getCreatedAt() { return createdAt; } public QualityGateDto setCreatedAt(Date createdAt) { this.createdAt = createdAt; return this; } public Date getUpdatedAt() { return updatedAt; } public QualityGateDto setUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; return this; } }
1,859
22.25
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualitygate/QualityGateFindingDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualitygate; public class QualityGateFindingDto { public static final String RATING_VALUE_TYPE = "RATING"; public static final String PERCENT_VALUE_TYPE = "PERCENT"; private String description = null; private String operator = null; private String valueType = null; private String errorThreshold = null; public String getDescription() { return description; } public String getOperatorDescription() { if (isRating(getValueType())) { return RatingType.valueOf(getOperator()).getDescription(); } return PercentageType.valueOf(getOperator()).getDescription(); } public String getErrorThreshold() { if (isRating(getValueType())) { return RatingValue.valueOf(Integer.parseInt(errorThreshold)); } if (isPercentage(getValueType())) { return errorThreshold + "%"; } return errorThreshold; } private String getOperator() { return operator; } private String getValueType() { return valueType; } private static boolean isRating(String metricType) { return RATING_VALUE_TYPE.equals(metricType); } private static boolean isPercentage(String metricType) { return PERCENT_VALUE_TYPE.equals(metricType); } public enum RatingType { LT("Is Better Than"), GT("Is Worse Than"), EQ("Is"), NE("Is Not"); private final String desc; RatingType(String desc) { this.desc = desc; } public String getDescription() { return desc; } } public enum PercentageType { LT("Is Less Than"), GT("Is Greater Than"), EQ("Is Equal To"), NE("Is Not Equal To"); private final String desc; PercentageType(String desc) { this.desc = desc; } public String getDescription() { return desc; } } public enum RatingValue { A, B, C, D, E; public static String valueOf(int index) { return values()[index - 1].name(); } } }
2,791
23.707965
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualitygate/QualityGateGroupPermissionsDao.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualitygate; import java.util.Collection; import java.util.List; import org.sonar.api.utils.System2; import org.sonar.db.Dao; import org.sonar.db.DbSession; import org.sonar.db.Pagination; import org.sonar.db.audit.AuditPersister; import org.sonar.db.audit.model.GroupEditorNewValue; import org.sonar.db.user.GroupDto; import org.sonar.db.user.SearchGroupMembershipDto; import org.sonar.db.user.SearchPermissionQuery; import static org.sonar.db.DatabaseUtils.executeLargeInputs; public class QualityGateGroupPermissionsDao implements Dao { private final System2 system2; private final AuditPersister auditPersister; public QualityGateGroupPermissionsDao(System2 system2, AuditPersister auditPersister) { this.system2 = system2; this.auditPersister = auditPersister; } public boolean exists(DbSession dbSession, QualityGateDto qualityGate, GroupDto group) { return this.exists(dbSession, qualityGate.getUuid(), group.getUuid()); } public boolean exists(DbSession dbSession, String qualityGateUuid, String groupUuid) { return mapper(dbSession).selectByQualityGateAndGroup(qualityGateUuid, groupUuid) != null; } public boolean exists(DbSession dbSession, QualityGateDto qualityGate, Collection<GroupDto> groups) { return !executeLargeInputs(groups.stream().map(GroupDto::getUuid).toList(), partition -> mapper(dbSession).selectByQualityGateAndGroups(qualityGate.getUuid(), partition)) .isEmpty(); } public void insert(DbSession dbSession, QualityGateGroupPermissionsDto dto, String qualityGateName, String groupName) { mapper(dbSession).insert(dto, system2.now()); auditPersister.addQualityGateEditor(dbSession, new GroupEditorNewValue(dto, qualityGateName, groupName)); } public List<SearchGroupMembershipDto> selectByQuery(DbSession dbSession, SearchPermissionQuery query, Pagination pagination) { return mapper(dbSession).selectByQuery(query, pagination); } public int countByQuery(DbSession dbSession, SearchPermissionQuery query) { return mapper(dbSession).countByQuery(query); } public void deleteByGroup(DbSession dbSession, GroupDto group) { int deletedRows = mapper(dbSession).deleteByGroup(group.getUuid()); if (deletedRows > 0) { auditPersister.deleteQualityGateEditor(dbSession, new GroupEditorNewValue(group)); } } public void deleteByQualityGateAndGroup(DbSession dbSession, QualityGateDto qualityGate, GroupDto group) { int deletedRows = mapper(dbSession).delete(qualityGate.getUuid(), group.getUuid()); if (deletedRows > 0) { auditPersister.deleteQualityGateEditor(dbSession, new GroupEditorNewValue(qualityGate, group)); } } public void deleteByQualityGate(DbSession dbSession, QualityGateDto qualityGate) { int deletedRows = mapper(dbSession).deleteByQualityGate(qualityGate.getUuid()); if (deletedRows > 0) { auditPersister.deleteQualityGateEditor(dbSession, new GroupEditorNewValue(qualityGate)); } } private static QualityGateGroupPermissionsMapper mapper(DbSession dbSession) { return dbSession.getMapper(QualityGateGroupPermissionsMapper.class); } }
4,005
39.06
128
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualitygate/QualityGateGroupPermissionsDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualitygate; import java.util.Date; /** * @since 9.2 */ public class QualityGateGroupPermissionsDto { private String uuid; private String groupUuid; private String qualityGateUuid; private Date createdAt; public QualityGateGroupPermissionsDto() { } public String getUuid() { return uuid; } public QualityGateGroupPermissionsDto setUuid(String uuid) { this.uuid = uuid; return this; } public String getGroupUuid() { return groupUuid; } public QualityGateGroupPermissionsDto setGroupUuid(String groupUuid) { this.groupUuid = groupUuid; return this; } public String getQualityGateUuid() { return qualityGateUuid; } public QualityGateGroupPermissionsDto setQualityGateUuid(String qualityGateUuid) { this.qualityGateUuid = qualityGateUuid; return this; } public Date getCreatedAt() { return createdAt; } public QualityGateGroupPermissionsDto setCreatedAt(Date createdAt) { this.createdAt = createdAt; return this; } }
1,884
24.472973
84
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualitygate/QualityGateGroupPermissionsMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualitygate; import java.util.List; import org.apache.ibatis.annotations.Param; import org.sonar.db.Pagination; import org.sonar.db.user.SearchGroupMembershipDto; import org.sonar.db.user.SearchPermissionQuery; public interface QualityGateGroupPermissionsMapper { QualityGateGroupPermissionsDto selectByQualityGateAndGroup(@Param("qualityGateUuid") String qualityGateUuid, @Param("groupUuid") String groupUuid); List<QualityGateGroupPermissionsDto> selectByQualityGateAndGroups(@Param("qualityGateUuid") String qualityGateUuid, @Param("groupUuids") List<String> groupUuids); void insert(@Param("dto") QualityGateGroupPermissionsDto dto, @Param("now") long now); List<SearchGroupMembershipDto> selectByQuery(@Param("query") SearchPermissionQuery query, @Param("pagination") Pagination pagination); int countByQuery(@Param("query") SearchPermissionQuery query); int deleteByGroup(@Param("groupUuid") String groupUuid); int delete(@Param("qualityGateUuid") String qualityGateUuid, @Param("groupUuid") String groupUuid); int deleteByQualityGate(@Param("qualityGateUuid") String qualityGateUuid); }
1,985
41.255319
164
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualitygate/QualityGateMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualitygate; import java.util.Collection; import java.util.List; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.session.ResultHandler; public interface QualityGateMapper { void insertQualityGate(QualityGateDto qualityGate); List<QualityGateDto> selectAll(); QualityGateDto selectByName(String name); QualityGateDto selectBuiltIn(); void delete(String uuid); void deleteByUuids(@Param("uuids") Collection<String> uuids); void update(QualityGateDto qGate); void ensureOneBuiltInQualityGate(String builtInQualityName); void selectQualityGateFindings(String qualityGateUuid, ResultHandler<QualityGateFindingDto> handler); QualityGateDto selectByUuid(String uuid); QualityGateDto selectDefault(); QualityGateDto selectByProjectUuid(@Param("projectUuid") String projectUuid); }
1,696
31.018868
103
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualitygate/QualityGateUserPermissionsDao.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualitygate; import java.util.List; import javax.annotation.Nullable; import org.sonar.api.utils.System2; import org.sonar.db.Dao; import org.sonar.db.DbSession; import org.sonar.db.Pagination; import org.sonar.db.audit.AuditPersister; import org.sonar.db.audit.model.UserEditorNewValue; import org.sonar.db.user.SearchPermissionQuery; import org.sonar.db.user.SearchUserMembershipDto; import org.sonar.db.user.UserDto; public class QualityGateUserPermissionsDao implements Dao { private final System2 system2; private final AuditPersister auditPersister; public QualityGateUserPermissionsDao(System2 system2, AuditPersister auditPersister) { this.system2 = system2; this.auditPersister = auditPersister; } public boolean exists(DbSession dbSession, QualityGateDto qualityGate, UserDto user) { return this.exists(dbSession, qualityGate.getUuid(), user.getUuid()); } public boolean exists(DbSession dbSession, @Nullable String qualityGateUuid, @Nullable String userUuid) { if (qualityGateUuid == null || userUuid == null) { return false; } return selectByQualityGateAndUser(dbSession, qualityGateUuid, userUuid) != null; } public QualityGateUserPermissionsDto selectByQualityGateAndUser(DbSession dbSession, String qualityGateUuid, String userUuid) { return mapper(dbSession).selectByQualityGateAndUser(qualityGateUuid, userUuid); } public void insert(DbSession dbSession, QualityGateUserPermissionsDto dto, String qualityGateName, String userLogin) { mapper(dbSession).insert(dto, system2.now()); auditPersister.addQualityGateEditor(dbSession, new UserEditorNewValue(dto, qualityGateName, userLogin)); } public List<SearchUserMembershipDto> selectByQuery(DbSession dbSession, SearchPermissionQuery query, Pagination pagination) { return mapper(dbSession).selectByQuery(query, pagination); } public int countByQuery(DbSession dbSession, SearchPermissionQuery query) { return mapper(dbSession).countByQuery(query); } public void deleteByQualityGateAndUser(DbSession dbSession, QualityGateDto qualityGate, UserDto user) { int deletedRows = mapper(dbSession).delete(qualityGate.getUuid(), user.getUuid()); if (deletedRows > 0) { auditPersister.deleteQualityGateEditor(dbSession, new UserEditorNewValue(qualityGate, user)); } } public void deleteByUser(DbSession dbSession, UserDto user) { int deletedRows = mapper(dbSession).deleteByUser(user.getUuid()); if (deletedRows > 0) { auditPersister.deleteQualityGateEditor(dbSession, new UserEditorNewValue(user)); } } public void deleteByQualityGate(DbSession dbSession, QualityGateDto qualityGate) { int deletedRows = mapper(dbSession).deleteByQualityGate(qualityGate.getUuid()); if (deletedRows > 0) { auditPersister.deleteQualityGateEditor(dbSession, new UserEditorNewValue(qualityGate)); } } private static QualityGateUserPermissionsMapper mapper(DbSession dbSession) { return dbSession.getMapper(QualityGateUserPermissionsMapper.class); } }
3,924
38.25
129
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualitygate/QualityGateUserPermissionsDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualitygate; public class QualityGateUserPermissionsDto { private String uuid; private String userUuid; private String qualityGateUuid; public QualityGateUserPermissionsDto() { } public QualityGateUserPermissionsDto(String uuid, String userUuid, String qualityGateUuid) { this.uuid = uuid; this.userUuid = userUuid; this.qualityGateUuid = qualityGateUuid; } public String getUuid() { return uuid; } public QualityGateUserPermissionsDto setUuid(String uuid) { this.uuid = uuid; return this; } public String getUserUuid() { return userUuid; } public QualityGateUserPermissionsDto setUserUuid(String userUuid) { this.userUuid = userUuid; return this; } public String getQualityGateUuid() { return qualityGateUuid; } public QualityGateUserPermissionsDto setQualityGateUuid(String qProfileUuid) { this.qualityGateUuid = qProfileUuid; return this; } }
1,807
26.815385
94
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualitygate/QualityGateUserPermissionsMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualitygate; import java.util.List; import org.apache.ibatis.annotations.Param; import org.sonar.db.Pagination; import org.sonar.db.user.SearchPermissionQuery; import org.sonar.db.user.SearchUserMembershipDto; public interface QualityGateUserPermissionsMapper { QualityGateUserPermissionsDto selectByQualityGateAndUser(@Param("qualityGateUuid") String qualityGateUuid, @Param("userUuid") String userUuid); void insert(@Param("dto") QualityGateUserPermissionsDto dto, @Param("now") long now); List<SearchUserMembershipDto> selectByQuery(@Param("query") SearchPermissionQuery query, @Param("pagination") Pagination pagination); int countByQuery(@Param("query") SearchPermissionQuery query); int delete(@Param("qualityGateUuid") String qualityGateUuid, @Param("userUuid") String userUuid); int deleteByUser(@Param("userUuid") String userUuid); int deleteByQualityGate(@Param("qualityGateUuid") String qualityGateUuid); }
1,806
39.155556
145
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualitygate/SearchQualityGatePermissionQuery.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualitygate; import java.util.Locale; import org.sonar.db.user.SearchPermissionQuery; import static java.util.Objects.requireNonNull; import static org.sonar.db.DaoUtils.buildLikeValue; import static org.sonar.db.WildcardPosition.BEFORE_AND_AFTER; public class SearchQualityGatePermissionQuery extends SearchPermissionQuery { private final String qualityGateUuid; public SearchQualityGatePermissionQuery(Builder builder) { this.qualityGateUuid = builder.qualityGate.getUuid(); this.query = builder.getQuery(); this.membership = builder.getMembership(); this.querySql = query == null ? null : buildLikeValue(query, BEFORE_AND_AFTER); this.querySqlLowercase = querySql == null ? null : querySql.toLowerCase(Locale.ENGLISH); } public String getQualityGateUuid() { return qualityGateUuid; } public static Builder builder() { return new Builder(); } public static class Builder extends SearchPermissionQuery.Builder<Builder> { private QualityGateDto qualityGate; public Builder setQualityGate(QualityGateDto qualityGate) { this.qualityGate = qualityGate; return this; } public SearchQualityGatePermissionQuery build() { requireNonNull(qualityGate, "Quality gate cant be null."); initMembership(); return new SearchQualityGatePermissionQuery(this); } } }
2,219
33.6875
92
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualitygate/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.db.qualitygate; import javax.annotation.ParametersAreNonnullByDefault;
965
37.64
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualityprofile/ActiveRuleCountQuery.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualityprofile; import java.util.List; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.rule.RuleStatus; import static com.google.common.base.Preconditions.checkState; public class ActiveRuleCountQuery { private final List<String> profileUuids; private final RuleStatus ruleStatus; private final String inheritance; public ActiveRuleCountQuery(Builder builder) { this.profileUuids = builder.profiles.stream().map(QProfileDto::getKee).toList(); this.ruleStatus = builder.ruleStatus; this.inheritance = builder.inheritance; } public List<String> getProfileUuids() { return profileUuids; } /** * When no rule status is set, removed rules are not returned */ @CheckForNull public RuleStatus getRuleStatus() { return ruleStatus; } @CheckForNull public String getInheritance() { return inheritance; } public static Builder builder() { return new Builder(); } public static class Builder { private List<QProfileDto> profiles; private RuleStatus ruleStatus; private String inheritance; public Builder setProfiles(List<QProfileDto> profiles) { this.profiles = profiles; return this; } public Builder setRuleStatus(@Nullable RuleStatus ruleStatus) { this.ruleStatus = ruleStatus; return this; } public Builder setInheritance(@Nullable String inheritance) { this.inheritance = inheritance; return this; } public ActiveRuleCountQuery build() { checkState(profiles != null, "Profiles cannot be null"); return new ActiveRuleCountQuery(this); } } }
2,519
27.314607
84
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualityprofile/ActiveRuleDao.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualityprofile; import com.google.common.base.Preconditions; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Consumer; import org.sonar.core.util.UuidFactory; import org.sonar.db.Dao; import org.sonar.db.DatabaseUtils; import org.sonar.db.DbSession; import org.sonar.db.rule.RuleParamDto; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Collections.emptyList; import static org.sonar.db.DatabaseUtils.executeLargeInputs; import static org.sonar.db.DatabaseUtils.executeLargeInputsWithoutOutput; import static org.sonar.db.KeyLongValue.toMap; public class ActiveRuleDao implements Dao { private static final String QUALITY_PROFILE_IS_NOT_PERSISTED = "Quality profile is not persisted (missing id)"; private static final String RULE_IS_NOT_PERSISTED = "Rule is not persisted"; private static final String RULE_PARAM_IS_NOT_PERSISTED = "Rule param is not persisted"; private static final String ACTIVE_RULE_IS_NOT_PERSISTED = "ActiveRule is not persisted"; private static final String ACTIVE_RULE_IS_ALREADY_PERSISTED = "ActiveRule is already persisted"; private static final String ACTIVE_RULE_PARAM_IS_NOT_PERSISTED = "ActiveRuleParam is not persisted"; private static final String ACTIVE_RULE_PARAM_IS_ALREADY_PERSISTED = "ActiveRuleParam is already persisted"; private final UuidFactory uuidFactory; public ActiveRuleDao(UuidFactory uuidFactory) { this.uuidFactory = uuidFactory; } public Optional<ActiveRuleDto> selectByKey(DbSession dbSession, ActiveRuleKey key) { return Optional.ofNullable(mapper(dbSession).selectByKey(key.getRuleProfileUuid(), key.getRuleKey().repository(), key.getRuleKey().rule())); } public List<OrgActiveRuleDto> selectByOrgRuleUuid(DbSession dbSession, String ruleUuid) { return mapper(dbSession).selectOrgByRuleUuid(ruleUuid); } public List<ActiveRuleDto> selectByRuleUuid(DbSession dbSession, String ruleUuid) { return mapper(dbSession).selectByRuleUuid(ruleUuid); } public List<OrgActiveRuleDto> selectByRuleUuids(DbSession dbSession, List<String> uuids) { return executeLargeInputs(uuids, chunk -> mapper(dbSession).selectByRuleUuids(chunk)); } /** * Active rule on removed rule are NOT returned */ public List<OrgActiveRuleDto> selectByProfileUuid(DbSession dbSession, String uuid) { return mapper(dbSession).selectByProfileUuid(uuid); } public List<OrgActiveRuleDto> selectByTypeAndProfileUuids(DbSession dbSession, List<Integer> types, List<String> uuids) { return executeLargeInputs(uuids, chunk -> mapper(dbSession).selectByTypeAndProfileUuids(types, chunk)); } public List<OrgActiveRuleDto> selectByProfile(DbSession dbSession, QProfileDto profile) { return selectByProfileUuid(dbSession, profile.getKee()); } public List<ActiveRuleDto> selectByRuleProfile(DbSession dbSession, RulesProfileDto ruleProfileDto) { return mapper(dbSession).selectByRuleProfileUuid(ruleProfileDto.getUuid()); } public Collection<ActiveRuleDto> selectByRulesAndRuleProfileUuids(DbSession dbSession, Collection<String> ruleUuids, Collection<String> ruleProfileUuids) { if (ruleUuids.isEmpty() || ruleProfileUuids.isEmpty()) { return emptyList(); } ActiveRuleMapper mapper = mapper(dbSession); return executeLargeInputs(ruleUuids, ruleUuidsChunk -> executeLargeInputs(ruleProfileUuids, chunk -> mapper.selectByRuleUuidsAndRuleProfileUuids(ruleUuidsChunk, chunk))); } public ActiveRuleDto insert(DbSession dbSession, ActiveRuleDto item) { checkArgument(item.getProfileUuid() != null, QUALITY_PROFILE_IS_NOT_PERSISTED); checkArgument(item.getRuleUuid() != null, RULE_IS_NOT_PERSISTED); checkArgument(item.getUuid() == null, ACTIVE_RULE_IS_ALREADY_PERSISTED); item.setUuid(uuidFactory.create()); mapper(dbSession).insert(item); return item; } public ActiveRuleDto update(DbSession dbSession, ActiveRuleDto item) { checkArgument(item.getProfileUuid() != null, QUALITY_PROFILE_IS_NOT_PERSISTED); checkArgument(item.getRuleUuid() != null, ActiveRuleDao.RULE_IS_NOT_PERSISTED); checkArgument(item.getUuid() != null, ACTIVE_RULE_IS_NOT_PERSISTED); mapper(dbSession).update(item); return item; } public Optional<ActiveRuleDto> delete(DbSession dbSession, ActiveRuleKey key) { Optional<ActiveRuleDto> activeRule = selectByKey(dbSession, key); if (activeRule.isPresent()) { mapper(dbSession).deleteParameters(activeRule.get().getUuid()); mapper(dbSession).delete(activeRule.get().getUuid()); } return activeRule; } public void deleteByRuleProfileUuids(DbSession dbSession, Collection<String> rulesProfileUuids) { ActiveRuleMapper mapper = mapper(dbSession); DatabaseUtils.executeLargeUpdates(rulesProfileUuids, mapper::deleteByRuleProfileUuids); } public void deleteByUuids(DbSession dbSession, List<String> activeRuleUuids) { ActiveRuleMapper mapper = mapper(dbSession); DatabaseUtils.executeLargeUpdates(activeRuleUuids, mapper::deleteByUuids); } public void deleteParametersByRuleProfileUuids(DbSession dbSession, Collection<String> rulesProfileUuids) { ActiveRuleMapper mapper = mapper(dbSession); DatabaseUtils.executeLargeUpdates(rulesProfileUuids, mapper::deleteParametersByRuleProfileUuids); } /** * Nested DTO ActiveRuleParams */ public List<ActiveRuleParamDto> selectParamsByActiveRuleUuid(DbSession dbSession, String activeRuleUuid) { return mapper(dbSession).selectParamsByActiveRuleUuid(activeRuleUuid); } public List<ActiveRuleParamDto> selectParamsByActiveRuleUuids(final DbSession dbSession, List<String> activeRuleUuids) { return executeLargeInputs(activeRuleUuids, mapper(dbSession)::selectParamsByActiveRuleUuids); } public ActiveRuleParamDto insertParam(DbSession dbSession, ActiveRuleDto activeRule, ActiveRuleParamDto activeRuleParam) { checkArgument(activeRule.getUuid() != null, ACTIVE_RULE_IS_NOT_PERSISTED); checkArgument(activeRuleParam.getUuid() == null, ACTIVE_RULE_PARAM_IS_ALREADY_PERSISTED); Preconditions.checkNotNull(activeRuleParam.getRulesParameterUuid(), RULE_PARAM_IS_NOT_PERSISTED); activeRuleParam.setActiveRuleUuid(activeRule.getUuid()); activeRuleParam.setUuid(uuidFactory.create()); mapper(dbSession).insertParameter(activeRuleParam); return activeRuleParam; } public void updateParam(DbSession dbSession, ActiveRuleParamDto activeRuleParam) { Preconditions.checkNotNull(activeRuleParam.getUuid(), ACTIVE_RULE_PARAM_IS_NOT_PERSISTED); mapper(dbSession).updateParameter(activeRuleParam); } public void deleteParam(DbSession dbSession, ActiveRuleParamDto activeRuleParam) { Preconditions.checkNotNull(activeRuleParam.getUuid(), ACTIVE_RULE_PARAM_IS_NOT_PERSISTED); deleteParamByUuid(dbSession, activeRuleParam.getUuid()); } public void deleteParamByUuid(DbSession dbSession, String uuid) { mapper(dbSession).deleteParameter(uuid); } public void deleteParamsByRuleParam(DbSession dbSession, RuleParamDto param) { List<ActiveRuleDto> activeRules = selectByRuleUuid(dbSession, param.getRuleUuid()); for (ActiveRuleDto activeRule : activeRules) { for (ActiveRuleParamDto activeParam : selectParamsByActiveRuleUuid(dbSession, activeRule.getUuid())) { if (activeParam.getKey().equals(param.getName())) { deleteParam(dbSession, activeParam); } } } } public void deleteParamsByActiveRuleUuids(DbSession dbSession, List<String> activeRuleUuids) { ActiveRuleMapper mapper = mapper(dbSession); DatabaseUtils.executeLargeUpdates(activeRuleUuids, mapper::deleteParamsByActiveRuleUuids); } public Map<String, Long> countActiveRulesByQuery(DbSession dbSession, ActiveRuleCountQuery query) { return toMap(executeLargeInputs(query.getProfileUuids(), partition -> mapper(dbSession).countActiveRulesByQuery(partition, query.getRuleStatus(), query.getInheritance()))); } public void scrollAllForIndexing(DbSession dbSession, Consumer<IndexedActiveRuleDto> consumer) { mapper(dbSession).scrollAllForIndexing(context -> { IndexedActiveRuleDto dto = context.getResultObject(); consumer.accept(dto); }); } public void scrollByUuidsForIndexing(DbSession dbSession, Collection<String> uuids, Consumer<IndexedActiveRuleDto> consumer) { ActiveRuleMapper mapper = mapper(dbSession); executeLargeInputsWithoutOutput(uuids, pageOfIds -> mapper .scrollByUuidsForIndexing(pageOfIds, context -> { IndexedActiveRuleDto dto = context.getResultObject(); consumer.accept(dto); })); } public void scrollByRuleProfileForIndexing(DbSession dbSession, String ruleProfileUuid, Consumer<IndexedActiveRuleDto> consumer) { mapper(dbSession).scrollByRuleProfileUuidForIndexing(ruleProfileUuid, context -> { IndexedActiveRuleDto dto = context.getResultObject(); consumer.accept(dto); }); } private static ActiveRuleMapper mapper(DbSession dbSession) { return dbSession.getMapper(ActiveRuleMapper.class); } }
10,053
43.096491
157
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualityprofile/ActiveRuleDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualityprofile; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ReflectionToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import org.sonar.api.rule.RuleKey; import org.sonar.api.rules.ActiveRule; import org.sonar.db.rule.RuleDto; import org.sonar.db.rule.SeverityUtil; import static java.util.Objects.requireNonNull; public class ActiveRuleDto { public static final String INHERITED = ActiveRule.INHERITED; public static final String OVERRIDES = ActiveRule.OVERRIDES; private String uuid; private String profileUuid; private String ruleUuid; private Integer severity; private String inheritance; private long createdAt; private long updatedAt; // These fields do not exists in db, it's only retrieve by joins private String repository; private String ruleField; private String ruleProfileUuid; private String securityStandards; private boolean isExternal; public ActiveRuleDto() { // nothing to do here } public ActiveRuleDto setKey(ActiveRuleKey key) { this.repository = key.getRuleKey().repository(); this.ruleField = key.getRuleKey().rule(); this.ruleProfileUuid = key.getRuleProfileUuid(); return this; } public ActiveRuleKey getKey() { return new ActiveRuleKey(ruleProfileUuid, RuleKey.of(repository, ruleField)); } public RuleKey getRuleKey() { return RuleKey.of(repository, ruleField); } public String getUuid() { return uuid; } public ActiveRuleDto setUuid(String uuid) { this.uuid = uuid; return this; } public String getProfileUuid() { return profileUuid; } public ActiveRuleDto setProfileUuid(String profileUuid) { this.profileUuid = profileUuid; return this; } public String getRuleUuid() { return ruleUuid; } public ActiveRuleDto setRuleUuid(String ruleUuid) { this.ruleUuid = ruleUuid; return this; } public Integer getSeverity() { return severity; } public String getSeverityString() { return SeverityUtil.getSeverityFromOrdinal(severity); } public ActiveRuleDto setSeverity(Integer severity) { this.severity = severity; return this; } public ActiveRuleDto setSeverity(String severity) { this.severity = SeverityUtil.getOrdinalFromSeverity(severity); return this; } @CheckForNull public String getInheritance() { return inheritance; } public ActiveRuleDto setInheritance(@Nullable String inheritance) { this.inheritance = inheritance; return this; } public boolean isInherited() { return StringUtils.equals(INHERITED, inheritance); } public boolean doesOverride() { return StringUtils.equals(OVERRIDES, inheritance); } public long getUpdatedAt() { return updatedAt; } public ActiveRuleDto setUpdatedAt(long updatedAt) { this.updatedAt = updatedAt; return this; } public long getCreatedAt() { return createdAt; } public ActiveRuleDto setCreatedAt(long createdAt) { this.createdAt = createdAt; return this; } public String getSecurityStandards() { return securityStandards; } public ActiveRuleDto setSecurityStandards(String securityStandards) { this.securityStandards = securityStandards; return this; } public boolean isExternal() { return this.isExternal; } public ActiveRuleDto setIsExternal(boolean isExternal) { this.isExternal = isExternal; return this; } public static ActiveRuleDto createFor(QProfileDto profile, RuleDto ruleDto) { requireNonNull(profile.getRulesProfileUuid(), "Profile is not persisted"); requireNonNull(ruleDto.getUuid(), "Rule is not persisted"); ActiveRuleDto dto = new ActiveRuleDto(); dto.setProfileUuid(profile.getRulesProfileUuid()); dto.setRuleUuid(ruleDto.getUuid()); dto.setKey(ActiveRuleKey.of(profile, ruleDto.getKey())); return dto; } @Override public String toString() { return new ReflectionToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).toString(); } }
4,982
25.365079
92
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualityprofile/ActiveRuleKey.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualityprofile; import com.google.common.base.Preconditions; import java.io.Serializable; import org.sonar.api.rule.RuleKey; /** * * @since 4.4 */ public class ActiveRuleKey implements Serializable, Comparable<ActiveRuleKey> { private final String ruleProfileUuid; private final RuleKey ruleKey; protected ActiveRuleKey(String ruleProfileUuid, RuleKey ruleKey) { this.ruleProfileUuid = ruleProfileUuid; this.ruleKey = ruleKey; } /** * Create a key. Parameters are NOT null. */ public static ActiveRuleKey of(QProfileDto profile, RuleKey ruleKey) { return new ActiveRuleKey(profile.getRulesProfileUuid(), ruleKey); } public static ActiveRuleKey of(RulesProfileDto rulesProfile, RuleKey ruleKey) { return new ActiveRuleKey(rulesProfile.getUuid(), ruleKey); } /** * Create a key from a string representation (see {@link #toString()}. An {@link IllegalArgumentException} is raised * if the format is not valid. */ public static ActiveRuleKey parse(String s) { Preconditions.checkArgument(s.split(":").length >= 3, "Bad format of activeRule key: " + s); int semiColonPos = s.indexOf(':'); String ruleProfileUuid = s.substring(0, semiColonPos); String ruleKey = s.substring(semiColonPos + 1); return new ActiveRuleKey(ruleProfileUuid, RuleKey.parse(ruleKey)); } /** * Never null */ public RuleKey getRuleKey() { return ruleKey; } /** * Never null */ public String getRuleProfileUuid() { return ruleProfileUuid; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ActiveRuleKey activeRuleKey = (ActiveRuleKey) o; if (!ruleProfileUuid.equals(activeRuleKey.ruleProfileUuid)) { return false; } return ruleKey.equals(activeRuleKey.ruleKey); } @Override public int hashCode() { int result = ruleProfileUuid.hashCode(); result = 31 * result + ruleKey.hashCode(); return result; } /** * Format is "qprofile:rule", for example "12345:java:AvoidCycle" */ @Override public String toString() { return String.format("%s:%s", ruleProfileUuid, ruleKey.toString()); } @Override public int compareTo(ActiveRuleKey o) { int compareQualityProfileKey = this.ruleProfileUuid.compareTo(o.ruleProfileUuid); if (compareQualityProfileKey == 0) { return this.ruleKey.compareTo(o.ruleKey); } return compareQualityProfileKey; } }
3,392
28.25
118
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualityprofile/ActiveRuleMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualityprofile; import java.util.Collection; import java.util.List; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.session.ResultHandler; import org.sonar.api.rule.RuleStatus; import org.sonar.db.KeyLongValue; public interface ActiveRuleMapper { void insert(ActiveRuleDto dto); void update(ActiveRuleDto dto); void delete(String activeRuleUuid); void deleteByRuleProfileUuids(@Param("rulesProfileUuids") Collection<String> rulesProfileUuids); void deleteByUuids(@Param("uuids") Collection<String> uuids); @CheckForNull ActiveRuleDto selectByKey(@Param("ruleProfileUuid") String ruleProfileUuid, @Param("repository") String repository, @Param("rule") String rule); List<OrgActiveRuleDto> selectOrgByRuleUuid(@Param("ruleUuid") String ruleUuid); List<ActiveRuleDto> selectByRuleUuid(String ruleUuid); List<OrgActiveRuleDto> selectByRuleUuids(@Param("ruleUuids") List<String> partitionOfRuleUuids); List<OrgActiveRuleDto> selectByProfileUuid(String uuid); List<OrgActiveRuleDto> selectByTypeAndProfileUuids(@Param("types") List<Integer> types, @Param("profileUuids") List<String> uuids); List<ActiveRuleDto> selectByRuleProfileUuid(@Param("ruleProfileUuid") String uuid); List<ActiveRuleDto> selectByRuleUuidsAndRuleProfileUuids( @Param("ruleUuids") Collection<String> ruleUuids, @Param("ruleProfileUuids") Collection<String> ruleProfileUuids); void insertParameter(ActiveRuleParamDto dto); void updateParameter(ActiveRuleParamDto dto); void deleteParameters(String activeRuleUuid); void deleteParametersByRuleProfileUuids(@Param("rulesProfileUuids") Collection<String> rulesProfileUuids); void deleteParameter(String activeRuleParamUuid); void deleteParamsByActiveRuleUuids(@Param("activeRuleUuids") Collection<String> activeRuleUuids); List<ActiveRuleParamDto> selectParamsByActiveRuleUuid(String activeRuleUuid); List<ActiveRuleParamDto> selectParamsByActiveRuleUuids(@Param("uuids") List<String> uuids); List<KeyLongValue> countActiveRulesByQuery(@Param("profileUuids") List<String> profileUuids, @Nullable @Param("ruleStatus") RuleStatus ruleStatus, @Param("inheritance") String inheritance); void scrollAllForIndexing(ResultHandler<IndexedActiveRuleDto> handler); void scrollByUuidsForIndexing(@Param("uuids") Collection<String> uuids, ResultHandler<IndexedActiveRuleDto> handler); void scrollByRuleProfileUuidForIndexing(@Param("ruleProfileUuid") String ruleProfileUuid, ResultHandler<IndexedActiveRuleDto> handler); }
3,473
38.477273
146
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualityprofile/ActiveRuleParamDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualityprofile; import com.google.common.base.Preconditions; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.builder.ReflectionToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import org.sonar.db.rule.RuleParamDto; public class ActiveRuleParamDto { private String uuid; private String activeRuleUuid; private String rulesParameterUuid; private String kee; private String value; public String getUuid() { return uuid; } public ActiveRuleParamDto setUuid(String uuid) { this.uuid = uuid; return this; } public String getActiveRuleUuid() { return activeRuleUuid; } public ActiveRuleParamDto setActiveRuleUuid(String activeRuleUuid) { this.activeRuleUuid = activeRuleUuid; return this; } public String getRulesParameterUuid() { return rulesParameterUuid; } // TODO set private or drop public ActiveRuleParamDto setRulesParameterUuid(String rulesParameterUuid) { this.rulesParameterUuid = rulesParameterUuid; return this; } public String getKey() { return kee; } public ActiveRuleParamDto setKey(String key) { this.kee = key; return this; } public String getValue() { return value; } public ActiveRuleParamDto setValue(String value) { this.value = value; return this; } @Override public String toString() { return new ReflectionToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).toString(); } public static ActiveRuleParamDto createFor(RuleParamDto param) { Preconditions.checkArgument(param.getUuid() != null, "Parameter is not persisted"); return new ActiveRuleParamDto() .setKey(param.getName()) .setRulesParameterUuid(param.getUuid()); } public static Map<String, ActiveRuleParamDto> groupByKey(Collection<ActiveRuleParamDto> params) { Map<String, ActiveRuleParamDto> result = new HashMap<>(); for (ActiveRuleParamDto param : params) { result.put(param.getKey(), param); } return result; } }
2,930
27.182692
99
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualityprofile/DefaultQProfileDao.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualityprofile; import java.util.Collection; import java.util.HashSet; import java.util.Optional; import java.util.Set; import org.sonar.api.utils.System2; import org.sonar.db.Dao; import org.sonar.db.DatabaseUtils; import org.sonar.db.DbSession; import static java.util.Collections.singletonList; public class DefaultQProfileDao implements Dao { private final System2 system2; public DefaultQProfileDao(System2 system2) { this.system2 = system2; } public void insertOrUpdate(DbSession dbSession, DefaultQProfileDto dto) { long now = system2.now(); DefaultQProfileMapper mapper = mapper(dbSession); if (mapper.update(dto, now) == 0) { mapper.insert(dto, now); } } public void insert(DbSession dbSession, DefaultQProfileDto dto) { long now = system2.now(); DefaultQProfileMapper mapper = mapper(dbSession); mapper.insert(dto, now); } public void deleteByQProfileUuids(DbSession dbSession, Collection<String> qProfileUuids) { DefaultQProfileMapper mapper = mapper(dbSession); DatabaseUtils.executeLargeUpdates(qProfileUuids, mapper::deleteByQProfileUuids); } public Set<String> selectExistingQProfileUuids(DbSession dbSession, Collection<String> qProfileUuids) { return new HashSet<>(DatabaseUtils.executeLargeInputs(qProfileUuids, uuids -> mapper(dbSession).selectExistingQProfileUuids(uuids))); } public boolean isDefault(DbSession dbSession, String qProfileUuid) { return selectExistingQProfileUuids(dbSession, singletonList(qProfileUuid)).contains(qProfileUuid); } public Optional<String> selectDefaultQProfileUuid(DbSession dbSession, String language) { return mapper(dbSession).selectDefaultQProfileUuid(language); } private static DefaultQProfileMapper mapper(DbSession dbSession) { return dbSession.getMapper(DefaultQProfileMapper.class); } }
2,721
34.815789
137
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualityprofile/DefaultQProfileDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualityprofile; public class DefaultQProfileDto { private String language; private String qProfileUuid; public String getLanguage() { return language; } public DefaultQProfileDto setLanguage(String s) { this.language = s; return this; } public String getQProfileUuid() { return qProfileUuid; } public DefaultQProfileDto setQProfileUuid(String s) { this.qProfileUuid = s; return this; } public static DefaultQProfileDto from(QProfileDto profile) { return new DefaultQProfileDto() .setLanguage(profile.getLanguage()) .setQProfileUuid(profile.getKee()); } @Override public String toString() { StringBuilder sb = new StringBuilder("DefaultQProfileDto{"); sb.append(", language='").append(language).append('\''); sb.append(", qProfileUuid='").append(qProfileUuid).append('\''); sb.append('}'); return sb.toString(); } }
1,776
29.118644
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualityprofile/DefaultQProfileMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualityprofile; import java.util.Collection; import java.util.List; import java.util.Optional; import org.apache.ibatis.annotations.Param; public interface DefaultQProfileMapper { void insert(@Param("dto") DefaultQProfileDto dto, @Param("now") long now); int update(@Param("dto") DefaultQProfileDto dto, @Param("now") long now); void deleteByQProfileUuids(@Param("qProfileUuids") Collection<String> qProfileUuids); List<String> selectExistingQProfileUuids(@Param("qProfileUuids") Collection<String> qProfileUuids); Optional<String> selectDefaultQProfileUuid(@Param("language") String language); }
1,477
37.894737
101
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualityprofile/ExportRuleDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualityprofile; import java.util.LinkedList; import java.util.List; import java.util.Objects; import org.sonar.api.rule.RuleKey; import org.sonar.api.rules.RuleType; import org.sonar.db.rule.SeverityUtil; public class ExportRuleDto { private String activeRuleUuid = null; private String description = null; private String repository = null; private String rule = null; private String name = null; private String extendedDescription = null; private String template = null; private Integer severity = null; private Integer type = null; private String tags = null; private List<ExportRuleParamDto> params = null; public boolean isCustomRule() { return template != null; } public String getActiveRuleUuid() { return activeRuleUuid; } public RuleKey getRuleKey() { return RuleKey.of(repository, rule); } public RuleKey getTemplateRuleKey() { return RuleKey.of(repository, template); } public String getSeverityString() { return SeverityUtil.getSeverityFromOrdinal(severity); } public String getExtendedDescription() { return extendedDescription; } public RuleType getRuleType() { return RuleType.valueOf(type); } public String getTags() { return tags; } public String getName() { return name; } public String getDescriptionOrThrow() { return Objects.requireNonNull(description, "description is expected to be set but it is null"); } public List<ExportRuleParamDto> getParams() { if (params == null) { params = new LinkedList<>(); } return params; } void setParams(List<ExportRuleParamDto> params) { this.params = params; } }
2,532
25.663158
99
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualityprofile/ExportRuleParamDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualityprofile; public class ExportRuleParamDto { private String activeRuleUuid = null; private String kee = null; private String value = null; public String getActiveRuleUuid() { return activeRuleUuid; } public String getKey() { return kee; } public String getValue() { return value; } }
1,187
29.461538
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualityprofile/IndexedActiveRuleDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualityprofile; import javax.annotation.CheckForNull; public class IndexedActiveRuleDto { private String uuid; private String ruleUuid; private int severity; private String inheritance; private String repository; private String key; private String ruleProfileUuid; public IndexedActiveRuleDto() { // nothing to do here } public String getUuid() { return uuid; } public String getRuleUuid() { return ruleUuid; } public int getSeverity() { return severity; } @CheckForNull public String getInheritance() { return inheritance; } public String getRepository() { return repository; } public String getKey() { return key; } public String getRuleProfileUuid() { return ruleProfileUuid; } }
1,637
23.818182
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualityprofile/OrgActiveRuleDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualityprofile; public class OrgActiveRuleDto extends ActiveRuleDto { private String orgProfileUuid; public String getOrgProfileUuid() { return orgProfileUuid; } public OrgActiveRuleDto setOrgProfileUuid(String s) { this.orgProfileUuid = s; return this; } }
1,147
32.764706
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualityprofile/OrgQProfileDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualityprofile; import javax.annotation.CheckForNull; import javax.annotation.Nullable; /** * Maps the table "org_qprofiles", which represents the profiles * available in an organization. * * Extracting organizations from table "rules_profiles" * allows to optimize storage and synchronization of built-in * profiles by implementing an alias mechanism. A built-in profile * is stored once in table "rules_profiles" and is referenced * multiple times in table "org_qprofiles". * User profiles are not shared across organizations, then one row * in "rules_profiles" is referenced by a single row in * "org_qprofiles". */ public class OrgQProfileDto { private String uuid; /** * UUID of referenced row in table "rules_profiles". Not null. */ private String rulesProfileUuid; private String parentUuid; private Long lastUsed; private Long userUpdatedAt; public String getUuid() { return uuid; } public OrgQProfileDto setUuid(String s) { this.uuid = s; return this; } public String getRulesProfileUuid() { return rulesProfileUuid; } public OrgQProfileDto setRulesProfileUuid(String s) { this.rulesProfileUuid = s; return this; } @CheckForNull public String getParentUuid() { return parentUuid; } public OrgQProfileDto setParentUuid(@Nullable String s) { this.parentUuid = s; return this; } @CheckForNull public Long getLastUsed() { return lastUsed; } public OrgQProfileDto setLastUsed(@Nullable Long lastUsed) { this.lastUsed = lastUsed; return this; } @CheckForNull public Long getUserUpdatedAt() { return userUpdatedAt; } public OrgQProfileDto setUserUpdatedAt(@Nullable Long userUpdatedAt) { this.userUpdatedAt = userUpdatedAt; return this; } public static OrgQProfileDto from(QProfileDto qProfileDto) { return new OrgQProfileDto() .setUuid(qProfileDto.getKee()) .setRulesProfileUuid(qProfileDto.getRulesProfileUuid()) .setParentUuid(qProfileDto.getParentKee()) .setLastUsed(qProfileDto.getLastUsed()) .setUserUpdatedAt(qProfileDto.getUserUpdatedAt()); } }
3,009
26.87037
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualityprofile/ProjectQprofileAssociationDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualityprofile; import javax.annotation.CheckForNull; public class ProjectQprofileAssociationDto { private String projectUuid; private String projectKey; private String projectName; private String profileKey; public String getProjectUuid() { return projectUuid; } public String getProjectKey() { return projectKey; } public String getProjectName() { return projectName; } @CheckForNull public String getProfileKey() { return profileKey; } public boolean isAssociated() { return profileKey != null; } }
1,424
26.403846
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualityprofile/QProfileChangeDao.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualityprofile; import java.util.Collection; 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.DatabaseUtils; import org.sonar.db.DbSession; import static com.google.common.base.Preconditions.checkState; public class QProfileChangeDao implements Dao { private final System2 system2; private final UuidFactory uuidFactory; public QProfileChangeDao(System2 system2, UuidFactory uuidFactory) { this.system2 = system2; this.uuidFactory = uuidFactory; } public void insert(DbSession dbSession, QProfileChangeDto dto) { checkState(dto.getCreatedAt() == 0L, "Date of QProfileChangeDto must be set by DAO only. Got %s.", dto.getCreatedAt()); dto.setUuid(uuidFactory.create()); dto.setCreatedAt(system2.now()); mapper(dbSession).insert(dto); } public List<QProfileChangeDto> selectByQuery(DbSession dbSession, QProfileChangeQuery query) { return mapper(dbSession).selectByQuery(query); } /** * Note: offset and limit of the query object will be ignored */ public int countByQuery(DbSession dbSession, QProfileChangeQuery query) { return mapper(dbSession).countByQuery(query); } public void deleteByRulesProfileUuids(DbSession dbSession, Collection<String> ruleProfileUuids) { QProfileChangeMapper mapper = mapper(dbSession); DatabaseUtils.executeLargeUpdates(ruleProfileUuids, mapper::deleteByRuleProfileUuids); } private static QProfileChangeMapper mapper(DbSession dbSession) { return dbSession.getMapper(QProfileChangeMapper.class); } }
2,479
34.942029
123
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualityprofile/QProfileChangeDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualityprofile; import java.util.Collections; import java.util.Map; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.apache.commons.lang.builder.ReflectionToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import org.sonar.api.utils.KeyValueFormat; public class QProfileChangeDto { private String uuid; private String rulesProfileUuid; private String changeType; private String userUuid; private String data; private long createdAt; public String getUuid() { return uuid; } public QProfileChangeDto setUuid(String s) { this.uuid = s; return this; } public String getRulesProfileUuid() { return rulesProfileUuid; } public QProfileChangeDto setRulesProfileUuid(String s) { this.rulesProfileUuid = s; return this; } public String getChangeType() { return changeType; } public QProfileChangeDto setChangeType(String s) { this.changeType = s; return this; } public long getCreatedAt() { return createdAt; } public QProfileChangeDto setCreatedAt(long l) { this.createdAt = l; return this; } @CheckForNull public String getUserUuid() { return userUuid; } public QProfileChangeDto setUserUuid(@Nullable String s) { this.userUuid = s; return this; } @CheckForNull public String getData() { return data; } public Map<String, String> getDataAsMap() { if (data == null) { return Collections.emptyMap(); } return KeyValueFormat.parse(data); } public QProfileChangeDto setData(@Nullable String csv) { this.data = csv; return this; } public QProfileChangeDto setData(@Nullable Map m) { if (m == null || m.isEmpty()) { this.data = null; } else { this.data = KeyValueFormat.format(m); } return this; } @Override public String toString() { return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE); } }
2,845
23.534483
86
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualityprofile/QProfileChangeMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualityprofile; import java.util.Collection; import java.util.List; import org.apache.ibatis.annotations.Param; public interface QProfileChangeMapper { void insert(QProfileChangeDto dto); List<QProfileChangeDto> selectByQuery(@Param("query") QProfileChangeQuery query); int countByQuery(@Param("query") QProfileChangeQuery query); void deleteByRuleProfileUuids(@Param("ruleProfileUuids") Collection<String> uuids); }
1,295
35
85
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualityprofile/QProfileChangeQuery.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualityprofile; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.apache.commons.lang.builder.ReflectionToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import static java.util.Objects.requireNonNull; public final class QProfileChangeQuery { private final String profileUuid; private Long fromIncluded; private Long toExcluded; private int offset = 0; private int limit = 100; public QProfileChangeQuery(String profileUuid) { this.profileUuid = requireNonNull(profileUuid); } public String getProfileUuid() { return profileUuid; } @CheckForNull public Long getFromIncluded() { return fromIncluded; } public void setFromIncluded(@Nullable Long l) { this.fromIncluded = l; } @CheckForNull public Long getToExcluded() { return toExcluded; } public void setToExcluded(@Nullable Long l) { this.toExcluded = l; } public int getOffset() { return offset; } public void setOffset(int offset) { this.offset = offset; } public int getLimit() { return limit; } public void setLimit(int limit) { this.limit = limit; } public void setPage(int page, int pageSize) { offset = (page -1) * pageSize; limit = pageSize; } public int getTotal() { return offset + limit; } @Override public String toString() { return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE); } }
2,335
24.11828
86
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualityprofile/QProfileDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualityprofile; import java.util.Date; import java.util.Objects; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.core.util.UtcDateUtils; /** * Represents the join of "org_qprofiles" and "rules_profiles" */ public class QProfileDto implements Comparable<QProfileDto> { private String kee; private String name; private String language; private String parentKee; private String rulesUpdatedAt; private Long lastUsed; private Long userUpdatedAt; private boolean isBuiltIn; private String rulesProfileUuid; public String getKee() { return kee; } public QProfileDto setKee(String s) { this.kee = s; return this; } public String getRulesProfileUuid() { return rulesProfileUuid; } public QProfileDto setRulesProfileUuid(String s) { this.rulesProfileUuid = s; return this; } public String getName() { return name; } public QProfileDto setName(String name) { this.name = name; return this; } public String getLanguage() { return language; } public QProfileDto setLanguage(String language) { this.language = language; return this; } @CheckForNull public String getParentKee() { return parentKee; } public QProfileDto setParentKee(@Nullable String s) { this.parentKee = s; return this; } public String getRulesUpdatedAt() { return rulesUpdatedAt; } public QProfileDto setRulesUpdatedAt(String s) { this.rulesUpdatedAt = s; return this; } public QProfileDto setRulesUpdatedAtAsDate(Date d) { this.rulesUpdatedAt = UtcDateUtils.formatDateTime(d); return this; } @CheckForNull public Long getLastUsed() { return lastUsed; } public QProfileDto setLastUsed(@Nullable Long lastUsed) { this.lastUsed = lastUsed; return this; } @CheckForNull public Long getUserUpdatedAt() { return userUpdatedAt; } public QProfileDto setUserUpdatedAt(@Nullable Long userUpdatedAt) { this.userUpdatedAt = userUpdatedAt; return this; } public boolean isBuiltIn() { return isBuiltIn; } public QProfileDto setIsBuiltIn(boolean b) { this.isBuiltIn = b; return this; } public static QProfileDto from(OrgQProfileDto org, RulesProfileDto rules) { return new QProfileDto() .setIsBuiltIn(rules.isBuiltIn()) .setKee(org.getUuid()) .setParentKee(org.getParentUuid()) .setRulesProfileUuid(rules.getUuid()) .setLanguage(rules.getLanguage()) .setName(rules.getName()) .setRulesUpdatedAt(rules.getRulesUpdatedAt()) .setLastUsed(org.getLastUsed()) .setUserUpdatedAt(org.getUserUpdatedAt()); } @Override public int compareTo(QProfileDto o) { return kee.compareTo(o.kee); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } QProfileDto that = (QProfileDto) o; return kee.equals(that.kee); } @Override public int hashCode() { return Objects.hash(kee); } }
3,961
22.86747
77
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualityprofile/QProfileEditGroupsDao.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualityprofile; import java.util.Collection; import java.util.Collections; import java.util.List; import org.sonar.api.utils.System2; import org.sonar.db.Dao; import org.sonar.db.DatabaseUtils; import org.sonar.db.DbSession; import org.sonar.db.Pagination; import org.sonar.db.audit.AuditPersister; import org.sonar.db.audit.model.GroupEditorNewValue; import org.sonar.db.user.GroupDto; import org.sonar.db.user.SearchGroupMembershipDto; import static org.sonar.db.DatabaseUtils.executeLargeInputs; import static org.sonar.db.DatabaseUtils.executeLargeUpdates; public class QProfileEditGroupsDao implements Dao { private final System2 system2; private final AuditPersister auditPersister; public QProfileEditGroupsDao(System2 system2, AuditPersister auditPersister) { this.system2 = system2; this.auditPersister = auditPersister; } public boolean exists(DbSession dbSession, QProfileDto profile, GroupDto group) { return exists(dbSession, profile, Collections.singletonList(group)); } public boolean exists(DbSession dbSession, QProfileDto profile, Collection<GroupDto> groups) { return !executeLargeInputs(groups.stream().map(GroupDto::getUuid).toList(), partition -> mapper(dbSession).selectByQProfileAndGroups(profile.getKee(), partition)) .isEmpty(); } public int countByQuery(DbSession dbSession, SearchQualityProfilePermissionQuery query) { return mapper(dbSession).countByQuery(query); } public List<SearchGroupMembershipDto> selectByQuery(DbSession dbSession, SearchQualityProfilePermissionQuery query, Pagination pagination) { return mapper(dbSession).selectByQuery(query, pagination); } public List<String> selectQProfileUuidsByGroups(DbSession dbSession, Collection<GroupDto> groups) { return DatabaseUtils.executeLargeInputs(groups.stream().map(GroupDto::getUuid).toList(), g -> mapper(dbSession).selectQProfileUuidsByGroups(g)); } public void insert(DbSession dbSession, QProfileEditGroupsDto dto, String qualityProfileName, String groupName) { mapper(dbSession).insert(dto, system2.now()); auditPersister.addQualityProfileEditor(dbSession, new GroupEditorNewValue(dto, qualityProfileName, groupName)); } public void deleteByQProfileAndGroup(DbSession dbSession, QProfileDto profile, GroupDto group) { int deletedRows = mapper(dbSession).delete(profile.getKee(), group.getUuid()); if (deletedRows > 0) { auditPersister.deleteQualityProfileEditor(dbSession, new GroupEditorNewValue(profile, group)); } } public void deleteByQProfiles(DbSession dbSession, List<QProfileDto> qProfiles) { executeLargeUpdates(qProfiles, partitionedProfiles -> { int deletedRows = mapper(dbSession).deleteByQProfiles(partitionedProfiles .stream() .map(QProfileDto::getKee) .toList()); if (deletedRows > 0) { partitionedProfiles.forEach(p -> auditPersister.deleteQualityProfileEditor(dbSession, new GroupEditorNewValue(p))); } }); } public void deleteByGroup(DbSession dbSession, GroupDto group) { int deletedRows = mapper(dbSession).deleteByGroup(group.getUuid()); if (deletedRows > 0) { auditPersister.deleteQualityProfileEditor(dbSession, new GroupEditorNewValue(group)); } } private static QProfileEditGroupsMapper mapper(DbSession dbSession) { return dbSession.getMapper(QProfileEditGroupsMapper.class); } }
4,307
38.163636
166
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualityprofile/QProfileEditGroupsDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualityprofile; public class QProfileEditGroupsDto { private String uuid; private String groupUuid; private String qProfileUuid; public String getUuid() { return uuid; } public QProfileEditGroupsDto setUuid(String uuid) { this.uuid = uuid; return this; } public String getGroupUuid() { return groupUuid; } public QProfileEditGroupsDto setGroupUuid(String groupUuid) { this.groupUuid = groupUuid; return this; } public String getQProfileUuid() { return qProfileUuid; } public QProfileEditGroupsDto setQProfileUuid(String qProfileUuid) { this.qProfileUuid = qProfileUuid; return this; } }
1,526
26.267857
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualityprofile/QProfileEditGroupsMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualityprofile; import java.util.Collection; import java.util.List; import org.apache.ibatis.annotations.Param; import org.sonar.db.Pagination; import org.sonar.db.user.SearchGroupMembershipDto; public interface QProfileEditGroupsMapper { List<QProfileEditGroupsDto> selectByQProfileAndGroups(@Param("qProfileUuid") String qProfileUuid, @Param("groupUuids") List<String> groupUuids); int countByQuery(@Param("query") SearchQualityProfilePermissionQuery query); List<SearchGroupMembershipDto> selectByQuery(@Param("query") SearchQualityProfilePermissionQuery query, @Param("pagination") Pagination pagination); List<String> selectQProfileUuidsByGroups(@Param("groupUuids") List<String> groupUuids); void insert(@Param("dto") QProfileEditGroupsDto dto, @Param("now") long now); int delete(@Param("qProfileUuid") String qProfileUuid, @Param("groupUuid") String groupUuid); int deleteByQProfiles(@Param("qProfileUuids") Collection<String> qProfileUuids); int deleteByGroup(@Param("groupUuid") String groupUuid); }
1,901
39.468085
150
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualityprofile/QProfileEditUsersDao.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualityprofile; import java.util.List; import org.sonar.api.utils.System2; import org.sonar.db.Dao; import org.sonar.db.DbSession; import org.sonar.db.Pagination; import org.sonar.db.audit.AuditPersister; import org.sonar.db.audit.model.UserEditorNewValue; import org.sonar.db.user.SearchUserMembershipDto; import org.sonar.db.user.UserDto; import static org.sonar.db.DatabaseUtils.executeLargeUpdates; public class QProfileEditUsersDao implements Dao { private final System2 system2; private final AuditPersister auditPersister; public QProfileEditUsersDao(System2 system2, AuditPersister auditPersister) { this.system2 = system2; this.auditPersister = auditPersister; } public boolean exists(DbSession dbSession, QProfileDto profile, UserDto user) { return mapper(dbSession).selectByQProfileAndUser(profile.getKee(), user.getUuid()) != null; } public int countByQuery(DbSession dbSession, SearchQualityProfilePermissionQuery query) { return mapper(dbSession).countByQuery(query); } public List<SearchUserMembershipDto> selectByQuery(DbSession dbSession, SearchQualityProfilePermissionQuery query, Pagination pagination) { return mapper(dbSession).selectByQuery(query, pagination); } public List<String> selectQProfileUuidsByUser(DbSession dbSession, UserDto userDto) { return mapper(dbSession).selectQProfileUuidsByUser(userDto.getUuid()); } public void insert(DbSession dbSession, QProfileEditUsersDto dto, String qualityProfileName, String userLogin) { mapper(dbSession).insert(dto, system2.now()); auditPersister.addQualityProfileEditor(dbSession, new UserEditorNewValue(dto, qualityProfileName, userLogin)); } public void deleteByQProfileAndUser(DbSession dbSession, QProfileDto profile, UserDto user) { int deletedRows = mapper(dbSession).delete(profile.getKee(), user.getUuid()); if (deletedRows > 0) { auditPersister.deleteQualityProfileEditor(dbSession, new UserEditorNewValue(profile, user)); } } public void deleteByQProfiles(DbSession dbSession, List<QProfileDto> qProfiles) { executeLargeUpdates(qProfiles, partitionedProfiles -> { int deletedRows = mapper(dbSession).deleteByQProfiles(partitionedProfiles .stream() .map(QProfileDto::getKee) .toList()); if (deletedRows > 0) { partitionedProfiles.forEach(p -> auditPersister.deleteQualityProfileEditor(dbSession, new UserEditorNewValue(p))); } }); } public void deleteByUser(DbSession dbSession, UserDto user) { int deletedRows = mapper(dbSession).deleteByUser(user.getUuid()); if (deletedRows > 0) { auditPersister.deleteQualityProfileEditor(dbSession, new UserEditorNewValue(user)); } } private static QProfileEditUsersMapper mapper(DbSession dbSession) { return dbSession.getMapper(QProfileEditUsersMapper.class); } }
3,768
36.69
141
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualityprofile/QProfileEditUsersDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualityprofile; public class QProfileEditUsersDto { private String uuid; private String userUuid; private String qProfileUuid; public String getUuid() { return uuid; } public QProfileEditUsersDto setUuid(String uuid) { this.uuid = uuid; return this; } public String getUserUuid() { return userUuid; } public QProfileEditUsersDto setUserUuid(String userUuid) { this.userUuid = userUuid; return this; } public String getQProfileUuid() { return qProfileUuid; } public QProfileEditUsersDto setQProfileUuid(String qProfileUuid) { this.qProfileUuid = qProfileUuid; return this; } }
1,515
26.071429
75
java
sonarqube
sonarqube-master/server/sonar-db-dao/src/main/java/org/sonar/db/qualityprofile/QProfileEditUsersMapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.qualityprofile; import java.util.Collection; import java.util.List; import org.apache.ibatis.annotations.Param; import org.sonar.db.Pagination; import org.sonar.db.user.SearchUserMembershipDto; public interface QProfileEditUsersMapper { QProfileEditUsersDto selectByQProfileAndUser(@Param("qProfileUuid") String qProfileUuid, @Param("userUuid") String userUuid); int countByQuery(@Param("query") SearchQualityProfilePermissionQuery query); List<SearchUserMembershipDto> selectByQuery(@Param("query") SearchQualityProfilePermissionQuery query, @Param("pagination") Pagination pagination); List<String> selectQProfileUuidsByUser(@Param("userUuid") String userUuid); void insert(@Param("dto") QProfileEditUsersDto dto, @Param("now") long now); int delete(@Param("qProfileUuid") String qProfileUuid, @Param("userUuid") String userUuid); int deleteByQProfiles(@Param("qProfileUuids") Collection<String> qProfileUuids); int deleteByUser(@Param("userUuid") String userUuid); }
1,860
39.456522
149
java