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.scan;
021
022 import org.apache.commons.lang.StringUtils;
023 import org.sonar.api.BatchComponent;
024 import org.sonar.api.resources.Resource;
025 import org.sonar.api.resources.ResourceUtils;
026 import org.sonar.api.utils.HttpDownloader;
027 import org.sonar.batch.bootstrap.AnalysisMode;
028 import org.sonar.batch.bootstrap.ServerClient;
029 import org.sonar.core.source.db.SnapshotSourceDao;
030
031 import javax.annotation.CheckForNull;
032
033 public class LastSnapshots implements BatchComponent {
034
035 private final AnalysisMode analysisMode;
036 private final ServerClient server;
037 private final SnapshotSourceDao sourceDao;
038
039 public LastSnapshots(AnalysisMode analysisMode, SnapshotSourceDao dao, ServerClient server) {
040 this.analysisMode = analysisMode;
041 this.sourceDao = dao;
042 this.server = server;
043 }
044
045 @CheckForNull
046 public String getSource(Resource resource) {
047 String source = null;
048 if (ResourceUtils.isFile(resource)) {
049 if (analysisMode.isPreview()) {
050 source = loadSourceFromWs(resource);
051 } else {
052 source = loadSourceFromDb(resource);
053 }
054 }
055 return StringUtils.defaultString(source, "");
056 }
057
058 @CheckForNull
059 private String loadSourceFromWs(Resource resource) {
060 try {
061 return server
062 .request("/api/sources?resource=" + ServerClient.encodeForUrl(resource.getEffectiveKey()) + "&format=txt", false, analysisMode.getPreviewReadTimeoutSec() * 1000);
063 } catch (HttpDownloader.HttpException he) {
064 if (he.getResponseCode() == 404) {
065 return "";
066 }
067 throw he;
068 }
069 }
070
071 @CheckForNull
072 private String loadSourceFromDb(Resource resource) {
073 return sourceDao.selectSnapshotSourceByComponentKey(resource.getEffectiveKey());
074 }
075 }