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.index;
021
022 import com.google.common.collect.Sets;
023 import org.sonar.api.database.model.Snapshot;
024 import org.sonar.api.resources.DuplicatedSourceException;
025 import org.sonar.api.resources.Resource;
026 import org.sonar.core.source.db.SnapshotSourceDao;
027 import org.sonar.core.source.db.SnapshotSourceDto;
028
029 import javax.annotation.CheckForNull;
030
031 import java.util.Set;
032
033 public final class SourcePersister {
034
035 private Set<Integer> savedSnapshotIds = Sets.newHashSet();
036 private ResourcePersister resourcePersister;
037 private final SnapshotSourceDao sourceDao;
038
039 public SourcePersister(ResourcePersister resourcePersister, SnapshotSourceDao sourceDao) {
040 this.resourcePersister = resourcePersister;
041 this.sourceDao = sourceDao;
042 }
043
044 public void saveSource(Resource resource, String source) {
045 Snapshot snapshot = resourcePersister.getSnapshotOrFail(resource);
046 if (isCached(snapshot)) {
047 throw new DuplicatedSourceException(resource);
048 }
049 SnapshotSourceDto dto = new SnapshotSourceDto();
050 dto.setSnapshotId(snapshot.getId().longValue());
051 dto.setData(source);
052 sourceDao.insert(dto);
053 addToCache(snapshot);
054 }
055
056 @CheckForNull
057 public String getSource(Resource resource) {
058 Snapshot snapshot = resourcePersister.getSnapshot(resource);
059 if (snapshot != null && snapshot.getId() != null) {
060 return sourceDao.selectSnapshotSource(snapshot.getId());
061 }
062 return null;
063 }
064
065 private boolean isCached(Snapshot snapshot) {
066 return savedSnapshotIds.contains(snapshot.getId());
067 }
068
069 private void addToCache(Snapshot snapshot) {
070 savedSnapshotIds.add(snapshot.getId());
071 }
072
073 public void clear() {
074 savedSnapshotIds.clear();
075 }
076 }