3 * Copyright (C) 2009-2021 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.utils.System2;
24 import org.sonar.db.DbClient;
25 import org.sonar.db.DbSession;
26 import org.sonar.db.project.ProjectDto;
29 * Creates or updates the data in table {@code PROJECTS} for the current root.
31 public class ProjectPersister {
32 private final DbClient dbClient;
33 private final TreeRootHolder treeRootHolder;
34 private final System2 system2;
36 public ProjectPersister(DbClient dbClient, TreeRootHolder treeRootHolder, System2 system2) {
37 this.dbClient = dbClient;
38 this.treeRootHolder = treeRootHolder;
39 this.system2 = system2;
42 public void persist(DbSession dbSession) {
43 if (shouldSkip(treeRootHolder.getRoot())) {
47 ProjectDto dbProjectDto = dbClient.projectDao().selectProjectByKey(dbSession, treeRootHolder.getRoot().getKey())
48 .orElseThrow(() -> new IllegalStateException("Project has been deleted by end-user during analysis"));
49 ProjectDto projectDto = toProjectDto(treeRootHolder.getRoot());
51 if (hasChanged(dbProjectDto, projectDto)) {
52 // insert or update in projects table
53 dbClient.projectDao().update(dbSession, projectDto);
57 private static boolean shouldSkip(Component rootComponent) {
58 return !rootComponent.getType().equals(Component.Type.PROJECT) && !rootComponent.getType().equals(Component.Type.PROJECT_VIEW);
61 private static boolean hasChanged(ProjectDto dbProject, ProjectDto newProject) {
62 return !StringUtils.equals(dbProject.getName(), newProject.getName()) ||
63 !StringUtils.equals(dbProject.getDescription(), newProject.getDescription());
66 private ProjectDto toProjectDto(Component root) {
67 ProjectDto projectDto = new ProjectDto();
68 projectDto.setUuid(root.getUuid());
69 projectDto.setName(root.getName());
70 projectDto.setDescription(root.getDescription());
71 projectDto.setUpdatedAt(system2.now());