3 * Copyright (C) 2009-2023 SonarSource SA
4 * mailto:info AT sonarsource DOT com
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 3 of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 package org.sonar.ce.task.projectanalysis.component;
22 import org.apache.commons.lang.StringUtils;
23 import org.sonar.api.resources.Qualifiers;
24 import org.sonar.api.utils.System2;
25 import org.sonar.db.DbClient;
26 import org.sonar.db.DbSession;
27 import org.sonar.db.project.ProjectDto;
30 * Creates or updates the data in table {@code PROJECTS} for the current root.
32 public class ProjectPersister {
33 private final DbClient dbClient;
34 private final TreeRootHolder treeRootHolder;
35 private final System2 system2;
37 public ProjectPersister(DbClient dbClient, TreeRootHolder treeRootHolder, System2 system2) {
38 this.dbClient = dbClient;
39 this.treeRootHolder = treeRootHolder;
40 this.system2 = system2;
43 public void persist(DbSession dbSession) {
44 if (shouldSkip(treeRootHolder.getRoot())) {
48 ProjectDto dbProjectDto = dbClient.projectDao().selectProjectByKey(dbSession, treeRootHolder.getRoot().getKey())
49 .orElseThrow(() -> new IllegalStateException("Project has been deleted by end-user during analysis"));
50 ProjectDto projectDto = toProjectDto(treeRootHolder.getRoot());
52 if (hasChanged(dbProjectDto, projectDto)) {
53 // insert or update in projects table
54 dbClient.projectDao().update(dbSession, projectDto);
58 private static boolean shouldSkip(Component rootComponent) {
59 return !rootComponent.getType().equals(Component.Type.PROJECT) && !rootComponent.getType().equals(Component.Type.PROJECT_VIEW);
62 private static boolean hasChanged(ProjectDto dbProject, ProjectDto newProject) {
63 return !StringUtils.equals(dbProject.getName(), newProject.getName()) ||
64 !StringUtils.equals(dbProject.getDescription(), newProject.getDescription());
67 private ProjectDto toProjectDto(Component root) {
68 ProjectDto projectDto = new ProjectDto();
69 projectDto.setUuid(root.getUuid());
70 projectDto.setName(root.getName());
71 projectDto.setDescription(root.getDescription());
72 projectDto.setUpdatedAt(system2.now());
73 projectDto.setKey(root.getKey());
74 projectDto.setQualifier(root.getType().equals(Component.Type.PROJECT) ? Qualifiers.PROJECT : Qualifiers.APP);