001/*
002 * Sonar, open source software quality management tool.
003 * Copyright (C) 2008-2012 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 */
020package org.sonar.plugins.core.timemachine;
021
022import org.sonar.api.batch.Decorator;
023import org.sonar.api.batch.DecoratorContext;
024import org.sonar.api.database.DatabaseSession;
025import org.sonar.api.database.model.Snapshot;
026import org.sonar.api.resources.Project;
027import org.sonar.api.resources.Resource;
028import org.sonar.api.resources.ResourceUtils;
029import org.sonar.batch.components.PastSnapshot;
030import org.sonar.batch.components.TimeMachineConfiguration;
031import org.sonar.core.NotDryRun;
032
033import java.util.List;
034
035@NotDryRun
036public final class TimeMachineConfigurationPersister implements Decorator {
037
038  private TimeMachineConfiguration configuration;
039  private Snapshot projectSnapshot;
040  private DatabaseSession session;
041
042  public TimeMachineConfigurationPersister(TimeMachineConfiguration configuration, Snapshot projectSnapshot, DatabaseSession session) {
043    this.configuration = configuration;
044    this.projectSnapshot = projectSnapshot;
045    this.session = session;
046  }
047
048  public void decorate(Resource resource, DecoratorContext context) {
049    if (ResourceUtils.isProject(resource)) {
050      persistConfiguration();
051    }
052  }
053
054  void persistConfiguration() {
055    List<PastSnapshot> pastSnapshots = configuration.getProjectPastSnapshots();
056    for (PastSnapshot pastSnapshot : pastSnapshots) {
057      projectSnapshot = session.reattach(Snapshot.class, projectSnapshot.getId());
058      projectSnapshot.setPeriodMode(pastSnapshot.getIndex(), pastSnapshot.getMode());
059      projectSnapshot.setPeriodModeParameter(pastSnapshot.getIndex(), pastSnapshot.getModeParameter());
060      projectSnapshot.setPeriodDate(pastSnapshot.getIndex(), pastSnapshot.getTargetDate());
061      session.save(projectSnapshot);
062    }
063    session.commit();
064  }
065
066  public boolean shouldExecuteOnProject(Project project) {
067    return true;
068  }
069}