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.batch.index;
021
022import org.sonar.api.database.DatabaseSession;
023import org.sonar.api.database.model.Snapshot;
024import org.sonar.api.design.Dependency;
025import org.sonar.api.design.DependencyDto;
026import org.sonar.api.resources.Project;
027
028public final class DependencyPersister {
029
030  private ResourcePersister resourcePersister;
031  private DatabaseSession session;
032
033  public DependencyPersister(ResourcePersister resourcePersister, DatabaseSession session) {
034    this.resourcePersister = resourcePersister;
035    this.session = session;
036  }
037
038  public void saveDependency(Project project, Dependency dependency, Dependency parentDependency) {
039    Snapshot fromSnapshot = resourcePersister.saveResource(project, dependency.getFrom());
040    Snapshot toSnapshot = resourcePersister.saveResource(project, dependency.getTo());
041    Snapshot projectSnapshot = resourcePersister.getSnapshot(project);
042
043    DependencyDto model = new DependencyDto();
044    model.setProjectSnapshotId(projectSnapshot.getId());
045    model.setUsage(dependency.getUsage());
046    model.setWeight(dependency.getWeight());
047
048    model.setFromResourceId(fromSnapshot.getResourceId());
049    model.setFromScope(fromSnapshot.getScope());
050    model.setFromSnapshotId(fromSnapshot.getId());
051
052    model.setToResourceId(toSnapshot.getResourceId());
053    model.setToSnapshotId(toSnapshot.getId());
054    model.setToScope(toSnapshot.getScope());
055
056    if (parentDependency != null) {
057      // assume that it has been previously saved
058      model.setParentDependencyId(parentDependency.getId());
059    }
060    session.save(model);
061    dependency.setId(model.getId());
062  }
063}