001 /*
002 * SonarQube, open source software quality management tool.
003 * Copyright (C) 2008-2014 SonarSource
004 * mailto:contact AT sonarsource DOT com
005 *
006 * SonarQube is free software; you can redistribute it and/or
007 * modify it under the terms of the GNU Lesser General Public
008 * License as published by the Free Software Foundation; either
009 * version 3 of the License, or (at your option) any later version.
010 *
011 * SonarQube is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
014 * Lesser General Public License for more details.
015 *
016 * You should have received a copy of the GNU Lesser General Public License
017 * along with this program; if not, write to the Free Software Foundation,
018 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
019 */
020 package org.sonar.batch.components;
021
022 import org.sonar.api.BatchExtension;
023 import org.sonar.api.CoreProperties;
024 import org.sonar.api.database.DatabaseSession;
025 import org.sonar.api.database.model.Snapshot;
026 import org.sonar.api.resources.Qualifiers;
027 import org.sonar.api.utils.DateUtils;
028
029 import javax.annotation.CheckForNull;
030 import java.text.SimpleDateFormat;
031 import java.util.Date;
032 import java.util.List;
033
034 public class PastSnapshotFinderByDate implements BatchExtension {
035
036 private DatabaseSession session;
037
038 public PastSnapshotFinderByDate(DatabaseSession session) {
039 this.session = session;
040 }
041
042 PastSnapshot findByDate(Snapshot projectSnapshot, Date date) {
043 Integer projectId = projectSnapshot != null ? projectSnapshot.getResourceId() : null;
044 return findByDate(projectId, date);
045 }
046
047 PastSnapshot findByDate(Integer projectId, Date date) {
048 Snapshot snapshot = null;
049 if (projectId != null) {
050 snapshot = findSnapshot(projectId, date);
051 }
052 SimpleDateFormat format = new SimpleDateFormat(DateUtils.DATE_FORMAT);
053 return new PastSnapshot(CoreProperties.TIMEMACHINE_MODE_DATE, date, snapshot).setModeParameter(format.format(date));
054 }
055
056 @CheckForNull
057 private Snapshot findSnapshot(Integer projectId, Date date) {
058 String hql = "from " + Snapshot.class.getSimpleName() + " where createdAt>=:date AND resourceId=:resourceId AND status=:status AND qualifier<>:lib order by createdAt asc";
059 List<Snapshot> snapshots = session.createQuery(hql)
060 .setParameter("date", date)
061 .setParameter("resourceId", projectId)
062 .setParameter("status", Snapshot.STATUS_PROCESSED)
063 .setParameter("lib", Qualifiers.LIBRARY)
064 .setMaxResults(1)
065 .getResultList();
066
067 return snapshots.isEmpty() ? null : snapshots.get(0);
068 }
069 }