import org.sonar.core.metric.DefaultMetricFinder;
import org.sonar.core.notification.DefaultNotificationManager;
import org.sonar.core.permission.PermissionFacade;
-import org.sonar.core.persistence.*;
+import org.sonar.core.persistence.DaoUtils;
+import org.sonar.core.persistence.DatabaseVersion;
+import org.sonar.core.persistence.DefaultDatabase;
+import org.sonar.core.persistence.MyBatis;
+import org.sonar.core.persistence.PreviewDatabaseFactory;
+import org.sonar.core.persistence.SemaphoreUpdater;
+import org.sonar.core.persistence.SemaphoresImpl;
import org.sonar.core.preview.PreviewCache;
import org.sonar.core.profiling.Profiling;
import org.sonar.core.purge.PurgeProfiler;
import org.sonar.server.activity.ws.ActivitiesWebService;
import org.sonar.server.activity.ws.ActivityMapping;
import org.sonar.server.authentication.ws.AuthenticationWs;
-import org.sonar.server.batch.*;
+import org.sonar.server.batch.BatchIndex;
+import org.sonar.server.batch.BatchWs;
+import org.sonar.server.batch.GlobalReferentialsAction;
+import org.sonar.server.batch.ProjectReferentialsAction;
+import org.sonar.server.batch.UploadReportAction;
import org.sonar.server.charts.ChartFactory;
import org.sonar.server.component.ComponentCleanerService;
import org.sonar.server.component.ComponentService;
import org.sonar.server.component.DefaultRubyComponentService;
import org.sonar.server.component.db.ComponentDao;
import org.sonar.server.component.db.SnapshotDao;
-import org.sonar.server.component.ws.*;
-import org.sonar.server.computation.*;
+import org.sonar.server.component.ws.ComponentAppAction;
+import org.sonar.server.component.ws.ComponentsWs;
+import org.sonar.server.component.ws.EventsWs;
+import org.sonar.server.component.ws.ProjectsWs;
+import org.sonar.server.component.ws.ResourcesWs;
+import org.sonar.server.computation.AnalysisReportQueue;
+import org.sonar.server.computation.AnalysisReportTaskCleaner;
+import org.sonar.server.computation.AnalysisReportTaskLauncher;
+import org.sonar.server.computation.ComponentIndexationInDatabaseStep;
+import org.sonar.server.computation.ComputationService;
+import org.sonar.server.computation.ComputationStepRegistry;
+import org.sonar.server.computation.DataCleanerStep;
+import org.sonar.server.computation.DigestAnalysisReportStep;
+import org.sonar.server.computation.IndexProjectIssuesStep;
+import org.sonar.server.computation.InvalidatePreviewCacheStep;
+import org.sonar.server.computation.SwitchSnapshotStep;
+import org.sonar.server.computation.SynchronizeProjectPermissionsStep;
import org.sonar.server.computation.db.AnalysisReportDao;
-import org.sonar.server.computation.ws.*;
+import org.sonar.server.computation.ws.ActiveAnalysisReportsAction;
+import org.sonar.server.computation.ws.AnalysisReportHistorySearchAction;
+import org.sonar.server.computation.ws.AnalysisReportWebService;
+import org.sonar.server.computation.ws.ExperimentalAnalysisReportAction;
+import org.sonar.server.computation.ws.ExperimentalAnalysisReportWebService;
+import org.sonar.server.computation.ws.IsAnalysisReportQueueEmptyAction;
import org.sonar.server.config.ws.PropertiesWs;
import org.sonar.server.dashboard.db.DashboardDao;
import org.sonar.server.dashboard.db.WidgetDao;
import org.sonar.server.db.EmbeddedDatabaseFactory;
import org.sonar.server.db.migrations.DatabaseMigrations;
import org.sonar.server.db.migrations.DatabaseMigrator;
-import org.sonar.server.debt.*;
+import org.sonar.server.debt.DebtCharacteristicsXMLImporter;
+import org.sonar.server.debt.DebtModelBackup;
+import org.sonar.server.debt.DebtModelLookup;
+import org.sonar.server.debt.DebtModelOperations;
+import org.sonar.server.debt.DebtModelPluginRepository;
+import org.sonar.server.debt.DebtModelService;
+import org.sonar.server.debt.DebtModelXMLExporter;
+import org.sonar.server.debt.DebtRulesXMLImporter;
import org.sonar.server.design.FileDesignWidget;
import org.sonar.server.duplication.ws.DuplicationsJsonWriter;
import org.sonar.server.duplication.ws.DuplicationsParser;
import org.sonar.server.duplication.ws.DuplicationsWs;
-import org.sonar.server.es.*;
-import org.sonar.server.issue.*;
+import org.sonar.server.es.EsClient;
+import org.sonar.server.es.IndexCreator;
+import org.sonar.server.es.IndexRegistry;
+import org.sonar.server.issue.ActionService;
+import org.sonar.server.issue.AssignAction;
+import org.sonar.server.issue.CommentAction;
+import org.sonar.server.issue.InternalRubyIssueService;
+import org.sonar.server.issue.IssueBulkChangeService;
+import org.sonar.server.issue.IssueChangelogFormatter;
+import org.sonar.server.issue.IssueChangelogService;
+import org.sonar.server.issue.IssueCommentService;
+import org.sonar.server.issue.IssueQueryService;
+import org.sonar.server.issue.IssueService;
+import org.sonar.server.issue.PlanAction;
+import org.sonar.server.issue.ServerIssueStorage;
+import org.sonar.server.issue.SetSeverityAction;
+import org.sonar.server.issue.TransitionAction;
import org.sonar.server.issue.actionplan.ActionPlanService;
import org.sonar.server.issue.actionplan.ActionPlanWs;
import org.sonar.server.issue.db.IssueDao;
import org.sonar.server.platform.ws.RestartHandler;
import org.sonar.server.platform.ws.ServerWs;
import org.sonar.server.platform.ws.SystemWs;
-import org.sonar.server.plugins.*;
+import org.sonar.server.plugins.InstalledPluginReferentialFactory;
+import org.sonar.server.plugins.PluginDownloader;
+import org.sonar.server.plugins.ServerExtensionInstaller;
+import org.sonar.server.plugins.ServerPluginJarInstaller;
+import org.sonar.server.plugins.ServerPluginJarsInstaller;
+import org.sonar.server.plugins.ServerPluginRepository;
+import org.sonar.server.plugins.UpdateCenterClient;
+import org.sonar.server.plugins.UpdateCenterMatrixFactory;
import org.sonar.server.properties.ProjectSettingsFactory;
import org.sonar.server.qualitygate.QgateProjectFinder;
import org.sonar.server.qualitygate.QualityGates;
import org.sonar.server.qualitygate.RegisterQualityGates;
-import org.sonar.server.qualitygate.ws.*;
-import org.sonar.server.qualityprofile.*;
+import org.sonar.server.qualitygate.ws.QGatesAppAction;
+import org.sonar.server.qualitygate.ws.QGatesCopyAction;
+import org.sonar.server.qualitygate.ws.QGatesCreateAction;
+import org.sonar.server.qualitygate.ws.QGatesCreateConditionAction;
+import org.sonar.server.qualitygate.ws.QGatesDeleteConditionAction;
+import org.sonar.server.qualitygate.ws.QGatesDeselectAction;
+import org.sonar.server.qualitygate.ws.QGatesDestroyAction;
+import org.sonar.server.qualitygate.ws.QGatesListAction;
+import org.sonar.server.qualitygate.ws.QGatesRenameAction;
+import org.sonar.server.qualitygate.ws.QGatesSearchAction;
+import org.sonar.server.qualitygate.ws.QGatesSelectAction;
+import org.sonar.server.qualitygate.ws.QGatesSetAsDefaultAction;
+import org.sonar.server.qualitygate.ws.QGatesShowAction;
+import org.sonar.server.qualitygate.ws.QGatesUnsetDefaultAction;
+import org.sonar.server.qualitygate.ws.QGatesUpdateConditionAction;
+import org.sonar.server.qualitygate.ws.QGatesWs;
+import org.sonar.server.qualityprofile.BuiltInProfiles;
+import org.sonar.server.qualityprofile.QProfileBackuper;
+import org.sonar.server.qualityprofile.QProfileCopier;
+import org.sonar.server.qualityprofile.QProfileExporters;
+import org.sonar.server.qualityprofile.QProfileFactory;
+import org.sonar.server.qualityprofile.QProfileLoader;
+import org.sonar.server.qualityprofile.QProfileLookup;
+import org.sonar.server.qualityprofile.QProfileProjectLookup;
+import org.sonar.server.qualityprofile.QProfileProjectOperations;
+import org.sonar.server.qualityprofile.QProfileReset;
+import org.sonar.server.qualityprofile.QProfileService;
+import org.sonar.server.qualityprofile.QProfiles;
+import org.sonar.server.qualityprofile.RegisterQualityProfiles;
+import org.sonar.server.qualityprofile.RuleActivator;
+import org.sonar.server.qualityprofile.RuleActivatorContextFactory;
import org.sonar.server.qualityprofile.db.ActiveRuleDao;
import org.sonar.server.qualityprofile.index.ActiveRuleIndex;
import org.sonar.server.qualityprofile.index.ActiveRuleNormalizer;
-import org.sonar.server.qualityprofile.ws.*;
-import org.sonar.server.rule.*;
+import org.sonar.server.qualityprofile.ws.BulkRuleActivationActions;
+import org.sonar.server.qualityprofile.ws.ProfilesWs;
+import org.sonar.server.qualityprofile.ws.QProfileRestoreBuiltInAction;
+import org.sonar.server.qualityprofile.ws.QProfilesWs;
+import org.sonar.server.qualityprofile.ws.RuleActivationActions;
+import org.sonar.server.rule.DefaultRuleFinder;
+import org.sonar.server.rule.DeprecatedRulesDefinitionLoader;
+import org.sonar.server.rule.RegisterRules;
+import org.sonar.server.rule.RubyRuleService;
+import org.sonar.server.rule.RuleCreator;
+import org.sonar.server.rule.RuleDefinitionsLoader;
+import org.sonar.server.rule.RuleDeleter;
+import org.sonar.server.rule.RuleOperations;
+import org.sonar.server.rule.RuleRepositories;
+import org.sonar.server.rule.RuleService;
+import org.sonar.server.rule.RuleUpdater;
import org.sonar.server.rule.db.RuleDao;
import org.sonar.server.rule.index.RuleIndex;
import org.sonar.server.rule.index.RuleNormalizer;
-import org.sonar.server.rule.ws.*;
-import org.sonar.server.search.*;
-import org.sonar.server.source.*;
+import org.sonar.server.rule.ws.ActiveRuleCompleter;
+import org.sonar.server.rule.ws.AppAction;
+import org.sonar.server.rule.ws.DeleteAction;
+import org.sonar.server.rule.ws.RuleMapping;
+import org.sonar.server.rule.ws.RulesWebService;
+import org.sonar.server.rule.ws.SearchAction;
+import org.sonar.server.rule.ws.TagsAction;
+import org.sonar.server.rule.ws.UpdateAction;
+import org.sonar.server.search.IndexClient;
+import org.sonar.server.search.IndexQueue;
+import org.sonar.server.search.IndexSynchronizer;
+import org.sonar.server.search.SearchClient;
+import org.sonar.server.search.SearchHealth;
+import org.sonar.server.source.HtmlSourceDecorator;
+import org.sonar.server.source.IndexSourceLinesStep;
+import org.sonar.server.source.SourceService;
import org.sonar.server.source.index.SourceLineIndex;
import org.sonar.server.source.index.SourceLineIndexDefinition;
import org.sonar.server.source.index.SourceLineIndexer;
-import org.sonar.server.source.ws.*;
+import org.sonar.server.source.ws.HashAction;
+import org.sonar.server.source.ws.LinesAction;
+import org.sonar.server.source.ws.RawAction;
+import org.sonar.server.source.ws.ScmAction;
+import org.sonar.server.source.ws.ScmWriter;
import org.sonar.server.source.ws.ShowAction;
-import org.sonar.server.startup.*;
+import org.sonar.server.source.ws.SourcesWs;
+import org.sonar.server.startup.CleanPreviewAnalysisCache;
+import org.sonar.server.startup.CopyRequirementsFromCharacteristicsToRules;
+import org.sonar.server.startup.GeneratePluginIndex;
+import org.sonar.server.startup.JdbcDriverDeployer;
+import org.sonar.server.startup.LogServerId;
+import org.sonar.server.startup.RegisterDashboards;
+import org.sonar.server.startup.RegisterDebtModel;
+import org.sonar.server.startup.RegisterMetrics;
+import org.sonar.server.startup.RegisterNewMeasureFilters;
+import org.sonar.server.startup.RegisterPermissionTemplates;
+import org.sonar.server.startup.RegisterServletFilters;
+import org.sonar.server.startup.RenameDeprecatedPropertyKeys;
+import org.sonar.server.startup.ServerMetadataPersister;
import org.sonar.server.test.CoverageService;
-import org.sonar.server.test.ws.*;
+import org.sonar.server.test.ws.CoverageShowAction;
+import org.sonar.server.test.ws.CoverageWs;
+import org.sonar.server.test.ws.TestsCoveredFilesAction;
+import org.sonar.server.test.ws.TestsShowAction;
+import org.sonar.server.test.ws.TestsTestCasesAction;
+import org.sonar.server.test.ws.TestsWs;
import org.sonar.server.text.MacroInterpreter;
import org.sonar.server.text.RubyTextService;
import org.sonar.server.ui.JRubyI18n;
import org.sonar.server.ui.PageDecorations;
import org.sonar.server.ui.Views;
import org.sonar.server.updatecenter.ws.UpdateCenterWs;
-import org.sonar.server.user.*;
+import org.sonar.server.user.DefaultUserService;
+import org.sonar.server.user.DoPrivileged;
+import org.sonar.server.user.GroupMembershipFinder;
+import org.sonar.server.user.GroupMembershipService;
+import org.sonar.server.user.NewUserNotifier;
+import org.sonar.server.user.SecurityRealmFactory;
import org.sonar.server.user.db.GroupDao;
import org.sonar.server.user.ws.FavoritesWs;
import org.sonar.server.user.ws.UserPropertiesWs;
import org.sonar.server.user.ws.UsersWs;
-import org.sonar.server.util.*;
+import org.sonar.server.util.BooleanTypeValidation;
+import org.sonar.server.util.FloatTypeValidation;
+import org.sonar.server.util.IntegerTypeValidation;
+import org.sonar.server.util.StringListTypeValidation;
+import org.sonar.server.util.StringTypeValidation;
+import org.sonar.server.util.TextTypeValidation;
+import org.sonar.server.util.TypeValidations;
import org.sonar.server.ws.ListingWs;
import org.sonar.server.ws.WebServiceEngine;
pico.addSingleton(ChartFactory.class);
pico.addSingleton(Languages.class);
pico.addSingleton(Views.class);
- pico.addSingleton(CodeColorizers.class);
pico.addSingleton(ResourceTypes.class);
pico.addSingleton(SettingsChangeNotifier.class);
pico.addSingleton(PageDecorations.class);
// source
pico.addSingleton(HtmlSourceDecorator.class);
- pico.addSingleton(DeprecatedSourceDecorator.class);
pico.addSingleton(SourceService.class);
pico.addSingleton(SourcesWs.class);
pico.addSingleton(ShowAction.class);
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.server.source;
-
-import com.google.common.collect.Lists;
-import org.apache.commons.lang.StringUtils;
-import org.slf4j.LoggerFactory;
-import org.sonar.api.ServerExtension;
-import org.sonar.api.web.CodeColorizerFormat;
-import org.sonar.colorizer.CodeColorizer;
-import org.sonar.colorizer.HtmlOptions;
-import org.sonar.colorizer.Tokenizer;
-
-import java.io.StringReader;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Central point for sonar-colorizer extensions
- */
-public class CodeColorizers implements ServerExtension {
-
- private final Map<String, CodeColorizerFormat> byLang;
-
- public CodeColorizers(List<CodeColorizerFormat> formats) {
- byLang = new HashMap<String, CodeColorizerFormat>();
- for (CodeColorizerFormat format : formats) {
- byLang.put(format.getLanguageKey(), format);
- }
-
- LoggerFactory.getLogger(getClass()).info("Code colorizer, supported languages: " + StringUtils.join(byLang.keySet(), ","));
- }
-
- /**
- * Used when no plugin is defining some CodeColorizerFormat
- */
- public CodeColorizers() {
- this(Lists.<CodeColorizerFormat>newArrayList());
- }
-
- public String toHtml(String code, String language) {
- CodeColorizerFormat format = byLang.get(language);
- List<Tokenizer> tokenizers;
- if (format == null) {
- tokenizers = Collections.emptyList();
- } else {
- tokenizers = format.getTokenizers();
- }
- return new CodeColorizer(tokenizers).toHtml(new StringReader(code), HtmlOptions.ONLY_SYNTAX);
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-package org.sonar.server.source;
-
-import com.google.common.base.Splitter;
-import org.sonar.api.ServerComponent;
-import org.sonar.core.persistence.DbSession;
-import org.sonar.core.persistence.MyBatis;
-import org.sonar.core.resource.ResourceDao;
-import org.sonar.core.resource.ResourceDto;
-import org.sonar.core.resource.ResourceQuery;
-import org.sonar.core.source.db.SnapshotSourceDao;
-import org.sonar.server.exceptions.NotFoundException;
-
-import javax.annotation.CheckForNull;
-import javax.annotation.Nullable;
-
-import java.util.List;
-
-import static com.google.common.collect.Lists.newArrayList;
-
-/**
- * When a plugin do not use the new API to add syntax highlighting on source code, this class is called to add html info on source code
- */
-public class DeprecatedSourceDecorator implements ServerComponent {
-
- private final MyBatis mybatis;
- private final ResourceDao resourceDao;
- private final CodeColorizers codeColorizers;
- private final SnapshotSourceDao snapshotSourceDao;
-
- public DeprecatedSourceDecorator(MyBatis mybatis, ResourceDao resourceDao, CodeColorizers codeColorizers, SnapshotSourceDao snapshotSourceDao) {
- this.mybatis = mybatis;
- this.resourceDao = resourceDao;
- this.codeColorizers = codeColorizers;
- this.snapshotSourceDao = snapshotSourceDao;
- }
-
- @CheckForNull
- public List<String> getSourceAsHtml(String componentKey) {
- return getSourceAsHtml(componentKey, null, null);
- }
-
- @CheckForNull
- public List<String> getSourceAsHtml(String componentKey, @Nullable Integer from, @Nullable Integer to) {
- DbSession session = mybatis.openSession(false);
- try {
- ResourceDto component = resourceDao.getResource(ResourceQuery.create().setKey(componentKey), session);
- if (component == null) {
- throw new NotFoundException("The component '" + componentKey + "' does not exists.");
- }
- String source = snapshotSourceDao.selectSnapshotSourceByComponentKey(componentKey, session);
- if (source != null) {
- return splitSourceByLine(source, component.getLanguage(), from, to);
- } else {
- return null;
- }
- } finally {
- MyBatis.closeQuietly(session);
- }
- }
-
- private List<String> splitSourceByLine(String source, String language, @Nullable Integer from, @Nullable Integer to) {
- String htmlSource = codeColorizers.toHtml(source, language);
- List<String> splitSource = newArrayList(Splitter.onPattern("\r?\n|\r").split(htmlSource));
- List<String> result = newArrayList();
- for (int i = 0; i < splitSource.size(); i++) {
- int currentLine = i + 1;
- if (to != null && to < currentLine) {
- break;
- } else if (from == null || currentLine >= from) {
- result.add(splitSource.get(currentLine - 1));
- }
- }
- return result;
- }
-}
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
-import org.apache.ibatis.session.SqlSession;
import org.sonar.api.ServerComponent;
-import org.sonar.core.persistence.MyBatis;
import org.sonar.core.source.SnapshotDataTypes;
-import org.sonar.core.source.db.SnapshotDataDao;
import org.sonar.core.source.db.SnapshotDataDto;
-import org.sonar.core.source.db.SnapshotSourceDao;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
private static final String SINGLE_LINE_SYMBOLS = "single_line_symbols";
- private final MyBatis mybatis;
-
- private final SnapshotSourceDao snapshotSourceDao;
- private final SnapshotDataDao snapshotDataDao;
-
- public HtmlSourceDecorator(MyBatis mybatis, SnapshotSourceDao snapshotSourceDao, SnapshotDataDao snapshotDataDao) {
- this.mybatis = mybatis;
- this.snapshotSourceDao = snapshotSourceDao;
- this.snapshotDataDao = snapshotDataDao;
- }
-
- @CheckForNull
- public List<String> getDecoratedSourceAsHtml(String componentKey, @Nullable Integer from, @Nullable Integer to) {
- SqlSession session = mybatis.openSession(false);
- try {
- Collection<SnapshotDataDto> snapshotDataEntries = snapshotDataDao.selectSnapshotDataByComponentKey(componentKey, highlightingDataTypes(), session);
- if (!snapshotDataEntries.isEmpty()) {
- String snapshotSource = snapshotSourceDao.selectSnapshotSourceByComponentKey(componentKey, session);
- return decorate(snapshotSource, snapshotDataEntries, from, to);
- }
- return null;
- } finally {
- MyBatis.closeQuietly(session);
- }
- }
-
- @CheckForNull
- public List<String> getDecoratedSourceAsHtml(long snapshotId) {
- Collection<SnapshotDataDto> snapshotDataEntries = snapshotDataDao.selectSnapshotData(snapshotId, highlightingDataTypes());
- if (!snapshotDataEntries.isEmpty()) {
- String snapshotSource = snapshotSourceDao.selectSnapshotSource(snapshotId);
- if (snapshotSource != null) {
- return decorate(snapshotSource, snapshotDataEntries, null, null);
- }
- }
- return null;
- }
-
@CheckForNull
public String getDecoratedSourceAsHtml(@Nullable String sourceLine, @Nullable String highlighting, @Nullable String symbols) {
Collection<SnapshotDataDto> snapshotDataEntries = Lists.newArrayList();
return null;
}
- private List<String> highlightingDataTypes() {
- return Lists.newArrayList(SnapshotDataTypes.SYNTAX_HIGHLIGHTING,
- SnapshotDataTypes.SYMBOL_HIGHLIGHTING);
- }
-
private void loadSnapshotData(DecorationDataHolder dataHolder, SnapshotDataDto entry) {
if (!Strings.isNullOrEmpty(entry.getData())) {
if (SnapshotDataTypes.SYNTAX_HIGHLIGHTING.equals(entry.getDataType())) {
package org.sonar.server.source;
-import com.google.common.base.Splitter;
+import org.apache.commons.lang.ObjectUtils;
import org.elasticsearch.common.collect.Lists;
import org.sonar.api.ServerComponent;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.core.measure.db.MeasureKey;
import org.sonar.core.persistence.DbSession;
import org.sonar.core.persistence.MyBatis;
-import org.sonar.core.source.db.SnapshotSourceDao;
import org.sonar.server.db.DbClient;
import org.sonar.server.source.index.SourceLineDoc;
import org.sonar.server.source.index.SourceLineIndex;
import java.util.List;
-import static com.google.common.collect.Lists.newArrayList;
-
public class SourceService implements ServerComponent {
private final DbClient dbClient;
private final HtmlSourceDecorator sourceDecorator;
- private final SnapshotSourceDao snapshotSourceDao;
private final SourceLineIndex sourceLineIndex;
- /**
- * Old service to colorize code
- */
- private final DeprecatedSourceDecorator deprecatedSourceDecorator;
-
- public SourceService(DbClient dbClient, HtmlSourceDecorator sourceDecorator, SnapshotSourceDao snapshotSourceDao, DeprecatedSourceDecorator deprecatedSourceDecorator,
- SourceLineIndex sourceLineIndex) {
+ public SourceService(DbClient dbClient, HtmlSourceDecorator sourceDecorator, SourceLineIndex sourceLineIndex) {
this.dbClient = dbClient;
this.sourceDecorator = sourceDecorator;
- this.snapshotSourceDao = snapshotSourceDao;
- this.deprecatedSourceDecorator = deprecatedSourceDecorator;
this.sourceLineIndex = sourceLineIndex;
}
- @CheckForNull
- public List<String> getLinesAsHtml(String fileKey) {
- return getLinesAsHtml(fileKey, null, null);
- }
-
- @CheckForNull
- public List<String> getLinesAsHtml(String fileKey, @Nullable Integer from, @Nullable Integer to) {
- checkPermission(fileKey);
-
- List<String> decoratedSource = sourceDecorator.getDecoratedSourceAsHtml(fileKey, from, to);
- if (decoratedSource != null) {
- return decoratedSource;
- }
- return deprecatedSourceDecorator.getSourceAsHtml(fileKey, from, to);
- }
-
/**
- * Raw lines of source file. Returns <code>null</code> if the file does not exist
+ * Raw lines of source file.
*/
- @CheckForNull
- public List<String> getLinesAsTxt(DbSession session, String fileKey) {
- checkPermission(fileKey);
-
- String source = snapshotSourceDao.selectSnapshotSourceByComponentKey(fileKey, session);
- if (source != null) {
- return newArrayList(Splitter.onPattern("\r?\n|\r").split(source));
+ public List<String> getLinesAsTxt(String fileUuid, @Nullable Integer fromParam, @Nullable Integer toParam) {
+ int from = (Integer) ObjectUtils.defaultIfNull(fromParam, 1);
+ int to = (Integer) ObjectUtils.defaultIfNull(toParam, Integer.MAX_VALUE);
+ List<String> lines = Lists.newArrayList();
+ for (SourceLineDoc lineDoc : sourceLineIndex.getLines(fileUuid, from, to)) {
+ lines.add(lineDoc.source());
}
- return null;
+ return lines;
}
/**
- * Raw lines of source file.
+ * Decorated lines of source file.
*/
- public List<String> getLinesAsTxt(String fileUuid) {
+ public List<String> getLinesAsHtml(String fileUuid, @Nullable Integer fromParam, @Nullable Integer toParam) {
+ int from = (Integer) ObjectUtils.defaultIfNull(fromParam, 1);
+ int to = (Integer) ObjectUtils.defaultIfNull(toParam, Integer.MAX_VALUE);
List<String> lines = Lists.newArrayList();
- for (SourceLineDoc lineDoc: sourceLineIndex.getLines(fileUuid, 1, Integer.MAX_VALUE)) {
- lines.add(lineDoc.source());
+ for (SourceLineDoc lineDoc : sourceLineIndex.getLines(fileUuid, from, to)) {
+ lines.add(sourceDecorator.getDecoratedSourceAsHtml(lineDoc.source(), lineDoc.highlighting(), lineDoc.symbols()));
}
return lines;
}
import java.util.Collection;
import java.util.Date;
+import java.util.HashMap;
import java.util.Map;
public class SourceLineDoc extends BaseDoc {
super(fields);
}
+ // For testing purpose
+ public SourceLineDoc() {
+ this(new HashMap<String, Object>());
+ }
+
public String projectUuid() {
return getField(SourceLineIndexDefinition.FIELD_PROJECT_UUID);
}
- public void setProjectUuid(String projectUuid) {
+ public SourceLineDoc setProjectUuid(String projectUuid) {
setField(SourceLineIndexDefinition.FIELD_PROJECT_UUID, projectUuid);
+ return this;
}
public String fileUuid() {
return getField(SourceLineIndexDefinition.FIELD_FILE_UUID);
}
- public void setFileUuid(String fileUuid) {
+ public SourceLineDoc setFileUuid(String fileUuid) {
setField(SourceLineIndexDefinition.FIELD_FILE_UUID, fileUuid);
+ return this;
}
public int line() {
- return ((Number)getField(SourceLineIndexDefinition.FIELD_LINE)).intValue();
+ return ((Number) getField(SourceLineIndexDefinition.FIELD_LINE)).intValue();
}
- public void setLine(int line) {
+ public SourceLineDoc setLine(int line) {
setField(SourceLineIndexDefinition.FIELD_LINE, line);
+ return this;
}
@CheckForNull
return getNullableField(SourceLineIndexDefinition.FIELD_SCM_REVISION);
}
- public void setScmRevision(String scmRevision) {
+ public SourceLineDoc setScmRevision(String scmRevision) {
setField(SourceLineIndexDefinition.FIELD_SCM_REVISION, scmRevision);
+ return this;
}
@CheckForNull
return getNullableField(SourceLineIndexDefinition.FIELD_SCM_AUTHOR);
}
- public void setScmAuthor(String scmAuthor) {
+ public SourceLineDoc setScmAuthor(String scmAuthor) {
setField(SourceLineIndexDefinition.FIELD_SCM_AUTHOR, scmAuthor);
+ return this;
}
@CheckForNull
return IndexUtils.parseDateTime(this.<String>getNullableField(SourceLineIndexDefinition.FIELD_SCM_DATE));
}
- public void setScmDate(@Nullable Date scmDate) {
+ public SourceLineDoc setScmDate(@Nullable Date scmDate) {
setField(SourceLineIndexDefinition.FIELD_SCM_DATE, scmDate);
+ return this;
}
@CheckForNull
return getNullableField(SourceLineIndexDefinition.FIELD_HIGHLIGHTING);
}
- public void setHighlighting(String s) {
+ public SourceLineDoc setHighlighting(String s) {
setField(SourceLineIndexDefinition.FIELD_HIGHLIGHTING, s);
+ return this;
}
public String source() {
return getField(SourceLineIndexDefinition.FIELD_SOURCE);
}
- public void setSource(String source) {
+ public SourceLineDoc setSource(String source) {
setField(SourceLineIndexDefinition.FIELD_SOURCE, source);
+ return this;
}
public Date updateDate() {
return getFieldAsDate(BaseNormalizer.UPDATED_AT_FIELD);
}
- public void setUpdateDate(Date updatedAt) {
+ public SourceLineDoc setUpdateDate(Date updatedAt) {
setField(BaseNormalizer.UPDATED_AT_FIELD, updatedAt);
+ return this;
}
public String key() {
return lineHits == null ? null : lineHits.intValue();
}
- public void setUtLineHits(@Nullable Integer lineHits) {
+ public SourceLineDoc setUtLineHits(@Nullable Integer lineHits) {
setField(SourceLineIndexDefinition.FIELD_UT_LINE_HITS, lineHits);
+ return this;
}
@CheckForNull
return conditions == null ? null : conditions.intValue();
}
- public void setUtConditions(@Nullable Integer conditions) {
+ public SourceLineDoc setUtConditions(@Nullable Integer conditions) {
setField(SourceLineIndexDefinition.FIELD_UT_CONDITIONS, conditions);
+ return this;
}
@CheckForNull
return coveredConditions == null ? null : coveredConditions.intValue();
}
- public void setUtCoveredConditions(@Nullable Integer coveredConditions) {
+ public SourceLineDoc setUtCoveredConditions(@Nullable Integer coveredConditions) {
setField(SourceLineIndexDefinition.FIELD_UT_COVERED_CONDITIONS, coveredConditions);
+ return this;
}
@CheckForNull
return lineHits == null ? null : lineHits.intValue();
}
- public void setItLineHits(@Nullable Integer lineHits) {
+ public SourceLineDoc setItLineHits(@Nullable Integer lineHits) {
setField(SourceLineIndexDefinition.FIELD_IT_LINE_HITS, lineHits);
+ return this;
}
@CheckForNull
return conditions == null ? null : conditions.intValue();
}
- public void setItConditions(@Nullable Integer conditions) {
+ public SourceLineDoc setItConditions(@Nullable Integer conditions) {
setField(SourceLineIndexDefinition.FIELD_IT_CONDITIONS, conditions);
+ return this;
}
@CheckForNull
public Integer itCoveredConditions() {
- Number coveredConditions = (Number)getNullableField(SourceLineIndexDefinition.FIELD_IT_COVERED_CONDITIONS);
+ Number coveredConditions = (Number) getNullableField(SourceLineIndexDefinition.FIELD_IT_COVERED_CONDITIONS);
return coveredConditions == null ? null : coveredConditions.intValue();
}
- public void setItCoveredConditions(@Nullable Integer coveredConditions) {
+ public SourceLineDoc setItCoveredConditions(@Nullable Integer coveredConditions) {
setField(SourceLineIndexDefinition.FIELD_IT_COVERED_CONDITIONS, coveredConditions);
+ return this;
}
@CheckForNull
return lineHits == null ? null : lineHits.intValue();
}
- public void setOverallLineHits(@Nullable Integer lineHits) {
+ public SourceLineDoc setOverallLineHits(@Nullable Integer lineHits) {
setField(SourceLineIndexDefinition.FIELD_OVERALL_LINE_HITS, lineHits);
+ return this;
}
@CheckForNull
return conditions == null ? null : conditions.intValue();
}
- public void setOverallConditions(@Nullable Integer conditions) {
+ public SourceLineDoc setOverallConditions(@Nullable Integer conditions) {
setField(SourceLineIndexDefinition.FIELD_OVERALL_CONDITIONS, conditions);
+ return this;
}
@CheckForNull
return coveredConditions == null ? null : coveredConditions.intValue();
}
- public void setOverallCoveredConditions(@Nullable Integer coveredConditions) {
+ public SourceLineDoc setOverallCoveredConditions(@Nullable Integer coveredConditions) {
setField(SourceLineIndexDefinition.FIELD_OVERALL_COVERED_CONDITIONS, coveredConditions);
+ return this;
}
@CheckForNull
return getNullableField(SourceLineIndexDefinition.FIELD_SYMBOLS);
}
- public void setSymbols(@Nullable String s) {
+ public SourceLineDoc setSymbols(@Nullable String s) {
setField(SourceLineIndexDefinition.FIELD_SYMBOLS, s);
+ return this;
}
public Collection<Integer> duplications() {
return duplications == null ? ImmutableList.<Integer>of() : duplications;
}
- public void setDuplications(@Nullable Collection<Integer> dups) {
+ public SourceLineDoc setDuplications(@Nullable Collection<Integer> dups) {
setField(SourceLineIndexDefinition.FIELD_DUPLICATIONS, dups == null ? ImmutableList.<Integer>of() : dups);
+ return this;
}
}
import org.sonar.api.server.ws.RequestHandler;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
+import org.sonar.core.component.ComponentDto;
import org.sonar.core.persistence.DbSession;
import org.sonar.server.db.DbClient;
-import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.source.SourceService;
import java.io.IOException;
String fileKey = request.mandatoryParam("key");
DbSession session = dbClient.openSession(false);
try {
- dbClient.componentDao().getByKey(session, fileKey);
- List<String> lines = sourceService.getLinesAsTxt(session, fileKey);
- if (lines == null) {
- throw new NotFoundException("File '" + fileKey + "' does not exist");
- }
+ ComponentDto componentDto = dbClient.componentDao().getByKey(session, fileKey);
+ List<String> lines = sourceService.getLinesAsTxt(componentDto.uuid(), null, null);
IOUtils.writeLines(lines, "\n", response.stream().output(), Charsets.UTF_8);
} catch (IOException e) {
throw new IllegalStateException("Fail to write raw source of file " + fileKey, e);
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.text.JsonWriter;
+import org.sonar.core.component.ComponentDto;
+import org.sonar.core.persistence.DbSession;
+import org.sonar.server.db.DbClient;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.source.SourceService;
public class ShowAction implements RequestHandler {
private final SourceService sourceService;
+ private final DbClient dbClient;
- public ShowAction(SourceService sourceService) {
+ public ShowAction(SourceService sourceService, DbClient dbClient) {
this.sourceService = sourceService;
+ this.dbClient = dbClient;
}
void define(WebService.NewController controller) {
int from = Math.max(request.mandatoryParamAsInt("from"), 1);
int to = (Integer) ObjectUtils.defaultIfNull(request.paramAsInt("to"), Integer.MAX_VALUE);
- List<String> sourceHtml = sourceService.getLinesAsHtml(fileKey, from, to);
- if (sourceHtml == null) {
- throw new NotFoundException("File '" + fileKey + "' has no sources");
- }
+ DbSession session = dbClient.openSession(false);
+ try {
+ ComponentDto componentDto = dbClient.componentDao().getByKey(session, fileKey);
+ List<String> linesHtml = sourceService.getLinesAsHtml(componentDto.uuid(), from, to);
+ if (linesHtml == null) {
+ throw new NotFoundException("File '" + fileKey + "' does not exist");
+ }
+
+ JsonWriter json = response.newJsonWriter().beginObject();
+ writeSource(linesHtml, from, json);
- JsonWriter json = response.newJsonWriter().beginObject();
- writeSource(sourceHtml, from, json);
+ json.endObject().close();
+ } finally {
+ session.close();
+ }
- json.endObject().close();
}
private void writeSource(List<String> lines, int from, JsonWriter json) {
import org.sonar.api.ServerComponent;
import org.sonar.markdown.Markdown;
-import org.sonar.server.source.HtmlSourceDecorator;
-
-import java.util.List;
/**
* @since 3.6
public class RubyTextService implements ServerComponent {
private final MacroInterpreter macroInterpreter;
- private final HtmlSourceDecorator sourceDecorator;
- public RubyTextService(MacroInterpreter macroInterpreter, HtmlSourceDecorator sourceDecorator) {
+ public RubyTextService(MacroInterpreter macroInterpreter) {
this.macroInterpreter = macroInterpreter;
- this.sourceDecorator = sourceDecorator;
}
// TODO add ruby example
public String markdownToHtml(String markdown) {
return Markdown.convertToHtml(markdown);
}
-
- // TODO add ruby example
- public List<String> highlightedSourceLines(long snapshotId) {
- return sourceDecorator.getDecoratedSourceAsHtml(snapshotId);
- }
}
import org.sonar.api.resources.Language;
import org.sonar.api.resources.ResourceType;
import org.sonar.api.resources.ResourceTypes;
-import org.sonar.api.web.*;
+import org.sonar.api.web.Footer;
+import org.sonar.api.web.NavigationSection;
+import org.sonar.api.web.Page;
+import org.sonar.api.web.RubyRailsWebservice;
+import org.sonar.api.web.Widget;
import org.sonar.core.persistence.Database;
import org.sonar.core.preview.PreviewCache;
import org.sonar.core.resource.ResourceIndexerDao;
import org.sonar.server.platform.ServerIdGenerator;
import org.sonar.server.platform.ServerSettings;
import org.sonar.server.platform.SettingsChangeNotifier;
-import org.sonar.server.plugins.*;
+import org.sonar.server.plugins.InstalledPluginReferentialFactory;
+import org.sonar.server.plugins.PluginDownloader;
+import org.sonar.server.plugins.ServerPluginJarsInstaller;
+import org.sonar.server.plugins.ServerPluginRepository;
+import org.sonar.server.plugins.UpdateCenterMatrixFactory;
import org.sonar.server.rule.RuleRepositories;
-import org.sonar.server.source.CodeColorizers;
import org.sonar.server.user.NewUserNotifier;
import org.sonar.updatecenter.common.PluginReferential;
import org.sonar.updatecenter.common.UpdateCenter;
return get(PluginRepository.class).getMetadata();
}
- // SYNTAX HIGHLIGHTING ------------------------------------------------------
- public String colorizeCode(String code, String language) {
- try {
- return get(CodeColorizers.class).toHtml(code, language);
- } catch (Exception e) {
- LoggerFactory.getLogger(getClass()).error("Can not highlight the code, language= " + language, e);
- return code;
- }
- }
-
public List<ViewProxy<Widget>> getWidgets(String resourceScope, String resourceQualifier, String resourceLanguage, Object[] availableMeasures) {
return get(Views.class).getWidgets(resourceScope, resourceQualifier, resourceLanguage, (String[]) availableMeasures);
}
import org.sonar.api.utils.KeyValueFormat;
import org.sonar.api.web.UserRole;
import org.sonar.core.component.ComponentDto;
-import org.sonar.core.component.SnapshotDto;
-import org.sonar.core.issue.db.*;
+import org.sonar.core.issue.db.ActionPlanDao;
+import org.sonar.core.issue.db.ActionPlanDto;
+import org.sonar.core.issue.db.IssueChangeDao;
+import org.sonar.core.issue.db.IssueChangeDto;
+import org.sonar.core.issue.db.IssueDto;
import org.sonar.core.permission.GlobalPermissions;
import org.sonar.core.persistence.DbSession;
import org.sonar.core.rule.RuleDto;
-import org.sonar.core.source.db.SnapshotSourceDao;
-import org.sonar.core.source.db.SnapshotSourceDto;
import org.sonar.core.user.UserDto;
import org.sonar.server.component.ComponentTesting;
import org.sonar.server.component.SnapshotTesting;
.setKey("MyComponent")
.setParentProjectId(project.getId());
db.componentDao().insert(session, file);
- SnapshotDto snapshot = db.snapshotDao().insert(session, SnapshotTesting.createForComponent(file, project));
- SnapshotSourceDto snapshotSource = new SnapshotSourceDto().setSnapshotId(snapshot.getId()).setData("First Line\n"
- + "Second Line\n"
- + "Third Line\n"
- + "Fourth Line\n"
- + "Fifth Line\n");
- tester.get(SnapshotSourceDao.class).insert(snapshotSource);
otherFile = ComponentTesting.newFileDto(project).setUuid("FEDC")
.setKey("OtherComponent")
.setParentProjectId(project.getId());
db.componentDao().insert(session, otherFile);
- snapshot = db.snapshotDao().insert(session, SnapshotTesting.createForComponent(otherFile, project));
- snapshotSource = new SnapshotSourceDto().setSnapshotId(snapshot.getId()).setData("First Line\n"
- + "Second Line\n"
- + "Third Line\n"
- + "Fourth Line\n"
- + "Fifth Line\n");
- tester.get(SnapshotSourceDao.class).insert(snapshotSource);
UserDto john = new UserDto().setLogin("john").setName("John").setEmail("john@email.com");
db.userDao().insert(session, john);
session.commit();
WsTester.Result result = wsTester.newGetRequest(IssuesWs.API_ENDPOINT, SearchAction.SEARCH_ACTION)
- .setParam(IssueFilterParameters.COMPONENTS, file.getKey())
- .setParam(IssueFilterParameters.IGNORE_PAGING, "true")
- .execute();
+ .setParam(IssueFilterParameters.COMPONENTS, file.getKey())
+ .setParam(IssueFilterParameters.IGNORE_PAGING, "true")
+ .execute();
result.assertJson(this.getClass(), "ignore_paging_with_one_component.json", false);
}
session.commit();
WsTester.Result result = wsTester.newGetRequest(IssuesWs.API_ENDPOINT, SearchAction.SEARCH_ACTION)
- .setParam(IssueFilterParameters.COMPONENTS, file.getKey() + "," + otherFile.getKey())
- .setParam(IssueFilterParameters.IGNORE_PAGING, "true")
- .execute();
+ .setParam(IssueFilterParameters.COMPONENTS, file.getKey() + "," + otherFile.getKey())
+ .setParam(IssueFilterParameters.IGNORE_PAGING, "true")
+ .execute();
result.assertJson(this.getClass(), "apply_paging_with_multiple_components.json", false);
}
result.assertJson(this.getClass(), "apply_paging_with_one_component.json", false);
}
-
@Test
public void components_contains_sub_projects() throws Exception {
ComponentDto project = ComponentTesting.newProjectDto().setKey("ProjectHavingModule");
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.server.source;
-
-import org.junit.Test;
-import org.sonar.api.web.CodeColorizerFormat;
-import org.sonar.colorizer.LiteralTokenizer;
-import org.sonar.colorizer.Tokenizer;
-
-import java.util.Arrays;
-import java.util.List;
-
-import static org.fest.assertions.Assertions.assertThat;
-
-public class CodeColorizersTest {
- @Test
- public void colorize_source_code() throws Exception {
- CodeColorizerFormat format = new LiteralFormat("java");
- CodeColorizers colorizers = new CodeColorizers(Arrays.asList(format));
-
- String html = colorizers.toHtml("String s = \"foo\";", "java");
- assertThat(html).isEqualTo("String s = <span class=\"s\">\"foo\"</span>;");
- }
-
- @Test
- public void do_not_fail_if_unsupported_language() throws Exception {
- CodeColorizerFormat format = new LiteralFormat("java");
- CodeColorizers colorizers = new CodeColorizers(Arrays.asList(format));
-
- String html = colorizers.toHtml("String s = \"foo\";", "groovy");
- assertThat(html).isEqualTo("String s = \"foo\";");
- }
-
- /**
- * Highlights only litterals
- */
- static class LiteralFormat extends CodeColorizerFormat {
- LiteralFormat(String languageKey) {
- super(languageKey);
- }
-
- @Override
- public List<Tokenizer> getTokenizers() {
- return Arrays.<Tokenizer>asList(new LiteralTokenizer("<span class=\"s\">", "</span>"));
- }
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-package org.sonar.server.source;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.sonar.core.persistence.DbSession;
-import org.sonar.core.persistence.MyBatis;
-import org.sonar.core.resource.ResourceDao;
-import org.sonar.core.resource.ResourceDto;
-import org.sonar.core.resource.ResourceQuery;
-import org.sonar.core.source.db.SnapshotSourceDao;
-import org.sonar.server.exceptions.NotFoundException;
-
-import java.util.List;
-
-import static org.fest.assertions.Assertions.assertThat;
-import static org.fest.assertions.Fail.fail;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.when;
-
-@RunWith(MockitoJUnitRunner.class)
-public class DeprecatedSourceDecoratorTest {
-
- @Mock
- MyBatis mybatis;
-
- @Mock
- DbSession session;
-
- @Mock
- ResourceDao resourceDao;
-
- @Mock
- CodeColorizers codeColorizers;
-
- @Mock
- SnapshotSourceDao snapshotSourceDao;
-
- DeprecatedSourceDecorator sourceDecorator;
-
- @Before
- public void setUp() throws Exception {
- when(mybatis.openSession(false)).thenReturn(session);
- sourceDecorator = new DeprecatedSourceDecorator(mybatis, resourceDao, codeColorizers, snapshotSourceDao);
- }
-
- @Test
- public void get_source_as_html() throws Exception {
- String componentKey = "org.sonar.sample:Sample";
- String source = "line 1\nline 2\nline 3\n";
- String htmlSource = "<span>line 1</span>\n<span>line 2</span>\n";
-
- when(resourceDao.getResource(any(ResourceQuery.class), eq(session))).thenReturn(new ResourceDto().setKey(componentKey).setLanguage("java"));
- when(snapshotSourceDao.selectSnapshotSourceByComponentKey(componentKey, session)).thenReturn(source);
- when(codeColorizers.toHtml(source, "java")).thenReturn(htmlSource);
-
- List<String> result = sourceDecorator.getSourceAsHtml(componentKey);
- assertThat(result).containsExactly("<span>line 1</span>", "<span>line 2</span>", "");
- }
-
- @Test
- public void return_null_if_no_source_code_on_component() throws Exception {
- String componentKey = "org.sonar.sample:Sample";
- when(resourceDao.getResource(any(ResourceQuery.class), eq(session))).thenReturn(new ResourceDto().setKey(componentKey).setLanguage("java"));
- when(snapshotSourceDao.selectSnapshotSourceByComponentKey(componentKey, session)).thenReturn(null);
-
- assertThat(sourceDecorator.getSourceAsHtml(componentKey)).isNull();
- }
-
- @Test
- public void fail_to_get_source_as_html_on_unknown_component() throws Exception {
- String componentKey = "org.sonar.sample:Sample";
- when(resourceDao.getResource(any(ResourceQuery.class), eq(session))).thenReturn(null);
- try {
- sourceDecorator.getSourceAsHtml(componentKey);
- fail();
- } catch (Exception e) {
- assertThat(e).isInstanceOf(NotFoundException.class);
- }
- }
-
- @Test
- public void get_source_as_html_with_from_and_to_params() throws Exception {
- String componentKey = "org.sonar.sample:Sample";
- String source = "line 1\nline 2\nline 3\n";
- String htmlSource = "<span>line 1</span>\n<span>line 2</span>\n<span>line 3</span>\n";
-
- when(resourceDao.getResource(any(ResourceQuery.class), eq(session))).thenReturn(new ResourceDto().setKey(componentKey).setLanguage("java"));
- when(snapshotSourceDao.selectSnapshotSourceByComponentKey(componentKey, session)).thenReturn(source);
- when(codeColorizers.toHtml(source, "java")).thenReturn(htmlSource);
-
- List<String> result = sourceDecorator.getSourceAsHtml(componentKey, 2, 3);
- assertThat(result).containsExactly("<span>line 2</span>", "<span>line 3</span>");
- }
-
- @Test
- public void get_source_as_html_with_from_param() throws Exception {
- String componentKey = "org.sonar.sample:Sample";
- String source = "line 1\nline 2\nline 3\n";
- String htmlSource = "<span>line 1</span>\n<span>line 2</span>\n<span>line 3</span>\n";
-
- when(resourceDao.getResource(any(ResourceQuery.class), eq(session))).thenReturn(new ResourceDto().setKey(componentKey).setLanguage("java"));
- when(snapshotSourceDao.selectSnapshotSourceByComponentKey(componentKey, session)).thenReturn(source);
- when(codeColorizers.toHtml(source, "java")).thenReturn(htmlSource);
-
- List<String> result = sourceDecorator.getSourceAsHtml(componentKey, 2, null);
- assertThat(result).containsExactly("<span>line 2</span>", "<span>line 3</span>", "");
- }
-
- @Test
- public void get_source_as_html_with_to_param() throws Exception {
- String componentKey = "org.sonar.sample:Sample";
- String source = "line 1\nline 2\nline 3\n";
- String htmlSource = "<span>line 1</span>\n<span>line 2</span>\n<span>line 3</span>\n";
-
- when(resourceDao.getResource(any(ResourceQuery.class), eq(session))).thenReturn(new ResourceDto().setKey(componentKey).setLanguage("java"));
- when(snapshotSourceDao.selectSnapshotSourceByComponentKey(componentKey, session)).thenReturn(source);
- when(codeColorizers.toHtml(source, "java")).thenReturn(htmlSource);
-
- List<String> result = sourceDecorator.getSourceAsHtml(componentKey, null, 3);
- assertThat(result).containsExactly("<span>line 1</span>", "<span>line 2</span>", "<span>line 3</span>");
- }
-}
package org.sonar.server.source;
-import com.google.common.collect.Lists;
-import org.apache.ibatis.session.SqlSession;
import org.junit.Before;
import org.junit.Test;
-import org.sonar.core.persistence.AbstractDaoTestCase;
-import org.sonar.core.persistence.MyBatis;
-import org.sonar.core.source.db.SnapshotDataDao;
-import org.sonar.core.source.db.SnapshotSourceDao;
-
-import java.util.List;
import static org.fest.assertions.Assertions.assertThat;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-
-public class HtmlSourceDecoratorTest extends AbstractDaoTestCase {
+public class HtmlSourceDecoratorTest {
HtmlSourceDecorator sourceDecorator;
@Before
public void setUpDatasets() {
- setupData("shared");
-
- SnapshotSourceDao snapshotSourceDao = new SnapshotSourceDao(getMyBatis());
- SnapshotDataDao snapshotDataDao = new SnapshotDataDao(getMyBatis());
- sourceDecorator = new HtmlSourceDecorator(getMyBatis(), snapshotSourceDao, snapshotDataDao);
- }
-
- @Test
- public void highlight_syntax_with_html() throws Exception {
- List<String> decoratedSource = sourceDecorator.getDecoratedSourceAsHtml(11L);
-
- assertThat(decoratedSource).containsExactly(
- "<span class=\"cppd\">/*</span>",
- "<span class=\"cppd\"> * Header</span>",
- "<span class=\"cppd\"> */</span>",
- "",
- "<span class=\"k\">public </span><span class=\"k\">class </span>HelloWorld {",
- "}"
- );
- }
-
- @Test
- public void highlight_syntax_with_html_from_component() throws Exception {
- List<String> decoratedSource = sourceDecorator.getDecoratedSourceAsHtml("org.apache.struts:struts:Dispatcher", (Integer) null, (Integer) null);
-
- assertThat(decoratedSource).containsExactly(
- "<span class=\"cppd\">/*</span>",
- "<span class=\"cppd\"> * Header</span>",
- "<span class=\"cppd\"> */</span>",
- "",
- "<span class=\"k\">public </span><span class=\"k\">class </span>HelloWorld {",
- "}"
- );
- }
-
- @Test
- public void highlight_syntax_with_html_from_component_on_given_lines() throws Exception {
- assertThat(sourceDecorator.getDecoratedSourceAsHtml("org.apache.struts:struts:Dispatcher", null, 2)).hasSize(2);
- assertThat(sourceDecorator.getDecoratedSourceAsHtml("org.apache.struts:struts:Dispatcher", 2, null)).hasSize(5);
- assertThat(sourceDecorator.getDecoratedSourceAsHtml("org.apache.struts:struts:Dispatcher", 1, 2)).hasSize(2);
- }
-
- @Test
- public void mark_symbols_with_html() throws Exception {
- List<String> decoratedSource = sourceDecorator.getDecoratedSourceAsHtml(12L);
-
- assertThat(decoratedSource).containsExactly(
- "/*",
- " * Header",
- " */",
- "",
- "public class <span class=\"sym-31 sym\">HelloWorld</span> {",
- "}"
- );
- }
-
- @Test
- public void mark_symbols_with_html_from_component() throws Exception {
- List<String> decoratedSource = sourceDecorator.getDecoratedSourceAsHtml("org.apache.struts:struts:VelocityManager", (Integer) null, (Integer) null);
-
- assertThat(decoratedSource).containsExactly(
- "/*",
- " * Header",
- " */",
- "",
- "public class <span class=\"sym-31 sym\">HelloWorld</span> {",
- "}"
- );
- }
-
- @Test
- public void decorate_source_with_multiple_decoration_strategies() throws Exception {
- List<String> decoratedSource = sourceDecorator.getDecoratedSourceAsHtml(13L);
-
- assertThat(decoratedSource).containsExactly(
- "<span class=\"cppd\">/*</span>",
- "<span class=\"cppd\"> * Header</span>",
- "<span class=\"cppd\"> */</span>",
- "",
- "<span class=\"k\">public </span><span class=\"k\">class </span><span class=\"sym-31 sym\">HelloWorld</span> {",
- " <span class=\"k\">public</span> <span class=\"k\">void</span> <span class=\"sym-58 sym\">foo</span>() {",
- " }",
- " <span class=\"k\">public</span> <span class=\"k\">void</span> <span class=\"sym-84 sym\">bar</span>() {",
- " <span class=\"sym-58 sym\">foo</span>();",
- " }",
- "}"
- );
- }
-
- @Test
- public void decorate_source_with_multiple_decoration_strategies_from_component() throws Exception {
- List<String> decoratedSource = sourceDecorator.getDecoratedSourceAsHtml("org.apache.struts:struts:DebuggingInterceptor", (Integer) null, (Integer) null);
-
- assertThat(decoratedSource).containsExactly(
- "<span class=\"cppd\">/*</span>",
- "<span class=\"cppd\"> * Header</span>",
- "<span class=\"cppd\"> */</span>",
- "",
- "<span class=\"k\">public </span><span class=\"k\">class </span><span class=\"sym-31 sym\">HelloWorld</span> {",
- " <span class=\"k\">public</span> <span class=\"k\">void</span> <span class=\"sym-58 sym\">foo</span>() {",
- " }",
- " <span class=\"k\">public</span> <span class=\"k\">void</span> <span class=\"sym-84 sym\">bar</span>() {",
- " <span class=\"sym-58 sym\">foo</span>();",
- " }",
- "}"
- );
- }
-
- @Test
- public void should_not_query_sources_if_no_snapshot_data() throws Exception {
- SnapshotSourceDao snapshotSourceDao = mock(SnapshotSourceDao.class);
- SnapshotDataDao snapshotDataDao = mock(SnapshotDataDao.class);
-
- HtmlSourceDecorator sourceDecorator = new HtmlSourceDecorator(mock(MyBatis.class), snapshotSourceDao, snapshotDataDao);
-
- sourceDecorator.getDecoratedSourceAsHtml(14L);
-
- verify(snapshotDataDao, times(1)).selectSnapshotData(14L, Lists.newArrayList("highlight_syntax", "symbol"));
- verify(snapshotSourceDao, times(0)).selectSnapshotSource(14L);
- }
-
- @Test
- public void should_not_query_sources_if_no_snapshot_data_from_component() throws Exception {
- SnapshotSourceDao snapshotSourceDao = mock(SnapshotSourceDao.class);
- SnapshotDataDao snapshotDataDao = mock(SnapshotDataDao.class);
-
- HtmlSourceDecorator sourceDecorator = new HtmlSourceDecorator(mock(MyBatis.class), snapshotSourceDao, snapshotDataDao);
-
- sourceDecorator.getDecoratedSourceAsHtml("org.apache.struts:struts:DebuggingInterceptor", (Integer) null, (Integer) null);
-
- verify(snapshotDataDao, times(1)).selectSnapshotDataByComponentKey(eq("org.apache.struts:struts:DebuggingInterceptor"), eq(Lists.newArrayList("highlight_syntax", "symbol")),
- any(SqlSession.class));
- verify(snapshotSourceDao, times(0)).selectSnapshotSourceByComponentKey(eq("org.apache.struts:struts:DebuggingInterceptor"),
- any(SqlSession.class));
+ sourceDecorator = new HtmlSourceDecorator();
}
@Test
String sourceLine = "package org.polop;";
String highlighting = "0,7,k";
String symbols = "8,17,42";
- assertThat(sourceDecorator.getDecoratedSourceAsHtml(sourceLine, highlighting, symbols)).isEqualTo("<span class=\"k\">package</span> <span class=\"sym-42 sym\">org.polop</span>;");
+ assertThat(sourceDecorator.getDecoratedSourceAsHtml(sourceLine, highlighting, symbols)).isEqualTo(
+ "<span class=\"k\">package</span> <span class=\"sym-42 sym\">org.polop</span>;");
}
@Test
}
}
-
import org.sonar.api.web.UserRole;
import org.sonar.core.measure.db.MeasureKey;
import org.sonar.core.persistence.DbSession;
-import org.sonar.core.source.db.SnapshotSourceDao;
import org.sonar.server.db.DbClient;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.measure.persistence.MeasureDao;
+import org.sonar.server.source.index.SourceLineDoc;
import org.sonar.server.source.index.SourceLineIndex;
import org.sonar.server.user.MockUserSession;
+import java.util.Arrays;
import java.util.List;
import static org.fest.assertions.Assertions.assertThat;
import static org.fest.assertions.Fail.fail;
import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@Mock
HtmlSourceDecorator sourceDecorator;
- @Mock
- SnapshotSourceDao snapshotSourceDao;
-
- @Mock
- DeprecatedSourceDecorator deprecatedSourceDecorator;
-
@Mock
MeasureDao measureDao;
SourceLineIndex sourceLineIndex;
static final String PROJECT_KEY = "org.sonar.sample";
- static final String COMPONENT_KEY = "org.sonar.sample:Sample";
+ static final String COMPONENT_UUID = "abc123";
SourceService service;
-
@Before
public void setUp() throws Exception {
DbClient dbClient = mock(DbClient.class);
when(dbClient.openSession(false)).thenReturn(session);
when(dbClient.measureDao()).thenReturn(measureDao);
- service = new SourceService(dbClient, sourceDecorator, snapshotSourceDao, deprecatedSourceDecorator, sourceLineIndex);
+ service = new SourceService(dbClient, sourceDecorator, sourceLineIndex);
}
@Test
public void get_html_lines() throws Exception {
- MockUserSession.set().addComponentPermission(UserRole.CODEVIEWER, PROJECT_KEY, COMPONENT_KEY);
+ MockUserSession.set().addComponentPermission(UserRole.CODEVIEWER, PROJECT_KEY, COMPONENT_UUID);
+ when(sourceLineIndex.getLines(COMPONENT_UUID, 1, Integer.MAX_VALUE)).thenReturn(
+ Arrays.asList(new SourceLineDoc().setSource("source").setHighlighting("highlight").setSymbols("symbols")));
- service.getLinesAsHtml(COMPONENT_KEY);
+ service.getLinesAsHtml(COMPONENT_UUID, null, null);
- verify(sourceDecorator).getDecoratedSourceAsHtml(COMPONENT_KEY, (Integer) null, (Integer) null);
+ verify(sourceDecorator).getDecoratedSourceAsHtml("source", "highlight", "symbols");
}
@Test
public void get_block_of_lines() throws Exception {
- MockUserSession.set().addComponentPermission(UserRole.CODEVIEWER, PROJECT_KEY, COMPONENT_KEY);
-
- service.getLinesAsHtml(COMPONENT_KEY, 1, 2);
+ MockUserSession.set().addComponentPermission(UserRole.CODEVIEWER, PROJECT_KEY, COMPONENT_UUID);
- verify(sourceDecorator).getDecoratedSourceAsHtml(COMPONENT_KEY, 1, 2);
- }
+ when(sourceLineIndex.getLines(COMPONENT_UUID, 1, Integer.MAX_VALUE)).thenReturn(
+ Arrays.asList(new SourceLineDoc().setSource("source").setHighlighting("highlight").setSymbols("symbols"),
+ new SourceLineDoc().setSource("source2").setHighlighting("highlight2").setSymbols("symbols2")));
- @Test
- public void get_lines_from_deprecated_source_decorator_when_no_data_from_new_decorator() throws Exception {
- MockUserSession.set().addComponentPermission(UserRole.CODEVIEWER, PROJECT_KEY, COMPONENT_KEY);
- when(sourceDecorator.getDecoratedSourceAsHtml(eq(COMPONENT_KEY), anyInt(), anyInt())).thenReturn(null);
+ service.getLinesAsHtml(COMPONENT_UUID, null, null);
- service.getLinesAsHtml(COMPONENT_KEY, 1, 2);
-
- verify(deprecatedSourceDecorator).getSourceAsHtml(COMPONENT_KEY, 1, 2);
+ verify(sourceDecorator).getDecoratedSourceAsHtml("source", "highlight", "symbols");
+ verify(sourceDecorator).getDecoratedSourceAsHtml("source2", "highlight2", "symbols2");
}
@Test
public void get_scm_author_data() throws Exception {
- service.getScmAuthorData(COMPONENT_KEY);
- verify(measureDao).getNullableByKey(session, MeasureKey.of(COMPONENT_KEY, CoreMetrics.SCM_AUTHORS_BY_LINE_KEY));
+ service.getScmAuthorData(COMPONENT_UUID);
+ verify(measureDao).getNullableByKey(session, MeasureKey.of(COMPONENT_UUID, CoreMetrics.SCM_AUTHORS_BY_LINE_KEY));
}
@Test
public void fail_to_get_scm_author_data_if_no_permission() throws Exception {
MockUserSession.set().setLogin("johh");
try {
- service.getScmAuthorData(COMPONENT_KEY);
+ service.getScmAuthorData(COMPONENT_UUID);
fail();
} catch (Exception e) {
assertThat(e).isInstanceOf(ForbiddenException.class);
@Test
public void not_get_scm_author_data_if_no_data() throws Exception {
- MockUserSession.set().addComponentPermission(UserRole.CODEVIEWER, PROJECT_KEY, COMPONENT_KEY);
+ MockUserSession.set().addComponentPermission(UserRole.CODEVIEWER, PROJECT_KEY, COMPONENT_UUID);
when(measureDao.getNullableByKey(eq(session), any(MeasureKey.class))).thenReturn(null);
- assertThat(service.getScmAuthorData(COMPONENT_KEY)).isNull();
+ assertThat(service.getScmAuthorData(COMPONENT_UUID)).isNull();
}
@Test
public void get_scm_date_data() throws Exception {
- MockUserSession.set().addComponentPermission(UserRole.CODEVIEWER, PROJECT_KEY, COMPONENT_KEY);
- service.getScmDateData(COMPONENT_KEY);
- verify(measureDao).getNullableByKey(session, MeasureKey.of(COMPONENT_KEY, CoreMetrics.SCM_LAST_COMMIT_DATETIMES_BY_LINE_KEY));
+ MockUserSession.set().addComponentPermission(UserRole.CODEVIEWER, PROJECT_KEY, COMPONENT_UUID);
+ service.getScmDateData(COMPONENT_UUID);
+ verify(measureDao).getNullableByKey(session, MeasureKey.of(COMPONENT_UUID, CoreMetrics.SCM_LAST_COMMIT_DATETIMES_BY_LINE_KEY));
}
@Test
public void not_get_scm_date_data_if_no_data() throws Exception {
- MockUserSession.set().addComponentPermission(UserRole.CODEVIEWER, PROJECT_KEY, COMPONENT_KEY);
+ MockUserSession.set().addComponentPermission(UserRole.CODEVIEWER, PROJECT_KEY, COMPONENT_UUID);
when(measureDao.getNullableByKey(eq(session), any(MeasureKey.class))).thenReturn(null);
- assertThat(service.getScmDateData(COMPONENT_KEY)).isNull();
+ assertThat(service.getScmDateData(COMPONENT_UUID)).isNull();
}
@Test
public void getLinesAsTxt() throws Exception {
- MockUserSession.set().addComponentPermission(UserRole.CODEVIEWER, PROJECT_KEY, COMPONENT_KEY);
-
- when(snapshotSourceDao.selectSnapshotSourceByComponentKey(COMPONENT_KEY, session)).thenReturn("line1\nline2");
+ MockUserSession.set().addComponentPermission(UserRole.CODEVIEWER, PROJECT_KEY, COMPONENT_UUID);
+ when(sourceLineIndex.getLines(COMPONENT_UUID, 1, Integer.MAX_VALUE)).thenReturn(
+ Arrays.asList(
+ new SourceLineDoc().setSource("line1"),
+ new SourceLineDoc().setSource("line2")));
- List<String> result = service.getLinesAsTxt(session, COMPONENT_KEY);
+ List<String> result = service.getLinesAsTxt(COMPONENT_UUID, null, null);
assertThat(result).contains("line1", "line2");
}
- @Test
- public void getLinesAsTxt_returns_null_when_no_sources() throws Exception {
- MockUserSession.set().addComponentPermission(UserRole.CODEVIEWER, PROJECT_KEY, COMPONENT_KEY);
-
- when(snapshotSourceDao.selectSnapshotSourceByComponentKey(COMPONENT_KEY, session)).thenReturn(null);
-
- List<String> result = service.getLinesAsTxt(session, COMPONENT_KEY);
- assertThat(result).isNull();
- }
-
}
import org.sonar.server.component.ComponentTesting;
import org.sonar.server.component.db.ComponentDao;
import org.sonar.server.db.DbClient;
-import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.source.SourceService;
import org.sonar.server.ws.WsTester;
import static com.google.common.collect.Lists.newArrayList;
import static org.fest.assertions.Assertions.assertThat;
-import static org.fest.assertions.Fail.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
String fileKey = "src/Foo.java";
when(componentDao.getByKey(session, fileKey)).thenReturn(file);
- when(sourceService.getLinesAsTxt(session, fileKey)).thenReturn(newArrayList(
+ when(sourceService.getLinesAsTxt(file.uuid(), null, null)).thenReturn(newArrayList(
"public class HelloWorld {",
"}"
));
String result = request.execute().outputAsString();
assertThat(result).isEqualTo("public class HelloWorld {\n}\n");
}
-
- @Test
- public void fail_to_get_txt_when_no_source() throws Exception {
- String fileKey = "src/Foo.java";
- when(componentDao.getByKey(session, fileKey)).thenReturn(file);
- when(sourceService.getLinesAsTxt(session, fileKey)).thenReturn(null);
-
- WsTester.TestRequest request = tester.newGetRequest("api/sources", "raw").setParam("key", fileKey);
- try {
- request.execute();
- fail();
- } catch (Exception e) {
- assertThat(e).isInstanceOf(NotFoundException.class).hasMessage("File 'src/Foo.java' does not exist");
- }
- }
}
import org.junit.Before;
import org.junit.Test;
-import org.sonar.server.exceptions.NotFoundException;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.runners.MockitoJUnitRunner;
+import org.sonar.core.component.ComponentDto;
+import org.sonar.core.persistence.DbSession;
+import org.sonar.server.component.ComponentTesting;
+import org.sonar.server.component.db.ComponentDao;
+import org.sonar.server.db.DbClient;
import org.sonar.server.source.SourceService;
import org.sonar.server.ws.WsTester;
import static com.google.common.collect.Lists.newArrayList;
-import static org.fest.assertions.Assertions.assertThat;
-import static org.fest.assertions.Fail.fail;
import static org.mockito.Matchers.anyInt;
-import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+@RunWith(MockitoJUnitRunner.class)
public class ShowActionTest {
SourceService sourceService = mock(SourceService.class);
WsTester tester;
+ @Mock
+ DbClient dbClient;
+
+ @Mock
+ DbSession session;
+
+ @Mock
+ ComponentDao componentDao;
+
+ ComponentDto project = ComponentTesting.newProjectDto();
+ ComponentDto file = ComponentTesting.newFileDto(project);
+
@Before
public void setUp() throws Exception {
- tester = new WsTester(new SourcesWs(new ShowAction(sourceService), mock(RawAction.class), new ScmAction(sourceService, mock(ScmWriter.class)), mock(LinesAction.class),
+ when(dbClient.componentDao()).thenReturn(componentDao);
+ when(dbClient.openSession(false)).thenReturn(session);
+ tester = new WsTester(new SourcesWs(new ShowAction(sourceService, dbClient), mock(RawAction.class), new ScmAction(sourceService, mock(ScmWriter.class)),
+ mock(LinesAction.class),
mock(HashAction.class)));
}
@Test
public void show_source() throws Exception {
- String componentKey = "src/Foo.java";
- when(sourceService.getLinesAsHtml(eq(componentKey), anyInt(), anyInt())).thenReturn(newArrayList(
+ String fileKey = "src/Foo.java";
+ when(componentDao.getByKey(session, fileKey)).thenReturn(file);
+ when(sourceService.getLinesAsHtml(eq(file.uuid()), anyInt(), anyInt())).thenReturn(newArrayList(
"/*",
" * Header",
" */",
"",
"public class <span class=\"sym-31 sym\">HelloWorld</span> {",
"}"
- ));
+ ));
- WsTester.TestRequest request = tester.newGetRequest("api/sources", "show").setParam("key", componentKey);
+ WsTester.TestRequest request = tester.newGetRequest("api/sources", "show").setParam("key", fileKey);
request.execute().assertJson(getClass(), "show_source.json");
}
- @Test
- public void fail_to_show_source_if_no_source_found() throws Exception {
- String componentKey = "src/Foo.java";
- when(sourceService.getLinesAsHtml(anyString(), anyInt(), anyInt())).thenReturn(null);
-
- try {
- WsTester.TestRequest request = tester.newGetRequest("api/sources", "show").setParam("key", componentKey);
- request.execute();
- fail();
- } catch (Exception e) {
- assertThat(e).isInstanceOf(NotFoundException.class);
- }
- }
-
@Test
public void show_source_with_from_and_to_params() throws Exception {
String fileKey = "src/Foo.java";
- when(sourceService.getLinesAsHtml(fileKey, 3, 5)).thenReturn(newArrayList(
+ when(componentDao.getByKey(session, fileKey)).thenReturn(file);
+ when(sourceService.getLinesAsHtml(file.uuid(), 3, 5)).thenReturn(newArrayList(
" */",
"",
"public class <span class=\"sym-31 sym\">HelloWorld</span> {"
- ));
+ ));
WsTester.TestRequest request = tester
.newGetRequest("api/sources", "show")
.setParam("key", fileKey)
@Test
public void show_source_accept_from_less_than_one() throws Exception {
String fileKey = "src/Foo.java";
- when(sourceService.getLinesAsHtml(fileKey, 1, 5)).thenReturn(newArrayList(
+ when(componentDao.getByKey(session, fileKey)).thenReturn(file);
+ when(sourceService.getLinesAsHtml(file.uuid(), 1, 5)).thenReturn(newArrayList(
" */",
"",
"public class <span class=\"sym-31 sym\">HelloWorld</span> {"
- ));
+ ));
WsTester.TestRequest request = tester
.newGetRequest("api/sources", "show")
.setParam("key", fileKey)
.setParam("from", "0")
.setParam("to", "5");
request.execute();
- verify(sourceService).getLinesAsHtml(fileKey, 1, 5);
+ verify(sourceService).getLinesAsHtml(file.uuid(), 1, 5);
}
}
public class SourcesWsTest {
- ShowAction showAction = new ShowAction(mock(SourceService.class));
+ ShowAction showAction = new ShowAction(mock(SourceService.class), mock(DbClient.class));
RawAction rawAction = new RawAction(mock(DbClient.class), mock(SourceService.class));
ScmAction scmAction = new ScmAction(mock(SourceService.class), new ScmWriter());
LinesAction linesAction = new LinesAction(mock(SourceLineIndex.class), mock(HtmlSourceDecorator.class));
package org.sonar.server.text;
import org.junit.Test;
-import org.sonar.server.source.HtmlSourceDecorator;
import static org.fest.assertions.Assertions.assertThat;
-import static org.mockito.Mockito.*;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
public class RubyTextServiceTest {
MacroInterpreter macroInterpreter = mock(MacroInterpreter.class);
- HtmlSourceDecorator sourceDecorator = mock(HtmlSourceDecorator.class);
- RubyTextService text = new RubyTextService(macroInterpreter, sourceDecorator);
+ RubyTextService text = new RubyTextService(macroInterpreter);
@Test
public void interpretMacros() throws Exception {
text.interpretMacros("text with macros");
verify(macroInterpreter, times(1)).interpret("text with macros");
- verifyZeroInteractions(sourceDecorator);
}
@Test
String html = text.markdownToHtml("a > b");
assertThat(html).isEqualTo("a > b");
}
-
- @Test
- public void highlightedSourceLines() throws Exception {
- text.highlightedSourceLines(123L);
- verify(sourceDecorator, times(1)).getDecoratedSourceAsHtml(123L);
- verifyZeroInteractions(macroInterpreter);
- }
}
+++ /dev/null
-<dataset>
-
- <projects id="1" kee="org.apache.struts:struts:Dispatcher" enabled="[true]" uuid="ABCD"/>
- <projects id="2" kee="org.apache.struts:struts:VelocityManager" enabled="[true]" uuid="BCDE"/>
- <projects id="3" kee="org.apache.struts:struts:DebuggingInterceptor" enabled="[true]" uuid="CDEF"/>
-
- <snapshots id="11" project_id="1" islast="[true]" />
- <snapshots id="12" project_id="2" islast="[true]" />
- <snapshots id="13" project_id="3" islast="[true]" />
- <snapshots id="14" project_id="3" islast="[true]" />
-
- <snapshot_data id="101" resource_id="1" snapshot_id="11" snapshot_data="0,16,cppd;18,25,k;25,31,k;" data_type="highlight_syntax" />
- <snapshot_data id="102" resource_id="2" snapshot_id="12" snapshot_data="31,41,31;" data_type="symbol" />
- <snapshot_data id="103" resource_id="3" snapshot_id="13" snapshot_data="0,16,cppd;18,25,k;25,31,k;46,52,k;53,57,k;72,78,k;79,83,k;" data_type="highlight_syntax" />
- <snapshot_data id="104" resource_id="3" snapshot_id="13" snapshot_data="31,41,31;58,61,58,96;84,87,84;" data_type="symbol" />
-
- <snapshot_sources id="101" snapshot_id="11" data="/* * Header */ public class HelloWorld { }" />
- <snapshot_sources id="102" snapshot_id="12" data="/* * Header */ public class HelloWorld { }" />
- <snapshot_sources id="103" snapshot_id="13" data="/* * Header */ public class HelloWorld { public void foo() { } public void bar() { foo(); } }" />
-</dataset>
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
+import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
+import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
}
@Override
- public String getSource(Resource resource) {
- return persistence.getSource(resource);
+ public String getSource(Resource reference) {
+ Resource resource = getResource(reference);
+ if (resource instanceof File) {
+ File file = (File) resource;
+ Project module = (Project) file.getParent().getParent();
+ ProjectDefinition def = projectTree.getProjectDefinition(module);
+ try {
+ return FileUtils.readFileToString(new java.io.File(def.getBaseDir(), file.getPath()));
+ } catch (IOException e) {
+ throw new IllegalStateException("Unable to read file content " + reference, e);
+ }
+ }
+ return null;
}
/**
return null;
}
- @Override
- public String getSource(Resource resource) {
- return sourcePersister.getSource(resource);
- }
-
@Override
public void saveDependency(Project project, Dependency dependency, Dependency parentDependency) {
if (ResourceUtils.isPersistable(dependency.getFrom()) && ResourceUtils.isPersistable(dependency.getTo())) {
Snapshot saveResource(Project project, Resource resource, @Nullable Resource parent);
- String getSource(Resource resource);
-
void saveDependency(Project project, Dependency dependency, Dependency parentDependency);
void saveLink(Project project, ProjectLink link);
import org.sonar.api.batch.sensor.duplication.DuplicationGroup;
import org.sonar.api.batch.sensor.duplication.DuplicationGroup.Block;
import org.sonar.api.batch.sensor.symbol.Symbol;
-import org.sonar.api.database.model.Snapshot;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.measures.Measure;
-import org.sonar.api.resources.Resource;
import org.sonar.api.utils.KeyValueFormat;
import org.sonar.api.utils.System2;
import org.sonar.api.utils.text.CsvWriter;
import org.sonar.core.source.SnapshotDataTypes;
import org.sonar.core.source.db.FileSourceDto;
import org.sonar.core.source.db.FileSourceMapper;
-import org.sonar.core.source.db.SnapshotSourceDao;
-import org.sonar.core.source.db.SnapshotSourceDto;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
private static final String BOM = "\uFEFF";
private final ResourcePersister resourcePersister;
- private final SnapshotSourceDao sourceDao;
private final InputPathCache inputPathCache;
private final MyBatis mybatis;
private final MeasureCache measureCache;
private CodeColorizers codeColorizers;
private DuplicationCache duplicationCache;
- public SourcePersister(ResourcePersister resourcePersister, SnapshotSourceDao sourceDao, InputPathCache inputPathCache,
+ public SourcePersister(ResourcePersister resourcePersister, InputPathCache inputPathCache,
MyBatis mybatis, MeasureCache measureCache, ComponentDataCache componentDataCache, ProjectTree projectTree, System2 system2,
ResourceCache resourceCache, CodeColorizers codeColorizers, DuplicationCache duplicationCache) {
this.resourcePersister = resourcePersister;
- this.sourceDao = sourceDao;
this.inputPathCache = inputPathCache;
this.mybatis = mybatis;
this.measureCache = measureCache;
this.duplicationCache = duplicationCache;
}
- public void saveSource(Resource resource, String source, Date updatedAt) {
- Snapshot snapshot = resourcePersister.getSnapshotOrFail(resource);
- SnapshotSourceDto dto = new SnapshotSourceDto();
- dto.setSnapshotId(snapshot.getId().longValue());
- dto.setData(source);
- dto.setUpdatedAt(updatedAt);
- sourceDao.insert(dto);
- }
-
- @CheckForNull
- public String getSource(Resource resource) {
- Snapshot snapshot = resourcePersister.getSnapshot(resource);
- if (snapshot != null && snapshot.getId() != null) {
- return sourceDao.selectSnapshotSource(snapshot.getId());
- }
- return null;
- }
-
@Override
public void persist() {
// Don't use batch insert for file_sources since keeping all data in memory can produce OOM for big files
*/
package org.sonar.batch.scan.filesystem;
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.CharMatcher;
-import com.google.common.io.Files;
import org.sonar.api.BatchComponent;
import org.sonar.api.batch.SonarIndex;
import org.sonar.api.batch.fs.FileSystem;
import org.sonar.api.batch.fs.InputFile;
-import org.sonar.api.batch.fs.InputFile.Status;
import org.sonar.api.batch.fs.internal.DeprecatedDefaultInputFile;
import org.sonar.api.resources.File;
import org.sonar.api.resources.Languages;
import org.sonar.api.resources.Project;
import org.sonar.api.resources.Resource;
-import org.sonar.api.utils.SonarException;
import org.sonar.batch.index.ResourceKeyMigration;
-import org.sonar.batch.index.SnapshotCache;
-import org.sonar.batch.index.SourcePersister;
-import org.sonar.batch.protocol.input.ProjectReferentials;
import org.sonar.batch.util.DeprecatedKeyUtils;
-import java.util.Date;
-
/**
* Index all files/directories of the module in SQ database and importing source code.
*
private final SonarIndex sonarIndex;
private final ResourceKeyMigration migration;
private final Project module;
- private final SourcePersister sourcePersister;
- private final ProjectReferentials projectReferentials;
- private final Date projectAnalysisDate;
- public ComponentIndexer(Project module, Languages languages, SonarIndex sonarIndex, ResourceKeyMigration migration, SourcePersister sourcePersister,
- ProjectReferentials projectReferentials, SnapshotCache snapshotCache) {
+ public ComponentIndexer(Project module, Languages languages, SonarIndex sonarIndex, ResourceKeyMigration migration) {
this.module = module;
this.languages = languages;
this.sonarIndex = sonarIndex;
this.migration = migration;
- this.sourcePersister = sourcePersister;
- this.projectReferentials = projectReferentials;
- this.projectAnalysisDate = snapshotCache.get(module.getEffectiveKey()).getBuildDate();
}
public void execute(FileSystem fs) {
sonarFile.setDeprecatedKey(pathFromSourceDir);
}
sonarIndex.index(sonarFile);
-
- importSources(fs, inputFile, sonarFile);
}
}
- @VisibleForTesting
- void importSources(FileSystem fs, InputFile inputFile, Resource sonarFile) {
- try {
- // TODO this part deserves optimization.
- // We should try to remove BOM and count lines in a single pass
- String source = Files.toString(inputFile.file(), fs.encoding());
- // SONAR-3860 Remove BOM character from source
- source = CharMatcher.anyOf("\uFEFF").removeFrom(source);
- if (inputFile.status() == Status.SAME) {
- sourcePersister.saveSource(sonarFile, source, projectReferentials.lastAnalysisDate());
- } else {
- sourcePersister.saveSource(sonarFile, source, this.projectAnalysisDate);
- }
-
- } catch (Exception e) {
- throw new SonarException("Unable to read and import the source file : '" + inputFile.absolutePath() + "' with the charset : '"
- + fs.encoding() + "'.", e);
- }
- }
}
import org.sonar.core.source.SnapshotDataTypes;
import org.sonar.core.source.db.FileSourceDao;
import org.sonar.core.source.db.FileSourceDto;
-import org.sonar.core.source.db.SnapshotSourceDao;
import java.io.IOException;
import java.util.Arrays;
when(measureCache.byMetric(anyString(), anyString())).thenReturn(Collections.<org.sonar.api.measures.Measure>emptyList());
componentDataCache = mock(ComponentDataCache.class);
duplicationCache = mock(DuplicationCache.class);
- sourcePersister = new SourcePersister(resourcePersister, new SnapshotSourceDao(getMyBatis()), inputPathCache,
+ sourcePersister = new SourcePersister(resourcePersister, inputPathCache,
getMyBatis(), measureCache, componentDataCache, projectTree, system2,
resourceCache, mock(CodeColorizers.class), duplicationCache);
Project project = new Project(PROJECT_KEY);
basedir = temp.newFolder();
}
- @Test
- public void shouldSaveSource() {
- setupData("shouldSaveSource");
- sourcePersister.saveSource(new File("org/foo/Bar.java"), "this is the file content", DateUtils.parseDateTime("2014-10-31T16:44:02+0100"));
- checkTables("shouldSaveSource", "snapshot_sources");
- }
-
@Test
public void testPersistDontTouchUnchanged() throws Exception {
setupData("file_sources");
*/
package org.sonar.batch.scan.filesystem;
-import com.google.common.base.Charsets;
import org.apache.commons.io.FileUtils;
-import org.apache.commons.lang.CharEncoding;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.mockito.ArgumentMatcher;
-import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent;
import org.sonar.api.batch.SonarIndex;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.internal.DefaultFileSystem;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.DeprecatedDefaultInputFile;
-import org.sonar.api.database.model.Snapshot;
import org.sonar.api.resources.AbstractLanguage;
import org.sonar.api.resources.Java;
import org.sonar.api.resources.Languages;
import org.sonar.api.resources.Project;
import org.sonar.api.resources.Qualifiers;
-import org.sonar.api.resources.Resource;
import org.sonar.batch.index.ResourceKeyMigration;
-import org.sonar.batch.index.SnapshotCache;
-import org.sonar.batch.index.SourcePersister;
-import org.sonar.batch.protocol.input.ProjectReferentials;
import java.io.File;
import java.io.IOException;
-import java.nio.charset.Charset;
-import java.util.Date;
import static org.mockito.Matchers.argThat;
-import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@Rule
public TemporaryFolder temp = new TemporaryFolder();
- File baseDir;
- DefaultFileSystem fs = new DefaultFileSystem();
- SonarIndex sonarIndex;
- AbstractLanguage cobolLanguage;
- Project project;
-
- String aClaess;
- String explicacao;
- private SourcePersister sourcePersister;
+ private File baseDir;
+ private DefaultFileSystem fs = new DefaultFileSystem();
+ private SonarIndex sonarIndex;
+ private AbstractLanguage cobolLanguage;
+ private Project project;
@Before
public void prepare() throws IOException {
baseDir = temp.newFolder();
sonarIndex = mock(SonarIndex.class);
- sourcePersister = mock(SourcePersister.class);
project = new Project("myProject");
cobolLanguage = new AbstractLanguage("cobol") {
@Override
return new String[] {"cbl"};
}
};
-
- aClaess = new String(new byte[] {65, 67, 108, 97, -61, -88, 115, 115, 40, 41}, CharEncoding.UTF_8);
- explicacao = new String(new byte[] {101, 120, 112, 108, 105, 99, 97, -61, -89, -61, -93, 111, 40, 41}, CharEncoding.UTF_8);
}
@Test
}
private ComponentIndexer createIndexer(Languages languages) {
- SnapshotCache snapshotCache = new SnapshotCache();
- snapshotCache.put("myProject", mock(Snapshot.class));
- ComponentIndexer indexer = new ComponentIndexer(project, languages, sonarIndex, mock(ResourceKeyMigration.class), sourcePersister, new ProjectReferentials(),
- snapshotCache);
- return indexer;
+ return new ComponentIndexer(project, languages, sonarIndex, mock(ResourceKeyMigration.class));
}
@Test
verify(sonarIndex).index(org.sonar.api.resources.File.create("/src/test/foo/bar/FooTest.cbl", "foo/bar/FooTest.cbl", cobolLanguage, true));
}
- @Test
- public void shouldImportSource() throws IOException {
- fs.add(newInputFile("src/main/java/foo/bar/Foo.java", "sample code", "foo/bar/Foo.java", "java", false));
- Languages languages = new Languages(Java.INSTANCE);
- ComponentIndexer indexer = createIndexer(languages);
- indexer.execute(fs);
-
- Resource sonarFile = org.sonar.api.resources.File.create("src/main/java/foo/bar/Foo.java", "foo/bar/Foo.java", Java.INSTANCE, false);
- verify(sonarIndex).index(sonarFile);
- verify(sourcePersister).saveSource(sonarFile, "sample code", null);
- }
-
- @Test
- public void should_use_mac_roman_charset_for_reading_source_files() throws Exception {
- String encoding = "MacRoman";
- String testFile = "MacRomanEncoding.java";
- fileEncodingTest(encoding, testFile);
- }
-
- @Test
- public void should_use_CP1252_charset_for_reading_source_files() throws Exception {
- String encoding = "CP1252";
- String testFile = "CP1252Encoding.java";
- fileEncodingTest(encoding, testFile);
- }
-
- @Test(expected = ArgumentsAreDifferent.class)
- public void should_fail_with_wrong_charset_for_reading_source_files() throws Exception {
- String encoding = CharEncoding.UTF_8;
- String testFile = "CP1252Encoding.java";
- fileEncodingTest(encoding, testFile);
- }
-
- @Test
- public void remove_byte_order_mark_character() throws Exception {
- File javaFile1 = new File(baseDir, "src/main/java/foo/bar/Foo.java");
- FileUtils.write(javaFile1, "\uFEFFpublic class Test", Charsets.UTF_8);
- fs.add(new DeprecatedDefaultInputFile("foo", "src/main/java/foo/bar/Foo.java")
- .setPathRelativeToSourceDir("foo/bar/Foo.java")
- .setFile(javaFile1)
- .setLanguage("java"));
- Languages languages = new Languages(Java.INSTANCE);
- ComponentIndexer indexer = createIndexer(languages);
- indexer.execute(fs);
-
- Resource sonarFile = org.sonar.api.resources.File.create("src/main/java/foo/bar/Foo.java", "foo/bar/Foo.java", Java.INSTANCE, false);
-
- verify(sourcePersister).saveSource(eq(sonarFile), argThat(new ArgumentMatcher<String>() {
- @Override
- public boolean matches(Object arg0) {
- String source = (String) arg0;
- return !source.contains("\uFEFF");
- }
- }), (Date) eq(null));
- }
-
- private void fileEncodingTest(String encoding, String testFile) throws Exception {
- fs.setEncoding(Charset.forName(encoding));
-
- File javaFile1 = new File(baseDir, "src/main/java/foo/bar/Foo.java");
- FileUtils.copyFile(getFile(testFile), javaFile1);
- fs.add(new DeprecatedDefaultInputFile("foo", "src/main/java/foo/bar/Foo.java")
- .setPathRelativeToSourceDir("foo/bar/Foo.java")
- .setFile(javaFile1)
- .setLanguage("java"));
- Languages languages = new Languages(Java.INSTANCE);
- ComponentIndexer indexer = createIndexer(languages);
- indexer.execute(fs);
-
- Resource sonarFile = org.sonar.api.resources.File.create("/src/main/java/foo/bar/Foo.java", "foo/bar/Foo.java", Java.INSTANCE, false);
-
- verify(sourcePersister).saveSource(eq(sonarFile), argThat(new ArgumentMatcher<String>() {
- @Override
- public boolean matches(Object arg0) {
- String source = (String) arg0;
- return source.contains(aClaess) && source.contains(explicacao);
- }
- }), (Date) eq(null));
- }
-
- private File getFile(String testFile) {
- return new File("test-resources/org/sonar/batch/phases/ComponentIndexerTest/encoding/" + testFile);
- }
-
private DefaultInputFile newInputFile(String path, String content, String sourceRelativePath, String languageKey, boolean unitTest) throws IOException {
File file = new File(baseDir, path);
FileUtils.write(file, content);
+++ /dev/null
-public class Car {
-
- public AClaèss() {
- }
-
- public int explicação() {
- return 1;
- }
-
- public String getS() {
- return "";
- }
-}
+++ /dev/null
-public class Car {
-
- public ACla\8fss() {
- }
-
- public int explica\8d\8bo() {
- return 1;
- }
-
- public String getS() {
- return "";
- }
-}
import org.sonar.core.dashboard.DashboardDao;
import org.sonar.core.duplication.DuplicationDao;
import org.sonar.core.graph.jdbc.GraphDao;
-import org.sonar.core.issue.db.*;
+import org.sonar.core.issue.db.ActionPlanDao;
+import org.sonar.core.issue.db.ActionPlanStatsDao;
+import org.sonar.core.issue.db.IssueChangeDao;
+import org.sonar.core.issue.db.IssueDao;
+import org.sonar.core.issue.db.IssueFilterDao;
+import org.sonar.core.issue.db.IssueFilterFavouriteDao;
import org.sonar.core.notification.db.NotificationQueueDao;
import org.sonar.core.permission.PermissionDao;
import org.sonar.core.permission.PermissionTemplateDao;
import org.sonar.core.rule.RuleDao;
import org.sonar.core.source.db.FileSourceDao;
import org.sonar.core.source.db.SnapshotDataDao;
-import org.sonar.core.source.db.SnapshotSourceDao;
import org.sonar.core.technicaldebt.db.CharacteristicDao;
import org.sonar.core.template.LoadedTemplateDao;
-import org.sonar.core.user.*;
+import org.sonar.core.user.AuthorDao;
+import org.sonar.core.user.AuthorizationDao;
+import org.sonar.core.user.GroupMembershipDao;
+import org.sonar.core.user.RoleDao;
+import org.sonar.core.user.UserDao;
import java.util.List;
RuleDao.class,
SemaphoreDao.class,
SnapshotDataDao.class,
- SnapshotSourceDao.class,
UserDao.class
- );
+ );
}
}
import org.sonar.core.source.db.FileSourceMapper;
import org.sonar.core.source.db.SnapshotDataDto;
import org.sonar.core.source.db.SnapshotDataMapper;
-import org.sonar.core.source.db.SnapshotSourceMapper;
import org.sonar.core.technicaldebt.db.CharacteristicDto;
import org.sonar.core.technicaldebt.db.CharacteristicMapper;
import org.sonar.core.technicaldebt.db.RequirementMigrationDto;
LoadedTemplateMapper.class, MeasureFilterMapper.class, Migration44Mapper.class, PermissionTemplateMapper.class, PropertiesMapper.class, PurgeMapper.class,
ResourceKeyUpdaterMapper.class, ResourceIndexerMapper.class, ResourceSnapshotMapper.class, RoleMapper.class, RuleMapper.class,
SchemaMigrationMapper.class, SemaphoreMapper.class, UserMapper.class, GroupMapper.class, WidgetMapper.class, WidgetPropertyMapper.class,
- org.sonar.api.database.model.MeasureMapper.class, SnapshotDataMapper.class, SnapshotSourceMapper.class, FileSourceMapper.class, ActionPlanMapper.class,
+ org.sonar.api.database.model.MeasureMapper.class, SnapshotDataMapper.class, FileSourceMapper.class, ActionPlanMapper.class,
ActionPlanStatsMapper.class,
NotificationQueueMapper.class, CharacteristicMapper.class,
GroupMembershipMapper.class, QualityProfileMapper.class, ActiveRuleMapper.class,
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-package org.sonar.core.source.db;
-
-import org.apache.ibatis.session.SqlSession;
-import org.sonar.api.BatchComponent;
-import org.sonar.api.ServerComponent;
-import org.sonar.core.persistence.MyBatis;
-
-import javax.annotation.CheckForNull;
-
-/**
- * @since 3.6
- */
-public class SnapshotSourceDao implements BatchComponent, ServerComponent {
-
- private final MyBatis mybatis;
-
- public SnapshotSourceDao(MyBatis myBatis) {
- this.mybatis = myBatis;
- }
-
- @CheckForNull
- public String selectSnapshotSource(long snapshotId) {
- SqlSession session = mybatis.openSession(false);
-
- try {
- SnapshotSourceMapper mapper = session.getMapper(SnapshotSourceMapper.class);
- return mapper.selectSnapshotSource(snapshotId);
-
- } finally {
- MyBatis.closeQuietly(session);
- }
- }
-
- @CheckForNull
- public String selectSnapshotSourceByComponentKey(String componentKey, SqlSession session) {
- SnapshotSourceMapper mapper = session.getMapper(SnapshotSourceMapper.class);
- return mapper.selectSnapshotSourceByComponentKey(componentKey);
- }
-
- @CheckForNull
- public String selectSnapshotSourceByComponentKey(String componentKey) {
- SqlSession session = mybatis.openSession(false);
- try {
- return selectSnapshotSourceByComponentKey(componentKey, session);
- } finally {
- MyBatis.closeQuietly(session);
- }
- }
-
- public void insert(SnapshotSourceDto dto) {
- SqlSession session = mybatis.openSession(false);
- try {
- session.getMapper(SnapshotSourceMapper.class).insert(dto);
- session.commit();
- } finally {
- MyBatis.closeQuietly(session);
- }
- }
-
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.core.source.db;
-
-import java.util.Date;
-
-public class SnapshotSourceDto {
- private Long id;
- private Long snapshotId;
- private String data;
- private Date updatedAt;
-
- public Long getId() {
- return id;
- }
-
- public SnapshotSourceDto setId(Long id) {
- this.id = id;
- return this;
- }
-
- public Long getSnapshotId() {
- return snapshotId;
- }
-
- public SnapshotSourceDto setSnapshotId(Long snapshotId) {
- this.snapshotId = snapshotId;
- return this;
- }
-
- public String getData() {
- return data;
- }
-
- public SnapshotSourceDto setData(String data) {
- this.data = data;
- return this;
- }
-
- public Date getUpdatedAt() {
- return updatedAt;
- }
-
- public SnapshotSourceDto setUpdatedAt(Date updatedAt) {
- this.updatedAt = updatedAt;
- return this;
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-package org.sonar.core.source.db;
-
-import javax.annotation.CheckForNull;
-
-/**
- * @since 3.6
- */
-public interface SnapshotSourceMapper {
-
- @CheckForNull
- String selectSnapshotSource(long snapshotId);
-
- @CheckForNull
- String selectSnapshotSourceByComponentKey(String componentKey);
-
- void insert(SnapshotSourceDto dto);
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8" ?>
-
-<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
-
-<mapper namespace="org.sonar.core.source.db.SnapshotSourceMapper">
-
- <select id="selectSnapshotSource" parameterType="long" resultType="string">
- SELECT data
- FROM snapshot_sources
- WHERE snapshot_id = #{sid}
- </select>
-
- <select id="selectSnapshotSourceByComponentKey" parameterType="String" resultType="string">
- SELECT data
- FROM snapshot_sources source
- INNER JOIN snapshots s ON s.id=source.snapshot_id and s.islast=${_true}
- INNER JOIN projects p ON p.id=s.project_id and p.enabled=${_true}
- WHERE p.kee = #{componentKey}
- </select>
-
- <insert id="insert" parameterType="org.sonar.core.source.db.SnapshotSourceDto" useGeneratedKeys="false">
- insert into snapshot_sources (snapshot_id, data, updated_at)
- values (#{snapshotId}, #{data}, #{updatedAt})
- </insert>
-
-</mapper>
-
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-package org.sonar.core.source.db;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.sonar.api.utils.DateUtils;
-import org.sonar.core.persistence.AbstractDaoTestCase;
-
-import static org.fest.assertions.Assertions.assertThat;
-
-public class SnapshotSourceDaoTest extends AbstractDaoTestCase {
-
- private SnapshotSourceDao dao;
-
- @Before
- public void setUpTestData() {
- dao = new SnapshotSourceDao(getMyBatis());
- setupData("shared");
- }
-
- @Test
- public void select_snapshot_source() throws Exception {
- String snapshotSource = dao.selectSnapshotSource(11L);
-
- assertThat(snapshotSource).isEqualTo("public class Foo {public Foo(){}}");
- }
-
- @Test
- public void select_snapshot_source_by_component_key() throws Exception {
- String snapshotSource = dao.selectSnapshotSourceByComponentKey("org.apache.struts:struts:Dispatcher");
-
- assertThat(snapshotSource).isEqualTo("public class Foo {public Foo(){}}");
- }
-
- @Test
- public void insert() throws Exception {
- dao.insert(new SnapshotSourceDto().setData("bar").setSnapshotId(11L).setUpdatedAt(DateUtils.parseDateTime("2014-10-31T16:44:02+0100")));
-
- checkTable("insert", "snapshot_sources");
- }
-
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-package org.sonar.core.source.db;
-
-import org.junit.Test;
-
-import static org.fest.assertions.Assertions.assertThat;
-
-public class SnapshotSourceDtoTest {
-
- @Test
- public void test_setters_and_getters() throws Exception {
- SnapshotSourceDto dto = new SnapshotSourceDto()
- .setId(1L)
- .setSnapshotId(10L)
- .setData("data");
-
- assertThat(dto.getId()).isEqualTo(1L);
- assertThat(dto.getSnapshotId()).isEqualTo(10L);
- assertThat(dto.getData()).isEqualTo("data");
- }
-}
+++ /dev/null
-<dataset>
-
- <projects id="1" kee="org.apache.struts:struts:Dispatcher" enabled="[true]"/>
-
- <snapshots id="10" project_id="1" islast="[false]"/>
- <snapshots id="11" project_id="1" islast="[true]"/>
-
- <snapshot_sources id="101" snapshot_id="11" data="public class Foo {public Foo(){}}" updated_at="2014-10-30 16:44:02.000"/>
-
- <snapshot_sources id="102" snapshot_id="11" data="bar" updated_at="2014-10-31 16:44:02.000"/>
-
-</dataset>
+++ /dev/null
-<dataset>
-
- <projects id="1" kee="org.apache.struts:struts:Dispatcher" enabled="[true]"/>
-
- <snapshots id="10" project_id="1" islast="[false]" />
- <snapshots id="11" project_id="1" islast="[true]" />
-
- <snapshot_sources id="101" snapshot_id="11" data="public class Foo {public Foo(){}}" updated_at="2014-10-30 16:44:02.000" />
-
-</dataset>
*/
package org.sonar.api.batch;
+import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.design.Dependency;
import org.sonar.api.measures.Measure;
* @return source code associated with a specified resource, <code>null</code> if not available
* (for example if resource is not a file)
* @since 2.9
+ * @deprecated since 5.0 sources are no more stored in SQ as a single blob. Use {@link InputFile#file()} to read file content from disk.
*/
+ @Deprecated
@CheckForNull
public abstract String getSource(Resource resource);
package org.sonar.api.web;
import com.google.common.base.Objects;
-import org.sonar.api.ServerExtension;
import org.sonar.api.source.Highlightable;
import org.sonar.api.task.TaskExtension;
import org.sonar.colorizer.Tokenizer;
* @deprecated since 4.5.2 use {@link Highlightable} API
*/
@Deprecated
-public abstract class CodeColorizerFormat implements ServerExtension, TaskExtension {
+public abstract class CodeColorizerFormat implements TaskExtension {
private String languageKey;