001    /*
002     * Sonar, open source software quality management tool.
003     * Copyright (C) 2008-2011 SonarSource
004     * mailto:contact AT sonarsource DOT com
005     *
006     * Sonar 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     * Sonar 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
017     * License along with Sonar; if not, write to the Free Software
018     * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02
019     */
020    package org.sonar.plugins.dbcleaner.purges;
021    
022    import org.apache.commons.configuration.Configuration;
023    import org.apache.commons.lang.time.DateUtils;
024    import org.sonar.api.database.DatabaseSession;
025    import org.sonar.api.database.model.Snapshot;
026    import org.sonar.api.resources.Scopes;
027    import org.sonar.api.utils.Logs;
028    import org.sonar.plugins.dbcleaner.api.Purge;
029    import org.sonar.plugins.dbcleaner.api.PurgeContext;
030    import org.sonar.plugins.dbcleaner.api.PurgeUtils;
031    
032    import javax.persistence.Query;
033    import java.util.Date;
034    import java.util.List;
035    
036    /**
037     * @since 1.11
038     */
039    public final class PurgeEntities extends Purge {
040    
041      private Configuration configuration;
042    
043      public PurgeEntities(DatabaseSession session, Configuration conf) {
044        super(session);
045        this.configuration = conf;
046      }
047    
048      public void purge(PurgeContext context) {
049        int minimumPeriodInHours = PurgeUtils.getMinimumPeriodInHours(configuration);
050        final Date beforeDate = DateUtils.addHours(new Date(), -minimumPeriodInHours);
051        Logs.INFO.info("Deleting files data before " + beforeDate);
052    
053        Query query = getSession().createQuery("SELECT s.id FROM " + Snapshot.class.getSimpleName() + " s WHERE s.last=:last AND scope=:scope AND s.createdAt<:date");
054        query.setParameter("scope", Scopes.FILE);
055        query.setParameter("date", beforeDate);
056        query.setParameter("last", Boolean.FALSE);
057        List<Integer> snapshotIds = query.getResultList();
058    
059        PurgeUtils.deleteSnapshotsData(getSession(), snapshotIds);
060      }
061    }