3 * Copyright (C) 2009-2016 SonarSource SA
4 * mailto:contact 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.server.computation.task.projectanalysis.step;
22 import java.time.temporal.ChronoUnit;
23 import java.util.Date;
24 import java.util.List;
25 import javax.annotation.CheckForNull;
26 import javax.annotation.Nullable;
27 import org.apache.commons.lang.StringUtils;
28 import org.sonar.api.config.Settings;
29 import org.sonar.api.utils.DateUtils;
30 import org.sonar.api.utils.log.Logger;
31 import org.sonar.api.utils.log.Loggers;
32 import org.sonar.db.DbClient;
33 import org.sonar.db.DbSession;
34 import org.sonar.db.component.SnapshotDto;
35 import org.sonar.db.component.SnapshotQuery;
36 import org.sonar.server.computation.task.projectanalysis.period.Period;
38 import static org.sonar.core.config.CorePropertyDefinitions.TIMEMACHINE_MODE_DATE;
39 import static org.sonar.core.config.CorePropertyDefinitions.TIMEMACHINE_MODE_DAYS;
40 import static org.sonar.core.config.CorePropertyDefinitions.TIMEMACHINE_MODE_PREVIOUS_ANALYSIS;
41 import static org.sonar.core.config.CorePropertyDefinitions.TIMEMACHINE_MODE_PREVIOUS_VERSION;
42 import static org.sonar.core.config.CorePropertyDefinitions.TIMEMACHINE_MODE_VERSION;
43 import static org.sonar.core.config.CorePropertyDefinitions.TIMEMACHINE_PERIOD_PREFIX;
44 import static org.sonar.db.component.SnapshotDto.STATUS_PROCESSED;
45 import static org.sonar.db.component.SnapshotQuery.SORT_FIELD.BY_DATE;
46 import static org.sonar.db.component.SnapshotQuery.SORT_ORDER.ASC;
47 import static org.sonar.db.component.SnapshotQuery.SORT_ORDER.DESC;
49 public class PeriodResolver {
50 private static final Logger LOG = Loggers.get(PeriodResolver.class);
52 private final DbClient dbClient;
53 private final DbSession session;
54 private final String projectUuid;
55 private final long analysisDate;
57 private final String currentVersion;
59 public PeriodResolver(DbClient dbClient, DbSession session, String projectUuid, long analysisDate, @Nullable String currentVersion) {
60 this.dbClient = dbClient;
61 this.session = session;
62 this.projectUuid = projectUuid;
63 this.analysisDate = analysisDate;
64 this.currentVersion = currentVersion;
68 public Period resolve(Settings settings) {
69 String propertyValue = getPropertyValue(settings);
70 if (StringUtils.isBlank(propertyValue)) {
73 Period period = resolve(propertyValue);
74 if (period == null && StringUtils.isNotBlank(propertyValue)) {
75 LOG.debug("Property " + TIMEMACHINE_PERIOD_PREFIX + 1 + " is not valid: " + propertyValue);
81 private Period resolve(String property) {
82 Integer days = tryToResolveByDays(property);
84 return findByDays(days);
86 Date date = DateUtils.parseDateQuietly(property);
88 return findByDate(date);
90 if (StringUtils.equals(TIMEMACHINE_MODE_PREVIOUS_ANALYSIS, property)) {
91 return findByPreviousAnalysis();
93 if (StringUtils.equals(TIMEMACHINE_MODE_PREVIOUS_VERSION, property)) {
94 return findByPreviousVersion();
96 return findByVersion(property);
99 private Period findByDate(Date date) {
100 SnapshotDto snapshot = findFirstSnapshot(session, createCommonQuery(projectUuid).setCreatedAfter(date.getTime()).setSort(BY_DATE, ASC));
101 if (snapshot == null) {
104 LOG.debug("Compare to date {} (analysis of {})", formatDate(date.getTime()), formatDate(snapshot.getCreatedAt()));
105 return new Period(TIMEMACHINE_MODE_DATE, DateUtils.formatDate(date), snapshot.getCreatedAt(), snapshot.getUuid());
109 private Period findByDays(int days) {
110 List<SnapshotDto> snapshots = dbClient.snapshotDao().selectAnalysesByQuery(session, createCommonQuery(projectUuid).setCreatedBefore(analysisDate).setSort(BY_DATE, ASC));
111 long targetDate = DateUtils.addDays(new Date(analysisDate), -days).getTime();
112 SnapshotDto snapshot = findNearestSnapshotToTargetDate(snapshots, targetDate);
113 if (snapshot == null) {
116 LOG.debug("Compare over {} days ({}, analysis of {})", String.valueOf(days), formatDate(targetDate), formatDate(snapshot.getCreatedAt()));
117 return new Period(TIMEMACHINE_MODE_DAYS, String.valueOf(days), snapshot.getCreatedAt(), snapshot.getUuid());
121 private Period findByPreviousAnalysis() {
122 SnapshotDto snapshot = findFirstSnapshot(session, createCommonQuery(projectUuid).setCreatedBefore(analysisDate).setIsLast(true).setSort(BY_DATE, DESC));
123 if (snapshot == null) {
126 LOG.debug("Compare to previous analysis ({})", formatDate(snapshot.getCreatedAt()));
127 return new Period(TIMEMACHINE_MODE_PREVIOUS_ANALYSIS, formatDate(snapshot.getCreatedAt()), snapshot.getCreatedAt(), snapshot.getUuid());
131 private Period findByPreviousVersion() {
132 if (currentVersion == null) {
135 List<SnapshotDto> snapshotDtos = dbClient.snapshotDao().selectPreviousVersionSnapshots(session, projectUuid, currentVersion);
136 if (snapshotDtos.isEmpty()) {
137 // If no previous version is found, the first analysis is returned
138 return findByFirstAnalysis();
140 SnapshotDto snapshotDto = snapshotDtos.get(0);
141 LOG.debug("Compare to previous version ({})", formatDate(snapshotDto.getCreatedAt()));
142 return new Period(TIMEMACHINE_MODE_PREVIOUS_VERSION, snapshotDto.getVersion(), snapshotDto.getCreatedAt(), snapshotDto.getUuid());
146 private Period findByFirstAnalysis() {
147 SnapshotDto snapshotDto = dbClient.snapshotDao().selectOldestSnapshot(session, projectUuid);
148 if (snapshotDto == null) {
151 LOG.debug("Compare to first analysis ({})", formatDate(snapshotDto.getCreatedAt()));
152 return new Period(TIMEMACHINE_MODE_PREVIOUS_VERSION, null, snapshotDto.getCreatedAt(), snapshotDto.getUuid());
156 private Period findByVersion(String version) {
157 SnapshotDto snapshot = findFirstSnapshot(session, createCommonQuery(projectUuid).setVersion(version).setSort(BY_DATE, DESC));
158 if (snapshot == null) {
161 LOG.debug("Compare to version ({}) ({})", version, formatDate(snapshot.getCreatedAt()));
162 return new Period(TIMEMACHINE_MODE_VERSION, version, snapshot.getCreatedAt(), snapshot.getUuid());
166 private SnapshotDto findFirstSnapshot(DbSession session, SnapshotQuery query) {
167 List<SnapshotDto> snapshots = dbClient.snapshotDao().selectAnalysesByQuery(session, query);
168 if (!snapshots.isEmpty()) {
169 return snapshots.get(0);
175 private static Integer tryToResolveByDays(String property) {
177 return Integer.parseInt(property);
178 } catch (NumberFormatException e) {
179 // Nothing to, it means that the property is not a number of days
185 private static SnapshotDto findNearestSnapshotToTargetDate(List<SnapshotDto> snapshots, Long targetDate) {
186 long bestDistance = Long.MAX_VALUE;
187 SnapshotDto nearest = null;
188 for (SnapshotDto snapshot : snapshots) {
189 long distance = Math.abs(snapshot.getCreatedAt() - targetDate);
190 if (distance <= bestDistance) {
191 bestDistance = distance;
198 private static SnapshotQuery createCommonQuery(String projectUuid) {
199 return new SnapshotQuery().setComponentUuid(projectUuid).setStatus(STATUS_PROCESSED);
202 private static String formatDate(long date) {
203 return DateUtils.formatDate(Date.from(new Date(date).toInstant().truncatedTo(ChronoUnit.SECONDS)));
206 private static String getPropertyValue(Settings settings) {
207 return settings.getString(TIMEMACHINE_PERIOD_PREFIX + 1);