]> source.dussan.org Git - sonarqube.git/commitdiff
SONAR-6134, SONAR-6048 Improve performance of FS indexation
authorJulien HENRY <julien.henry@sonarsource.com>
Wed, 28 Jan 2015 21:41:25 +0000 (22:41 +0100)
committerJulien HENRY <julien.henry@sonarsource.com>
Tue, 10 Feb 2015 16:16:01 +0000 (17:16 +0100)
276 files changed:
plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/issue/CountUnresolvedIssuesDecorator.java
plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/timemachine/AbstractNewCoverageFileAnalyzer.java
plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/timemachine/NewCoverageFileAnalyzer.java
plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/timemachine/NewItCoverageFileAnalyzer.java
plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/timemachine/NewOverallCoverageFileAnalyzer.java
plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/timemachine/TendencyDecorator.java
plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/timemachine/TimeMachineConfigurationPersister.java
plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/timemachine/VariationDecorator.java
plugins/sonar-core-plugin/src/test/java/org/sonar/plugins/core/issue/CountFalsePositivesDecoratorTest.java
plugins/sonar-core-plugin/src/test/java/org/sonar/plugins/core/issue/CountUnresolvedIssuesDecoratorTest.java
plugins/sonar-core-plugin/src/test/java/org/sonar/plugins/core/sensors/DirectoriesDecoratorTest.java
plugins/sonar-core-plugin/src/test/java/org/sonar/plugins/core/sensors/ManualMeasureDecoratorTest.java
plugins/sonar-core-plugin/src/test/java/org/sonar/plugins/core/timemachine/TendencyDecoratorTest.java
plugins/sonar-core-plugin/src/test/java/org/sonar/plugins/core/timemachine/TimeMachineConfigurationPersisterTest.java
plugins/sonar-core-plugin/src/test/java/org/sonar/plugins/core/timemachine/VariationDecoratorTest.java
plugins/sonar-cpd-plugin/src/test/java/org/sonar/plugins/cpd/CpdSensorTest.java
plugins/sonar-cpd-plugin/src/test/java/org/sonar/plugins/cpd/JavaCpdEngineTest.java
plugins/sonar-cpd-plugin/src/test/java/org/sonar/plugins/cpd/decorators/SumDuplicationsDecoratorTest.java
plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/lang/CoveragePerTestSensorTest.java
plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/lang/DependencySensorTest.java
plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/lang/MeasureSensorTest.java
plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/lang/SymbolReferencesSensorTest.java
plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/lang/SyntaxHighlightingSensorTest.java
plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/lang/TestCaseSensorTest.java
plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/lang/XooTokenizerSensorTest.java
plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/rule/OneIssuePerLineSensorTest.java
plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/scm/XooBlameCommandTest.java
server/sonar-server/src/test/java/org/sonar/server/issue/notification/IssueNotificationsTest.java
sonar-batch/pom.xml
sonar-batch/src/main/java/org/sonar/batch/DecoratorsSelector.java [deleted file]
sonar-batch/src/main/java/org/sonar/batch/DefaultDecoratorContext.java [deleted file]
sonar-batch/src/main/java/org/sonar/batch/DefaultProjectClasspath.java [deleted file]
sonar-batch/src/main/java/org/sonar/batch/DefaultResourceCreationLock.java [deleted file]
sonar-batch/src/main/java/org/sonar/batch/DefaultTimeMachine.java [deleted file]
sonar-batch/src/main/java/org/sonar/batch/DeprecatedSensorContext.java [deleted file]
sonar-batch/src/main/java/org/sonar/batch/FormulaDecorator.java [deleted file]
sonar-batch/src/main/java/org/sonar/batch/ProjectConfigurator.java
sonar-batch/src/main/java/org/sonar/batch/ResourceFilters.java [deleted file]
sonar-batch/src/main/java/org/sonar/batch/bootstrap/GlobalContainer.java
sonar-batch/src/main/java/org/sonar/batch/bootstrap/TaskContainer.java
sonar-batch/src/main/java/org/sonar/batch/components/PastMeasuresLoader.java
sonar-batch/src/main/java/org/sonar/batch/components/PastSnapshot.java
sonar-batch/src/main/java/org/sonar/batch/components/PastSnapshotFinder.java
sonar-batch/src/main/java/org/sonar/batch/components/PastSnapshotFinderByDate.java [deleted file]
sonar-batch/src/main/java/org/sonar/batch/components/PastSnapshotFinderByDays.java [deleted file]
sonar-batch/src/main/java/org/sonar/batch/components/PastSnapshotFinderByPreviousAnalysis.java [deleted file]
sonar-batch/src/main/java/org/sonar/batch/components/PastSnapshotFinderByPreviousVersion.java [deleted file]
sonar-batch/src/main/java/org/sonar/batch/components/PastSnapshotFinderByVersion.java [deleted file]
sonar-batch/src/main/java/org/sonar/batch/components/Period.java [deleted file]
sonar-batch/src/main/java/org/sonar/batch/components/PeriodsDefinition.java [deleted file]
sonar-batch/src/main/java/org/sonar/batch/components/TimeMachineConfiguration.java
sonar-batch/src/main/java/org/sonar/batch/debt/NewDebtDecorator.java
sonar-batch/src/main/java/org/sonar/batch/deprecated/DeprecatedSensorContext.java [new file with mode: 0644]
sonar-batch/src/main/java/org/sonar/batch/deprecated/ResourceFilters.java [new file with mode: 0644]
sonar-batch/src/main/java/org/sonar/batch/deprecated/components/DefaultProjectClasspath.java [new file with mode: 0644]
sonar-batch/src/main/java/org/sonar/batch/deprecated/components/DefaultResourceCreationLock.java [new file with mode: 0644]
sonar-batch/src/main/java/org/sonar/batch/deprecated/components/DefaultTimeMachine.java [new file with mode: 0644]
sonar-batch/src/main/java/org/sonar/batch/deprecated/components/PastSnapshotFinderByDate.java [new file with mode: 0644]
sonar-batch/src/main/java/org/sonar/batch/deprecated/components/PastSnapshotFinderByDays.java [new file with mode: 0644]
sonar-batch/src/main/java/org/sonar/batch/deprecated/components/PastSnapshotFinderByPreviousAnalysis.java [new file with mode: 0644]
sonar-batch/src/main/java/org/sonar/batch/deprecated/components/PastSnapshotFinderByPreviousVersion.java [new file with mode: 0644]
sonar-batch/src/main/java/org/sonar/batch/deprecated/components/PastSnapshotFinderByVersion.java [new file with mode: 0644]
sonar-batch/src/main/java/org/sonar/batch/deprecated/components/Period.java [new file with mode: 0644]
sonar-batch/src/main/java/org/sonar/batch/deprecated/components/PeriodsDefinition.java [new file with mode: 0644]
sonar-batch/src/main/java/org/sonar/batch/deprecated/components/package-info.java [new file with mode: 0644]
sonar-batch/src/main/java/org/sonar/batch/deprecated/decorator/DecoratorsSelector.java [new file with mode: 0644]
sonar-batch/src/main/java/org/sonar/batch/deprecated/decorator/DefaultDecoratorContext.java [new file with mode: 0644]
sonar-batch/src/main/java/org/sonar/batch/deprecated/decorator/FormulaDecorator.java [new file with mode: 0644]
sonar-batch/src/main/java/org/sonar/batch/deprecated/package-info.java [new file with mode: 0644]
sonar-batch/src/main/java/org/sonar/batch/deprecated/tasks/ListTask.java [new file with mode: 0644]
sonar-batch/src/main/java/org/sonar/batch/deprecated/tasks/Tasks.java [new file with mode: 0644]
sonar-batch/src/main/java/org/sonar/batch/deprecated/tasks/package-info.java [new file with mode: 0644]
sonar-batch/src/main/java/org/sonar/batch/index/DefaultIndex.java
sonar-batch/src/main/java/org/sonar/batch/index/ResourceKeyMigration.java
sonar-batch/src/main/java/org/sonar/batch/index/SourceDataFactory.java
sonar-batch/src/main/java/org/sonar/batch/index/SourcePersister.java
sonar-batch/src/main/java/org/sonar/batch/issue/tracking/FileHashes.java
sonar-batch/src/main/java/org/sonar/batch/issue/tracking/IssueHandlers.java
sonar-batch/src/main/java/org/sonar/batch/issue/tracking/IssueTrackingDecorator.java
sonar-batch/src/main/java/org/sonar/batch/issue/tracking/LocalIssueTracking.java
sonar-batch/src/main/java/org/sonar/batch/issue/tracking/SourceHashHolder.java
sonar-batch/src/main/java/org/sonar/batch/languages/DefaultLanguagesReferential.java [deleted file]
sonar-batch/src/main/java/org/sonar/batch/languages/Language.java [deleted file]
sonar-batch/src/main/java/org/sonar/batch/languages/LanguagesReferential.java [deleted file]
sonar-batch/src/main/java/org/sonar/batch/languages/package-info.java [deleted file]
sonar-batch/src/main/java/org/sonar/batch/mediumtest/TaskResult.java
sonar-batch/src/main/java/org/sonar/batch/phases/DecoratorsExecutor.java
sonar-batch/src/main/java/org/sonar/batch/phases/Phases.java
sonar-batch/src/main/java/org/sonar/batch/phases/SensorMatcher.java
sonar-batch/src/main/java/org/sonar/batch/repository/language/DefaultLanguagesRepository.java [new file with mode: 0644]
sonar-batch/src/main/java/org/sonar/batch/repository/language/Language.java [new file with mode: 0644]
sonar-batch/src/main/java/org/sonar/batch/repository/language/LanguagesRepository.java [new file with mode: 0644]
sonar-batch/src/main/java/org/sonar/batch/repository/language/package-info.java [new file with mode: 0644]
sonar-batch/src/main/java/org/sonar/batch/repository/user/User.java [new file with mode: 0644]
sonar-batch/src/main/java/org/sonar/batch/repository/user/UserRepository.java [new file with mode: 0644]
sonar-batch/src/main/java/org/sonar/batch/repository/user/package-info.java [new file with mode: 0644]
sonar-batch/src/main/java/org/sonar/batch/rule/QProfileSensor.java
sonar-batch/src/main/java/org/sonar/batch/scan/LanguageVerifier.java
sonar-batch/src/main/java/org/sonar/batch/scan/ModuleScanContainer.java
sonar-batch/src/main/java/org/sonar/batch/scan/ProjectScanContainer.java
sonar-batch/src/main/java/org/sonar/batch/scan/filesystem/AdditionalFilePredicates.java
sonar-batch/src/main/java/org/sonar/batch/scan/filesystem/ComponentIndexer.java
sonar-batch/src/main/java/org/sonar/batch/scan/filesystem/DefaultInputFileValueCoder.java [deleted file]
sonar-batch/src/main/java/org/sonar/batch/scan/filesystem/DefaultModuleFileSystem.java
sonar-batch/src/main/java/org/sonar/batch/scan/filesystem/DeprecatedFileFilters.java
sonar-batch/src/main/java/org/sonar/batch/scan/filesystem/FileIndexer.java
sonar-batch/src/main/java/org/sonar/batch/scan/filesystem/FileMetadata.java
sonar-batch/src/main/java/org/sonar/batch/scan/filesystem/InputFileBuilder.java
sonar-batch/src/main/java/org/sonar/batch/scan/filesystem/InputFileBuilderFactory.java
sonar-batch/src/main/java/org/sonar/batch/scan/filesystem/InputFileMetadata.java [new file with mode: 0644]
sonar-batch/src/main/java/org/sonar/batch/scan/filesystem/InputPathCache.java
sonar-batch/src/main/java/org/sonar/batch/scan/filesystem/LanguageDetection.java
sonar-batch/src/main/java/org/sonar/batch/scan/filesystem/LanguageDetectionFactory.java
sonar-batch/src/main/java/org/sonar/batch/scan/filesystem/ModuleInputFileCache.java
sonar-batch/src/main/java/org/sonar/batch/scan/report/JSONReport.java
sonar-batch/src/main/java/org/sonar/batch/scm/ScmSensor.java
sonar-batch/src/main/java/org/sonar/batch/source/CodeColorizers.java
sonar-batch/src/main/java/org/sonar/batch/source/LinesSensor.java
sonar-batch/src/main/java/org/sonar/batch/tasks/ListTask.java [deleted file]
sonar-batch/src/main/java/org/sonar/batch/tasks/Tasks.java [deleted file]
sonar-batch/src/main/java/org/sonar/batch/tasks/package-info.java [deleted file]
sonar-batch/src/main/java/org/sonar/batch/user/User.java [deleted file]
sonar-batch/src/main/java/org/sonar/batch/user/UserRepository.java [deleted file]
sonar-batch/src/main/java/org/sonar/batch/user/package-info.java [deleted file]
sonar-batch/src/test/java/org/sonar/batch/DecoratorsSelectorTest.java [deleted file]
sonar-batch/src/test/java/org/sonar/batch/DefaultFileLinesContextTest.java
sonar-batch/src/test/java/org/sonar/batch/FormulaDecoratorTest.java [deleted file]
sonar-batch/src/test/java/org/sonar/batch/ResourceFiltersTest.java [deleted file]
sonar-batch/src/test/java/org/sonar/batch/components/PastMeasuresLoaderTest.java
sonar-batch/src/test/java/org/sonar/batch/components/PastSnapshotFinderByDateTest.java [deleted file]
sonar-batch/src/test/java/org/sonar/batch/components/PastSnapshotFinderByDaysTest.java [deleted file]
sonar-batch/src/test/java/org/sonar/batch/components/PastSnapshotFinderByPreviousAnalysisTest.java [deleted file]
sonar-batch/src/test/java/org/sonar/batch/components/PastSnapshotFinderByPreviousVersionTest.java [deleted file]
sonar-batch/src/test/java/org/sonar/batch/components/PastSnapshotFinderByVersionTest.java [deleted file]
sonar-batch/src/test/java/org/sonar/batch/components/PastSnapshotFinderTest.java
sonar-batch/src/test/java/org/sonar/batch/components/PastSnapshotTest.java
sonar-batch/src/test/java/org/sonar/batch/components/PeriodsDefinitionTest.java [deleted file]
sonar-batch/src/test/java/org/sonar/batch/components/TimeMachineConfigurationTest.java
sonar-batch/src/test/java/org/sonar/batch/debt/DebtDecoratorTest.java
sonar-batch/src/test/java/org/sonar/batch/debt/NewDebtDecoratorTest.java
sonar-batch/src/test/java/org/sonar/batch/debt/SqaleRatingDecoratorTest.java
sonar-batch/src/test/java/org/sonar/batch/deprecated/ResourceFiltersTest.java [new file with mode: 0644]
sonar-batch/src/test/java/org/sonar/batch/deprecated/components/PastSnapshotFinderByDateTest.java [new file with mode: 0644]
sonar-batch/src/test/java/org/sonar/batch/deprecated/components/PastSnapshotFinderByDaysTest.java [new file with mode: 0644]
sonar-batch/src/test/java/org/sonar/batch/deprecated/components/PastSnapshotFinderByPreviousAnalysisTest.java [new file with mode: 0644]
sonar-batch/src/test/java/org/sonar/batch/deprecated/components/PastSnapshotFinderByPreviousVersionTest.java [new file with mode: 0644]
sonar-batch/src/test/java/org/sonar/batch/deprecated/components/PastSnapshotFinderByVersionTest.java [new file with mode: 0644]
sonar-batch/src/test/java/org/sonar/batch/deprecated/components/PeriodsDefinitionTest.java [new file with mode: 0644]
sonar-batch/src/test/java/org/sonar/batch/deprecated/decorator/DecoratorsSelectorTest.java [new file with mode: 0644]
sonar-batch/src/test/java/org/sonar/batch/deprecated/decorator/FormulaDecoratorTest.java [new file with mode: 0644]
sonar-batch/src/test/java/org/sonar/batch/deprecated/tasks/ListTaskTest.java [new file with mode: 0644]
sonar-batch/src/test/java/org/sonar/batch/deprecated/tasks/TasksTest.java [new file with mode: 0644]
sonar-batch/src/test/java/org/sonar/batch/design/DirectoryDsmDecoratorTest.java
sonar-batch/src/test/java/org/sonar/batch/design/DsmSerializerTest.java
sonar-batch/src/test/java/org/sonar/batch/design/SubProjectDsmDecoratorTest.java
sonar-batch/src/test/java/org/sonar/batch/index/BucketTest.java
sonar-batch/src/test/java/org/sonar/batch/index/DefaultIndexTest.java
sonar-batch/src/test/java/org/sonar/batch/index/DuplicationPersisterTest.java
sonar-batch/src/test/java/org/sonar/batch/index/MeasurePersisterTest.java
sonar-batch/src/test/java/org/sonar/batch/index/ResourceCacheTest.java
sonar-batch/src/test/java/org/sonar/batch/index/ResourceKeyMigrationTest.java
sonar-batch/src/test/java/org/sonar/batch/index/ResourcePersisterTest.java
sonar-batch/src/test/java/org/sonar/batch/index/SourceDataFactoryTest.java
sonar-batch/src/test/java/org/sonar/batch/issue/IssuableFactoryTest.java
sonar-batch/src/test/java/org/sonar/batch/issue/ModuleIssuesTest.java
sonar-batch/src/test/java/org/sonar/batch/issue/ignore/scanner/IssueExclusionsLoaderTest.java
sonar-batch/src/test/java/org/sonar/batch/issue/tracking/IssueTrackingDecoratorTest.java
sonar-batch/src/test/java/org/sonar/batch/issue/tracking/IssueTrackingTest.java
sonar-batch/src/test/java/org/sonar/batch/issue/tracking/SourceHashHolderTest.java
sonar-batch/src/test/java/org/sonar/batch/phases/DecoratorsExecutorTest.java
sonar-batch/src/test/java/org/sonar/batch/qualitygate/GenerateQualityGateEventsTest.java
sonar-batch/src/test/java/org/sonar/batch/report/ComponentsPublisherTest.java
sonar-batch/src/test/java/org/sonar/batch/repository/user/UserRepositoryTest.java [new file with mode: 0644]
sonar-batch/src/test/java/org/sonar/batch/rule/QProfileSensorTest.java
sonar-batch/src/test/java/org/sonar/batch/rule/QProfileVerifierTest.java
sonar-batch/src/test/java/org/sonar/batch/scan/LanguageVerifierTest.java
sonar-batch/src/test/java/org/sonar/batch/scan/filesystem/AdditionalFilePredicatesTest.java
sonar-batch/src/test/java/org/sonar/batch/scan/filesystem/ComponentIndexerTest.java
sonar-batch/src/test/java/org/sonar/batch/scan/filesystem/DefaultModuleFileSystemTest.java
sonar-batch/src/test/java/org/sonar/batch/scan/filesystem/DeprecatedFileFiltersTest.java
sonar-batch/src/test/java/org/sonar/batch/scan/filesystem/ExclusionFiltersTest.java
sonar-batch/src/test/java/org/sonar/batch/scan/filesystem/FileMetadataTest.java
sonar-batch/src/test/java/org/sonar/batch/scan/filesystem/InputFileBuilderFactoryTest.java
sonar-batch/src/test/java/org/sonar/batch/scan/filesystem/InputFileBuilderTest.java
sonar-batch/src/test/java/org/sonar/batch/scan/filesystem/InputPathCacheTest.java
sonar-batch/src/test/java/org/sonar/batch/scan/filesystem/LanguageDetectionFactoryTest.java
sonar-batch/src/test/java/org/sonar/batch/scan/filesystem/LanguageDetectionTest.java
sonar-batch/src/test/java/org/sonar/batch/scan/measure/MeasureCacheTest.java
sonar-batch/src/test/java/org/sonar/batch/scan/report/JSONReportTest.java
sonar-batch/src/test/java/org/sonar/batch/sensor/AnalyzerOptimizerTest.java
sonar-batch/src/test/java/org/sonar/batch/sensor/DefaultSensorContextTest.java
sonar-batch/src/test/java/org/sonar/batch/sensor/DefaultSensorStorageTest.java
sonar-batch/src/test/java/org/sonar/batch/sensor/coverage/CoverageExclusionsTest.java
sonar-batch/src/test/java/org/sonar/batch/source/CodeColorizersTest.java
sonar-batch/src/test/java/org/sonar/batch/source/HighlightableBuilderTest.java
sonar-batch/src/test/java/org/sonar/batch/tasks/ListTaskTest.java [deleted file]
sonar-batch/src/test/java/org/sonar/batch/tasks/TasksTest.java [deleted file]
sonar-batch/src/test/java/org/sonar/batch/user/UserRepositoryTest.java [deleted file]
sonar-batch/src/test/resources/org/sonar/batch/components/PastSnapshotFinderByDateTest/shared.xml [deleted file]
sonar-batch/src/test/resources/org/sonar/batch/components/PastSnapshotFinderByDaysTest/shared.xml [deleted file]
sonar-batch/src/test/resources/org/sonar/batch/components/PastSnapshotFinderByDaysTest/shouldNotFindSelf.xml [deleted file]
sonar-batch/src/test/resources/org/sonar/batch/components/PastSnapshotFinderByPreviousAnalysisTest/shouldFindPreviousAnalysis.xml [deleted file]
sonar-batch/src/test/resources/org/sonar/batch/components/PastSnapshotFinderByPreviousAnalysisTest/shouldNotFindPreviousAnalysis.xml [deleted file]
sonar-batch/src/test/resources/org/sonar/batch/components/PastSnapshotFinderByPreviousVersionTest/no-previous-version.xml [deleted file]
sonar-batch/src/test/resources/org/sonar/batch/components/PastSnapshotFinderByPreviousVersionTest/with-previous-version-deleted.xml [deleted file]
sonar-batch/src/test/resources/org/sonar/batch/components/PastSnapshotFinderByPreviousVersionTest/with-previous-version.xml [deleted file]
sonar-batch/src/test/resources/org/sonar/batch/components/PastSnapshotFinderByVersionTest/shared.xml [deleted file]
sonar-batch/src/test/resources/org/sonar/batch/components/PeriodsDefinitionTest/shared.xml [deleted file]
sonar-batch/src/test/resources/org/sonar/batch/deprecated/components/PastSnapshotFinderByDateTest/shared.xml [new file with mode: 0644]
sonar-batch/src/test/resources/org/sonar/batch/deprecated/components/PastSnapshotFinderByDaysTest/shared.xml [new file with mode: 0644]
sonar-batch/src/test/resources/org/sonar/batch/deprecated/components/PastSnapshotFinderByDaysTest/shouldNotFindSelf.xml [new file with mode: 0644]
sonar-batch/src/test/resources/org/sonar/batch/deprecated/components/PastSnapshotFinderByPreviousAnalysisTest/shouldFindPreviousAnalysis.xml [new file with mode: 0644]
sonar-batch/src/test/resources/org/sonar/batch/deprecated/components/PastSnapshotFinderByPreviousAnalysisTest/shouldNotFindPreviousAnalysis.xml [new file with mode: 0644]
sonar-batch/src/test/resources/org/sonar/batch/deprecated/components/PastSnapshotFinderByPreviousVersionTest/no-previous-version.xml [new file with mode: 0644]
sonar-batch/src/test/resources/org/sonar/batch/deprecated/components/PastSnapshotFinderByPreviousVersionTest/with-previous-version-deleted.xml [new file with mode: 0644]
sonar-batch/src/test/resources/org/sonar/batch/deprecated/components/PastSnapshotFinderByPreviousVersionTest/with-previous-version.xml [new file with mode: 0644]
sonar-batch/src/test/resources/org/sonar/batch/deprecated/components/PastSnapshotFinderByVersionTest/shared.xml [new file with mode: 0644]
sonar-batch/src/test/resources/org/sonar/batch/deprecated/components/PeriodsDefinitionTest/shared.xml [new file with mode: 0644]
sonar-batch/src/test/resources/org/sonar/batch/index/ResourcePersisterTest/shouldSaveNewMultiModulesProject-result.xml
sonar-batch/src/test/resources/org/sonar/batch/index/ResourcePersisterTest/shouldSaveNewMultiModulesProjectAndLibrary-result.xml
sonar-core/src/main/java/org/sonar/batch/index/ResourceCopy.java
sonar-core/src/test/java/org/sonar/core/component/ComponentKeysTest.java
sonar-core/src/test/java/org/sonar/core/component/ResourceComponentTest.java
sonar-deprecated/src/main/java/org/sonar/api/batch/AbstractSourceImporter.java
sonar-deprecated/src/test/java/org/sonar/api/checks/NoSonarFilterTest.java
sonar-plugin-api/src/main/java/org/sonar/api/CoreProperties.java
sonar-plugin-api/src/main/java/org/sonar/api/batch/TimeMachine.java
sonar-plugin-api/src/main/java/org/sonar/api/batch/fs/InputDir.java
sonar-plugin-api/src/main/java/org/sonar/api/batch/fs/InputFile.java
sonar-plugin-api/src/main/java/org/sonar/api/batch/fs/InputPath.java
sonar-plugin-api/src/main/java/org/sonar/api/batch/fs/internal/AbsolutePathPredicate.java
sonar-plugin-api/src/main/java/org/sonar/api/batch/fs/internal/DefaultFilePredicates.java
sonar-plugin-api/src/main/java/org/sonar/api/batch/fs/internal/DefaultFileSystem.java
sonar-plugin-api/src/main/java/org/sonar/api/batch/fs/internal/DefaultInputDir.java
sonar-plugin-api/src/main/java/org/sonar/api/batch/fs/internal/DefaultInputFile.java
sonar-plugin-api/src/main/java/org/sonar/api/batch/fs/internal/DeprecatedDefaultInputFile.java
sonar-plugin-api/src/main/java/org/sonar/api/resources/Directory.java
sonar-plugin-api/src/main/java/org/sonar/api/resources/File.java
sonar-plugin-api/src/main/java/org/sonar/api/resources/Library.java
sonar-plugin-api/src/main/java/org/sonar/api/resources/Project.java
sonar-plugin-api/src/main/java/org/sonar/api/resources/ProjectFileSystem.java
sonar-plugin-api/src/main/java/org/sonar/api/resources/Resource.java
sonar-plugin-api/src/main/java/org/sonar/api/scan/filesystem/FileSystemFilter.java
sonar-plugin-api/src/main/java/org/sonar/api/task/Task.java
sonar-plugin-api/src/main/java/org/sonar/api/task/TaskComponent.java
sonar-plugin-api/src/main/java/org/sonar/api/task/TaskDefinition.java
sonar-plugin-api/src/main/java/org/sonar/api/task/TaskExtension.java
sonar-plugin-api/src/test/java/org/sonar/api/batch/fs/internal/DefaultFilePredicatesTest.java
sonar-plugin-api/src/test/java/org/sonar/api/batch/fs/internal/DefaultFileSystemTest.java
sonar-plugin-api/src/test/java/org/sonar/api/batch/fs/internal/DefaultInputDirTest.java
sonar-plugin-api/src/test/java/org/sonar/api/batch/fs/internal/DefaultInputFileTest.java
sonar-plugin-api/src/test/java/org/sonar/api/batch/fs/internal/DeprecatedDefaultInputFileTest.java
sonar-plugin-api/src/test/java/org/sonar/api/batch/fs/internal/PathPatternTest.java
sonar-plugin-api/src/test/java/org/sonar/api/batch/sensor/test/internal/DefaultTestCaseCoverageTest.java
sonar-plugin-api/src/test/java/org/sonar/api/batch/sensor/test/internal/DefaultTestCaseExecutionTest.java
sonar-plugin-api/src/test/java/org/sonar/api/measures/AverageFormulaTest.java
sonar-plugin-api/src/test/java/org/sonar/api/measures/SumChildDistributionFormulaTest.java
sonar-plugin-api/src/test/java/org/sonar/api/resources/DirectoryTest.java
sonar-plugin-api/src/test/java/org/sonar/api/resources/FileTest.java
sonar-plugin-api/src/test/java/org/sonar/api/resources/ResourceUtilsTest.java
sonar-plugin-api/src/test/java/org/sonar/api/resources/ScopesTest.java
sonar-plugin-api/src/test/java/org/sonar/api/scan/filesystem/PathResolverTest.java
sonar-plugin-api/src/test/java/org/sonar/api/test/IsResource.java
sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample-with-symlink/.gitignore [new file with mode: 0644]
sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample-with-symlink/sonar-project.properties [new file with mode: 0644]
sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample-with-symlink/testx [new symlink]
sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample-with-symlink/xources [new symlink]
sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample/sonar-project.properties [new file with mode: 0644]
sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample/testx/ClassOneTest.xoo [new file with mode: 0644]
sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample/testx/ClassOneTest.xoo.measures [new file with mode: 0644]
sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample/testx/ClassOneTest.xoo.scm [new file with mode: 0644]
sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample/xources/hello/HelloJava.xoo [new file with mode: 0644]
sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample/xources/hello/HelloJava.xoo.measures [new file with mode: 0644]
sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample/xources/hello/HelloJava.xoo.scm [new file with mode: 0644]
sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample/xources/hello/helloscala.xoo [new file with mode: 0644]
sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample/xources/hello/helloscala.xoo.measures [new file with mode: 0644]

index d775ba8ec4c1a5a8937d45216c79c92d85e07f62..61a6b69cc74b12325ab040487b193544b93b6aa1 100644 (file)
@@ -19,6 +19,9 @@
  */
 package org.sonar.plugins.core.issue;
 
+import org.sonar.batch.components.TimeMachineConfiguration;
+
+import org.sonar.batch.deprecated.components.Period;
 import com.google.common.annotations.VisibleForTesting;
 import com.google.common.collect.*;
 import org.apache.commons.lang.time.DateUtils;
@@ -32,8 +35,6 @@ import org.sonar.api.resources.Resource;
 import org.sonar.api.resources.ResourceUtils;
 import org.sonar.api.rule.RuleKey;
 import org.sonar.api.rules.RulePriority;
-import org.sonar.batch.components.Period;
-import org.sonar.batch.components.TimeMachineConfiguration;
 
 import javax.annotation.Nullable;
 
index 90435de8f3b515aa3a292d1588d1586294b61c13..c275645899ef9e006de4d2db242b3b7c1753a3db 100644 (file)
  */
 package org.sonar.plugins.core.timemachine;
 
-import org.sonar.api.batch.RequiresDB;
+import org.sonar.batch.components.TimeMachineConfiguration;
 
+import org.sonar.batch.deprecated.components.Period;
+import org.sonar.api.batch.RequiresDB;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
 import org.apache.commons.lang.ObjectUtils;
@@ -33,8 +35,6 @@ import org.sonar.api.resources.Qualifiers;
 import org.sonar.api.resources.Resource;
 import org.sonar.api.resources.Scopes;
 import org.sonar.api.utils.KeyValueFormat;
-import org.sonar.batch.components.Period;
-import org.sonar.batch.components.TimeMachineConfiguration;
 
 import javax.annotation.Nullable;
 
index ee415fdda3317ef36ee3a10abe7601ceabd9ca4b..352070ccc686b9beee689d6f61b2432a19fd7554 100644 (file)
  */
 package org.sonar.plugins.core.timemachine;
 
+import org.sonar.batch.components.TimeMachineConfiguration;
+
 import org.sonar.api.measures.CoreMetrics;
 import org.sonar.api.measures.Metric;
-import org.sonar.batch.components.TimeMachineConfiguration;
 
 import java.util.List;
 
index 61351c1a8e4705c6f96f26003b4fa3ef792aa394..2dbcf8416a440decd43669169e07f1a01c1cb793 100644 (file)
  */
 package org.sonar.plugins.core.timemachine;
 
+import org.sonar.batch.components.TimeMachineConfiguration;
+
 import org.sonar.api.measures.CoreMetrics;
 import org.sonar.api.measures.Metric;
-import org.sonar.batch.components.TimeMachineConfiguration;
 
 public class NewItCoverageFileAnalyzer extends AbstractNewCoverageFileAnalyzer {
 
index 6ff8481786e3ab2c1c83d58b4c095fcd90d5a2a3..b57db6dbe0ead58e72b23e0392c6d0d395ae74f1 100644 (file)
  */
 package org.sonar.plugins.core.timemachine;
 
+import org.sonar.batch.components.TimeMachineConfiguration;
+
 import org.sonar.api.measures.CoreMetrics;
 import org.sonar.api.measures.Metric;
-import org.sonar.batch.components.TimeMachineConfiguration;
 
 public class NewOverallCoverageFileAnalyzer extends AbstractNewCoverageFileAnalyzer {
 
index 44684523efddaf01f99cbe4155ec6f7b97895a89..aa98cf6c603c459d70725e1dfa5c524718a74cda 100644 (file)
@@ -19,8 +19,9 @@
  */
 package org.sonar.plugins.core.timemachine;
 
-import org.sonar.api.batch.RequiresDB;
+import org.sonar.batch.deprecated.components.PeriodsDefinition;
 
+import org.sonar.api.batch.RequiresDB;
 import com.google.common.collect.ArrayListMultimap;
 import com.google.common.collect.ListMultimap;
 import com.google.common.collect.Lists;
@@ -39,7 +40,6 @@ import org.sonar.api.measures.MetricFinder;
 import org.sonar.api.resources.Project;
 import org.sonar.api.resources.Resource;
 import org.sonar.api.resources.Scopes;
-import org.sonar.batch.components.PeriodsDefinition;
 
 import java.util.List;
 
index 84125404fb0dbc863e582f319db7a765ca770240..38083fed3dbead418a9d31d74a687242c6356064 100644 (file)
@@ -19,6 +19,9 @@
  */
 package org.sonar.plugins.core.timemachine;
 
+import org.sonar.batch.components.TimeMachineConfiguration;
+
+import org.sonar.batch.components.PastSnapshot;
 import org.sonar.api.batch.Decorator;
 import org.sonar.api.batch.DecoratorBarriers;
 import org.sonar.api.batch.DecoratorContext;
@@ -28,8 +31,6 @@ import org.sonar.api.database.model.Snapshot;
 import org.sonar.api.resources.Project;
 import org.sonar.api.resources.Resource;
 import org.sonar.api.resources.ResourceUtils;
-import org.sonar.batch.components.PastSnapshot;
-import org.sonar.batch.components.TimeMachineConfiguration;
 import org.sonar.batch.index.ResourceCache;
 
 import java.util.List;
index dc6cab324c7b54b1fde93a449da3859055aefc11..a997423aa37721865086af5a2bab630f2031b2fb 100644 (file)
  */
 package org.sonar.plugins.core.timemachine;
 
+import org.sonar.batch.components.TimeMachineConfiguration;
+
+import org.sonar.batch.components.PastSnapshot;
+import org.sonar.batch.components.PastMeasuresLoader;
 import com.google.common.collect.Maps;
 import org.apache.commons.lang.StringUtils;
 import org.sonar.api.batch.Decorator;
@@ -38,9 +42,6 @@ import org.sonar.api.resources.Scopes;
 import org.sonar.api.rules.Rule;
 import org.sonar.api.rules.RuleFinder;
 import org.sonar.api.technicaldebt.batch.Characteristic;
-import org.sonar.batch.components.PastMeasuresLoader;
-import org.sonar.batch.components.PastSnapshot;
-import org.sonar.batch.components.TimeMachineConfiguration;
 
 import javax.annotation.Nullable;
 
index cb8007f0b81b46f3ac47c8070f68faf5a7a80e4a..28327ac59541bf12132349162e19213a6855e329 100644 (file)
@@ -34,7 +34,10 @@ import org.sonar.java.api.JavaClass;
 import java.util.Arrays;
 
 import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.Mockito.*;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.mockito.Mockito.when;
 
 public class CountFalsePositivesDecoratorTest {
 
@@ -48,7 +51,7 @@ public class CountFalsePositivesDecoratorTest {
     DefaultIssue fixed = new DefaultIssue().setRuleKey(RuleKey.parse("squid:AvoidCycles"))
       .setResolution(Issue.RESOLUTION_FIXED).setStatus(Issue.STATUS_RESOLVED);
 
-    File file = new File("foo.c");
+    File file = File.create("foo.c");
     Issuable issuable = mock(Issuable.class);
     when(perspectives.as(Issuable.class, file)).thenReturn(issuable);
     when(issuable.resolvedIssues()).thenReturn(Arrays.<Issue>asList(falsePositive, fixed));
index be9b8ae586c1625c6b0848c48fa3493bb36413df..912779a5356070751fc746085c79e5b7c6f9f455 100644 (file)
@@ -20,6 +20,9 @@
 
 package org.sonar.plugins.core.issue;
 
+import org.sonar.batch.components.TimeMachineConfiguration;
+
+import org.sonar.batch.deprecated.components.Period;
 import com.google.common.collect.Lists;
 import org.apache.commons.lang.ObjectUtils;
 import org.apache.commons.lang.time.DateUtils;
@@ -40,8 +43,6 @@ import org.sonar.api.rule.Severity;
 import org.sonar.api.rules.Rule;
 import org.sonar.api.rules.RulePriority;
 import org.sonar.api.test.IsRuleMeasure;
-import org.sonar.batch.components.Period;
-import org.sonar.batch.components.TimeMachineConfiguration;
 
 import java.util.Calendar;
 import java.util.Collections;
index adb52dfece02bb132ee04006079406289f838f99..01524877fb119c2d8e57e5307598381c04edc96f 100644 (file)
@@ -43,7 +43,7 @@ public class DirectoriesDecoratorTest {
   @Test
   public void doNotInsertZeroOnFiles() {
     DirectoriesDecorator decorator = new DirectoriesDecorator();
-    Resource file = new File("foo.php");
+    Resource file = File.create("foo.php");
     DecoratorContext context = mock(DecoratorContext.class);
 
     decorator.decorate(file, context);
@@ -54,7 +54,7 @@ public class DirectoriesDecoratorTest {
   @Test
   public void directoryCountsForOne() {
     DirectoriesDecorator decorator = new DirectoriesDecorator();
-    Resource directory = new Directory("org/foo");
+    Resource directory = Directory.create("org/foo");
     DecoratorContext context = mock(DecoratorContext.class);
     decorator.decorate(directory, context);
     verify(context).saveMeasure(CoreMetrics.DIRECTORIES, 1.0);
index 2731680adc94f36c4be2ccef2f4d87a853b59314..02793e1160c4e69ac6b5472185a86c91ee1dafab 100644 (file)
@@ -39,7 +39,7 @@ public class ManualMeasureDecoratorTest extends AbstractDbUnitTestCase {
   public void testCopyManualMeasures() throws Exception {
     setupData("testCopyManualMeasures");
 
-    File javaFile = new File("Foo.java");
+    File javaFile = File.create("Foo.java");
     javaFile.setId(40);
 
     ManualMeasureDecorator decorator = new ManualMeasureDecorator(getSession(), new DefaultMetricFinder(getSessionFactory()));
index ce7cc6cf5ddbbd98f5cbccb274b44232d2d73b41..839e6f5186247be027e2827e6f00e8c983fab1be 100644 (file)
@@ -36,8 +36,8 @@ import java.text.SimpleDateFormat;
 import java.util.Arrays;
 import java.util.Date;
 
-import static org.hamcrest.Matchers.is;
 import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.is;
 import static org.mockito.Matchers.anyList;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.never;
@@ -75,14 +75,14 @@ public class TendencyDecoratorTest {
       new Object[] {date("2009-12-02"), CoreMetrics.LINES, 1300.0},
       new Object[] {date("2009-12-02"), CoreMetrics.COVERAGE, 79.6},
       new Object[] {date("2009-12-15"), CoreMetrics.LINES, 1150.0}
-    ));
+      ));
 
     DecoratorContext context = mock(DecoratorContext.class);
     when(context.getMeasure(CoreMetrics.LINES)).thenReturn(new Measure(CoreMetrics.LINES, 1400.0));
     when(context.getMeasure(CoreMetrics.COVERAGE)).thenReturn(new Measure(CoreMetrics.LINES, 90.0));
 
     TendencyDecorator decorator = new TendencyDecorator(timeMachine, query, analyser);
-    decorator.decorate(new Directory("org/foo"), context);
+    decorator.decorate(Directory.create("org/foo"), context);
 
     verify(analyser).analyseLevel(Arrays.asList(1200.0, 1300.0, 1150.0, 1400.0));
     verify(analyser).analyseLevel(Arrays.asList(80.5, 79.6, 90.0));
@@ -97,11 +97,11 @@ public class TendencyDecoratorTest {
     when(timeMachine.getMeasuresFields(query)).thenReturn(Arrays.<Object[]>asList(
       new Object[] {date("2009-12-01"), CoreMetrics.LINES, 1200.0},
       new Object[] {date("2009-12-02"), CoreMetrics.LINES, 1300.0}
-    ));
+      ));
 
     DecoratorContext context = mock(DecoratorContext.class);
     TendencyDecorator decorator = new TendencyDecorator(timeMachine, query, analyser);
-    decorator.decorate(new Directory("org/foo"), context);
+    decorator.decorate(Directory.create("org/foo"), context);
 
     verify(analyser, never()).analyseLevel(anyList());
   }
index f422f6f60204416d70789cc668cbbb4779d77eb6..ae79e7a47d377f80da123549943f7e7c958f7835 100644 (file)
  */
 package org.sonar.plugins.core.timemachine;
 
+import org.sonar.batch.components.TimeMachineConfiguration;
+
+import org.sonar.batch.components.PastSnapshot;
 import org.junit.Test;
 import org.sonar.api.database.model.Snapshot;
 import org.sonar.api.resources.Project;
 import org.sonar.api.utils.DateUtils;
-import org.sonar.batch.components.PastSnapshot;
-import org.sonar.batch.components.TimeMachineConfiguration;
 import org.sonar.batch.index.ResourceCache;
 import org.sonar.jpa.test.AbstractDbUnitTestCase;
 
index 4f6569e08cd1fba0f0918ec51048779fedd42b57..223abadcbacb1fa3d5e407f8841b594e31ba8175 100644 (file)
  */
 package org.sonar.plugins.core.timemachine;
 
+import org.sonar.batch.components.TimeMachineConfiguration;
+
+import org.sonar.batch.components.PastSnapshot;
+import org.sonar.batch.components.PastMeasuresLoader;
 import org.junit.Test;
 import org.mockito.Matchers;
 import org.sonar.api.batch.DecoratorContext;
@@ -33,9 +37,6 @@ import org.sonar.api.resources.Project;
 import org.sonar.api.resources.Resource;
 import org.sonar.api.rules.Rule;
 import org.sonar.api.rules.RuleFinder;
-import org.sonar.batch.components.PastMeasuresLoader;
-import org.sonar.batch.components.PastSnapshot;
-import org.sonar.batch.components.TimeMachineConfiguration;
 import org.sonar.jpa.test.AbstractDbUnitTestCase;
 
 import java.util.Arrays;
@@ -64,12 +65,12 @@ public class VariationDecoratorTest extends AbstractDbUnitTestCase {
     VariationDecorator decorator = new VariationDecorator(mock(PastMeasuresLoader.class), mock(MetricFinder.class), timeMachineConfiguration, mock(RuleFinder.class));
 
     assertThat(decorator.shouldComputeVariation(new Project("foo"))).isTrue();
-    assertThat(decorator.shouldComputeVariation(new File("foo/bar.c"))).isFalse();
+    assertThat(decorator.shouldComputeVariation(File.create("foo/bar.c"))).isFalse();
   }
 
   @Test
   public void shouldCompareAndSaveVariation() {
-    Resource dir = new Directory("org/foo");
+    Resource dir = Directory.create("org/foo");
 
     PastMeasuresLoader pastMeasuresLoader = mock(PastMeasuresLoader.class);
     PastSnapshot pastSnapshot1 = new PastSnapshot("days", new Date()).setIndex(1);
@@ -117,7 +118,7 @@ public class VariationDecoratorTest extends AbstractDbUnitTestCase {
     when(ruleFinder.findByKey(rule1.ruleKey())).thenReturn(rule1);
     when(ruleFinder.findByKey(rule2.ruleKey())).thenReturn(rule2);
 
-    Resource dir = new Directory("org/foo");
+    Resource dir = Directory.create("org/foo");
 
     PastMeasuresLoader pastMeasuresLoader = mock(PastMeasuresLoader.class);
     PastSnapshot pastSnapshot1 = new PastSnapshot("days", new Date()).setIndex(1);
index 28a78f5cc503b0ef10d2dc88d652f9f5f50c3bb2..a4cfc381ae868c7c9ecd15115f7068674855730b 100644 (file)
@@ -52,7 +52,7 @@ public class CpdSensorTest {
     sonarBridgeEngine = new DefaultCpdEngine(indexFactory, new CpdMappings(), null, null, mock(BlockCache.class));
     settings = new Settings(new PropertyDefinitions(CpdPlugin.class));
 
-    DefaultFileSystem fs = new DefaultFileSystem(temp.newFolder());
+    DefaultFileSystem fs = new DefaultFileSystem(temp.newFolder().toPath());
     sensor = new CpdSensor(sonarEngine, sonarBridgeEngine, settings, fs);
   }
 
index aa87b90dc13ff64e63526ba7e6f7db0cdf530eeb..182f57091d0bd8d61b8b51def65e683450c08436 100644 (file)
@@ -72,7 +72,7 @@ public class JavaCpdEngineTest {
     inputFile = new DeprecatedDefaultInputFile("foo", "src/main/java/Foo.java");
     duplicationBuilder = spy(new DefaultDuplicationBuilder(inputFile));
     when(context.duplicationBuilder(any(InputFile.class))).thenReturn(duplicationBuilder);
-    inputFile.setFile(temp.newFile("Foo.java"));
+    inputFile.setModuleBaseDir(temp.newFolder().toPath());
   }
 
   @SuppressWarnings("unchecked")
index 0c733e9227a6ecc8adaa43c92db4bf77d6d8fa34..de90865b0d0ad511387a2d01f3486cc4d673ab3b 100644 (file)
@@ -27,8 +27,8 @@ import org.sonar.api.resources.File;
 import org.sonar.api.resources.Qualifiers;
 import org.sonar.api.test.IsMeasure;
 
-import static org.hamcrest.Matchers.is;
 import static org.hamcrest.Matchers.greaterThan;
+import static org.hamcrest.Matchers.is;
 import static org.junit.Assert.assertThat;
 import static org.mockito.Matchers.any;
 import static org.mockito.Matchers.argThat;
@@ -48,7 +48,7 @@ public class SumDuplicationsDecoratorTest {
   @Test
   public void doNotSetDuplicationsOnUnitTests() {
     SumDuplicationsDecorator decorator = new SumDuplicationsDecorator();
-    File unitTest = new File("org/foo/BarTest.java");
+    File unitTest = File.create("org/foo/BarTest.java");
     unitTest.setQualifier(Qualifiers.UNIT_TEST_FILE);
     DecoratorContext context = mock(DecoratorContext.class);
 
@@ -60,7 +60,7 @@ public class SumDuplicationsDecoratorTest {
   @Test
   public void saveZeroIfNoDuplications() {
     SumDuplicationsDecorator decorator = new SumDuplicationsDecorator();
-    File file = new File("org/foo/BarTest.java");
+    File file = File.create("org/foo/BarTest.java");
     DecoratorContext context = mock(DecoratorContext.class);
 
     decorator.decorate(file, context);
index 7cf94a15d021afa5cc69faec59ac72b85bd71eca..4b57e3973625a8d8cc41b94960ff414507cda0ed 100644 (file)
@@ -57,7 +57,7 @@ public class CoveragePerTestSensorTest {
   public void prepare() throws IOException {
     baseDir = temp.newFolder();
     sensor = new CoveragePerTestSensor();
-    fileSystem = new DefaultFileSystem(baseDir);
+    fileSystem = new DefaultFileSystem(baseDir.toPath());
     when(context.fileSystem()).thenReturn(fileSystem);
   }
 
@@ -68,7 +68,7 @@ public class CoveragePerTestSensorTest {
 
   @Test
   public void testNoExecutionIfCoveragePerTestFile() {
-    DefaultInputFile testFile = new DefaultInputFile("foo", "test/fooTest.xoo").setAbsolutePath(new File(baseDir, "test/fooTest.xoo").getAbsolutePath()).setLanguage("xoo")
+    DefaultInputFile testFile = new DefaultInputFile("foo", "test/fooTest.xoo").setLanguage("xoo")
       .setType(Type.TEST);
     fileSystem.add(testFile);
     sensor.execute(context);
@@ -78,8 +78,8 @@ public class CoveragePerTestSensorTest {
   public void testExecution() throws IOException {
     File coverPerTest = new File(baseDir, "test/fooTest.xoo.coveragePerTest");
     FileUtils.write(coverPerTest, "test1:src/foo.xoo:1,2,3,4\ntest2:src/foo.xoo:5,6,7\n\n#comment");
-    DefaultInputFile inputFile = new DefaultInputFile("foo", "src/foo.xoo").setAbsolutePath(new File(baseDir, "src/foo.xoo").getAbsolutePath()).setLanguage("xoo");
-    DefaultInputFile testFile = new DefaultInputFile("foo", "test/fooTest.xoo").setAbsolutePath(new File(baseDir, "test/fooTest.xoo").getAbsolutePath()).setLanguage("xoo")
+    DefaultInputFile inputFile = new DefaultInputFile("foo", "src/foo.xoo").setLanguage("xoo");
+    DefaultInputFile testFile = new DefaultInputFile("foo", "test/fooTest.xoo").setLanguage("xoo")
       .setType(Type.TEST);
     fileSystem.add(inputFile);
     fileSystem.add(testFile);
index 46f6e56c69da12f4db311dab7efab9df00b47484..e586263feda0f15e334ddc5675edaad223ff3ef4 100644 (file)
@@ -56,7 +56,7 @@ public class DependencySensorTest {
   public void prepare() throws IOException {
     baseDir = temp.newFolder();
     sensor = new DependencySensor();
-    fileSystem = new DefaultFileSystem(baseDir);
+    fileSystem = new DefaultFileSystem(baseDir.toPath());
     when(context.fileSystem()).thenReturn(fileSystem);
   }
 
@@ -67,7 +67,7 @@ public class DependencySensorTest {
 
   @Test
   public void testNoExecutionIfNoDepsFile() {
-    DefaultInputFile file = new DefaultInputFile("foo", "src/foo.xoo").setAbsolutePath(new File(baseDir, "src/foo.xoo").getAbsolutePath()).setLanguage("xoo")
+    DefaultInputFile file = new DefaultInputFile("foo", "src/foo.xoo").setLanguage("xoo")
       .setType(Type.MAIN);
     fileSystem.add(file);
     sensor.execute(context);
@@ -77,9 +77,9 @@ public class DependencySensorTest {
   public void testExecution() throws IOException {
     File deps = new File(baseDir, "src/foo.xoo.deps");
     FileUtils.write(deps, "src/foo2.xoo:2\nsrc2/foo3.xoo:6\n\n#comment");
-    DefaultInputFile inputFile1 = new DefaultInputFile("foo", "src/foo.xoo").setAbsolutePath(new File(baseDir, "src/foo.xoo").getAbsolutePath()).setLanguage("xoo");
-    DefaultInputFile inputFile2 = new DefaultInputFile("foo", "src/foo2.xoo").setAbsolutePath(new File(baseDir, "src/foo2.xoo").getAbsolutePath()).setLanguage("xoo");
-    DefaultInputFile inputFile3 = new DefaultInputFile("foo", "src2/foo3.xoo").setAbsolutePath(new File(baseDir, "src2/foo3.xoo").getAbsolutePath()).setLanguage("xoo");
+    DefaultInputFile inputFile1 = new DefaultInputFile("foo", "src/foo.xoo").setLanguage("xoo");
+    DefaultInputFile inputFile2 = new DefaultInputFile("foo", "src/foo2.xoo").setLanguage("xoo");
+    DefaultInputFile inputFile3 = new DefaultInputFile("foo", "src2/foo3.xoo").setLanguage("xoo");
     fileSystem.add(inputFile1);
     fileSystem.add(inputFile2);
     fileSystem.add(inputFile3);
index ade948848f7a17223eba7b1782cac472f6e2415e..6626a5e95456b111470908c940846cd9874fc5d1 100644 (file)
@@ -65,7 +65,7 @@ public class MeasureSensorTest {
     baseDir = temp.newFolder();
     metricFinder = mock(MetricFinder.class);
     sensor = new MeasureSensor(metricFinder);
-    fileSystem = new DefaultFileSystem(baseDir);
+    fileSystem = new DefaultFileSystem(baseDir.toPath());
     when(context.fileSystem()).thenReturn(fileSystem);
     storage = mock(SensorStorage.class);
     when(context.newMeasure()).then(new Answer<DefaultMeasure>() {
@@ -83,7 +83,7 @@ public class MeasureSensorTest {
 
   @Test
   public void testNoExecutionIfNoMeasureFile() {
-    DefaultInputFile inputFile = new DefaultInputFile("foo", "src/foo.xoo").setAbsolutePath(new File(baseDir, "src/foo.xoo").getAbsolutePath()).setLanguage("xoo");
+    DefaultInputFile inputFile = new DefaultInputFile("foo", "src/foo.xoo").setLanguage("xoo");
     fileSystem.add(inputFile);
     sensor.execute(context);
   }
@@ -92,7 +92,7 @@ public class MeasureSensorTest {
   public void testExecution() throws IOException {
     File measures = new File(baseDir, "src/foo.xoo.measures");
     FileUtils.write(measures, "ncloc:12\nbranch_coverage:5.3\nsqale_index:300\nbool:true\n\n#comment");
-    DefaultInputFile inputFile = new DefaultInputFile("foo", "src/foo.xoo").setAbsolutePath(new File(baseDir, "src/foo.xoo").getAbsolutePath()).setLanguage("xoo");
+    DefaultInputFile inputFile = new DefaultInputFile("foo", "src/foo.xoo").setLanguage("xoo");
     fileSystem.add(inputFile);
 
     Metric<Boolean> booleanMetric = new Metric.Builder("bool", "Bool", Metric.ValueType.BOOL)
@@ -115,7 +115,7 @@ public class MeasureSensorTest {
   public void failIfMetricNotFound() throws IOException {
     File measures = new File(baseDir, "src/foo.xoo.measures");
     FileUtils.write(measures, "unknow:12\n\n#comment");
-    DefaultInputFile inputFile = new DefaultInputFile("foo", "src/foo.xoo").setAbsolutePath(new File(baseDir, "src/foo.xoo").getAbsolutePath()).setLanguage("xoo");
+    DefaultInputFile inputFile = new DefaultInputFile("foo", "src/foo.xoo").setLanguage("xoo");
     fileSystem.add(inputFile);
 
     thrown.expect(IllegalStateException.class);
index 945253e72b0ebfb8381b3fb82ea79434624ed556..5673221a46e6605b0a2368e3ab914e735c176b23 100644 (file)
@@ -52,7 +52,7 @@ public class SymbolReferencesSensorTest {
   public void prepare() throws IOException {
     baseDir = temp.newFolder();
     sensor = new SymbolReferencesSensor();
-    fileSystem = new DefaultFileSystem(baseDir);
+    fileSystem = new DefaultFileSystem(baseDir.toPath());
     when(context.fileSystem()).thenReturn(fileSystem);
   }
 
@@ -63,7 +63,7 @@ public class SymbolReferencesSensorTest {
 
   @Test
   public void testNoExecutionIfNoSymbolFile() {
-    DefaultInputFile inputFile = new DefaultInputFile("foo", "src/foo.xoo").setAbsolutePath(new File(baseDir, "src/foo.xoo").getAbsolutePath()).setLanguage("xoo");
+    DefaultInputFile inputFile = new DefaultInputFile("foo", "src/foo.xoo").setLanguage("xoo");
     fileSystem.add(inputFile);
     sensor.execute(context);
   }
@@ -72,7 +72,7 @@ public class SymbolReferencesSensorTest {
   public void testExecution() throws IOException {
     File symbol = new File(baseDir, "src/foo.xoo.symbol");
     FileUtils.write(symbol, "1,4,7\n12,15,23\n\n#comment");
-    DefaultInputFile inputFile = new DefaultInputFile("foo", "src/foo.xoo").setAbsolutePath(new File(baseDir, "src/foo.xoo").getAbsolutePath()).setLanguage("xoo");
+    DefaultInputFile inputFile = new DefaultInputFile("foo", "src/foo.xoo").setLanguage("xoo");
     fileSystem.add(inputFile);
     SymbolTableBuilder symbolTableBuilder = mock(SymbolTableBuilder.class);
     when(context.symbolTableBuilder(inputFile)).thenReturn(symbolTableBuilder);
index 75c5a1c668570a7634c131165983ebe4d0534f8d..559f6b37b0854491fb9c44bee6f2fac653b802b8 100644 (file)
@@ -52,7 +52,7 @@ public class SyntaxHighlightingSensorTest {
   public void prepare() throws IOException {
     baseDir = temp.newFolder();
     sensor = new SyntaxHighlightingSensor();
-    fileSystem = new DefaultFileSystem(baseDir);
+    fileSystem = new DefaultFileSystem(baseDir.toPath());
     when(context.fileSystem()).thenReturn(fileSystem);
   }
 
@@ -63,7 +63,7 @@ public class SyntaxHighlightingSensorTest {
 
   @Test
   public void testNoExecutionIfNoSyntaxFile() {
-    DefaultInputFile inputFile = new DefaultInputFile("foo", "src/foo.xoo").setAbsolutePath(new File(baseDir, "src/foo.xoo").getAbsolutePath()).setLanguage("xoo");
+    DefaultInputFile inputFile = new DefaultInputFile("foo", "src/foo.xoo").setLanguage("xoo");
     fileSystem.add(inputFile);
     sensor.execute(context);
   }
@@ -72,7 +72,7 @@ public class SyntaxHighlightingSensorTest {
   public void testExecution() throws IOException {
     File symbol = new File(baseDir, "src/foo.xoo.highlighting");
     FileUtils.write(symbol, "1:4:k\n12:15:cppd\n\n#comment");
-    DefaultInputFile inputFile = new DefaultInputFile("foo", "src/foo.xoo").setAbsolutePath(new File(baseDir, "src/foo.xoo").getAbsolutePath()).setLanguage("xoo");
+    DefaultInputFile inputFile = new DefaultInputFile("foo", "src/foo.xoo").setLanguage("xoo");
     fileSystem.add(inputFile);
     HighlightingBuilder builder = mock(HighlightingBuilder.class);
     when(context.highlightingBuilder(inputFile)).thenReturn(builder);
index 41109c800c4108053656df9c724d53e44c1ceefb..5e1a1344f4e3e7e5cbae8638abe5314b943d01e2 100644 (file)
@@ -56,7 +56,7 @@ public class TestCaseSensorTest {
   public void prepare() throws IOException {
     baseDir = temp.newFolder();
     sensor = new TestCaseSensor();
-    fileSystem = new DefaultFileSystem(baseDir);
+    fileSystem = new DefaultFileSystem(baseDir.toPath());
     when(context.fileSystem()).thenReturn(fileSystem);
   }
 
@@ -67,7 +67,7 @@ public class TestCaseSensorTest {
 
   @Test
   public void testNoExecutionIfNoTestFile() {
-    DefaultInputFile testFile = new DefaultInputFile("foo", "test/fooTest.xoo").setAbsolutePath(new File(baseDir, "test/fooTest.xoo").getAbsolutePath()).setLanguage("xoo")
+    DefaultInputFile testFile = new DefaultInputFile("foo", "test/fooTest.xoo").setLanguage("xoo")
       .setType(Type.TEST);
     fileSystem.add(testFile);
     sensor.execute(context);
@@ -77,7 +77,7 @@ public class TestCaseSensorTest {
   public void testExecution() throws IOException {
     File testPlan = new File(baseDir, "test/fooTest.xoo.testplan");
     FileUtils.write(testPlan, "test1:UNIT:OK:::10\ntest2:INTEGRATION:ERROR:message:stack:15\n\n#comment");
-    DefaultInputFile testFile = new DefaultInputFile("foo", "test/fooTest.xoo").setAbsolutePath(new File(baseDir, "test/fooTest.xoo").getAbsolutePath()).setLanguage("xoo")
+    DefaultInputFile testFile = new DefaultInputFile("foo", "test/fooTest.xoo").setLanguage("xoo")
       .setType(Type.TEST);
     fileSystem.add(testFile);
 
index 752f4144aba43666f19ceb590034b21251852f2f..1fe44615f9ba8d16d4d0fc8f1b219f537a48572e 100644 (file)
@@ -57,7 +57,7 @@ public class XooTokenizerSensorTest {
   public void prepare() throws IOException {
     baseDir = temp.newFolder();
     sensor = new XooTokenizerSensor();
-    fileSystem = new DefaultFileSystem(baseDir);
+    fileSystem = new DefaultFileSystem(baseDir.toPath());
     when(context.fileSystem()).thenReturn(fileSystem);
     settings = new Settings();
     when(context.settings()).thenReturn(settings);
@@ -70,7 +70,7 @@ public class XooTokenizerSensorTest {
 
   @Test
   public void testNoExecutionIfExclusion() {
-    DefaultInputFile inputFile = new DefaultInputFile("foo", "src/foo.xoo").setAbsolutePath(new File(baseDir, "src/foo.xoo").getAbsolutePath()).setLanguage("xoo");
+    DefaultInputFile inputFile = new DefaultInputFile("foo", "src/foo.xoo").setLanguage("xoo");
     fileSystem.add(inputFile);
     settings.setProperty(CoreProperties.CPD_EXCLUSIONS, "**/foo.xoo");
     sensor.execute(context);
@@ -81,7 +81,7 @@ public class XooTokenizerSensorTest {
   public void testExecution() throws IOException {
     File source = new File(baseDir, "src/foo.xoo");
     FileUtils.write(source, "token1 token2 token3\ntoken4");
-    DefaultInputFile inputFile = new DefaultInputFile("foo", "src/foo.xoo").setAbsolutePath(new File(baseDir, "src/foo.xoo").getAbsolutePath()).setLanguage("xoo");
+    DefaultInputFile inputFile = new DefaultInputFile("foo", "src/foo.xoo").setLanguage("xoo");
     fileSystem.add(inputFile);
     DuplicationTokenBuilder builder = mock(DuplicationTokenBuilder.class);
     when(context.duplicationTokenBuilder(inputFile)).thenReturn(builder);
index f283ffb0cd195c3b53c80165a32db18d9e0cc6cb..9f1a4436a0e1441299075f26584813cf98cb4183 100644 (file)
@@ -60,7 +60,7 @@ public class OneIssuePerLineSensorTest {
 
   @Test
   public void testRule() throws IOException {
-    DefaultFileSystem fs = new DefaultFileSystem(temp.newFolder());
+    DefaultFileSystem fs = new DefaultFileSystem(temp.newFolder().toPath());
     DefaultInputFile inputFile = new DefaultInputFile("foo", "src/Foo.xoo").setLanguage(Xoo.KEY).setLines(10);
     fs.add(inputFile);
 
@@ -84,7 +84,7 @@ public class OneIssuePerLineSensorTest {
 
   @Test
   public void testForceSeverity() throws IOException {
-    DefaultFileSystem fs = new DefaultFileSystem(temp.newFolder());
+    DefaultFileSystem fs = new DefaultFileSystem(temp.newFolder().toPath());
     DefaultInputFile inputFile = new DefaultInputFile("foo", "src/Foo.xoo").setLanguage(Xoo.KEY).setLines(10);
     fs.add(inputFile);
 
index d0156cc083da63a590d5d700c0801d8200654365..eda682a7a43b90e3f5b37f78909d97275e97e28b 100644 (file)
@@ -57,7 +57,7 @@ public class XooBlameCommandTest {
   @Before
   public void prepare() throws IOException {
     baseDir = temp.newFolder();
-    fs = new DefaultFileSystem(baseDir);
+    fs = new DefaultFileSystem(baseDir.toPath());
     input = mock(BlameInput.class);
     when(input.fileSystem()).thenReturn(fs);
   }
@@ -68,7 +68,7 @@ public class XooBlameCommandTest {
     FileUtils.write(source, "sample content");
     File scm = new File(baseDir, "src/foo.xoo.scm");
     FileUtils.write(scm, "123,julien,2014-12-12\n234,julien,2014-12-24");
-    DefaultInputFile inputFile = new DefaultInputFile("foo", "src/foo.xoo").setAbsolutePath(new File(baseDir, "src/foo.xoo").getAbsolutePath()).setLanguage(Xoo.KEY);
+    DefaultInputFile inputFile = new DefaultInputFile("foo", "src/foo.xoo").setLanguage(Xoo.KEY);
     fs.add(inputFile);
 
     BlameOutput result = mock(BlameOutput.class);
index a06d4d36ed6bd900ff9a4ac094aa7fcabfc2d3f0..d96777a8b16740ec451400067cdcb6c2a867fcac 100644 (file)
@@ -28,6 +28,7 @@
       <groupId>org.codehaus.sonar</groupId>
       <artifactId>sonar-persistit</artifactId>
     </dependency>
+    
     <dependency>
       <groupId>org.codehaus.sonar</groupId>
       <artifactId>sonar-core</artifactId>
diff --git a/sonar-batch/src/main/java/org/sonar/batch/DecoratorsSelector.java b/sonar-batch/src/main/java/org/sonar/batch/DecoratorsSelector.java
deleted file mode 100644 (file)
index 7ce661a..0000000
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * 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.batch;
-
-import com.google.common.collect.HashMultimap;
-import com.google.common.collect.SetMultimap;
-import org.sonar.api.batch.Decorator;
-import org.sonar.api.measures.Metric;
-import org.sonar.api.resources.Project;
-import org.sonar.batch.bootstrap.BatchExtensionDictionnary;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-public final class DecoratorsSelector {
-
-  private BatchExtensionDictionnary batchExtDictionnary;
-
-  public DecoratorsSelector(BatchExtensionDictionnary dictionnary) {
-    this.batchExtDictionnary = dictionnary;
-  }
-
-  public Collection<Decorator> select(Project project) {
-    List<Decorator> decorators = new ArrayList<Decorator>(batchExtDictionnary.select(Decorator.class, project, false, null));
-    SetMultimap<Metric, Decorator> decoratorsByGeneratedMetric = getDecoratorsByMetric(decorators);
-    for (Metric metric : batchExtDictionnary.select(Metric.class, null, false, null)) {
-      if (metric.getFormula() != null) {
-        decorators.add(new FormulaDecorator(metric, decoratorsByGeneratedMetric.get(metric)));
-      }
-    }
-
-    return batchExtDictionnary.sort(decorators);
-  }
-
-  private SetMultimap<Metric, Decorator> getDecoratorsByMetric(Collection<Decorator> pluginDecorators) {
-    SetMultimap<Metric, Decorator> decoratorsByGeneratedMetric = HashMultimap.create();
-    for (Decorator decorator : pluginDecorators) {
-      List dependents = batchExtDictionnary.getDependents(decorator);
-      for (Object dependent : dependents) {
-        if (dependent instanceof Metric) {
-          decoratorsByGeneratedMetric.put((Metric) dependent, decorator);
-        }
-      }
-    }
-    return decoratorsByGeneratedMetric;
-  }
-}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/DefaultDecoratorContext.java b/sonar-batch/src/main/java/org/sonar/batch/DefaultDecoratorContext.java
deleted file mode 100644 (file)
index 3d18e06..0000000
+++ /dev/null
@@ -1,258 +0,0 @@
-/*
- * 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.batch;
-
-import com.google.common.collect.ArrayListMultimap;
-import com.google.common.collect.ListMultimap;
-import com.google.common.collect.Lists;
-import org.sonar.api.batch.DecoratorContext;
-import org.sonar.api.batch.Event;
-import org.sonar.api.batch.SonarIndex;
-import org.sonar.api.batch.sensor.duplication.DuplicationGroup;
-import org.sonar.api.design.Dependency;
-import org.sonar.api.measures.CoreMetrics;
-import org.sonar.api.measures.Measure;
-import org.sonar.api.measures.MeasuresFilter;
-import org.sonar.api.measures.MeasuresFilters;
-import org.sonar.api.measures.Metric;
-import org.sonar.api.measures.MetricFinder;
-import org.sonar.api.resources.Project;
-import org.sonar.api.resources.Resource;
-import org.sonar.api.rules.Violation;
-import org.sonar.api.utils.SonarException;
-import org.sonar.batch.duplication.DuplicationCache;
-import org.sonar.batch.duplication.DuplicationUtils;
-import org.sonar.batch.scan.measure.MeasureCache;
-import org.sonar.batch.sensor.coverage.CoverageExclusions;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Date;
-import java.util.List;
-import java.util.Set;
-
-public class DefaultDecoratorContext implements DecoratorContext {
-
-  private static final String SAVE_MEASURE_METHOD = "saveMeasure";
-  private SonarIndex sonarIndex;
-  private Resource resource;
-  private boolean readOnly = false;
-
-  private List<DecoratorContext> childrenContexts;
-
-  private ListMultimap<String, Measure> measuresByMetric = ArrayListMultimap.create();
-  private MeasureCache measureCache;
-  private MetricFinder metricFinder;
-  private final DuplicationCache duplicationCache;
-  private final CoverageExclusions coverageFilter;
-
-  public DefaultDecoratorContext(Resource resource,
-    SonarIndex index,
-    List<DecoratorContext> childrenContexts,
-    MeasureCache measureCache, MetricFinder metricFinder, DuplicationCache duplicationCache, CoverageExclusions coverageFilter) {
-    this.sonarIndex = index;
-    this.resource = resource;
-    this.childrenContexts = childrenContexts;
-    this.measureCache = measureCache;
-    this.metricFinder = metricFinder;
-    this.duplicationCache = duplicationCache;
-    this.coverageFilter = coverageFilter;
-  }
-
-  public void init() {
-    Iterable<Measure> unfiltered = measureCache.byResource(resource);
-    for (Measure measure : unfiltered) {
-      measuresByMetric.put(measure.getMetricKey(), measure);
-    }
-  }
-
-  public DefaultDecoratorContext end() {
-    readOnly = true;
-    childrenContexts = null;
-    for (Measure measure : measuresByMetric.values()) {
-      measureCache.put(resource, measure);
-    }
-    return this;
-  }
-
-  @Override
-  public Project getProject() {
-    return sonarIndex.getProject();
-  }
-
-  @Override
-  public List<DecoratorContext> getChildren() {
-    checkReadOnly("getModules");
-    return childrenContexts;
-  }
-
-  private void checkReadOnly(String methodName) {
-    if (readOnly) {
-      throw new IllegalStateException("Method DecoratorContext." + methodName + "() can not be executed on children.");
-    }
-  }
-
-  @Override
-  public <M> M getMeasures(MeasuresFilter<M> filter) {
-    Collection<Measure> unfiltered;
-    if (filter instanceof MeasuresFilters.MetricFilter) {
-      unfiltered = getMeasuresOfASingleMetric(filter);
-    } else {
-      unfiltered = measuresByMetric.values();
-    }
-    return filter.filter(unfiltered);
-  }
-
-  private <M> Collection<Measure> getMeasuresOfASingleMetric(MeasuresFilter<M> filter) {
-    Collection<Measure> unfiltered;
-    String metricKey = ((MeasuresFilters.MetricFilter<M>) filter).filterOnMetricKey();
-    if (CoreMetrics.DUPLICATIONS_DATA_KEY.equals(metricKey)) {
-      // Hack for SONAR-5765
-      List<DuplicationGroup> group = duplicationCache.byComponent(resource.getEffectiveKey());
-      if (group != null) {
-        unfiltered = Arrays.asList(new Measure(CoreMetrics.DUPLICATIONS_DATA, DuplicationUtils.toXml(group)));
-      } else {
-        unfiltered = Collections.<Measure>emptyList();
-      }
-    } else {
-      // optimization
-      unfiltered = measuresByMetric.get(metricKey);
-    }
-    return unfiltered;
-  }
-
-  @Override
-  public Measure getMeasure(Metric metric) {
-    return getMeasures(MeasuresFilters.metric(metric));
-  }
-
-  @Override
-  public Collection<Measure> getChildrenMeasures(MeasuresFilter filter) {
-    List<Measure> result = Lists.newArrayList();
-    for (DecoratorContext childContext : childrenContexts) {
-      Object childResult = childContext.getMeasures(filter);
-      if (childResult != null) {
-        if (childResult instanceof Collection) {
-          result.addAll((Collection) childResult);
-        } else {
-          result.add((Measure) childResult);
-        }
-      }
-    }
-    return result;
-  }
-
-  @Override
-  public Collection<Measure> getChildrenMeasures(Metric metric) {
-    return getChildrenMeasures(MeasuresFilters.metric(metric));
-  }
-
-  @Override
-  public Resource getResource() {
-    return resource;
-  }
-
-  @Override
-  public DecoratorContext saveMeasure(Measure measure) {
-    checkReadOnly(SAVE_MEASURE_METHOD);
-    Metric metric = metricFinder.findByKey(measure.getMetricKey());
-    if (metric == null) {
-      throw new SonarException("Unknown metric: " + measure.getMetricKey());
-    }
-    measure.setMetric(metric);
-    if (coverageFilter.accept(resource, measure)) {
-      List<Measure> metricMeasures = measuresByMetric.get(measure.getMetricKey());
-
-      boolean add = true;
-      if (metricMeasures != null) {
-        int index = metricMeasures.indexOf(measure);
-        if (index > -1) {
-          if (metricMeasures.get(index) == measure) {
-            add = false;
-          } else {
-            throw new SonarException("Can not add twice the same measure on " + resource + ": " + measure);
-          }
-        }
-      }
-      if (add) {
-        measuresByMetric.put(measure.getMetricKey(), measure);
-      }
-    }
-    return this;
-  }
-
-  @Override
-  public DecoratorContext saveMeasure(Metric metric, Double value) {
-    checkReadOnly(SAVE_MEASURE_METHOD);
-    saveMeasure(new Measure(metric, value));
-    return this;
-  }
-
-  @Override
-  public Dependency saveDependency(Dependency dependency) {
-    checkReadOnly("addDependency");
-    return sonarIndex.addDependency(dependency);
-  }
-
-  @Override
-  public Set<Dependency> getDependencies() {
-    return sonarIndex.getDependencies();
-  }
-
-  @Override
-  public Collection<Dependency> getIncomingDependencies() {
-    return sonarIndex.getIncomingEdges(resource);
-  }
-
-  @Override
-  public Collection<Dependency> getOutgoingDependencies() {
-    return sonarIndex.getOutgoingEdges(resource);
-  }
-
-  @Override
-  public List<Event> getEvents() {
-    return sonarIndex.getEvents(resource);
-  }
-
-  @Override
-  public Event createEvent(String name, String description, String category, Date date) {
-    return sonarIndex.addEvent(resource, name, description, category, date);
-  }
-
-  @Override
-  public void deleteEvent(Event event) {
-    sonarIndex.deleteEvent(event);
-  }
-
-  @Override
-  public DefaultDecoratorContext saveViolation(Violation violation, boolean force) {
-    if (violation.getResource() == null) {
-      violation.setResource(resource);
-    }
-    sonarIndex.addViolation(violation, force);
-    return this;
-  }
-
-  @Override
-  public DefaultDecoratorContext saveViolation(Violation violation) {
-    return saveViolation(violation, false);
-  }
-}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/DefaultProjectClasspath.java b/sonar-batch/src/main/java/org/sonar/batch/DefaultProjectClasspath.java
deleted file mode 100644 (file)
index d497906..0000000
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * 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.batch;
-
-import com.google.common.collect.Lists;
-import org.apache.maven.project.MavenProject;
-import org.sonar.api.batch.ProjectClasspath;
-import org.sonar.api.batch.bootstrap.ProjectDefinition;
-import org.sonar.api.resources.ProjectFileSystem;
-
-import javax.annotation.Nullable;
-
-import java.io.File;
-import java.util.List;
-
-public class DefaultProjectClasspath extends ProjectClasspath {
-
-  private ProjectDefinition def;
-  private ProjectFileSystem projectFileSystem;
-
-  public DefaultProjectClasspath(ProjectDefinition def, ProjectFileSystem projectFileSystem) {
-    this(def, projectFileSystem, null);
-  }
-
-  public DefaultProjectClasspath(ProjectDefinition def, ProjectFileSystem projectFileSystem, @Nullable MavenProject pom) {
-    super(pom);
-    this.def = def;
-    this.projectFileSystem = projectFileSystem;
-  }
-
-  @Override
-  protected List<File> createElements() {
-    if (pom != null) {
-      return super.createElements();
-    } else {
-      List<File> elements = Lists.newArrayList();
-      for (String path : def.getBinaries()) {
-        elements.add(projectFileSystem.resolvePath(path));
-      }
-      for (String path : def.getLibraries()) {
-        elements.add(projectFileSystem.resolvePath(path));
-      }
-      return elements;
-    }
-  }
-}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/DefaultResourceCreationLock.java b/sonar-batch/src/main/java/org/sonar/batch/DefaultResourceCreationLock.java
deleted file mode 100644 (file)
index 1adb507..0000000
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * 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.batch;
-
-import org.sonar.api.batch.ResourceCreationLock;
-
-/**
- * This lock is used to ensure that Sonar resources (files, packages, directories) are not created by buggy plugins
- * when saving measures/violations on unknown resources.
- *
- * @since 2.3
- * @deprecated not used since 4.2
- */
-@Deprecated
-public final class DefaultResourceCreationLock implements ResourceCreationLock {
-
-  @Override
-  public void lock() {
-    // does nothing since 4.2. Creation of components (ex-resources) is
-    // the responsibility of core, not plugins
-  }
-
-}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/DefaultTimeMachine.java b/sonar-batch/src/main/java/org/sonar/batch/DefaultTimeMachine.java
deleted file mode 100644 (file)
index 79d61dd..0000000
+++ /dev/null
@@ -1,177 +0,0 @@
-/*
- * 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.batch;
-
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-import org.sonar.api.batch.TimeMachine;
-import org.sonar.api.batch.TimeMachineQuery;
-import org.sonar.api.database.DatabaseSession;
-import org.sonar.api.database.model.MeasureModel;
-import org.sonar.api.database.model.Snapshot;
-import org.sonar.api.measures.Measure;
-import org.sonar.api.measures.Metric;
-import org.sonar.api.measures.MetricFinder;
-import org.sonar.api.resources.Qualifiers;
-import org.sonar.api.resources.Resource;
-import org.sonar.api.technicaldebt.batch.Characteristic;
-import org.sonar.api.technicaldebt.batch.TechnicalDebtModel;
-import org.sonar.batch.index.DefaultIndex;
-
-import javax.annotation.Nullable;
-import javax.persistence.Query;
-import java.util.*;
-
-import static org.sonar.api.utils.DateUtils.dateToLong;
-
-public class DefaultTimeMachine implements TimeMachine {
-
-  private DatabaseSession session;
-  private DefaultIndex index;
-  private MetricFinder metricFinder;
-  private TechnicalDebtModel techDebtModel;
-
-  public DefaultTimeMachine(DatabaseSession session, DefaultIndex index, MetricFinder metricFinder, TechnicalDebtModel techDebtModel) {
-    this.session = session;
-    this.index = index;
-    this.metricFinder = metricFinder;
-    this.techDebtModel = techDebtModel;
-  }
-
-  @Override
-  public List<Measure> getMeasures(TimeMachineQuery query) {
-    Map<Integer, Metric> metricById = getMetricsById(query);
-
-    List<Object[]> objects = execute(query, true, metricById.keySet());
-    List<Measure> result = Lists.newArrayList();
-
-    for (Object[] object : objects) {
-      MeasureModel model = (MeasureModel) object[0];
-      Integer characteristicId = model.getCharacteristicId();
-      Characteristic characteristic = techDebtModel.characteristicById(characteristicId);
-      Measure measure = toMeasure(model, metricById.get(model.getMetricId()), characteristic);
-      measure.setDate(new Date((Long) object[1]));
-      result.add(measure);
-    }
-    return result;
-  }
-
-  @Override
-  public List<Object[]> getMeasuresFields(TimeMachineQuery query) {
-    Map<Integer, Metric> metricById = getMetricsById(query);
-    List<Object[]> rows = execute(query, false, metricById.keySet());
-    for (Object[] fields : rows) {
-      fields[1] = metricById.get(fields[1]);
-    }
-    return rows;
-  }
-
-  protected List<Object[]> execute(TimeMachineQuery query, boolean selectAllFields, Set<Integer> metricIds) {
-    Resource resource = query.getResource();
-    if (resource != null && resource.getId() == null) {
-      resource = index.getResource(query.getResource());
-    }
-    if (resource == null) {
-      return Collections.emptyList();
-    }
-
-    StringBuilder sb = new StringBuilder();
-    Map<String, Object> params = Maps.newHashMap();
-
-    if (selectAllFields) {
-      sb.append("SELECT m, s.createdAt ");
-    } else {
-      sb.append("SELECT s.createdAt, m.metricId, m.value ");
-    }
-    sb.append(" FROM ")
-      .append(MeasureModel.class.getSimpleName())
-      .append(" m, ")
-      .append(Snapshot.class.getSimpleName())
-      .append(" s WHERE m.snapshotId=s.id AND s.resourceId=:resourceId AND s.status=:status AND s.qualifier<>:lib");
-    params.put("resourceId", resource.getId());
-    params.put("status", Snapshot.STATUS_PROCESSED);
-    params.put("lib", Qualifiers.LIBRARY);
-
-    sb.append(" AND m.characteristicId IS NULL");
-    sb.append(" AND m.personId IS NULL");
-    sb.append(" AND m.ruleId IS NULL AND m.rulePriority IS NULL");
-    if (!metricIds.isEmpty()) {
-      sb.append(" AND m.metricId IN (:metricIds) ");
-      params.put("metricIds", metricIds);
-    }
-    if (query.isFromCurrentAnalysis()) {
-      sb.append(" AND s.createdAt>=:from ");
-      params.put("from", index.getProject().getAnalysisDate());
-
-    } else if (query.getFrom() != null) {
-      sb.append(" AND s.createdAt>=:from ");
-      params.put("from", dateToLong(query.getFrom()));
-    }
-    if (query.isToCurrentAnalysis()) {
-      sb.append(" AND s.createdAt<=:to ");
-      params.put("to", dateToLong(index.getProject().getAnalysisDate()));
-
-    } else if (query.getTo() != null) {
-      sb.append(" AND s.createdAt<=:to ");
-      params.put("to", dateToLong(query.getTo()));
-    }
-    if (query.isOnlyLastAnalysis()) {
-      sb.append(" AND s.last=:last ");
-      params.put("last", Boolean.TRUE);
-    }
-    sb.append(" ORDER BY s.createdAt ");
-
-    Query jpaQuery = session.createQuery(sb.toString());
-
-    for (Map.Entry<String, Object> entry : params.entrySet()) {
-      jpaQuery.setParameter(entry.getKey(), entry.getValue());
-    }
-    return jpaQuery.getResultList();
-  }
-
-  public Map<Integer, Metric> getMetricsById(TimeMachineQuery query) {
-    Collection<Metric> metrics = metricFinder.findAll(query.getMetricKeys());
-    Map<Integer, Metric> result = Maps.newHashMap();
-    for (Metric metric : metrics) {
-      result.put(metric.getId(), metric);
-    }
-    return result;
-  }
-
-  static Measure toMeasure(MeasureModel model, Metric metric, @Nullable Characteristic characteristic) {
-    // NOTE: measures on rule are not supported
-    Measure measure = new Measure(metric);
-    measure.setDescription(model.getDescription());
-    measure.setValue(model.getValue());
-    measure.setData(model.getData(metric));
-    measure.setAlertStatus(model.getAlertStatus());
-    measure.setAlertText(model.getAlertText());
-    measure.setTendency(model.getTendency());
-    measure.setVariation1(model.getVariationValue1());
-    measure.setVariation2(model.getVariationValue2());
-    measure.setVariation3(model.getVariationValue3());
-    measure.setVariation4(model.getVariationValue4());
-    measure.setVariation5(model.getVariationValue5());
-    measure.setUrl(model.getUrl());
-    measure.setCharacteristic(characteristic);
-    measure.setPersonId(model.getPersonId());
-    return measure;
-  }
-}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/DeprecatedSensorContext.java b/sonar-batch/src/main/java/org/sonar/batch/DeprecatedSensorContext.java
deleted file mode 100644 (file)
index 49998b1..0000000
+++ /dev/null
@@ -1,298 +0,0 @@
-/*
- * 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.batch;
-
-import org.apache.commons.lang.StringUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.sonar.api.batch.AnalysisMode;
-import org.sonar.api.batch.Event;
-import org.sonar.api.batch.SensorContext;
-import org.sonar.api.batch.SonarIndex;
-import org.sonar.api.batch.fs.FileSystem;
-import org.sonar.api.batch.fs.InputDir;
-import org.sonar.api.batch.fs.InputFile;
-import org.sonar.api.batch.fs.InputPath;
-import org.sonar.api.batch.rule.ActiveRules;
-import org.sonar.api.batch.sensor.SensorStorage;
-import org.sonar.api.config.Settings;
-import org.sonar.api.design.Dependency;
-import org.sonar.api.measures.Measure;
-import org.sonar.api.measures.MeasuresFilter;
-import org.sonar.api.measures.Metric;
-import org.sonar.api.resources.Directory;
-import org.sonar.api.resources.File;
-import org.sonar.api.resources.Project;
-import org.sonar.api.resources.ProjectLink;
-import org.sonar.api.resources.Qualifiers;
-import org.sonar.api.resources.Resource;
-import org.sonar.api.rules.Violation;
-import org.sonar.api.utils.SonarException;
-import org.sonar.batch.duplication.BlockCache;
-import org.sonar.batch.duplication.DuplicationCache;
-import org.sonar.batch.index.ComponentDataCache;
-import org.sonar.batch.sensor.DefaultSensorContext;
-import org.sonar.batch.sensor.coverage.CoverageExclusions;
-
-import java.io.Serializable;
-import java.util.Collection;
-import java.util.Date;
-import java.util.List;
-import java.util.Set;
-
-public class DeprecatedSensorContext extends DefaultSensorContext implements SensorContext {
-
-  private static final Logger LOG = LoggerFactory.getLogger(DeprecatedSensorContext.class);
-
-  private final SonarIndex index;
-  private final Project project;
-  private final CoverageExclusions coverageFilter;
-
-  public DeprecatedSensorContext(SonarIndex index, Project project, Settings settings, FileSystem fs, ActiveRules activeRules,
-    AnalysisMode analysisMode, ComponentDataCache componentDataCache, CoverageExclusions coverageFilter,
-    BlockCache blockCache, DuplicationCache duplicationCache, SensorStorage sensorStorage) {
-    super(settings, fs, activeRules, analysisMode, componentDataCache, blockCache, duplicationCache, sensorStorage);
-    this.index = index;
-    this.project = project;
-    this.coverageFilter = coverageFilter;
-  }
-
-  public Project getProject() {
-    return project;
-  }
-
-  @Override
-  public boolean index(Resource resource) {
-    // SONAR-5006
-    if (indexedByCore(resource)) {
-      logWarning();
-      return true;
-    }
-    return index.index(resource);
-  }
-
-  private boolean indexedByCore(Resource resource) {
-    return StringUtils.equals(Qualifiers.DIRECTORY, resource.getQualifier()) ||
-      StringUtils.equals(Qualifiers.FILE, resource.getQualifier());
-  }
-
-  @Override
-  public boolean index(Resource resource, Resource parentReference) {
-    // SONAR-5006
-    if (indexedByCore(resource)) {
-      logWarning();
-      return true;
-    }
-    return index.index(resource, parentReference);
-  }
-
-  private void logWarning() {
-    if (LOG.isDebugEnabled()) {
-      LOG.debug("Plugins are no more responsible for indexing physical resources like directories and files. This is now handled by the platform.", new SonarException(
-        "Plugin should not index physical resources"));
-    }
-  }
-
-  @Override
-  public boolean isExcluded(Resource reference) {
-    return index.isExcluded(reference);
-  }
-
-  @Override
-  public boolean isIndexed(Resource reference, boolean acceptExcluded) {
-    return index.isIndexed(reference, acceptExcluded);
-  }
-
-  @Override
-  public Resource getParent(Resource reference) {
-    return index.getParent(reference);
-  }
-
-  @Override
-  public Collection<Resource> getChildren(Resource reference) {
-    return index.getChildren(reference);
-  }
-
-  @Override
-  public <G extends Serializable> Measure<G> getMeasure(Metric<G> metric) {
-    return index.getMeasure(project, metric);
-  }
-
-  @Override
-  public <M> M getMeasures(MeasuresFilter<M> filter) {
-    return index.getMeasures(project, filter);
-  }
-
-  @Override
-  public Measure saveMeasure(Measure measure) {
-    return index.addMeasure(project, measure);
-  }
-
-  @Override
-  public Measure saveMeasure(Metric metric, Double value) {
-    return index.addMeasure(project, new Measure(metric, value));
-  }
-
-  @Override
-  public <G extends Serializable> Measure<G> getMeasure(Resource resource, Metric<G> metric) {
-    return index.getMeasure(resource, metric);
-  }
-
-  @Override
-  public String saveResource(Resource resource) {
-    Resource persistedResource = index.addResource(resource);
-    if (persistedResource != null) {
-      return persistedResource.getEffectiveKey();
-    }
-    return null;
-  }
-
-  public boolean saveResource(Resource resource, Resource parentReference) {
-    return index.index(resource, parentReference);
-  }
-
-  @Override
-  public Resource getResource(Resource resource) {
-    return index.getResource(resource);
-  }
-
-  @Override
-  public <M> M getMeasures(Resource resource, MeasuresFilter<M> filter) {
-    return index.getMeasures(resource, filter);
-  }
-
-  @Override
-  public Measure saveMeasure(Resource resource, Metric metric, Double value) {
-    return saveMeasure(resource, new Measure(metric, value));
-  }
-
-  @Override
-  public Measure saveMeasure(Resource resource, Measure measure) {
-    Resource resourceOrProject = resourceOrProject(resource);
-    if (coverageFilter.accept(resourceOrProject, measure)) {
-      return index.addMeasure(resourceOrProject, measure);
-    } else {
-      return measure;
-    }
-  }
-
-  @Override
-  public void saveViolation(Violation violation, boolean force) {
-    if (violation.getResource() == null) {
-      violation.setResource(resourceOrProject(violation.getResource()));
-    }
-    index.addViolation(violation, force);
-  }
-
-  @Override
-  public void saveViolation(Violation violation) {
-    saveViolation(violation, false);
-  }
-
-  @Override
-  public void saveViolations(Collection<Violation> violations) {
-    if (violations != null) {
-      for (Violation violation : violations) {
-        saveViolation(violation);
-      }
-    }
-  }
-
-  @Override
-  public Dependency saveDependency(Dependency dependency) {
-    return index.addDependency(dependency);
-  }
-
-  @Override
-  public Set<Dependency> getDependencies() {
-    return index.getDependencies();
-  }
-
-  @Override
-  public Collection<Dependency> getIncomingDependencies(Resource to) {
-    return index.getIncomingEdges(resourceOrProject(to));
-  }
-
-  @Override
-  public Collection<Dependency> getOutgoingDependencies(Resource from) {
-    return index.getOutgoingEdges(resourceOrProject(from));
-  }
-
-  @Override
-  public void saveSource(Resource reference, String source) {
-    // useless since 4.2.
-  }
-
-  @Override
-  public void saveLink(ProjectLink link) {
-    index.addLink(link);
-  }
-
-  @Override
-  public void deleteLink(String key) {
-    index.deleteLink(key);
-  }
-
-  @Override
-  public List<Event> getEvents(Resource resource) {
-    return index.getEvents(resource);
-  }
-
-  @Override
-  public Event createEvent(Resource resource, String name, String description, String category, Date date) {
-    return index.addEvent(resource, name, description, category, date);
-  }
-
-  @Override
-  public void deleteEvent(Event event) {
-    index.deleteEvent(event);
-  }
-
-  private Resource resourceOrProject(Resource resource) {
-    if (resource == null) {
-      return project;
-    }
-    Resource indexedResource = getResource(resource);
-    return indexedResource != null ? indexedResource : resource;
-  }
-
-  @Override
-  public Measure saveMeasure(InputFile inputFile, Metric metric, Double value) {
-    return saveMeasure(getResource(inputFile), metric, value);
-  }
-
-  @Override
-  public Measure saveMeasure(InputFile inputFile, Measure measure) {
-    return saveMeasure(getResource(inputFile), measure);
-  }
-
-  @Override
-  public Resource getResource(InputPath inputPath) {
-    Resource r;
-    if (inputPath instanceof InputDir) {
-      r = Directory.create(((InputDir) inputPath).relativePath());
-    } else if (inputPath instanceof InputFile) {
-      r = File.create(((InputFile) inputPath).relativePath());
-    } else {
-      throw new IllegalArgumentException("Unknow input path type: " + inputPath);
-    }
-    return getResource(r);
-  }
-}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/FormulaDecorator.java b/sonar-batch/src/main/java/org/sonar/batch/FormulaDecorator.java
deleted file mode 100644 (file)
index 75de882..0000000
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * 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.batch;
-
-import org.sonar.api.batch.*;
-import org.sonar.api.measures.FormulaData;
-import org.sonar.api.measures.Measure;
-import org.sonar.api.measures.Metric;
-import org.sonar.api.resources.Project;
-import org.sonar.api.resources.Resource;
-
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.Set;
-
-/**
- * A pre-implementation of a decorator using a simple calculation formula
- * @since 1.11
- */
-public final class FormulaDecorator implements Decorator {
-
-  private Metric metric;
-  private DefaultFormulaContext formulaContext;
-  private Set<Decorator> executeAfterDecorators;
-
-  /**
-   * Creates a FormulaDecorator
-   *
-   * @param metric the metric should have an associated formula
-   * 
-   * @throws IllegalArgumentException if no formula is associated to the metric
-   */
-  public FormulaDecorator(Metric metric, Set<Decorator> executeAfterDecorators) {
-    if (metric.getFormula() == null) {
-      throw new IllegalArgumentException("No formula defined on metric");
-    }
-    this.metric = metric;
-    this.formulaContext = new DefaultFormulaContext(metric);
-    this.executeAfterDecorators = executeAfterDecorators;
-  }
-
-  public FormulaDecorator(Metric metric) {
-    this(metric, Collections.<Decorator>emptySet());
-  }
-
-  /**
-   * {@inheritDoc}
-   */
-  @Override
-  public boolean shouldExecuteOnProject(Project project) {
-    return true;
-  }
-
-  /**
-   * @return metric generated by the decorator
-   */
-  @DependedUpon
-  public Metric generatesMetric() {
-    return metric;
-  }
-
-  /**
-   * @return metric the decorator depends upon
-   */
-  @DependsUpon
-  public List<Metric> dependsUponMetrics() {
-    return metric.getFormula().dependsUponMetrics();
-  }
-
-  @DependsUpon
-  public Collection<Decorator> dependsUponDecorators() {
-    return executeAfterDecorators;
-  }
-
-  /**
-   * {@inheritDoc}
-   */
-  @Override
-  public void decorate(Resource resource, DecoratorContext context) {
-    if (context.getMeasure(metric) != null) {
-      return;
-    }
-
-    formulaContext.setDecoratorContext(context);
-    FormulaData data = new DefaultFormulaData(context);
-    Measure measure = metric.getFormula().calculate(data, formulaContext);
-    if (measure != null) {
-      context.saveMeasure(measure);
-    }
-  }
-
-  @Override
-  public boolean equals(Object o) {
-    if (this == o) {
-      return true;
-    }
-    if (o == null || getClass() != o.getClass()) {
-      return false;
-    }
-    FormulaDecorator that = (FormulaDecorator) o;
-    return !(metric != null ? !metric.equals(that.metric) : that.metric != null);
-  }
-
-  @Override
-  public int hashCode() {
-    return metric != null ? metric.hashCode() : 0;
-  }
-
-  @Override
-  public String toString() {
-    return new StringBuilder().append("f(").append(metric.getKey()).append(")").toString();
-  }
-}
index b345f2e1b0aa3e61692487411328342b0df68d41..21dd83e51ab40a24b94722b8dfee230c02a9efe5 100644 (file)
@@ -41,6 +41,10 @@ import java.util.Date;
 import static org.sonar.api.utils.DateUtils.formatDateTime;
 import static org.sonar.api.utils.DateUtils.longToDate;
 
+/**
+ * Used by views !!
+ *
+ */
 public class ProjectConfigurator implements BatchComponent {
 
   private static final Logger LOG = LoggerFactory.getLogger(ProjectConfigurator.class);
diff --git a/sonar-batch/src/main/java/org/sonar/batch/ResourceFilters.java b/sonar-batch/src/main/java/org/sonar/batch/ResourceFilters.java
deleted file mode 100644 (file)
index 8680300..0000000
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * 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.batch;
-
-import com.google.common.base.Joiner;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.sonar.api.batch.ResourceFilter;
-
-/**
- * @since 1.12
- */
-public class ResourceFilters {
-
-  public ResourceFilters(ResourceFilter[] filters) {
-    this(LoggerFactory.getLogger(ResourceFilters.class), filters);
-  }
-
-  public ResourceFilters() {
-    // perfect
-  }
-
-  ResourceFilters(Logger logger, ResourceFilter[] filters) {
-    check(logger, filters);
-  }
-
-  private void check(Logger logger, ResourceFilter[] filters) {
-    if (filters.length > 0) {
-      logger.warn("ResourceFilters are not supported since version 4.2: " + Joiner.on(", ").join(filters));
-    }
-  }
-}
index f55308c348ce023bdbd48df22c3d39f7c4254f23..8052569765329d81dac901a2846189a3972136e6 100644 (file)
  */
 package org.sonar.batch.bootstrap;
 
+import org.sonar.batch.components.PastSnapshotFinder;
+
+import org.sonar.batch.deprecated.components.PastSnapshotFinderByDate;
+import org.sonar.batch.deprecated.components.PastSnapshotFinderByDays;
+import org.sonar.batch.deprecated.components.PastSnapshotFinderByPreviousAnalysis;
+import org.sonar.batch.deprecated.components.PastSnapshotFinderByPreviousVersion;
+import org.sonar.batch.deprecated.components.PastSnapshotFinderByVersion;
+import org.sonar.batch.repository.user.UserRepository;
 import org.sonar.api.Plugin;
 import org.sonar.api.config.EmailSettings;
 import org.sonar.api.platform.ComponentContainer;
@@ -28,12 +36,6 @@ import org.sonar.api.utils.HttpDownloader;
 import org.sonar.api.utils.System2;
 import org.sonar.api.utils.UriReader;
 import org.sonar.api.utils.internal.TempFolderCleaner;
-import org.sonar.batch.components.PastSnapshotFinder;
-import org.sonar.batch.components.PastSnapshotFinderByDate;
-import org.sonar.batch.components.PastSnapshotFinderByDays;
-import org.sonar.batch.components.PastSnapshotFinderByPreviousAnalysis;
-import org.sonar.batch.components.PastSnapshotFinderByPreviousVersion;
-import org.sonar.batch.components.PastSnapshotFinderByVersion;
 import org.sonar.batch.platform.DefaultServer;
 import org.sonar.batch.repository.DefaultGlobalRepositoriesLoader;
 import org.sonar.batch.repository.DefaultPreviousIssuesLoader;
@@ -42,7 +44,6 @@ import org.sonar.batch.repository.GlobalRepositoriesLoader;
 import org.sonar.batch.repository.GlobalRepositoriesProvider;
 import org.sonar.batch.repository.PreviousIssuesLoader;
 import org.sonar.batch.repository.ProjectRepositoriesLoader;
-import org.sonar.batch.user.UserRepository;
 import org.sonar.core.cluster.NullQueue;
 import org.sonar.core.config.Logback;
 import org.sonar.core.i18n.DefaultI18n;
index d301f1aa476216b042723c76e41b67a96c5a921d..b3fd7e46392271cad6f22b71ec9e4ea738f69b93 100644 (file)
@@ -19,6 +19,8 @@
  */
 package org.sonar.batch.bootstrap;
 
+import org.sonar.batch.components.PastMeasuresLoader;
+
 import org.apache.commons.lang.StringUtils;
 import org.sonar.api.CoreProperties;
 import org.sonar.api.platform.ComponentContainer;
@@ -28,19 +30,21 @@ import org.sonar.api.task.TaskComponent;
 import org.sonar.api.task.TaskDefinition;
 import org.sonar.api.utils.MessageException;
 import org.sonar.batch.bootstrapper.EnvironmentInformation;
-import org.sonar.batch.components.PastMeasuresLoader;
+import org.sonar.batch.deprecated.tasks.ListTask;
+import org.sonar.batch.deprecated.tasks.Tasks;
 import org.sonar.batch.scan.DeprecatedProjectReactorBuilder;
 import org.sonar.batch.scan.ProjectReactorBuilder;
 import org.sonar.batch.scan.ScanTask;
 import org.sonar.batch.scan.measure.DefaultMetricFinder;
 import org.sonar.batch.scan.measure.DeprecatedMetricFinder;
-import org.sonar.batch.tasks.ListTask;
-import org.sonar.batch.tasks.Tasks;
 import org.sonar.core.permission.PermissionFacade;
 import org.sonar.core.resource.DefaultResourcePermissions;
 
 import java.util.Map;
 
+/**
+ * Used by views !!
+ */
 public class TaskContainer extends ComponentContainer {
 
   private final Map<String, String> taskProperties;
index 6cfd61dcabe4a2982c3f3529c3c8cfea463cb4f1..d969e172338df0b65d212aa25597093f0979eeaf 100644 (file)
@@ -38,6 +38,9 @@ import java.util.Collections;
 import java.util.List;
 import java.util.Map;
 
+/**
+ * Can't be moved. Used by devcockpit.
+ */
 public class PastMeasuresLoader implements BatchComponent {
 
   private Map<Integer, Metric> metricByIds;
index 48955f9738f43fcc0c309b85dcbbaa1f88d15f96..a85eb172cf7f88325d43f7193675578c0880ee30 100644 (file)
@@ -26,11 +26,15 @@ import org.sonar.api.database.model.Snapshot;
 import org.sonar.api.utils.DateUtils;
 
 import javax.annotation.Nullable;
+
 import java.util.Calendar;
 import java.util.Date;
 
 import static org.sonar.api.utils.DateUtils.longToDate;
 
+/**
+ * Used by devcockpit
+ */
 public class PastSnapshot {
 
   private int index;
@@ -96,7 +100,7 @@ public class PastSnapshot {
     return this;
   }
 
-  Integer getProjectSnapshotId() {
+  public Integer getProjectSnapshotId() {
     return projectSnapshot != null ? projectSnapshot.getId() : null;
   }
 
index 56263637b14b8cfd102dc2a96d1c8133e5856b8e..745dcbf817b9ecd8dc57fc4e1cbc4341a99fe008 100644 (file)
@@ -27,6 +27,11 @@ import org.sonar.api.BatchExtension;
 import org.sonar.api.CoreProperties;
 import org.sonar.api.config.Settings;
 import org.sonar.api.database.model.Snapshot;
+import org.sonar.batch.deprecated.components.PastSnapshotFinderByDate;
+import org.sonar.batch.deprecated.components.PastSnapshotFinderByDays;
+import org.sonar.batch.deprecated.components.PastSnapshotFinderByPreviousAnalysis;
+import org.sonar.batch.deprecated.components.PastSnapshotFinderByPreviousVersion;
+import org.sonar.batch.deprecated.components.PastSnapshotFinderByVersion;
 
 import javax.annotation.Nullable;
 
@@ -34,6 +39,9 @@ import java.text.ParseException;
 import java.text.SimpleDateFormat;
 import java.util.Date;
 
+/**
+ * Can't be moved since it is used by devcockpit.
+ */
 public class PastSnapshotFinder implements BatchExtension {
 
   private static final Logger LOG = LoggerFactory.getLogger(PastSnapshotFinder.class);
diff --git a/sonar-batch/src/main/java/org/sonar/batch/components/PastSnapshotFinderByDate.java b/sonar-batch/src/main/java/org/sonar/batch/components/PastSnapshotFinderByDate.java
deleted file mode 100644 (file)
index fbae438..0000000
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * 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.batch.components;
-
-import org.sonar.api.BatchExtension;
-import org.sonar.api.CoreProperties;
-import org.sonar.api.database.DatabaseSession;
-import org.sonar.api.database.model.Snapshot;
-import org.sonar.api.resources.Qualifiers;
-import org.sonar.api.utils.DateUtils;
-
-import javax.annotation.CheckForNull;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.List;
-
-import static org.sonar.api.utils.DateUtils.dateToLong;
-
-public class PastSnapshotFinderByDate implements BatchExtension {
-
-  private DatabaseSession session;
-
-  public PastSnapshotFinderByDate(DatabaseSession session) {
-    this.session = session;
-  }
-
-  PastSnapshot findByDate(Snapshot projectSnapshot, Date date) {
-    Integer projectId = projectSnapshot != null ? projectSnapshot.getResourceId() : null;
-    return findByDate(projectId, date);
-  }
-
-  PastSnapshot findByDate(Integer projectId, Date date) {
-    Snapshot snapshot = null;
-    if (projectId != null) {
-      snapshot = findSnapshot(projectId, date);
-    }
-    SimpleDateFormat format = new SimpleDateFormat(DateUtils.DATE_FORMAT);
-    return new PastSnapshot(CoreProperties.TIMEMACHINE_MODE_DATE, date, snapshot).setModeParameter(format.format(date));
-  }
-
-  @CheckForNull
-  private Snapshot findSnapshot(Integer projectId, Date date) {
-    String hql = "from " + Snapshot.class.getSimpleName() + " where createdAt>=:date AND resourceId=:resourceId AND status=:status AND qualifier<>:lib order by createdAt asc";
-    List<Snapshot> snapshots = session.createQuery(hql)
-      .setParameter("date", dateToLong(date))
-      .setParameter("resourceId", projectId)
-      .setParameter("status", Snapshot.STATUS_PROCESSED)
-      .setParameter("lib", Qualifiers.LIBRARY)
-      .setMaxResults(1)
-      .getResultList();
-
-    return snapshots.isEmpty() ? null : snapshots.get(0);
-  }
-}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/components/PastSnapshotFinderByDays.java b/sonar-batch/src/main/java/org/sonar/batch/components/PastSnapshotFinderByDays.java
deleted file mode 100644 (file)
index 0f80268..0000000
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * 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.batch.components;
-
-import org.apache.commons.lang.time.DateUtils;
-import org.sonar.api.BatchExtension;
-import org.sonar.api.CoreProperties;
-import org.sonar.api.database.DatabaseSession;
-import org.sonar.api.database.model.Snapshot;
-import org.sonar.api.resources.Qualifiers;
-
-import javax.annotation.CheckForNull;
-import java.util.Date;
-import java.util.List;
-
-import static org.sonar.api.utils.DateUtils.longToDate;
-
-public class PastSnapshotFinderByDays implements BatchExtension {
-
-  private DatabaseSession session;
-
-  public PastSnapshotFinderByDays(DatabaseSession session) {
-    this.session = session;
-  }
-
-  PastSnapshot findFromDays(Snapshot projectSnapshot, int days) {
-    Date targetDate = DateUtils.addDays(longToDate(projectSnapshot.getCreatedAtMs()), -days);
-    String hql = "from " + Snapshot.class.getSimpleName() + " where resourceId=:resourceId AND status=:status AND createdAt<:date AND qualifier<>:lib order by createdAt asc";
-    List<Snapshot> snapshots = session.createQuery(hql)
-      .setParameter("date", projectSnapshot.getCreatedAtMs())
-      .setParameter("resourceId", projectSnapshot.getResourceId())
-      .setParameter("status", Snapshot.STATUS_PROCESSED)
-      .setParameter("lib", Qualifiers.LIBRARY)
-      .getResultList();
-
-    Snapshot snapshot = getNearestToTarget(snapshots, targetDate);
-    return new PastSnapshot(CoreProperties.TIMEMACHINE_MODE_DAYS, targetDate, snapshot).setModeParameter(String.valueOf(days));
-  }
-
-  @CheckForNull
-  static Snapshot getNearestToTarget(List<Snapshot> snapshots, Date currentDate, int distanceInDays) {
-    Date targetDate = DateUtils.addDays(currentDate, -distanceInDays);
-    return getNearestToTarget(snapshots, targetDate);
-  }
-
-  @CheckForNull
-  static Snapshot getNearestToTarget(List<Snapshot> snapshots, Date targetDate) {
-    long bestDistance = Long.MAX_VALUE;
-    Snapshot nearest = null;
-    for (Snapshot snapshot : snapshots) {
-      long distance = distance(longToDate(snapshot.getCreatedAtMs()), targetDate);
-      if (distance <= bestDistance) {
-        bestDistance = distance;
-        nearest = snapshot;
-      }
-    }
-    return nearest;
-  }
-
-  static long distance(Date d1, Date d2) {
-    return Math.abs(d1.getTime() - d2.getTime());
-  }
-}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/components/PastSnapshotFinderByPreviousAnalysis.java b/sonar-batch/src/main/java/org/sonar/batch/components/PastSnapshotFinderByPreviousAnalysis.java
deleted file mode 100644 (file)
index 5062957..0000000
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * 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.batch.components;
-
-import org.sonar.api.BatchExtension;
-import org.sonar.api.CoreProperties;
-import org.sonar.api.database.DatabaseSession;
-import org.sonar.api.database.model.Snapshot;
-import org.sonar.api.resources.Qualifiers;
-import org.sonar.api.utils.DateUtils;
-
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.List;
-
-import static org.sonar.api.utils.DateUtils.longToDate;
-
-public class PastSnapshotFinderByPreviousAnalysis implements BatchExtension {
-
-  private DatabaseSession session;
-
-  public PastSnapshotFinderByPreviousAnalysis(DatabaseSession session) {
-    this.session = session;
-  }
-
-  PastSnapshot findByPreviousAnalysis(Snapshot projectSnapshot) {
-    String hql = "from " + Snapshot.class.getSimpleName()
-        + " where createdAt<:date AND resourceId=:resourceId AND status=:status and last=:last and qualifier<>:lib order by createdAt desc";
-    List<Snapshot> snapshots = session.createQuery(hql)
-        .setParameter("date", projectSnapshot.getCreatedAtMs())
-        .setParameter("resourceId", projectSnapshot.getResourceId())
-        .setParameter("status", Snapshot.STATUS_PROCESSED)
-        .setParameter("last", true)
-        .setParameter("lib", Qualifiers.LIBRARY)
-        .setMaxResults(1)
-        .getResultList();
-
-    if (snapshots.isEmpty()) {
-      return new PastSnapshot(CoreProperties.TIMEMACHINE_MODE_PREVIOUS_ANALYSIS);
-    }
-    Snapshot snapshot = snapshots.get(0);
-    Date targetDate = longToDate(snapshot.getCreatedAtMs());
-    SimpleDateFormat format = new SimpleDateFormat(DateUtils.DATE_FORMAT);
-    return new PastSnapshot(CoreProperties.TIMEMACHINE_MODE_PREVIOUS_ANALYSIS, targetDate, snapshot).setModeParameter(format.format(targetDate));
-  }
-}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/components/PastSnapshotFinderByPreviousVersion.java b/sonar-batch/src/main/java/org/sonar/batch/components/PastSnapshotFinderByPreviousVersion.java
deleted file mode 100644 (file)
index 6437688..0000000
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * 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.batch.components;
-
-import org.sonar.api.BatchExtension;
-import org.sonar.api.CoreProperties;
-import org.sonar.api.batch.Event;
-import org.sonar.api.database.DatabaseSession;
-import org.sonar.api.database.model.Snapshot;
-
-import java.util.List;
-
-import static org.sonar.api.utils.DateUtils.longToDate;
-
-public class PastSnapshotFinderByPreviousVersion implements BatchExtension {
-
-  private final DatabaseSession session;
-
-  public PastSnapshotFinderByPreviousVersion(DatabaseSession session) {
-    this.session = session;
-  }
-
-  PastSnapshot findByPreviousVersion(Snapshot projectSnapshot) {
-    String currentVersion = projectSnapshot.getVersion();
-    Integer resourceId = projectSnapshot.getResourceId();
-
-    String hql = "from " + Event.class.getSimpleName() +
-      " where name<>:version AND category='Version' AND resourceId=:resourceId ORDER BY date DESC";
-
-    List<Event> events = session.createQuery(hql)
-        .setParameter("version", currentVersion)
-        .setParameter("resourceId", resourceId)
-        .setMaxResults(1)
-        .getResultList();
-
-    if (events.isEmpty()) {
-      return new PastSnapshot(CoreProperties.TIMEMACHINE_MODE_PREVIOUS_VERSION);
-    }
-
-    Event previousVersionEvent = events.get(0);
-    Snapshot snapshot = session.getSingleResult(Snapshot.class, "id", previousVersionEvent.getSnapshot().getId());
-
-    return new PastSnapshot(CoreProperties.TIMEMACHINE_MODE_PREVIOUS_VERSION, longToDate(snapshot.getCreatedAtMs()), snapshot).setModeParameter(snapshot.getVersion());
-  }
-
-}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/components/PastSnapshotFinderByVersion.java b/sonar-batch/src/main/java/org/sonar/batch/components/PastSnapshotFinderByVersion.java
deleted file mode 100644 (file)
index 161bd87..0000000
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * 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.batch.components;
-
-import org.sonar.api.BatchExtension;
-import org.sonar.api.CoreProperties;
-import org.sonar.api.database.DatabaseSession;
-import org.sonar.api.database.model.Snapshot;
-import org.sonar.api.resources.Qualifiers;
-
-import java.util.Date;
-import java.util.List;
-
-import static org.sonar.api.utils.DateUtils.longToDate;
-
-public class PastSnapshotFinderByVersion implements BatchExtension {
-
-  private final DatabaseSession session;
-
-  public PastSnapshotFinderByVersion(DatabaseSession session) {
-    this.session = session;
-  }
-
-  PastSnapshot findByVersion(Snapshot projectSnapshot, String version) {
-    String hql = "from " + Snapshot.class.getSimpleName() + " where version=:version AND resourceId=:resourceId AND status=:status AND qualifier<>:lib order by createdAt desc";
-    List<Snapshot> snapshots = session.createQuery(hql)
-        .setParameter("version", version)
-        .setParameter("resourceId", projectSnapshot.getResourceId())
-        .setParameter("status", Snapshot.STATUS_PROCESSED)
-        .setParameter("lib", Qualifiers.LIBRARY)
-        .setMaxResults(1)
-        .getResultList();
-
-    PastSnapshot result;
-    if (snapshots.isEmpty()) {
-      result = new PastSnapshot(CoreProperties.TIMEMACHINE_MODE_VERSION);
-    } else {
-      Snapshot snapshot = snapshots.get(0);
-      Date targetDate = longToDate(snapshot.getCreatedAtMs());
-      result = new PastSnapshot(CoreProperties.TIMEMACHINE_MODE_VERSION, targetDate, snapshot).setModeParameter(version);
-    }
-    return result;
-  }
-
-}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/components/Period.java b/sonar-batch/src/main/java/org/sonar/batch/components/Period.java
deleted file mode 100644 (file)
index 4e2f15e..0000000
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * 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.batch.components;
-
-import javax.annotation.CheckForNull;
-import javax.annotation.Nullable;
-
-import java.util.Date;
-
-public class Period {
-
-  private int index;
-  private Date date;
-
-  public Period(int index, @Nullable Date date) {
-    this.index = index;
-    this.date = date;
-  }
-
-  public int getIndex() {
-    return index;
-  }
-
-  @CheckForNull
-  public Date getDate() {
-    return date;
-  }
-}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/components/PeriodsDefinition.java b/sonar-batch/src/main/java/org/sonar/batch/components/PeriodsDefinition.java
deleted file mode 100644 (file)
index 6f1eb16..0000000
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * 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.batch.components;
-
-import org.sonar.api.BatchComponent;
-import org.sonar.api.config.Settings;
-import org.sonar.api.database.DatabaseSession;
-import org.sonar.api.database.model.Snapshot;
-import org.sonar.api.resources.Qualifiers;
-import org.sonar.batch.ProjectTree;
-
-import javax.persistence.Query;
-import java.util.List;
-
-import static com.google.common.collect.Lists.newLinkedList;
-import static org.sonar.api.utils.DateUtils.dateToLong;
-
-public class PeriodsDefinition implements BatchComponent {
-
-  public static final int CORE_TENDENCY_DEPTH_DEFAULT_VALUE = 30;
-  private static final int NUMBER_OF_VARIATION_SNAPSHOTS = 5;
-
-  private DatabaseSession session;
-
-  private ProjectTree projectTree;
-  private final Settings settings;
-
-  private List<PastSnapshot> projectPastSnapshots;
-
-  public PeriodsDefinition(DatabaseSession session, ProjectTree projectTree, Settings settings,
-                           PastSnapshotFinder pastSnapshotFinder) {
-    this.session = session;
-    this.projectTree = projectTree;
-    this.settings = settings;
-    initPastSnapshots(pastSnapshotFinder, projectTree.getRootProject().getQualifier());
-  }
-
-  private void initPastSnapshots(PastSnapshotFinder pastSnapshotFinder, String rootQualifier) {
-    Snapshot projectSnapshot = buildProjectSnapshot();
-    projectPastSnapshots = newLinkedList();
-    if (projectSnapshot != null) {
-      for (int index = 1; index <= NUMBER_OF_VARIATION_SNAPSHOTS; index++) {
-        PastSnapshot pastSnapshot = pastSnapshotFinder.find(projectSnapshot, rootQualifier, settings, index);
-        // SONAR-4700 Add a past snapshot only if it exists
-        if (pastSnapshot != null && pastSnapshot.getProjectSnapshot() != null) {
-          projectPastSnapshots.add(pastSnapshot);
-        }
-      }
-    }
-  }
-
-  private Snapshot buildProjectSnapshot() {
-    Query query = session
-      .createNativeQuery("select p.id from projects p where p.kee=:resourceKey and p.qualifier<>:lib and p.enabled=:enabled");
-    query.setParameter("resourceKey", projectTree.getRootProject().getKey());
-    query.setParameter("lib", Qualifiers.LIBRARY);
-    query.setParameter("enabled", Boolean.TRUE);
-
-    Snapshot snapshot = null;
-    Number projectId = session.getSingleResult(query, null);
-    if (projectId != null) {
-      snapshot = new Snapshot();
-      snapshot.setResourceId(projectId.intValue());
-      snapshot.setCreatedAtMs(dateToLong(projectTree.getRootProject().getAnalysisDate()));
-      snapshot.setBuildDateMs(System.currentTimeMillis());
-      snapshot.setVersion(projectTree.getRootProject().getAnalysisVersion());
-    }
-    return snapshot;
-  }
-
-  /**
-   * @return past snapshots of root project
-   */
-  List<PastSnapshot> getRootProjectPastSnapshots() {
-    return projectPastSnapshots;
-  }
-
-}
index 2d4c71bc9c12beaf2e6dea705801c267046c4fad..ec346aa4dccb784d193b7f7c57f98efe00f400bb 100644 (file)
@@ -27,8 +27,11 @@ import org.sonar.api.batch.RequiresDB;
 import org.sonar.api.database.DatabaseSession;
 import org.sonar.api.database.model.Snapshot;
 import org.sonar.api.resources.Qualifiers;
+import org.sonar.batch.deprecated.components.Period;
+import org.sonar.batch.deprecated.components.PeriodsDefinition;
 
 import javax.annotation.CheckForNull;
+
 import java.util.List;
 
 import static com.google.common.collect.Lists.newLinkedList;
index 43046d3763b67db6127659ceaf09d6b90a6b7200..452fe02551cd94aacf285c0d1573bdbed2dc985d 100644 (file)
@@ -20,6 +20,9 @@
 
 package org.sonar.batch.debt;
 
+import org.sonar.batch.components.TimeMachineConfiguration;
+
+import org.sonar.batch.deprecated.components.Period;
 import com.google.common.collect.ImmutableList;
 import org.sonar.api.batch.Decorator;
 import org.sonar.api.batch.DecoratorBarriers;
@@ -35,8 +38,6 @@ import org.sonar.api.measures.MeasureUtils;
 import org.sonar.api.measures.Metric;
 import org.sonar.api.resources.Project;
 import org.sonar.api.resources.Resource;
-import org.sonar.batch.components.Period;
-import org.sonar.batch.components.TimeMachineConfiguration;
 
 import javax.annotation.Nullable;
 
diff --git a/sonar-batch/src/main/java/org/sonar/batch/deprecated/DeprecatedSensorContext.java b/sonar-batch/src/main/java/org/sonar/batch/deprecated/DeprecatedSensorContext.java
new file mode 100644 (file)
index 0000000..e02cadc
--- /dev/null
@@ -0,0 +1,298 @@
+/*
+ * 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.batch.deprecated;
+
+import org.apache.commons.lang.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.sonar.api.batch.AnalysisMode;
+import org.sonar.api.batch.Event;
+import org.sonar.api.batch.SensorContext;
+import org.sonar.api.batch.SonarIndex;
+import org.sonar.api.batch.fs.FileSystem;
+import org.sonar.api.batch.fs.InputDir;
+import org.sonar.api.batch.fs.InputFile;
+import org.sonar.api.batch.fs.InputPath;
+import org.sonar.api.batch.rule.ActiveRules;
+import org.sonar.api.batch.sensor.SensorStorage;
+import org.sonar.api.config.Settings;
+import org.sonar.api.design.Dependency;
+import org.sonar.api.measures.Measure;
+import org.sonar.api.measures.MeasuresFilter;
+import org.sonar.api.measures.Metric;
+import org.sonar.api.resources.Directory;
+import org.sonar.api.resources.File;
+import org.sonar.api.resources.Project;
+import org.sonar.api.resources.ProjectLink;
+import org.sonar.api.resources.Qualifiers;
+import org.sonar.api.resources.Resource;
+import org.sonar.api.rules.Violation;
+import org.sonar.api.utils.SonarException;
+import org.sonar.batch.duplication.BlockCache;
+import org.sonar.batch.duplication.DuplicationCache;
+import org.sonar.batch.index.ComponentDataCache;
+import org.sonar.batch.sensor.DefaultSensorContext;
+import org.sonar.batch.sensor.coverage.CoverageExclusions;
+
+import java.io.Serializable;
+import java.util.Collection;
+import java.util.Date;
+import java.util.List;
+import java.util.Set;
+
+public class DeprecatedSensorContext extends DefaultSensorContext implements SensorContext {
+
+  private static final Logger LOG = LoggerFactory.getLogger(DeprecatedSensorContext.class);
+
+  private final SonarIndex index;
+  private final Project project;
+  private final CoverageExclusions coverageFilter;
+
+  public DeprecatedSensorContext(SonarIndex index, Project project, Settings settings, FileSystem fs, ActiveRules activeRules,
+    AnalysisMode analysisMode, ComponentDataCache componentDataCache, CoverageExclusions coverageFilter,
+    BlockCache blockCache, DuplicationCache duplicationCache, SensorStorage sensorStorage) {
+    super(settings, fs, activeRules, analysisMode, componentDataCache, blockCache, duplicationCache, sensorStorage);
+    this.index = index;
+    this.project = project;
+    this.coverageFilter = coverageFilter;
+  }
+
+  public Project getProject() {
+    return project;
+  }
+
+  @Override
+  public boolean index(Resource resource) {
+    // SONAR-5006
+    if (indexedByCore(resource)) {
+      logWarning();
+      return true;
+    }
+    return index.index(resource);
+  }
+
+  private boolean indexedByCore(Resource resource) {
+    return StringUtils.equals(Qualifiers.DIRECTORY, resource.getQualifier()) ||
+      StringUtils.equals(Qualifiers.FILE, resource.getQualifier());
+  }
+
+  @Override
+  public boolean index(Resource resource, Resource parentReference) {
+    // SONAR-5006
+    if (indexedByCore(resource)) {
+      logWarning();
+      return true;
+    }
+    return index.index(resource, parentReference);
+  }
+
+  private void logWarning() {
+    if (LOG.isDebugEnabled()) {
+      LOG.debug("Plugins are no more responsible for indexing physical resources like directories and files. This is now handled by the platform.", new SonarException(
+        "Plugin should not index physical resources"));
+    }
+  }
+
+  @Override
+  public boolean isExcluded(Resource reference) {
+    return index.isExcluded(reference);
+  }
+
+  @Override
+  public boolean isIndexed(Resource reference, boolean acceptExcluded) {
+    return index.isIndexed(reference, acceptExcluded);
+  }
+
+  @Override
+  public Resource getParent(Resource reference) {
+    return index.getParent(reference);
+  }
+
+  @Override
+  public Collection<Resource> getChildren(Resource reference) {
+    return index.getChildren(reference);
+  }
+
+  @Override
+  public <G extends Serializable> Measure<G> getMeasure(Metric<G> metric) {
+    return index.getMeasure(project, metric);
+  }
+
+  @Override
+  public <M> M getMeasures(MeasuresFilter<M> filter) {
+    return index.getMeasures(project, filter);
+  }
+
+  @Override
+  public Measure saveMeasure(Measure measure) {
+    return index.addMeasure(project, measure);
+  }
+
+  @Override
+  public Measure saveMeasure(Metric metric, Double value) {
+    return index.addMeasure(project, new Measure(metric, value));
+  }
+
+  @Override
+  public <G extends Serializable> Measure<G> getMeasure(Resource resource, Metric<G> metric) {
+    return index.getMeasure(resource, metric);
+  }
+
+  @Override
+  public String saveResource(Resource resource) {
+    Resource persistedResource = index.addResource(resource);
+    if (persistedResource != null) {
+      return persistedResource.getEffectiveKey();
+    }
+    return null;
+  }
+
+  public boolean saveResource(Resource resource, Resource parentReference) {
+    return index.index(resource, parentReference);
+  }
+
+  @Override
+  public Resource getResource(Resource resource) {
+    return index.getResource(resource);
+  }
+
+  @Override
+  public <M> M getMeasures(Resource resource, MeasuresFilter<M> filter) {
+    return index.getMeasures(resource, filter);
+  }
+
+  @Override
+  public Measure saveMeasure(Resource resource, Metric metric, Double value) {
+    return saveMeasure(resource, new Measure(metric, value));
+  }
+
+  @Override
+  public Measure saveMeasure(Resource resource, Measure measure) {
+    Resource resourceOrProject = resourceOrProject(resource);
+    if (coverageFilter.accept(resourceOrProject, measure)) {
+      return index.addMeasure(resourceOrProject, measure);
+    } else {
+      return measure;
+    }
+  }
+
+  @Override
+  public void saveViolation(Violation violation, boolean force) {
+    if (violation.getResource() == null) {
+      violation.setResource(resourceOrProject(violation.getResource()));
+    }
+    index.addViolation(violation, force);
+  }
+
+  @Override
+  public void saveViolation(Violation violation) {
+    saveViolation(violation, false);
+  }
+
+  @Override
+  public void saveViolations(Collection<Violation> violations) {
+    if (violations != null) {
+      for (Violation violation : violations) {
+        saveViolation(violation);
+      }
+    }
+  }
+
+  @Override
+  public Dependency saveDependency(Dependency dependency) {
+    return index.addDependency(dependency);
+  }
+
+  @Override
+  public Set<Dependency> getDependencies() {
+    return index.getDependencies();
+  }
+
+  @Override
+  public Collection<Dependency> getIncomingDependencies(Resource to) {
+    return index.getIncomingEdges(resourceOrProject(to));
+  }
+
+  @Override
+  public Collection<Dependency> getOutgoingDependencies(Resource from) {
+    return index.getOutgoingEdges(resourceOrProject(from));
+  }
+
+  @Override
+  public void saveSource(Resource reference, String source) {
+    // useless since 4.2.
+  }
+
+  @Override
+  public void saveLink(ProjectLink link) {
+    index.addLink(link);
+  }
+
+  @Override
+  public void deleteLink(String key) {
+    index.deleteLink(key);
+  }
+
+  @Override
+  public List<Event> getEvents(Resource resource) {
+    return index.getEvents(resource);
+  }
+
+  @Override
+  public Event createEvent(Resource resource, String name, String description, String category, Date date) {
+    return index.addEvent(resource, name, description, category, date);
+  }
+
+  @Override
+  public void deleteEvent(Event event) {
+    index.deleteEvent(event);
+  }
+
+  private Resource resourceOrProject(Resource resource) {
+    if (resource == null) {
+      return project;
+    }
+    Resource indexedResource = getResource(resource);
+    return indexedResource != null ? indexedResource : resource;
+  }
+
+  @Override
+  public Measure saveMeasure(InputFile inputFile, Metric metric, Double value) {
+    return saveMeasure(getResource(inputFile), metric, value);
+  }
+
+  @Override
+  public Measure saveMeasure(InputFile inputFile, Measure measure) {
+    return saveMeasure(getResource(inputFile), measure);
+  }
+
+  @Override
+  public Resource getResource(InputPath inputPath) {
+    Resource r;
+    if (inputPath instanceof InputDir) {
+      r = Directory.create(((InputDir) inputPath).relativePath());
+    } else if (inputPath instanceof InputFile) {
+      r = File.create(((InputFile) inputPath).relativePath());
+    } else {
+      throw new IllegalArgumentException("Unknow input path type: " + inputPath);
+    }
+    return getResource(r);
+  }
+}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/deprecated/ResourceFilters.java b/sonar-batch/src/main/java/org/sonar/batch/deprecated/ResourceFilters.java
new file mode 100644 (file)
index 0000000..f607135
--- /dev/null
@@ -0,0 +1,49 @@
+/*
+ * 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.batch.deprecated;
+
+import com.google.common.base.Joiner;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.sonar.api.batch.ResourceFilter;
+
+/**
+ * @since 1.12
+ */
+public class ResourceFilters {
+
+  public ResourceFilters(ResourceFilter[] filters) {
+    this(LoggerFactory.getLogger(ResourceFilters.class), filters);
+  }
+
+  public ResourceFilters() {
+    // perfect
+  }
+
+  ResourceFilters(Logger logger, ResourceFilter[] filters) {
+    check(logger, filters);
+  }
+
+  private void check(Logger logger, ResourceFilter[] filters) {
+    if (filters.length > 0) {
+      logger.warn("ResourceFilters are not supported since version 4.2: " + Joiner.on(", ").join(filters));
+    }
+  }
+}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/deprecated/components/DefaultProjectClasspath.java b/sonar-batch/src/main/java/org/sonar/batch/deprecated/components/DefaultProjectClasspath.java
new file mode 100644 (file)
index 0000000..f5a07c9
--- /dev/null
@@ -0,0 +1,63 @@
+/*
+ * 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.batch.deprecated.components;
+
+import com.google.common.collect.Lists;
+import org.apache.maven.project.MavenProject;
+import org.sonar.api.batch.ProjectClasspath;
+import org.sonar.api.batch.bootstrap.ProjectDefinition;
+import org.sonar.api.resources.ProjectFileSystem;
+
+import javax.annotation.Nullable;
+
+import java.io.File;
+import java.util.List;
+
+public class DefaultProjectClasspath extends ProjectClasspath {
+
+  private ProjectDefinition def;
+  private ProjectFileSystem projectFileSystem;
+
+  public DefaultProjectClasspath(ProjectDefinition def, ProjectFileSystem projectFileSystem) {
+    this(def, projectFileSystem, null);
+  }
+
+  public DefaultProjectClasspath(ProjectDefinition def, ProjectFileSystem projectFileSystem, @Nullable MavenProject pom) {
+    super(pom);
+    this.def = def;
+    this.projectFileSystem = projectFileSystem;
+  }
+
+  @Override
+  protected List<File> createElements() {
+    if (pom != null) {
+      return super.createElements();
+    } else {
+      List<File> elements = Lists.newArrayList();
+      for (String path : def.getBinaries()) {
+        elements.add(projectFileSystem.resolvePath(path));
+      }
+      for (String path : def.getLibraries()) {
+        elements.add(projectFileSystem.resolvePath(path));
+      }
+      return elements;
+    }
+  }
+}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/deprecated/components/DefaultResourceCreationLock.java b/sonar-batch/src/main/java/org/sonar/batch/deprecated/components/DefaultResourceCreationLock.java
new file mode 100644 (file)
index 0000000..52ca67c
--- /dev/null
@@ -0,0 +1,40 @@
+/*
+ * 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.batch.deprecated.components;
+
+import org.sonar.api.batch.ResourceCreationLock;
+
+/**
+ * This lock is used to ensure that Sonar resources (files, packages, directories) are not created by buggy plugins
+ * when saving measures/violations on unknown resources.
+ *
+ * @since 2.3
+ * @deprecated not used since 4.2
+ */
+@Deprecated
+public final class DefaultResourceCreationLock implements ResourceCreationLock {
+
+  @Override
+  public void lock() {
+    // does nothing since 4.2. Creation of components (ex-resources) is
+    // the responsibility of core, not plugins
+  }
+
+}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/deprecated/components/DefaultTimeMachine.java b/sonar-batch/src/main/java/org/sonar/batch/deprecated/components/DefaultTimeMachine.java
new file mode 100644 (file)
index 0000000..460f3a6
--- /dev/null
@@ -0,0 +1,177 @@
+/*
+ * 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.batch.deprecated.components;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import org.sonar.api.batch.TimeMachine;
+import org.sonar.api.batch.TimeMachineQuery;
+import org.sonar.api.database.DatabaseSession;
+import org.sonar.api.database.model.MeasureModel;
+import org.sonar.api.database.model.Snapshot;
+import org.sonar.api.measures.Measure;
+import org.sonar.api.measures.Metric;
+import org.sonar.api.measures.MetricFinder;
+import org.sonar.api.resources.Qualifiers;
+import org.sonar.api.resources.Resource;
+import org.sonar.api.technicaldebt.batch.Characteristic;
+import org.sonar.api.technicaldebt.batch.TechnicalDebtModel;
+import org.sonar.batch.index.DefaultIndex;
+
+import javax.annotation.Nullable;
+import javax.persistence.Query;
+import java.util.*;
+
+import static org.sonar.api.utils.DateUtils.dateToLong;
+
+public class DefaultTimeMachine implements TimeMachine {
+
+  private DatabaseSession session;
+  private DefaultIndex index;
+  private MetricFinder metricFinder;
+  private TechnicalDebtModel techDebtModel;
+
+  public DefaultTimeMachine(DatabaseSession session, DefaultIndex index, MetricFinder metricFinder, TechnicalDebtModel techDebtModel) {
+    this.session = session;
+    this.index = index;
+    this.metricFinder = metricFinder;
+    this.techDebtModel = techDebtModel;
+  }
+
+  @Override
+  public List<Measure> getMeasures(TimeMachineQuery query) {
+    Map<Integer, Metric> metricById = getMetricsById(query);
+
+    List<Object[]> objects = execute(query, true, metricById.keySet());
+    List<Measure> result = Lists.newArrayList();
+
+    for (Object[] object : objects) {
+      MeasureModel model = (MeasureModel) object[0];
+      Integer characteristicId = model.getCharacteristicId();
+      Characteristic characteristic = techDebtModel.characteristicById(characteristicId);
+      Measure measure = toMeasure(model, metricById.get(model.getMetricId()), characteristic);
+      measure.setDate(new Date((Long) object[1]));
+      result.add(measure);
+    }
+    return result;
+  }
+
+  @Override
+  public List<Object[]> getMeasuresFields(TimeMachineQuery query) {
+    Map<Integer, Metric> metricById = getMetricsById(query);
+    List<Object[]> rows = execute(query, false, metricById.keySet());
+    for (Object[] fields : rows) {
+      fields[1] = metricById.get(fields[1]);
+    }
+    return rows;
+  }
+
+  protected List<Object[]> execute(TimeMachineQuery query, boolean selectAllFields, Set<Integer> metricIds) {
+    Resource resource = query.getResource();
+    if (resource != null && resource.getId() == null) {
+      resource = index.getResource(query.getResource());
+    }
+    if (resource == null) {
+      return Collections.emptyList();
+    }
+
+    StringBuilder sb = new StringBuilder();
+    Map<String, Object> params = Maps.newHashMap();
+
+    if (selectAllFields) {
+      sb.append("SELECT m, s.createdAt ");
+    } else {
+      sb.append("SELECT s.createdAt, m.metricId, m.value ");
+    }
+    sb.append(" FROM ")
+      .append(MeasureModel.class.getSimpleName())
+      .append(" m, ")
+      .append(Snapshot.class.getSimpleName())
+      .append(" s WHERE m.snapshotId=s.id AND s.resourceId=:resourceId AND s.status=:status AND s.qualifier<>:lib");
+    params.put("resourceId", resource.getId());
+    params.put("status", Snapshot.STATUS_PROCESSED);
+    params.put("lib", Qualifiers.LIBRARY);
+
+    sb.append(" AND m.characteristicId IS NULL");
+    sb.append(" AND m.personId IS NULL");
+    sb.append(" AND m.ruleId IS NULL AND m.rulePriority IS NULL");
+    if (!metricIds.isEmpty()) {
+      sb.append(" AND m.metricId IN (:metricIds) ");
+      params.put("metricIds", metricIds);
+    }
+    if (query.isFromCurrentAnalysis()) {
+      sb.append(" AND s.createdAt>=:from ");
+      params.put("from", index.getProject().getAnalysisDate());
+
+    } else if (query.getFrom() != null) {
+      sb.append(" AND s.createdAt>=:from ");
+      params.put("from", dateToLong(query.getFrom()));
+    }
+    if (query.isToCurrentAnalysis()) {
+      sb.append(" AND s.createdAt<=:to ");
+      params.put("to", dateToLong(index.getProject().getAnalysisDate()));
+
+    } else if (query.getTo() != null) {
+      sb.append(" AND s.createdAt<=:to ");
+      params.put("to", dateToLong(query.getTo()));
+    }
+    if (query.isOnlyLastAnalysis()) {
+      sb.append(" AND s.last=:last ");
+      params.put("last", Boolean.TRUE);
+    }
+    sb.append(" ORDER BY s.createdAt ");
+
+    Query jpaQuery = session.createQuery(sb.toString());
+
+    for (Map.Entry<String, Object> entry : params.entrySet()) {
+      jpaQuery.setParameter(entry.getKey(), entry.getValue());
+    }
+    return jpaQuery.getResultList();
+  }
+
+  public Map<Integer, Metric> getMetricsById(TimeMachineQuery query) {
+    Collection<Metric> metrics = metricFinder.findAll(query.getMetricKeys());
+    Map<Integer, Metric> result = Maps.newHashMap();
+    for (Metric metric : metrics) {
+      result.put(metric.getId(), metric);
+    }
+    return result;
+  }
+
+  static Measure toMeasure(MeasureModel model, Metric metric, @Nullable Characteristic characteristic) {
+    // NOTE: measures on rule are not supported
+    Measure measure = new Measure(metric);
+    measure.setDescription(model.getDescription());
+    measure.setValue(model.getValue());
+    measure.setData(model.getData(metric));
+    measure.setAlertStatus(model.getAlertStatus());
+    measure.setAlertText(model.getAlertText());
+    measure.setTendency(model.getTendency());
+    measure.setVariation1(model.getVariationValue1());
+    measure.setVariation2(model.getVariationValue2());
+    measure.setVariation3(model.getVariationValue3());
+    measure.setVariation4(model.getVariationValue4());
+    measure.setVariation5(model.getVariationValue5());
+    measure.setUrl(model.getUrl());
+    measure.setCharacteristic(characteristic);
+    measure.setPersonId(model.getPersonId());
+    return measure;
+  }
+}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/deprecated/components/PastSnapshotFinderByDate.java b/sonar-batch/src/main/java/org/sonar/batch/deprecated/components/PastSnapshotFinderByDate.java
new file mode 100644 (file)
index 0000000..5a5fff1
--- /dev/null
@@ -0,0 +1,73 @@
+/*
+ * 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.batch.deprecated.components;
+
+import org.sonar.api.BatchExtension;
+import org.sonar.api.CoreProperties;
+import org.sonar.api.database.DatabaseSession;
+import org.sonar.api.database.model.Snapshot;
+import org.sonar.api.resources.Qualifiers;
+import org.sonar.api.utils.DateUtils;
+import org.sonar.batch.components.PastSnapshot;
+
+import javax.annotation.CheckForNull;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.List;
+
+import static org.sonar.api.utils.DateUtils.dateToLong;
+
+public class PastSnapshotFinderByDate implements BatchExtension {
+
+  private DatabaseSession session;
+
+  public PastSnapshotFinderByDate(DatabaseSession session) {
+    this.session = session;
+  }
+
+  public PastSnapshot findByDate(Snapshot projectSnapshot, Date date) {
+    Integer projectId = projectSnapshot != null ? projectSnapshot.getResourceId() : null;
+    return findByDate(projectId, date);
+  }
+
+  PastSnapshot findByDate(Integer projectId, Date date) {
+    Snapshot snapshot = null;
+    if (projectId != null) {
+      snapshot = findSnapshot(projectId, date);
+    }
+    SimpleDateFormat format = new SimpleDateFormat(DateUtils.DATE_FORMAT);
+    return new PastSnapshot(CoreProperties.TIMEMACHINE_MODE_DATE, date, snapshot).setModeParameter(format.format(date));
+  }
+
+  @CheckForNull
+  private Snapshot findSnapshot(Integer projectId, Date date) {
+    String hql = "from " + Snapshot.class.getSimpleName() + " where createdAt>=:date AND resourceId=:resourceId AND status=:status AND qualifier<>:lib order by createdAt asc";
+    List<Snapshot> snapshots = session.createQuery(hql)
+      .setParameter("date", dateToLong(date))
+      .setParameter("resourceId", projectId)
+      .setParameter("status", Snapshot.STATUS_PROCESSED)
+      .setParameter("lib", Qualifiers.LIBRARY)
+      .setMaxResults(1)
+      .getResultList();
+
+    return snapshots.isEmpty() ? null : snapshots.get(0);
+  }
+}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/deprecated/components/PastSnapshotFinderByDays.java b/sonar-batch/src/main/java/org/sonar/batch/deprecated/components/PastSnapshotFinderByDays.java
new file mode 100644 (file)
index 0000000..5183236
--- /dev/null
@@ -0,0 +1,82 @@
+/*
+ * 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.batch.deprecated.components;
+
+import org.apache.commons.lang.time.DateUtils;
+import org.sonar.api.BatchExtension;
+import org.sonar.api.CoreProperties;
+import org.sonar.api.database.DatabaseSession;
+import org.sonar.api.database.model.Snapshot;
+import org.sonar.api.resources.Qualifiers;
+import org.sonar.batch.components.PastSnapshot;
+
+import javax.annotation.CheckForNull;
+
+import java.util.Date;
+import java.util.List;
+
+import static org.sonar.api.utils.DateUtils.longToDate;
+
+public class PastSnapshotFinderByDays implements BatchExtension {
+
+  private DatabaseSession session;
+
+  public PastSnapshotFinderByDays(DatabaseSession session) {
+    this.session = session;
+  }
+
+  public PastSnapshot findFromDays(Snapshot projectSnapshot, int days) {
+    Date targetDate = DateUtils.addDays(longToDate(projectSnapshot.getCreatedAtMs()), -days);
+    String hql = "from " + Snapshot.class.getSimpleName() + " where resourceId=:resourceId AND status=:status AND createdAt<:date AND qualifier<>:lib order by createdAt asc";
+    List<Snapshot> snapshots = session.createQuery(hql)
+      .setParameter("date", projectSnapshot.getCreatedAtMs())
+      .setParameter("resourceId", projectSnapshot.getResourceId())
+      .setParameter("status", Snapshot.STATUS_PROCESSED)
+      .setParameter("lib", Qualifiers.LIBRARY)
+      .getResultList();
+
+    Snapshot snapshot = getNearestToTarget(snapshots, targetDate);
+    return new PastSnapshot(CoreProperties.TIMEMACHINE_MODE_DAYS, targetDate, snapshot).setModeParameter(String.valueOf(days));
+  }
+
+  @CheckForNull
+  static Snapshot getNearestToTarget(List<Snapshot> snapshots, Date currentDate, int distanceInDays) {
+    Date targetDate = DateUtils.addDays(currentDate, -distanceInDays);
+    return getNearestToTarget(snapshots, targetDate);
+  }
+
+  @CheckForNull
+  static Snapshot getNearestToTarget(List<Snapshot> snapshots, Date targetDate) {
+    long bestDistance = Long.MAX_VALUE;
+    Snapshot nearest = null;
+    for (Snapshot snapshot : snapshots) {
+      long distance = distance(longToDate(snapshot.getCreatedAtMs()), targetDate);
+      if (distance <= bestDistance) {
+        bestDistance = distance;
+        nearest = snapshot;
+      }
+    }
+    return nearest;
+  }
+
+  static long distance(Date d1, Date d2) {
+    return Math.abs(d1.getTime() - d2.getTime());
+  }
+}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/deprecated/components/PastSnapshotFinderByPreviousAnalysis.java b/sonar-batch/src/main/java/org/sonar/batch/deprecated/components/PastSnapshotFinderByPreviousAnalysis.java
new file mode 100644 (file)
index 0000000..e770975
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+ * 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.batch.deprecated.components;
+
+import org.sonar.api.BatchExtension;
+import org.sonar.api.CoreProperties;
+import org.sonar.api.database.DatabaseSession;
+import org.sonar.api.database.model.Snapshot;
+import org.sonar.api.resources.Qualifiers;
+import org.sonar.api.utils.DateUtils;
+import org.sonar.batch.components.PastSnapshot;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.List;
+
+import static org.sonar.api.utils.DateUtils.longToDate;
+
+public class PastSnapshotFinderByPreviousAnalysis implements BatchExtension {
+
+  private DatabaseSession session;
+
+  public PastSnapshotFinderByPreviousAnalysis(DatabaseSession session) {
+    this.session = session;
+  }
+
+  public PastSnapshot findByPreviousAnalysis(Snapshot projectSnapshot) {
+    String hql = "from " + Snapshot.class.getSimpleName()
+      + " where createdAt<:date AND resourceId=:resourceId AND status=:status and last=:last and qualifier<>:lib order by createdAt desc";
+    List<Snapshot> snapshots = session.createQuery(hql)
+      .setParameter("date", projectSnapshot.getCreatedAtMs())
+      .setParameter("resourceId", projectSnapshot.getResourceId())
+      .setParameter("status", Snapshot.STATUS_PROCESSED)
+      .setParameter("last", true)
+      .setParameter("lib", Qualifiers.LIBRARY)
+      .setMaxResults(1)
+      .getResultList();
+
+    if (snapshots.isEmpty()) {
+      return new PastSnapshot(CoreProperties.TIMEMACHINE_MODE_PREVIOUS_ANALYSIS);
+    }
+    Snapshot snapshot = snapshots.get(0);
+    Date targetDate = longToDate(snapshot.getCreatedAtMs());
+    SimpleDateFormat format = new SimpleDateFormat(DateUtils.DATE_FORMAT);
+    return new PastSnapshot(CoreProperties.TIMEMACHINE_MODE_PREVIOUS_ANALYSIS, targetDate, snapshot).setModeParameter(format.format(targetDate));
+  }
+}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/deprecated/components/PastSnapshotFinderByPreviousVersion.java b/sonar-batch/src/main/java/org/sonar/batch/deprecated/components/PastSnapshotFinderByPreviousVersion.java
new file mode 100644 (file)
index 0000000..0125fa7
--- /dev/null
@@ -0,0 +1,65 @@
+/*
+ * 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.batch.deprecated.components;
+
+import org.sonar.batch.components.PastSnapshot;
+
+import org.sonar.api.BatchExtension;
+import org.sonar.api.CoreProperties;
+import org.sonar.api.batch.Event;
+import org.sonar.api.database.DatabaseSession;
+import org.sonar.api.database.model.Snapshot;
+
+import java.util.List;
+
+import static org.sonar.api.utils.DateUtils.longToDate;
+
+public class PastSnapshotFinderByPreviousVersion implements BatchExtension {
+
+  private final DatabaseSession session;
+
+  public PastSnapshotFinderByPreviousVersion(DatabaseSession session) {
+    this.session = session;
+  }
+
+  public PastSnapshot findByPreviousVersion(Snapshot projectSnapshot) {
+    String currentVersion = projectSnapshot.getVersion();
+    Integer resourceId = projectSnapshot.getResourceId();
+
+    String hql = "from " + Event.class.getSimpleName() +
+      " where name<>:version AND category='Version' AND resourceId=:resourceId ORDER BY date DESC";
+
+    List<Event> events = session.createQuery(hql)
+      .setParameter("version", currentVersion)
+      .setParameter("resourceId", resourceId)
+      .setMaxResults(1)
+      .getResultList();
+
+    if (events.isEmpty()) {
+      return new PastSnapshot(CoreProperties.TIMEMACHINE_MODE_PREVIOUS_VERSION);
+    }
+
+    Event previousVersionEvent = events.get(0);
+    Snapshot snapshot = session.getSingleResult(Snapshot.class, "id", previousVersionEvent.getSnapshot().getId());
+
+    return new PastSnapshot(CoreProperties.TIMEMACHINE_MODE_PREVIOUS_VERSION, longToDate(snapshot.getCreatedAtMs()), snapshot).setModeParameter(snapshot.getVersion());
+  }
+
+}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/deprecated/components/PastSnapshotFinderByVersion.java b/sonar-batch/src/main/java/org/sonar/batch/deprecated/components/PastSnapshotFinderByVersion.java
new file mode 100644 (file)
index 0000000..c6f5423
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+ * 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.batch.deprecated.components;
+
+import org.sonar.batch.components.PastSnapshot;
+
+import org.sonar.api.BatchExtension;
+import org.sonar.api.CoreProperties;
+import org.sonar.api.database.DatabaseSession;
+import org.sonar.api.database.model.Snapshot;
+import org.sonar.api.resources.Qualifiers;
+
+import java.util.Date;
+import java.util.List;
+
+import static org.sonar.api.utils.DateUtils.longToDate;
+
+public class PastSnapshotFinderByVersion implements BatchExtension {
+
+  private final DatabaseSession session;
+
+  public PastSnapshotFinderByVersion(DatabaseSession session) {
+    this.session = session;
+  }
+
+  public PastSnapshot findByVersion(Snapshot projectSnapshot, String version) {
+    String hql = "from " + Snapshot.class.getSimpleName() + " where version=:version AND resourceId=:resourceId AND status=:status AND qualifier<>:lib order by createdAt desc";
+    List<Snapshot> snapshots = session.createQuery(hql)
+      .setParameter("version", version)
+      .setParameter("resourceId", projectSnapshot.getResourceId())
+      .setParameter("status", Snapshot.STATUS_PROCESSED)
+      .setParameter("lib", Qualifiers.LIBRARY)
+      .setMaxResults(1)
+      .getResultList();
+
+    PastSnapshot result;
+    if (snapshots.isEmpty()) {
+      result = new PastSnapshot(CoreProperties.TIMEMACHINE_MODE_VERSION);
+    } else {
+      Snapshot snapshot = snapshots.get(0);
+      Date targetDate = longToDate(snapshot.getCreatedAtMs());
+      result = new PastSnapshot(CoreProperties.TIMEMACHINE_MODE_VERSION, targetDate, snapshot).setModeParameter(version);
+    }
+    return result;
+  }
+
+}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/deprecated/components/Period.java b/sonar-batch/src/main/java/org/sonar/batch/deprecated/components/Period.java
new file mode 100644 (file)
index 0000000..45ca282
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+ * 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.batch.deprecated.components;
+
+import javax.annotation.CheckForNull;
+import javax.annotation.Nullable;
+
+import java.util.Date;
+
+public class Period {
+
+  private int index;
+  private Date date;
+
+  public Period(int index, @Nullable Date date) {
+    this.index = index;
+    this.date = date;
+  }
+
+  public int getIndex() {
+    return index;
+  }
+
+  @CheckForNull
+  public Date getDate() {
+    return date;
+  }
+}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/deprecated/components/PeriodsDefinition.java b/sonar-batch/src/main/java/org/sonar/batch/deprecated/components/PeriodsDefinition.java
new file mode 100644 (file)
index 0000000..b235129
--- /dev/null
@@ -0,0 +1,98 @@
+/*
+ * 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.batch.deprecated.components;
+
+import org.sonar.api.BatchComponent;
+import org.sonar.api.config.Settings;
+import org.sonar.api.database.DatabaseSession;
+import org.sonar.api.database.model.Snapshot;
+import org.sonar.api.resources.Qualifiers;
+import org.sonar.batch.ProjectTree;
+import org.sonar.batch.components.PastSnapshot;
+import org.sonar.batch.components.PastSnapshotFinder;
+
+import javax.persistence.Query;
+import java.util.List;
+
+import static com.google.common.collect.Lists.newLinkedList;
+import static org.sonar.api.utils.DateUtils.dateToLong;
+
+public class PeriodsDefinition implements BatchComponent {
+
+  public static final int CORE_TENDENCY_DEPTH_DEFAULT_VALUE = 30;
+  private static final int NUMBER_OF_VARIATION_SNAPSHOTS = 5;
+
+  private DatabaseSession session;
+
+  private ProjectTree projectTree;
+  private final Settings settings;
+
+  private List<PastSnapshot> projectPastSnapshots;
+
+  public PeriodsDefinition(DatabaseSession session, ProjectTree projectTree, Settings settings,
+    PastSnapshotFinder pastSnapshotFinder) {
+    this.session = session;
+    this.projectTree = projectTree;
+    this.settings = settings;
+    initPastSnapshots(pastSnapshotFinder, projectTree.getRootProject().getQualifier());
+  }
+
+  private void initPastSnapshots(PastSnapshotFinder pastSnapshotFinder, String rootQualifier) {
+    Snapshot projectSnapshot = buildProjectSnapshot();
+    projectPastSnapshots = newLinkedList();
+    if (projectSnapshot != null) {
+      for (int index = 1; index <= NUMBER_OF_VARIATION_SNAPSHOTS; index++) {
+        PastSnapshot pastSnapshot = pastSnapshotFinder.find(projectSnapshot, rootQualifier, settings, index);
+        // SONAR-4700 Add a past snapshot only if it exists
+        if (pastSnapshot != null && pastSnapshot.getProjectSnapshot() != null) {
+          projectPastSnapshots.add(pastSnapshot);
+        }
+      }
+    }
+  }
+
+  private Snapshot buildProjectSnapshot() {
+    Query query = session
+      .createNativeQuery("select p.id from projects p where p.kee=:resourceKey and p.qualifier<>:lib and p.enabled=:enabled");
+    query.setParameter("resourceKey", projectTree.getRootProject().getKey());
+    query.setParameter("lib", Qualifiers.LIBRARY);
+    query.setParameter("enabled", Boolean.TRUE);
+
+    Snapshot snapshot = null;
+    Number projectId = session.getSingleResult(query, null);
+    if (projectId != null) {
+      snapshot = new Snapshot();
+      snapshot.setResourceId(projectId.intValue());
+      snapshot.setCreatedAtMs(dateToLong(projectTree.getRootProject().getAnalysisDate()));
+      snapshot.setBuildDateMs(System.currentTimeMillis());
+      snapshot.setVersion(projectTree.getRootProject().getAnalysisVersion());
+    }
+    return snapshot;
+  }
+
+  /**
+   * @return past snapshots of root project
+   */
+  public List<PastSnapshot> getRootProjectPastSnapshots() {
+    return projectPastSnapshots;
+  }
+
+}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/deprecated/components/package-info.java b/sonar-batch/src/main/java/org/sonar/batch/deprecated/components/package-info.java
new file mode 100644 (file)
index 0000000..65baa1e
--- /dev/null
@@ -0,0 +1,23 @@
+/*
+ * 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.
+ */
+@ParametersAreNonnullByDefault
+package org.sonar.batch.deprecated.components;
+
+import javax.annotation.ParametersAreNonnullByDefault;
diff --git a/sonar-batch/src/main/java/org/sonar/batch/deprecated/decorator/DecoratorsSelector.java b/sonar-batch/src/main/java/org/sonar/batch/deprecated/decorator/DecoratorsSelector.java
new file mode 100644 (file)
index 0000000..c50574f
--- /dev/null
@@ -0,0 +1,65 @@
+/*
+ * 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.batch.deprecated.decorator;
+
+import com.google.common.collect.HashMultimap;
+import com.google.common.collect.SetMultimap;
+import org.sonar.api.batch.Decorator;
+import org.sonar.api.measures.Metric;
+import org.sonar.api.resources.Project;
+import org.sonar.batch.bootstrap.BatchExtensionDictionnary;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+public final class DecoratorsSelector {
+
+  private BatchExtensionDictionnary batchExtDictionnary;
+
+  public DecoratorsSelector(BatchExtensionDictionnary dictionnary) {
+    this.batchExtDictionnary = dictionnary;
+  }
+
+  public Collection<Decorator> select(Project project) {
+    List<Decorator> decorators = new ArrayList<Decorator>(batchExtDictionnary.select(Decorator.class, project, false, null));
+    SetMultimap<Metric, Decorator> decoratorsByGeneratedMetric = getDecoratorsByMetric(decorators);
+    for (Metric metric : batchExtDictionnary.select(Metric.class, null, false, null)) {
+      if (metric.getFormula() != null) {
+        decorators.add(new FormulaDecorator(metric, decoratorsByGeneratedMetric.get(metric)));
+      }
+    }
+
+    return batchExtDictionnary.sort(decorators);
+  }
+
+  private SetMultimap<Metric, Decorator> getDecoratorsByMetric(Collection<Decorator> pluginDecorators) {
+    SetMultimap<Metric, Decorator> decoratorsByGeneratedMetric = HashMultimap.create();
+    for (Decorator decorator : pluginDecorators) {
+      List dependents = batchExtDictionnary.getDependents(decorator);
+      for (Object dependent : dependents) {
+        if (dependent instanceof Metric) {
+          decoratorsByGeneratedMetric.put((Metric) dependent, decorator);
+        }
+      }
+    }
+    return decoratorsByGeneratedMetric;
+  }
+}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/deprecated/decorator/DefaultDecoratorContext.java b/sonar-batch/src/main/java/org/sonar/batch/deprecated/decorator/DefaultDecoratorContext.java
new file mode 100644 (file)
index 0000000..1740a1a
--- /dev/null
@@ -0,0 +1,258 @@
+/*
+ * 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.batch.deprecated.decorator;
+
+import com.google.common.collect.ArrayListMultimap;
+import com.google.common.collect.ListMultimap;
+import com.google.common.collect.Lists;
+import org.sonar.api.batch.DecoratorContext;
+import org.sonar.api.batch.Event;
+import org.sonar.api.batch.SonarIndex;
+import org.sonar.api.batch.sensor.duplication.DuplicationGroup;
+import org.sonar.api.design.Dependency;
+import org.sonar.api.measures.CoreMetrics;
+import org.sonar.api.measures.Measure;
+import org.sonar.api.measures.MeasuresFilter;
+import org.sonar.api.measures.MeasuresFilters;
+import org.sonar.api.measures.Metric;
+import org.sonar.api.measures.MetricFinder;
+import org.sonar.api.resources.Project;
+import org.sonar.api.resources.Resource;
+import org.sonar.api.rules.Violation;
+import org.sonar.api.utils.SonarException;
+import org.sonar.batch.duplication.DuplicationCache;
+import org.sonar.batch.duplication.DuplicationUtils;
+import org.sonar.batch.scan.measure.MeasureCache;
+import org.sonar.batch.sensor.coverage.CoverageExclusions;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Date;
+import java.util.List;
+import java.util.Set;
+
+public class DefaultDecoratorContext implements DecoratorContext {
+
+  private static final String SAVE_MEASURE_METHOD = "saveMeasure";
+  private SonarIndex sonarIndex;
+  private Resource resource;
+  private boolean readOnly = false;
+
+  private List<DecoratorContext> childrenContexts;
+
+  private ListMultimap<String, Measure> measuresByMetric = ArrayListMultimap.create();
+  private MeasureCache measureCache;
+  private MetricFinder metricFinder;
+  private final DuplicationCache duplicationCache;
+  private final CoverageExclusions coverageFilter;
+
+  public DefaultDecoratorContext(Resource resource,
+    SonarIndex index,
+    List<DecoratorContext> childrenContexts,
+    MeasureCache measureCache, MetricFinder metricFinder, DuplicationCache duplicationCache, CoverageExclusions coverageFilter) {
+    this.sonarIndex = index;
+    this.resource = resource;
+    this.childrenContexts = childrenContexts;
+    this.measureCache = measureCache;
+    this.metricFinder = metricFinder;
+    this.duplicationCache = duplicationCache;
+    this.coverageFilter = coverageFilter;
+  }
+
+  public void init() {
+    Iterable<Measure> unfiltered = measureCache.byResource(resource);
+    for (Measure measure : unfiltered) {
+      measuresByMetric.put(measure.getMetricKey(), measure);
+    }
+  }
+
+  public DefaultDecoratorContext end() {
+    readOnly = true;
+    childrenContexts = null;
+    for (Measure measure : measuresByMetric.values()) {
+      measureCache.put(resource, measure);
+    }
+    return this;
+  }
+
+  @Override
+  public Project getProject() {
+    return sonarIndex.getProject();
+  }
+
+  @Override
+  public List<DecoratorContext> getChildren() {
+    checkReadOnly("getModules");
+    return childrenContexts;
+  }
+
+  private void checkReadOnly(String methodName) {
+    if (readOnly) {
+      throw new IllegalStateException("Method DecoratorContext." + methodName + "() can not be executed on children.");
+    }
+  }
+
+  @Override
+  public <M> M getMeasures(MeasuresFilter<M> filter) {
+    Collection<Measure> unfiltered;
+    if (filter instanceof MeasuresFilters.MetricFilter) {
+      unfiltered = getMeasuresOfASingleMetric(filter);
+    } else {
+      unfiltered = measuresByMetric.values();
+    }
+    return filter.filter(unfiltered);
+  }
+
+  private <M> Collection<Measure> getMeasuresOfASingleMetric(MeasuresFilter<M> filter) {
+    Collection<Measure> unfiltered;
+    String metricKey = ((MeasuresFilters.MetricFilter<M>) filter).filterOnMetricKey();
+    if (CoreMetrics.DUPLICATIONS_DATA_KEY.equals(metricKey)) {
+      // Hack for SONAR-5765
+      List<DuplicationGroup> group = duplicationCache.byComponent(resource.getEffectiveKey());
+      if (group != null) {
+        unfiltered = Arrays.asList(new Measure(CoreMetrics.DUPLICATIONS_DATA, DuplicationUtils.toXml(group)));
+      } else {
+        unfiltered = Collections.<Measure>emptyList();
+      }
+    } else {
+      // optimization
+      unfiltered = measuresByMetric.get(metricKey);
+    }
+    return unfiltered;
+  }
+
+  @Override
+  public Measure getMeasure(Metric metric) {
+    return getMeasures(MeasuresFilters.metric(metric));
+  }
+
+  @Override
+  public Collection<Measure> getChildrenMeasures(MeasuresFilter filter) {
+    List<Measure> result = Lists.newArrayList();
+    for (DecoratorContext childContext : childrenContexts) {
+      Object childResult = childContext.getMeasures(filter);
+      if (childResult != null) {
+        if (childResult instanceof Collection) {
+          result.addAll((Collection) childResult);
+        } else {
+          result.add((Measure) childResult);
+        }
+      }
+    }
+    return result;
+  }
+
+  @Override
+  public Collection<Measure> getChildrenMeasures(Metric metric) {
+    return getChildrenMeasures(MeasuresFilters.metric(metric));
+  }
+
+  @Override
+  public Resource getResource() {
+    return resource;
+  }
+
+  @Override
+  public DecoratorContext saveMeasure(Measure measure) {
+    checkReadOnly(SAVE_MEASURE_METHOD);
+    Metric metric = metricFinder.findByKey(measure.getMetricKey());
+    if (metric == null) {
+      throw new SonarException("Unknown metric: " + measure.getMetricKey());
+    }
+    measure.setMetric(metric);
+    if (coverageFilter.accept(resource, measure)) {
+      List<Measure> metricMeasures = measuresByMetric.get(measure.getMetricKey());
+
+      boolean add = true;
+      if (metricMeasures != null) {
+        int index = metricMeasures.indexOf(measure);
+        if (index > -1) {
+          if (metricMeasures.get(index) == measure) {
+            add = false;
+          } else {
+            throw new SonarException("Can not add twice the same measure on " + resource + ": " + measure);
+          }
+        }
+      }
+      if (add) {
+        measuresByMetric.put(measure.getMetricKey(), measure);
+      }
+    }
+    return this;
+  }
+
+  @Override
+  public DecoratorContext saveMeasure(Metric metric, Double value) {
+    checkReadOnly(SAVE_MEASURE_METHOD);
+    saveMeasure(new Measure(metric, value));
+    return this;
+  }
+
+  @Override
+  public Dependency saveDependency(Dependency dependency) {
+    checkReadOnly("addDependency");
+    return sonarIndex.addDependency(dependency);
+  }
+
+  @Override
+  public Set<Dependency> getDependencies() {
+    return sonarIndex.getDependencies();
+  }
+
+  @Override
+  public Collection<Dependency> getIncomingDependencies() {
+    return sonarIndex.getIncomingEdges(resource);
+  }
+
+  @Override
+  public Collection<Dependency> getOutgoingDependencies() {
+    return sonarIndex.getOutgoingEdges(resource);
+  }
+
+  @Override
+  public List<Event> getEvents() {
+    return sonarIndex.getEvents(resource);
+  }
+
+  @Override
+  public Event createEvent(String name, String description, String category, Date date) {
+    return sonarIndex.addEvent(resource, name, description, category, date);
+  }
+
+  @Override
+  public void deleteEvent(Event event) {
+    sonarIndex.deleteEvent(event);
+  }
+
+  @Override
+  public DefaultDecoratorContext saveViolation(Violation violation, boolean force) {
+    if (violation.getResource() == null) {
+      violation.setResource(resource);
+    }
+    sonarIndex.addViolation(violation, force);
+    return this;
+  }
+
+  @Override
+  public DefaultDecoratorContext saveViolation(Violation violation) {
+    return saveViolation(violation, false);
+  }
+}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/deprecated/decorator/FormulaDecorator.java b/sonar-batch/src/main/java/org/sonar/batch/deprecated/decorator/FormulaDecorator.java
new file mode 100644 (file)
index 0000000..8b60efc
--- /dev/null
@@ -0,0 +1,131 @@
+/*
+ * 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.batch.deprecated.decorator;
+
+import org.sonar.api.batch.*;
+import org.sonar.api.measures.FormulaData;
+import org.sonar.api.measures.Measure;
+import org.sonar.api.measures.Metric;
+import org.sonar.api.resources.Project;
+import org.sonar.api.resources.Resource;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * A pre-implementation of a decorator using a simple calculation formula
+ * @since 1.11
+ */
+public final class FormulaDecorator implements Decorator {
+
+  private Metric metric;
+  private DefaultFormulaContext formulaContext;
+  private Set<Decorator> executeAfterDecorators;
+
+  /**
+   * Creates a FormulaDecorator
+   *
+   * @param metric the metric should have an associated formula
+   * 
+   * @throws IllegalArgumentException if no formula is associated to the metric
+   */
+  public FormulaDecorator(Metric metric, Set<Decorator> executeAfterDecorators) {
+    if (metric.getFormula() == null) {
+      throw new IllegalArgumentException("No formula defined on metric");
+    }
+    this.metric = metric;
+    this.formulaContext = new DefaultFormulaContext(metric);
+    this.executeAfterDecorators = executeAfterDecorators;
+  }
+
+  public FormulaDecorator(Metric metric) {
+    this(metric, Collections.<Decorator>emptySet());
+  }
+
+  /**
+   * {@inheritDoc}
+   */
+  @Override
+  public boolean shouldExecuteOnProject(Project project) {
+    return true;
+  }
+
+  /**
+   * @return metric generated by the decorator
+   */
+  @DependedUpon
+  public Metric generatesMetric() {
+    return metric;
+  }
+
+  /**
+   * @return metric the decorator depends upon
+   */
+  @DependsUpon
+  public List<Metric> dependsUponMetrics() {
+    return metric.getFormula().dependsUponMetrics();
+  }
+
+  @DependsUpon
+  public Collection<Decorator> dependsUponDecorators() {
+    return executeAfterDecorators;
+  }
+
+  /**
+   * {@inheritDoc}
+   */
+  @Override
+  public void decorate(Resource resource, DecoratorContext context) {
+    if (context.getMeasure(metric) != null) {
+      return;
+    }
+
+    formulaContext.setDecoratorContext(context);
+    FormulaData data = new DefaultFormulaData(context);
+    Measure measure = metric.getFormula().calculate(data, formulaContext);
+    if (measure != null) {
+      context.saveMeasure(measure);
+    }
+  }
+
+  @Override
+  public boolean equals(Object o) {
+    if (this == o) {
+      return true;
+    }
+    if (o == null || getClass() != o.getClass()) {
+      return false;
+    }
+    FormulaDecorator that = (FormulaDecorator) o;
+    return !(metric != null ? !metric.equals(that.metric) : that.metric != null);
+  }
+
+  @Override
+  public int hashCode() {
+    return metric != null ? metric.hashCode() : 0;
+  }
+
+  @Override
+  public String toString() {
+    return new StringBuilder().append("f(").append(metric.getKey()).append(")").toString();
+  }
+}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/deprecated/package-info.java b/sonar-batch/src/main/java/org/sonar/batch/deprecated/package-info.java
new file mode 100644 (file)
index 0000000..ca1dcad
--- /dev/null
@@ -0,0 +1,23 @@
+/*
+ * 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.
+ */
+@ParametersAreNonnullByDefault
+package org.sonar.batch.deprecated;
+
+import javax.annotation.ParametersAreNonnullByDefault;
diff --git a/sonar-batch/src/main/java/org/sonar/batch/deprecated/tasks/ListTask.java b/sonar-batch/src/main/java/org/sonar/batch/deprecated/tasks/ListTask.java
new file mode 100644 (file)
index 0000000..bcd02a0
--- /dev/null
@@ -0,0 +1,59 @@
+/*
+ * 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.batch.deprecated.tasks;
+
+import org.sonar.api.task.Task;
+import org.sonar.api.task.TaskDefinition;
+
+public class ListTask implements Task {
+
+  public static final String KEY = "list";
+
+  public static final TaskDefinition DEFINITION = TaskDefinition.builder()
+    .key(KEY)
+    .description("List available tasks")
+    .taskClass(ListTask.class)
+    .build();
+
+  private final Tasks tasks;
+
+  public ListTask(Tasks tasks) {
+    this.tasks = tasks;
+  }
+
+  @Override
+  public void execute() {
+    logBlankLine();
+    log("Available tasks:");
+    logBlankLine();
+    for (TaskDefinition def : tasks.definitions()) {
+      log("  - " + def.key() + ": " + def.description());
+    }
+    logBlankLine();
+  }
+
+  void log(String s) {
+    System.out.println(s);
+  }
+
+  void logBlankLine() {
+    System.out.println();
+  }
+}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/deprecated/tasks/Tasks.java b/sonar-batch/src/main/java/org/sonar/batch/deprecated/tasks/Tasks.java
new file mode 100644 (file)
index 0000000..c97bdea
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ * 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.batch.deprecated.tasks;
+
+import com.google.common.collect.ImmutableSortedMap;
+import com.google.common.collect.Maps;
+import org.sonar.api.task.Task;
+import org.sonar.api.task.TaskComponent;
+import org.sonar.api.task.TaskDefinition;
+import org.sonar.api.utils.SonarException;
+
+import java.util.Collection;
+import java.util.Map;
+import java.util.SortedMap;
+
+public class Tasks implements TaskComponent {
+
+  private final SortedMap<String, TaskDefinition> byKey;
+
+  public Tasks(TaskDefinition[] definitions) {
+    SortedMap<String, TaskDefinition> map = Maps.newTreeMap();
+    for (TaskDefinition definition : definitions) {
+      if (map.containsKey(definition.key())) {
+        throw new SonarException("Task '" + definition.key() + "' is declared twice");
+      }
+      map.put(definition.key(), definition);
+    }
+    this.byKey = ImmutableSortedMap.copyOf(map);
+  }
+
+  public TaskDefinition definition(String taskKey) {
+    return byKey.get(taskKey);
+  }
+
+  public Collection<TaskDefinition> definitions() {
+    return byKey.values();
+  }
+
+  /**
+   * Perform validation of task definitions
+   */
+  public void start() {
+    checkDuplicatedClasses();
+  }
+
+  private void checkDuplicatedClasses() {
+    Map<Class<? extends Task>, TaskDefinition> byClass = Maps.newHashMap();
+    for (TaskDefinition def : definitions()) {
+      TaskDefinition other = byClass.get(def.taskClass());
+      if (other == null) {
+        byClass.put(def.taskClass(), def);
+      } else {
+        throw new SonarException("Task '" + def.taskClass().getName() + "' is defined twice: first by '" + other.key() + "' and then by '" + def.key() + "'");
+      }
+    }
+  }
+}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/deprecated/tasks/package-info.java b/sonar-batch/src/main/java/org/sonar/batch/deprecated/tasks/package-info.java
new file mode 100644 (file)
index 0000000..f346de5
--- /dev/null
@@ -0,0 +1,23 @@
+/*
+ * 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.
+ */
+@ParametersAreNonnullByDefault
+package org.sonar.batch.deprecated.tasks;
+
+import javax.annotation.ParametersAreNonnullByDefault;
index eeb37de63ed228cddabcb7733fa4fa9b87bda8fc..6cf8ae826f4dd913fb5d47d080919499425b96b4 100644 (file)
@@ -38,7 +38,6 @@ import org.sonar.api.measures.CoreMetrics;
 import org.sonar.api.measures.Measure;
 import org.sonar.api.measures.MeasuresFilter;
 import org.sonar.api.measures.MeasuresFilters;
-import org.sonar.api.resources.Directory;
 import org.sonar.api.resources.File;
 import org.sonar.api.resources.Project;
 import org.sonar.api.resources.ProjectLink;
@@ -107,7 +106,6 @@ public class DefaultIndex extends SonarIndex {
   // caches
   private Project currentProject;
   private Map<Resource, Bucket> buckets = Maps.newLinkedHashMap();
-  private Map<String, Bucket> bucketsByDeprecatedKey = Maps.newLinkedHashMap();
   private Set<Dependency> dependencies = Sets.newLinkedHashSet();
   private Map<Resource, Map<Resource, Dependency>> outgoingDependenciesByResource = Maps.newLinkedHashMap();
   private Map<Resource, Map<Resource, Dependency>> incomingDependenciesByResource = Maps.newLinkedHashMap();
@@ -166,9 +164,6 @@ public class DefaultIndex extends SonarIndex {
 
   private void addBucket(Resource resource, Bucket bucket) {
     buckets.put(resource, bucket);
-    if (StringUtils.isNotBlank(resource.getDeprecatedKey())) {
-      bucketsByDeprecatedKey.put(resource.getDeprecatedKey(), bucket);
-    }
   }
 
   private void addModule(Project parent, Project module) {
@@ -613,12 +608,6 @@ public class DefaultIndex extends SonarIndex {
     return getBucket(reference) != null;
   }
 
-  /**
-   * Should support 2 situations
-   * 1) key = new key and deprecatedKey = old key : this is the standard use case in a perfect world
-   * 2) key = null and deprecatedKey = oldKey : this is for plugins that are using deprecated constructors of
-   * {@link File} and {@link Directory}
-   */
   private Bucket getBucket(@Nullable Resource reference) {
     if (reference == null) {
       return null;
@@ -626,17 +615,6 @@ public class DefaultIndex extends SonarIndex {
     if (StringUtils.isNotBlank(reference.getKey())) {
       return buckets.get(reference);
     }
-    if (StringUtils.isNotBlank(reference.getDeprecatedKey())) {
-      // Fallback to use deprecated key
-      Bucket bucket = bucketsByDeprecatedKey.get(reference.getDeprecatedKey());
-      if (bucket != null) {
-        // Fix reference resource
-        reference.setKey(bucket.getResource().getKey());
-        reference.setPath(bucket.getResource().getPath());
-        LOG.debug("Resource {} was found using deprecated key. Please update your plugin.", reference);
-        return bucket;
-      }
-    }
     return null;
   }
 
index 0cb5a0b182d88a8ad5065c87ee3f31394a9a7252..69b7dd98d85b5b76b39989907689f757d8865ebe 100644 (file)
@@ -24,20 +24,21 @@ import org.apache.commons.lang.StringUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.sonar.api.BatchComponent;
-import org.sonar.api.batch.fs.FileSystem;
 import org.sonar.api.batch.fs.InputFile;
 import org.sonar.api.batch.fs.internal.DeprecatedDefaultInputFile;
 import org.sonar.api.database.DatabaseSession;
 import org.sonar.api.database.model.ResourceModel;
 import org.sonar.api.resources.Directory;
-import org.sonar.api.resources.File;
 import org.sonar.api.resources.Project;
 import org.sonar.api.resources.Qualifiers;
-import org.sonar.api.resources.Resource;
 import org.sonar.api.resources.Scopes;
+import org.sonar.api.scan.filesystem.PathResolver;
 import org.sonar.api.utils.PathUtils;
+import org.sonar.batch.scan.filesystem.DefaultModuleFileSystem;
 import org.sonar.batch.util.DeprecatedKeyUtils;
 
+import javax.annotation.CheckForNull;
+
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -48,17 +49,19 @@ public class ResourceKeyMigration implements BatchComponent {
   private static final String COMPONENT_CHANGED_TO = "Component {} changed to {}";
   private final Logger logger;
   private final DatabaseSession session;
+  private final PathResolver pathResolver;
 
   private boolean migrationNeeded = false;
 
-  public ResourceKeyMigration(DatabaseSession session) {
-    this(session, LoggerFactory.getLogger(ResourceKeyMigration.class));
+  public ResourceKeyMigration(DatabaseSession session, PathResolver pathResolver) {
+    this(session, pathResolver, LoggerFactory.getLogger(ResourceKeyMigration.class));
   }
 
   @VisibleForTesting
-  ResourceKeyMigration(DatabaseSession session, Logger logger) {
+  ResourceKeyMigration(DatabaseSession session, PathResolver pathResolver, Logger logger) {
     this.session = session;
     this.logger = logger;
+    this.pathResolver = pathResolver;
   }
 
   public void checkIfMigrationNeeded(Project rootProject) {
@@ -68,19 +71,19 @@ public class ResourceKeyMigration implements BatchComponent {
     }
   }
 
-  public void migrateIfNeeded(Project module, FileSystem fs) {
+  public void migrateIfNeeded(Project module, DefaultModuleFileSystem fs) {
     if (migrationNeeded) {
-      migrateIfNeeded(module, fs.inputFiles(fs.predicates().all()));
+      migrateIfNeeded(module, fs.inputFiles(fs.predicates().all()), fs);
     }
   }
 
-  void migrateIfNeeded(Project module, Iterable<InputFile> inputFiles) {
+  void migrateIfNeeded(Project module, Iterable<InputFile> inputFiles, DefaultModuleFileSystem fs) {
     logger.info("Update component keys");
     Map<String, InputFile> deprecatedFileKeyMapper = new HashMap<String, InputFile>();
     Map<String, InputFile> deprecatedTestKeyMapper = new HashMap<String, InputFile>();
     Map<String, String> deprecatedDirectoryKeyMapper = new HashMap<String, String>();
     for (InputFile inputFile : inputFiles) {
-      String deprecatedKey = ((DeprecatedDefaultInputFile) inputFile).deprecatedKey();
+      String deprecatedKey = computeDeprecatedKey(module.getKey(), (DeprecatedDefaultInputFile) inputFile, fs);
       if (deprecatedKey != null) {
         if (InputFile.Type.TEST == inputFile.type() && !deprecatedTestKeyMapper.containsKey(deprecatedKey)) {
           deprecatedTestKeyMapper.put(deprecatedKey, inputFile);
@@ -97,6 +100,23 @@ public class ResourceKeyMigration implements BatchComponent {
     session.commit();
   }
 
+  @CheckForNull
+  private String computeDeprecatedKey(String moduleKey, DeprecatedDefaultInputFile inputFile, DefaultModuleFileSystem fs) {
+    List<java.io.File> sourceDirs = InputFile.Type.MAIN == inputFile.type() ? fs.sourceDirs() : fs.testDirs();
+    for (java.io.File sourceDir : sourceDirs) {
+      String sourceRelativePath = pathResolver.relativePath(sourceDir, inputFile.file());
+      if (sourceRelativePath != null) {
+        if ("java".equals(inputFile.language())) {
+          return new StringBuilder()
+            .append(moduleKey).append(":").append(DeprecatedKeyUtils.getJavaFileDeprecatedKey(sourceRelativePath)).toString();
+        } else {
+          return new StringBuilder().append(moduleKey).append(":").append(sourceRelativePath).toString();
+        }
+      }
+    }
+    return null;
+  }
+
   private void migrateFiles(Project module, Map<String, InputFile> deprecatedFileKeyMapper, Map<String, InputFile> deprecatedTestKeyMapper,
     Map<String, String> deprecatedDirectoryKeyMapper,
     int moduleId) {
@@ -113,13 +133,11 @@ public class ResourceKeyMigration implements BatchComponent {
         String newEffectiveKey = ((DeprecatedDefaultInputFile) matchedFile).key();
         // Now compute migration of the parent dir
         String oldKey = StringUtils.substringAfterLast(oldEffectiveKey, ":");
-        Resource sonarFile;
         String parentOldKey;
         if ("java".equals(resourceModel.getLanguageKey())) {
           parentOldKey = String.format("%s:%s", module.getEffectiveKey(), DeprecatedKeyUtils.getJavaFileParentDeprecatedKey(oldKey));
         } else {
-          sonarFile = new File(oldKey);
-          parentOldKey = String.format("%s:%s", module.getEffectiveKey(), sonarFile.getParent().getDeprecatedKey());
+          parentOldKey = String.format("%s:%s", module.getEffectiveKey(), oldParentKey(oldKey));
         }
         String parentNewKey = String.format("%s:%s", module.getEffectiveKey(), getParentKey(matchedFile));
         if (!deprecatedDirectoryKeyMapper.containsKey(parentOldKey)) {
@@ -137,6 +155,18 @@ public class ResourceKeyMigration implements BatchComponent {
     }
   }
 
+  private String oldParentKey(String oldKey) {
+    String cleanKey = StringUtils.trim(oldKey.replace('\\', '/'));
+    if (cleanKey.indexOf(Directory.SEPARATOR) >= 0) {
+      String oldParentKey = Directory.parseKey(StringUtils.substringBeforeLast(oldKey, Directory.SEPARATOR));
+      oldParentKey = StringUtils.removeStart(oldParentKey, Directory.SEPARATOR);
+      oldParentKey = StringUtils.removeEnd(oldParentKey, Directory.SEPARATOR);
+      return oldParentKey;
+    } else {
+      return Directory.ROOT;
+    }
+  }
+
   private void updateKey(ResourceModel resourceModel, String newEffectiveKey, Map<String, ResourceModel> disabledResourceByKey) {
     // Look for disabled resource with conflicting key
     if (disabledResourceByKey.containsKey(newEffectiveKey)) {
index e3e9f33bc795002a183ae7dd08edb599a4384e00..9a089eaef97770da6607bbd188cd44ec2f3222a2 100644 (file)
@@ -35,6 +35,7 @@ import org.sonar.api.utils.KeyValueFormat;
 import org.sonar.batch.duplication.DuplicationCache;
 import org.sonar.batch.highlighting.SyntaxHighlightingData;
 import org.sonar.batch.highlighting.SyntaxHighlightingRule;
+import org.sonar.batch.scan.filesystem.InputFileMetadata;
 import org.sonar.batch.scan.measure.MeasureCache;
 import org.sonar.batch.source.CodeColorizers;
 import org.sonar.batch.symbol.SymbolData;
@@ -72,18 +73,18 @@ public class SourceDataFactory implements BatchComponent {
     this.codeColorizers = codeColorizers;
   }
 
-  public byte[] consolidateData(DefaultInputFile inputFile) throws IOException {
+  public byte[] consolidateData(DefaultInputFile inputFile, InputFileMetadata metadata) throws IOException {
     FileSourceDb.Data.Builder dataBuilder = createForSource(inputFile);
     applyLineMeasures(inputFile, dataBuilder);
     applyDuplications(inputFile.key(), dataBuilder);
-    applyHighlighting(inputFile, dataBuilder);
-    applySymbolReferences(inputFile, dataBuilder);
+    applyHighlighting(inputFile, metadata, dataBuilder);
+    applySymbolReferences(inputFile, metadata, dataBuilder);
     return FileSourceDto.encodeData(dataBuilder.build());
   }
 
   FileSourceDb.Data.Builder createForSource(DefaultInputFile inputFile) throws IOException {
     FileSourceDb.Data.Builder result = FileSourceDb.Data.newBuilder();
-    List<String> lines = FileUtils.readLines(inputFile.file(), inputFile.encoding());
+    List<String> lines = FileUtils.readLines(inputFile.file(), inputFile.charset());
     // Missing empty last line
     if (lines.size() == inputFile.lines() - 1) {
       lines.add("");
@@ -191,11 +192,11 @@ public class SourceDataFactory implements BatchComponent {
     void apply(String value, FileSourceDb.Line.Builder lineBuilder);
   }
 
-  void applyHighlighting(DefaultInputFile inputFile, FileSourceDb.Data.Builder to) {
+  void applyHighlighting(DefaultInputFile inputFile, InputFileMetadata metadata, FileSourceDb.Data.Builder to) {
     SyntaxHighlightingData highlighting = componentDataCache.getData(inputFile.key(), SnapshotDataTypes.SYNTAX_HIGHLIGHTING);
     String language = inputFile.language();
     if (highlighting == null && language != null) {
-      highlighting = codeColorizers.toSyntaxHighlighting(inputFile.file(), inputFile.encoding(), language);
+      highlighting = codeColorizers.toSyntaxHighlighting(inputFile.file(), inputFile.charset(), language);
     }
     if (highlighting == null) {
       return;
@@ -204,12 +205,12 @@ public class SourceDataFactory implements BatchComponent {
     RuleItemWriter ruleItemWriter = new RuleItemWriter();
     int currentLineIdx = 1;
     for (SyntaxHighlightingRule rule : highlighting.syntaxHighlightingRuleSet()) {
-      while (currentLineIdx < inputFile.lines() && rule.getStartPosition() >= inputFile.originalLineOffsets()[currentLineIdx]) {
+      while (currentLineIdx < inputFile.lines() && rule.getStartPosition() >= metadata.originalLineOffsets()[currentLineIdx]) {
         // This rule starts on another line so advance
         currentLineIdx++;
       }
       // Now we know current rule starts on current line
-      writeDataPerLine(inputFile.originalLineOffsets(), rule, rule.getStartPosition(), rule.getEndPosition(), highlightingPerLine, currentLineIdx, ruleItemWriter);
+      writeDataPerLine(metadata.originalLineOffsets(), rule, rule.getStartPosition(), rule.getEndPosition(), highlightingPerLine, currentLineIdx, ruleItemWriter);
     }
     for (int i = 0; i < highlightingPerLine.length; i++) {
       StringBuilder sb = highlightingPerLine[i];
@@ -219,7 +220,7 @@ public class SourceDataFactory implements BatchComponent {
     }
   }
 
-  void applySymbolReferences(DefaultInputFile file, FileSourceDb.Data.Builder to) {
+  void applySymbolReferences(DefaultInputFile file, InputFileMetadata metadata, FileSourceDb.Data.Builder to) {
     SymbolData symbolRefs = componentDataCache.getData(file.key(), SnapshotDataTypes.SYMBOL_HIGHLIGHTING);
     if (symbolRefs != null) {
       StringBuilder[] refsPerLine = new StringBuilder[file.lines()];
@@ -236,13 +237,13 @@ public class SourceDataFactory implements BatchComponent {
         int declarationStartOffset = symbol.getDeclarationStartOffset();
         int declarationEndOffset = symbol.getDeclarationEndOffset();
         int length = declarationEndOffset - declarationStartOffset;
-        addSymbol(symbolId, declarationStartOffset, declarationEndOffset, file.originalLineOffsets(), refsPerLine);
+        addSymbol(symbolId, declarationStartOffset, declarationEndOffset, metadata.originalLineOffsets(), refsPerLine);
         for (Integer referenceStartOffset : symbolRefs.referencesBySymbol().get(symbol)) {
           if (referenceStartOffset == declarationStartOffset) {
             // Ignore old API that used to store reference as first declaration
             continue;
           }
-          addSymbol(symbolId, referenceStartOffset, referenceStartOffset + length, file.originalLineOffsets(), refsPerLine);
+          addSymbol(symbolId, referenceStartOffset, referenceStartOffset + length, metadata.originalLineOffsets(), refsPerLine);
         }
         symbolId++;
       }
@@ -255,12 +256,12 @@ public class SourceDataFactory implements BatchComponent {
     }
   }
 
-  private void addSymbol(int symbolId, int startOffset, int endOffset, long[] originalLineOffsets, StringBuilder[] result) {
+  private void addSymbol(int symbolId, int startOffset, int endOffset, int[] originalLineOffsets, StringBuilder[] result) {
     int startLine = binarySearchLine(startOffset, originalLineOffsets);
     writeDataPerLine(originalLineOffsets, symbolId, startOffset, endOffset, result, startLine, new SymbolItemWriter());
   }
 
-  private int binarySearchLine(int declarationStartOffset, long[] originalLineOffsets) {
+  private int binarySearchLine(int declarationStartOffset, int[] originalLineOffsets) {
     int begin = 0;
     int end = originalLineOffsets.length - 1;
     while (begin < end) {
@@ -274,7 +275,7 @@ public class SourceDataFactory implements BatchComponent {
     return begin + 1;
   }
 
-  private <G> void writeDataPerLine(long[] originalLineOffsets, G item, int globalStartOffset, int globalEndOffset, StringBuilder[] dataPerLine, int startLine,
+  private <G> void writeDataPerLine(int[] originalLineOffsets, G item, int globalStartOffset, int globalEndOffset, StringBuilder[] dataPerLine, int startLine,
     RangeItemWriter<G> writer) {
     int currentLineIdx = startLine;
     // We know current item starts on current line
index a7a18548418a5cf34eec187313806813a6ab0677..14cd85e371a2d29059aa4198fac6d702c604dc71 100644 (file)
  */
 package org.sonar.batch.index;
 
-import org.apache.commons.codec.binary.Hex;
 import org.apache.commons.codec.digest.DigestUtils;
 import org.apache.ibatis.session.ResultContext;
 import org.apache.ibatis.session.ResultHandler;
-import org.sonar.api.batch.fs.InputPath;
+import org.sonar.api.batch.fs.InputFile;
 import org.sonar.api.batch.fs.internal.DefaultInputFile;
 import org.sonar.api.utils.System2;
 import org.sonar.batch.ProjectTree;
+import org.sonar.batch.scan.filesystem.InputFileMetadata;
 import org.sonar.batch.scan.filesystem.InputPathCache;
 import org.sonar.core.persistence.DbSession;
 import org.sonar.core.persistence.MyBatis;
@@ -35,7 +35,9 @@ import org.sonar.core.source.db.FileSourceMapper;
 
 import javax.annotation.CheckForNull;
 
+import java.io.BufferedReader;
 import java.io.IOException;
+import java.nio.file.Files;
 import java.util.HashMap;
 import java.util.Map;
 
@@ -73,10 +75,8 @@ public class SourcePersister implements ScanPersister {
       });
 
       FileSourceMapper mapper = session.getMapper(FileSourceMapper.class);
-      for (InputPath inputPath : inputPathCache.all()) {
-        if (inputPath instanceof DefaultInputFile) {
-          persist(session, mapper, (DefaultInputFile) inputPath, previousDtosByUuid);
-        }
+      for (InputFile inputFile : inputPathCache.allFiles()) {
+        persist(session, mapper, (DefaultInputFile) inputFile, previousDtosByUuid);
       }
     } catch (Exception e) {
       throw new IllegalStateException("Unable to save file sources", e);
@@ -87,7 +87,8 @@ public class SourcePersister implements ScanPersister {
   private void persist(DbSession session, FileSourceMapper mapper, DefaultInputFile inputFile, Map<String, FileSourceDto> previousDtosByUuid) {
     String fileUuid = resourceCache.get(inputFile.key()).resource().getUuid();
 
-    byte[] data = computeData(inputFile);
+    InputFileMetadata metadata = inputPathCache.getFileMetadata(inputFile.moduleKey(), inputFile.relativePath());
+    byte[] data = computeData(inputFile, metadata);
     String dataHash = DigestUtils.md5Hex(data);
     FileSourceDto previousDto = previousDtosByUuid.get(fileUuid);
     if (previousDto == null) {
@@ -96,20 +97,20 @@ public class SourcePersister implements ScanPersister {
         .setFileUuid(fileUuid)
         .setBinaryData(data)
         .setDataHash(dataHash)
-        .setSrcHash(inputFile.hash())
-        .setLineHashes(lineHashesAsMd5Hex(inputFile))
+        .setSrcHash(metadata.hash())
+        .setLineHashes(lineHashesAsMd5Hex(inputFile, metadata))
         .setCreatedAt(system2.now())
         .setUpdatedAt(system2.now());
       mapper.insert(dto);
       session.commit();
     } else {
       // Update only if data_hash has changed or if src_hash is missing (progressive migration)
-      if (!dataHash.equals(previousDto.getDataHash()) || !inputFile.hash().equals(previousDto.getSrcHash())) {
+      if (!dataHash.equals(previousDto.getDataHash()) || !metadata.hash().equals(previousDto.getSrcHash())) {
         previousDto
           .setBinaryData(data)
           .setDataHash(dataHash)
-          .setSrcHash(inputFile.hash())
-          .setLineHashes(lineHashesAsMd5Hex(inputFile))
+          .setSrcHash(metadata.hash())
+          .setLineHashes(lineHashesAsMd5Hex(inputFile, metadata))
           .setUpdatedAt(system2.now());
         mapper.update(previousDto);
         session.commit();
@@ -118,24 +119,41 @@ public class SourcePersister implements ScanPersister {
   }
 
   @CheckForNull
-  private String lineHashesAsMd5Hex(DefaultInputFile inputFile) {
-    if (inputFile.lines() == 0) {
+  private String lineHashesAsMd5Hex(DefaultInputFile f, InputFileMetadata metadata) {
+    if (f.lines() == 0) {
       return null;
     }
     // A md5 string is 32 char long + '\n' = 33
-    StringBuilder result = new StringBuilder(inputFile.lines() * (32 + 1));
-    for (byte[] lineHash : inputFile.lineHashes()) {
-      if (result.length() > 0) {
-        result.append("\n");
+    StringBuilder result = new StringBuilder(f.lines() * (32 + 1));
+
+    try {
+      BufferedReader reader = Files.newBufferedReader(f.path(), f.charset());
+      StringBuilder sb = new StringBuilder();
+      for (int i = 0; i < f.lines(); i++) {
+        String lineStr = reader.readLine();
+        lineStr = lineStr == null ? "" : lineStr;
+        for (int j = 0; j < lineStr.length(); j++) {
+          char c = lineStr.charAt(j);
+          if (!Character.isWhitespace(c)) {
+            sb.append(c);
+          }
+        }
+        if (i > 0) {
+          result.append("\n");
+        }
+        result.append(sb.length() > 0 ? DigestUtils.md5Hex(sb.toString()) : "");
+        sb.setLength(0);
       }
-      result.append(lineHash != null ? Hex.encodeHexString(lineHash) : "");
+    } catch (Exception e) {
+      throw new IllegalStateException("Unable to compute line hashes of file " + f, e);
     }
+
     return result.toString();
   }
 
-  private byte[] computeData(DefaultInputFile inputFile) {
+  private byte[] computeData(DefaultInputFile inputFile, InputFileMetadata metadata) {
     try {
-      return dataFactory.consolidateData(inputFile);
+      return dataFactory.consolidateData(inputFile, metadata);
     } catch (IOException e) {
       throw new IllegalStateException("Fail to read file " + inputFile, e);
     }
index 49b0405787b41ba63c6b857e41710da1af085004..fbc293e8004633ff1a5763d3514468311cc9085e 100644 (file)
  */
 package org.sonar.batch.issue.tracking;
 
+import com.google.common.base.Charsets;
 import com.google.common.collect.LinkedHashMultimap;
 import com.google.common.collect.Multimap;
 import org.apache.commons.codec.binary.Hex;
+import org.apache.commons.codec.digest.DigestUtils;
 import org.apache.commons.lang.ObjectUtils;
+import org.sonar.api.batch.fs.internal.DefaultInputFile;
 
+import java.io.BufferedReader;
+import java.nio.file.Files;
+import java.security.MessageDigest;
 import java.util.Collection;
 
 /**
@@ -49,7 +55,29 @@ public final class FileHashes {
     return new FileHashes(hashes, linesByHash);
   }
 
-  public static FileHashes create(byte[][] hashes) {
+  public static FileHashes create(DefaultInputFile f) {
+    byte[][] hashes = new byte[f.lines()][];
+    try {
+      BufferedReader reader = Files.newBufferedReader(f.path(), f.charset());
+      MessageDigest lineMd5Digest = DigestUtils.getMd5Digest();
+      StringBuilder sb = new StringBuilder();
+      for (int i = 0; i < f.lines(); i++) {
+        String lineStr = reader.readLine();
+        if (lineStr != null) {
+          for (int j = 0; j < lineStr.length(); j++) {
+            char c = lineStr.charAt(j);
+            if (!Character.isWhitespace(c)) {
+              sb.append(c);
+            }
+          }
+        }
+        hashes[i] = sb.length() > 0 ? lineMd5Digest.digest(sb.toString().getBytes(Charsets.UTF_8)) : null;
+        sb.setLength(0);
+      }
+    } catch (Exception e) {
+      throw new IllegalStateException("Unable to compute line hashes of file " + f, e);
+    }
+
     int size = hashes.length;
     Multimap<String, Integer> linesByHash = LinkedHashMultimap.create();
     String[] hexHashes = new String[size];
index f8a98c29b0031285c40c3becc330980ec5dc4507..b501e18ad662f27f066de05af54ef59a0a9fde6d 100644 (file)
@@ -19,7 +19,7 @@
  */
 package org.sonar.batch.issue.tracking;
 
-import org.sonar.api.BatchExtension;
+import org.sonar.api.BatchComponent;
 import org.sonar.api.issue.Issue;
 import org.sonar.api.issue.IssueHandler;
 import org.sonar.api.issue.internal.DefaultIssue;
@@ -30,7 +30,7 @@ import org.sonar.core.user.DefaultUser;
 
 import javax.annotation.Nullable;
 
-public class IssueHandlers implements BatchExtension {
+public class IssueHandlers implements BatchComponent {
   private final IssueHandler[] handlers;
   private final DefaultContext context;
 
@@ -117,7 +117,7 @@ public class IssueHandlers implements BatchExtension {
     @Override
     public IssueHandler.Context assign(@Nullable String assignee) {
       User user = null;
-      if(assignee != null) {
+      if (assignee != null) {
         user = new DefaultUser().setLogin(assignee).setName(assignee);
       }
       updater.assign(issue, user, changeContext);
index c3826cbd3911e29c33ce48c9537bf9aa733b35ba..c1ae052034c77cfe5ff09ee855d059c36dcd0ba4 100644 (file)
@@ -19,8 +19,6 @@
  */
 package org.sonar.batch.issue.tracking;
 
-import org.sonar.api.batch.RequiresDB;
-
 import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Strings;
 import com.google.common.collect.Lists;
@@ -32,6 +30,7 @@ import org.sonar.api.batch.DecoratorBarriers;
 import org.sonar.api.batch.DecoratorContext;
 import org.sonar.api.batch.DependedUpon;
 import org.sonar.api.batch.DependsUpon;
+import org.sonar.api.batch.RequiresDB;
 import org.sonar.api.batch.fs.InputFile;
 import org.sonar.api.batch.fs.internal.DefaultInputFile;
 import org.sonar.api.component.ResourcePerspectives;
@@ -133,7 +132,7 @@ public class IssueTrackingDecorator implements Decorator {
       File sonarFile = (File) resource;
       InputFile file = inputPathCache.getFile(project.getEffectiveKey(), sonarFile.getPath());
       if (file == null) {
-        throw new IllegalStateException("Resource " + resource + " was not found in InputPath cache");
+        throw new IllegalStateException("File " + resource + " was not found in InputPath cache");
       }
       sourceHashHolder = new SourceHashHolder((DefaultInputFile) file, lastLineHashes);
     }
index f0c22e52c688d3e306e845b0ea0c5d2787f8818c..c4d9a65769f88cdf19ee2514bc904881344ea7c1 100644 (file)
@@ -24,7 +24,6 @@ import com.google.common.collect.Lists;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.sonar.api.BatchComponent;
-import org.sonar.api.batch.fs.InputFile;
 import org.sonar.api.batch.fs.internal.DefaultInputFile;
 import org.sonar.api.batch.rule.ActiveRule;
 import org.sonar.api.batch.rule.ActiveRules;
@@ -108,7 +107,7 @@ public class LocalIssueTracking implements BatchComponent {
 
     SourceHashHolder sourceHashHolder = null;
     if (component.isFile()) {
-      InputFile file = (InputFile) inputPathCache.getInputPath(component);
+      DefaultInputFile file = (DefaultInputFile) inputPathCache.getInputPath(component);
       if (file == null) {
         throw new IllegalStateException("Resource " + component.resource() + " was not found in InputPath cache");
       }
index 38f0af7745a35df47b05ababc55bf25070788510..8151f4184f4675ec741f6f2cbcaf85f857742406 100644 (file)
@@ -43,7 +43,7 @@ public class SourceHashHolder {
 
   private void initHashes() {
     if (hashedSource == null) {
-      hashedSource = FileHashes.create(inputFile.lineHashes());
+      hashedSource = FileHashes.create(inputFile);
       Status status = inputFile.status();
       if (status == Status.ADDED) {
         hashedReference = null;
diff --git a/sonar-batch/src/main/java/org/sonar/batch/languages/DefaultLanguagesReferential.java b/sonar-batch/src/main/java/org/sonar/batch/languages/DefaultLanguagesReferential.java
deleted file mode 100644 (file)
index 4d43ea2..0000000
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * 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.batch.languages;
-
-import org.sonar.api.resources.Languages;
-
-import javax.annotation.CheckForNull;
-
-import java.util.ArrayList;
-import java.util.Collection;
-
-/**
- * Languages referential using {@link Languages}
- * @since 4.4
- */
-public class DefaultLanguagesReferential implements LanguagesReferential {
-
-  private Languages languages;
-
-  public DefaultLanguagesReferential(Languages languages) {
-    this.languages = languages;
-  }
-
-  /**
-   * Get language.
-   */
-  @Override
-  @CheckForNull
-  public Language get(String languageKey) {
-    org.sonar.api.resources.Language language = languages.get(languageKey);
-    return language != null ? new Language(language.getKey(), language.getName(), language.getFileSuffixes()) : null;
-  }
-
-  /**
-   * Get list of all supported languages.
-   */
-  @Override
-  public Collection<Language> all() {
-    org.sonar.api.resources.Language[] all = languages.all();
-    Collection<Language> result = new ArrayList<Language>(all.length);
-    for (org.sonar.api.resources.Language language : all) {
-      result.add(new Language(language.getKey(), language.getName(), language.getFileSuffixes()));
-    }
-    return result;
-  }
-
-}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/languages/Language.java b/sonar-batch/src/main/java/org/sonar/batch/languages/Language.java
deleted file mode 100644 (file)
index daeb7d5..0000000
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * 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.batch.languages;
-
-import java.util.Arrays;
-import java.util.Collection;
-
-public final class Language {
-
-  private final String key, name;
-  private final String[] fileSuffixes;
-
-  public Language(String key, String name, String... fileSuffixes) {
-    this.key = key;
-    this.name = name;
-    this.fileSuffixes = fileSuffixes;
-  }
-
-  /**
-   * For example "java".
-   */
-  public String key() {
-    return key;
-  }
-
-  /**
-   * For example "Java"
-   */
-  public String name() {
-    return name;
-  }
-
-  /**
-   * For example ["jav", "java"].
-   */
-  public Collection<String> fileSuffixes() {
-    return Arrays.asList(fileSuffixes);
-  }
-
-}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/languages/LanguagesReferential.java b/sonar-batch/src/main/java/org/sonar/batch/languages/LanguagesReferential.java
deleted file mode 100644 (file)
index da1596c..0000000
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * 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.batch.languages;
-
-import org.sonar.api.BatchComponent;
-
-import javax.annotation.CheckForNull;
-
-import java.util.Collection;
-
-/**
- * Languages referential
- * @since 4.4
- */
-public interface LanguagesReferential extends BatchComponent {
-
-  /**
-   * Get language.
-   */
-  @CheckForNull
-  Language get(String languageKey);
-
-  /**
-   * Get list of all supported languages.
-   */
-  Collection<Language> all();
-
-}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/languages/package-info.java b/sonar-batch/src/main/java/org/sonar/batch/languages/package-info.java
deleted file mode 100644 (file)
index 7a5d7a9..0000000
+++ /dev/null
@@ -1,21 +0,0 @@
-/*
- * 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.
- */
-@javax.annotation.ParametersAreNonnullByDefault
-package org.sonar.batch.languages;
index 7bc120b37d68a7a1f87098fb2782186836fef719..4d89b9e4b3ed40380691d87bbe45a9a3a093c3d1 100644 (file)
@@ -24,7 +24,6 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.sonar.api.batch.fs.InputDir;
 import org.sonar.api.batch.fs.InputFile;
-import org.sonar.api.batch.fs.InputPath;
 import org.sonar.api.batch.fs.internal.DefaultInputFile;
 import org.sonar.api.batch.sensor.dependency.Dependency;
 import org.sonar.api.batch.sensor.duplication.DuplicationGroup;
@@ -165,12 +164,11 @@ public class TaskResult implements org.sonar.batch.mediumtest.ScanTaskObserver {
 
   private void storeFs(ProjectScanContainer container) {
     InputPathCache inputFileCache = container.getComponentByType(InputPathCache.class);
-    for (InputPath inputPath : inputFileCache.all()) {
-      if (inputPath instanceof InputFile) {
-        inputFiles.put(inputPath.relativePath(), (InputFile) inputPath);
-      } else {
-        inputDirs.put(inputPath.relativePath(), (InputDir) inputPath);
-      }
+    for (InputFile inputPath : inputFileCache.allFiles()) {
+      inputFiles.put(inputPath.relativePath(), inputPath);
+    }
+    for (InputDir inputPath : inputFileCache.allDirs()) {
+      inputDirs.put(inputPath.relativePath(), inputPath);
     }
   }
 
index 6da48d12bb85314fbca20067ac3bcf29e613d2ad..b555f76ded9737d62a4974b50f11c3cd935af2dc 100644 (file)
@@ -19,6 +19,9 @@
  */
 package org.sonar.batch.phases;
 
+import org.sonar.batch.deprecated.decorator.DefaultDecoratorContext;
+
+import org.sonar.batch.deprecated.decorator.DecoratorsSelector;
 import com.google.common.collect.Lists;
 import org.sonar.api.BatchComponent;
 import org.sonar.api.batch.Decorator;
@@ -29,8 +32,6 @@ import org.sonar.api.resources.Project;
 import org.sonar.api.resources.Resource;
 import org.sonar.api.utils.MessageException;
 import org.sonar.api.utils.SonarException;
-import org.sonar.batch.DecoratorsSelector;
-import org.sonar.batch.DefaultDecoratorContext;
 import org.sonar.batch.bootstrap.BatchExtensionDictionnary;
 import org.sonar.batch.duplication.DuplicationCache;
 import org.sonar.batch.events.EventBus;
index 6c84c6dff1582ba029d58fef54cfd71660c4d340..2a2e08056ad64c6129d75b4d3fef1785739c4b5c 100644 (file)
@@ -24,6 +24,9 @@ import com.google.common.collect.Sets;
 import java.util.Arrays;
 import java.util.Set;
 
+/**
+ * Used by views
+ */
 public class Phases {
 
   public static enum Phase {
index c50d3727184a0eb8a07877dbe549c1e5014aada8..38502235cff67c807005d8c718a7cbb576554e07 100644 (file)
@@ -27,6 +27,7 @@ import org.sonar.batch.bootstrap.ExtensionMatcher;
 
 /**
  * Allow to filter sensors that will be executed.
+ * Used by views !!
  * @since 3.6
  *
  */
diff --git a/sonar-batch/src/main/java/org/sonar/batch/repository/language/DefaultLanguagesRepository.java b/sonar-batch/src/main/java/org/sonar/batch/repository/language/DefaultLanguagesRepository.java
new file mode 100644 (file)
index 0000000..fe5f50b
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+ * 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.batch.repository.language;
+
+import org.sonar.api.resources.Languages;
+
+import javax.annotation.CheckForNull;
+
+import java.util.ArrayList;
+import java.util.Collection;
+
+/**
+ * Languages repository using {@link Languages}
+ * @since 4.4
+ */
+public class DefaultLanguagesRepository implements LanguagesRepository {
+
+  private Languages languages;
+
+  public DefaultLanguagesRepository(Languages languages) {
+    this.languages = languages;
+  }
+
+  /**
+   * Get language.
+   */
+  @Override
+  @CheckForNull
+  public Language get(String languageKey) {
+    org.sonar.api.resources.Language language = languages.get(languageKey);
+    return language != null ? new Language(language.getKey(), language.getName(), language.getFileSuffixes()) : null;
+  }
+
+  /**
+   * Get list of all supported languages.
+   */
+  @Override
+  public Collection<Language> all() {
+    org.sonar.api.resources.Language[] all = languages.all();
+    Collection<Language> result = new ArrayList<Language>(all.length);
+    for (org.sonar.api.resources.Language language : all) {
+      result.add(new Language(language.getKey(), language.getName(), language.getFileSuffixes()));
+    }
+    return result;
+  }
+
+}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/repository/language/Language.java b/sonar-batch/src/main/java/org/sonar/batch/repository/language/Language.java
new file mode 100644 (file)
index 0000000..67629ae
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * 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.batch.repository.language;
+
+import java.util.Arrays;
+import java.util.Collection;
+
+public final class Language {
+
+  private final String key, name;
+  private final String[] fileSuffixes;
+
+  public Language(String key, String name, String... fileSuffixes) {
+    this.key = key;
+    this.name = name;
+    this.fileSuffixes = fileSuffixes;
+  }
+
+  /**
+   * For example "java".
+   */
+  public String key() {
+    return key;
+  }
+
+  /**
+   * For example "Java"
+   */
+  public String name() {
+    return name;
+  }
+
+  /**
+   * For example ["jav", "java"].
+   */
+  public Collection<String> fileSuffixes() {
+    return Arrays.asList(fileSuffixes);
+  }
+
+}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/repository/language/LanguagesRepository.java b/sonar-batch/src/main/java/org/sonar/batch/repository/language/LanguagesRepository.java
new file mode 100644 (file)
index 0000000..dd80fee
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * 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.batch.repository.language;
+
+import org.sonar.api.BatchComponent;
+
+import javax.annotation.CheckForNull;
+
+import java.util.Collection;
+
+/**
+ * Languages repository
+ * @since 4.4
+ */
+public interface LanguagesRepository extends BatchComponent {
+
+  /**
+   * Get language.
+   */
+  @CheckForNull
+  Language get(String languageKey);
+
+  /**
+   * Get list of all supported languages.
+   */
+  Collection<Language> all();
+
+}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/repository/language/package-info.java b/sonar-batch/src/main/java/org/sonar/batch/repository/language/package-info.java
new file mode 100644 (file)
index 0000000..03e334e
--- /dev/null
@@ -0,0 +1,21 @@
+/*
+ * 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.
+ */
+@javax.annotation.ParametersAreNonnullByDefault
+package org.sonar.batch.repository.language;
diff --git a/sonar-batch/src/main/java/org/sonar/batch/repository/user/User.java b/sonar-batch/src/main/java/org/sonar/batch/repository/user/User.java
new file mode 100644 (file)
index 0000000..5323e18
--- /dev/null
@@ -0,0 +1,61 @@
+/*
+ * 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.batch.repository.user;
+
+import org.apache.commons.lang.builder.EqualsBuilder;
+
+public class User {
+
+  private final String login;
+  private final String name;
+
+  public User(String login, String name) {
+    this.login = login;
+    this.name = name;
+  }
+
+  public String login() {
+    return login;
+  }
+
+  public String name() {
+    return name;
+  }
+
+  // For testing
+  @Override
+  public boolean equals(Object obj) {
+    if (obj == null) {
+      return false;
+    }
+    if (obj == this) {
+      return true;
+    }
+    if (obj.getClass() != getClass()) {
+      return false;
+    }
+    User rhs = (User) obj;
+    return new EqualsBuilder()
+      .append(login, rhs.login)
+      .append(name, rhs.name)
+      .isEquals();
+  }
+
+}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/repository/user/UserRepository.java b/sonar-batch/src/main/java/org/sonar/batch/repository/user/UserRepository.java
new file mode 100644 (file)
index 0000000..e7185b9
--- /dev/null
@@ -0,0 +1,58 @@
+/*
+ * 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.batch.repository.user;
+
+import com.google.common.base.Joiner;
+import org.sonar.batch.bootstrap.ServerClient;
+import org.sonar.batch.protocol.GsonHelper;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+
+public class UserRepository {
+
+  private ServerClient serverClient;
+
+  public UserRepository(ServerClient serverClient) {
+    this.serverClient = serverClient;
+  }
+
+  private static class Users {
+
+    private List<User> users = new ArrayList<>();
+
+    public List<User> getUsers() {
+      return users;
+    }
+  }
+
+  public Collection<User> loadFromWs(List<String> userLogins) {
+    if (userLogins.isEmpty()) {
+      return Collections.emptyList();
+    }
+    String url = "/api/users/search?format=json&includeDeactivated=true&logins=" + Joiner.on(',').join(userLogins);
+    String json = serverClient.request(url);
+    Users users = GsonHelper.create().fromJson(json, Users.class);
+    return users.getUsers();
+  }
+
+}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/repository/user/package-info.java b/sonar-batch/src/main/java/org/sonar/batch/repository/user/package-info.java
new file mode 100644 (file)
index 0000000..a86ee26
--- /dev/null
@@ -0,0 +1,23 @@
+/*
+ * 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.
+ */
+@ParametersAreNonnullByDefault
+package org.sonar.batch.repository.user;
+
+import javax.annotation.ParametersAreNonnullByDefault;
index 13ab4448d78d99e24bd508f4395614b07c275161..37455f5b58ad8233b7600b67a571c021480f75c0 100644 (file)
@@ -19,6 +19,7 @@
  */
 package org.sonar.batch.rule;
 
+import org.sonar.api.batch.AnalysisMode;
 import org.sonar.api.batch.Sensor;
 import org.sonar.api.batch.SensorContext;
 import org.sonar.api.batch.fs.FileSystem;
@@ -33,16 +34,20 @@ public class QProfileSensor implements Sensor {
 
   private final ModuleQProfiles moduleQProfiles;
   private final FileSystem fs;
+  private final AnalysisMode analysisMode;
 
-  public QProfileSensor(ModuleQProfiles moduleQProfiles, FileSystem fs) {
+  public QProfileSensor(ModuleQProfiles moduleQProfiles, FileSystem fs, AnalysisMode analysisMode) {
     this.moduleQProfiles = moduleQProfiles;
     this.fs = fs;
+    this.analysisMode = analysisMode;
   }
 
   @Override
   public boolean shouldExecuteOnProject(Project project) {
     // Should be only executed on leaf modules
-    return project.getModules().isEmpty();
+    return project.getModules().isEmpty()
+      // Useless in preview mode
+      && !analysisMode.isPreview();
   }
 
   @Override
index 801fadddd44b571fea5fba0d137ed772d609c9aa..f813c050681e97ba1476ffbfca91afc2c32b0409 100644 (file)
@@ -19,7 +19,8 @@
  */
 package org.sonar.batch.scan;
 
-import org.sonar.batch.languages.Language;
+import org.sonar.batch.repository.language.Language;
+import org.sonar.batch.repository.language.LanguagesRepository;
 
 import org.picocontainer.Startable;
 import org.slf4j.Logger;
@@ -28,7 +29,6 @@ import org.sonar.api.CoreProperties;
 import org.sonar.api.batch.fs.internal.DefaultFileSystem;
 import org.sonar.api.config.Settings;
 import org.sonar.api.utils.MessageException;
-import org.sonar.batch.languages.LanguagesReferential;
 
 /**
  * Verifies that the property sonar.language is valid
@@ -38,10 +38,10 @@ public class LanguageVerifier implements Startable {
   private static final Logger LOG = LoggerFactory.getLogger(LanguageVerifier.class);
 
   private final Settings settings;
-  private final LanguagesReferential languages;
+  private final LanguagesRepository languages;
   private final DefaultFileSystem fs;
 
-  public LanguageVerifier(Settings settings, LanguagesReferential languages, DefaultFileSystem fs) {
+  public LanguageVerifier(Settings settings, LanguagesRepository languages, DefaultFileSystem fs) {
     this.settings = settings;
     this.languages = languages;
     this.fs = fs;
index e350fd28992d25f1612d38f9e85a79621398c94d..0f457c735d9962247f1cc498007b82a391bc0f19 100644 (file)
@@ -29,11 +29,7 @@ import org.sonar.api.checks.NoSonarFilter;
 import org.sonar.api.platform.ComponentContainer;
 import org.sonar.api.resources.Project;
 import org.sonar.api.scan.filesystem.FileExclusions;
-import org.sonar.batch.DefaultProjectClasspath;
-import org.sonar.batch.DefaultTimeMachine;
-import org.sonar.batch.DeprecatedSensorContext;
 import org.sonar.batch.ProjectTree;
-import org.sonar.batch.ResourceFilters;
 import org.sonar.batch.bootstrap.BatchExtensionDictionnary;
 import org.sonar.batch.bootstrap.DefaultAnalysisMode;
 import org.sonar.batch.bootstrap.ExtensionInstaller;
@@ -45,6 +41,10 @@ import org.sonar.batch.debt.IssueChangelogDebtCalculator;
 import org.sonar.batch.debt.NewDebtDecorator;
 import org.sonar.batch.debt.SqaleRatingDecorator;
 import org.sonar.batch.debt.SqaleRatingSettings;
+import org.sonar.batch.deprecated.DeprecatedSensorContext;
+import org.sonar.batch.deprecated.ResourceFilters;
+import org.sonar.batch.deprecated.components.DefaultProjectClasspath;
+import org.sonar.batch.deprecated.components.DefaultTimeMachine;
 import org.sonar.batch.events.EventBus;
 import org.sonar.batch.index.DefaultIndex;
 import org.sonar.batch.issue.IssuableFactory;
@@ -87,6 +87,7 @@ import org.sonar.batch.scan.filesystem.DefaultModuleFileSystem;
 import org.sonar.batch.scan.filesystem.DeprecatedFileFilters;
 import org.sonar.batch.scan.filesystem.ExclusionFilters;
 import org.sonar.batch.scan.filesystem.FileIndexer;
+import org.sonar.batch.scan.filesystem.FileMetadata;
 import org.sonar.batch.scan.filesystem.FileSystemLogger;
 import org.sonar.batch.scan.filesystem.InputFileBuilderFactory;
 import org.sonar.batch.scan.filesystem.LanguageDetectionFactory;
@@ -158,6 +159,7 @@ public class ModuleScanContainer extends ComponentContainer {
       ExclusionFilters.class,
       DeprecatedFileFilters.class,
       InputFileBuilderFactory.class,
+      FileMetadata.class,
       StatusDetectionFactory.class,
       LanguageDetectionFactory.class,
       FileIndexer.class,
index 30ef5615488ddb98b77fa5e885d9936356f6bcf5..98c464310930821960b2f1f590a505a52bc4f809 100644 (file)
  */
 package org.sonar.batch.scan;
 
+import org.sonar.batch.deprecated.components.DefaultResourceCreationLock;
+
+import org.sonar.batch.deprecated.components.PeriodsDefinition;
+import org.sonar.batch.repository.language.DefaultLanguagesRepository;
 import com.google.common.annotations.VisibleForTesting;
 import org.sonar.api.BatchComponent;
 import org.sonar.api.CoreProperties;
@@ -32,7 +36,6 @@ import org.sonar.api.resources.Project;
 import org.sonar.api.scan.filesystem.PathResolver;
 import org.sonar.api.utils.SonarException;
 import org.sonar.batch.DefaultFileLinesContextFactory;
-import org.sonar.batch.DefaultResourceCreationLock;
 import org.sonar.batch.ProjectConfigurator;
 import org.sonar.batch.ProjectTree;
 import org.sonar.batch.bootstrap.DefaultAnalysisMode;
@@ -40,7 +43,6 @@ import org.sonar.batch.bootstrap.ExtensionInstaller;
 import org.sonar.batch.bootstrap.ExtensionMatcher;
 import org.sonar.batch.bootstrap.ExtensionUtils;
 import org.sonar.batch.bootstrap.MetricProvider;
-import org.sonar.batch.components.PeriodsDefinition;
 import org.sonar.batch.debt.DebtModelProvider;
 import org.sonar.batch.debt.IssueChangelogDebtCalculator;
 import org.sonar.batch.duplication.BlockCache;
@@ -63,7 +65,6 @@ import org.sonar.batch.issue.IssueCache;
 import org.sonar.batch.issue.tracking.InitialOpenIssuesStack;
 import org.sonar.batch.issue.tracking.LocalIssueTracking;
 import org.sonar.batch.issue.tracking.PreviousIssueRepository;
-import org.sonar.batch.languages.DefaultLanguagesReferential;
 import org.sonar.batch.mediumtest.ScanTaskObservers;
 import org.sonar.batch.phases.GraphPersister;
 import org.sonar.batch.profiling.PhasesSumUpTimeProfiler;
@@ -177,7 +178,7 @@ public class ProjectScanContainer extends ComponentContainer {
 
       // lang
       Languages.class,
-      DefaultLanguagesReferential.class,
+      DefaultLanguagesRepository.class,
       HighlightableBuilder.class,
       SymbolizableBuilder.class,
 
index 4d4967ec1f3961e662c987d58c138c5de8084620..83fbd7454264d2c7c1e3029a9dac9377bd0f6fbc 100644 (file)
@@ -19,7 +19,6 @@
  */
 package org.sonar.batch.scan.filesystem;
 
-import org.apache.commons.io.FilenameUtils;
 import org.sonar.api.batch.fs.AbstractFilePredicate;
 import org.sonar.api.batch.fs.InputFile;
 import org.sonar.api.batch.fs.internal.DeprecatedDefaultInputFile;
@@ -47,42 +46,4 @@ class AdditionalFilePredicates {
     }
   }
 
-  static class DeprecatedKeyPredicate extends AbstractFilePredicate {
-    private final String key;
-
-    DeprecatedKeyPredicate(String key) {
-      this.key = key;
-    }
-
-    @Override
-    public boolean apply(InputFile f) {
-      return key.equals(((DeprecatedDefaultInputFile) f).deprecatedKey());
-    }
-  }
-
-  static class SourceRelativePathPredicate extends AbstractFilePredicate {
-    private final String path;
-
-    SourceRelativePathPredicate(String s) {
-      this.path = FilenameUtils.normalize(s, true);
-    }
-
-    @Override
-    public boolean apply(InputFile f) {
-      return path.equals(((DeprecatedDefaultInputFile) f).pathRelativeToSourceDir());
-    }
-  }
-
-  static class SourceDirPredicate extends AbstractFilePredicate {
-    private final String path;
-
-    SourceDirPredicate(String s) {
-      this.path = FilenameUtils.normalize(s, true);
-    }
-
-    @Override
-    public boolean apply(InputFile f) {
-      return path.equals(((DeprecatedDefaultInputFile) f).sourceDirAbsolutePath());
-    }
-  }
 }
index 69438106d8fc9df5bf8f30571ecf30ba73aec846..460a08831b34b0d5425756f13691cc04fe716f7c 100644 (file)
@@ -21,16 +21,13 @@ package org.sonar.batch.scan.filesystem;
 
 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.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.batch.index.ResourceKeyMigration;
 import org.sonar.batch.index.ResourcePersister;
-import org.sonar.batch.util.DeprecatedKeyUtils;
 
 import javax.annotation.Nullable;
 
@@ -60,7 +57,9 @@ public class ComponentIndexer implements BatchComponent {
     this(module, languages, sonarIndex, null, null);
   }
 
-  public void execute(FileSystem fs) {
+  public void execute(DefaultModuleFileSystem fs) {
+    module.setBaseDir(fs.baseDir());
+
     if (resourcePersister != null) {
       // Force persistence of module structure in order to know if project should be migrated
       resourcePersister.persist();
@@ -73,16 +72,7 @@ public class ComponentIndexer implements BatchComponent {
     for (InputFile inputFile : fs.inputFiles(fs.predicates().all())) {
       String languageKey = inputFile.language();
       boolean unitTest = InputFile.Type.TEST == inputFile.type();
-      String pathFromSourceDir = ((DeprecatedDefaultInputFile) inputFile).pathRelativeToSourceDir();
-      if (pathFromSourceDir == null) {
-        pathFromSourceDir = inputFile.relativePath();
-      }
-      Resource sonarFile = File.create(inputFile.relativePath(), pathFromSourceDir, languages.get(languageKey), unitTest);
-      if ("java".equals(languageKey)) {
-        sonarFile.setDeprecatedKey(DeprecatedKeyUtils.getJavaFileDeprecatedKey(pathFromSourceDir));
-      } else {
-        sonarFile.setDeprecatedKey(pathFromSourceDir);
-      }
+      Resource sonarFile = File.create(inputFile.relativePath(), languages.get(languageKey), unitTest);
       sonarIndex.index(sonarFile);
     }
 
diff --git a/sonar-batch/src/main/java/org/sonar/batch/scan/filesystem/DefaultInputFileValueCoder.java b/sonar-batch/src/main/java/org/sonar/batch/scan/filesystem/DefaultInputFileValueCoder.java
deleted file mode 100644 (file)
index 31e0880..0000000
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * 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.batch.scan.filesystem;
-
-import com.persistit.Value;
-import com.persistit.encoding.CoderContext;
-import com.persistit.encoding.ValueCoder;
-import org.sonar.api.batch.fs.InputFile;
-import org.sonar.api.batch.fs.internal.DeprecatedDefaultInputFile;
-
-import javax.annotation.Nullable;
-
-import java.io.File;
-
-class DefaultInputFileValueCoder implements ValueCoder {
-
-  @Override
-  public void put(Value value, Object object, CoderContext context) {
-    DeprecatedDefaultInputFile f = (DeprecatedDefaultInputFile) object;
-    putUTFOrNull(value, f.moduleKey());
-    putUTFOrNull(value, f.relativePath());
-    value.putString(f.getFileBaseDir().toString());
-    putUTFOrNull(value, f.deprecatedKey());
-    value.putString(f.sourceDirAbsolutePath());
-    putUTFOrNull(value, f.pathRelativeToSourceDir());
-    putUTFOrNull(value, f.absolutePath());
-    value.putString(f.language());
-    value.putString(f.type().name());
-    value.putString(f.status().name());
-    putUTFOrNull(value, f.hash());
-    value.put(f.lines());
-    value.put(f.nonBlankLines());
-    putUTFOrNull(value, f.encoding());
-    value.put(f.isEmpty());
-    value.putLongArray(f.originalLineOffsets());
-    for (int i = 0; i < f.lines(); i++) {
-      value.putByteArray(f.lineHashes()[i]);
-    }
-  }
-
-  private void putUTFOrNull(Value value, @Nullable String utfOrNull) {
-    if (utfOrNull != null) {
-      value.putUTF(utfOrNull);
-    } else {
-      value.putNull();
-    }
-  }
-
-  @Override
-  public Object get(Value value, Class clazz, CoderContext context) {
-    String moduleKey = value.getString();
-    DeprecatedDefaultInputFile file = new DeprecatedDefaultInputFile(moduleKey, value.getString());
-    file.setBasedir(new File(value.getString()));
-    file.setDeprecatedKey(value.getString());
-    file.setSourceDirAbsolutePath(value.getString());
-    file.setPathRelativeToSourceDir(value.getString());
-    file.setAbsolutePath(value.getString());
-    file.setLanguage(value.getString());
-    file.setType(InputFile.Type.valueOf(value.getString()));
-    file.setStatus(InputFile.Status.valueOf(value.getString()));
-    file.setHash(value.getString());
-    file.setLines(value.getInt());
-    file.setNonBlankLines(value.getInt());
-    file.setEncoding(value.getString());
-    file.setEmpty(value.getBoolean());
-    file.setOriginalLineOffsets(value.getLongArray());
-    byte[][] lineHashes = new byte[file.lines()][];
-    for (int i = 0; i < file.lines(); i++) {
-      lineHashes[i] = value.getByteArray();
-    }
-    file.setLineHashes(lineHashes);
-    return file;
-  }
-
-}
index 43006d48ef6e6cebdf18cac377075b42ee44b9b6..5f16313e853646ec55e36e2a4585d486795253b1 100644 (file)
  */
 package org.sonar.batch.scan.filesystem;
 
+import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Function;
 import com.google.common.collect.Collections2;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Lists;
 import org.apache.commons.lang.StringUtils;
 import org.sonar.api.CoreProperties;
-import org.sonar.api.batch.bootstrap.ProjectDefinition;
 import org.sonar.api.batch.fs.FilePredicate;
 import org.sonar.api.batch.fs.internal.DefaultFileSystem;
 import org.sonar.api.config.Settings;
@@ -45,8 +45,6 @@ import java.util.List;
 import java.util.Map;
 
 /**
- * This class can't be immutable because of execution of maven plugins that can change the project structure (see MavenPluginHandler and sonar.phase)
- *
  * @since 3.5
  */
 public class DefaultModuleFileSystem extends DefaultFileSystem implements ModuleFileSystem {
@@ -62,27 +60,26 @@ public class DefaultModuleFileSystem extends DefaultFileSystem implements Module
   private ComponentIndexer componentIndexer;
   private boolean initialized;
 
-  /**
-   * Used by scan2 
-   */
-  public DefaultModuleFileSystem(ModuleInputFileCache moduleInputFileCache, ProjectDefinition def, Settings settings,
-    FileIndexer indexer, ModuleFileSystemInitializer initializer) {
-    this(moduleInputFileCache, def.getKey(), settings, indexer, initializer, null);
-  }
-
   public DefaultModuleFileSystem(ModuleInputFileCache moduleInputFileCache, Project project,
-    Settings settings, FileIndexer indexer,
-    ModuleFileSystemInitializer initializer,
-    ComponentIndexer componentIndexer) {
-    this(moduleInputFileCache, project.getKey(), settings, indexer, initializer, componentIndexer);
+    Settings settings, FileIndexer indexer, ModuleFileSystemInitializer initializer, ComponentIndexer componentIndexer) {
+    super(initializer.baseDir().toPath(), moduleInputFileCache);
+    this.componentIndexer = componentIndexer;
+    this.moduleKey = project.getKey();
+    this.settings = settings;
+    this.indexer = indexer;
+    setWorkDir(initializer.workingDir());
+    this.buildDir = initializer.buildDir();
+    this.sourceDirsOrFiles = initializer.sources();
+    this.testDirsOrFiles = initializer.tests();
+    this.binaryDirs = initializer.binaryDirs();
   }
 
-  private DefaultModuleFileSystem(ModuleInputFileCache moduleInputFileCache, String moduleKey, Settings settings,
-    FileIndexer indexer, ModuleFileSystemInitializer initializer,
-    @Nullable ComponentIndexer componentIndexer) {
-    super(initializer.baseDir(), moduleInputFileCache);
+  @VisibleForTesting
+  public DefaultModuleFileSystem(Project project,
+    Settings settings, FileIndexer indexer, ModuleFileSystemInitializer initializer, ComponentIndexer componentIndexer) {
+    super(initializer.baseDir().toPath());
     this.componentIndexer = componentIndexer;
-    this.moduleKey = moduleKey;
+    this.moduleKey = project.getKey();
     this.settings = settings;
     this.indexer = indexer;
     setWorkDir(initializer.workingDir());
@@ -260,30 +257,6 @@ public class DefaultModuleFileSystem extends DefaultFileSystem implements Module
         }
       }));
     }
-    if ("CMP_DEPRECATED_KEY".equals(key)) {
-      return predicates().or(Collections2.transform(value, new Function<String, FilePredicate>() {
-        @Override
-        public FilePredicate apply(@Nullable String s) {
-          return s == null ? predicates().all() : new AdditionalFilePredicates.DeprecatedKeyPredicate(s);
-        }
-      }));
-    }
-    if ("SRC_REL_PATH".equals(key)) {
-      return predicates().or(Collections2.transform(value, new Function<String, FilePredicate>() {
-        @Override
-        public FilePredicate apply(@Nullable String s) {
-          return s == null ? predicates().all() : new AdditionalFilePredicates.SourceRelativePathPredicate(s);
-        }
-      }));
-    }
-    if ("SRC_DIR_PATH".equals(key)) {
-      return predicates().or(Collections2.transform(value, new Function<String, FilePredicate>() {
-        @Override
-        public FilePredicate apply(@Nullable String s) {
-          return s == null ? predicates().all() : new AdditionalFilePredicates.SourceDirPredicate(s);
-        }
-      }));
-    }
     throw new IllegalArgumentException("Unsupported file attribute: " + key);
   }
 
index d52e19b0b0be1d57fbe2997d2f146356d67d21a9..9fa6ea98a23b26b51f8f36a5e5178264e54b48b2 100644 (file)
@@ -21,13 +21,10 @@ package org.sonar.batch.scan.filesystem;
 
 import org.sonar.api.batch.fs.InputFile;
 import org.sonar.api.batch.fs.InputFileFilter;
-import org.sonar.api.batch.fs.internal.DeprecatedDefaultInputFile;
 import org.sonar.api.scan.filesystem.FileSystemFilter;
 import org.sonar.api.scan.filesystem.FileType;
 import org.sonar.api.scan.filesystem.ModuleFileSystem;
 
-import java.io.File;
-
 public class DeprecatedFileFilters implements InputFileFilter {
   private final FileSystemFilter[] filters;
 
@@ -70,14 +67,9 @@ public class DeprecatedFileFilters implements InputFileFilter {
       return FileType.valueOf(type);
     }
 
-    @Override
-    public File relativeDir() {
-      return new File(((DeprecatedDefaultInputFile)inputFile).sourceDirAbsolutePath());
-    }
-
     @Override
     public String relativePath() {
-      return ((DeprecatedDefaultInputFile)inputFile).pathRelativeToSourceDir();
+      return inputFile.relativePath();
     }
 
     @Override
index e78ae260ca35e86528d3481a3619322e8fe298c1..d4626209aa2af28cef8ab79bc49f023466eb73b1 100644 (file)
@@ -23,20 +23,18 @@ import org.apache.commons.io.FileUtils;
 import org.apache.commons.io.filefilter.FileFilterUtils;
 import org.apache.commons.io.filefilter.HiddenFileFilter;
 import org.apache.commons.io.filefilter.IOFileFilter;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 import org.sonar.api.BatchComponent;
 import org.sonar.api.batch.bootstrap.ProjectDefinition;
-import org.sonar.api.batch.fs.InputDir;
 import org.sonar.api.batch.fs.InputFile;
 import org.sonar.api.batch.fs.InputFileFilter;
 import org.sonar.api.batch.fs.internal.DefaultInputDir;
-import org.sonar.api.batch.fs.internal.DefaultInputFile;
 import org.sonar.api.batch.fs.internal.DeprecatedDefaultInputFile;
 import org.sonar.api.scan.filesystem.PathResolver;
 import org.sonar.api.utils.MessageException;
+import org.sonar.batch.util.ProgressReport;
 
 import java.io.File;
+import java.nio.file.Path;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.HashSet;
@@ -47,14 +45,13 @@ import java.util.concurrent.ExecutionException;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
 
 /**
  * Index input files into {@link InputPathCache}.
  */
 public class FileIndexer implements BatchComponent {
 
-  private static final Logger LOG = LoggerFactory.getLogger(FileIndexer.class);
-
   private static final IOFileFilter DIR_FILTER = FileFilterUtils.and(HiddenFileFilter.VISIBLE, FileFilterUtils.notFileFilter(FileFilterUtils.prefixFileFilter(".")));
   private static final IOFileFilter FILE_FILTER = HiddenFileFilter.VISIBLE;
 
@@ -62,18 +59,19 @@ public class FileIndexer implements BatchComponent {
   private final boolean isAggregator;
   private final ExclusionFilters exclusionFilters;
   private final InputFileBuilderFactory inputFileBuilderFactory;
+  private final InputPathCache inputPathCache;
 
-  public FileIndexer(List<InputFileFilter> filters, ExclusionFilters exclusionFilters, InputFileBuilderFactory inputFileBuilderFactory,
-    ProjectDefinition def) {
-    this(filters, exclusionFilters, inputFileBuilderFactory, !def.getSubProjects().isEmpty());
-  }
+  private ProgressReport progressReport;
+  private ExecutorService executorService;
+  private List<Future<Void>> tasks;
 
-  private FileIndexer(List<InputFileFilter> filters, ExclusionFilters exclusionFilters, InputFileBuilderFactory inputFileBuilderFactory,
-    boolean isAggregator) {
+  public FileIndexer(List<InputFileFilter> filters, ExclusionFilters exclusionFilters, InputFileBuilderFactory inputFileBuilderFactory,
+    ProjectDefinition def, InputPathCache inputPathCache) {
+    this.inputPathCache = inputPathCache;
     this.filters = filters;
     this.exclusionFilters = exclusionFilters;
     this.inputFileBuilderFactory = inputFileBuilderFactory;
-    this.isAggregator = isAggregator;
+    this.isAggregator = !def.getSubProjects().isEmpty();
   }
 
   void index(DefaultModuleFileSystem fileSystem) {
@@ -81,47 +79,34 @@ public class FileIndexer implements BatchComponent {
       // No indexing for an aggregator module
       return;
     }
-    LOG.info("Index files");
+    progressReport = new ProgressReport("Report about progress of file indexation", TimeUnit.SECONDS.toMillis(10));
+    progressReport.start("Index files");
     exclusionFilters.prepare();
 
     Progress progress = new Progress();
 
     InputFileBuilder inputFileBuilder = inputFileBuilderFactory.create(fileSystem);
+    executorService = Executors.newFixedThreadPool(Math.max(1, Runtime.getRuntime().availableProcessors() - 1));
+    tasks = new ArrayList<Future<Void>>();
     indexFiles(fileSystem, progress, inputFileBuilder, fileSystem.sources(), InputFile.Type.MAIN);
     indexFiles(fileSystem, progress, inputFileBuilder, fileSystem.tests(), InputFile.Type.TEST);
 
-    indexAllConcurrently(progress);
-
-    // Populate FS in a synchronous way because PersistIt Exchange is not concurrent
-    for (InputFile indexed : progress.indexed) {
-      fileSystem.add(indexed);
-    }
-    for (InputDir indexed : progress.indexedDir) {
-      fileSystem.add(indexed);
-    }
-
-    LOG.info(String.format("%d files indexed", progress.count()));
+    waitForTasksToComplete();
 
+    progressReport.stop(progress.count() + " files indexed");
   }
 
-  private void indexAllConcurrently(Progress progress) {
-    ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 1);
-    try {
-      List<Future<Void>> all = executor.invokeAll(progress.indexingTasks);
-      for (Future<Void> future : all) {
-        future.get();
-      }
-    } catch (InterruptedException e) {
-      throw new IllegalStateException("FileIndexer was interrupted", e);
-    } catch (ExecutionException e) {
-      Throwable cause = e.getCause();
-      if (cause instanceof RuntimeException) {
-        throw (RuntimeException) cause;
-      } else {
-        throw new IllegalStateException("Error during file indexing", e);
+  private void waitForTasksToComplete() {
+    for (Future<Void> task : tasks) {
+      try {
+        task.get();
+      } catch (ExecutionException e) {
+        // Unwrap ExecutionException
+        throw e.getCause() instanceof RuntimeException ? (RuntimeException) e.getCause() : new IllegalStateException(e.getCause());
+      } catch (InterruptedException e) {
+        throw new IllegalStateException(e);
       }
     }
-    executor.shutdown();
   }
 
   private void indexFiles(DefaultModuleFileSystem fileSystem, Progress progress, InputFileBuilder inputFileBuilder, List<File> sources, InputFile.Type type) {
@@ -151,25 +136,25 @@ public class FileIndexer implements BatchComponent {
   private void indexFile(final InputFileBuilder inputFileBuilder, final DefaultModuleFileSystem fs,
     final Progress status, final DeprecatedDefaultInputFile inputFile, final InputFile.Type type) {
 
-    Callable<Void> task = new Callable<Void>() {
-
+    tasks.add(executorService.submit(new Callable<Void>() {
       @Override
-      public Void call() throws Exception {
-        DefaultInputFile completedFile = inputFileBuilder.complete(inputFile, type);
-        if (completedFile != null && accept(completedFile)) {
+      public Void call() {
+        InputFileMetadata metadata = inputFileBuilder.completeAndComputeMetadata(inputFile, type);
+        if (metadata != null && accept(inputFile)) {
+          fs.add(inputFile);
           status.markAsIndexed(inputFile);
+          inputPathCache.put(inputFile.moduleKey(), inputFile.relativePath(), metadata);
           File parentDir = inputFile.file().getParentFile();
           String relativePath = new PathResolver().relativePath(fs.baseDir(), parentDir);
           if (relativePath != null) {
             DefaultInputDir inputDir = new DefaultInputDir(fs.moduleKey(), relativePath);
-            inputDir.setFile(parentDir);
-            status.markAsIndexed(inputDir);
+            fs.add(inputDir);
           }
         }
         return null;
       }
-    };
-    status.planForIndexing(task);
+    }));
+
   }
 
   private boolean accept(InputFile inputFile) {
@@ -182,31 +167,16 @@ public class FileIndexer implements BatchComponent {
     return true;
   }
 
-  private static class Progress {
-    private final Set<InputFile> indexed;
-    private final Set<InputDir> indexedDir;
-    private final List<Callable<Void>> indexingTasks;
-
-    Progress() {
-      this.indexed = new HashSet<InputFile>();
-      this.indexedDir = new HashSet<InputDir>();
-      this.indexingTasks = new ArrayList<Callable<Void>>();
-    }
-
-    void planForIndexing(Callable<Void> indexingTask) {
-      this.indexingTasks.add(indexingTask);
-    }
+  private class Progress {
+    private final Set<Path> indexed = new HashSet<>();
 
     synchronized void markAsIndexed(InputFile inputFile) {
-      if (indexed.contains(inputFile)) {
+      if (indexed.contains(inputFile.path())) {
         throw MessageException.of("File " + inputFile + " can't be indexed twice. Please check that inclusion/exclusion patterns produce "
           + "disjoint sets for main and test files");
       }
-      indexed.add(inputFile);
-    }
-
-    synchronized void markAsIndexed(InputDir inputDir) {
-      indexedDir.add(inputDir);
+      indexed.add(inputFile.path());
+      progressReport.message(indexed.size() + " files indexed...  (last one was " + inputFile.relativePath() + ")");
     }
 
     int count() {
index b3b4d1469fdb9753f480524af9f4097199fed162..0f91e4ae3cccbd52be7d7bcaa585bbbe9d6e46c3 100644 (file)
 package org.sonar.batch.scan.filesystem;
 
 import com.google.common.base.Charsets;
-import com.google.common.primitives.Longs;
+import com.google.common.primitives.Ints;
 import org.apache.commons.codec.binary.Hex;
 import org.apache.commons.codec.digest.DigestUtils;
 import org.apache.commons.io.ByteOrderMark;
 import org.apache.commons.io.input.BOMInputStream;
+import org.sonar.api.BatchComponent;
+import org.sonar.api.batch.AnalysisMode;
 
 import javax.annotation.CheckForNull;
 
-import java.io.*;
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.Reader;
 import java.nio.charset.Charset;
 import java.security.MessageDigest;
 import java.util.ArrayList;
@@ -40,10 +45,15 @@ import java.util.List;
  * Computes hash of files. Ends of Lines are ignored, so files with
  * same content but different EOL encoding have the same hash.
  */
-class FileMetadata {
+public class FileMetadata implements BatchComponent {
 
   private static final char LINE_FEED = '\n';
   private static final char CARRIAGE_RETURN = '\r';
+  private final AnalysisMode analysisMode;
+
+  public FileMetadata(AnalysisMode analysisMode) {
+    this.analysisMode = analysisMode;
+  }
 
   private abstract class CharHandler {
 
@@ -110,14 +120,25 @@ class FileMetadata {
   private class FileHashComputer extends CharHandler {
     private MessageDigest globalMd5Digest = DigestUtils.getMd5Digest();
 
+    StringBuffer sb = new StringBuffer();
+
     @Override
     void handleIgnoreEoL(char c) {
-      updateDigestUTF8Char(c, globalMd5Digest);
+      sb.append(c);
     }
 
     @Override
     void newLine() {
-      updateDigestUTF8Char(LINE_FEED, globalMd5Digest);
+      sb.append(LINE_FEED);
+      globalMd5Digest.update(sb.toString().getBytes(Charsets.UTF_8));
+      sb.setLength(0);
+    }
+
+    @Override
+    void eof() {
+      if (sb.length() > 0) {
+        globalMd5Digest.update(sb.toString().getBytes(Charsets.UTF_8));
+      }
     }
 
     @CheckForNull
@@ -127,11 +148,11 @@ class FileMetadata {
   }
 
   private class LineOffsetCounter extends CharHandler {
-    private long currentOriginalOffset = 0;
-    private List<Long> originalLineOffsets = new ArrayList<Long>();
+    private int currentOriginalOffset = 0;
+    private List<Integer> originalLineOffsets = new ArrayList<Integer>();
 
     public LineOffsetCounter() {
-      originalLineOffsets.add(0L);
+      originalLineOffsets.add(0);
     }
 
     @Override
@@ -144,41 +165,12 @@ class FileMetadata {
       originalLineOffsets.add(currentOriginalOffset);
     }
 
-    public List<Long> getOriginalLineOffsets() {
+    public List<Integer> getOriginalLineOffsets() {
       return originalLineOffsets;
     }
 
   }
 
-  private class LineHashesComputer extends CharHandler {
-    private List<Object> lineHashes = new ArrayList<Object>();
-    private MessageDigest lineMd5Digest = DigestUtils.getMd5Digest();
-    private boolean blankLine = true;
-
-    @Override
-    void handleIgnoreEoL(char c) {
-      if (!Character.isWhitespace(c)) {
-        blankLine = false;
-        updateDigestUTF8Char(c, lineMd5Digest);
-      }
-    }
-
-    @Override
-    void newLine() {
-      lineHashes.add(blankLine ? null : lineMd5Digest.digest());
-      blankLine = true;
-    }
-
-    @Override
-    void eof() {
-      lineHashes.add(blankLine ? null : lineMd5Digest.digest());
-    }
-
-    public byte[][] lineHashes() {
-      return lineHashes.toArray(new byte[0][]);
-    }
-  }
-
   /**
    * Compute hash of a file ignoring line ends differences.
    * Maximum performance is needed.
@@ -188,8 +180,13 @@ class FileMetadata {
     LineCounter lineCounter = new LineCounter();
     FileHashComputer fileHashComputer = new FileHashComputer();
     LineOffsetCounter lineOffsetCounter = new LineOffsetCounter();
-    LineHashesComputer lineHashesComputer = new LineHashesComputer();
-    CharHandler[] handlers = new CharHandler[] {lineCounter, fileHashComputer, lineOffsetCounter, lineHashesComputer};
+    CharHandler[] handlers;
+    if (analysisMode.isPreview()) {
+      // No need to compute line offsets in preview mode since there is no syntax highlighting
+      handlers = new CharHandler[] {lineCounter, fileHashComputer};
+    } else {
+      handlers = new CharHandler[] {lineCounter, fileHashComputer, lineOffsetCounter};
+    }
     try (BOMInputStream bomIn = new BOMInputStream(new FileInputStream(file),
       ByteOrderMark.UTF_8, ByteOrderMark.UTF_16LE, ByteOrderMark.UTF_16BE, ByteOrderMark.UTF_32LE, ByteOrderMark.UTF_32BE);
       Reader reader = new BufferedReader(new InputStreamReader(bomIn, encoding))) {
@@ -228,41 +225,26 @@ class FileMetadata {
         handler.eof();
       }
       return new Metadata(lineCounter.lines(), lineCounter.nonBlankLines(), fileHashComputer.getHash(), lineOffsetCounter.getOriginalLineOffsets(),
-        lineHashesComputer.lineHashes(), lineCounter.isEmpty());
+        lineCounter.isEmpty());
 
     } catch (IOException e) {
       throw new IllegalStateException(String.format("Fail to read file '%s' with encoding '%s'", file.getAbsolutePath(), encoding), e);
     }
   }
 
-  private void updateDigestUTF8Char(char c, MessageDigest md5Digest) {
-    CharBuffer cb = CharBuffer.allocate(1);
-    cb.put(c);
-    cb.flip();
-    ByteBuffer bb = Charsets.UTF_8.encode(cb);
-    byte[] array = bb.array();
-    for (int i = 0; i < array.length; i++) {
-      if (array[i] != 0) {
-        md5Digest.update(array[i]);
-      }
-    }
-  }
-
   static class Metadata {
     final int lines;
     final int nonBlankLines;
     final String hash;
-    final long[] originalLineOffsets;
-    final byte[][] lineHashes;
+    final int[] originalLineOffsets;
     final boolean empty;
 
-    private Metadata(int lines, int nonBlankLines, String hash, List<Long> originalLineOffsets, byte[][] lineHashes, boolean empty) {
+    private Metadata(int lines, int nonBlankLines, String hash, List<Integer> originalLineOffsets, boolean empty) {
       this.lines = lines;
       this.nonBlankLines = nonBlankLines;
       this.hash = hash;
       this.empty = empty;
-      this.originalLineOffsets = Longs.toArray(originalLineOffsets);
-      this.lineHashes = lineHashes;
+      this.originalLineOffsets = Ints.toArray(originalLineOffsets);
     }
   }
 }
index 748410fea36969a6ea825d8c8edf49e49558c4d9..56b8319ac44e023dde1192624e9372d077ab0c03 100644 (file)
@@ -19,7 +19,6 @@
  */
 package org.sonar.batch.scan.filesystem;
 
-import org.apache.commons.io.FilenameUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.sonar.api.CoreProperties;
@@ -29,12 +28,10 @@ import org.sonar.api.batch.fs.internal.DeprecatedDefaultInputFile;
 import org.sonar.api.config.Settings;
 import org.sonar.api.scan.filesystem.PathResolver;
 import org.sonar.batch.bootstrap.DefaultAnalysisMode;
-import org.sonar.batch.util.DeprecatedKeyUtils;
 
 import javax.annotation.CheckForNull;
 
 import java.io.File;
-import java.util.List;
 
 class InputFileBuilder {
 
@@ -47,9 +44,10 @@ class InputFileBuilder {
   private final DefaultModuleFileSystem fs;
   private final DefaultAnalysisMode analysisMode;
   private final Settings settings;
+  private final FileMetadata fileMetadata;
 
   InputFileBuilder(String moduleKey, PathResolver pathResolver, LanguageDetection langDetection,
-    StatusDetection statusDetection, DefaultModuleFileSystem fs, DefaultAnalysisMode analysisMode, Settings settings) {
+    StatusDetection statusDetection, DefaultModuleFileSystem fs, DefaultAnalysisMode analysisMode, Settings settings, FileMetadata fileMetadata) {
     this.moduleKey = moduleKey;
     this.pathResolver = pathResolver;
     this.langDetection = langDetection;
@@ -57,6 +55,7 @@ class InputFileBuilder {
     this.fs = fs;
     this.analysisMode = analysisMode;
     this.settings = settings;
+    this.fileMetadata = fileMetadata;
   }
 
   String moduleKey() {
@@ -86,20 +85,17 @@ class InputFileBuilder {
       LOG.warn("File '{}' is ignored. It is not located in module basedir '{}'.", file.getAbsolutePath(), fs.baseDir());
       return null;
     }
-    DeprecatedDefaultInputFile inputFile = new DeprecatedDefaultInputFile(moduleKey, relativePath);
-    inputFile.setBasedir(fs.baseDir());
-    inputFile.setFile(file);
-    return inputFile;
+    return new DeprecatedDefaultInputFile(moduleKey, relativePath);
   }
 
   /**
-   * Optimization to not set all InputFile data if the file is excluded from analysis.
+   * Optimization to not compute InputFile metadata if the file is excluded from analysis.
    */
   @CheckForNull
-  DeprecatedDefaultInputFile complete(DeprecatedDefaultInputFile inputFile, InputFile.Type type) {
+  InputFileMetadata completeAndComputeMetadata(DeprecatedDefaultInputFile inputFile, InputFile.Type type) {
     inputFile.setType(type);
-    inputFile.setBasedir(fs.baseDir());
-    inputFile.setEncoding(fs.encoding().name());
+    inputFile.setModuleBaseDir(fs.baseDir().toPath());
+    inputFile.setCharset(fs.encoding());
 
     String lang = langDetection.language(inputFile);
     if (lang == null && !settings.getBoolean(CoreProperties.IMPORT_UNKNOWN_FILES_KEY)) {
@@ -107,36 +103,21 @@ class InputFileBuilder {
     }
     inputFile.setLanguage(lang);
 
-    FileMetadata.Metadata metadata = new FileMetadata().read(inputFile.file(), fs.encoding());
+    InputFileMetadata result = new InputFileMetadata();
+
+    FileMetadata.Metadata metadata = fileMetadata.read(inputFile.file(), fs.encoding());
     inputFile.setLines(metadata.lines);
-    inputFile.setNonBlankLines(metadata.nonBlankLines);
-    inputFile.setHash(metadata.hash);
-    inputFile.setOriginalLineOffsets(metadata.originalLineOffsets);
-    inputFile.setLineHashes(metadata.lineHashes);
-    inputFile.setEmpty(metadata.empty);
+
+    result.setNonBlankLines(metadata.nonBlankLines);
+    result.setHash(metadata.hash);
+    result.setOriginalLineOffsets(metadata.originalLineOffsets);
+    result.setEmpty(metadata.empty);
+
     inputFile.setStatus(statusDetection.status(inputFile.moduleKey(), inputFile.relativePath(), metadata.hash));
     if (analysisMode.isIncremental() && inputFile.status() == InputFile.Status.SAME) {
       return null;
     }
-    fillDeprecatedData(inputFile);
-    return inputFile;
+    return result;
   }
 
-  private void fillDeprecatedData(DeprecatedDefaultInputFile inputFile) {
-    List<File> sourceDirs = InputFile.Type.MAIN == inputFile.type() ? fs.sourceDirs() : fs.testDirs();
-    for (File sourceDir : sourceDirs) {
-      String sourceRelativePath = pathResolver.relativePath(sourceDir, inputFile.file());
-      if (sourceRelativePath != null) {
-        inputFile.setPathRelativeToSourceDir(sourceRelativePath);
-        inputFile.setSourceDirAbsolutePath(FilenameUtils.normalize(sourceDir.getAbsolutePath(), true));
-
-        if ("java".equals(inputFile.language())) {
-          inputFile.setDeprecatedKey(new StringBuilder()
-            .append(moduleKey).append(":").append(DeprecatedKeyUtils.getJavaFileDeprecatedKey(sourceRelativePath)).toString());
-        } else {
-          inputFile.setDeprecatedKey(new StringBuilder().append(moduleKey).append(":").append(sourceRelativePath).toString());
-        }
-      }
-    }
-  }
 }
index c3dde447e018eeb6564a02f2b8afe9792990cb87..c173975fc532b905b0d1eac9d350424bcd631456 100644 (file)
@@ -33,15 +33,12 @@ public class InputFileBuilderFactory implements BatchComponent {
   private final StatusDetectionFactory statusDetectionFactory;
   private final DefaultAnalysisMode analysisMode;
   private final Settings settings;
+  private final FileMetadata fileMetadata;
 
   public InputFileBuilderFactory(ProjectDefinition def, PathResolver pathResolver, LanguageDetectionFactory langDetectionFactory,
-    StatusDetectionFactory statusDetectionFactory, DefaultAnalysisMode analysisMode, Settings settings) {
-    this(def.getKeyWithBranch(), pathResolver, langDetectionFactory, statusDetectionFactory, analysisMode, settings);
-  }
-
-  private InputFileBuilderFactory(String effectiveKey, PathResolver pathResolver, LanguageDetectionFactory langDetectionFactory,
-    StatusDetectionFactory statusDetectionFactory, DefaultAnalysisMode analysisMode, Settings settings) {
-    this.moduleKey = effectiveKey;
+    StatusDetectionFactory statusDetectionFactory, DefaultAnalysisMode analysisMode, Settings settings, FileMetadata fileMetadata) {
+    this.fileMetadata = fileMetadata;
+    this.moduleKey = def.getKeyWithBranch();
     this.pathResolver = pathResolver;
     this.langDetectionFactory = langDetectionFactory;
     this.statusDetectionFactory = statusDetectionFactory;
@@ -50,6 +47,6 @@ public class InputFileBuilderFactory implements BatchComponent {
   }
 
   InputFileBuilder create(DefaultModuleFileSystem fs) {
-    return new InputFileBuilder(moduleKey, pathResolver, langDetectionFactory.create(), statusDetectionFactory.create(), fs, analysisMode, settings);
+    return new InputFileBuilder(moduleKey, pathResolver, langDetectionFactory.create(), statusDetectionFactory.create(), fs, analysisMode, settings, fileMetadata);
   }
 }
diff --git a/sonar-batch/src/main/java/org/sonar/batch/scan/filesystem/InputFileMetadata.java b/sonar-batch/src/main/java/org/sonar/batch/scan/filesystem/InputFileMetadata.java
new file mode 100644 (file)
index 0000000..f37c672
--- /dev/null
@@ -0,0 +1,73 @@
+/*
+ * 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.batch.scan.filesystem;
+
+import java.io.Serializable;
+
+/**
+ * Additional input file metadata that are stored in a disk storage to save memory
+ */
+public class InputFileMetadata implements Serializable {
+
+  private String hash;
+  private int nonBlankLines;
+  private int[] originalLineOffsets;
+  private boolean empty;
+
+  /**
+   * Digest hash of the file.
+   */
+  public String hash() {
+    return hash;
+  }
+
+  public int nonBlankLines() {
+    return nonBlankLines;
+  }
+
+  public int[] originalLineOffsets() {
+    return originalLineOffsets;
+  }
+
+  public InputFileMetadata setHash(String hash) {
+    this.hash = hash;
+    return this;
+  }
+
+  public InputFileMetadata setNonBlankLines(int nonBlankLines) {
+    this.nonBlankLines = nonBlankLines;
+    return this;
+  }
+
+  public InputFileMetadata setOriginalLineOffsets(int[] originalLineOffsets) {
+    this.originalLineOffsets = originalLineOffsets;
+    return this;
+  }
+
+  public boolean isEmpty() {
+    return this.empty;
+  }
+
+  public InputFileMetadata setEmpty(boolean empty) {
+    this.empty = empty;
+    return this;
+  }
+
+}
index adc1a16150c0ae2d7f4b813543921cabbcd33ed4..6270eda9cf24860bacf8964489019adaec7a4e0a 100644 (file)
  */
 package org.sonar.batch.scan.filesystem;
 
+import com.google.common.base.Function;
+import com.google.common.collect.Iterables;
 import org.sonar.api.BatchComponent;
 import org.sonar.api.batch.fs.InputDir;
 import org.sonar.api.batch.fs.InputFile;
 import org.sonar.api.batch.fs.InputPath;
-import org.sonar.api.batch.fs.internal.DeprecatedDefaultInputFile;
 import org.sonar.batch.index.BatchResource;
-import org.sonar.batch.index.Cache;
-import org.sonar.batch.index.Caches;
 
 import javax.annotation.CheckForNull;
 
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
 /**
- * Cache of all files. This cache is shared amongst all project modules. Inclusion and
+ * Cache of all files and dirs. This cache is shared amongst all project modules. Inclusion and
  * exclusion patterns are already applied.
  */
 public class InputPathCache implements BatchComponent {
 
-  private static final String DIR = "DIR";
-  private static final String FILE = "FILE";
-  // [module key | type | path] -> InputPath
-  // For example:
-  // [struts-core | FILE | src/main/java/Action.java] -> InputFile
-  // [struts-core | FILE | src/main/java/Filter.java] -> InputFile
-  // [struts-core | DIR | src/main/java] -> InputDir
-  private final Cache<InputPath> cache;
-
-  public InputPathCache(Caches caches) {
-    caches.registerValueCoder(DeprecatedDefaultInputFile.class, new DefaultInputFileValueCoder());
-    cache = caches.createCache("inputFiles");
+  private final Map<String, Map<String, InputFile>> inputFileCache = new HashMap<>();
+  private final Map<String, Map<String, InputDir>> inputDirCache = new HashMap<>();
+  private final Map<String, Map<String, InputFileMetadata>> inputFileMetadataCache = new HashMap<>();
+
+  public Iterable<InputFile> allFiles() {
+    return Iterables.concat(Iterables.transform(inputFileCache.values(), new Function<Map<String, InputFile>, Collection<InputFile>>() {
+      @Override
+      public Collection<InputFile> apply(Map<String, InputFile> input) {
+        return input.values();
+      }
+    }));
   }
 
-  public Iterable<InputPath> all() {
-    return cache.values();
+  public Iterable<InputDir> allDirs() {
+    return Iterables.concat(Iterables.transform(inputDirCache.values(), new Function<Map<String, InputDir>, Collection<InputDir>>() {
+      @Override
+      public Collection<InputDir> apply(Map<String, InputDir> input) {
+        return input.values();
+      }
+    }));
   }
 
   public Iterable<InputFile> filesByModule(String moduleKey) {
-    return (Iterable) cache.values(moduleKey, FILE);
+    if (inputFileCache.containsKey(moduleKey)) {
+      return inputFileCache.get(moduleKey).values();
+    }
+    return Collections.emptyList();
   }
 
   public Iterable<InputDir> dirsByModule(String moduleKey) {
-    return (Iterable) cache.values(moduleKey, DIR);
+    if (inputDirCache.containsKey(moduleKey)) {
+      return inputDirCache.get(moduleKey).values();
+    }
+    return Collections.emptyList();
   }
 
   public InputPathCache removeModule(String moduleKey) {
-    cache.clear(moduleKey);
+    inputFileCache.remove(moduleKey);
+    inputDirCache.remove(moduleKey);
+    inputFileMetadataCache.remove(moduleKey);
     return this;
   }
 
   public InputPathCache remove(String moduleKey, InputFile inputFile) {
-    cache.remove(moduleKey, FILE, inputFile.relativePath());
+    if (inputFileCache.containsKey(moduleKey)) {
+      inputFileCache.get(moduleKey).remove(inputFile.relativePath());
+    }
+    if (inputFileMetadataCache.containsKey(moduleKey)) {
+      inputFileMetadataCache.get(moduleKey).remove(inputFile.relativePath());
+    }
     return this;
   }
 
   public InputPathCache remove(String moduleKey, InputDir inputDir) {
-    cache.remove(moduleKey, DIR, inputDir.relativePath());
+    if (inputDirCache.containsKey(moduleKey)) {
+      inputDirCache.get(moduleKey).remove(inputDir.relativePath());
+    }
     return this;
   }
 
   public InputPathCache put(String moduleKey, InputFile inputFile) {
-    cache.put(moduleKey, FILE, inputFile.relativePath(), inputFile);
+    if (!inputFileCache.containsKey(moduleKey)) {
+      inputFileCache.put(moduleKey, new HashMap<String, InputFile>());
+    }
+    inputFileCache.get(moduleKey).put(inputFile.relativePath(), inputFile);
+    return this;
+  }
+
+  public synchronized InputPathCache put(String moduleKey, String relativePath, InputFileMetadata metadata) {
+    if (!inputFileMetadataCache.containsKey(moduleKey)) {
+      inputFileMetadataCache.put(moduleKey, new HashMap<String, InputFileMetadata>());
+    }
+    inputFileMetadataCache.get(moduleKey).put(relativePath, metadata);
     return this;
   }
 
   public InputPathCache put(String moduleKey, InputDir inputDir) {
-    cache.put(moduleKey, DIR, inputDir.relativePath(), inputDir);
+    if (!inputDirCache.containsKey(moduleKey)) {
+      inputDirCache.put(moduleKey, new HashMap<String, InputDir>());
+    }
+    inputDirCache.get(moduleKey).put(inputDir.relativePath(), inputDir);
     return this;
   }
 
   @CheckForNull
   public InputFile getFile(String moduleKey, String relativePath) {
-    return (InputFile) cache.get(moduleKey, FILE, relativePath);
+    if (inputFileCache.containsKey(moduleKey)) {
+      return inputFileCache.get(moduleKey).get(relativePath);
+    }
+    return null;
+  }
+
+  @CheckForNull
+  public InputFileMetadata getFileMetadata(String moduleKey, String relativePath) {
+    if (inputFileMetadataCache.containsKey(moduleKey)) {
+      return inputFileMetadataCache.get(moduleKey).get(relativePath);
+    }
+    return null;
   }
 
   @CheckForNull
   public InputDir getDir(String moduleKey, String relativePath) {
-    return (InputDir) cache.get(moduleKey, DIR, relativePath);
+    if (inputDirCache.containsKey(moduleKey)) {
+      return inputDirCache.get(moduleKey).get(relativePath);
+    }
+    return null;
   }
 
   @CheckForNull
index 1ee5379f579d72a4d03b2ef4096884ccb8806a81..131ac8a4ca4e7e509ee1b6a160c2bb364a01fb25 100644 (file)
@@ -19,7 +19,8 @@
  */
 package org.sonar.batch.scan.filesystem;
 
-import org.sonar.batch.languages.Language;
+import org.sonar.batch.repository.language.Language;
+import org.sonar.batch.repository.language.LanguagesRepository;
 
 import com.google.common.base.Joiner;
 import com.google.common.collect.Lists;
@@ -32,7 +33,6 @@ import org.sonar.api.batch.fs.InputFile;
 import org.sonar.api.batch.fs.internal.PathPattern;
 import org.sonar.api.config.Settings;
 import org.sonar.api.utils.MessageException;
-import org.sonar.batch.languages.LanguagesReferential;
 
 import javax.annotation.CheckForNull;
 
@@ -54,7 +54,7 @@ class LanguageDetection {
   private final List<String> languagesToConsider = Lists.newArrayList();
   private final String forcedLanguage;
 
-  LanguageDetection(Settings settings, LanguagesReferential languages) {
+  LanguageDetection(Settings settings, LanguagesRepository languages) {
     for (Language language : languages.all()) {
       String[] filePatterns = settings.getStringArray(getFileLangPatternPropKey(language.key()));
       PathPattern[] pathPatterns = PathPattern.create(filePatterns);
index 6ff579fd769010ddfbca32e1ece050e7be8cb175..c52118612c39e5b7f48e7e7a054638a056a791b7 100644 (file)
  */
 package org.sonar.batch.scan.filesystem;
 
+import org.sonar.batch.repository.language.LanguagesRepository;
+
 import org.sonar.api.BatchComponent;
 import org.sonar.api.config.Settings;
-import org.sonar.batch.languages.LanguagesReferential;
 
 public class LanguageDetectionFactory implements BatchComponent {
   private final Settings settings;
-  private final LanguagesReferential languages;
+  private final LanguagesRepository languages;
 
-  public LanguageDetectionFactory(Settings settings, LanguagesReferential languages) {
+  public LanguageDetectionFactory(Settings settings, LanguagesRepository languages) {
     this.settings = settings;
     this.languages = languages;
   }
index b932295dc40ecded55ee2b4d9ab794f23c55644f..17420fc2dc850271e24177739c04df6d636b260a 100644 (file)
@@ -28,35 +28,35 @@ import org.sonar.api.batch.fs.internal.DefaultFileSystem;
 public class ModuleInputFileCache extends DefaultFileSystem.Cache implements BatchComponent {
 
   private final String moduleKey;
-  private final InputPathCache projectCache;
+  private final InputPathCache inputPathCache;
 
   public ModuleInputFileCache(ProjectDefinition projectDef, InputPathCache projectCache) {
     this.moduleKey = projectDef.getKeyWithBranch();
-    this.projectCache = projectCache;
+    this.inputPathCache = projectCache;
   }
 
   @Override
   public Iterable<InputFile> inputFiles() {
-    return projectCache.filesByModule(moduleKey);
+    return inputPathCache.filesByModule(moduleKey);
   }
 
   @Override
   public InputFile inputFile(String relativePath) {
-    return projectCache.getFile(moduleKey, relativePath);
+    return inputPathCache.getFile(moduleKey, relativePath);
   }
 
   @Override
   public InputDir inputDir(String relativePath) {
-    return projectCache.getDir(moduleKey, relativePath);
+    return inputPathCache.getDir(moduleKey, relativePath);
   }
 
   @Override
   protected void doAdd(InputFile inputFile) {
-    projectCache.put(moduleKey, inputFile);
+    inputPathCache.put(moduleKey, inputFile);
   }
 
   @Override
   protected void doAdd(InputDir inputDir) {
-    projectCache.put(moduleKey, inputDir);
+    inputPathCache.put(moduleKey, inputDir);
   }
 }
index d4fd9b6923139aa68b4332ef2a420ab95850b4de..19523999ab04ad9f4bc3652e6d646d2fb75b18a7 100644 (file)
@@ -30,7 +30,6 @@ import org.sonar.api.PropertyType;
 import org.sonar.api.batch.fs.FileSystem;
 import org.sonar.api.batch.fs.InputDir;
 import org.sonar.api.batch.fs.InputFile;
-import org.sonar.api.batch.fs.InputPath;
 import org.sonar.api.batch.fs.internal.DefaultInputDir;
 import org.sonar.api.batch.fs.internal.DefaultInputFile;
 import org.sonar.api.batch.rule.ActiveRules;
@@ -43,9 +42,9 @@ import org.sonar.api.rule.RuleKey;
 import org.sonar.api.utils.SonarException;
 import org.sonar.api.utils.text.JsonWriter;
 import org.sonar.batch.issue.IssueCache;
+import org.sonar.batch.repository.user.User;
+import org.sonar.batch.repository.user.UserRepository;
 import org.sonar.batch.scan.filesystem.InputPathCache;
-import org.sonar.batch.user.User;
-import org.sonar.batch.user.UserRepository;
 
 import java.io.BufferedWriter;
 import java.io.File;
@@ -167,27 +166,24 @@ public class JSONReport implements Reporter {
     json.name("components").beginArray();
     // Dump modules
     writeJsonModuleComponents(json, rootModule);
-    for (InputPath inputPath : fileCache.all()) {
-      if (inputPath instanceof InputFile) {
-        InputFile inputFile = (InputFile) inputPath;
-        String key = ((DefaultInputFile) inputFile).key();
-        json
-          .beginObject()
-          .prop("key", key)
-          .prop("path", inputFile.relativePath())
-          .prop("moduleKey", StringUtils.substringBeforeLast(key, ":"))
-          .prop("status", inputFile.status().name())
-          .endObject();
-      } else {
-        InputDir inputDir = (InputDir) inputPath;
-        String key = ((DefaultInputDir) inputDir).key();
-        json
-          .beginObject()
-          .prop("key", key)
-          .prop("path", inputDir.relativePath())
-          .prop("moduleKey", StringUtils.substringBeforeLast(key, ":"))
-          .endObject();
-      }
+    for (InputFile inputFile : fileCache.allFiles()) {
+      String key = ((DefaultInputFile) inputFile).key();
+      json
+        .beginObject()
+        .prop("key", key)
+        .prop("path", inputFile.relativePath())
+        .prop("moduleKey", StringUtils.substringBeforeLast(key, ":"))
+        .prop("status", inputFile.status().name())
+        .endObject();
+    }
+    for (InputDir inputDir : fileCache.allDirs()) {
+      String key = ((DefaultInputDir) inputDir).key();
+      json
+        .beginObject()
+        .prop("key", key)
+        .prop("path", inputDir.relativePath())
+        .prop("moduleKey", StringUtils.substringBeforeLast(key, ":"))
+        .endObject();
 
     }
     json.endArray();
index 2a33ed3b3fb965bc6f940919cc8a22908bd96971..74fccaa446a51055b3bc1b880f5d0155987d38d5 100644 (file)
@@ -35,6 +35,8 @@ import org.sonar.api.measures.CoreMetrics;
 import org.sonar.api.utils.TimeProfiler;
 import org.sonar.batch.protocol.input.FileData;
 import org.sonar.batch.protocol.input.ProjectRepositories;
+import org.sonar.batch.scan.filesystem.InputFileMetadata;
+import org.sonar.batch.scan.filesystem.InputPathCache;
 
 import java.util.LinkedList;
 import java.util.List;
@@ -47,13 +49,15 @@ public final class ScmSensor implements Sensor {
   private final ScmConfiguration configuration;
   private final FileSystem fs;
   private final ProjectRepositories projectReferentials;
+  private final InputPathCache inputPathCache;
 
   public ScmSensor(ProjectDefinition projectDefinition, ScmConfiguration configuration,
-    ProjectRepositories projectReferentials, FileSystem fs) {
+    ProjectRepositories projectReferentials, FileSystem fs, InputPathCache inputPathCache) {
     this.projectDefinition = projectDefinition;
     this.configuration = configuration;
     this.projectReferentials = projectReferentials;
     this.fs = fs;
+    this.inputPathCache = inputPathCache;
   }
 
   @Override
@@ -104,7 +108,7 @@ public final class ScmSensor implements Sensor {
 
     if (f.status() == Status.SAME && fileData != null) {
       if (fileData.needBlame()) {
-        addIfNotEmpty(filesToBlame, f);
+        addIfNotEmpty(filesToBlame, (DefaultInputFile) f);
       } else {
         // Copy previous measures
         String scmAuthorsByLine = fileData.scmAuthorsByLine();
@@ -117,12 +121,13 @@ public final class ScmSensor implements Sensor {
         }
       }
     } else {
-      addIfNotEmpty(filesToBlame, f);
+      addIfNotEmpty(filesToBlame, (DefaultInputFile) f);
     }
   }
 
-  private void addIfNotEmpty(List<InputFile> filesToBlame, InputFile f) {
-    if (!((DefaultInputFile) f).isEmpty()) {
+  private void addIfNotEmpty(List<InputFile> filesToBlame, DefaultInputFile f) {
+    InputFileMetadata metadata = inputPathCache.getFileMetadata(f.moduleKey(), f.relativePath());
+    if (!metadata.isEmpty()) {
       filesToBlame.add(f);
     }
   }
index f0d4789f7bc00266d3937df3c287cd9f147b8667..4b99191538a49a318edb52450a54d62c31fba1e3 100644 (file)
@@ -37,6 +37,7 @@ import java.io.File;
 import java.io.FileInputStream;
 import java.io.InputStreamReader;
 import java.io.Reader;
+import java.nio.charset.Charset;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -67,7 +68,7 @@ public class CodeColorizers implements BatchComponent {
   }
 
   @CheckForNull
-  public SyntaxHighlightingData toSyntaxHighlighting(File file, String encoding, String language) {
+  public SyntaxHighlightingData toSyntaxHighlighting(File file, Charset charset, String language) {
     CodeColorizerFormat format = byLang.get(language);
     List<Tokenizer> tokenizers;
     if (format == null) {
@@ -81,7 +82,7 @@ public class CodeColorizers implements BatchComponent {
     } else {
       tokenizers = format.getTokenizers();
     }
-    try (Reader reader = new BufferedReader(new InputStreamReader(new BOMInputStream(new FileInputStream(file)), encoding))) {
+    try (Reader reader = new BufferedReader(new InputStreamReader(new BOMInputStream(new FileInputStream(file)), charset))) {
       return new HighlightingRenderer().render(reader, tokenizers);
     } catch (Exception e) {
       throw new IllegalStateException("Unable to read source file for colorization", e);
index 4829066972a2908c4b14e4ac211d8c27b48ae11a..b2f159d099771053b2b95d13ac578224163043b7 100644 (file)
@@ -29,14 +29,16 @@ import org.sonar.api.batch.sensor.SensorContext;
 import org.sonar.api.batch.sensor.SensorDescriptor;
 import org.sonar.api.batch.sensor.measure.internal.DefaultMeasure;
 import org.sonar.api.measures.CoreMetrics;
+import org.sonar.batch.scan.filesystem.InputFileMetadata;
+import org.sonar.batch.scan.filesystem.InputPathCache;
 
 @Phase(name = Phase.Name.PRE)
 public final class LinesSensor implements Sensor {
 
-  private final FileSystem fs;
+  private final InputPathCache inputPathCache;
 
-  public LinesSensor(FileSystem fs) {
-    this.fs = fs;
+  public LinesSensor(InputPathCache inputPathCache) {
+    this.inputPathCache = inputPathCache;
   }
 
   @Override
@@ -46,6 +48,7 @@ public final class LinesSensor implements Sensor {
 
   @Override
   public void execute(final SensorContext context) {
+    FileSystem fs = context.fileSystem();
     for (InputFile f : fs.inputFiles(fs.predicates().hasType(Type.MAIN))) {
       ((DefaultMeasure<Integer>) context.<Integer>newMeasure()
         .onFile(f)
@@ -55,10 +58,11 @@ public final class LinesSensor implements Sensor {
         .save();
       if (f.language() == null) {
         // As an approximation for files with no language plugin we consider every non blank line as ncloc
+        InputFileMetadata metadata = inputPathCache.getFileMetadata(((DefaultInputFile) f).moduleKey(), f.relativePath());
         ((DefaultMeasure<Integer>) context.<Integer>newMeasure()
           .onFile(f)
           .forMetric(CoreMetrics.NCLOC)
-          .withValue(((DefaultInputFile) f).nonBlankLines()))
+          .withValue(metadata.nonBlankLines()))
           .save();
       }
     }
diff --git a/sonar-batch/src/main/java/org/sonar/batch/tasks/ListTask.java b/sonar-batch/src/main/java/org/sonar/batch/tasks/ListTask.java
deleted file mode 100644 (file)
index 93a0419..0000000
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * 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.batch.tasks;
-
-import org.sonar.api.task.Task;
-import org.sonar.api.task.TaskDefinition;
-
-public class ListTask implements Task {
-
-  public static final String KEY = "list";
-
-  public static final TaskDefinition DEFINITION = TaskDefinition.builder()
-    .key(KEY)
-    .description("List available tasks")
-    .taskClass(ListTask.class)
-    .build();
-
-  private final Tasks tasks;
-
-  public ListTask(Tasks tasks) {
-    this.tasks = tasks;
-  }
-
-  @Override
-  public void execute() {
-    logBlankLine();
-    log("Available tasks:");
-    logBlankLine();
-    for (TaskDefinition def : tasks.definitions()) {
-      log("  - " + def.key() + ": " + def.description());
-    }
-    logBlankLine();
-  }
-
-  void log(String s) {
-    System.out.println(s);
-  }
-
-  void logBlankLine() {
-    System.out.println();
-  }
-}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/tasks/Tasks.java b/sonar-batch/src/main/java/org/sonar/batch/tasks/Tasks.java
deleted file mode 100644 (file)
index f68fb69..0000000
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * 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.batch.tasks;
-
-import com.google.common.collect.ImmutableSortedMap;
-import com.google.common.collect.Maps;
-import org.sonar.api.task.Task;
-import org.sonar.api.task.TaskComponent;
-import org.sonar.api.task.TaskDefinition;
-import org.sonar.api.utils.SonarException;
-
-import java.util.Collection;
-import java.util.Map;
-import java.util.SortedMap;
-
-public class Tasks implements TaskComponent {
-
-  private final SortedMap<String, TaskDefinition> byKey;
-
-  public Tasks(TaskDefinition[] definitions) {
-    SortedMap<String, TaskDefinition> map = Maps.newTreeMap();
-    for (TaskDefinition definition : definitions) {
-      if (map.containsKey(definition.key())) {
-        throw new SonarException("Task '" + definition.key() + "' is declared twice");
-      }
-      map.put(definition.key(), definition);
-    }
-    this.byKey = ImmutableSortedMap.copyOf(map);
-  }
-
-  public TaskDefinition definition(String taskKey) {
-    return byKey.get(taskKey);
-  }
-
-  public Collection<TaskDefinition> definitions() {
-    return byKey.values();
-  }
-
-  /**
-   * Perform validation of task definitions
-   */
-  public void start() {
-    checkDuplicatedClasses();
-  }
-
-  private void checkDuplicatedClasses() {
-    Map<Class<? extends Task>, TaskDefinition> byClass = Maps.newHashMap();
-    for (TaskDefinition def : definitions()) {
-      TaskDefinition other = byClass.get(def.taskClass());
-      if (other == null) {
-        byClass.put(def.taskClass(), def);
-      } else {
-        throw new SonarException("Task '" + def.taskClass().getName() + "' is defined twice: first by '" + other.key() + "' and then by '" + def.key() + "'");
-      }
-    }
-  }
-}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/tasks/package-info.java b/sonar-batch/src/main/java/org/sonar/batch/tasks/package-info.java
deleted file mode 100644 (file)
index 0f2b4e0..0000000
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * 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.
- */
-@ParametersAreNonnullByDefault
-package org.sonar.batch.tasks;
-
-import javax.annotation.ParametersAreNonnullByDefault;
diff --git a/sonar-batch/src/main/java/org/sonar/batch/user/User.java b/sonar-batch/src/main/java/org/sonar/batch/user/User.java
deleted file mode 100644 (file)
index bd96d27..0000000
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * 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.batch.user;
-
-import org.apache.commons.lang.builder.EqualsBuilder;
-
-public class User {
-
-  private final String login;
-  private final String name;
-
-  public User(String login, String name) {
-    this.login = login;
-    this.name = name;
-  }
-
-  public String login() {
-    return login;
-  }
-
-  public String name() {
-    return name;
-  }
-
-  // For testing
-  @Override
-  public boolean equals(Object obj) {
-    if (obj == null) {
-      return false;
-    }
-    if (obj == this) {
-      return true;
-    }
-    if (obj.getClass() != getClass()) {
-      return false;
-    }
-    User rhs = (User) obj;
-    return new EqualsBuilder()
-      .append(login, rhs.login)
-      .append(name, rhs.name)
-      .isEquals();
-  }
-
-}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/user/UserRepository.java b/sonar-batch/src/main/java/org/sonar/batch/user/UserRepository.java
deleted file mode 100644 (file)
index c129bb7..0000000
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * 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.batch.user;
-
-import com.google.common.base.Joiner;
-import org.sonar.batch.bootstrap.ServerClient;
-import org.sonar.batch.protocol.GsonHelper;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-
-public class UserRepository {
-
-  private ServerClient serverClient;
-
-  public UserRepository(ServerClient serverClient) {
-    this.serverClient = serverClient;
-  }
-
-  private static class Users {
-
-    private List<User> users = new ArrayList<>();
-
-    public List<User> getUsers() {
-      return users;
-    }
-  }
-
-  public Collection<User> loadFromWs(List<String> userLogins) {
-    if (userLogins.isEmpty()) {
-      return Collections.emptyList();
-    }
-    String url = "/api/users/search?format=json&includeDeactivated=true&logins=" + Joiner.on(',').join(userLogins);
-    String json = serverClient.request(url);
-    Users users = GsonHelper.create().fromJson(json, Users.class);
-    return users.getUsers();
-  }
-
-}
diff --git a/sonar-batch/src/main/java/org/sonar/batch/user/package-info.java b/sonar-batch/src/main/java/org/sonar/batch/user/package-info.java
deleted file mode 100644 (file)
index 6415ba1..0000000
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * 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.
- */
-@ParametersAreNonnullByDefault
-package org.sonar.batch.user;
-
-import javax.annotation.ParametersAreNonnullByDefault;
diff --git a/sonar-batch/src/test/java/org/sonar/batch/DecoratorsSelectorTest.java b/sonar-batch/src/test/java/org/sonar/batch/DecoratorsSelectorTest.java
deleted file mode 100644 (file)
index 8a0e9a2..0000000
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * 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.batch;
-
-import com.google.common.collect.Iterables;
-import org.junit.Test;
-import org.sonar.api.batch.Decorator;
-import org.sonar.api.batch.DecoratorContext;
-import org.sonar.api.batch.DependedUpon;
-import org.sonar.api.measures.Formula;
-import org.sonar.api.measures.FormulaContext;
-import org.sonar.api.measures.FormulaData;
-import org.sonar.api.measures.Measure;
-import org.sonar.api.measures.Metric;
-import org.sonar.api.platform.ComponentContainer;
-import org.sonar.api.resources.Project;
-import org.sonar.api.resources.Resource;
-import org.sonar.batch.bootstrap.BatchExtensionDictionnary;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-public class DecoratorsSelectorTest {
-
-  private Metric withFormula1 = new Metric("metric1").setFormula(new FakeFormula());
-  private Metric withFormula2 = new Metric("metric2").setFormula(new FakeFormula());
-  private Metric withoutFormula3 = new Metric("metric3");
-
-  @Test
-  public void selectAndSortFormulas() {
-    Project project = new Project("key");
-    BatchExtensionDictionnary batchExtDictionnary = newBatchDictionnary(withFormula1, withoutFormula3, withFormula2);
-
-    Collection<Decorator> decorators = new DecoratorsSelector(batchExtDictionnary).select(project);
-    assertThat(decorators).hasSize(2);
-    assertThat(decorators).contains(new FormulaDecorator(withFormula1));
-    assertThat(decorators).contains(new FormulaDecorator(withFormula2));
-  }
-
-  @Test
-  public void decoratorsShouldBeExecutedBeforeFormulas() {
-    Project project = new Project("key");
-    Decorator metric1Decorator = new Metric1Decorator();
-    BatchExtensionDictionnary batchExtDictionnary = newBatchDictionnary(withFormula1, metric1Decorator);
-
-    Collection<Decorator> decorators = new DecoratorsSelector(batchExtDictionnary).select(project);
-
-    Decorator firstDecorator = Iterables.get(decorators, 0);
-    Decorator secondDecorator = Iterables.get(decorators, 1);
-
-    assertThat(firstDecorator).isInstanceOf(Metric1Decorator.class);
-    assertThat(secondDecorator).isInstanceOf(FormulaDecorator.class);
-
-    FormulaDecorator formulaDecorator = (FormulaDecorator) secondDecorator;
-    assertThat(formulaDecorator.dependsUponDecorators()).hasSize(1);
-    assertThat(Iterables.get(formulaDecorator.dependsUponDecorators(), 0)).isEqualTo(firstDecorator);
-  }
-
-  private BatchExtensionDictionnary newBatchDictionnary(Object... extensions) {
-    ComponentContainer ioc = new ComponentContainer();
-    for (Object extension : extensions) {
-      ioc.addSingleton(extension);
-    }
-    return new BatchExtensionDictionnary(ioc, null, null);
-  }
-
-  class FakeFormula implements Formula {
-    public List<Metric> dependsUponMetrics() {
-      return Arrays.asList();
-    }
-
-    public Measure calculate(FormulaData data, FormulaContext context) {
-      return null;
-    }
-  }
-
-  public class Metric1Decorator implements Decorator {
-    @DependedUpon
-    public Metric generatesMetric1Measure() {
-      return withFormula1;
-    }
-
-    public void decorate(Resource resource, DecoratorContext context) {
-
-    }
-
-    public boolean shouldExecuteOnProject(Project project) {
-      return true;
-    }
-  }
-
-  public class FakeDecorator implements Decorator {
-    public void decorate(Resource resource, DecoratorContext context) {
-
-    }
-
-    public boolean shouldExecuteOnProject(Project project) {
-      return true;
-    }
-  }
-}
index 9bf9dc201d48ec5a2763daf44a8f11cca39f1b0f..e85e6003c2fcd7a13f5d89b03240f38e632099ae 100644 (file)
@@ -57,7 +57,7 @@ public class DefaultFileLinesContextTest {
 
   @Test(expected = IllegalArgumentException.class)
   public void shouldNotAllowCreationForDirectory() {
-    new DefaultFileLinesContext(index, new Directory("key"));
+    new DefaultFileLinesContext(index, Directory.create("key"));
   }
 
   @Test
diff --git a/sonar-batch/src/test/java/org/sonar/batch/FormulaDecoratorTest.java b/sonar-batch/src/test/java/org/sonar/batch/FormulaDecoratorTest.java
deleted file mode 100644 (file)
index ff5fdc5..0000000
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * 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.batch;
-
-import org.junit.Test;
-import org.sonar.api.batch.DecoratorContext;
-import org.sonar.api.measures.CoreMetrics;
-import org.sonar.api.measures.Formula;
-import org.sonar.api.measures.FormulaContext;
-import org.sonar.api.measures.FormulaData;
-import org.sonar.api.measures.Measure;
-import org.sonar.api.measures.Metric;
-import org.sonar.api.test.IsMeasure;
-
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.hamcrest.core.Is.is;
-import static org.junit.Assert.assertThat;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.argThat;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-public class FormulaDecoratorTest {
-
-  @Test
-  public void doAlwaysExecute() {
-    assertThat(new FormulaDecorator(CoreMetrics.LINES).shouldExecuteOnProject(null), is(true));
-  }
-
-  @Test
-  public void declareDependencies() {
-    Formula formula = new Formula() {
-      public List<Metric> dependsUponMetrics() {
-        return Arrays.<Metric>asList(CoreMetrics.COMPLEXITY, CoreMetrics.COVERAGE);
-      }
-
-      public Measure calculate(FormulaData data, FormulaContext context) {
-        return null;
-      }
-    };
-    Metric metric = new Metric("ncloc").setFormula(formula);
-    List<Metric> dependencies = new FormulaDecorator(metric).dependsUponMetrics();
-    assertThat(dependencies).containsOnly(CoreMetrics.COMPLEXITY, CoreMetrics.COVERAGE);
-  }
-
-  @Test
-  public void saveMeasure() {
-    FormulaDecorator decorator = new FormulaDecorator(new Metric("fake").setFormula(new FakeFormula()));
-
-    DecoratorContext context = mock(DecoratorContext.class);
-    decorator.decorate(null, context);
-
-    verify(context).saveMeasure(argThat(new IsMeasure(new Metric("fake"), 50.0)));
-  }
-
-  @Test
-  public void doNotExecuteIfExistingResult() {
-    Metric fake = new Metric("fake");
-    FormulaDecorator decorator = new FormulaDecorator(fake.setFormula(new FakeFormula()));
-
-    DecoratorContext context = mock(DecoratorContext.class);
-    when(context.getMeasure(fake)).thenReturn(new Measure(fake, 10.0));
-    decorator.decorate(null, context);
-
-    verify(context, never()).saveMeasure(any(Measure.class));
-  }
-
-  class FakeFormula implements Formula {
-
-    public List<Metric> dependsUponMetrics() {
-      return Collections.emptyList();
-    }
-
-    public Measure calculate(FormulaData data, FormulaContext context) {
-      return new Measure(new Metric("fake")).setValue(50.0);
-    }
-  }
-}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/ResourceFiltersTest.java b/sonar-batch/src/test/java/org/sonar/batch/ResourceFiltersTest.java
deleted file mode 100644 (file)
index 602b6c7..0000000
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * 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.batch;
-
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.sonar.api.batch.ResourceFilter;
-
-import static org.mockito.Matchers.startsWith;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-
-public class ResourceFiltersTest {
-  @Test
-  public void warn_on_resource_filters() throws Exception {
-    Logger logger = mock(Logger.class);
-    ResourceFilter[] filters = {mock(ResourceFilter.class)};
-    new ResourceFilters(logger, filters);
-    verify(logger).warn(startsWith("ResourceFilters are not supported since version 4.2"));
-
-    // verify that the standard constructor does not fail
-    new ResourceFilters(filters);
-  }
-
-  @Test
-  public void ok_if_no_resource_filters() throws Exception {
-    // just for verify that it does not fail. Should check that no warning is logged.
-    new ResourceFilters();
-  }
-}
index 4be6293c27a98b7f73fd5646c446a512ee308cb4..d032e2b1cd12a160a859e81bd528e0405ebf7ab0 100644 (file)
@@ -19,6 +19,8 @@
  */
 package org.sonar.batch.components;
 
+import org.sonar.batch.components.PastMeasuresLoader;
+
 import org.junit.Test;
 import org.sonar.api.database.model.Snapshot;
 import org.sonar.api.measures.Metric;
diff --git a/sonar-batch/src/test/java/org/sonar/batch/components/PastSnapshotFinderByDateTest.java b/sonar-batch/src/test/java/org/sonar/batch/components/PastSnapshotFinderByDateTest.java
deleted file mode 100644 (file)
index 7abd043..0000000
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * 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.batch.components;
-
-import org.junit.Test;
-import org.sonar.api.database.model.Snapshot;
-import org.sonar.jpa.test.AbstractDbUnitTestCase;
-
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertThat;
-
-public class PastSnapshotFinderByDateTest extends AbstractDbUnitTestCase {
-  public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
-
-  @Test
-  public void shouldFindDate() throws ParseException {
-    setupData("shared");
-
-    Snapshot projectSnapshot = getSession().getSingleResult(Snapshot.class, "id", 1010);
-    PastSnapshotFinderByDate finder = new PastSnapshotFinderByDate(getSession());
-
-    Date date = DATE_FORMAT.parse("2008-11-22");
-
-    PastSnapshot pastSnapshot = finder.findByDate(projectSnapshot, date);
-    assertThat(pastSnapshot.getProjectSnapshotId(), is(1006));
-  }
-
-  @Test
-  public void shouldFindNearestLaterDate() throws ParseException {
-    setupData("shared");
-
-    Snapshot projectSnapshot = getSession().getSingleResult(Snapshot.class, "id", 1010);
-    PastSnapshotFinderByDate finder = new PastSnapshotFinderByDate(getSession());
-
-    Date date = DATE_FORMAT.parse("2008-11-24");
-   
-    PastSnapshot pastSnapshot = finder.findByDate(projectSnapshot, date);
-    assertThat(pastSnapshot.getProjectSnapshotId(), is(1009));
-  }
-}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/components/PastSnapshotFinderByDaysTest.java b/sonar-batch/src/test/java/org/sonar/batch/components/PastSnapshotFinderByDaysTest.java
deleted file mode 100644 (file)
index 1b136e9..0000000
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * 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.batch.components;
-
-import org.hamcrest.core.IsNull;
-import org.junit.Test;
-import org.sonar.api.database.model.Snapshot;
-import org.sonar.jpa.test.AbstractDbUnitTestCase;
-
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Date;
-import java.util.List;
-
-import static org.hamcrest.Matchers.is;
-import static org.hamcrest.Matchers.nullValue;
-import static org.junit.Assert.assertThat;
-
-public class PastSnapshotFinderByDaysTest extends AbstractDbUnitTestCase {
-
-  private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
-
-  @Test
-  public void shouldGetNextSnapshot() {
-    setupData("shared");
-
-    Snapshot projectSnapshot = getSession().getSingleResult(Snapshot.class, "id", 1009); // 2008-11-16
-    PastSnapshotFinderByDays finder = new PastSnapshotFinderByDays(getSession());
-
-    assertThat(finder.findFromDays(projectSnapshot, 50).getProjectSnapshotId(), is(1000));
-  }
-
-  @Test
-  public void shouldIgnoreUnprocessedSnapshots() {
-    setupData("shared");
-
-    Snapshot projectSnapshot = getSession().getSingleResult(Snapshot.class, "id", 1009); // 2008-11-16
-    PastSnapshotFinderByDays finder = new PastSnapshotFinderByDays(getSession());
-
-    assertThat(finder.findFromDays(projectSnapshot, 7).getProjectSnapshotId(), is(1006));
-  }
-
-  @Test
-  public void shouldNotFindSelf() {
-    setupData("shouldNotFindSelf");
-
-    Snapshot projectSnapshot = getSession().getSingleResult(Snapshot.class, "id", 1009); // 2008-11-16
-    PastSnapshotFinderByDays finder = new PastSnapshotFinderByDays(getSession());
-
-    assertThat(finder.findFromDays(projectSnapshot, 1).getProjectSnapshot(), nullValue());
-  }
-
-  @Test
-  public void shouldLocateNearestSnapshotBefore() throws ParseException {
-    Date current = dateFormat.parse("2010-10-20");
-    // distance: 15 => target is 2010-10-05
-
-    List<Snapshot> snapshots = Arrays.asList(
-        newSnapshot(1, "2010-09-30"),
-        newSnapshot(2, "2010-10-03"),// -2 days
-        newSnapshot(3, "2010-10-08"),// +3 days
-        newSnapshot(4, "2010-10-12") // + 7 days
-        );
-    assertThat(PastSnapshotFinderByDays.getNearestToTarget(snapshots, current, 15).getId(), is(2));
-  }
-
-  @Test
-  public void shouldLocateNearestSnapshotAfter() throws ParseException {
-    Date current = dateFormat.parse("2010-10-20");
-    // distance: 15 => target is 2010-10-05
-
-    List<Snapshot> snapshots = Arrays.asList(
-        newSnapshot(1, "2010-09-30"),
-        newSnapshot(2, "2010-10-01"),// -4 days
-        newSnapshot(3, "2010-10-08"),// +3 days
-        newSnapshot(4, "2010-10-12") // + 7 days
-        );
-    assertThat(PastSnapshotFinderByDays.getNearestToTarget(snapshots, current, 15).getId(), is(3));
-  }
-
-  @Test
-  public void shouldReturnNullIfNoSnapshots() throws ParseException {
-    Date current = dateFormat.parse("2010-10-20");
-    List<Snapshot> snapshots = Collections.emptyList();
-    assertThat(PastSnapshotFinderByDays.getNearestToTarget(snapshots, current, 15), IsNull.nullValue());
-  }
-
-  private Snapshot newSnapshot(int id, String date) throws ParseException {
-    Snapshot snapshot = new Snapshot();
-    snapshot.setId(id);
-    snapshot.setCreatedAtMs(dateFormat.parse(date).getTime());
-    return snapshot;
-  }
-}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/components/PastSnapshotFinderByPreviousAnalysisTest.java b/sonar-batch/src/test/java/org/sonar/batch/components/PastSnapshotFinderByPreviousAnalysisTest.java
deleted file mode 100644 (file)
index a2c0d82..0000000
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * 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.batch.components;
-
-import org.junit.Test;
-import org.sonar.api.database.model.Snapshot;
-import org.sonar.jpa.test.AbstractDbUnitTestCase;
-
-import static org.hamcrest.Matchers.is;
-import static org.hamcrest.core.IsNull.nullValue;
-import static org.junit.Assert.assertThat;
-
-public class PastSnapshotFinderByPreviousAnalysisTest extends AbstractDbUnitTestCase {
-
-  @Test
-  public void shouldFindPreviousAnalysis() {
-    setupData("shouldFindPreviousAnalysis");
-
-    Snapshot projectSnapshot = getSession().getSingleResult(Snapshot.class, "id", 1010);
-    PastSnapshotFinderByPreviousAnalysis finder = new PastSnapshotFinderByPreviousAnalysis(getSession());
-
-    PastSnapshot pastSnapshot = finder.findByPreviousAnalysis(projectSnapshot);
-    assertThat(pastSnapshot.getProjectSnapshotId(), is(1009));
-  }
-
-  @Test
-  public void shouldReturnPastSnapshotEvenWhenNoPreviousAnalysis() {
-    setupData("shouldNotFindPreviousAnalysis");
-
-    Snapshot projectSnapshot = getSession().getSingleResult(Snapshot.class, "id", 1010);
-    PastSnapshotFinderByPreviousAnalysis finder = new PastSnapshotFinderByPreviousAnalysis(getSession());
-
-    PastSnapshot pastSnapshot = finder.findByPreviousAnalysis(projectSnapshot);
-    assertThat(pastSnapshot.isRelatedToSnapshot(), is(false));
-    assertThat(pastSnapshot.getProjectSnapshot(), nullValue());
-    assertThat(pastSnapshot.getDate(), nullValue());
-  }
-}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/components/PastSnapshotFinderByPreviousVersionTest.java b/sonar-batch/src/test/java/org/sonar/batch/components/PastSnapshotFinderByPreviousVersionTest.java
deleted file mode 100644 (file)
index da160c8..0000000
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * 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.batch.components;
-
-import org.junit.Test;
-import org.sonar.api.CoreProperties;
-import org.sonar.api.database.model.Snapshot;
-import org.sonar.jpa.test.AbstractDbUnitTestCase;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-public class PastSnapshotFinderByPreviousVersionTest extends AbstractDbUnitTestCase {
-
-  @Test
-  public void shouldFindByPreviousVersion() {
-    setupData("with-previous-version");
-    PastSnapshotFinderByPreviousVersion finder = new PastSnapshotFinderByPreviousVersion(getSession());
-
-    Snapshot currentProjectSnapshot = getSession().getSingleResult(Snapshot.class, "id", 1003);
-    PastSnapshot foundSnapshot = finder.findByPreviousVersion(currentProjectSnapshot);
-    assertThat(foundSnapshot.getProjectSnapshotId()).isEqualTo(1001);
-    assertThat(foundSnapshot.getMode()).isEqualTo(CoreProperties.TIMEMACHINE_MODE_PREVIOUS_VERSION);
-    assertThat(foundSnapshot.getModeParameter()).isEqualTo("1.1");
-  }
-
-  @Test
-  public void shouldFindByPreviousVersionWhenPreviousVersionDeleted() {
-    setupData("with-previous-version-deleted");
-    PastSnapshotFinderByPreviousVersion finder = new PastSnapshotFinderByPreviousVersion(getSession());
-
-    Snapshot currentProjectSnapshot = getSession().getSingleResult(Snapshot.class, "id", 1003);
-    PastSnapshot foundSnapshot = finder.findByPreviousVersion(currentProjectSnapshot);
-    assertThat(foundSnapshot.getProjectSnapshotId()).isEqualTo(1000);
-    assertThat(foundSnapshot.getMode()).isEqualTo(CoreProperties.TIMEMACHINE_MODE_PREVIOUS_VERSION);
-    assertThat(foundSnapshot.getModeParameter()).isEqualTo("1.0");
-  }
-
-  @Test
-  public void testWithNoPreviousVersion() {
-    setupData("no-previous-version");
-    PastSnapshotFinderByPreviousVersion finder = new PastSnapshotFinderByPreviousVersion(getSession());
-
-    Snapshot currentProjectSnapshot = getSession().getSingleResult(Snapshot.class, "id", 1003);
-    PastSnapshot foundSnapshot = finder.findByPreviousVersion(currentProjectSnapshot);
-    assertThat(foundSnapshot.getMode()).isEqualTo(CoreProperties.TIMEMACHINE_MODE_PREVIOUS_VERSION);
-    assertThat(foundSnapshot.getProjectSnapshot()).isNull();
-    assertThat(foundSnapshot.getModeParameter()).isNull();
-  }
-
-}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/components/PastSnapshotFinderByVersionTest.java b/sonar-batch/src/test/java/org/sonar/batch/components/PastSnapshotFinderByVersionTest.java
deleted file mode 100644 (file)
index b35f4b8..0000000
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * 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.batch.components;
-
-import org.junit.Test;
-import org.sonar.api.CoreProperties;
-import org.sonar.api.database.model.Snapshot;
-import org.sonar.jpa.test.AbstractDbUnitTestCase;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-public class PastSnapshotFinderByVersionTest extends AbstractDbUnitTestCase {
-
-  @Test
-  public void shouldFindByVersion() {
-    setupData("shared");
-
-    Snapshot currentProjectSnapshot = getSession().getSingleResult(Snapshot.class, "id", 1010);
-    PastSnapshotFinderByVersion finder = new PastSnapshotFinderByVersion(getSession());
-
-    PastSnapshot foundSnapshot = finder.findByVersion(currentProjectSnapshot, "1.1");
-    assertThat(foundSnapshot.getProjectSnapshotId()).isEqualTo(1009);
-    assertThat(foundSnapshot.getMode()).isEqualTo(CoreProperties.TIMEMACHINE_MODE_VERSION);
-  }
-
-  @Test
-  public void testIfNoVersionFound() {
-    setupData("shared");
-
-    Snapshot currentProjectSnapshot = getSession().getSingleResult(Snapshot.class, "id", 1010);
-    PastSnapshotFinderByVersion finder = new PastSnapshotFinderByVersion(getSession());
-
-    PastSnapshot foundSnapshot = finder.findByVersion(currentProjectSnapshot, "2.1");
-    assertThat(foundSnapshot.getMode()).isEqualTo(CoreProperties.TIMEMACHINE_MODE_VERSION);
-    assertThat(foundSnapshot.getProjectSnapshot()).isNull();
-    assertThat(foundSnapshot.getModeParameter()).isNull();
-  }
-
-}
index c335d3b87d68edd0e2af54519bf285f8a66b8956..f712b04dbc4bbbe4038e768284ae69025e87311e 100644 (file)
  */
 package org.sonar.batch.components;
 
+import org.sonar.batch.components.PastSnapshotFinder;
+import org.sonar.batch.deprecated.components.PastSnapshotFinderByDate;
+import org.sonar.batch.deprecated.components.PastSnapshotFinderByDays;
+import org.sonar.batch.deprecated.components.PastSnapshotFinderByPreviousAnalysis;
+import org.sonar.batch.deprecated.components.PastSnapshotFinderByPreviousVersion;
+import org.sonar.batch.deprecated.components.PastSnapshotFinderByVersion;
 import org.junit.Before;
 import org.junit.Test;
 import org.mockito.ArgumentMatcher;
index 3d38431f780b24bfb61165eddc675704a6721db1..201155b1188d08e155c45c1ed493b42c25b290b6 100644 (file)
@@ -19,6 +19,8 @@
  */
 package org.sonar.batch.components;
 
+import org.sonar.batch.components.PastSnapshot;
+
 import org.junit.Test;
 import org.sonar.api.CoreProperties;
 import org.sonar.api.database.model.Snapshot;
diff --git a/sonar-batch/src/test/java/org/sonar/batch/components/PeriodsDefinitionTest.java b/sonar-batch/src/test/java/org/sonar/batch/components/PeriodsDefinitionTest.java
deleted file mode 100644 (file)
index 7483d54..0000000
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * 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.batch.components;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.ArgumentMatcher;
-import org.sonar.api.config.Settings;
-import org.sonar.api.database.model.Snapshot;
-import org.sonar.api.resources.Project;
-import org.sonar.batch.ProjectTree;
-import org.sonar.jpa.test.AbstractDbUnitTestCase;
-
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Matchers.argThat;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.*;
-
-public class PeriodsDefinitionTest extends AbstractDbUnitTestCase {
-
-  private Settings settings;
-  private PastSnapshotFinder pastSnapshotFinder;
-
-  @Before
-  public void before() {
-    setupData("shared");
-    settings = new Settings();
-    pastSnapshotFinder = mock(PastSnapshotFinder.class);
-  }
-
-  @Test
-  public void should_init_past_snapshots() {
-    ProjectTree projectTree = mock(ProjectTree.class);
-    when(projectTree.getRootProject()).thenReturn(new Project("my:project"));
-    new PeriodsDefinition(getSession(), projectTree, settings, pastSnapshotFinder);
-
-    verify(pastSnapshotFinder).find(argThat(new ArgumentMatcher<Snapshot>() {
-      @Override
-      public boolean matches(Object o) {
-        return ((Snapshot) o).getResourceId() == 2 /* see database in shared.xml */;
-      }
-    }), anyString(), eq(settings), eq(1));
-  }
-
-  @Test
-  public void should_not_init_past_snapshots_if_first_analysis() {
-    ProjectTree projectTree = mock(ProjectTree.class);
-    when(projectTree.getRootProject()).thenReturn(new Project("new:project"));
-
-    new PeriodsDefinition(getSession(), projectTree, settings, pastSnapshotFinder);
-
-    verifyZeroInteractions(pastSnapshotFinder);
-  }
-}
index 023690acdbdab82be52316c9c19938e4924ca4d1..eae7b0f8377b764bfd7ea7842ddbfe2171489112 100644 (file)
  */
 package org.sonar.batch.components;
 
+import org.sonar.batch.components.TimeMachineConfiguration;
+
+import org.sonar.batch.components.PastSnapshot;
+import org.sonar.batch.deprecated.components.PeriodsDefinition;
 import org.junit.Before;
 import org.junit.Test;
 import org.sonar.api.database.model.Snapshot;
index 945a3d7614be4bfb5a85c3f1e4b0f7df2543d8f7..7cb4b47c1c58f4c562adf490fa8106f6bf532036 100644 (file)
@@ -247,7 +247,7 @@ public class DebtDecoratorTest {
 
     // or for a file
     context = mock(DecoratorContext.class);
-    when(context.getResource()).thenReturn(new File("foo"));
+    when(context.getResource()).thenReturn(File.create("foo"));
     decorator.saveCharacteristicMeasure(context, (Characteristic) null, 12.0, false);
     verify(context, times(1)).saveMeasure(new Measure(CoreMetrics.TECHNICAL_DEBT));
   }
@@ -282,7 +282,7 @@ public class DebtDecoratorTest {
   @Test
   public void not_save_technical_debt_for_file_if_zero() throws Exception {
     DecoratorContext context = mock(DecoratorContext.class);
-    when(context.getResource()).thenReturn(new File("foo"));
+    when(context.getResource()).thenReturn(File.create("foo"));
 
     decorator.saveCharacteristicMeasure(context, null, 0.0, true);
     verify(context, never()).saveMeasure(new Measure(CoreMetrics.TECHNICAL_DEBT));
index 0bb25ad1d826e906f8890f011a3187be36ff24b6..c930eb1075ef65ce3d18577431fa5e225f74ef10 100644 (file)
@@ -20,6 +20,9 @@
 
 package org.sonar.batch.debt;
 
+import org.sonar.batch.components.TimeMachineConfiguration;
+
+import org.sonar.batch.deprecated.components.Period;
 import org.apache.commons.lang.ObjectUtils;
 import org.apache.commons.lang.time.DateUtils;
 import org.junit.Before;
@@ -42,8 +45,6 @@ import org.sonar.api.measures.Metric;
 import org.sonar.api.resources.Resource;
 import org.sonar.api.test.IsMeasure;
 import org.sonar.api.utils.Duration;
-import org.sonar.batch.components.Period;
-import org.sonar.batch.components.TimeMachineConfiguration;
 import org.sonar.batch.debt.IssueChangelogDebtCalculator;
 import org.sonar.batch.debt.NewDebtDecorator;
 
index 0caa8cf219ecc8e08515c079414e152bd6256c8a..79ce075a097d2334dd0ed4ece4fbe55e30cf8f63 100644 (file)
@@ -73,10 +73,9 @@ public class SqaleRatingDecoratorTest {
   public void setUp() throws Exception {
     settings = new Settings();
 
-    fs = new DefaultFileSystem(temp.newFolder());
+    fs = new DefaultFileSystem(temp.newFolder().toPath());
     fs.add(new DefaultInputFile("foo", file.getPath())
-      .setLanguage("java")
-      .setFile(temp.newFile("Foo.java")));
+      .setLanguage("java"));
 
     decorator = new SqaleRatingDecorator(new SqaleRatingSettings(settings), metrics, fs);
   }
diff --git a/sonar-batch/src/test/java/org/sonar/batch/deprecated/ResourceFiltersTest.java b/sonar-batch/src/test/java/org/sonar/batch/deprecated/ResourceFiltersTest.java
new file mode 100644 (file)
index 0000000..c933344
--- /dev/null
@@ -0,0 +1,47 @@
+/*
+ * 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.batch.deprecated;
+
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.sonar.api.batch.ResourceFilter;
+
+import static org.mockito.Matchers.startsWith;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+
+public class ResourceFiltersTest {
+  @Test
+  public void warn_on_resource_filters() throws Exception {
+    Logger logger = mock(Logger.class);
+    ResourceFilter[] filters = {mock(ResourceFilter.class)};
+    new ResourceFilters(logger, filters);
+    verify(logger).warn(startsWith("ResourceFilters are not supported since version 4.2"));
+
+    // verify that the standard constructor does not fail
+    new ResourceFilters(filters);
+  }
+
+  @Test
+  public void ok_if_no_resource_filters() throws Exception {
+    // just for verify that it does not fail. Should check that no warning is logged.
+    new ResourceFilters();
+  }
+}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/deprecated/components/PastSnapshotFinderByDateTest.java b/sonar-batch/src/test/java/org/sonar/batch/deprecated/components/PastSnapshotFinderByDateTest.java
new file mode 100644 (file)
index 0000000..2cf8b31
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+ * 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.batch.deprecated.components;
+
+import org.sonar.batch.components.PastSnapshot;
+
+import org.sonar.batch.deprecated.components.PastSnapshotFinderByDate;
+import org.junit.Test;
+import org.sonar.api.database.model.Snapshot;
+import org.sonar.jpa.test.AbstractDbUnitTestCase;
+
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+import static org.hamcrest.Matchers.is;
+import static org.junit.Assert.assertThat;
+
+public class PastSnapshotFinderByDateTest extends AbstractDbUnitTestCase {
+  public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
+
+  @Test
+  public void shouldFindDate() throws ParseException {
+    setupData("shared");
+
+    Snapshot projectSnapshot = getSession().getSingleResult(Snapshot.class, "id", 1010);
+    PastSnapshotFinderByDate finder = new PastSnapshotFinderByDate(getSession());
+
+    Date date = DATE_FORMAT.parse("2008-11-22");
+
+    PastSnapshot pastSnapshot = finder.findByDate(projectSnapshot, date);
+    assertThat(pastSnapshot.getProjectSnapshotId(), is(1006));
+  }
+
+  @Test
+  public void shouldFindNearestLaterDate() throws ParseException {
+    setupData("shared");
+
+    Snapshot projectSnapshot = getSession().getSingleResult(Snapshot.class, "id", 1010);
+    PastSnapshotFinderByDate finder = new PastSnapshotFinderByDate(getSession());
+
+    Date date = DATE_FORMAT.parse("2008-11-24");
+   
+    PastSnapshot pastSnapshot = finder.findByDate(projectSnapshot, date);
+    assertThat(pastSnapshot.getProjectSnapshotId(), is(1009));
+  }
+}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/deprecated/components/PastSnapshotFinderByDaysTest.java b/sonar-batch/src/test/java/org/sonar/batch/deprecated/components/PastSnapshotFinderByDaysTest.java
new file mode 100644 (file)
index 0000000..0515b30
--- /dev/null
@@ -0,0 +1,115 @@
+/*
+ * 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.batch.deprecated.components;
+
+import org.sonar.batch.deprecated.components.PastSnapshotFinderByDays;
+
+import org.hamcrest.core.IsNull;
+import org.junit.Test;
+import org.sonar.api.database.model.Snapshot;
+import org.sonar.jpa.test.AbstractDbUnitTestCase;
+
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Date;
+import java.util.List;
+
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.nullValue;
+import static org.junit.Assert.assertThat;
+
+public class PastSnapshotFinderByDaysTest extends AbstractDbUnitTestCase {
+
+  private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
+
+  @Test
+  public void shouldGetNextSnapshot() {
+    setupData("shared");
+
+    Snapshot projectSnapshot = getSession().getSingleResult(Snapshot.class, "id", 1009); // 2008-11-16
+    PastSnapshotFinderByDays finder = new PastSnapshotFinderByDays(getSession());
+
+    assertThat(finder.findFromDays(projectSnapshot, 50).getProjectSnapshotId(), is(1000));
+  }
+
+  @Test
+  public void shouldIgnoreUnprocessedSnapshots() {
+    setupData("shared");
+
+    Snapshot projectSnapshot = getSession().getSingleResult(Snapshot.class, "id", 1009); // 2008-11-16
+    PastSnapshotFinderByDays finder = new PastSnapshotFinderByDays(getSession());
+
+    assertThat(finder.findFromDays(projectSnapshot, 7).getProjectSnapshotId(), is(1006));
+  }
+
+  @Test
+  public void shouldNotFindSelf() {
+    setupData("shouldNotFindSelf");
+
+    Snapshot projectSnapshot = getSession().getSingleResult(Snapshot.class, "id", 1009); // 2008-11-16
+    PastSnapshotFinderByDays finder = new PastSnapshotFinderByDays(getSession());
+
+    assertThat(finder.findFromDays(projectSnapshot, 1).getProjectSnapshot(), nullValue());
+  }
+
+  @Test
+  public void shouldLocateNearestSnapshotBefore() throws ParseException {
+    Date current = dateFormat.parse("2010-10-20");
+    // distance: 15 => target is 2010-10-05
+
+    List<Snapshot> snapshots = Arrays.asList(
+        newSnapshot(1, "2010-09-30"),
+        newSnapshot(2, "2010-10-03"),// -2 days
+        newSnapshot(3, "2010-10-08"),// +3 days
+        newSnapshot(4, "2010-10-12") // + 7 days
+        );
+    assertThat(PastSnapshotFinderByDays.getNearestToTarget(snapshots, current, 15).getId(), is(2));
+  }
+
+  @Test
+  public void shouldLocateNearestSnapshotAfter() throws ParseException {
+    Date current = dateFormat.parse("2010-10-20");
+    // distance: 15 => target is 2010-10-05
+
+    List<Snapshot> snapshots = Arrays.asList(
+        newSnapshot(1, "2010-09-30"),
+        newSnapshot(2, "2010-10-01"),// -4 days
+        newSnapshot(3, "2010-10-08"),// +3 days
+        newSnapshot(4, "2010-10-12") // + 7 days
+        );
+    assertThat(PastSnapshotFinderByDays.getNearestToTarget(snapshots, current, 15).getId(), is(3));
+  }
+
+  @Test
+  public void shouldReturnNullIfNoSnapshots() throws ParseException {
+    Date current = dateFormat.parse("2010-10-20");
+    List<Snapshot> snapshots = Collections.emptyList();
+    assertThat(PastSnapshotFinderByDays.getNearestToTarget(snapshots, current, 15), IsNull.nullValue());
+  }
+
+  private Snapshot newSnapshot(int id, String date) throws ParseException {
+    Snapshot snapshot = new Snapshot();
+    snapshot.setId(id);
+    snapshot.setCreatedAtMs(dateFormat.parse(date).getTime());
+    return snapshot;
+  }
+}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/deprecated/components/PastSnapshotFinderByPreviousAnalysisTest.java b/sonar-batch/src/test/java/org/sonar/batch/deprecated/components/PastSnapshotFinderByPreviousAnalysisTest.java
new file mode 100644 (file)
index 0000000..9ec2024
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * 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.batch.deprecated.components;
+
+import org.sonar.batch.components.PastSnapshot;
+
+import org.sonar.batch.deprecated.components.PastSnapshotFinderByPreviousAnalysis;
+import org.junit.Test;
+import org.sonar.api.database.model.Snapshot;
+import org.sonar.jpa.test.AbstractDbUnitTestCase;
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.core.IsNull.nullValue;
+import static org.junit.Assert.assertThat;
+
+public class PastSnapshotFinderByPreviousAnalysisTest extends AbstractDbUnitTestCase {
+
+  @Test
+  public void shouldFindPreviousAnalysis() {
+    setupData("shouldFindPreviousAnalysis");
+
+    Snapshot projectSnapshot = getSession().getSingleResult(Snapshot.class, "id", 1010);
+    PastSnapshotFinderByPreviousAnalysis finder = new PastSnapshotFinderByPreviousAnalysis(getSession());
+
+    PastSnapshot pastSnapshot = finder.findByPreviousAnalysis(projectSnapshot);
+    assertThat(pastSnapshot.getProjectSnapshotId(), is(1009));
+  }
+
+  @Test
+  public void shouldReturnPastSnapshotEvenWhenNoPreviousAnalysis() {
+    setupData("shouldNotFindPreviousAnalysis");
+
+    Snapshot projectSnapshot = getSession().getSingleResult(Snapshot.class, "id", 1010);
+    PastSnapshotFinderByPreviousAnalysis finder = new PastSnapshotFinderByPreviousAnalysis(getSession());
+
+    PastSnapshot pastSnapshot = finder.findByPreviousAnalysis(projectSnapshot);
+    assertThat(pastSnapshot.isRelatedToSnapshot(), is(false));
+    assertThat(pastSnapshot.getProjectSnapshot(), nullValue());
+    assertThat(pastSnapshot.getDate(), nullValue());
+  }
+}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/deprecated/components/PastSnapshotFinderByPreviousVersionTest.java b/sonar-batch/src/test/java/org/sonar/batch/deprecated/components/PastSnapshotFinderByPreviousVersionTest.java
new file mode 100644 (file)
index 0000000..d932060
--- /dev/null
@@ -0,0 +1,69 @@
+/*
+ * 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.batch.deprecated.components;
+
+import org.sonar.batch.components.PastSnapshot;
+
+import org.sonar.batch.deprecated.components.PastSnapshotFinderByPreviousVersion;
+import org.junit.Test;
+import org.sonar.api.CoreProperties;
+import org.sonar.api.database.model.Snapshot;
+import org.sonar.jpa.test.AbstractDbUnitTestCase;
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class PastSnapshotFinderByPreviousVersionTest extends AbstractDbUnitTestCase {
+
+  @Test
+  public void shouldFindByPreviousVersion() {
+    setupData("with-previous-version");
+    PastSnapshotFinderByPreviousVersion finder = new PastSnapshotFinderByPreviousVersion(getSession());
+
+    Snapshot currentProjectSnapshot = getSession().getSingleResult(Snapshot.class, "id", 1003);
+    PastSnapshot foundSnapshot = finder.findByPreviousVersion(currentProjectSnapshot);
+    assertThat(foundSnapshot.getProjectSnapshotId()).isEqualTo(1001);
+    assertThat(foundSnapshot.getMode()).isEqualTo(CoreProperties.TIMEMACHINE_MODE_PREVIOUS_VERSION);
+    assertThat(foundSnapshot.getModeParameter()).isEqualTo("1.1");
+  }
+
+  @Test
+  public void shouldFindByPreviousVersionWhenPreviousVersionDeleted() {
+    setupData("with-previous-version-deleted");
+    PastSnapshotFinderByPreviousVersion finder = new PastSnapshotFinderByPreviousVersion(getSession());
+
+    Snapshot currentProjectSnapshot = getSession().getSingleResult(Snapshot.class, "id", 1003);
+    PastSnapshot foundSnapshot = finder.findByPreviousVersion(currentProjectSnapshot);
+    assertThat(foundSnapshot.getProjectSnapshotId()).isEqualTo(1000);
+    assertThat(foundSnapshot.getMode()).isEqualTo(CoreProperties.TIMEMACHINE_MODE_PREVIOUS_VERSION);
+    assertThat(foundSnapshot.getModeParameter()).isEqualTo("1.0");
+  }
+
+  @Test
+  public void testWithNoPreviousVersion() {
+    setupData("no-previous-version");
+    PastSnapshotFinderByPreviousVersion finder = new PastSnapshotFinderByPreviousVersion(getSession());
+
+    Snapshot currentProjectSnapshot = getSession().getSingleResult(Snapshot.class, "id", 1003);
+    PastSnapshot foundSnapshot = finder.findByPreviousVersion(currentProjectSnapshot);
+    assertThat(foundSnapshot.getMode()).isEqualTo(CoreProperties.TIMEMACHINE_MODE_PREVIOUS_VERSION);
+    assertThat(foundSnapshot.getProjectSnapshot()).isNull();
+    assertThat(foundSnapshot.getModeParameter()).isNull();
+  }
+
+}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/deprecated/components/PastSnapshotFinderByVersionTest.java b/sonar-batch/src/test/java/org/sonar/batch/deprecated/components/PastSnapshotFinderByVersionTest.java
new file mode 100644 (file)
index 0000000..5d8c87a
--- /dev/null
@@ -0,0 +1,58 @@
+/*
+ * 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.batch.deprecated.components;
+
+import org.sonar.batch.components.PastSnapshot;
+
+import org.sonar.batch.deprecated.components.PastSnapshotFinderByVersion;
+import org.junit.Test;
+import org.sonar.api.CoreProperties;
+import org.sonar.api.database.model.Snapshot;
+import org.sonar.jpa.test.AbstractDbUnitTestCase;
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class PastSnapshotFinderByVersionTest extends AbstractDbUnitTestCase {
+
+  @Test
+  public void shouldFindByVersion() {
+    setupData("shared");
+
+    Snapshot currentProjectSnapshot = getSession().getSingleResult(Snapshot.class, "id", 1010);
+    PastSnapshotFinderByVersion finder = new PastSnapshotFinderByVersion(getSession());
+
+    PastSnapshot foundSnapshot = finder.findByVersion(currentProjectSnapshot, "1.1");
+    assertThat(foundSnapshot.getProjectSnapshotId()).isEqualTo(1009);
+    assertThat(foundSnapshot.getMode()).isEqualTo(CoreProperties.TIMEMACHINE_MODE_VERSION);
+  }
+
+  @Test
+  public void testIfNoVersionFound() {
+    setupData("shared");
+
+    Snapshot currentProjectSnapshot = getSession().getSingleResult(Snapshot.class, "id", 1010);
+    PastSnapshotFinderByVersion finder = new PastSnapshotFinderByVersion(getSession());
+
+    PastSnapshot foundSnapshot = finder.findByVersion(currentProjectSnapshot, "2.1");
+    assertThat(foundSnapshot.getMode()).isEqualTo(CoreProperties.TIMEMACHINE_MODE_VERSION);
+    assertThat(foundSnapshot.getProjectSnapshot()).isNull();
+    assertThat(foundSnapshot.getModeParameter()).isNull();
+  }
+
+}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/deprecated/components/PeriodsDefinitionTest.java b/sonar-batch/src/test/java/org/sonar/batch/deprecated/components/PeriodsDefinitionTest.java
new file mode 100644 (file)
index 0000000..425ce9e
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ * 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.batch.deprecated.components;
+
+import org.sonar.batch.components.PastSnapshotFinder;
+
+import org.sonar.batch.deprecated.components.PeriodsDefinition;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.ArgumentMatcher;
+import org.sonar.api.config.Settings;
+import org.sonar.api.database.model.Snapshot;
+import org.sonar.api.resources.Project;
+import org.sonar.batch.ProjectTree;
+import org.sonar.jpa.test.AbstractDbUnitTestCase;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Matchers.argThat;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.*;
+
+public class PeriodsDefinitionTest extends AbstractDbUnitTestCase {
+
+  private Settings settings;
+  private PastSnapshotFinder pastSnapshotFinder;
+
+  @Before
+  public void before() {
+    setupData("shared");
+    settings = new Settings();
+    pastSnapshotFinder = mock(PastSnapshotFinder.class);
+  }
+
+  @Test
+  public void should_init_past_snapshots() {
+    ProjectTree projectTree = mock(ProjectTree.class);
+    when(projectTree.getRootProject()).thenReturn(new Project("my:project"));
+    new PeriodsDefinition(getSession(), projectTree, settings, pastSnapshotFinder);
+
+    verify(pastSnapshotFinder).find(argThat(new ArgumentMatcher<Snapshot>() {
+      @Override
+      public boolean matches(Object o) {
+        return ((Snapshot) o).getResourceId() == 2 /* see database in shared.xml */;
+      }
+    }), anyString(), eq(settings), eq(1));
+  }
+
+  @Test
+  public void should_not_init_past_snapshots_if_first_analysis() {
+    ProjectTree projectTree = mock(ProjectTree.class);
+    when(projectTree.getRootProject()).thenReturn(new Project("new:project"));
+
+    new PeriodsDefinition(getSession(), projectTree, settings, pastSnapshotFinder);
+
+    verifyZeroInteractions(pastSnapshotFinder);
+  }
+}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/deprecated/decorator/DecoratorsSelectorTest.java b/sonar-batch/src/test/java/org/sonar/batch/deprecated/decorator/DecoratorsSelectorTest.java
new file mode 100644 (file)
index 0000000..f469d6b
--- /dev/null
@@ -0,0 +1,121 @@
+/*
+ * 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.batch.deprecated.decorator;
+
+import com.google.common.collect.Iterables;
+import org.junit.Test;
+import org.sonar.api.batch.Decorator;
+import org.sonar.api.batch.DecoratorContext;
+import org.sonar.api.batch.DependedUpon;
+import org.sonar.api.measures.Formula;
+import org.sonar.api.measures.FormulaContext;
+import org.sonar.api.measures.FormulaData;
+import org.sonar.api.measures.Measure;
+import org.sonar.api.measures.Metric;
+import org.sonar.api.platform.ComponentContainer;
+import org.sonar.api.resources.Project;
+import org.sonar.api.resources.Resource;
+import org.sonar.batch.bootstrap.BatchExtensionDictionnary;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class DecoratorsSelectorTest {
+
+  private Metric withFormula1 = new Metric("metric1").setFormula(new FakeFormula());
+  private Metric withFormula2 = new Metric("metric2").setFormula(new FakeFormula());
+  private Metric withoutFormula3 = new Metric("metric3");
+
+  @Test
+  public void selectAndSortFormulas() {
+    Project project = new Project("key");
+    BatchExtensionDictionnary batchExtDictionnary = newBatchDictionnary(withFormula1, withoutFormula3, withFormula2);
+
+    Collection<Decorator> decorators = new DecoratorsSelector(batchExtDictionnary).select(project);
+    assertThat(decorators).hasSize(2);
+    assertThat(decorators).contains(new FormulaDecorator(withFormula1));
+    assertThat(decorators).contains(new FormulaDecorator(withFormula2));
+  }
+
+  @Test
+  public void decoratorsShouldBeExecutedBeforeFormulas() {
+    Project project = new Project("key");
+    Decorator metric1Decorator = new Metric1Decorator();
+    BatchExtensionDictionnary batchExtDictionnary = newBatchDictionnary(withFormula1, metric1Decorator);
+
+    Collection<Decorator> decorators = new DecoratorsSelector(batchExtDictionnary).select(project);
+
+    Decorator firstDecorator = Iterables.get(decorators, 0);
+    Decorator secondDecorator = Iterables.get(decorators, 1);
+
+    assertThat(firstDecorator).isInstanceOf(Metric1Decorator.class);
+    assertThat(secondDecorator).isInstanceOf(FormulaDecorator.class);
+
+    FormulaDecorator formulaDecorator = (FormulaDecorator) secondDecorator;
+    assertThat(formulaDecorator.dependsUponDecorators()).hasSize(1);
+    assertThat(Iterables.get(formulaDecorator.dependsUponDecorators(), 0)).isEqualTo(firstDecorator);
+  }
+
+  private BatchExtensionDictionnary newBatchDictionnary(Object... extensions) {
+    ComponentContainer ioc = new ComponentContainer();
+    for (Object extension : extensions) {
+      ioc.addSingleton(extension);
+    }
+    return new BatchExtensionDictionnary(ioc, null, null);
+  }
+
+  class FakeFormula implements Formula {
+    public List<Metric> dependsUponMetrics() {
+      return Arrays.asList();
+    }
+
+    public Measure calculate(FormulaData data, FormulaContext context) {
+      return null;
+    }
+  }
+
+  public class Metric1Decorator implements Decorator {
+    @DependedUpon
+    public Metric generatesMetric1Measure() {
+      return withFormula1;
+    }
+
+    public void decorate(Resource resource, DecoratorContext context) {
+
+    }
+
+    public boolean shouldExecuteOnProject(Project project) {
+      return true;
+    }
+  }
+
+  public class FakeDecorator implements Decorator {
+    public void decorate(Resource resource, DecoratorContext context) {
+
+    }
+
+    public boolean shouldExecuteOnProject(Project project) {
+      return true;
+    }
+  }
+}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/deprecated/decorator/FormulaDecoratorTest.java b/sonar-batch/src/test/java/org/sonar/batch/deprecated/decorator/FormulaDecoratorTest.java
new file mode 100644 (file)
index 0000000..4507ab8
--- /dev/null
@@ -0,0 +1,103 @@
+/*
+ * 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.batch.deprecated.decorator;
+
+import org.sonar.batch.deprecated.decorator.FormulaDecorator;
+
+import org.junit.Test;
+import org.sonar.api.batch.DecoratorContext;
+import org.sonar.api.measures.CoreMetrics;
+import org.sonar.api.measures.Formula;
+import org.sonar.api.measures.FormulaContext;
+import org.sonar.api.measures.FormulaData;
+import org.sonar.api.measures.Measure;
+import org.sonar.api.measures.Metric;
+import org.sonar.api.test.IsMeasure;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.hamcrest.core.Is.is;
+import static org.junit.Assert.assertThat;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.argThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+public class FormulaDecoratorTest {
+
+  @Test
+  public void doAlwaysExecute() {
+    assertThat(new FormulaDecorator(CoreMetrics.LINES).shouldExecuteOnProject(null), is(true));
+  }
+
+  @Test
+  public void declareDependencies() {
+    Formula formula = new Formula() {
+      public List<Metric> dependsUponMetrics() {
+        return Arrays.<Metric>asList(CoreMetrics.COMPLEXITY, CoreMetrics.COVERAGE);
+      }
+
+      public Measure calculate(FormulaData data, FormulaContext context) {
+        return null;
+      }
+    };
+    Metric metric = new Metric("ncloc").setFormula(formula);
+    List<Metric> dependencies = new FormulaDecorator(metric).dependsUponMetrics();
+    assertThat(dependencies).containsOnly(CoreMetrics.COMPLEXITY, CoreMetrics.COVERAGE);
+  }
+
+  @Test
+  public void saveMeasure() {
+    FormulaDecorator decorator = new FormulaDecorator(new Metric("fake").setFormula(new FakeFormula()));
+
+    DecoratorContext context = mock(DecoratorContext.class);
+    decorator.decorate(null, context);
+
+    verify(context).saveMeasure(argThat(new IsMeasure(new Metric("fake"), 50.0)));
+  }
+
+  @Test
+  public void doNotExecuteIfExistingResult() {
+    Metric fake = new Metric("fake");
+    FormulaDecorator decorator = new FormulaDecorator(fake.setFormula(new FakeFormula()));
+
+    DecoratorContext context = mock(DecoratorContext.class);
+    when(context.getMeasure(fake)).thenReturn(new Measure(fake, 10.0));
+    decorator.decorate(null, context);
+
+    verify(context, never()).saveMeasure(any(Measure.class));
+  }
+
+  class FakeFormula implements Formula {
+
+    public List<Metric> dependsUponMetrics() {
+      return Collections.emptyList();
+    }
+
+    public Measure calculate(FormulaData data, FormulaContext context) {
+      return new Measure(new Metric("fake")).setValue(50.0);
+    }
+  }
+}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/deprecated/tasks/ListTaskTest.java b/sonar-batch/src/test/java/org/sonar/batch/deprecated/tasks/ListTaskTest.java
new file mode 100644 (file)
index 0000000..2812b4d
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+ * 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.batch.deprecated.tasks;
+
+import org.sonar.batch.deprecated.tasks.ListTask;
+import org.sonar.batch.deprecated.tasks.Tasks;
+
+import org.junit.Test;
+import org.sonar.api.task.Task;
+import org.sonar.api.task.TaskDefinition;
+
+import java.util.Arrays;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+public class ListTaskTest {
+  @Test
+  public void should_list_available_tasks() {
+    Tasks tasks = mock(Tasks.class);
+    when(tasks.definitions()).thenReturn(Arrays.asList(
+      TaskDefinition.builder().key("foo").description("Foo").taskClass(FooTask.class).build(),
+      TaskDefinition.builder().key("purge").description("Purge database").taskClass(FakePurgeTask.class).build()
+    ));
+
+    ListTask task = spy(new ListTask(tasks));
+
+    task.execute();
+
+    verify(task, times(1)).log("Available tasks:");
+    verify(task, times(1)).log("  - foo: Foo");
+    verify(task, times(1)).log("  - purge: Purge database");
+  }
+
+  private static class FakePurgeTask implements Task {
+    public void execute() {
+    }
+  }
+
+  private static class FooTask implements Task {
+    public void execute() {
+    }
+  }
+}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/deprecated/tasks/TasksTest.java b/sonar-batch/src/test/java/org/sonar/batch/deprecated/tasks/TasksTest.java
new file mode 100644 (file)
index 0000000..51f6eb1
--- /dev/null
@@ -0,0 +1,92 @@
+/*
+ * 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.batch.deprecated.tasks;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.sonar.api.task.Task;
+import org.sonar.api.task.TaskDefinition;
+import org.sonar.api.utils.SonarException;
+import org.sonar.batch.scan.ScanTask;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class TasksTest {
+
+  @Rule
+  public ExpectedException thrown = ExpectedException.none();
+
+  @Test
+  public void should_get_definitions() {
+    Tasks tasks = new Tasks(new TaskDefinition[] {ScanTask.DEFINITION, ListTask.DEFINITION});
+    assertThat(tasks.definitions()).hasSize(2);
+  }
+
+  @Test
+  public void should_get_definition_by_key() {
+    Tasks tasks = new Tasks(new TaskDefinition[] {ScanTask.DEFINITION, ListTask.DEFINITION});
+    tasks.start();
+    assertThat(tasks.definition(ListTask.DEFINITION.key())).isEqualTo(ListTask.DEFINITION);
+  }
+
+  @Test
+  public void should_return_null_if_task_not_found() {
+    Tasks tasks = new Tasks(new TaskDefinition[] {ScanTask.DEFINITION, ListTask.DEFINITION});
+
+    assertThat(tasks.definition("not-exists")).isNull();
+  }
+
+  @Test
+  public void should_fail_on_duplicated_keys() {
+    thrown.expect(SonarException.class);
+    thrown.expectMessage("Task 'foo' is declared twice");
+
+    new Tasks(new TaskDefinition[] {
+      TaskDefinition.builder().key("foo").taskClass(FakeTask1.class).description("foo1").build(),
+      TaskDefinition.builder().key("foo").taskClass(FakeTask2.class).description("foo2").build()
+    });
+  }
+
+  @Test
+  public void should_fail_on_duplicated_class() {
+    Tasks tasks = new Tasks(new TaskDefinition[] {
+      TaskDefinition.builder().key("foo1").taskClass(FakeTask1.class).description("foo1").build(),
+      TaskDefinition.builder().key("foo2").taskClass(FakeTask1.class).description("foo1").build()
+    });
+
+    thrown.expect(SonarException.class);
+    thrown.expectMessage("Task 'org.sonar.batch.deprecated.tasks.TasksTest$FakeTask1' is defined twice: first by 'foo1' and then by 'foo2'");
+
+    tasks.start();
+  }
+
+  private static class FakeTask1 implements Task {
+    public void execute() {
+    }
+  }
+
+  private static class FakeTask2 implements Task {
+    public void execute() {
+    }
+
+  }
+
+}
index 598bf4d6f88f9c6f7890245f166b2c7fe07d1f53..fa3ceecc3a561bd921823dc10340404fd5f44bdc 100644 (file)
@@ -65,9 +65,9 @@ public class DirectoryDsmDecoratorTest {
     dir = Directory.create("src");
     dirContext = mock(DecoratorContext.class);
 
-    file1 = File.create("src/Foo1.java", "Foo1.java", null, false);
+    file1 = File.create("src/Foo1.java", null, false);
     file1.setId(1);
-    file2 = File.create("src/Foo2.java", "Foo2.java", null, false);
+    file2 = File.create("src/Foo2.java", null, false);
     file2.setId(2);
 
     file1Context = mock(DecoratorContext.class);
index 24d949d000c174f768daac71efa36dd37a8714ab..5d9b0b508ef0d8478b7fa3a14b998ecf82bd2fc6 100644 (file)
@@ -43,8 +43,8 @@ public class DsmSerializerTest {
 
   @Test
   public void serialize() throws IOException {
-    Resource foo = Directory.create("src/org/foo", "org/foo").setId(7);
-    Resource bar = Directory.create("src/org/bar", "org/bar").setId(8);
+    Resource foo = Directory.create("src/org/foo").setId(7);
+    Resource bar = Directory.create("src/org/bar").setId(8);
     Dependency dep = new Dependency(foo, bar).setId(30l).setWeight(1);
 
     DirectedGraph<Resource, Dependency> graph = new DirectedGraph<Resource, Dependency>();
index 94d7d621108088b1835bf3624ec8956b93a11ba1..a9a41264adf95fdb2e9c7703c03efc0eaf62b670 100644 (file)
@@ -60,9 +60,9 @@ public class SubProjectDsmDecoratorTest {
     module = new Project("foo");
     moduleContext = mock(DecoratorContext.class);
 
-    dir1 = Directory.create("src/foo1", "foo1");
+    dir1 = Directory.create("src/foo1");
     dir1.setId(1);
-    dir2 = Directory.create("src/foo2", "foo2");
+    dir2 = Directory.create("src/foo2");
     dir2.setId(2);
 
     DecoratorContext dir1Context = mock(DecoratorContext.class);
index 51a9c0269c9adf756fc4a0ae01b64b826e735afc..97bdb61d75eebc6f24f3e557cb2aeb0ceddaa513 100644 (file)
@@ -24,17 +24,17 @@ import org.sonar.api.measures.Metric;
 import org.sonar.api.resources.Directory;
 import org.sonar.api.resources.File;
 
+import static org.hamcrest.Matchers.hasItem;
 import static org.hamcrest.Matchers.is;
 import static org.hamcrest.core.IsNot.not;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertThat;
-import static org.hamcrest.Matchers.hasItem;
 
 public class BucketTest {
 
-  Directory directory = new Directory("org/foo");
-  File javaFile = new File("org/foo/Bar.java");
+  Directory directory = Directory.create("org/foo");
+  File javaFile = File.create("org/foo/Bar.java");
   Metric ncloc = new Metric("ncloc");
 
   @Test
index ca7a86e791ccdecafc676388fd0507056e475ff0..fe541281e0534ec4fd759310d3642e9576ac77cc 100644 (file)
@@ -95,10 +95,10 @@ public class DefaultIndexTest {
 
   @Test
   public void shouldIndexParentOfDeprecatedFiles() {
-    File file = File.create("src/org/foo/Bar.java", "org/foo/Bar.java", null, false);
+    File file = File.create("src/org/foo/Bar.java", null, false);
     assertThat(index.index(file)).isTrue();
 
-    Directory reference = Directory.create("src/org/foo", "org/foo");
+    Directory reference = Directory.create("src/org/foo");
     assertThat(index.getResource(reference).getName()).isEqualTo("src/org/foo");
     assertThat(index.isIndexed(reference, true)).isTrue();
     assertThat(index.isExcluded(reference)).isFalse();
@@ -108,15 +108,14 @@ public class DefaultIndexTest {
 
   @Test
   public void shouldIndexTreeOfResources() {
-    Directory directory = Directory.create("src/org/foo", "org/foo");
-    File file = File.create("src/org/foo/Bar.java", "org/foo/Bar.java", Java.INSTANCE, false);
+    Directory directory = Directory.create("src/org/foo");
+    File file = File.create("src/org/foo/Bar.java", Java.INSTANCE, false);
 
     assertThat(index.index(directory)).isTrue();
     assertThat(index.index(file, directory)).isTrue();
 
-    File fileRef = File.create("src/org/foo/Bar.java", "org/foo/Bar.java", null, false);
+    File fileRef = File.create("src/org/foo/Bar.java", null, false);
     assertThat(index.getResource(fileRef).getKey()).isEqualTo("src/org/foo/Bar.java");
-    assertThat(index.getResource(fileRef).getDeprecatedKey()).isEqualTo("org/foo/Bar.java");
     assertThat(index.getResource(fileRef).getLanguage().getKey()).isEqualTo("java");
     assertThat(index.isIndexed(fileRef, true)).isTrue();
     assertThat(index.isExcluded(fileRef)).isFalse();
@@ -126,14 +125,14 @@ public class DefaultIndexTest {
 
   @Test
   public void shouldGetSource() throws Exception {
-    Directory directory = Directory.create("src/org/foo", "org/foo");
-    File file = File.create("src/org/foo/Bar.java", "org/foo/Bar.java", Java.INSTANCE, false);
+    Directory directory = Directory.create("src/org/foo");
+    File file = File.create("src/org/foo/Bar.java", Java.INSTANCE, false);
     FileUtils.write(new java.io.File(baseDir, "src/org/foo/Bar.java"), "Foo bar");
 
     assertThat(index.index(directory)).isTrue();
     assertThat(index.index(file, directory)).isTrue();
 
-    File fileRef = File.create("src/org/foo/Bar.java", "org/foo/Bar.java", null, false);
+    File fileRef = File.create("src/org/foo/Bar.java", null, false);
     assertThat(index.getSource(fileRef)).isEqualTo("Foo bar");
   }
 
@@ -150,12 +149,12 @@ public class DefaultIndexTest {
 
   @Test
   public void shouldNotIndexResourceIfParentNotIndexed() {
-    Directory directory = Directory.create("src/org/other", "org/other");
-    File file = File.create("src/org/foo/Bar.java", "org/foo/Bar.java", null, false);
+    Directory directory = Directory.create("src/org/other");
+    File file = File.create("src/org/foo/Bar.java", null, false);
 
     assertThat(index.index(file, directory)).isFalse();
 
-    File fileRef = File.create("src/org/foo/Bar.java", "org/foo/Bar.java", null, false);
+    File fileRef = File.create("src/org/foo/Bar.java", null, false);
     assertThat(index.isIndexed(directory, true)).isFalse();
     assertThat(index.isIndexed(fileRef, true)).isFalse();
     assertThat(index.isExcluded(fileRef)).isFalse();
@@ -165,7 +164,7 @@ public class DefaultIndexTest {
 
   @Test
   public void shouldNotIndexResourceWhenAddingMeasure() {
-    Resource dir = Directory.create("src/org/foo", "org/foo");
+    Resource dir = Directory.create("src/org/foo");
     index.addMeasure(dir, new Measure("ncloc").setValue(50.0));
 
     assertThat(index.isIndexed(dir, true)).isFalse();
index 3517b28789f95890d3a6733688a60d7ec5d161c2..a62dd075bb528024cdcff77494abb238dcde1b2d 100644 (file)
@@ -46,7 +46,7 @@ public class DuplicationPersisterTest extends AbstractDaoTestCase {
 
   DuplicationPersister duplicationPersister;
   RuleFinder ruleFinder = mock(RuleFinder.class);
-  File aFile = new File("org/foo/Bar.java");
+  File aFile = File.create("org/foo/Bar.java");
   Snapshot fileSnapshot = snapshot(FILE_SNAPSHOT_ID);
 
   private DuplicationCache duplicationCache;
index b5cfb38c063abb50e3a6067ca53045b411adfa7d..fb59aa4d0a5121bbad6ddf11187002eef83443bf 100644 (file)
@@ -61,8 +61,8 @@ public class MeasurePersisterTest extends AbstractDaoTestCase {
   MeasurePersister measurePersister;
   RuleFinder ruleFinder = mock(RuleFinder.class);
   Project project = new Project("foo");
-  Directory aDirectory = new Directory("org/foo");
-  File aFile = new File("org/foo/Bar.java");
+  Directory aDirectory = Directory.create("org/foo");
+  File aFile = File.create("org/foo/Bar.java");
   BatchResource projectResource = batchResource(project, PROJECT_SNAPSHOT_ID);
   BatchResource dirResource = batchResource(aDirectory, PACKAGE_SNAPSHOT_ID);
   BatchResource fileResource = batchResource(aFile, FILE_SNAPSHOT_ID);
index 33eb06086d089a95d1819f68fe0ad1311c9655ae..bd250b544dd77906a13cbc7c2691793d5ed7e948 100644 (file)
@@ -31,7 +31,7 @@ public class ResourceCacheTest {
   public void should_cache_resource() throws Exception {
     ResourceCache cache = new ResourceCache();
     String componentKey = "struts:src/org/struts/Action.java";
-    Resource resource = new File("org/struts/Action.java").setEffectiveKey(componentKey);
+    Resource resource = File.create("org/struts/Action.java").setEffectiveKey(componentKey);
     cache.add(resource, null);
 
     assertThat(cache.get(componentKey).resource()).isSameAs(resource);
@@ -41,7 +41,7 @@ public class ResourceCacheTest {
   @Test
   public void should_fail_if_missing_component_key() throws Exception {
     ResourceCache cache = new ResourceCache();
-    Resource resource = new File("org/struts/Action.java").setEffectiveKey(null);
+    Resource resource = File.create("org/struts/Action.java").setEffectiveKey(null);
     try {
       cache.add(resource, null);
       fail();
index e91b5596101599ba4cbf3ce4a23ef4fcaca14c76..1d3d227a4d4029606ddd7954a63e617f2098f65d 100644 (file)
@@ -31,6 +31,8 @@ import org.sonar.api.batch.fs.internal.DefaultInputFile;
 import org.sonar.api.batch.fs.internal.DeprecatedDefaultInputFile;
 import org.sonar.api.config.Settings;
 import org.sonar.api.resources.Project;
+import org.sonar.api.scan.filesystem.PathResolver;
+import org.sonar.batch.scan.filesystem.DefaultModuleFileSystem;
 import org.sonar.jpa.test.AbstractDbUnitTestCase;
 
 import java.io.File;
@@ -39,6 +41,7 @@ import java.util.Arrays;
 
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
 
 public class ResourceKeyMigrationTest extends AbstractDbUnitTestCase {
 
@@ -73,23 +76,21 @@ public class ResourceKeyMigrationTest extends AbstractDbUnitTestCase {
     baseDir = temp.newFolder();
 
     javaInputFiles = (Iterable) Arrays.asList(
-      newInputFile(javaModule, "src/main/java/org/foo/Bar.java", "org.foo.Bar", false),
-      newInputFile(javaModule, "src/main/java/RootBar.java", "[default].RootBar", false),
-      newInputFile(javaModule, "src/test/java/org/foo/BarTest.java", "org.foo.BarTest", true));
+      newInputFile(javaModule, "src/main/java/org/foo/Bar.java", false, "java"),
+      newInputFile(javaModule, "src/main/java/RootBar.java", false, "java"),
+      newInputFile(javaModule, "src/test/java/org/foo/BarTest.java", true, "java"));
 
     phpInputFiles = (Iterable) Arrays.asList(
-      newInputFile(phpModule, "org/foo/Bar.php", "org/foo/Bar.php", false),
-      newInputFile(phpModule, "RootBar.php", "RootBar.php", false),
-      newInputFile(phpModule, "test/org/foo/BarTest.php", "org/foo/BarTest.php", true));
+      newInputFile(phpModule, "org/foo/Bar.php", false, "php"),
+      newInputFile(phpModule, "RootBar.php", false, "php"),
+      newInputFile(phpModule, "test/org/foo/BarTest.php", true, "php"));
 
   }
 
-  private DefaultInputFile newInputFile(Project module, String path, String deprecatedKey, boolean isTest) {
-    File file = new File(baseDir, path);
-    String deprecatedEffectiveKey = module.getKey() + ":" + deprecatedKey;
+  private DefaultInputFile newInputFile(Project module, String path, boolean isTest, String language) {
     return new DeprecatedDefaultInputFile(module.getKey(), path)
-      .setDeprecatedKey(deprecatedEffectiveKey)
-      .setFile(file)
+      .setModuleBaseDir(baseDir.toPath())
+      .setLanguage(language)
       .setType(isTest ? InputFile.Type.TEST : InputFile.Type.MAIN);
   }
 
@@ -98,11 +99,17 @@ public class ResourceKeyMigrationTest extends AbstractDbUnitTestCase {
     setupData("shouldMigrateResourceKeys");
 
     Logger logger = mock(Logger.class);
-    ResourceKeyMigration migration = new ResourceKeyMigration(getSession(), logger);
+    ResourceKeyMigration migration = new ResourceKeyMigration(getSession(), new PathResolver(), logger);
     migration.checkIfMigrationNeeded(multiModuleProject);
 
-    migration.migrateIfNeeded(javaModule, javaInputFiles);
-    migration.migrateIfNeeded(phpModule, phpInputFiles);
+    DefaultModuleFileSystem fs = mock(DefaultModuleFileSystem.class);
+    when(fs.sourceDirs()).thenReturn(Arrays.asList(new File(baseDir, "src/main/java")));
+    when(fs.testDirs()).thenReturn(Arrays.asList(new File(baseDir, "src/test/java")));
+    migration.migrateIfNeeded(javaModule, javaInputFiles, fs);
+
+    when(fs.sourceDirs()).thenReturn(Arrays.asList(new File(baseDir, ".")));
+    when(fs.testDirs()).thenReturn(Arrays.asList(new File(baseDir, "test")));
+    migration.migrateIfNeeded(phpModule, phpInputFiles, fs);
 
     verify(logger).info("Component {} changed to {}", "b:org.foo.Bar", "b:src/main/java/org/foo/Bar.java");
     verify(logger).warn("Directory with key b:org/foo matches both b:src/main/java/org/foo and b:src/test/java/org/foo. First match is arbitrary chosen.");
index 6ec57439787bbf5f5b477f672e7befb01461a63f..6a4506273b43b0cf409c752b4ccf874ae8670dd3 100644 (file)
@@ -290,7 +290,7 @@ public class ResourcePersisterTest extends AbstractDbUnitTestCase {
     setupData("shared");
 
     resourceCache.add(singleProject, null).setSnapshot(persister.persist(null, singleProject, null));
-    persister.persist(singleProject, Directory.create("src/main/java/org/foo", "org.foo").setEffectiveKey("foo:src/main/java/org/foo"), null);
+    persister.persist(singleProject, Directory.create("src/main/java/org/foo").setEffectiveKey("foo:src/main/java/org/foo"), null);
     // check that the directory is attached to the project
     checkTables("shouldSaveNewDirectory", new String[] {"build_date", "created_at", "authorization_updated_at", "uuid", "project_uuid", "module_uuid", "module_uuid_path"},
       "projects", "snapshots");
index 821cb7357569929b895f5bcf5f15cd2e9373413c..2c510d62aac243aa0b131ea2f478d5be570d0cb1 100644 (file)
@@ -26,6 +26,7 @@ import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.rules.TemporaryFolder;
+import org.sonar.api.batch.fs.internal.DefaultFileSystem;
 import org.sonar.api.batch.fs.internal.DefaultInputFile;
 import org.sonar.api.batch.sensor.duplication.DuplicationGroup;
 import org.sonar.api.batch.sensor.highlighting.TypeOfText;
@@ -35,6 +36,7 @@ import org.sonar.api.measures.Metric;
 import org.sonar.batch.duplication.DuplicationCache;
 import org.sonar.batch.highlighting.SyntaxHighlightingData;
 import org.sonar.batch.highlighting.SyntaxHighlightingDataBuilder;
+import org.sonar.batch.scan.filesystem.InputFileMetadata;
 import org.sonar.batch.scan.measure.MeasureCache;
 import org.sonar.batch.source.CodeColorizers;
 import org.sonar.batch.symbol.DefaultSymbolTableBuilder;
@@ -58,18 +60,21 @@ public class SourceDataFactoryTest {
   DuplicationCache duplicationCache = mock(DuplicationCache.class);
   CodeColorizers colorizers = mock(CodeColorizers.class);
   DefaultInputFile inputFile;
+  InputFileMetadata metadata;
   SourceDataFactory sut = new SourceDataFactory(measureCache, componentDataCache, duplicationCache, colorizers);
   FileSourceDb.Data.Builder output;
 
   @Before
   public void setUp() throws Exception {
     // generate a file with 3 lines
-    File file = temp.newFile();
+    File baseDir = temp.newFolder();
+    DefaultFileSystem fs = new DefaultFileSystem(baseDir.toPath());
     inputFile = new DefaultInputFile("module_key", "src/Foo.java")
       .setLines(3)
-      .setEncoding(Charsets.UTF_8.name())
-      .setFile(file);
-    FileUtils.write(file, "one\ntwo\nthree\n");
+      .setCharset(Charsets.UTF_8);
+    fs.add(inputFile);
+    metadata = new InputFileMetadata();
+    FileUtils.write(inputFile.file(), "one\ntwo\nthree\n");
     output = sut.createForSource(inputFile);
   }
 
@@ -84,7 +89,7 @@ public class SourceDataFactoryTest {
 
   @Test
   public void consolidateData() throws Exception {
-    byte[] bytes = sut.consolidateData(inputFile);
+    byte[] bytes = sut.consolidateData(inputFile, metadata);
     assertThat(bytes).isNotEmpty();
   }
 
@@ -145,7 +150,6 @@ public class SourceDataFactoryTest {
       Arrays.asList(new Measure().setData(dataPerLine).setMetric(metric)));
   }
 
-
   @Test
   public void applyDuplications() throws Exception {
     DuplicationGroup group1 = new DuplicationGroup(new DuplicationGroup.Block(inputFile.key(), 1, 1))
@@ -169,7 +173,7 @@ public class SourceDataFactoryTest {
   public void applyHighlighting_missing() throws Exception {
     when(componentDataCache.getData(inputFile.key(), SnapshotDataTypes.SYNTAX_HIGHLIGHTING)).thenReturn(null);
 
-    sut.applyHighlighting(inputFile, output);
+    sut.applyHighlighting(inputFile, metadata, output);
 
     FileSourceDb.Data data = output.build();
     assertThat(data.getLines(0).hasHighlighting()).isFalse();
@@ -185,9 +189,9 @@ public class SourceDataFactoryTest {
       .registerHighlightingRule(7, 16, TypeOfText.CONSTANT)
       .build();
     when(componentDataCache.getData(inputFile.key(), SnapshotDataTypes.SYNTAX_HIGHLIGHTING)).thenReturn(highlighting);
-    inputFile.setOriginalLineOffsets(new long[] {0, 4, 7});
+    metadata.setOriginalLineOffsets(new int[] {0, 4, 7});
 
-    sut.applyHighlighting(inputFile, output);
+    sut.applyHighlighting(inputFile, metadata, output);
 
     FileSourceDb.Data data = output.build();
     assertThat(data.getLines(0).getHighlighting()).isEqualTo("0,4,a");
@@ -203,9 +207,9 @@ public class SourceDataFactoryTest {
       .registerHighlightingRule(10, 16, TypeOfText.CONSTANT)
       .build();
     when(componentDataCache.getData(inputFile.key(), SnapshotDataTypes.SYNTAX_HIGHLIGHTING)).thenReturn(highlighting);
-    inputFile.setOriginalLineOffsets(new long[] {0, 4, 7});
+    metadata.setOriginalLineOffsets(new int[] {0, 4, 7});
 
-    sut.applyHighlighting(inputFile, output);
+    sut.applyHighlighting(inputFile, metadata, output);
 
     FileSourceDb.Data data = output.build();
     assertThat(data.getLines(0).getHighlighting()).isEqualTo("0,3,a");
@@ -222,9 +226,9 @@ public class SourceDataFactoryTest {
       .registerHighlightingRule(8, 15, TypeOfText.KEYWORD)
       .build();
     when(componentDataCache.getData(inputFile.key(), SnapshotDataTypes.SYNTAX_HIGHLIGHTING)).thenReturn(highlighting);
-    inputFile.setOriginalLineOffsets(new long[] {0, 4, 7});
+    metadata.setOriginalLineOffsets(new int[] {0, 4, 7});
 
-    sut.applyHighlighting(inputFile, output);
+    sut.applyHighlighting(inputFile, metadata, output);
 
     FileSourceDb.Data data = output.build();
     assertThat(data.getLines(0).getHighlighting()).isEqualTo("0,3,a");
@@ -241,9 +245,9 @@ public class SourceDataFactoryTest {
       .registerHighlightingRule(8, 15, TypeOfText.KEYWORD)
       .build();
     when(componentDataCache.getData(inputFile.key(), SnapshotDataTypes.SYNTAX_HIGHLIGHTING)).thenReturn(highlighting);
-    inputFile.setOriginalLineOffsets(new long[] {0, 4, 7});
+    metadata.setOriginalLineOffsets(new int[] {0, 4, 7});
 
-    sut.applyHighlighting(inputFile, output);
+    sut.applyHighlighting(inputFile, metadata, output);
 
     FileSourceDb.Data data = output.build();
     assertThat(data.getLines(0).getHighlighting()).isEqualTo("0,3,a");
@@ -255,7 +259,7 @@ public class SourceDataFactoryTest {
   public void applySymbolReferences_missing() throws Exception {
     when(componentDataCache.getData(inputFile.key(), SnapshotDataTypes.SYMBOL_HIGHLIGHTING)).thenReturn(null);
 
-    sut.applySymbolReferences(inputFile, output);
+    sut.applySymbolReferences(inputFile, metadata, output);
 
     FileSourceDb.Data data = output.build();
     assertThat(data.getLines(0).hasSymbols()).isFalse();
@@ -273,9 +277,9 @@ public class SourceDataFactoryTest {
     symbolBuilder.newReference(s2, 0);
     symbolBuilder.newReference(s2, 7);
     when(componentDataCache.getData(inputFile.key(), SnapshotDataTypes.SYMBOL_HIGHLIGHTING)).thenReturn(symbolBuilder.build());
-    inputFile.setOriginalLineOffsets(new long[] {0, 4, 7});
+    metadata.setOriginalLineOffsets(new int[] {0, 4, 7});
 
-    sut.applySymbolReferences(inputFile, output);
+    sut.applySymbolReferences(inputFile, metadata, output);
 
     FileSourceDb.Data data = output.build();
     assertThat(data.getLines(0).getSymbols()).isEqualTo("1,2,1;0,2,2");
@@ -293,9 +297,9 @@ public class SourceDataFactoryTest {
     symbolBuilder.newReference(s1, 11);
     symbolBuilder.newReference(s1, 4);
     when(componentDataCache.getData(inputFile.key(), SnapshotDataTypes.SYMBOL_HIGHLIGHTING)).thenReturn(symbolBuilder.build());
-    inputFile.setOriginalLineOffsets(new long[] {0, 4, 7});
+    metadata.setOriginalLineOffsets(new int[] {0, 4, 7});
 
-    sut.applySymbolReferences(inputFile, output);
+    sut.applySymbolReferences(inputFile, metadata, output);
 
     FileSourceDb.Data data = output.build();
     assertThat(data.getLines(0).getSymbols()).isEqualTo("1,2,1;0,2,2");
index c24e04a1ded203802bf7bb09c3070832f1587a25..514a6d05a1bc91b5d584e5b1402792862baf31a1 100644 (file)
@@ -40,7 +40,7 @@ public class IssuableFactoryTest {
   @Test
   public void file_should_be_issuable() throws Exception {
     IssuableFactory factory = new IssuableFactory(moduleIssues, cache, projectTree);
-    Component component = new ResourceComponent(new File("foo/bar.c").setEffectiveKey("foo/bar.c"));
+    Component component = new ResourceComponent(File.create("foo/bar.c").setEffectiveKey("foo/bar.c"));
     Issuable issuable = factory.loadPerspective(Issuable.class, component);
 
     assertThat(issuable).isNotNull();
index 0594cb162347ac7bcaeb1d0baba570f6ba4c7bcd..7ffa990572183c408ce32c438932dfba42ee507d 100644 (file)
@@ -207,7 +207,7 @@ public class ModuleIssuesTest {
     initModuleIssues();
 
     org.sonar.api.rules.Rule rule = org.sonar.api.rules.Rule.create("squid", "AvoidCycle", "Avoid Cycle");
-    Resource resource = new File("org/struts/Action.java").setEffectiveKey("struts:src/org/struts/Action.java");
+    Resource resource = File.create("org/struts/Action.java").setEffectiveKey("struts:src/org/struts/Action.java");
     Violation violation = new Violation(rule, resource);
     violation.setLineId(42);
     violation.setSeverity(RulePriority.CRITICAL);
index 9fd36ece0b77abf7978e6cfa66d2ace7ecda4af1..3cca58ac2b27d105c45141d606bf35aa2f5b524e 100644 (file)
@@ -72,7 +72,7 @@ public class IssueExclusionsLoaderTest {
   @Before
   public void before() throws Exception {
     baseDir = temp.newFolder();
-    fs = new DefaultFileSystem(baseDir).setEncoding(UTF_8);
+    fs = new DefaultFileSystem(baseDir.toPath()).setEncoding(UTF_8);
     MockitoAnnotations.initMocks(this);
     scanner = new IssueExclusionsLoader(regexpScanner, exclusionPatternInitializer, inclusionPatternInitializer, fs);
   }
@@ -106,11 +106,9 @@ public class IssueExclusionsLoaderTest {
   public void shouldAnalyzeProject() throws IOException {
     File javaFile1 = new File(baseDir, "src/main/java/Foo.java");
     fs.add(new DeprecatedDefaultInputFile("polop", "src/main/java/Foo.java")
-      .setFile(javaFile1)
       .setType(InputFile.Type.MAIN));
     File javaTestFile1 = new File(baseDir, "src/test/java/FooTest.java");
     fs.add(new DeprecatedDefaultInputFile("polop", "src/test/java/FooTest.java")
-      .setFile(javaTestFile1)
       .setType(InputFile.Type.TEST));
 
     when(exclusionPatternInitializer.hasFileContentPattern()).thenReturn(true);
@@ -129,11 +127,9 @@ public class IssueExclusionsLoaderTest {
   public void shouldAnalyseFilesOnlyWhenRegexConfigured() throws IOException {
     File javaFile1 = new File(baseDir, "src/main/java/Foo.java");
     fs.add(new DeprecatedDefaultInputFile("polop", "src/main/java/Foo.java")
-      .setFile(javaFile1)
       .setType(InputFile.Type.MAIN));
     File javaTestFile1 = new File(baseDir, "src/test/java/FooTest.java");
     fs.add(new DeprecatedDefaultInputFile("polop", "src/test/java/FooTest.java")
-      .setFile(javaTestFile1)
       .setType(InputFile.Type.TEST));
     when(exclusionPatternInitializer.hasFileContentPattern()).thenReturn(false);
 
@@ -150,7 +146,6 @@ public class IssueExclusionsLoaderTest {
   public void shouldReportFailure() throws IOException {
     File phpFile1 = new File(baseDir, "src/Foo.php");
     fs.add(new DeprecatedDefaultInputFile("polop", "src/Foo.php")
-      .setFile(phpFile1)
       .setType(InputFile.Type.MAIN));
 
     when(exclusionPatternInitializer.hasFileContentPattern()).thenReturn(true);
index 7691dbf6538ff112f6ae57c911e0586a59f72c4d..1c5e080cd062fc079a94770fe476a43fc945f0ff 100644 (file)
  */
 package org.sonar.batch.issue.tracking;
 
+import com.google.common.base.Charsets;
 import org.apache.commons.codec.digest.DigestUtils;
+import org.apache.commons.io.FileUtils;
 import org.junit.Before;
 import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
 import org.mockito.ArgumentCaptor;
 import org.mockito.ArgumentMatcher;
 import org.sonar.api.batch.DecoratorContext;
@@ -41,6 +44,7 @@ import org.sonar.api.utils.Duration;
 import org.sonar.api.utils.System2;
 import org.sonar.batch.issue.IssueCache;
 import org.sonar.batch.scan.LastLineHashes;
+import org.sonar.batch.scan.filesystem.InputFileMetadata;
 import org.sonar.batch.scan.filesystem.InputPathCache;
 import org.sonar.core.issue.IssueUpdater;
 import org.sonar.core.issue.db.IssueChangeDto;
@@ -48,6 +52,7 @@ import org.sonar.core.issue.db.IssueDto;
 import org.sonar.core.issue.workflow.IssueWorkflow;
 import org.sonar.java.api.JavaClass;
 
+import java.io.IOException;
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.Collections;
@@ -71,6 +76,9 @@ import static org.mockito.Mockito.when;
 
 public class IssueTrackingDecoratorTest {
 
+  @org.junit.Rule
+  public TemporaryFolder temp = new TemporaryFolder();
+
   IssueTrackingDecorator decorator;
   IssueCache issueCache = mock(IssueCache.class, RETURNS_MOCKS);
   InitialOpenIssuesStack initialOpenIssues = mock(InitialOpenIssuesStack.class);
@@ -124,6 +132,7 @@ public class IssueTrackingDecoratorTest {
     List<PreviousIssue> dbIssues = Collections.emptyList();
     when(initialOpenIssues.selectAndRemoveIssues("struts:Action.java")).thenReturn(dbIssues);
     when(inputPathCache.getFile("foo", "Action.java")).thenReturn(mock(DefaultInputFile.class));
+    when(inputPathCache.getFileMetadata("foo", "Action.java")).thenReturn(new InputFileMetadata());
     decorator.doDecorate(file);
 
     // Apply filters, track, apply transitions, notify extensions then update cache
@@ -152,6 +161,7 @@ public class IssueTrackingDecoratorTest {
 
     when(tracking.track(isA(SourceHashHolder.class), anyCollection(), anyCollection())).thenReturn(trackingResult);
     when(inputPathCache.getFile("foo", "Action.java")).thenReturn(mock(DefaultInputFile.class));
+    when(inputPathCache.getFileMetadata("foo", "Action.java")).thenReturn(new InputFileMetadata());
 
     decorator.doDecorate(file);
 
@@ -210,10 +220,13 @@ public class IssueTrackingDecoratorTest {
     assertThat(issue.isOnDisabledRule()).isFalse();
   }
 
-  private Resource mockHashes(String originalSource, String newSource) {
+  private Resource mockHashes(String originalSource, String newSource) throws IOException {
     DefaultInputFile inputFile = mock(DefaultInputFile.class);
-    byte[][] hashes = computeHashes(newSource);
-    when(inputFile.lineHashes()).thenReturn(hashes);
+    java.io.File f = temp.newFile();
+    when(inputFile.path()).thenReturn(f.toPath());
+    when(inputFile.charset()).thenReturn(Charsets.UTF_8);
+    when(inputFile.lines()).thenReturn(newSource.split("\n").length);
+    FileUtils.write(f, newSource, Charsets.UTF_8);
     when(inputFile.key()).thenReturn("foo:Action.java");
     when(inputPathCache.getFile("foo", "Action.java")).thenReturn(inputFile);
     when(lastSnapshots.getLineHashes("foo:Action.java")).thenReturn(computeHexHashes(originalSource));
@@ -561,15 +574,6 @@ public class IssueTrackingDecoratorTest {
     assertThat(issue.changes()).hasSize(1);
   }
 
-  private byte[][] computeHashes(String source) {
-    String[] lines = source.split("\n");
-    byte[][] hashes = new byte[lines.length][];
-    for (int i = 0; i < lines.length; i++) {
-      hashes[i] = DigestUtils.md5(lines[i].replaceAll("[\t ]", ""));
-    }
-    return hashes;
-  }
-
   private String[] computeHexHashes(String source) {
     String[] lines = source.split("\n");
     String[] hashes = new String[lines.length];
index 2efb24c13ebff956777112596b2a76c65dfdb483..bcc25ac598c9e9b49e71cc631088ba0f8e6e0b3f 100644 (file)
@@ -24,8 +24,11 @@ import com.google.common.base.Charsets;
 import com.google.common.collect.Lists;
 import com.google.common.io.Resources;
 import org.apache.commons.codec.digest.DigestUtils;
+import org.apache.commons.io.FileUtils;
 import org.junit.Before;
+import org.junit.Rule;
 import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
 import org.sonar.api.batch.fs.internal.DefaultInputFile;
 import org.sonar.api.issue.Issue;
 import org.sonar.api.issue.internal.DefaultIssue;
@@ -35,6 +38,7 @@ import org.sonar.api.rule.RuleKey;
 import org.sonar.batch.scan.LastLineHashes;
 import org.sonar.core.issue.db.IssueDto;
 
+import java.io.File;
 import java.io.IOException;
 import java.util.Arrays;
 import java.util.Collections;
@@ -47,6 +51,9 @@ import static org.mockito.Mockito.when;
 
 public class IssueTrackingTest {
 
+  @Rule
+  public TemporaryFolder temp = new TemporaryFolder();
+
   IssueTracking tracking;
   Resource project;
   SourceHashHolder sourceHashHolder;
@@ -345,22 +352,17 @@ public class IssueTrackingTest {
 
   private void initLastHashes(String reference, String newSource) throws IOException {
     DefaultInputFile inputFile = mock(DefaultInputFile.class);
-    byte[][] hashes = computeHashes(load(newSource));
-    when(inputFile.lineHashes()).thenReturn(hashes);
+    File f = temp.newFile();
+    when(inputFile.path()).thenReturn(f.toPath());
+    when(inputFile.charset()).thenReturn(Charsets.UTF_8);
+    String data = load(newSource);
+    when(inputFile.lines()).thenReturn(data.split("\n").length);
+    FileUtils.write(f, data, Charsets.UTF_8);
     when(inputFile.key()).thenReturn("foo:Action.java");
     when(lastSnapshots.getLineHashes("foo:Action.java")).thenReturn(computeHexHashes(load(reference)));
     sourceHashHolder = new SourceHashHolder(inputFile, lastSnapshots);
   }
 
-  private byte[][] computeHashes(String source) {
-    String[] lines = source.split("\n");
-    byte[][] hashes = new byte[lines.length][];
-    for (int i = 0; i < lines.length; i++) {
-      hashes[i] = DigestUtils.md5(lines[i].replaceAll("[\t ]", ""));
-    }
-    return hashes;
-  }
-
   private String[] computeHexHashes(String source) {
     String[] lines = source.split("\n");
     String[] hashes = new String[lines.length];
index 6ac6645bbae734d604baa0995ca9f05596367c98..59371ca494768032b248f98069277682a7a5f103 100644 (file)
  */
 package org.sonar.batch.issue.tracking;
 
+import com.google.common.base.Charsets;
+import org.apache.commons.io.FileUtils;
 import org.junit.Before;
+import org.junit.Rule;
 import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
 import org.mockito.Mockito;
 import org.sonar.api.batch.fs.InputFile;
 import org.sonar.api.batch.fs.internal.DefaultInputFile;
 import org.sonar.batch.scan.LastLineHashes;
 
-import static org.apache.commons.codec.digest.DigestUtils.md5;
+import java.io.File;
+
 import static org.apache.commons.codec.digest.DigestUtils.md5Hex;
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.mockito.Mockito.mock;
@@ -35,39 +40,48 @@ import static org.mockito.Mockito.when;
 
 public class SourceHashHolderTest {
 
+  @Rule
+  public TemporaryFolder temp = new TemporaryFolder();
+
   SourceHashHolder sourceHashHolder;
 
   LastLineHashes lastSnapshots;
   DefaultInputFile file;
 
+  private File ioFile;
+
   @Before
-  public void setUp() {
+  public void setUp() throws Exception {
     lastSnapshots = mock(LastLineHashes.class);
     file = mock(DefaultInputFile.class);
+    ioFile = temp.newFile();
+    when(file.file()).thenReturn(ioFile);
+    when(file.path()).thenReturn(ioFile.toPath());
+    when(file.lines()).thenReturn(1);
+    when(file.charset()).thenReturn(Charsets.UTF_8);
 
     sourceHashHolder = new SourceHashHolder(file, lastSnapshots);
   }
 
   @Test
-  public void should_lazy_load_line_hashes() {
+  public void should_lazy_load_line_hashes() throws Exception {
     final String source = "source";
-    when(file.lineHashes()).thenReturn(new byte[][] {md5(source), null});
+    FileUtils.write(ioFile, source + "\n", Charsets.UTF_8);
+    when(file.lines()).thenReturn(2);
 
     assertThat(sourceHashHolder.getHashedSource().getHash(1)).isEqualTo(md5Hex(source));
     assertThat(sourceHashHolder.getHashedSource().getHash(2)).isEqualTo("");
-    verify(file).lineHashes();
     verify(file).key();
     verify(file).status();
 
     assertThat(sourceHashHolder.getHashedSource().getHash(1)).isEqualTo(md5Hex(source));
-    Mockito.verifyNoMoreInteractions(file);
   }
 
   @Test
-  public void should_lazy_load_reference_hashes_when_status_changed() {
+  public void should_lazy_load_reference_hashes_when_status_changed() throws Exception {
     final String source = "source";
     String key = "foo:src/Foo.java";
-    when(file.lineHashes()).thenReturn(new byte[][] {md5(source)});
+    FileUtils.write(ioFile, source, Charsets.UTF_8);
     when(file.key()).thenReturn(key);
     when(file.status()).thenReturn(InputFile.Status.CHANGED);
     when(lastSnapshots.getLineHashes(key)).thenReturn(new String[] {md5Hex(source)});
@@ -80,23 +94,22 @@ public class SourceHashHolderTest {
   }
 
   @Test
-  public void should_not_load_reference_hashes_when_status_same() {
+  public void should_not_load_reference_hashes_when_status_same() throws Exception {
     final String source = "source";
     String key = "foo:src/Foo.java";
-    when(file.lineHashes()).thenReturn(new byte[][] {md5(source)});
+    FileUtils.write(ioFile, source, Charsets.UTF_8);
     when(file.key()).thenReturn(key);
     when(file.status()).thenReturn(InputFile.Status.SAME);
 
-    assertThat(sourceHashHolder.getHashedReference().getHash(1)).isEqualTo(md5Hex(source));
     assertThat(sourceHashHolder.getHashedReference().getHash(1)).isEqualTo(md5Hex(source));
     Mockito.verifyNoMoreInteractions(lastSnapshots);
   }
 
   @Test
-  public void no_reference_hashes_when_status_added() {
+  public void no_reference_hashes_when_status_added() throws Exception {
     final String source = "source";
     String key = "foo:src/Foo.java";
-    when(file.lineHashes()).thenReturn(new byte[][] {md5(source)});
+    FileUtils.write(ioFile, source, Charsets.UTF_8);
     when(file.key()).thenReturn(key);
     when(file.status()).thenReturn(InputFile.Status.ADDED);
 
index 45774d11f95eae042b916b9f94932d6ef4257658..7b644d27530c4d326728a22309b3fbdc64d0b772 100644 (file)
@@ -28,8 +28,8 @@ import org.sonar.api.resources.File;
 import org.sonar.api.resources.Project;
 import org.sonar.api.resources.Resource;
 import org.sonar.api.utils.SonarException;
-import org.sonar.batch.DefaultDecoratorContext;
 import org.sonar.batch.bootstrap.BatchExtensionDictionnary;
+import org.sonar.batch.deprecated.decorator.DefaultDecoratorContext;
 import org.sonar.batch.duplication.DuplicationCache;
 import org.sonar.batch.events.EventBus;
 import org.sonar.batch.scan.measure.MeasureCache;
@@ -69,7 +69,7 @@ public class DecoratorsExecutorTest {
     DecoratorsExecutor executor = new DecoratorsExecutor(mock(BatchExtensionDictionnary.class), new Project("key"), mock(SonarIndex.class),
       mock(EventBus.class), mock(CoverageExclusions.class), mock(MeasureCache.class), mock(MetricFinder.class), mock(DuplicationCache.class));
     try {
-      executor.executeDecorator(decorator, mock(DefaultDecoratorContext.class), File.create("src/org/foo/Bar.java", "org/foo/Bar.java", null, false));
+      executor.executeDecorator(decorator, mock(DefaultDecoratorContext.class), File.create("src/org/foo/Bar.java", null, false));
       fail("Exception has not been thrown");
 
     } catch (SonarException e) {
index 83cab61793e91f85b26d523bfb06961dec89d307..e7e2c3328384261337b0f7c4ddf57c0799cb71da 100644 (file)
@@ -19,8 +19,6 @@
  */
 package org.sonar.batch.qualitygate;
 
-import org.sonar.batch.qualitygate.GenerateQualityGateEvents;
-
 import org.junit.Before;
 import org.junit.Test;
 import org.sonar.api.batch.DecoratorContext;
@@ -35,14 +33,20 @@ import org.sonar.api.notifications.NotificationManager;
 import org.sonar.api.resources.File;
 import org.sonar.api.resources.Project;
 import org.sonar.api.test.ProjectTestBuilder;
-import org.sonar.batch.qualitygate.QualityGate;
 
 import java.util.Arrays;
 import java.util.Date;
 
 import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.Matchers.*;
-import static org.mockito.Mockito.*;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Matchers.isNull;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
 
 public class GenerateQualityGateEventsTest {
   private GenerateQualityGateEvents decorator;
@@ -80,7 +84,7 @@ public class GenerateQualityGateEventsTest {
 
   @Test
   public void shouldNotDecorateIfNotRootProject() {
-    decorator.decorate(new File("Foo"), context);
+    decorator.decorate(File.create("Foo"), context);
     verify(context, never()).createEvent(anyString(), anyString(), anyString(), (Date) isNull());
   }
 
index 87a72c6c0578dde9ab9c2b2bdd727f89a80805f5..30f56d3a46eae8321ceb884266caa8f6de346e61 100644 (file)
@@ -62,17 +62,17 @@ public class ComponentsPublisherTest {
     dir.setId(3).setUuid("DIR_UUID");
     resourceCache.add(dir, module1).setSnapshot(new Snapshot().setId(13));
 
-    org.sonar.api.resources.File file = org.sonar.api.resources.File.create("src/Foo.java", "Foo.java", Java.INSTANCE, false);
+    org.sonar.api.resources.File file = org.sonar.api.resources.File.create("src/Foo.java", Java.INSTANCE, false);
     file.setEffectiveKey("foo:src/Foo.java");
     file.setId(4).setUuid("FILE_UUID");
     resourceCache.add(file, dir).setSnapshot(new Snapshot().setId(14));
 
-    org.sonar.api.resources.File fileWithoutLang = org.sonar.api.resources.File.create("src/make", "make", null, false);
+    org.sonar.api.resources.File fileWithoutLang = org.sonar.api.resources.File.create("src/make", null, false);
     fileWithoutLang.setEffectiveKey("foo:src/make");
     fileWithoutLang.setId(5).setUuid("FILE_WITHOUT_LANG_UUID");
     resourceCache.add(fileWithoutLang, dir).setSnapshot(new Snapshot().setId(15));
 
-    org.sonar.api.resources.File testFile = org.sonar.api.resources.File.create("test/FooTest.java", "FooTest.java", Java.INSTANCE, true);
+    org.sonar.api.resources.File testFile = org.sonar.api.resources.File.create("test/FooTest.java", Java.INSTANCE, true);
     testFile.setEffectiveKey("foo:test/FooTest.java");
     testFile.setId(6).setUuid("TEST_FILE_UUID");
     resourceCache.add(testFile, dir).setSnapshot(new Snapshot().setId(16));
diff --git a/sonar-batch/src/test/java/org/sonar/batch/repository/user/UserRepositoryTest.java b/sonar-batch/src/test/java/org/sonar/batch/repository/user/UserRepositoryTest.java
new file mode 100644 (file)
index 0000000..ad8c954
--- /dev/null
@@ -0,0 +1,44 @@
+/*
+ * 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.batch.repository.user;
+
+import org.junit.Test;
+import org.sonar.batch.bootstrap.ServerClient;
+
+import java.util.Arrays;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+public class UserRepositoryTest {
+
+  @Test
+  public void testLoad() {
+    ServerClient serverClient = mock(ServerClient.class);
+    UserRepository userRepo = new UserRepository(serverClient);
+
+    when(serverClient.request("/api/users/search?format=json&includeDeactivated=true&logins=fmallet,sbrandhof"))
+      .thenReturn(
+        "{ \"users\": [ { \"login\": \"fmallet\", \"name\": \"Freddy Mallet\", \"active\": true, \"email\": \"f@m.com\" }, { \"login\": \"sbrandhof\", \"name\": \"Simon\", \"active\": true } ] }");
+
+    assertThat(userRepo.loadFromWs(Arrays.asList("fmallet", "sbrandhof"))).containsOnly(new User("fmallet", "Freddy Mallet"), new User("sbrandhof", "Simon"));
+  }
+}
index c9e6deabcaf35027e63413b5fa78badf31c6daff..7c83baad914f8f21bff21dfeaf3d5cae696cec14 100644 (file)
@@ -23,6 +23,7 @@ import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.rules.TemporaryFolder;
+import org.sonar.api.batch.AnalysisMode;
 import org.sonar.api.batch.SensorContext;
 import org.sonar.api.batch.fs.internal.DefaultFileSystem;
 import org.sonar.api.measures.CoreMetrics;
@@ -57,20 +58,29 @@ public class QProfileSensorTest {
 
   @Before
   public void prepare() throws Exception {
-    fs = new DefaultFileSystem(temp.newFolder());
+    fs = new DefaultFileSystem(temp.newFolder().toPath());
   }
 
   @Test
   public void to_string() throws Exception {
-    QProfileSensor sensor = new QProfileSensor(moduleQProfiles, fs);
+    QProfileSensor sensor = new QProfileSensor(moduleQProfiles, fs, mock(AnalysisMode.class));
     assertThat(sensor.toString()).isEqualTo("QProfileSensor");
   }
 
+  @Test
+  public void no_execution_in_preview() throws Exception {
+    AnalysisMode analysisMode = mock(AnalysisMode.class);
+    when(analysisMode.isPreview()).thenReturn(true);
+    QProfileSensor sensor = new QProfileSensor(moduleQProfiles, fs, analysisMode);
+    assertThat(sensor.shouldExecuteOnProject(project)).isFalse();
+
+  }
+
   @Test
   public void no_qprofiles() throws Exception {
     when(moduleQProfiles.findAll()).thenReturn(Collections.<QProfile>emptyList());
 
-    QProfileSensor sensor = new QProfileSensor(moduleQProfiles, fs);
+    QProfileSensor sensor = new QProfileSensor(moduleQProfiles, fs, mock(AnalysisMode.class));
     assertThat(sensor.shouldExecuteOnProject(project)).isTrue();
     sensor.analyse(project, sensorContext);
 
@@ -85,7 +95,7 @@ public class QProfileSensorTest {
     when(moduleQProfiles.findByLanguage("abap")).thenReturn(null);
     fs.addLanguages("java", "php", "abap");
 
-    QProfileSensor sensor = new QProfileSensor(moduleQProfiles, fs);
+    QProfileSensor sensor = new QProfileSensor(moduleQProfiles, fs, mock(AnalysisMode.class));
     assertThat(sensor.shouldExecuteOnProject(project)).isTrue();
     sensor.analyse(project, sensorContext);
   }
@@ -97,7 +107,7 @@ public class QProfileSensorTest {
     when(moduleQProfiles.findByLanguage("abap")).thenReturn(null);
     fs.addLanguages("java");
 
-    QProfileSensor sensor = new QProfileSensor(moduleQProfiles, fs);
+    QProfileSensor sensor = new QProfileSensor(moduleQProfiles, fs, mock(AnalysisMode.class));
     assertThat(sensor.shouldExecuteOnProject(project)).isTrue();
     sensor.analyse(project, sensorContext);
 
@@ -113,7 +123,7 @@ public class QProfileSensorTest {
     when(moduleQProfiles.findByLanguage("abap")).thenReturn(null);
     fs.addLanguages("java", "php");
 
-    QProfileSensor sensor = new QProfileSensor(moduleQProfiles, fs);
+    QProfileSensor sensor = new QProfileSensor(moduleQProfiles, fs, mock(AnalysisMode.class));
     assertThat(sensor.shouldExecuteOnProject(project)).isTrue();
     sensor.analyse(project, sensorContext);
 
index 9c5db0f6d6af723fee02588cd24952455a905185..61463ae574283291512e22cdaccf23a247e9c4aa 100644 (file)
@@ -47,7 +47,7 @@ public class QProfileVerifierTest {
 
   @Before
   public void before() throws Exception {
-    fs = new DefaultFileSystem(temp.newFolder());
+    fs = new DefaultFileSystem(temp.newFolder().toPath());
     profiles = mock(ModuleQProfiles.class);
     QProfile javaProfile = new QProfile().setKey("p1").setName("My Java profile").setLanguage("java");
     when(profiles.findByLanguage("java")).thenReturn(javaProfile);
index a60fd596e531909bce7c41fe2d5c73512fcb9f1b..420d0641c36fc3063106a5a7eae9ac4656409927 100644 (file)
@@ -29,8 +29,8 @@ import org.sonar.api.config.Settings;
 import org.sonar.api.resources.Java;
 import org.sonar.api.resources.Languages;
 import org.sonar.api.utils.MessageException;
-import org.sonar.batch.languages.DefaultLanguagesReferential;
-import org.sonar.batch.languages.LanguagesReferential;
+import org.sonar.batch.repository.language.DefaultLanguagesRepository;
+import org.sonar.batch.repository.language.LanguagesRepository;
 
 import static org.assertj.core.api.Assertions.assertThat;
 
@@ -43,12 +43,12 @@ public class LanguageVerifierTest {
   public ExpectedException thrown = ExpectedException.none();
 
   private Settings settings = new Settings();
-  private LanguagesReferential languages = new DefaultLanguagesReferential(new Languages(Java.INSTANCE));
+  private LanguagesRepository languages = new DefaultLanguagesRepository(new Languages(Java.INSTANCE));
   private DefaultFileSystem fs;
 
   @Before
   public void prepare() throws Exception {
-    fs = new DefaultFileSystem(temp.newFolder());
+    fs = new DefaultFileSystem(temp.newFolder().toPath());
   }
 
   @Test
index ff6e76e08575ce65612006bb0ee8aef141f579b7..ad3dfffc4915dc551c0c8465db3b913f12f612c7 100644 (file)
@@ -26,8 +26,6 @@ import org.sonar.api.batch.fs.FilePredicate;
 import org.sonar.api.batch.fs.internal.DefaultInputFile;
 import org.sonar.api.batch.fs.internal.DeprecatedDefaultInputFile;
 
-import java.io.File;
-
 import static org.assertj.core.api.Assertions.assertThat;
 
 public class AdditionalFilePredicatesTest {
@@ -45,38 +43,4 @@ public class AdditionalFilePredicatesTest {
     inputFile = new DeprecatedDefaultInputFile("struts", "Filter.java");
     assertThat(predicate.apply(inputFile)).isFalse();
   }
-
-  @Test
-  public void deprecated_key() throws Exception {
-    FilePredicate predicate = new AdditionalFilePredicates.DeprecatedKeyPredicate("struts:Action.java");
-
-    DeprecatedDefaultInputFile inputFile = new DeprecatedDefaultInputFile("struts", "Action.java").setDeprecatedKey("struts:Action.java");
-    assertThat(predicate.apply(inputFile)).isTrue();
-
-    inputFile = new DeprecatedDefaultInputFile("struts", "Filter.java").setDeprecatedKey("struts:Filter.java");
-    assertThat(predicate.apply(inputFile)).isFalse();
-  }
-
-  @Test
-  public void absolute_path_of_source_dir() throws Exception {
-    File dir = temp.newFolder();
-    FilePredicate predicate = new AdditionalFilePredicates.SourceDirPredicate(dir.getAbsolutePath());
-
-    DeprecatedDefaultInputFile inputFile = new DeprecatedDefaultInputFile("struts", "Action.java").setSourceDirAbsolutePath(dir.getAbsolutePath());
-    assertThat(predicate.apply(inputFile)).isTrue();
-
-    inputFile = new DeprecatedDefaultInputFile("struts", "Filter.java").setSourceDirAbsolutePath(temp.newFolder().getAbsolutePath());
-    assertThat(predicate.apply(inputFile)).isFalse();
-  }
-
-  @Test
-  public void path_relative_to_source_dir() throws Exception {
-    FilePredicate predicate = new AdditionalFilePredicates.SourceRelativePathPredicate("foo/Bar.php");
-
-    DeprecatedDefaultInputFile inputFile = new DeprecatedDefaultInputFile("foo", "src/php/foo/Bar.php").setPathRelativeToSourceDir("foo/Bar.php");
-    assertThat(predicate.apply(inputFile)).isTrue();
-
-    inputFile = new DeprecatedDefaultInputFile("foo", "foo/Bar.php").setPathRelativeToSourceDir("Bar.php");
-    assertThat(predicate.apply(inputFile)).isFalse();
-  }
 }
index 702aa2fb068d89e32c5db1b0d3a0aed543218735..5960fab5c2d0aec129be3a6e800b0b6fcf2bc4f1 100644 (file)
@@ -42,6 +42,7 @@ import java.io.IOException;
 import static org.mockito.Matchers.argThat;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
 
 public class ComponentIndexerTest {
 
@@ -52,13 +53,17 @@ public class ComponentIndexerTest {
   private SonarIndex sonarIndex;
   private AbstractLanguage cobolLanguage;
   private Project project;
+  private ModuleFileSystemInitializer initializer;
 
   @Before
   public void prepare() throws IOException {
     baseDir = temp.newFolder();
-    fs = new DefaultFileSystem(baseDir);
+    fs = new DefaultFileSystem(baseDir.toPath());
     sonarIndex = mock(SonarIndex.class);
     project = new Project("myProject");
+    initializer = mock(ModuleFileSystemInitializer.class);
+    when(initializer.baseDir()).thenReturn(baseDir);
+    when(initializer.workingDir()).thenReturn(temp.newFolder());
     cobolLanguage = new AbstractLanguage("cobol") {
       @Override
       public String[] getFileSuffixes() {
@@ -69,15 +74,17 @@ public class ComponentIndexerTest {
 
   @Test
   public void should_index_java_files() throws IOException {
+    Languages languages = new Languages(Java.INSTANCE);
+    ComponentIndexer indexer = createIndexer(languages);
+    DefaultModuleFileSystem fs = new DefaultModuleFileSystem(project, null, mock(FileIndexer.class), initializer, indexer);
     fs.add(newInputFile("src/main/java/foo/bar/Foo.java", "", "foo/bar/Foo.java", "java", false));
     fs.add(newInputFile("src/main/java2/foo/bar/Foo.java", "", "foo/bar/Foo.java", "java", false));
     fs.add(newInputFile("src/test/java/foo/bar/FooTest.java", "", "foo/bar/FooTest.java", "java", true));
-    Languages languages = new Languages(Java.INSTANCE);
-    ComponentIndexer indexer = createIndexer(languages);
-    indexer.execute(fs);
 
-    verify(sonarIndex).index(org.sonar.api.resources.File.create("src/main/java/foo/bar/Foo.java", "foo/bar/Foo.java", Java.INSTANCE, false));
-    verify(sonarIndex).index(org.sonar.api.resources.File.create("src/main/java2/foo/bar/Foo.java", "foo/bar/Foo.java", Java.INSTANCE, false));
+    fs.index();
+
+    verify(sonarIndex).index(org.sonar.api.resources.File.create("src/main/java/foo/bar/Foo.java", Java.INSTANCE, false));
+    verify(sonarIndex).index(org.sonar.api.resources.File.create("src/main/java2/foo/bar/Foo.java", Java.INSTANCE, false));
     verify(sonarIndex).index(argThat(new ArgumentMatcher<org.sonar.api.resources.File>() {
       @Override
       public boolean matches(Object arg0) {
@@ -95,25 +102,24 @@ public class ComponentIndexerTest {
 
   @Test
   public void should_index_cobol_files() throws IOException {
+    Languages languages = new Languages(cobolLanguage);
+    ComponentIndexer indexer = createIndexer(languages);
+    DefaultModuleFileSystem fs = new DefaultModuleFileSystem(project, null, mock(FileIndexer.class), initializer, indexer);
     fs.add(newInputFile("src/foo/bar/Foo.cbl", "", "foo/bar/Foo.cbl", "cobol", false));
     fs.add(newInputFile("src2/foo/bar/Foo.cbl", "", "foo/bar/Foo.cbl", "cobol", false));
     fs.add(newInputFile("src/test/foo/bar/FooTest.cbl", "", "foo/bar/FooTest.cbl", "cobol", true));
 
-    Languages languages = new Languages(cobolLanguage);
-    ComponentIndexer indexer = createIndexer(languages);
-    indexer.execute(fs);
+    fs.index();
 
-    verify(sonarIndex).index(org.sonar.api.resources.File.create("/src/foo/bar/Foo.cbl", "foo/bar/Foo.cbl", cobolLanguage, false));
-    verify(sonarIndex).index(org.sonar.api.resources.File.create("/src2/foo/bar/Foo.cbl", "foo/bar/Foo.cbl", cobolLanguage, false));
-    verify(sonarIndex).index(org.sonar.api.resources.File.create("/src/test/foo/bar/FooTest.cbl", "foo/bar/FooTest.cbl", cobolLanguage, true));
+    verify(sonarIndex).index(org.sonar.api.resources.File.create("/src/foo/bar/Foo.cbl", cobolLanguage, false));
+    verify(sonarIndex).index(org.sonar.api.resources.File.create("/src2/foo/bar/Foo.cbl", cobolLanguage, false));
+    verify(sonarIndex).index(org.sonar.api.resources.File.create("/src/test/foo/bar/FooTest.cbl", cobolLanguage, true));
   }
 
   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);
     return new DeprecatedDefaultInputFile("foo", path)
-      .setPathRelativeToSourceDir(sourceRelativePath)
-      .setFile(file)
       .setLanguage(languageKey)
       .setType(unitTest ? InputFile.Type.TEST : InputFile.Type.MAIN);
   }
index 12be04385306ec761b4e88a2cfe1db1bb1433d74..7f954c405a2faaa0bb522283b05d0bc5ced11124 100644 (file)
@@ -135,9 +135,9 @@ public class DefaultModuleFileSystemTest {
     DefaultModuleFileSystem fs = new DefaultModuleFileSystem(moduleInputFileCache,
       new Project("foo"), settings, fileIndexer, initializer, componentIndexer);
 
-    File mainFile = temp.newFile();
-    InputFile mainInput = new DeprecatedDefaultInputFile("foo", "Main.java").setFile(mainFile).setType(InputFile.Type.MAIN);
-    InputFile testInput = new DeprecatedDefaultInputFile("foo", "Test.java").setFile(temp.newFile()).setType(InputFile.Type.TEST);
+    File baseDir = temp.newFile();
+    InputFile mainInput = new DeprecatedDefaultInputFile("foo", "Main.java").setModuleBaseDir(baseDir.toPath()).setType(InputFile.Type.MAIN);
+    InputFile testInput = new DeprecatedDefaultInputFile("foo", "Test.java").setModuleBaseDir(baseDir.toPath()).setType(InputFile.Type.TEST);
     when(moduleInputFileCache.inputFiles()).thenReturn(Lists.newArrayList(mainInput, testInput));
 
     fs.index();
@@ -145,7 +145,7 @@ public class DefaultModuleFileSystemTest {
     assertThat(inputFiles).containsOnly(mainInput);
 
     Iterable<File> files = fs.files(fs.predicates().hasType(InputFile.Type.MAIN));
-    assertThat(files).containsOnly(mainFile);
+    assertThat(files).containsOnly(new File(baseDir, "Main.java"));
   }
 
   @Test
index 4066080360ba5b5871721ab45a43c163518f869e..3235301f031251105ccf13c314bb1ced6ce805a3 100644 (file)
@@ -49,7 +49,7 @@ public class DeprecatedFileFiltersTest {
   public void no_filters() throws Exception {
     DeprecatedFileFilters filters = new DeprecatedFileFilters();
 
-    InputFile inputFile = new DeprecatedDefaultInputFile("foo", "src/main/java/Foo.java").setFile(temp.newFile());
+    InputFile inputFile = new DeprecatedDefaultInputFile("foo", "src/main/java/Foo.java");
     assertThat(filters.accept(inputFile)).isTrue();
   }
 
@@ -58,11 +58,9 @@ public class DeprecatedFileFiltersTest {
     DeprecatedFileFilters filters = new DeprecatedFileFilters(new FileSystemFilter[] {filter});
 
     File basedir = temp.newFolder();
-    File file = temp.newFile();
+    File file = new File(basedir, "src/main/java/Foo.java");
     InputFile inputFile = new DeprecatedDefaultInputFile("foo", "src/main/java/Foo.java")
-      .setSourceDirAbsolutePath(new File(basedir, "src/main/java").getAbsolutePath())
-      .setPathRelativeToSourceDir("Foo.java")
-      .setFile(file)
+      .setModuleBaseDir(basedir.toPath())
       .setType(InputFile.Type.MAIN);
     when(filter.accept(eq(file), any(DeprecatedFileFilters.DeprecatedContext.class))).thenReturn(false);
 
@@ -73,8 +71,7 @@ public class DeprecatedFileFiltersTest {
 
     DeprecatedFileFilters.DeprecatedContext context = argument.getValue();
     assertThat(context.canonicalPath()).isEqualTo(FilenameUtils.separatorsToUnix(file.getAbsolutePath()));
-    assertThat(context.relativeDir()).isEqualTo(new File(basedir, "src/main/java"));
-    assertThat(context.relativePath()).isEqualTo("Foo.java");
+    assertThat(context.relativePath()).isEqualTo("src/main/java/Foo.java");
     assertThat(context.type()).isEqualTo(FileType.MAIN);
   }
 }
index 02478075c9c4e6bd3486ddfcbb148c50cb81e59e..c5bd36cddf5a9f95b331b08d8698f79b2929301e 100644 (file)
@@ -28,6 +28,7 @@ import org.sonar.api.batch.fs.internal.DefaultInputFile;
 import org.sonar.api.config.Settings;
 import org.sonar.api.scan.filesystem.FileExclusions;
 
+import java.io.File;
 import java.io.IOException;
 
 import static org.assertj.core.api.Assertions.assertThat;
@@ -43,7 +44,7 @@ public class ExclusionFiltersTest {
     filter.prepare();
 
     java.io.File file = temp.newFile();
-    DefaultInputFile inputFile = new DefaultInputFile("foo", "src/main/java/com/mycompany/FooDao.java").setFile(file);
+    DefaultInputFile inputFile = new DefaultInputFile("foo", "src/main/java/com/mycompany/FooDao.java").setModuleBaseDir(temp.newFolder().toPath());
     assertThat(filter.accept(inputFile, InputFile.Type.MAIN)).isTrue();
     assertThat(filter.accept(inputFile, InputFile.Type.TEST)).isTrue();
   }
@@ -56,10 +57,10 @@ public class ExclusionFiltersTest {
     filter.prepare();
 
     java.io.File file = temp.newFile();
-    DefaultInputFile inputFile = new DefaultInputFile("foo", "src/main/java/com/mycompany/FooDao.java").setFile(file);
+    DefaultInputFile inputFile = new DefaultInputFile("foo", "src/main/java/com/mycompany/FooDao.java").setModuleBaseDir(temp.newFolder().toPath());
     assertThat(filter.accept(inputFile, InputFile.Type.MAIN)).isTrue();
 
-    inputFile = new DefaultInputFile("foo", "src/main/java/com/mycompany/Foo.java").setFile(file);
+    inputFile = new DefaultInputFile("foo", "src/main/java/com/mycompany/Foo.java").setModuleBaseDir(temp.newFolder().toPath());
     assertThat(filter.accept(inputFile, InputFile.Type.MAIN)).isFalse();
   }
 
@@ -73,10 +74,10 @@ public class ExclusionFiltersTest {
 
     java.io.File file = temp.newFile();
 
-    DefaultInputFile inputFile = new DefaultInputFile("foo", "src/main/java/com/mycompany/Foo.java").setFile(file);
+    DefaultInputFile inputFile = new DefaultInputFile("foo", "src/main/java/com/mycompany/Foo.java").setModuleBaseDir(temp.newFolder().toPath());
     assertThat(filter.accept(inputFile, InputFile.Type.MAIN)).isFalse();
 
-    inputFile = new DefaultInputFile("foo", "src/main/java/com/mycompany/FooDto.java").setFile(file);
+    inputFile = new DefaultInputFile("foo", "src/main/java/com/mycompany/FooDto.java").setModuleBaseDir(temp.newFolder().toPath());
     assertThat(filter.accept(inputFile, InputFile.Type.MAIN)).isTrue();
   }
 
@@ -91,21 +92,21 @@ public class ExclusionFiltersTest {
     filter.prepare();
 
     java.io.File file = temp.newFile();
-    DefaultInputFile inputFile = new DefaultInputFile("foo", "src/main/java/com/mycompany/FooDao.java").setFile(file);
+    DefaultInputFile inputFile = new DefaultInputFile("foo", "src/main/java/com/mycompany/FooDao.java").setModuleBaseDir(temp.newFolder().toPath());
     assertThat(filter.accept(inputFile, InputFile.Type.MAIN)).isFalse();
 
-    inputFile = new DefaultInputFile("foo", "src/main/java/com/mycompany/Foo.java").setFile(file);
+    inputFile = new DefaultInputFile("foo", "src/main/java/com/mycompany/Foo.java").setModuleBaseDir(temp.newFolder().toPath());
     assertThat(filter.accept(inputFile, InputFile.Type.MAIN)).isTrue();
 
     // source exclusions do not apply to tests
-    inputFile = new DefaultInputFile("foo", "src/test/java/com/mycompany/FooDao.java").setFile(file);
+    inputFile = new DefaultInputFile("foo", "src/test/java/com/mycompany/FooDao.java").setModuleBaseDir(temp.newFolder().toPath());
     assertThat(filter.accept(inputFile, InputFile.Type.TEST)).isTrue();
   }
 
   @Test
   public void match_exclusion_by_absolute_path() throws IOException {
-    java.io.File includedFile = temp.newFile("Foo.java");
-    java.io.File excludedFile = temp.newFile("Bar.java");
+    File baseDir = temp.newFile();
+    File excludedFile = new File(baseDir, "src/main/java/org/bar/Bar.java");
 
     Settings settings = new Settings();
     settings.setProperty(CoreProperties.PROJECT_INCLUSIONS_PROPERTY, "src/main/java/**/*");
@@ -114,10 +115,10 @@ public class ExclusionFiltersTest {
 
     filter.prepare();
 
-    DefaultInputFile inputFile = new DefaultInputFile("foo", "src/main/java/org/bar/Foo.java").setFile(includedFile);
+    DefaultInputFile inputFile = new DefaultInputFile("foo", "src/main/java/org/bar/Foo.java").setModuleBaseDir(baseDir.toPath());
     assertThat(filter.accept(inputFile, InputFile.Type.MAIN)).isTrue();
 
-    inputFile = new DefaultInputFile("foo", "src/main/java/org/bar/Bar.java").setFile(excludedFile);
+    inputFile = new DefaultInputFile("foo", "src/main/java/org/bar/Bar.java").setModuleBaseDir(baseDir.toPath());
     assertThat(filter.accept(inputFile, InputFile.Type.MAIN)).isFalse();
   }
 
index cbfcb03242bce927e64fb64062dcfdecdcaf9070..b34c5d502717c0502240c5ffb39b48f3d47703cf 100644 (file)
@@ -25,12 +25,13 @@ import org.junit.Rule;
 import org.junit.Test;
 import org.junit.rules.ExpectedException;
 import org.junit.rules.TemporaryFolder;
+import org.sonar.api.batch.AnalysisMode;
 
 import java.io.File;
 
-import static org.apache.commons.codec.digest.DigestUtils.md5;
 import static org.apache.commons.codec.digest.DigestUtils.md5Hex;
 import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
 
 public class FileMetadataTest {
 
@@ -40,17 +41,18 @@ public class FileMetadataTest {
   @Rule
   public TemporaryFolder temp = new TemporaryFolder();
 
+  private AnalysisMode mode = mock(AnalysisMode.class);
+
   @Test
   public void empty_file() throws Exception {
     File tempFile = temp.newFile();
     FileUtils.touch(tempFile);
 
-    FileMetadata.Metadata metadata = new FileMetadata().read(tempFile, Charsets.UTF_8);
+    FileMetadata.Metadata metadata = new FileMetadata(mode).read(tempFile, Charsets.UTF_8);
     assertThat(metadata.lines).isEqualTo(1);
     assertThat(metadata.nonBlankLines).isEqualTo(0);
     assertThat(metadata.hash).isNotEmpty();
     assertThat(metadata.originalLineOffsets).containsOnly(0);
-    assertThat(metadata.lineHashes[0]).isNull();
     assertThat(metadata.empty).isTrue();
   }
 
@@ -59,14 +61,11 @@ public class FileMetadataTest {
     File tempFile = temp.newFile();
     FileUtils.write(tempFile, "foo\r\nbar\r\nbaz", Charsets.UTF_8, true);
 
-    FileMetadata.Metadata metadata = new FileMetadata().read(tempFile, Charsets.UTF_8);
+    FileMetadata.Metadata metadata = new FileMetadata(mode).read(tempFile, Charsets.UTF_8);
     assertThat(metadata.lines).isEqualTo(3);
     assertThat(metadata.nonBlankLines).isEqualTo(3);
     assertThat(metadata.hash).isEqualTo(md5Hex("foo\nbar\nbaz"));
     assertThat(metadata.originalLineOffsets).containsOnly(0, 5, 10);
-    assertThat(metadata.lineHashes[0]).containsOnly(md5("foo"));
-    assertThat(metadata.lineHashes[1]).containsOnly(md5("bar"));
-    assertThat(metadata.lineHashes[2]).containsOnly(md5("baz"));
     assertThat(metadata.empty).isFalse();
   }
 
@@ -75,15 +74,11 @@ public class FileMetadataTest {
     File tempFile = temp.newFile();
     FileUtils.write(tempFile, "föo\r\nbàr\r\n\u1D11Ebaßz\r\n", Charsets.UTF_8, true);
 
-    FileMetadata.Metadata metadata = new FileMetadata().read(tempFile, Charsets.UTF_8);
+    FileMetadata.Metadata metadata = new FileMetadata(mode).read(tempFile, Charsets.UTF_8);
     assertThat(metadata.lines).isEqualTo(4);
     assertThat(metadata.nonBlankLines).isEqualTo(3);
     assertThat(metadata.hash).isEqualTo(md5Hex("föo\nbàr\n\u1D11Ebaßz\n"));
     assertThat(metadata.originalLineOffsets).containsOnly(0, 5, 10, 18);
-    assertThat(metadata.lineHashes[0]).containsExactly(md5("föo"));
-    assertThat(metadata.lineHashes[1]).containsExactly(md5("bàr"));
-    assertThat(metadata.lineHashes[2]).containsExactly(md5("\u1D11Ebaßz"));
-    assertThat(metadata.lineHashes[3]).isNull();
   }
 
   @Test
@@ -91,15 +86,11 @@ public class FileMetadataTest {
     File tempFile = temp.newFile();
     FileUtils.write(tempFile, "föo\r\nbàr\r\n\u1D11Ebaßz\r\n", Charsets.UTF_16, true);
 
-    FileMetadata.Metadata metadata = new FileMetadata().read(tempFile, Charsets.UTF_16);
+    FileMetadata.Metadata metadata = new FileMetadata(mode).read(tempFile, Charsets.UTF_16);
     assertThat(metadata.lines).isEqualTo(4);
     assertThat(metadata.nonBlankLines).isEqualTo(3);
     assertThat(metadata.hash).isEqualTo(md5Hex("föo\nbàr\n\u1D11Ebaßz\n"));
     assertThat(metadata.originalLineOffsets).containsOnly(0, 5, 10, 18);
-    assertThat(metadata.lineHashes[0]).containsExactly(md5("föo"));
-    assertThat(metadata.lineHashes[1]).containsExactly(md5("bàr"));
-    assertThat(metadata.lineHashes[2]).containsExactly(md5("\u1D11Ebaßz"));
-    assertThat(metadata.lineHashes[3]).isNull();
   }
 
   @Test
@@ -107,14 +98,11 @@ public class FileMetadataTest {
     File tempFile = temp.newFile();
     FileUtils.write(tempFile, "foo\nbar\nbaz", Charsets.UTF_8, true);
 
-    FileMetadata.Metadata metadata = new FileMetadata().read(tempFile, Charsets.UTF_8);
+    FileMetadata.Metadata metadata = new FileMetadata(mode).read(tempFile, Charsets.UTF_8);
     assertThat(metadata.lines).isEqualTo(3);
     assertThat(metadata.nonBlankLines).isEqualTo(3);
     assertThat(metadata.hash).isEqualTo(md5Hex("foo\nbar\nbaz"));
     assertThat(metadata.originalLineOffsets).containsOnly(0, 4, 8);
-    assertThat(metadata.lineHashes[0]).containsOnly(md5("foo"));
-    assertThat(metadata.lineHashes[1]).containsOnly(md5("bar"));
-    assertThat(metadata.lineHashes[2]).containsOnly(md5("baz"));
   }
 
   @Test
@@ -122,15 +110,11 @@ public class FileMetadataTest {
     File tempFile = temp.newFile();
     FileUtils.write(tempFile, "foo\nbar\nbaz\n", Charsets.UTF_8, true);
 
-    FileMetadata.Metadata metadata = new FileMetadata().read(tempFile, Charsets.UTF_8);
+    FileMetadata.Metadata metadata = new FileMetadata(mode).read(tempFile, Charsets.UTF_8);
     assertThat(metadata.lines).isEqualTo(4);
     assertThat(metadata.nonBlankLines).isEqualTo(3);
     assertThat(metadata.hash).isEqualTo(md5Hex("foo\nbar\nbaz\n"));
     assertThat(metadata.originalLineOffsets).containsOnly(0, 4, 8, 12);
-    assertThat(metadata.lineHashes[0]).containsOnly(md5("foo"));
-    assertThat(metadata.lineHashes[1]).containsOnly(md5("bar"));
-    assertThat(metadata.lineHashes[2]).containsOnly(md5("baz"));
-    assertThat(metadata.lineHashes[3]).isNull();
   }
 
   @Test
@@ -138,15 +122,11 @@ public class FileMetadataTest {
     File tempFile = temp.newFile();
     FileUtils.write(tempFile, "foo\nbar\r\nbaz\n", Charsets.UTF_8, true);
 
-    FileMetadata.Metadata metadata = new FileMetadata().read(tempFile, Charsets.UTF_8);
+    FileMetadata.Metadata metadata = new FileMetadata(mode).read(tempFile, Charsets.UTF_8);
     assertThat(metadata.lines).isEqualTo(4);
     assertThat(metadata.nonBlankLines).isEqualTo(3);
     assertThat(metadata.hash).isEqualTo(md5Hex("foo\nbar\nbaz\n"));
     assertThat(metadata.originalLineOffsets).containsOnly(0, 4, 9, 13);
-    assertThat(metadata.lineHashes[0]).containsOnly(md5("foo"));
-    assertThat(metadata.lineHashes[1]).containsOnly(md5("bar"));
-    assertThat(metadata.lineHashes[2]).containsOnly(md5("baz"));
-    assertThat(metadata.lineHashes[3]).isNull();
   }
 
   @Test
@@ -154,15 +134,11 @@ public class FileMetadataTest {
     File tempFile = temp.newFile();
     FileUtils.write(tempFile, "foo\n\n\nbar", Charsets.UTF_8, true);
 
-    FileMetadata.Metadata metadata = new FileMetadata().read(tempFile, Charsets.UTF_8);
+    FileMetadata.Metadata metadata = new FileMetadata(mode).read(tempFile, Charsets.UTF_8);
     assertThat(metadata.lines).isEqualTo(4);
     assertThat(metadata.nonBlankLines).isEqualTo(2);
     assertThat(metadata.hash).isEqualTo(md5Hex("foo\n\n\nbar"));
     assertThat(metadata.originalLineOffsets).containsOnly(0, 4, 5, 6);
-    assertThat(metadata.lineHashes[0]).containsOnly(md5("foo"));
-    assertThat(metadata.lineHashes[1]).isNull();
-    assertThat(metadata.lineHashes[2]).isNull();
-    assertThat(metadata.lineHashes[3]).containsOnly(md5("bar"));
   }
 
   @Test
@@ -170,14 +146,11 @@ public class FileMetadataTest {
     File tempFile = temp.newFile();
     FileUtils.write(tempFile, "foo\nbar\r\nbaz", Charsets.UTF_8, true);
 
-    FileMetadata.Metadata metadata = new FileMetadata().read(tempFile, Charsets.UTF_8);
+    FileMetadata.Metadata metadata = new FileMetadata(mode).read(tempFile, Charsets.UTF_8);
     assertThat(metadata.lines).isEqualTo(3);
     assertThat(metadata.nonBlankLines).isEqualTo(3);
     assertThat(metadata.hash).isEqualTo(md5Hex("foo\nbar\nbaz"));
     assertThat(metadata.originalLineOffsets).containsOnly(0, 4, 9);
-    assertThat(metadata.lineHashes[0]).containsOnly(md5("foo"));
-    assertThat(metadata.lineHashes[1]).containsOnly(md5("bar"));
-    assertThat(metadata.lineHashes[2]).containsOnly(md5("baz"));
   }
 
   @Test
@@ -185,15 +158,11 @@ public class FileMetadataTest {
     File tempFile = temp.newFile();
     FileUtils.write(tempFile, "\nfoo\nbar\r\nbaz", Charsets.UTF_8, true);
 
-    FileMetadata.Metadata metadata = new FileMetadata().read(tempFile, Charsets.UTF_8);
+    FileMetadata.Metadata metadata = new FileMetadata(mode).read(tempFile, Charsets.UTF_8);
     assertThat(metadata.lines).isEqualTo(4);
     assertThat(metadata.nonBlankLines).isEqualTo(3);
     assertThat(metadata.hash).isEqualTo(md5Hex("\nfoo\nbar\nbaz"));
     assertThat(metadata.originalLineOffsets).containsOnly(0, 1, 5, 10);
-    assertThat(metadata.lineHashes[0]).isNull();
-    assertThat(metadata.lineHashes[1]).containsOnly(md5("foo"));
-    assertThat(metadata.lineHashes[2]).containsOnly(md5("bar"));
-    assertThat(metadata.lineHashes[3]).containsOnly(md5("baz"));
   }
 
   @Test
@@ -201,14 +170,11 @@ public class FileMetadataTest {
     File tempFile = temp.newFile();
     FileUtils.write(tempFile, "\uFEFFfoo\nbar\r\nbaz", Charsets.UTF_8, true);
 
-    FileMetadata.Metadata metadata = new FileMetadata().read(tempFile, Charsets.UTF_8);
+    FileMetadata.Metadata metadata = new FileMetadata(mode).read(tempFile, Charsets.UTF_8);
     assertThat(metadata.lines).isEqualTo(3);
     assertThat(metadata.nonBlankLines).isEqualTo(3);
     assertThat(metadata.hash).isEqualTo(md5Hex("foo\nbar\nbaz"));
     assertThat(metadata.originalLineOffsets).containsOnly(0, 4, 9);
-    assertThat(metadata.lineHashes[0]).containsOnly(md5("foo"));
-    assertThat(metadata.lineHashes[1]).containsOnly(md5("bar"));
-    assertThat(metadata.lineHashes[2]).containsOnly(md5("baz"));
   }
 
   @Test
@@ -216,13 +182,10 @@ public class FileMetadataTest {
     File tempFile = temp.newFile();
     FileUtils.write(tempFile, " foo\nb ar\r\nbaz \t", Charsets.UTF_8, true);
 
-    FileMetadata.Metadata metadata = new FileMetadata().read(tempFile, Charsets.UTF_8);
+    FileMetadata.Metadata metadata = new FileMetadata(mode).read(tempFile, Charsets.UTF_8);
     assertThat(metadata.lines).isEqualTo(3);
     assertThat(metadata.nonBlankLines).isEqualTo(3);
     assertThat(metadata.hash).isEqualTo(md5Hex(" foo\nb ar\nbaz \t"));
-    assertThat(metadata.lineHashes[0]).containsOnly(md5("foo"));
-    assertThat(metadata.lineHashes[1]).containsOnly(md5("bar"));
-    assertThat(metadata.lineHashes[2]).containsOnly(md5("baz"));
   }
 
   @Test
@@ -233,7 +196,7 @@ public class FileMetadataTest {
     thrown.expect(IllegalStateException.class);
     thrown.expectMessage("Fail to read file '" + file.getAbsolutePath() + "' with encoding 'UTF-8'");
 
-    new FileMetadata().read(file, Charsets.UTF_8);
+    new FileMetadata(mode).read(file, Charsets.UTF_8);
   }
 
   @Test
@@ -248,9 +211,9 @@ public class FileMetadataTest {
     File file2 = temp.newFile();
     FileUtils.write(file2, "foo\nbar", Charsets.UTF_8, true);
 
-    String hash1 = new FileMetadata().read(file1, Charsets.UTF_8).hash;
-    String hash1a = new FileMetadata().read(file1a, Charsets.UTF_8).hash;
-    String hash2 = new FileMetadata().read(file2, Charsets.UTF_8).hash;
+    String hash1 = new FileMetadata(mode).read(file1, Charsets.UTF_8).hash;
+    String hash1a = new FileMetadata(mode).read(file1a, Charsets.UTF_8).hash;
+    String hash2 = new FileMetadata(mode).read(file2, Charsets.UTF_8).hash;
     assertThat(hash1).isEqualTo(hash1a);
     assertThat(hash1).isNotEqualTo(hash2);
   }
index e702dbbfa81ff0141e7ce332fc0e39c5a91f2cb3..2b5b1f4bcca6fcec0a1c7efaabfb4de3733a414b 100644 (file)
@@ -39,7 +39,7 @@ public class InputFileBuilderFactoryTest {
     DefaultAnalysisMode analysisMode = mock(DefaultAnalysisMode.class);
 
     InputFileBuilderFactory factory = new InputFileBuilderFactory(ProjectDefinition.create().setKey("struts"), pathResolver, langDetectionFactory,
-      statusDetectionFactory, analysisMode, new Settings());
+      statusDetectionFactory, analysisMode, new Settings(), new FileMetadata(analysisMode));
     InputFileBuilder builder = factory.create(fs);
 
     assertThat(builder.langDetection()).isNotNull();
index 36682184b37999411f042289965d801a7e0f1945..df058f13c8f0f38c21733cfa4d361436135d2499 100644 (file)
@@ -32,7 +32,6 @@ import org.sonar.api.utils.PathUtils;
 import org.sonar.batch.bootstrap.DefaultAnalysisMode;
 
 import java.io.File;
-import java.util.Arrays;
 
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.mockito.Matchers.any;
@@ -67,9 +66,9 @@ public class InputFileBuilderTest {
       .thenReturn(InputFile.Status.ADDED);
 
     InputFileBuilder builder = new InputFileBuilder("struts", new PathResolver(),
-      langDetection, statusDetection, fs, analysisMode, new Settings());
+      langDetection, statusDetection, fs, analysisMode, new Settings(), new FileMetadata(analysisMode));
     DeprecatedDefaultInputFile inputFile = builder.create(srcFile);
-    inputFile = builder.complete(inputFile, InputFile.Type.MAIN);
+    builder.completeAndComputeMetadata(inputFile, InputFile.Type.MAIN);
 
     assertThat(inputFile.type()).isEqualTo(InputFile.Type.MAIN);
     assertThat(inputFile.file()).isEqualTo(srcFile.getAbsoluteFile());
@@ -78,9 +77,6 @@ public class InputFileBuilderTest {
     assertThat(inputFile.key()).isEqualTo("struts:src/main/java/foo/Bar.java");
     assertThat(inputFile.relativePath()).isEqualTo("src/main/java/foo/Bar.java");
     assertThat(inputFile.lines()).isEqualTo(1);
-    assertThat(inputFile.sourceDirAbsolutePath()).isNull();
-    assertThat(inputFile.pathRelativeToSourceDir()).isNull();
-    assertThat(inputFile.deprecatedKey()).isNull();
   }
 
   @Test
@@ -93,7 +89,7 @@ public class InputFileBuilderTest {
     when(fs.baseDir()).thenReturn(basedir);
 
     InputFileBuilder builder = new InputFileBuilder("struts", new PathResolver(),
-      langDetection, statusDetection, fs, analysisMode, new Settings());
+      langDetection, statusDetection, fs, analysisMode, new Settings(), new FileMetadata(analysisMode));
     DeprecatedDefaultInputFile inputFile = builder.create(srcFile);
 
     assertThat(inputFile).isNull();
@@ -113,69 +109,11 @@ public class InputFileBuilderTest {
     when(langDetection.language(any(InputFile.class))).thenReturn(null);
 
     InputFileBuilder builder = new InputFileBuilder("struts", new PathResolver(),
-      langDetection, statusDetection, fs, analysisMode, new Settings());
+      langDetection, statusDetection, fs, analysisMode, new Settings(), new FileMetadata(analysisMode));
     DeprecatedDefaultInputFile inputFile = builder.create(srcFile);
-    inputFile = builder.complete(inputFile, InputFile.Type.MAIN);
+    InputFileMetadata metadata = builder.completeAndComputeMetadata(inputFile, InputFile.Type.MAIN);
 
-    assertThat(inputFile).isNull();
-  }
-
-  @Test
-  public void fill_deprecated_data_of_java_file() throws Exception {
-    // file system
-    File basedir = temp.newFolder();
-    File srcFile = new File(basedir, "src/main/java/foo/Bar.java");
-    FileUtils.touch(srcFile);
-    FileUtils.write(srcFile, "single line");
-    when(fs.baseDir()).thenReturn(basedir);
-    when(fs.encoding()).thenReturn(Charsets.UTF_8);
-    File sourceDir = new File(basedir, "src/main/java");
-    when(fs.sourceDirs()).thenReturn(Arrays.asList(sourceDir));
-
-    // lang
-    when(langDetection.language(any(InputFile.class))).thenReturn("java");
-
-    // status
-    when(statusDetection.status("foo", "src/main/java/foo/Bar.java", "6c1d64c0b3555892fe7273e954f6fb5a"))
-      .thenReturn(InputFile.Status.ADDED);
-
-    InputFileBuilder builder = new InputFileBuilder("struts", new PathResolver(),
-      langDetection, statusDetection, fs, analysisMode, new Settings());
-    DeprecatedDefaultInputFile inputFile = builder.create(srcFile);
-    inputFile = builder.complete(inputFile, InputFile.Type.MAIN);
-
-    assertThat(inputFile.pathRelativeToSourceDir()).isEqualTo("foo/Bar.java");
-    assertThat(inputFile.sourceDirAbsolutePath()).isEqualTo(PathUtils.sanitize(sourceDir.getAbsolutePath()));
-    assertThat(inputFile.deprecatedKey()).isEqualTo("struts:foo.Bar");
+    assertThat(metadata).isNull();
   }
 
-  @Test
-  public void fill_deprecated_data_of_non_java_file() throws Exception {
-    // file system
-    File basedir = temp.newFolder();
-    File srcFile = new File(basedir, "src/foo/Bar.php");
-    FileUtils.touch(srcFile);
-    FileUtils.write(srcFile, "single line");
-    when(fs.baseDir()).thenReturn(basedir);
-    when(fs.encoding()).thenReturn(Charsets.UTF_8);
-    File sourceDir = new File(basedir, "src");
-    when(fs.sourceDirs()).thenReturn(Arrays.asList(sourceDir));
-
-    // lang
-    when(langDetection.language(any(InputFile.class))).thenReturn("php");
-
-    // status
-    when(statusDetection.status("foo", "src/Bar.php", "6c1d64c0b3555892fe7273e954f6fb5a"))
-      .thenReturn(InputFile.Status.ADDED);
-
-    InputFileBuilder builder = new InputFileBuilder("struts", new PathResolver(),
-      langDetection, statusDetection, fs, analysisMode, new Settings());
-    DeprecatedDefaultInputFile inputFile = builder.create(srcFile);
-    inputFile = builder.complete(inputFile, InputFile.Type.MAIN);
-
-    assertThat(inputFile.pathRelativeToSourceDir()).isEqualTo("foo/Bar.php");
-    assertThat(inputFile.sourceDirAbsolutePath()).isEqualTo(PathUtils.sanitize(sourceDir.getAbsolutePath()));
-    assertThat(inputFile.deprecatedKey()).isEqualTo("struts:foo/Bar.php");
-
-  }
 }
index 1a38d6e998ce38a0a9bf937e770400f3293e1bea..7c943e06f66ff4dc9971e98ed0378b0ee1f59f7a 100644 (file)
@@ -19,7 +19,7 @@
  */
 package org.sonar.batch.scan.filesystem;
 
-import org.apache.commons.codec.digest.DigestUtils;
+import com.google.common.base.Charsets;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Rule;
@@ -30,8 +30,6 @@ import org.sonar.api.batch.fs.InputFile.Type;
 import org.sonar.api.batch.fs.InputPath;
 import org.sonar.api.batch.fs.internal.DefaultInputFile;
 import org.sonar.api.batch.fs.internal.DeprecatedDefaultInputFile;
-import org.sonar.batch.index.Caches;
-import org.sonar.batch.index.CachesTest;
 
 import static org.assertj.core.api.Assertions.assertThat;
 
@@ -40,59 +38,61 @@ public class InputPathCacheTest {
   @Rule
   public TemporaryFolder temp = new TemporaryFolder();
 
-  Caches caches;
-
   @Before
   public void start() throws Exception {
-    caches = CachesTest.createCacheOnTemp(temp);
-    caches.start();
   }
 
   @After
   public void stop() {
-    caches.stop();
   }
 
   @Test
   public void should_add_input_file() throws Exception {
-    InputPathCache cache = new InputPathCache(caches);
-    DefaultInputFile fooFile = new DefaultInputFile("foo", "src/main/java/Foo.java").setFile(temp.newFile("Foo.java"));
+    InputPathCache cache = new InputPathCache();
+    DefaultInputFile fooFile = new DefaultInputFile("foo", "src/main/java/Foo.java").setModuleBaseDir(temp.newFolder().toPath());
     cache.put("struts", fooFile);
     cache.put("struts-core", new DeprecatedDefaultInputFile("foo", "src/main/java/Bar.java")
-      .setBasedir(temp.newFolder())
-      .setDeprecatedKey("foo")
-      .setSourceDirAbsolutePath("foo")
-      .setPathRelativeToSourceDir("foo")
       .setLanguage("bla")
       .setType(Type.MAIN)
       .setStatus(Status.ADDED)
-      .setHash("xyz")
       .setLines(2)
-      .setEncoding("UTF-8")
-      .setOriginalLineOffsets(new long[] {0, 4})
-      .setLineHashes(new byte[][] {DigestUtils.md5("foo"), DigestUtils.md5("bar")})
-      .setFile(temp.newFile("Bar.java")));
+      .setCharset(Charsets.UTF_8)
+      .setModuleBaseDir(temp.newFolder().toPath()));
 
     DefaultInputFile loadedFile = (DefaultInputFile) cache.getFile("struts-core", "src/main/java/Bar.java");
     assertThat(loadedFile.relativePath()).isEqualTo("src/main/java/Bar.java");
-    assertThat(loadedFile.encoding()).isEqualTo("UTF-8");
-    assertThat(loadedFile.originalLineOffsets()).containsOnly(0, 4);
-    assertThat(loadedFile.lineHashes()[0]).containsOnly(DigestUtils.md5("foo"));
-    assertThat(loadedFile.lineHashes()[1]).containsOnly(DigestUtils.md5("bar"));
+    assertThat(loadedFile.charset()).isEqualTo(Charsets.UTF_8);
 
     assertThat(cache.filesByModule("struts")).hasSize(1);
     assertThat(cache.filesByModule("struts-core")).hasSize(1);
-    assertThat(cache.all()).hasSize(2);
-    for (InputPath inputPath : cache.all()) {
+    assertThat(cache.allFiles()).hasSize(2);
+    for (InputPath inputPath : cache.allFiles()) {
       assertThat(inputPath.relativePath()).startsWith("src/main/java/");
     }
 
     cache.remove("struts", fooFile);
-    assertThat(cache.all()).hasSize(1);
+    assertThat(cache.allFiles()).hasSize(1);
 
     cache.removeModule("struts");
     assertThat(cache.filesByModule("struts")).hasSize(0);
     assertThat(cache.filesByModule("struts-core")).hasSize(1);
-    assertThat(cache.all()).hasSize(1);
+    assertThat(cache.allFiles()).hasSize(1);
+  }
+
+  @Test
+  public void should_add_input_file_metadata() throws Exception {
+    InputPathCache cache = new InputPathCache();
+    cache.put("struts-core", "src/main/java/Bar.java", new InputFileMetadata()
+      .setHash("xyz")
+      .setNonBlankLines(2)
+      .setEmpty(true)
+      .setOriginalLineOffsets(new int[] {0, 4}));
+
+    InputFileMetadata loadedFileMetadata = cache.getFileMetadata("struts-core", "src/main/java/Bar.java");
+    assertThat(loadedFileMetadata.originalLineOffsets()).containsOnly(0, 4);
+    assertThat(loadedFileMetadata.hash()).isEqualTo("xyz");
+    assertThat(loadedFileMetadata.nonBlankLines()).isEqualTo(2);
+    assertThat(loadedFileMetadata.isEmpty()).isTrue();
+
   }
 }
index af30dcfc7062949e146cbc2115bf6bc0e95a3959..93b4d05145a9b545af2f83fc78f04e8f284ab405 100644 (file)
  */
 package org.sonar.batch.scan.filesystem;
 
+import org.sonar.batch.repository.language.DefaultLanguagesRepository;
+import org.sonar.batch.repository.language.LanguagesRepository;
+
 import org.junit.Test;
 import org.sonar.api.config.Settings;
 import org.sonar.api.resources.Java;
 import org.sonar.api.resources.Languages;
-import org.sonar.batch.languages.DefaultLanguagesReferential;
-import org.sonar.batch.languages.LanguagesReferential;
-
 import static org.assertj.core.api.Assertions.assertThat;
 
 public class LanguageDetectionFactoryTest {
   @Test
   public void testCreate() throws Exception {
-    LanguagesReferential languages = new DefaultLanguagesReferential(new Languages(Java.INSTANCE));
+    LanguagesRepository languages = new DefaultLanguagesRepository(new Languages(Java.INSTANCE));
     LanguageDetectionFactory factory = new LanguageDetectionFactory(new Settings(), languages);
     LanguageDetection languageDetection = factory.create();
     assertThat(languageDetection).isNotNull();
index e9155fd9c8ad06c54e4f8344ec514496968bf062..95d3631eaa57faa4020d7e4243223392b1149b04 100644 (file)
@@ -30,8 +30,8 @@ import org.sonar.api.config.Settings;
 import org.sonar.api.resources.Language;
 import org.sonar.api.resources.Languages;
 import org.sonar.api.utils.MessageException;
-import org.sonar.batch.languages.DefaultLanguagesReferential;
-import org.sonar.batch.languages.LanguagesReferential;
+import org.sonar.batch.repository.language.DefaultLanguagesRepository;
+import org.sonar.batch.repository.language.LanguagesRepository;
 
 import java.io.File;
 import java.io.IOException;
@@ -58,7 +58,7 @@ public class LanguageDetectionTest {
 
   @Test
   public void search_by_file_extension() throws Exception {
-    LanguagesReferential languages = new DefaultLanguagesReferential(new Languages(new MockLanguage("java", "java", "jav"), new MockLanguage("cobol", "cbl", "cob")));
+    LanguagesRepository languages = new DefaultLanguagesRepository(new Languages(new MockLanguage("java", "java", "jav"), new MockLanguage("cobol", "cbl", "cob")));
     LanguageDetection detection = new LanguageDetection(new Settings(), languages);
 
     assertThat(detection.language(newInputFile("Foo.java"))).isEqualTo("java");
@@ -76,13 +76,13 @@ public class LanguageDetectionTest {
 
   @Test
   public void should_not_fail_if_no_language() throws Exception {
-    LanguageDetection detection = spy(new LanguageDetection(new Settings(), new DefaultLanguagesReferential(new Languages())));
+    LanguageDetection detection = spy(new LanguageDetection(new Settings(), new DefaultLanguagesRepository(new Languages())));
     assertThat(detection.language(newInputFile("Foo.java"))).isNull();
   }
 
   @Test
   public void plugin_can_declare_a_file_extension_twice_for_case_sensitivity() throws Exception {
-    LanguagesReferential languages = new DefaultLanguagesReferential(new Languages(new MockLanguage("abap", "abap", "ABAP")));
+    LanguagesRepository languages = new DefaultLanguagesRepository(new Languages(new MockLanguage("abap", "abap", "ABAP")));
 
     LanguageDetection detection = new LanguageDetection(new Settings(), languages);
     assertThat(detection.language(newInputFile("abc.abap"))).isEqualTo("abap");
@@ -92,7 +92,7 @@ public class LanguageDetectionTest {
   public void language_with_no_extension() throws Exception {
     // abap does not declare any file extensions.
     // When analyzing an ABAP project, then all source files must be parsed.
-    LanguagesReferential languages = new DefaultLanguagesReferential(new Languages(new MockLanguage("java", "java"), new MockLanguage("abap")));
+    LanguagesRepository languages = new DefaultLanguagesRepository(new Languages(new MockLanguage("java", "java"), new MockLanguage("abap")));
 
     // No side-effect on non-ABAP projects
     LanguageDetection detection = new LanguageDetection(new Settings(), languages);
@@ -110,7 +110,7 @@ public class LanguageDetectionTest {
 
   @Test
   public void force_language_using_deprecated_property() throws Exception {
-    LanguagesReferential languages = new DefaultLanguagesReferential(new Languages(new MockLanguage("java", "java"), new MockLanguage("php", "php")));
+    LanguagesRepository languages = new DefaultLanguagesRepository(new Languages(new MockLanguage("java", "java"), new MockLanguage("php", "php")));
 
     Settings settings = new Settings();
     settings.setProperty(CoreProperties.PROJECT_LANGUAGE_PROPERTY, "java");
@@ -126,7 +126,7 @@ public class LanguageDetectionTest {
     thrown.expect(MessageException.class);
     thrown.expectMessage("No language is installed with key 'unknown'. Please update property 'sonar.language'");
 
-    LanguagesReferential languages = new DefaultLanguagesReferential(new Languages(new MockLanguage("java", "java"), new MockLanguage("php", "php")));
+    LanguagesRepository languages = new DefaultLanguagesRepository(new Languages(new MockLanguage("java", "java"), new MockLanguage("php", "php")));
     Settings settings = new Settings();
     settings.setProperty(CoreProperties.PROJECT_LANGUAGE_PROPERTY, "unknown");
     new LanguageDetection(settings, languages);
@@ -134,7 +134,7 @@ public class LanguageDetectionTest {
 
   @Test
   public void fail_if_conflicting_language_suffix() throws Exception {
-    LanguagesReferential languages = new DefaultLanguagesReferential(new Languages(new MockLanguage("xml", "xhtml"), new MockLanguage("web", "xhtml")));
+    LanguagesRepository languages = new DefaultLanguagesRepository(new Languages(new MockLanguage("xml", "xhtml"), new MockLanguage("web", "xhtml")));
     LanguageDetection detection = new LanguageDetection(new Settings(), languages);
     try {
       detection.language(newInputFile("abc.xhtml"));
@@ -149,7 +149,7 @@ public class LanguageDetectionTest {
 
   @Test
   public void solve_conflict_using_filepattern() throws Exception {
-    LanguagesReferential languages = new DefaultLanguagesReferential(new Languages(new MockLanguage("xml", "xhtml"), new MockLanguage("web", "xhtml")));
+    LanguagesRepository languages = new DefaultLanguagesRepository(new Languages(new MockLanguage("xml", "xhtml"), new MockLanguage("web", "xhtml")));
 
     Settings settings = new Settings();
     settings.setProperty("sonar.lang.patterns.xml", "xml/**");
@@ -161,7 +161,7 @@ public class LanguageDetectionTest {
 
   @Test
   public void fail_if_conflicting_filepattern() throws Exception {
-    LanguagesReferential languages = new DefaultLanguagesReferential(new Languages(new MockLanguage("abap", "abap"), new MockLanguage("cobol", "cobol")));
+    LanguagesRepository languages = new DefaultLanguagesRepository(new Languages(new MockLanguage("abap", "abap"), new MockLanguage("cobol", "cobol")));
     Settings settings = new Settings();
     settings.setProperty("sonar.lang.patterns.abap", "*.abap,*.txt");
     settings.setProperty("sonar.lang.patterns.cobol", "*.cobol,*.txt");
@@ -183,7 +183,7 @@ public class LanguageDetectionTest {
 
   private InputFile newInputFile(String path) throws IOException {
     File basedir = temp.newFolder();
-    return new DefaultInputFile("foo", path).setFile(new File(basedir, path));
+    return new DefaultInputFile("foo", path).setModuleBaseDir(basedir.toPath());
   }
 
   static class MockLanguage implements Language {
index ebb97af649278f47936bb7401a6cf85929fbfb01..7aa5c49856d50cae9cad3db24586bb4612d5bb5d 100644 (file)
@@ -233,9 +233,9 @@ public class MeasureCacheTest {
   @Test
   public void should_get_measures() throws Exception {
     Project p = new Project("struts");
-    Resource dir = new Directory("foo/bar").setEffectiveKey("struts:foo/bar");
-    Resource file1 = new File("foo/bar/File1.txt").setEffectiveKey("struts:foo/bar/File1.txt");
-    Resource file2 = new File("foo/bar/File2.txt").setEffectiveKey("struts:foo/bar/File2.txt");
+    Resource dir = Directory.create("foo/bar").setEffectiveKey("struts:foo/bar");
+    Resource file1 = Directory.create("foo/bar/File1.txt").setEffectiveKey("struts:foo/bar/File1.txt");
+    Resource file2 = Directory.create("foo/bar/File2.txt").setEffectiveKey("struts:foo/bar/File2.txt");
 
     assertThat(cache.entries()).hasSize(0);
 
@@ -271,7 +271,7 @@ public class MeasureCacheTest {
 
   @Test
   public void test_measure_coder() throws Exception {
-    Resource file1 = new File("foo/bar/File1.txt").setEffectiveKey("struts:foo/bar/File1.txt");
+    Resource file1 = File.create("foo/bar/File1.txt").setEffectiveKey("struts:foo/bar/File1.txt");
 
     Measure measure = new Measure(CoreMetrics.NCLOC, 1.786, 5);
     cache.put(file1, measure);
index 786d5a7f040d3521f358db337dd3575064719b4e..1e61491a8c13f19bdcd480ef09cef98b0bc92a08 100644 (file)
@@ -27,8 +27,8 @@ import org.junit.Before;
 import org.junit.Test;
 import org.junit.rules.TemporaryFolder;
 import org.skyscreamer.jsonassert.JSONAssert;
+import org.sonar.api.batch.fs.InputDir;
 import org.sonar.api.batch.fs.InputFile;
-import org.sonar.api.batch.fs.InputPath;
 import org.sonar.api.batch.fs.internal.DefaultFileSystem;
 import org.sonar.api.batch.fs.internal.DefaultInputDir;
 import org.sonar.api.batch.fs.internal.DeprecatedDefaultInputFile;
@@ -42,9 +42,9 @@ import org.sonar.api.resources.Project;
 import org.sonar.api.resources.Resource;
 import org.sonar.api.rule.RuleKey;
 import org.sonar.batch.issue.IssueCache;
+import org.sonar.batch.repository.user.User;
+import org.sonar.batch.repository.user.UserRepository;
 import org.sonar.batch.scan.filesystem.InputPathCache;
-import org.sonar.batch.user.User;
-import org.sonar.batch.user.UserRepository;
 
 import java.io.File;
 import java.io.IOException;
@@ -77,7 +77,7 @@ public class JSONReportTest {
 
   @Before
   public void before() throws Exception {
-    fs = new DefaultFileSystem(temp.newFolder());
+    fs = new DefaultFileSystem(temp.newFolder().toPath());
     SIMPLE_DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("GMT+02:00"));
     when(resource.getEffectiveKey()).thenReturn("Action.java");
     when(server.getVersion()).thenReturn("3.6");
@@ -86,7 +86,8 @@ public class JSONReportTest {
     DeprecatedDefaultInputFile inputFile = new DeprecatedDefaultInputFile("struts", "src/main/java/org/apache/struts/Action.java");
     inputFile.setStatus(InputFile.Status.CHANGED);
     InputPathCache fileCache = mock(InputPathCache.class);
-    when(fileCache.all()).thenReturn(Arrays.<InputPath>asList(inputDir, inputFile));
+    when(fileCache.allFiles()).thenReturn(Arrays.<InputFile>asList(inputFile));
+    when(fileCache.allDirs()).thenReturn(Arrays.<InputDir>asList(inputDir));
     Project rootModule = new Project("struts");
     Project moduleA = new Project("struts-core");
     moduleA.setParent(rootModule).setPath("core");
index d0cf02f65a3f00f4c3539c1a773973779836a7e7..1850fe2b001f7b5e636ec5d2f1d824fca8357046 100644 (file)
@@ -53,7 +53,7 @@ public class AnalyzerOptimizerTest {
 
   @Before
   public void prepare() throws Exception {
-    fs = new DefaultFileSystem(temp.newFolder());
+    fs = new DefaultFileSystem(temp.newFolder().toPath());
     settings = new Settings();
     analysisMode = mock(AnalysisMode.class);
     optimizer = new AnalyzerOptimizer(fs, new ActiveRulesBuilder().build(), settings, analysisMode);
index e6d24b0643fa991ad217b6db886be9219f53caed..1812fde5cf475df123f800f4d3897c9c5ed3fedb 100644 (file)
@@ -58,7 +58,7 @@ public class DefaultSensorContextTest {
   @Before
   public void prepare() throws Exception {
     activeRules = new ActiveRulesBuilder().build();
-    fs = new DefaultFileSystem(temp.newFolder());
+    fs = new DefaultFileSystem(temp.newFolder().toPath());
     MetricFinder metricFinder = mock(MetricFinder.class);
     when(metricFinder.findByKey(CoreMetrics.NCLOC_KEY)).thenReturn(CoreMetrics.NCLOC);
     when(metricFinder.findByKey(CoreMetrics.FUNCTION_COMPLEXITY_DISTRIBUTION_KEY)).thenReturn(CoreMetrics.FUNCTION_COMPLEXITY_DISTRIBUTION);
index 658f48e41fd8668c2654b45865294b70414a8a90..506bcd328e1addc48467f03581835a667d798162 100644 (file)
@@ -84,7 +84,7 @@ public class DefaultSensorStorageTest {
   @Before
   public void prepare() throws Exception {
     activeRules = new ActiveRulesBuilder().build();
-    fs = new DefaultFileSystem(temp.newFolder());
+    fs = new DefaultFileSystem(temp.newFolder().toPath());
     MetricFinder metricFinder = mock(MetricFinder.class);
     when(metricFinder.findByKey(CoreMetrics.NCLOC_KEY)).thenReturn(CoreMetrics.NCLOC);
     when(metricFinder.findByKey(CoreMetrics.FUNCTION_COMPLEXITY_DISTRIBUTION_KEY)).thenReturn(CoreMetrics.FUNCTION_COMPLEXITY_DISTRIBUTION);
@@ -279,7 +279,7 @@ public class DefaultSensorStorageTest {
     when(sonarIndex.getEdge(foo, bar)).thenReturn(new Dependency(foo, bar));
 
     thrown.expect(IllegalStateException.class);
-    thrown.expectMessage("Dependency between [moduleKey=foo, relative=src/Foo.java, abs=null] and [moduleKey=foo, relative=src/Bar.java, abs=null] was already saved.");
+    thrown.expectMessage("Dependency between [moduleKey=foo, relative=src/Foo.java, basedir=null] and [moduleKey=foo, relative=src/Bar.java, basedir=null] was already saved.");
 
     sensorStorage.store(new DefaultDependency()
       .from(new DefaultInputFile("foo", "src/Foo.java").setType(Type.MAIN))
index ec592a7962e04ef48aaaa4dc990bab57048b5e46..0e2efc2782af00842afed8023b63d43b4895ce4f 100644 (file)
@@ -54,7 +54,7 @@ public class CoverageExclusionsTest {
 
   @Test
   public void shouldFilterFileBasedOnPattern() {
-    Resource resource = File.create("src/org/polop/File.php", "org/polop/File.php", null, false);
+    Resource resource = File.create("src/org/polop/File.php", null, false);
     Measure coverageMeasure = mock(Measure.class);
     when(coverageMeasure.getMetric()).thenReturn(CoreMetrics.LINES_TO_COVER);
 
@@ -65,7 +65,7 @@ public class CoverageExclusionsTest {
 
   @Test
   public void shouldNotFilterFileBasedOnPattern() {
-    Resource resource = File.create("src/org/polop/File.php", "org/polop/File.php", null, false);
+    Resource resource = File.create("src/org/polop/File.php", null, false);
     Measure coverageMeasure = mock(Measure.class);
     when(coverageMeasure.getMetric()).thenReturn(CoreMetrics.COVERAGE);
 
index 58f1d3f86c811cd3f96c9c7bafbc388f0466f40d..a7486ad376b0f69d523ca39a52872b83b407f06a 100644 (file)
@@ -19,6 +19,7 @@
  */
 package org.sonar.batch.source;
 
+import com.google.common.base.Charsets;
 import com.google.common.collect.ImmutableList;
 import org.apache.commons.io.FileUtils;
 import org.junit.Rule;
@@ -52,7 +53,7 @@ public class CodeColorizersTest {
 
     File jsFile = new File(this.getClass().getResource("CodeColorizersTest/Person.js").toURI());
 
-    SyntaxHighlightingData syntaxHighlighting = codeColorizers.toSyntaxHighlighting(jsFile, "UTF-8", "js");
+    SyntaxHighlightingData syntaxHighlighting = codeColorizers.toSyntaxHighlighting(jsFile, Charsets.UTF_8, "js");
 
     assertThat(syntaxHighlighting.writeString()).isEqualTo(HIGHLIGHTING_JS);
 
@@ -67,7 +68,7 @@ public class CodeColorizersTest {
     File jsFile = new File(this.getClass().getResource("CodeColorizersTest/Person.js").toURI());
     FileUtils.write(fileWithBom, FileUtils.readFileToString(jsFile), "UTF-8", true);
 
-    SyntaxHighlightingData syntaxHighlighting = codeColorizers.toSyntaxHighlighting(fileWithBom, "UTF-8", "js");
+    SyntaxHighlightingData syntaxHighlighting = codeColorizers.toSyntaxHighlighting(fileWithBom, Charsets.UTF_8, "js");
 
     assertThat(syntaxHighlighting.writeString()).isEqualTo(HIGHLIGHTING_JS);
   }
@@ -78,7 +79,7 @@ public class CodeColorizersTest {
 
     File javaFile = new File(this.getClass().getResource("CodeColorizersTest/Person.java").toURI());
 
-    SyntaxHighlightingData syntaxHighlighting = codeColorizers.toSyntaxHighlighting(javaFile, "UTF-8", "java");
+    SyntaxHighlightingData syntaxHighlighting = codeColorizers.toSyntaxHighlighting(javaFile, Charsets.UTF_8, "java");
 
     assertThat(syntaxHighlighting.writeString()).isEqualTo(HIGHLIGHTING_JAVA);
 
index 4a26c3b4bbf586392c793cb0dc4453412f38689c..e2adf2dd0db07cc7ab5e8c42d6ffa16fc053b053 100644 (file)
@@ -37,7 +37,7 @@ public class HighlightableBuilderTest {
 
   @Test
   public void should_load_default_perspective() throws Exception {
-    Resource file = new File("foo.c").setEffectiveKey("myproject:path/to/foo.c");
+    Resource file = File.create("foo.c").setEffectiveKey("myproject:path/to/foo.c");
     Component component = new ResourceComponent(file);
 
     HighlightableBuilder builder = new HighlightableBuilder(cache);
diff --git a/sonar-batch/src/test/java/org/sonar/batch/tasks/ListTaskTest.java b/sonar-batch/src/test/java/org/sonar/batch/tasks/ListTaskTest.java
deleted file mode 100644 (file)
index 923af51..0000000
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * 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.batch.tasks;
-
-import org.junit.Test;
-import org.sonar.api.task.Task;
-import org.sonar.api.task.TaskDefinition;
-
-import java.util.Arrays;
-
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-public class ListTaskTest {
-  @Test
-  public void should_list_available_tasks() {
-    Tasks tasks = mock(Tasks.class);
-    when(tasks.definitions()).thenReturn(Arrays.asList(
-      TaskDefinition.builder().key("foo").description("Foo").taskClass(FooTask.class).build(),
-      TaskDefinition.builder().key("purge").description("Purge database").taskClass(FakePurgeTask.class).build()
-    ));
-
-    ListTask task = spy(new ListTask(tasks));
-
-    task.execute();
-
-    verify(task, times(1)).log("Available tasks:");
-    verify(task, times(1)).log("  - foo: Foo");
-    verify(task, times(1)).log("  - purge: Purge database");
-  }
-
-  private static class FakePurgeTask implements Task {
-    public void execute() {
-    }
-  }
-
-  private static class FooTask implements Task {
-    public void execute() {
-    }
-  }
-}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/tasks/TasksTest.java b/sonar-batch/src/test/java/org/sonar/batch/tasks/TasksTest.java
deleted file mode 100644 (file)
index 5c43158..0000000
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * 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.batch.tasks;
-
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
-import org.sonar.api.task.Task;
-import org.sonar.api.task.TaskDefinition;
-import org.sonar.api.utils.SonarException;
-import org.sonar.batch.scan.ScanTask;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-public class TasksTest {
-
-  @Rule
-  public ExpectedException thrown = ExpectedException.none();
-
-  @Test
-  public void should_get_definitions() {
-    Tasks tasks = new Tasks(new TaskDefinition[]{ScanTask.DEFINITION, ListTask.DEFINITION});
-    assertThat(tasks.definitions()).hasSize(2);
-  }
-
-  @Test
-  public void should_get_definition_by_key() {
-    Tasks tasks = new Tasks(new TaskDefinition[]{ScanTask.DEFINITION, ListTask.DEFINITION});
-    tasks.start();
-    assertThat(tasks.definition(ListTask.DEFINITION.key())).isEqualTo(ListTask.DEFINITION);
-  }
-
-  @Test
-  public void should_return_null_if_task_not_found() {
-    Tasks tasks = new Tasks(new TaskDefinition[]{ScanTask.DEFINITION, ListTask.DEFINITION});
-
-    assertThat(tasks.definition("not-exists")).isNull();
-  }
-
-  @Test
-  public void should_fail_on_duplicated_keys() {
-    thrown.expect(SonarException.class);
-    thrown.expectMessage("Task 'foo' is declared twice");
-
-    new Tasks(new TaskDefinition[]{
-      TaskDefinition.builder().key("foo").taskClass(FakeTask1.class).description("foo1").build(),
-      TaskDefinition.builder().key("foo").taskClass(FakeTask2.class).description("foo2").build()
-    });
-  }
-
-  @Test
-  public void should_fail_on_duplicated_class() {
-    Tasks tasks = new Tasks(new TaskDefinition[]{
-      TaskDefinition.builder().key("foo1").taskClass(FakeTask1.class).description("foo1").build(),
-      TaskDefinition.builder().key("foo2").taskClass(FakeTask1.class).description("foo1").build()
-    });
-
-    thrown.expect(SonarException.class);
-    thrown.expectMessage("Task 'org.sonar.batch.tasks.TasksTest$FakeTask1' is defined twice: first by 'foo1' and then by 'foo2'");
-
-    tasks.start();
-  }
-
-  private static class FakeTask1 implements Task {
-    public void execute() {
-    }
-  }
-
-  private static class FakeTask2 implements Task {
-    public void execute() {
-    }
-
-  }
-
-}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/user/UserRepositoryTest.java b/sonar-batch/src/test/java/org/sonar/batch/user/UserRepositoryTest.java
deleted file mode 100644 (file)
index 7191d18..0000000
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * 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.batch.user;
-
-import org.junit.Test;
-import org.sonar.batch.bootstrap.ServerClient;
-
-import java.util.Arrays;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-public class UserRepositoryTest {
-
-  @Test
-  public void testLoad() {
-    ServerClient serverClient = mock(ServerClient.class);
-    UserRepository userRepo = new UserRepository(serverClient);
-
-    when(serverClient.request("/api/users/search?format=json&includeDeactivated=true&logins=fmallet,sbrandhof"))
-      .thenReturn(
-        "{ \"users\": [ { \"login\": \"fmallet\", \"name\": \"Freddy Mallet\", \"active\": true, \"email\": \"f@m.com\" }, { \"login\": \"sbrandhof\", \"name\": \"Simon\", \"active\": true } ] }");
-
-    assertThat(userRepo.loadFromWs(Arrays.asList("fmallet", "sbrandhof"))).containsOnly(new User("fmallet", "Freddy Mallet"), new User("sbrandhof", "Simon"));
-  }
-}
diff --git a/sonar-batch/src/test/resources/org/sonar/batch/components/PastSnapshotFinderByDateTest/shared.xml b/sonar-batch/src/test/resources/org/sonar/batch/components/PastSnapshotFinderByDateTest/shared.xml
deleted file mode 100644 (file)
index d794c3a..0000000
+++ /dev/null
@@ -1,42 +0,0 @@
-<dataset>
-
-  <projects long_name="[null]" id="1" scope="PRJ" qualifier="TRK" kee="project" name="project"
-            root_id="[null]"
-            description="[null]"
-            enabled="true" language="java" copy_resource_id="[null]" person_id="[null]"/>
-
-
-  <!-- 2008-11-01 -->
-  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1000"
-             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
-             scope="PRJ" qualifier="TRK" created_at="1225544280000" build_date="1225544280000" version="1.1-SNAPSHOT" path=""
-             status="P" islast="false" depth="0" />
-
-
-  <!-- 2008-11-12 -->
-  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1003"
-             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
-             scope="PRJ" qualifier="TRK" created_at="1226494680000" build_date="1226494680000" version="1.1-SNAPSHOT" path=""
-             status="P" islast="true" depth="0" />
-
-
-  <!-- 2008-11-22 -->
-  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1006"
-             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
-             scope="PRJ" qualifier="TRK" created_at="1227358680000" build_date="1227358680000" version="1.1" path=""
-             status="P" islast="false" depth="0" />
-
-
-  <!-- 2008-11-25-->
-  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1009"
-             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
-             scope="PRJ" qualifier="TRK" created_at="1227617880000" build_date="1227617880000" version="1.1" path=""
-             status="P" islast="false" depth="0" />
-
-  <!-- current analysis -->
-  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1010"
-             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
-             scope="PRJ" qualifier="TRK" created_at="1227790680000" build_date="1227790680000" version="1.2-SNAPSHOT" path=""
-             status="U" islast="false" depth="0" />
-
-</dataset>
diff --git a/sonar-batch/src/test/resources/org/sonar/batch/components/PastSnapshotFinderByDaysTest/shared.xml b/sonar-batch/src/test/resources/org/sonar/batch/components/PastSnapshotFinderByDaysTest/shared.xml
deleted file mode 100644 (file)
index 119f739..0000000
+++ /dev/null
@@ -1,76 +0,0 @@
-<dataset>
-
-  <!-- project -->
-  <projects long_name="[null]" id="1" scope="PRJ" qualifier="TRK" kee="project" name="project"
-            root_id="[null]"
-            description="[null]"
-            enabled="true" language="java" copy_resource_id="[null]" person_id="[null]"/>
-
-  <!-- package -->
-  <projects long_name="[null]" id="2" scope="DIR" qualifier="PAC" kee="project:org.foo" name="org.foo"
-            root_id="1"
-            description="[null]"
-            enabled="true" language="java" copy_resource_id="[null]" person_id="[null]"/>
-
-  <!-- file -->
-  <projects long_name="org.foo.Bar" id="3" scope="FIL" qualifier="CLA" kee="project:org.foo.Bar"
-            name="Bar" root_id="[null]"
-            description="[null]"
-            enabled="true" language="java" copy_resource_id="[null]" person_id="[null]"/>
-
-
-  <!-- first analysis : 2008-11-01-->
-  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1000" project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
-             scope="PRJ" qualifier="TRK" created_at="1225544280000" build_date="1225544280000" version="[null]" path=""
-             status="P" islast="false" depth="0" />
-
-  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1001" project_id="2" parent_snapshot_id="1000" root_project_id="1" root_snapshot_id="1000"
-             scope="DIR" qualifier="PAC" created_at="1225544280000" build_date="1225544280000" version="[null]" path="1000."
-             status="P" islast="false" depth="1" />
-
-  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1002" project_id="3" parent_snapshot_id="1001" root_project_id="1" root_snapshot_id="1000"
-             scope="FIL" qualifier="CLA" created_at="1225544280000" build_date="1225544280000" version="[null]" path="1000.1001."
-             status="P" islast="false" depth="2" />
-
-
-  <!-- second unprocessed analysis - to ignore: 2008-11-12 -->
-  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1003" project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
-             scope="PRJ" qualifier="TRK" created_at="1226494680000" build_date="1226494680000" version="[null]" path=""
-             status="U" islast="false" depth="0" />
-
-  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1004" project_id="2" parent_snapshot_id="1003" root_project_id="1" root_snapshot_id="1003"
-             scope="DIR" qualifier="PAC" created_at="1226494680000" build_date="1226494680000" version="[null]" path="1003."
-             status="U" islast="false" depth="1" />
-
-  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1005" project_id="3" parent_snapshot_id="1004" root_project_id="1" root_snapshot_id="1003"
-             scope="FIL" qualifier="CLA" created_at="1226494680000" build_date="1226494680000" version="[null]" path="1003.1004."
-             status="P" islast="false" depth="2" />
-
-
-  <!-- second analysis : 2008-11-13-->
-  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1006" project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
-             scope="PRJ" qualifier="TRK" created_at="1226581080000" build_date="1226581080000" version="[null]" path=""
-             status="P" islast="true" depth="0" />
-
-  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1007" project_id="2" parent_snapshot_id="1006" root_project_id="1" root_snapshot_id="1006"
-             scope="DIR" qualifier="PAC" created_at="1226581080000" build_date="1226581080000" version="[null]" path="1006."
-             status="P" islast="true" depth="1" />
-
-  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1008" project_id="3" parent_snapshot_id="1007" root_project_id="1" root_snapshot_id="1006"
-             scope="FIL" qualifier="CLA" created_at="1226581080000" build_date="1226581080000" version="[null]" path="1006.1007."
-             status="P" islast="true" depth="2" />
-
-
-  <!-- current analysis : 2008-11-16 -->
-  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1009" project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
-             scope="PRJ" qualifier="TRK" created_at="1226840280000" build_date="1226840280000" version="[null]" path=""
-             status="U" islast="false" depth="0" />
-
-  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1010" project_id="2" parent_snapshot_id="1009" root_project_id="1" root_snapshot_id="1009"
-             scope="DIR" qualifier="PAC" created_at="1226840280000" build_date="1226840280000" version="[null]" path="1009."
-             status="U" islast="false" depth="1" />
-
-  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1011" project_id="3" parent_snapshot_id="1010" root_project_id="1" root_snapshot_id="1009"
-             scope="FIL" qualifier="CLA" created_at="1226840280000" build_date="1226840280000" version="[null]" path="1009.1010."
-             status="U" islast="false" depth="2" />
-</dataset>
diff --git a/sonar-batch/src/test/resources/org/sonar/batch/components/PastSnapshotFinderByDaysTest/shouldNotFindSelf.xml b/sonar-batch/src/test/resources/org/sonar/batch/components/PastSnapshotFinderByDaysTest/shouldNotFindSelf.xml
deleted file mode 100644 (file)
index 166f7c1..0000000
+++ /dev/null
@@ -1,34 +0,0 @@
-<dataset>
-
-  <!-- project -->
-  <projects long_name="[null]" id="1" scope="PRJ" qualifier="TRK" kee="project" name="project"
-            root_id="[null]"
-            description="[null]"
-            enabled="true" language="java" copy_resource_id="[null]" person_id="[null]"/>
-
-  <!-- package -->
-  <projects long_name="[null]" id="2" scope="DIR" qualifier="PAC" kee="project:org.foo" name="org.foo"
-            root_id="1"
-            description="[null]"
-            enabled="true" language="java" copy_resource_id="[null]" person_id="[null]"/>
-
-  <!-- file -->
-  <projects long_name="org.foo.Bar" id="3" scope="FIL" qualifier="CLA" kee="project:org.foo.Bar"
-            name="Bar" root_id="[null]"
-            description="[null]"
-            enabled="true" language="java" copy_resource_id="[null]" person_id="[null]"/>
-
-
-  <!-- current analysis : 2008-11-16 -->
-  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1009" project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
-             scope="PRJ" qualifier="TRK" created_at="1226840280000" build_date="1226840280000" version="[null]" path=""
-             status="U" islast="false" depth="0" />
-
-  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1010" project_id="2" parent_snapshot_id="1009" root_project_id="1" root_snapshot_id="1009"
-             scope="DIR" qualifier="PAC" created_at="1226840280000" build_date="1226840280000" version="[null]" path="1009."
-             status="U" islast="false" depth="1" />
-
-  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1011" project_id="3" parent_snapshot_id="1010" root_project_id="1" root_snapshot_id="1009"
-             scope="FIL" qualifier="CLA" created_at="1226840280000" build_date="1226840280000" version="[null]" path="1009.1010."
-             status="U" islast="false" depth="2" />
-</dataset>
\ No newline at end of file
diff --git a/sonar-batch/src/test/resources/org/sonar/batch/components/PastSnapshotFinderByPreviousAnalysisTest/shouldFindPreviousAnalysis.xml b/sonar-batch/src/test/resources/org/sonar/batch/components/PastSnapshotFinderByPreviousAnalysisTest/shouldFindPreviousAnalysis.xml
deleted file mode 100644 (file)
index eb5136d..0000000
+++ /dev/null
@@ -1,26 +0,0 @@
-<dataset>
-
-  <projects long_name="[null]" id="1" scope="PRJ" qualifier="TRK" kee="project" name="project"
-            root_id="[null]"
-            description="[null]"
-            enabled="true" language="java" copy_resource_id="[null]" person_id="[null]"/>
-
-  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1006"
-             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
-             scope="PRJ" qualifier="TRK" created_at="1227358680000" build_date="1227358680000" version="1.1" path=""
-             status="P" islast="false" depth="0" />
-
-
-  <!-- last analysis -->
-  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1009"
-             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
-             scope="PRJ" qualifier="TRK" created_at="1227617880000" build_date="1227617880000" version="1.1" path=""
-             status="P" islast="true" depth="0" />
-
-  <!-- current analysis -->
-  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1010"
-             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
-             scope="PRJ" qualifier="TRK" created_at="1227790680000" build_date="1227790680000" version="1.2-SNAPSHOT" path=""
-             status="U" islast="false" depth="0" />
-
-</dataset>
\ No newline at end of file
diff --git a/sonar-batch/src/test/resources/org/sonar/batch/components/PastSnapshotFinderByPreviousAnalysisTest/shouldNotFindPreviousAnalysis.xml b/sonar-batch/src/test/resources/org/sonar/batch/components/PastSnapshotFinderByPreviousAnalysisTest/shouldNotFindPreviousAnalysis.xml
deleted file mode 100644 (file)
index 5809598..0000000
+++ /dev/null
@@ -1,21 +0,0 @@
-<dataset>
-
-  <projects long_name="[null]" id="1" scope="PRJ" qualifier="TRK" kee="project" name="project"
-            root_id="[null]"
-            description="[null]"
-            enabled="true" language="java" copy_resource_id="[null]" person_id="[null]"/>
-
-
-  <!-- unprocessed analysis -->
-  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1009"
-             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
-             scope="PRJ" qualifier="TRK" created_at="1227617880000" build_date="1227617880000" version="1.1" path=""
-             status="U" islast="false" depth="0" />
-
-  <!-- current analysis -->
-  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1010"
-             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
-             scope="PRJ" qualifier="TRK" created_at="1227790680000" build_date="1227790680000" version="1.2-SNAPSHOT" path=""
-             status="U" islast="false" depth="0" />
-
-</dataset>
\ No newline at end of file
diff --git a/sonar-batch/src/test/resources/org/sonar/batch/components/PastSnapshotFinderByPreviousVersionTest/no-previous-version.xml b/sonar-batch/src/test/resources/org/sonar/batch/components/PastSnapshotFinderByPreviousVersionTest/no-previous-version.xml
deleted file mode 100644 (file)
index 2f01f86..0000000
+++ /dev/null
@@ -1,42 +0,0 @@
-<dataset>
-
-  <projects long_name="[null]" id="1" scope="PRJ" qualifier="TRK" kee="project" name="project"
-            root_id="[null]"
-            description="[null]"
-            enabled="true" language="java" copy_resource_id="[null]" person_id="[null]"/>
-
-
-  <!-- version 1.0 -->
-  <snapshots id="1000" purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]"
-             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
-             scope="PRJ" qualifier="TRK" created_at="1225630680000" build_date="1225630680000" version="1.0" path=""
-             status="P" islast="false" depth="0" />
-
-  <!-- version 1.1 -->
-  <snapshots id="1001" purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]"
-             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
-             scope="PRJ" qualifier="TRK" created_at="1225803480000" build_date="1225803480000" version="1.1" path=""
-             status="P" islast="false" depth="0" />
-
-  <!-- version 1.2-SNAPSHOT -->
-  <snapshots id="1002" purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]"
-             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
-             scope="PRJ" qualifier="TRK" created_at="1225976280000" build_date="1225976280000" version="1.2-SNAPSHOT" path=""
-             status="P" islast="false" depth="0" />
-
-  <!-- version 1.2-SNAPSHOT, current analysis -->
-  <snapshots id="1003" purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]"
-             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
-             scope="PRJ" qualifier="TRK" created_at="1226235480000" build_date="1226235480000" version="1.2-SNAPSHOT" path=""
-             status="U" islast="true" depth="0" />
-  
-  <events id="2" name="Foo" resource_id="1" snapshot_id="1000" category="Other" event_date="2008-11-03 13:58:00.00" created_at="2008-11-03 13:58:00.00" description=""
-          event_data="[null]"/>
-  <events id="4" name="Bar" resource_id="1" snapshot_id="1001" category="Other" event_date="2008-11-05 13:58:00.00" created_at="2008-11-05 13:58:00.00" description=""
-          event_data="[null]"/>
-  <events id="5" name="Uhh" resource_id="1" snapshot_id="1002" category="Other" event_date="2008-11-07 13:58:00.00" created_at="2008-11-07 13:58:00.00" description=""
-          event_data="[null]"/>
-  <events id="6" name="1.2-SNAPSHOT" resource_id="1" snapshot_id="1003" category="Version" event_date="2008-11-09 13:58:00.00" created_at="2008-11-09 13:58:00.00" description=""
-          event_data="[null]"/>
-
-</dataset>
diff --git a/sonar-batch/src/test/resources/org/sonar/batch/components/PastSnapshotFinderByPreviousVersionTest/with-previous-version-deleted.xml b/sonar-batch/src/test/resources/org/sonar/batch/components/PastSnapshotFinderByPreviousVersionTest/with-previous-version-deleted.xml
deleted file mode 100644 (file)
index d990e64..0000000
+++ /dev/null
@@ -1,46 +0,0 @@
-<dataset>
-
-  <projects long_name="[null]" id="1" scope="PRJ" qualifier="TRK" kee="project" name="project"
-            root_id="[null]"
-            description="[null]"
-            enabled="true" language="java" copy_resource_id="[null]" person_id="[null]"/>
-
-
-  <!-- version 1.0 -->
-  <snapshots id="1000" purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]"
-             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
-             scope="PRJ" qualifier="TRK" created_at="1225630680000" build_date="1225630680000" version="1.0" path=""
-             status="P" islast="false" depth="0" />
-
-  <!-- version 1.1 -->
-  <snapshots id="1001" purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]"
-             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
-             scope="PRJ" qualifier="TRK" created_at="1225803480000" build_date="1225803480000" version="1.1" path=""
-             status="P" islast="false" depth="0" />
-
-  <!-- version 1.2-SNAPSHOT -->
-  <snapshots id="1002" purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]"
-             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
-             scope="PRJ" qualifier="TRK" created_at="1225976280000" build_date="1225976280000" version="1.2-SNAPSHOT" path=""
-             status="P" islast="false" depth="0" />
-
-  <!-- version 1.2-SNAPSHOT, current analysis -->
-  <snapshots id="1003" purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]"
-             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
-             scope="PRJ" qualifier="TRK" created_at="1226235480000" build_date="1226235480000" version="1.2-SNAPSHOT" path=""
-             status="U" islast="true" depth="0" />
-  
-  <events id="1" name="1.0" resource_id="1" snapshot_id="1000" category="Version" event_date="2008-11-02 13:58:00.00" created_at="2008-11-02 13:58:00.00" description=""
-          event_data="[null]"/>
-  <events id="2" name="Foo" resource_id="1" snapshot_id="1000" category="Other" event_date="2008-11-03 13:58:00.00" created_at="2008-11-03 13:58:00.00" description=""
-          event_data="[null]"/>
-  <!-- The "1.1" version was deleted from the history :  -->
-  <!-- events id="3" name="1.1" resource_id="1" snapshot_id="1001" category="Version" event_date="2008-11-04 13:58:00.00" created_at="2008-11-04 13:58:00.00" description=""/-->
-  <events id="4" name="Bar" resource_id="1" snapshot_id="1001" category="Other" event_date="2008-11-05 13:58:00.00" created_at="2008-11-05 13:58:00.00" description=""
-          event_data="[null]"/>
-  <events id="5" name="Uhh" resource_id="1" snapshot_id="1002" category="Other" event_date="2008-11-07 13:58:00.00" created_at="2008-11-07 13:58:00.00" description=""
-          event_data="[null]"/>
-  <events id="6" name="1.2-SNAPSHOT" resource_id="1" snapshot_id="1003" category="Version" event_date="2008-11-09 13:58:00.00" created_at="2008-11-09 13:58:00.00" description=""
-          event_data="[null]"/>
-
-</dataset>
diff --git a/sonar-batch/src/test/resources/org/sonar/batch/components/PastSnapshotFinderByPreviousVersionTest/with-previous-version.xml b/sonar-batch/src/test/resources/org/sonar/batch/components/PastSnapshotFinderByPreviousVersionTest/with-previous-version.xml
deleted file mode 100644 (file)
index 5ecbc2f..0000000
+++ /dev/null
@@ -1,40 +0,0 @@
-<dataset>
-
-  <projects long_name="[null]" id="1" scope="PRJ" qualifier="TRK" kee="project" name="project"
-            root_id="[null]"
-            description="[null]"
-            enabled="true" language="java" copy_resource_id="[null]" person_id="[null]"/>
-
-
-  <!-- version 1.0 -->
-  <snapshots id="1000" purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]"
-             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
-             scope="PRJ" qualifier="TRK" created_at="1225630680000" build_date="1225630680000" version="1.0" path=""
-             status="P" islast="false" depth="0" />
-
-  <!-- version 1.1 -->
-  <snapshots id="1001" purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]"
-             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
-             scope="PRJ" qualifier="TRK" created_at="1225803480000" build_date="1225803480000" version="1.1" path=""
-             status="P" islast="false" depth="0" />
-
-  <!-- version 1.2-SNAPSHOT -->
-  <snapshots id="1002" purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]"
-             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
-             scope="PRJ" qualifier="TRK" created_at="1225976280000" build_date="1225976280000" version="1.2-SNAPSHOT" path=""
-             status="P" islast="false" depth="0" />
-
-  <!-- version 1.2-SNAPSHOT, current analysis -->
-  <snapshots id="1003" purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]"
-             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
-             scope="PRJ" qualifier="TRK" created_at="1226235480000" build_date="1226235480000" version="1.2-SNAPSHOT" path=""
-             status="U" islast="true" depth="0" />
-  
-  <events id="1" name="1.0" resource_id="1" snapshot_id="1000" category="Version" event_date="2008-11-02 13:58:00.00" created_at="2008-11-02 13:58:00.00" description="" event_data="[null]"/>
-  <events id="2" name="Foo" resource_id="1" snapshot_id="1000" category="Other" event_date="2008-11-03 13:58:00.00" created_at="2008-11-03 13:58:00.00" description="" event_data="[null]"/>
-  <events id="3" name="1.1" resource_id="1" snapshot_id="1001" category="Version" event_date="2008-11-04 13:58:00.00" created_at="2008-11-04 13:58:00.00" description="" event_data="[null]"/>
-  <events id="4" name="Bar" resource_id="1" snapshot_id="1001" category="Other" event_date="2008-11-05 13:58:00.00" created_at="2008-11-05 13:58:00.00" description="" event_data="[null]"/>
-  <events id="5" name="Uhh" resource_id="1" snapshot_id="1002" category="Other" event_date="2008-11-07 13:58:00.00" created_at="2008-11-07 13:58:00.00" description="" event_data="[null]"/>
-  <events id="6" name="1.2-SNAPSHOT" resource_id="1" snapshot_id="1003" category="Version" event_date="2008-11-09 13:58:00.00" created_at="2008-11-09 13:58:00.00" description="" event_data="[null]"/>
-
-</dataset>
diff --git a/sonar-batch/src/test/resources/org/sonar/batch/components/PastSnapshotFinderByVersionTest/shared.xml b/sonar-batch/src/test/resources/org/sonar/batch/components/PastSnapshotFinderByVersionTest/shared.xml
deleted file mode 100644 (file)
index 289a362..0000000
+++ /dev/null
@@ -1,42 +0,0 @@
-<dataset>
-
-  <projects long_name="[null]" id="1" scope="PRJ" qualifier="TRK" kee="project" name="project"
-            root_id="[null]"
-            description="[null]"
-            enabled="true" language="java" copy_resource_id="[null]" person_id="[null]"/>
-
-
-  <!-- version 1.1-SNAPSHOT -->
-  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1000"
-             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
-             scope="PRJ" qualifier="TRK" created_at="1225544280000" build_date="1225544280000" version="1.1-SNAPSHOT" path=""
-             status="P" islast="false" depth="0" />
-
-
-  <!-- version 1.1-SNAPSHOT -->
-  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1003"
-             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
-             scope="PRJ" qualifier="TRK" created_at="1225630680000" build_date="1225630680000" version="1.1-SNAPSHOT" path=""
-             status="P" islast="true" depth="0" />
-
-
-  <!-- unprocessed version 1.1 (to ignore) -->
-  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1006"
-             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
-             scope="PRJ" qualifier="TRK" created_at="1225717080000" build_date="1225717080000" version="1.1" path=""
-             status="U" islast="false" depth="0" />
-
-
-  <!-- version 1.1 -->
-  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1009"
-             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
-             scope="PRJ" qualifier="TRK" created_at="1225803480000" build_date="1225803480000" version="1.1" path=""
-             status="P" islast="false" depth="0" />
-
-  <!-- current analysis -->
-  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1010"
-             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
-             scope="PRJ" qualifier="TRK" created_at="1225889880000" build_date="1225889880000" version="1.2-SNAPSHOT" path=""
-             status="U" islast="false" depth="0" />
-
-</dataset>
diff --git a/sonar-batch/src/test/resources/org/sonar/batch/components/PeriodsDefinitionTest/shared.xml b/sonar-batch/src/test/resources/org/sonar/batch/components/PeriodsDefinitionTest/shared.xml
deleted file mode 100644 (file)
index c8796e2..0000000
+++ /dev/null
@@ -1,12 +0,0 @@
-<dataset>
-
-  <projects long_name="[null]" id="1" scope="PRJ" kee="my:project" qualifier="LIB" name="my project as lib"
-            root_id="[null]" description="[null]" enabled="true"  language="java" copy_resource_id="[null]" person_id="[null]"/>
-
-  <projects long_name="[null]" id="2" scope="PRJ" kee="my:project" qualifier="TRK" name="my project"
-            root_id="[null]" description="[null]" enabled="true"  language="java" copy_resource_id="[null]" person_id="[null]"/>
-
-  <projects long_name="[null]" id="3" scope="DIR" kee="my:project:path/to/dir" qualifier="TRK" name="my dir"
-            root_id="2" description="[null]" enabled="true"  language="java" copy_resource_id="[null]" person_id="[null]"/>
-
-</dataset>
diff --git a/sonar-batch/src/test/resources/org/sonar/batch/deprecated/components/PastSnapshotFinderByDateTest/shared.xml b/sonar-batch/src/test/resources/org/sonar/batch/deprecated/components/PastSnapshotFinderByDateTest/shared.xml
new file mode 100644 (file)
index 0000000..d794c3a
--- /dev/null
@@ -0,0 +1,42 @@
+<dataset>
+
+  <projects long_name="[null]" id="1" scope="PRJ" qualifier="TRK" kee="project" name="project"
+            root_id="[null]"
+            description="[null]"
+            enabled="true" language="java" copy_resource_id="[null]" person_id="[null]"/>
+
+
+  <!-- 2008-11-01 -->
+  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1000"
+             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
+             scope="PRJ" qualifier="TRK" created_at="1225544280000" build_date="1225544280000" version="1.1-SNAPSHOT" path=""
+             status="P" islast="false" depth="0" />
+
+
+  <!-- 2008-11-12 -->
+  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1003"
+             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
+             scope="PRJ" qualifier="TRK" created_at="1226494680000" build_date="1226494680000" version="1.1-SNAPSHOT" path=""
+             status="P" islast="true" depth="0" />
+
+
+  <!-- 2008-11-22 -->
+  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1006"
+             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
+             scope="PRJ" qualifier="TRK" created_at="1227358680000" build_date="1227358680000" version="1.1" path=""
+             status="P" islast="false" depth="0" />
+
+
+  <!-- 2008-11-25-->
+  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1009"
+             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
+             scope="PRJ" qualifier="TRK" created_at="1227617880000" build_date="1227617880000" version="1.1" path=""
+             status="P" islast="false" depth="0" />
+
+  <!-- current analysis -->
+  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1010"
+             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
+             scope="PRJ" qualifier="TRK" created_at="1227790680000" build_date="1227790680000" version="1.2-SNAPSHOT" path=""
+             status="U" islast="false" depth="0" />
+
+</dataset>
diff --git a/sonar-batch/src/test/resources/org/sonar/batch/deprecated/components/PastSnapshotFinderByDaysTest/shared.xml b/sonar-batch/src/test/resources/org/sonar/batch/deprecated/components/PastSnapshotFinderByDaysTest/shared.xml
new file mode 100644 (file)
index 0000000..119f739
--- /dev/null
@@ -0,0 +1,76 @@
+<dataset>
+
+  <!-- project -->
+  <projects long_name="[null]" id="1" scope="PRJ" qualifier="TRK" kee="project" name="project"
+            root_id="[null]"
+            description="[null]"
+            enabled="true" language="java" copy_resource_id="[null]" person_id="[null]"/>
+
+  <!-- package -->
+  <projects long_name="[null]" id="2" scope="DIR" qualifier="PAC" kee="project:org.foo" name="org.foo"
+            root_id="1"
+            description="[null]"
+            enabled="true" language="java" copy_resource_id="[null]" person_id="[null]"/>
+
+  <!-- file -->
+  <projects long_name="org.foo.Bar" id="3" scope="FIL" qualifier="CLA" kee="project:org.foo.Bar"
+            name="Bar" root_id="[null]"
+            description="[null]"
+            enabled="true" language="java" copy_resource_id="[null]" person_id="[null]"/>
+
+
+  <!-- first analysis : 2008-11-01-->
+  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1000" project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
+             scope="PRJ" qualifier="TRK" created_at="1225544280000" build_date="1225544280000" version="[null]" path=""
+             status="P" islast="false" depth="0" />
+
+  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1001" project_id="2" parent_snapshot_id="1000" root_project_id="1" root_snapshot_id="1000"
+             scope="DIR" qualifier="PAC" created_at="1225544280000" build_date="1225544280000" version="[null]" path="1000."
+             status="P" islast="false" depth="1" />
+
+  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1002" project_id="3" parent_snapshot_id="1001" root_project_id="1" root_snapshot_id="1000"
+             scope="FIL" qualifier="CLA" created_at="1225544280000" build_date="1225544280000" version="[null]" path="1000.1001."
+             status="P" islast="false" depth="2" />
+
+
+  <!-- second unprocessed analysis - to ignore: 2008-11-12 -->
+  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1003" project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
+             scope="PRJ" qualifier="TRK" created_at="1226494680000" build_date="1226494680000" version="[null]" path=""
+             status="U" islast="false" depth="0" />
+
+  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1004" project_id="2" parent_snapshot_id="1003" root_project_id="1" root_snapshot_id="1003"
+             scope="DIR" qualifier="PAC" created_at="1226494680000" build_date="1226494680000" version="[null]" path="1003."
+             status="U" islast="false" depth="1" />
+
+  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1005" project_id="3" parent_snapshot_id="1004" root_project_id="1" root_snapshot_id="1003"
+             scope="FIL" qualifier="CLA" created_at="1226494680000" build_date="1226494680000" version="[null]" path="1003.1004."
+             status="P" islast="false" depth="2" />
+
+
+  <!-- second analysis : 2008-11-13-->
+  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1006" project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
+             scope="PRJ" qualifier="TRK" created_at="1226581080000" build_date="1226581080000" version="[null]" path=""
+             status="P" islast="true" depth="0" />
+
+  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1007" project_id="2" parent_snapshot_id="1006" root_project_id="1" root_snapshot_id="1006"
+             scope="DIR" qualifier="PAC" created_at="1226581080000" build_date="1226581080000" version="[null]" path="1006."
+             status="P" islast="true" depth="1" />
+
+  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1008" project_id="3" parent_snapshot_id="1007" root_project_id="1" root_snapshot_id="1006"
+             scope="FIL" qualifier="CLA" created_at="1226581080000" build_date="1226581080000" version="[null]" path="1006.1007."
+             status="P" islast="true" depth="2" />
+
+
+  <!-- current analysis : 2008-11-16 -->
+  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1009" project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
+             scope="PRJ" qualifier="TRK" created_at="1226840280000" build_date="1226840280000" version="[null]" path=""
+             status="U" islast="false" depth="0" />
+
+  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1010" project_id="2" parent_snapshot_id="1009" root_project_id="1" root_snapshot_id="1009"
+             scope="DIR" qualifier="PAC" created_at="1226840280000" build_date="1226840280000" version="[null]" path="1009."
+             status="U" islast="false" depth="1" />
+
+  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1011" project_id="3" parent_snapshot_id="1010" root_project_id="1" root_snapshot_id="1009"
+             scope="FIL" qualifier="CLA" created_at="1226840280000" build_date="1226840280000" version="[null]" path="1009.1010."
+             status="U" islast="false" depth="2" />
+</dataset>
diff --git a/sonar-batch/src/test/resources/org/sonar/batch/deprecated/components/PastSnapshotFinderByDaysTest/shouldNotFindSelf.xml b/sonar-batch/src/test/resources/org/sonar/batch/deprecated/components/PastSnapshotFinderByDaysTest/shouldNotFindSelf.xml
new file mode 100644 (file)
index 0000000..166f7c1
--- /dev/null
@@ -0,0 +1,34 @@
+<dataset>
+
+  <!-- project -->
+  <projects long_name="[null]" id="1" scope="PRJ" qualifier="TRK" kee="project" name="project"
+            root_id="[null]"
+            description="[null]"
+            enabled="true" language="java" copy_resource_id="[null]" person_id="[null]"/>
+
+  <!-- package -->
+  <projects long_name="[null]" id="2" scope="DIR" qualifier="PAC" kee="project:org.foo" name="org.foo"
+            root_id="1"
+            description="[null]"
+            enabled="true" language="java" copy_resource_id="[null]" person_id="[null]"/>
+
+  <!-- file -->
+  <projects long_name="org.foo.Bar" id="3" scope="FIL" qualifier="CLA" kee="project:org.foo.Bar"
+            name="Bar" root_id="[null]"
+            description="[null]"
+            enabled="true" language="java" copy_resource_id="[null]" person_id="[null]"/>
+
+
+  <!-- current analysis : 2008-11-16 -->
+  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1009" project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
+             scope="PRJ" qualifier="TRK" created_at="1226840280000" build_date="1226840280000" version="[null]" path=""
+             status="U" islast="false" depth="0" />
+
+  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1010" project_id="2" parent_snapshot_id="1009" root_project_id="1" root_snapshot_id="1009"
+             scope="DIR" qualifier="PAC" created_at="1226840280000" build_date="1226840280000" version="[null]" path="1009."
+             status="U" islast="false" depth="1" />
+
+  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1011" project_id="3" parent_snapshot_id="1010" root_project_id="1" root_snapshot_id="1009"
+             scope="FIL" qualifier="CLA" created_at="1226840280000" build_date="1226840280000" version="[null]" path="1009.1010."
+             status="U" islast="false" depth="2" />
+</dataset>
\ No newline at end of file
diff --git a/sonar-batch/src/test/resources/org/sonar/batch/deprecated/components/PastSnapshotFinderByPreviousAnalysisTest/shouldFindPreviousAnalysis.xml b/sonar-batch/src/test/resources/org/sonar/batch/deprecated/components/PastSnapshotFinderByPreviousAnalysisTest/shouldFindPreviousAnalysis.xml
new file mode 100644 (file)
index 0000000..eb5136d
--- /dev/null
@@ -0,0 +1,26 @@
+<dataset>
+
+  <projects long_name="[null]" id="1" scope="PRJ" qualifier="TRK" kee="project" name="project"
+            root_id="[null]"
+            description="[null]"
+            enabled="true" language="java" copy_resource_id="[null]" person_id="[null]"/>
+
+  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1006"
+             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
+             scope="PRJ" qualifier="TRK" created_at="1227358680000" build_date="1227358680000" version="1.1" path=""
+             status="P" islast="false" depth="0" />
+
+
+  <!-- last analysis -->
+  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1009"
+             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
+             scope="PRJ" qualifier="TRK" created_at="1227617880000" build_date="1227617880000" version="1.1" path=""
+             status="P" islast="true" depth="0" />
+
+  <!-- current analysis -->
+  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1010"
+             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
+             scope="PRJ" qualifier="TRK" created_at="1227790680000" build_date="1227790680000" version="1.2-SNAPSHOT" path=""
+             status="U" islast="false" depth="0" />
+
+</dataset>
\ No newline at end of file
diff --git a/sonar-batch/src/test/resources/org/sonar/batch/deprecated/components/PastSnapshotFinderByPreviousAnalysisTest/shouldNotFindPreviousAnalysis.xml b/sonar-batch/src/test/resources/org/sonar/batch/deprecated/components/PastSnapshotFinderByPreviousAnalysisTest/shouldNotFindPreviousAnalysis.xml
new file mode 100644 (file)
index 0000000..5809598
--- /dev/null
@@ -0,0 +1,21 @@
+<dataset>
+
+  <projects long_name="[null]" id="1" scope="PRJ" qualifier="TRK" kee="project" name="project"
+            root_id="[null]"
+            description="[null]"
+            enabled="true" language="java" copy_resource_id="[null]" person_id="[null]"/>
+
+
+  <!-- unprocessed analysis -->
+  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1009"
+             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
+             scope="PRJ" qualifier="TRK" created_at="1227617880000" build_date="1227617880000" version="1.1" path=""
+             status="U" islast="false" depth="0" />
+
+  <!-- current analysis -->
+  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1010"
+             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
+             scope="PRJ" qualifier="TRK" created_at="1227790680000" build_date="1227790680000" version="1.2-SNAPSHOT" path=""
+             status="U" islast="false" depth="0" />
+
+</dataset>
\ No newline at end of file
diff --git a/sonar-batch/src/test/resources/org/sonar/batch/deprecated/components/PastSnapshotFinderByPreviousVersionTest/no-previous-version.xml b/sonar-batch/src/test/resources/org/sonar/batch/deprecated/components/PastSnapshotFinderByPreviousVersionTest/no-previous-version.xml
new file mode 100644 (file)
index 0000000..2f01f86
--- /dev/null
@@ -0,0 +1,42 @@
+<dataset>
+
+  <projects long_name="[null]" id="1" scope="PRJ" qualifier="TRK" kee="project" name="project"
+            root_id="[null]"
+            description="[null]"
+            enabled="true" language="java" copy_resource_id="[null]" person_id="[null]"/>
+
+
+  <!-- version 1.0 -->
+  <snapshots id="1000" purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]"
+             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
+             scope="PRJ" qualifier="TRK" created_at="1225630680000" build_date="1225630680000" version="1.0" path=""
+             status="P" islast="false" depth="0" />
+
+  <!-- version 1.1 -->
+  <snapshots id="1001" purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]"
+             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
+             scope="PRJ" qualifier="TRK" created_at="1225803480000" build_date="1225803480000" version="1.1" path=""
+             status="P" islast="false" depth="0" />
+
+  <!-- version 1.2-SNAPSHOT -->
+  <snapshots id="1002" purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]"
+             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
+             scope="PRJ" qualifier="TRK" created_at="1225976280000" build_date="1225976280000" version="1.2-SNAPSHOT" path=""
+             status="P" islast="false" depth="0" />
+
+  <!-- version 1.2-SNAPSHOT, current analysis -->
+  <snapshots id="1003" purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]"
+             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
+             scope="PRJ" qualifier="TRK" created_at="1226235480000" build_date="1226235480000" version="1.2-SNAPSHOT" path=""
+             status="U" islast="true" depth="0" />
+  
+  <events id="2" name="Foo" resource_id="1" snapshot_id="1000" category="Other" event_date="2008-11-03 13:58:00.00" created_at="2008-11-03 13:58:00.00" description=""
+          event_data="[null]"/>
+  <events id="4" name="Bar" resource_id="1" snapshot_id="1001" category="Other" event_date="2008-11-05 13:58:00.00" created_at="2008-11-05 13:58:00.00" description=""
+          event_data="[null]"/>
+  <events id="5" name="Uhh" resource_id="1" snapshot_id="1002" category="Other" event_date="2008-11-07 13:58:00.00" created_at="2008-11-07 13:58:00.00" description=""
+          event_data="[null]"/>
+  <events id="6" name="1.2-SNAPSHOT" resource_id="1" snapshot_id="1003" category="Version" event_date="2008-11-09 13:58:00.00" created_at="2008-11-09 13:58:00.00" description=""
+          event_data="[null]"/>
+
+</dataset>
diff --git a/sonar-batch/src/test/resources/org/sonar/batch/deprecated/components/PastSnapshotFinderByPreviousVersionTest/with-previous-version-deleted.xml b/sonar-batch/src/test/resources/org/sonar/batch/deprecated/components/PastSnapshotFinderByPreviousVersionTest/with-previous-version-deleted.xml
new file mode 100644 (file)
index 0000000..d990e64
--- /dev/null
@@ -0,0 +1,46 @@
+<dataset>
+
+  <projects long_name="[null]" id="1" scope="PRJ" qualifier="TRK" kee="project" name="project"
+            root_id="[null]"
+            description="[null]"
+            enabled="true" language="java" copy_resource_id="[null]" person_id="[null]"/>
+
+
+  <!-- version 1.0 -->
+  <snapshots id="1000" purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]"
+             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
+             scope="PRJ" qualifier="TRK" created_at="1225630680000" build_date="1225630680000" version="1.0" path=""
+             status="P" islast="false" depth="0" />
+
+  <!-- version 1.1 -->
+  <snapshots id="1001" purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]"
+             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
+             scope="PRJ" qualifier="TRK" created_at="1225803480000" build_date="1225803480000" version="1.1" path=""
+             status="P" islast="false" depth="0" />
+
+  <!-- version 1.2-SNAPSHOT -->
+  <snapshots id="1002" purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]"
+             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
+             scope="PRJ" qualifier="TRK" created_at="1225976280000" build_date="1225976280000" version="1.2-SNAPSHOT" path=""
+             status="P" islast="false" depth="0" />
+
+  <!-- version 1.2-SNAPSHOT, current analysis -->
+  <snapshots id="1003" purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]"
+             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
+             scope="PRJ" qualifier="TRK" created_at="1226235480000" build_date="1226235480000" version="1.2-SNAPSHOT" path=""
+             status="U" islast="true" depth="0" />
+  
+  <events id="1" name="1.0" resource_id="1" snapshot_id="1000" category="Version" event_date="2008-11-02 13:58:00.00" created_at="2008-11-02 13:58:00.00" description=""
+          event_data="[null]"/>
+  <events id="2" name="Foo" resource_id="1" snapshot_id="1000" category="Other" event_date="2008-11-03 13:58:00.00" created_at="2008-11-03 13:58:00.00" description=""
+          event_data="[null]"/>
+  <!-- The "1.1" version was deleted from the history :  -->
+  <!-- events id="3" name="1.1" resource_id="1" snapshot_id="1001" category="Version" event_date="2008-11-04 13:58:00.00" created_at="2008-11-04 13:58:00.00" description=""/-->
+  <events id="4" name="Bar" resource_id="1" snapshot_id="1001" category="Other" event_date="2008-11-05 13:58:00.00" created_at="2008-11-05 13:58:00.00" description=""
+          event_data="[null]"/>
+  <events id="5" name="Uhh" resource_id="1" snapshot_id="1002" category="Other" event_date="2008-11-07 13:58:00.00" created_at="2008-11-07 13:58:00.00" description=""
+          event_data="[null]"/>
+  <events id="6" name="1.2-SNAPSHOT" resource_id="1" snapshot_id="1003" category="Version" event_date="2008-11-09 13:58:00.00" created_at="2008-11-09 13:58:00.00" description=""
+          event_data="[null]"/>
+
+</dataset>
diff --git a/sonar-batch/src/test/resources/org/sonar/batch/deprecated/components/PastSnapshotFinderByPreviousVersionTest/with-previous-version.xml b/sonar-batch/src/test/resources/org/sonar/batch/deprecated/components/PastSnapshotFinderByPreviousVersionTest/with-previous-version.xml
new file mode 100644 (file)
index 0000000..5ecbc2f
--- /dev/null
@@ -0,0 +1,40 @@
+<dataset>
+
+  <projects long_name="[null]" id="1" scope="PRJ" qualifier="TRK" kee="project" name="project"
+            root_id="[null]"
+            description="[null]"
+            enabled="true" language="java" copy_resource_id="[null]" person_id="[null]"/>
+
+
+  <!-- version 1.0 -->
+  <snapshots id="1000" purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]"
+             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
+             scope="PRJ" qualifier="TRK" created_at="1225630680000" build_date="1225630680000" version="1.0" path=""
+             status="P" islast="false" depth="0" />
+
+  <!-- version 1.1 -->
+  <snapshots id="1001" purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]"
+             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
+             scope="PRJ" qualifier="TRK" created_at="1225803480000" build_date="1225803480000" version="1.1" path=""
+             status="P" islast="false" depth="0" />
+
+  <!-- version 1.2-SNAPSHOT -->
+  <snapshots id="1002" purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]"
+             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
+             scope="PRJ" qualifier="TRK" created_at="1225976280000" build_date="1225976280000" version="1.2-SNAPSHOT" path=""
+             status="P" islast="false" depth="0" />
+
+  <!-- version 1.2-SNAPSHOT, current analysis -->
+  <snapshots id="1003" purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]"
+             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
+             scope="PRJ" qualifier="TRK" created_at="1226235480000" build_date="1226235480000" version="1.2-SNAPSHOT" path=""
+             status="U" islast="true" depth="0" />
+  
+  <events id="1" name="1.0" resource_id="1" snapshot_id="1000" category="Version" event_date="2008-11-02 13:58:00.00" created_at="2008-11-02 13:58:00.00" description="" event_data="[null]"/>
+  <events id="2" name="Foo" resource_id="1" snapshot_id="1000" category="Other" event_date="2008-11-03 13:58:00.00" created_at="2008-11-03 13:58:00.00" description="" event_data="[null]"/>
+  <events id="3" name="1.1" resource_id="1" snapshot_id="1001" category="Version" event_date="2008-11-04 13:58:00.00" created_at="2008-11-04 13:58:00.00" description="" event_data="[null]"/>
+  <events id="4" name="Bar" resource_id="1" snapshot_id="1001" category="Other" event_date="2008-11-05 13:58:00.00" created_at="2008-11-05 13:58:00.00" description="" event_data="[null]"/>
+  <events id="5" name="Uhh" resource_id="1" snapshot_id="1002" category="Other" event_date="2008-11-07 13:58:00.00" created_at="2008-11-07 13:58:00.00" description="" event_data="[null]"/>
+  <events id="6" name="1.2-SNAPSHOT" resource_id="1" snapshot_id="1003" category="Version" event_date="2008-11-09 13:58:00.00" created_at="2008-11-09 13:58:00.00" description="" event_data="[null]"/>
+
+</dataset>
diff --git a/sonar-batch/src/test/resources/org/sonar/batch/deprecated/components/PastSnapshotFinderByVersionTest/shared.xml b/sonar-batch/src/test/resources/org/sonar/batch/deprecated/components/PastSnapshotFinderByVersionTest/shared.xml
new file mode 100644 (file)
index 0000000..289a362
--- /dev/null
@@ -0,0 +1,42 @@
+<dataset>
+
+  <projects long_name="[null]" id="1" scope="PRJ" qualifier="TRK" kee="project" name="project"
+            root_id="[null]"
+            description="[null]"
+            enabled="true" language="java" copy_resource_id="[null]" person_id="[null]"/>
+
+
+  <!-- version 1.1-SNAPSHOT -->
+  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1000"
+             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
+             scope="PRJ" qualifier="TRK" created_at="1225544280000" build_date="1225544280000" version="1.1-SNAPSHOT" path=""
+             status="P" islast="false" depth="0" />
+
+
+  <!-- version 1.1-SNAPSHOT -->
+  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1003"
+             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
+             scope="PRJ" qualifier="TRK" created_at="1225630680000" build_date="1225630680000" version="1.1-SNAPSHOT" path=""
+             status="P" islast="true" depth="0" />
+
+
+  <!-- unprocessed version 1.1 (to ignore) -->
+  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1006"
+             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
+             scope="PRJ" qualifier="TRK" created_at="1225717080000" build_date="1225717080000" version="1.1" path=""
+             status="U" islast="false" depth="0" />
+
+
+  <!-- version 1.1 -->
+  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1009"
+             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
+             scope="PRJ" qualifier="TRK" created_at="1225803480000" build_date="1225803480000" version="1.1" path=""
+             status="P" islast="false" depth="0" />
+
+  <!-- current analysis -->
+  <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="1010"
+             project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
+             scope="PRJ" qualifier="TRK" created_at="1225889880000" build_date="1225889880000" version="1.2-SNAPSHOT" path=""
+             status="U" islast="false" depth="0" />
+
+</dataset>
diff --git a/sonar-batch/src/test/resources/org/sonar/batch/deprecated/components/PeriodsDefinitionTest/shared.xml b/sonar-batch/src/test/resources/org/sonar/batch/deprecated/components/PeriodsDefinitionTest/shared.xml
new file mode 100644 (file)
index 0000000..c8796e2
--- /dev/null
@@ -0,0 +1,12 @@
+<dataset>
+
+  <projects long_name="[null]" id="1" scope="PRJ" kee="my:project" qualifier="LIB" name="my project as lib"
+            root_id="[null]" description="[null]" enabled="true"  language="java" copy_resource_id="[null]" person_id="[null]"/>
+
+  <projects long_name="[null]" id="2" scope="PRJ" kee="my:project" qualifier="TRK" name="my project"
+            root_id="[null]" description="[null]" enabled="true"  language="java" copy_resource_id="[null]" person_id="[null]"/>
+
+  <projects long_name="[null]" id="3" scope="DIR" kee="my:project:path/to/dir" qualifier="TRK" name="my dir"
+            root_id="2" description="[null]" enabled="true"  language="java" copy_resource_id="[null]" person_id="[null]"/>
+
+</dataset>
index bed6ddbad3dda1bbfff05ddcbc99053fa78ed06d..e168b6bc85da42e6158694698560cb744fe8e090 100644 (file)
@@ -31,7 +31,7 @@
             enabled="true" language="[null]" copy_resource_id="[null]" person_id="[null]" path="src/main/java/org" deprecated_kee="[null]" />
 
   <projects id="1006" scope="FIL" qualifier="FIL" kee="b1:src/main/java/org/Foo.java" root_id="1004"
-            name="src/main/java/org/Foo.java" long_name="src/main/java/org/Foo.java" description="[null]"
+            name="Foo.java" long_name="src/main/java/org/Foo.java" description="[null]"
             enabled="true" language="[null]" copy_resource_id="[null]" person_id="[null]" path="src/main/java/org/Foo.java" deprecated_kee="[null]" />
 
   <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="3001" project_id="1001" root_project_id="1001" parent_snapshot_id="[null]"  root_snapshot_id="[null]"
index 86b94e2762207b52eac7f74b8fa6527570a50c39..f475284edcbc9d38328f3abf669183efa814dcd7 100644 (file)
@@ -31,7 +31,7 @@
             enabled="true" language="[null]" copy_resource_id="[null]" person_id="[null]" path="src/main/java/org" deprecated_kee="[null]" />
 
   <projects id="1006" scope="FIL" qualifier="FIL" kee="b1:src/main/java/org/Foo.java" root_id="1004"
-            name="src/main/java/org/Foo.java" long_name="src/main/java/org/Foo.java" description="[null]"
+            name="Foo.java" long_name="src/main/java/org/Foo.java" description="[null]"
             enabled="true" language="[null]" copy_resource_id="[null]" person_id="[null]" path="src/main/java/org/Foo.java" deprecated_kee="[null]" />
 
   <snapshots purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]" period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]" period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]" period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]" id="3001" project_id="1001" root_project_id="1001" parent_snapshot_id="[null]"  root_snapshot_id="[null]"
index 7364e115cf31ed8fbccde869cc3d7dcec9d043c4..6a3ccd830294b643519063cd8d1694092a108cf7 100644 (file)
@@ -19,6 +19,9 @@
  */
 package org.sonar.batch.index;
 
+/**
+ * Used by views !!
+ */
 public interface ResourceCopy {
 
   int getCopyResourceId();
index 650996e9c8d7ee69fbf3efd0676d68302adf79aa..6ec3ca2853600aca4241372775946da5978da52f 100644 (file)
@@ -35,7 +35,7 @@ public class ComponentKeysTest {
     Project project = new Project("my_project");
     assertThat(ComponentKeys.createEffectiveKey(project, project)).isEqualTo("my_project");
 
-    Directory dir = Directory.create("src/org/foo", "org/foo");
+    Directory dir = Directory.create("src/org/foo");
     assertThat(ComponentKeys.createEffectiveKey(project, dir)).isEqualTo("my_project:src/org/foo");
 
     Library library = new Library("junit:junit", "4.7");
index de50b2ceb5a393eff7c3c1cf4776ee38c0ed3dab..ef2644a5b866cd62cc9c4bbe2b83329181560a9d 100644 (file)
@@ -34,7 +34,7 @@ public class ResourceComponentTest {
 
   @Before
   public void prepare() {
-    file = new File("foo.c").setEffectiveKey("myproject:path/to/foo.c");
+    file = File.create("foo.c").setEffectiveKey("myproject:path/to/foo.c");
     file.setKey("path/to/foo.c");
   }
 
@@ -67,7 +67,7 @@ public class ResourceComponentTest {
   @Test
   public void effective_key_should_be_set() {
     try {
-      File file = new File("foo.c");
+      File file = File.create("foo.c");
       new ResourceComponent(file);
       fail();
     } catch (IllegalArgumentException e) {
index f453c1e65799de82c328769bb46bbbaa73591d16..137437fae4f813754c3acbdfcac83c5ac2627308 100644 (file)
@@ -22,7 +22,6 @@ package org.sonar.api.batch;
 import org.sonar.api.resources.Language;
 import org.sonar.api.resources.Project;
 import org.sonar.api.resources.ProjectFileSystem;
-import org.sonar.api.resources.Qualifiers;
 import org.sonar.api.resources.Resource;
 
 import java.io.File;
@@ -66,14 +65,7 @@ public abstract class AbstractSourceImporter implements Sensor {
   }
 
   protected Resource createResource(File file, List<File> sourceDirs, boolean unitTest) {
-    org.sonar.api.resources.File resource = org.sonar.api.resources.File.fromIOFile(file, sourceDirs);
-    if (resource != null) {
-      resource.setLanguage(language);
-      if (unitTest) {
-        resource.setQualifier(Qualifiers.UNIT_TEST_FILE);
-      }
-    }
-    return resource;
+    return null;
   }
 
   protected boolean isEnabled(Project project) {
index 1521ca67b52aad2d43ee947bd4202a7030da58b5..4cc3bda88721264695e476838ccf936e5ddfff2e 100644 (file)
@@ -45,8 +45,8 @@ public class NoSonarFilterTest {
   @Before
   public void prepare() {
     when(chain.accept(isA(Issue.class))).thenReturn(true);
-    javaFile = new File("org.foo.Bar");
-    javaFile.setEffectiveKey("struts:org.apache.Action");
+    javaFile = File.create("org/foo/Bar.java");
+    javaFile.setEffectiveKey("struts:org/foo/Bar.java");
     when(sonarIndex.getResource(javaFile)).thenReturn(javaFile);
   }
 
@@ -58,7 +58,7 @@ public class NoSonarFilterTest {
     filter.addResource(javaFile, noSonarLines);
 
     Issue issue = mock(Issue.class);
-    when(issue.componentKey()).thenReturn("struts:org.apache.Action");
+    when(issue.componentKey()).thenReturn("struts:org/foo/Bar.java");
     when(issue.ruleKey()).thenReturn(RuleKey.of("squid", "Foo"));
 
     // violation on class
index f7b2c06227faf0ef9ad8b217d2f9fa114474c1c0..14699e354f48b79c2b841a59b96d806b9ae422a6 100644 (file)
@@ -20,6 +20,7 @@
 package org.sonar.api;
 
 import org.sonar.api.batch.AnalysisMode;
+import org.sonar.api.batch.fs.FileSystem;
 
 /**
  * Non-exhaustive list of constants of core properties.
@@ -148,7 +149,7 @@ public interface CoreProperties {
   String PROJECT_DESCRIPTION_PROPERTY = "sonar.projectDescription";
 
   /**
-   * To determine value of this property use {@link org.sonar.api.resources.ProjectFileSystem#getSourceCharset()}.
+   * To determine value of this property use {@link FileSystem#encoding()}.
    *
    * @since 2.6
    */
index f1f9670e8d4f88affc785a92aa5108b5f39a1d26..eb6341b5135f1527cbe643a34b8a1b795eb81143 100644 (file)
@@ -25,10 +25,13 @@ import org.sonar.api.measures.Measure;
 import java.util.List;
 
 /**
- * The TimeMachine extension point
+ * The TimeMachine component
  *
  * @since 1.10
+ * @deprecated since 5.1 ability to access previous data from batch side will soon be removed
  */
+@Deprecated
+@RequiresDB
 public interface TimeMachine extends BatchComponent {
 
   /**
index d120c609e4edc2b9e1c57b8ecd38c3a7938733ca..d958aaebc7f5c7fbb9dc6373468311ce8c08d80d 100644 (file)
@@ -20,6 +20,7 @@
 package org.sonar.api.batch.fs;
 
 import java.io.File;
+import java.nio.file.Path;
 
 /**
  * Layer over {@link java.io.File} for directories.
@@ -58,4 +59,10 @@ public interface InputDir extends InputPath {
   @Override
   File file();
 
+  /**
+   * The underlying absolute {@link Path}
+   */
+  @Override
+  Path path();
+
 }
index 2cf8ee33c37b9da0d84081340e010a41966ab190..768986d8c0c915eb5e4861298378cf9d8d5f37bd 100644 (file)
@@ -22,6 +22,7 @@ package org.sonar.api.batch.fs;
 import javax.annotation.CheckForNull;
 
 import java.io.File;
+import java.nio.file.Path;
 
 /**
  * This layer over {@link java.io.File} adds information for code analyzers.
@@ -71,6 +72,12 @@ public interface InputFile extends InputPath {
   @Override
   File file();
 
+  /**
+   * The underlying absolute {@link Path}
+   */
+  @Override
+  Path path();
+
   /**
    * Language, for example "java" or "php". Can be null if indexation of all files is enabled and no language claims to support the file.
    */
index c4d2ae73f16bca7f600eb8a22a9cba138eaed52f..121df157028d0e6a89e092a989f6a9a02a9de133 100644 (file)
@@ -21,6 +21,7 @@ package org.sonar.api.batch.fs;
 
 import java.io.File;
 import java.io.Serializable;
+import java.nio.file.Path;
 
 /**
  * Layer over {@link java.io.File} for files or directories.
@@ -49,4 +50,11 @@ public interface InputPath extends Serializable {
    */
   File file();
 
+  /**
+   * @see InputFile#path()
+   * @see InputDir#path()
+   * @since 5.1
+   */
+  Path path();
+
 }
index 88ea160a6a947d220b64089edc8abd3747d54c90..218d00e891ddf855292a5b6477e08b017b926a16 100644 (file)
@@ -26,6 +26,7 @@ import org.sonar.api.scan.filesystem.PathResolver;
 import org.sonar.api.utils.PathUtils;
 
 import java.io.File;
+import java.nio.file.Path;
 import java.util.Arrays;
 import java.util.Collections;
 
@@ -35,9 +36,9 @@ import java.util.Collections;
 class AbsolutePathPredicate extends AbstractFilePredicate {
 
   private final String path;
-  private final File baseDir;
+  private final Path baseDir;
 
-  AbsolutePathPredicate(String path, File baseDir) {
+  AbsolutePathPredicate(String path, Path baseDir) {
     this.baseDir = baseDir;
     this.path = PathUtils.sanitize(path);
   }
@@ -49,7 +50,7 @@ class AbsolutePathPredicate extends AbstractFilePredicate {
 
   @Override
   public Iterable<InputFile> get(Index index) {
-    String relative = PathUtils.sanitize(new PathResolver().relativePath(baseDir, new File(path)));
+    String relative = PathUtils.sanitize(new PathResolver().relativePath(baseDir.toFile(), new File(path)));
     if (relative == null) {
       return Collections.<InputFile>emptyList();
     }
index 67bcc0b0bd37fe2793aa9c9dff83893109dbafac..7d3d34f764211ce052cd9f02bd639d788bcade41 100644 (file)
@@ -24,6 +24,7 @@ import org.sonar.api.batch.fs.FilePredicates;
 import org.sonar.api.batch.fs.InputFile;
 
 import java.io.File;
+import java.nio.file.Path;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
@@ -36,12 +37,12 @@ import java.util.List;
  */
 public class DefaultFilePredicates implements FilePredicates {
 
-  private final File baseDir;
+  private final Path baseDir;
 
   /**
    * Client code should use {@link org.sonar.api.batch.fs.FileSystem#predicates()} to get an instance
    */
-  DefaultFilePredicates(File baseDir) {
+  DefaultFilePredicates(Path baseDir) {
     this.baseDir = baseDir;
   }
 
index 27a00412dd94269017755f538ce99ef95e1a0bf8..236ecb7d42424a287161018023ef0b838bada679 100644 (file)
@@ -36,6 +36,7 @@ import javax.annotation.Nullable;
 import java.io.File;
 import java.io.IOException;
 import java.nio.charset.Charset;
+import java.nio.file.Path;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.HashMap;
@@ -51,28 +52,28 @@ public class DefaultFileSystem implements FileSystem {
 
   private final Cache cache;
   private final SortedSet<String> languages = new TreeSet<String>();
-  private final File baseDir;
-  private File workDir;
+  private final Path baseDir;
+  private Path workDir;
   private Charset encoding;
   private final FilePredicates predicates;
 
   /**
    * Only for testing
    */
-  public DefaultFileSystem(File baseDir) {
+  public DefaultFileSystem(Path baseDir) {
     this(baseDir, new MapCache());
   }
 
-  protected DefaultFileSystem(File baseDir, Cache cache) {
+  protected DefaultFileSystem(Path baseDir, Cache cache) {
     Preconditions.checkNotNull(baseDir, "Base directory can't be null");
-    this.baseDir = baseDir.getAbsoluteFile();
+    this.baseDir = baseDir.toAbsolutePath().normalize();
     this.cache = cache;
     this.predicates = new DefaultFilePredicates(baseDir);
   }
 
   @Override
   public File baseDir() {
-    return baseDir;
+    return baseDir.toFile();
   }
 
   public DefaultFileSystem setEncoding(@Nullable Charset e) {
@@ -90,13 +91,13 @@ public class DefaultFileSystem implements FileSystem {
   }
 
   public DefaultFileSystem setWorkDir(File d) {
-    this.workDir = d.getAbsoluteFile();
+    this.workDir = d.getAbsoluteFile().toPath().normalize();
     return this;
   }
 
   @Override
   public File workDir() {
-    return workDir;
+    return workDir.toFile();
   }
 
   @Override
@@ -151,7 +152,7 @@ public class DefaultFileSystem implements FileSystem {
   @Override
   public InputDir inputDir(File dir) {
     doPreloadFiles();
-    String relativePath = PathUtils.sanitize(new PathResolver().relativePath(baseDir, dir));
+    String relativePath = PathUtils.sanitize(new PathResolver().relativePath(baseDir.toFile(), dir));
     if (relativePath == null) {
       return null;
     }
@@ -162,7 +163,11 @@ public class DefaultFileSystem implements FileSystem {
    * Adds InputFile to the list and registers its language, if present.
    * Synchronized because PersistIt Exchange is not concurrent
    */
-  public synchronized DefaultFileSystem add(InputFile inputFile) {
+  public synchronized DefaultFileSystem add(DefaultInputFile inputFile) {
+    if (this.baseDir == null) {
+      throw new IllegalStateException("Please set basedir on filesystem before adding files");
+    }
+    inputFile.setModuleBaseDir(this.baseDir);
     cache.add(inputFile);
     if (inputFile.language() != null) {
       languages.add(inputFile.language());
@@ -174,7 +179,11 @@ public class DefaultFileSystem implements FileSystem {
    * Adds InputDir to the list.
    * Synchronized because PersistIt Exchange is not concurrent
    */
-  public synchronized DefaultFileSystem add(InputDir inputDir) {
+  public synchronized DefaultFileSystem add(DefaultInputDir inputDir) {
+    if (this.baseDir == null) {
+      throw new IllegalStateException("Please set basedir on filesystem before adding dirs");
+    }
+    inputDir.setModuleBaseDir(this.baseDir);
     cache.add(inputDir);
     return this;
   }
index 71026d52d3309df9433d37b0d7b5632ab0a81ffe..834c6e9c8107ad3d65e0171e0566e0eca5960aaa 100644 (file)
@@ -24,6 +24,7 @@ import org.sonar.api.utils.PathUtils;
 
 import java.io.File;
 import java.io.Serializable;
+import java.nio.file.Path;
 
 /**
  * @since 4.5
@@ -32,7 +33,7 @@ public class DefaultInputDir implements InputDir, Serializable {
 
   private final String relativePath;
   private final String moduleKey;
-  private String absolutePath;
+  private Path moduleBaseDir;
 
   public DefaultInputDir(String moduleKey, String relativePath) {
     this.moduleKey = moduleKey;
@@ -46,15 +47,20 @@ public class DefaultInputDir implements InputDir, Serializable {
 
   @Override
   public String absolutePath() {
-    return absolutePath;
+    return PathUtils.sanitize(path().toString());
   }
 
   @Override
   public File file() {
-    if (absolutePath == null) {
-      throw new IllegalStateException("Can not return the java.io.File because absolute path is not set (see method setFile(java.io.File))");
+    return path().toFile();
+  }
+
+  @Override
+  public Path path() {
+    if (moduleBaseDir == null) {
+      throw new IllegalStateException("Can not return the java.nio.file.Path because module baseDir is not set (see method setModuleBaseDir(java.io.File))");
     }
-    return new File(absolutePath);
+    return moduleBaseDir.resolve(relativePath);
   }
 
   public String moduleKey() {
@@ -65,13 +71,11 @@ public class DefaultInputDir implements InputDir, Serializable {
     return new StringBuilder().append(moduleKey).append(":").append(relativePath).toString();
   }
 
-  public DefaultInputDir setAbsolutePath(String s) {
-    this.absolutePath = PathUtils.sanitize(s);
-    return this;
-  }
-
-  public DefaultInputDir setFile(File file) {
-    setAbsolutePath(file.getAbsolutePath());
+  /**
+   * For testing purpose. Will be automaticall set when dir is added to {@link DefaultFileSystem}
+   */
+  public DefaultInputDir setModuleBaseDir(Path moduleBaseDir) {
+    this.moduleBaseDir = moduleBaseDir.normalize();
     return this;
   }
 
@@ -95,6 +99,6 @@ public class DefaultInputDir implements InputDir, Serializable {
 
   @Override
   public String toString() {
-    return "[moduleKey=" + moduleKey + ", relative=" + relativePath + ", abs=" + absolutePath + "]";
+    return "[moduleKey=" + moduleKey + ", relative=" + relativePath + ", basedir=" + moduleBaseDir + "]";
   }
 }
index 393e69331fac433b53e550a4c4d56e68ecc92e2e..cebd7c410f81e3f7b2c97d6d84653a75fdff0552 100644 (file)
@@ -27,6 +27,8 @@ import javax.annotation.Nullable;
 
 import java.io.File;
 import java.io.Serializable;
+import java.nio.charset.Charset;
+import java.nio.file.Path;
 
 /**
  * @since 4.2
@@ -35,17 +37,12 @@ public class DefaultInputFile implements InputFile, Serializable {
 
   private final String relativePath;
   private final String moduleKey;
-  private String absolutePath;
+  protected Path moduleBaseDir;
   private String language;
   private Type type = Type.MAIN;
   private Status status;
-  private String hash;
   private int lines;
-  private int nonBlankLines;
-  private String encoding;
-  private long[] originalLineOffsets;
-  private byte[][] lineHashes;
-  private boolean empty;
+  private Charset charset;
 
   public DefaultInputFile(String moduleKey, String relativePath) {
     this.moduleKey = moduleKey;
@@ -59,15 +56,20 @@ public class DefaultInputFile implements InputFile, Serializable {
 
   @Override
   public String absolutePath() {
-    return absolutePath;
+    return PathUtils.sanitize(path().toString());
   }
 
   @Override
   public File file() {
-    if (absolutePath == null) {
-      throw new IllegalStateException("Can not return the java.io.File because absolute path is not set (see method setFile(java.io.File))");
+    return path().toFile();
+  }
+
+  @Override
+  public Path path() {
+    if (moduleBaseDir == null) {
+      throw new IllegalStateException("Can not return the java.nio.file.Path because module baseDir is not set (see method setModuleBaseDir(java.io.File))");
     }
-    return new File(absolutePath);
+    return moduleBaseDir.resolve(relativePath);
   }
 
   @CheckForNull
@@ -89,22 +91,11 @@ public class DefaultInputFile implements InputFile, Serializable {
     return status;
   }
 
-  /**
-   * Digest hash of the file.
-   */
-  public String hash() {
-    return hash;
-  }
-
   @Override
   public int lines() {
     return lines;
   }
 
-  public int nonBlankLines() {
-    return nonBlankLines;
-  }
-
   /**
    * Component key.
    */
@@ -116,20 +107,15 @@ public class DefaultInputFile implements InputFile, Serializable {
     return moduleKey;
   }
 
-  public String encoding() {
-    return encoding;
+  public Charset charset() {
+    return charset;
   }
 
-  public long[] originalLineOffsets() {
-    return originalLineOffsets;
-  }
-
-  public byte[][] lineHashes() {
-    return lineHashes;
-  }
-
-  public DefaultInputFile setAbsolutePath(String s) {
-    this.absolutePath = PathUtils.sanitize(s);
+  /**
+   * For testing purpose. Will be automaticall set when file is added to {@link DefaultFileSystem}
+   */
+  public DefaultInputFile setModuleBaseDir(Path moduleBaseDir) {
+    this.moduleBaseDir = moduleBaseDir.normalize();
     return this;
   }
 
@@ -138,11 +124,6 @@ public class DefaultInputFile implements InputFile, Serializable {
     return this;
   }
 
-  public DefaultInputFile setFile(File file) {
-    setAbsolutePath(file.getAbsolutePath());
-    return this;
-  }
-
   public DefaultInputFile setType(Type type) {
     this.type = type;
     return this;
@@ -153,42 +134,13 @@ public class DefaultInputFile implements InputFile, Serializable {
     return this;
   }
 
-  public DefaultInputFile setHash(String hash) {
-    this.hash = hash;
-    return this;
-  }
-
   public DefaultInputFile setLines(int lines) {
     this.lines = lines;
     return this;
   }
 
-  public DefaultInputFile setNonBlankLines(int nonBlankLines) {
-    this.nonBlankLines = nonBlankLines;
-    return this;
-  }
-
-  public DefaultInputFile setEncoding(String encoding) {
-    this.encoding = encoding;
-    return this;
-  }
-
-  public DefaultInputFile setOriginalLineOffsets(long[] originalLineOffsets) {
-    this.originalLineOffsets = originalLineOffsets;
-    return this;
-  }
-
-  public DefaultInputFile setLineHashes(byte[][] lineHashes) {
-    this.lineHashes = lineHashes;
-    return this;
-  }
-
-  public boolean isEmpty() {
-    return this.empty;
-  }
-
-  public DefaultInputFile setEmpty(boolean empty) {
-    this.empty = empty;
+  public DefaultInputFile setCharset(Charset charset) {
+    this.charset = charset;
     return this;
   }
 
@@ -212,7 +164,7 @@ public class DefaultInputFile implements InputFile, Serializable {
 
   @Override
   public String toString() {
-    return "[moduleKey=" + moduleKey + ", relative=" + relativePath + ", abs=" + absolutePath + "]";
+    return "[moduleKey=" + moduleKey + ", relative=" + relativePath + ", basedir=" + moduleBaseDir + "]";
   }
 
 }
index a599b6ff6561c96bbcc28c9251a1da2c4bdfab05..f70d4a75eeaa7e539803c21b5c6e8d282e0578fa 100644 (file)
@@ -19,8 +19,6 @@
  */
 package org.sonar.api.batch.fs.internal;
 
-import org.sonar.api.utils.PathUtils;
-
 import java.io.BufferedInputStream;
 import java.io.File;
 import java.io.FileInputStream;
@@ -32,11 +30,6 @@ import java.io.InputStream;
  */
 public class DeprecatedDefaultInputFile extends DefaultInputFile implements org.sonar.api.resources.InputFile {
 
-  private String basedir;
-  private String deprecatedKey;
-  private String sourceDirAbsolutePath;
-  private String pathRelativeToSourceDir;
-
   public DeprecatedDefaultInputFile(String moduleKey, String relativePath) {
     super(moduleKey, relativePath);
   }
@@ -47,12 +40,7 @@ public class DeprecatedDefaultInputFile extends DefaultInputFile implements org.
   @Deprecated
   @Override
   public File getFileBaseDir() {
-    return new File(basedir);
-  }
-
-  public DeprecatedDefaultInputFile setBasedir(File basedir) {
-    this.basedir = PathUtils.sanitize(basedir.getAbsolutePath());
-    return this;
+    return moduleBaseDir.toFile();
   }
 
   /**
@@ -70,44 +58,7 @@ public class DeprecatedDefaultInputFile extends DefaultInputFile implements org.
   @Deprecated
   @Override
   public String getRelativePath() {
-    return pathRelativeToSourceDir;
-  }
-
-  /**
-   * Key used before version 4.2. It can be different than {@link #key} on Java files.
-   */
-  public String deprecatedKey() {
-    return deprecatedKey;
-  }
-
-  public DeprecatedDefaultInputFile setDeprecatedKey(String s) {
-    this.deprecatedKey = s;
-    return this;
-  }
-
-  /**
-   * Used only for backward-compatibility. Meaningless since version 4.2.
-   */
-  public String sourceDirAbsolutePath() {
-    return sourceDirAbsolutePath;
-  }
-
-  public DeprecatedDefaultInputFile setSourceDirAbsolutePath(String s) {
-    this.sourceDirAbsolutePath = PathUtils.sanitize(s);
-    return this;
-  }
-
-  /**
-   * Used only for backward-compatibility. Meaningless since version 4.2.
-   */
-
-  public String pathRelativeToSourceDir() {
-    return pathRelativeToSourceDir;
-  }
-
-  public DeprecatedDefaultInputFile setPathRelativeToSourceDir(String s) {
-    this.pathRelativeToSourceDir = PathUtils.sanitize(s);
-    return this;
+    return relativePath();
   }
 
   @Override
index fe6edc0b2cdf3415f06b982cd5eb03eb350865ea..f11f2f432a871f5dc4983f609a7395f1b1097bdf 100644 (file)
@@ -21,7 +21,7 @@ package org.sonar.api.resources;
 
 import org.apache.commons.lang.StringUtils;
 import org.apache.commons.lang.builder.ToStringBuilder;
-import org.sonar.api.batch.SensorContext;
+import org.sonar.api.batch.fs.FileSystem;
 import org.sonar.api.scan.filesystem.PathResolver;
 import org.sonar.api.utils.WildcardPattern;
 
@@ -39,22 +39,6 @@ public class Directory extends Resource {
     // Used by factory
   }
 
-  /**
-   * @deprecated since 4.2 use {@link #fromIOFile(java.io.File, Project)}
-   */
-  @Deprecated
-  public Directory(String relativePathFromSourceDir) {
-    this(relativePathFromSourceDir, null);
-  }
-
-  /**
-   * @deprecated since 4.2 use {@link #fromIOFile(java.io.File, Project)}
-   */
-  @Deprecated
-  public Directory(String relativePathFromSourceDir, Language language) {
-    setDeprecatedKey(parseKey(relativePathFromSourceDir));
-  }
-
   @Override
   public String getName() {
     return getKey();
@@ -109,17 +93,13 @@ public class Directory extends Resource {
   }
 
   /**
-   * Creates a {@link Directory} from an absolute {@link java.io.File} and a module.
-   * The returned {@link Directory} can be then passed for example to
-   * {@link SensorContext#saveMeasure(Resource, org.sonar.api.measures.Measure)}.
-   * @param dir absolute path to a directory
-   * @param module
-   * @return null if the directory is not under module basedir.
    * @since 4.2
+   * @deprecated since 5.1 use {@link FileSystem#inputDir(java.io.File)}
    */
+  @Deprecated
   @CheckForNull
   public static Directory fromIOFile(java.io.File dir, Project module) {
-    String relativePathFromBasedir = new PathResolver().relativePath(module.getFileSystem().getBasedir(), dir);
+    String relativePathFromBasedir = new PathResolver().relativePath(module.getBaseDir(), dir);
     if (relativePathFromBasedir != null) {
       return Directory.create(relativePathFromBasedir);
     }
@@ -127,10 +107,10 @@ public class Directory extends Resource {
   }
 
   /**
-   * Create a Directory that is partially initialized. But that's enough to call for example
-   * {@link SensorContext#saveMeasure(Resource, org.sonar.api.measures.Measure)} when resources are already indexed.
    * Internal use only.
+   * @deprecated since 5.1 use {@link FileSystem#inputDir(java.io.File)}
    */
+  @Deprecated
   public static Directory create(String relativePathFromBaseDir) {
     Directory d = new Directory();
     String normalizedPath = normalize(relativePathFromBaseDir);
@@ -139,22 +119,10 @@ public class Directory extends Resource {
     return d;
   }
 
-  /**
-   * Create a directory that is fully initialized. Use for indexing resources.
-   * Internal use only.
-   * @since 4.2
-   */
-  public static Directory create(String relativePathFromBaseDir, String relativePathFromSourceDir) {
-    Directory d = Directory.create(relativePathFromBaseDir);
-    d.setDeprecatedKey(parseKey(relativePathFromSourceDir));
-    return d;
-  }
-
   @Override
   public String toString() {
     return new ToStringBuilder(this)
       .append("key", getKey())
-      .append("deprecatedKey", getDeprecatedKey())
       .append("path", getPath())
       .toString();
   }
index 707116c728db8f6ca5c1e1f551b4b8ddd5f401a6..afe82db8a845ced5683ddae8f35c0c3beb600468 100644 (file)
@@ -28,8 +28,6 @@ import org.sonar.api.utils.WildcardPattern;
 
 import javax.annotation.CheckForNull;
 
-import java.util.List;
-
 /**
  * This class is an implementation of a resource of type FILE
  *
@@ -39,7 +37,6 @@ public class File extends Resource {
 
   public static final String SCOPE = Scopes.FILE;
 
-  private String directoryDeprecatedKey;
   private String filename;
   private Language language;
   private Directory parent;
@@ -49,65 +46,6 @@ public class File extends Resource {
     // Used by factory method
   }
 
-  /**
-   * File in project. Key is the path relative to project source directories. It is not the absolute path and it does not include the path
-   * to source directories. Example : <code>new File("org/sonar/foo.sql")</code>. The absolute path may be
-   * c:/myproject/src/main/sql/org/sonar/foo.sql. Project root is c:/myproject and source dir is src/main/sql.
-   * @deprecated since 4.2 use {@link #fromIOFile(java.io.File, Project)}
-   */
-  @Deprecated
-  public File(String relativePathFromSourceDir) {
-    if (relativePathFromSourceDir == null) {
-      throw new IllegalArgumentException("File key is null");
-    }
-    String realKey = parseKey(relativePathFromSourceDir);
-    if (realKey.indexOf(Directory.SEPARATOR) >= 0) {
-      this.directoryDeprecatedKey = Directory.parseKey(StringUtils.substringBeforeLast(relativePathFromSourceDir, Directory.SEPARATOR));
-      this.filename = StringUtils.substringAfterLast(realKey, Directory.SEPARATOR);
-      realKey = new StringBuilder().append(this.directoryDeprecatedKey).append(Directory.SEPARATOR).append(filename).toString();
-
-    } else {
-      this.filename = relativePathFromSourceDir;
-    }
-    setDeprecatedKey(realKey);
-  }
-
-  /**
-   * Creates a file from its containing directory and name
-   * @deprecated since 4.2 use {@link #fromIOFile(java.io.File, Project)}
-   */
-  @Deprecated
-  public File(String relativeDirectoryPathFromSourceDir, String filename) {
-    this.filename = StringUtils.trim(filename);
-    if (StringUtils.isBlank(relativeDirectoryPathFromSourceDir)) {
-      setDeprecatedKey(filename);
-
-    } else {
-      this.directoryDeprecatedKey = Directory.parseKey(relativeDirectoryPathFromSourceDir);
-      setDeprecatedKey(new StringBuilder().append(directoryDeprecatedKey).append(Directory.SEPARATOR).append(this.filename).toString());
-    }
-  }
-
-  /**
-   * Creates a File from its language and its key
-   * @deprecated since 4.2 use {@link #fromIOFile(java.io.File, Project)}
-   */
-  @Deprecated
-  public File(Language language, String relativePathFromSourceDir) {
-    this(relativePathFromSourceDir);
-    this.language = language;
-  }
-
-  /**
-   * Creates a File from language, directory and filename
-   * @deprecated since 4.2 use {@link #fromIOFile(java.io.File, Project)}
-   */
-  @Deprecated
-  public File(Language language, String relativeDirectoryPathFromSourceDir, String filename) {
-    this(relativeDirectoryPathFromSourceDir, filename);
-    this.language = language;
-  }
-
   /**
    * {@inheritDoc}
    *
@@ -115,9 +53,6 @@ public class File extends Resource {
    */
   @Override
   public Directory getParent() {
-    if (parent == null) {
-      parent = new Directory(directoryDeprecatedKey);
-    }
     return parent;
   }
 
@@ -142,20 +77,6 @@ public class File extends Resource {
     return matcher.match(getKey());
   }
 
-  /**
-   * Creates a File from an io.file and a list of sources directories
-   * @deprecated since 4.2 use {@link #fromIOFile(java.io.File, Project)}
-   */
-  @Deprecated
-  @CheckForNull
-  public static File fromIOFile(java.io.File file, List<java.io.File> sourceDirs) {
-    PathResolver.RelativePath relativePath = new PathResolver().relativePath(sourceDirs, file);
-    if (relativePath != null) {
-      return new File(relativePath.path());
-    }
-    return null;
-  }
-
   /**
    * Creates a {@link File} from an absolute {@link java.io.File} and a module.
    * The returned {@link File} can be then passed for example to
@@ -168,7 +89,7 @@ public class File extends Resource {
   @Deprecated
   @CheckForNull
   public static File fromIOFile(java.io.File file, Project module) {
-    String relativePathFromBasedir = new PathResolver().relativePath(module.getFileSystem().getBasedir(), file);
+    String relativePathFromBasedir = new PathResolver().relativePath(module.getBaseDir(), file);
     if (relativePathFromBasedir != null) {
       return File.create(relativePathFromBasedir);
     }
@@ -243,11 +164,10 @@ public class File extends Resource {
   }
 
   /**
-   * Create a File that is partially initialized. But that's enough to call for example
-   * {@link SensorContext#saveMeasure(Resource, org.sonar.api.measures.Measure)} when resources are already indexed.
    * Internal use only.
-   * @since 4.2
+   * @deprecated since 5.1 use {@link FileSystem#inputFile(org.sonar.api.batch.fs.FilePredicate)}
    */
+  @Deprecated
   public static File create(String relativePathFromBasedir) {
     File file = new File();
     String normalizedPath = normalize(relativePathFromBasedir);
@@ -256,34 +176,26 @@ public class File extends Resource {
     String directoryPath;
     if (normalizedPath != null && normalizedPath.contains(Directory.SEPARATOR)) {
       directoryPath = StringUtils.substringBeforeLast(normalizedPath, Directory.SEPARATOR);
+      file.filename = StringUtils.substringAfterLast(normalizedPath, Directory.SEPARATOR);
     } else {
       directoryPath = Directory.SEPARATOR;
+      file.filename = normalizedPath;
     }
     file.parent = Directory.create(directoryPath);
     return file;
   }
 
   /**
-   * Create a file that is fully initialized. Use for indexing resources.
    * Internal use only.
-   * @since 4.2
+   * @deprecated since 5.1 use {@link FileSystem#inputFile(org.sonar.api.batch.fs.FilePredicate)}
    */
-  public static File create(String relativePathFromBasedir, String relativePathFromSourceDir, Language language, boolean unitTest) {
+  @Deprecated
+  public static File create(String relativePathFromBasedir, Language language, boolean unitTest) {
     File file = create(relativePathFromBasedir);
     file.setLanguage(language);
-    if (relativePathFromSourceDir.contains(Directory.SEPARATOR)) {
-      file.filename = StringUtils.substringAfterLast(relativePathFromSourceDir, Directory.SEPARATOR);
-      file.directoryDeprecatedKey = Directory.parseKey(StringUtils.substringBeforeLast(relativePathFromSourceDir, Directory.SEPARATOR));
-      file.setDeprecatedKey(file.directoryDeprecatedKey + Directory.SEPARATOR + file.filename);
-    } else {
-      file.filename = relativePathFromSourceDir;
-      file.directoryDeprecatedKey = Directory.ROOT;
-      file.setDeprecatedKey(file.filename);
-    }
     if (unitTest) {
       file.setQualifier(Qualifiers.UNIT_TEST_FILE);
     }
-    file.parent.setDeprecatedKey(file.directoryDeprecatedKey);
     return file;
   }
 
@@ -291,9 +203,7 @@ public class File extends Resource {
   public String toString() {
     return new ToStringBuilder(this)
       .append("key", getKey())
-      .append("deprecatedKey", getDeprecatedKey())
       .append("path", getPath())
-      .append("dir", directoryDeprecatedKey)
       .append("filename", filename)
       .append("language", language)
       .toString();
index da5cc35681bfac7a3567b9ee3d6a0ab228ba3b08..607d2ea96406004e460b123a4516ab7ab1fe70f6 100644 (file)
@@ -29,7 +29,6 @@ public final class Library extends Resource {
 
   public Library(String key, String version) {
     setKey(key);
-    setDeprecatedKey(key);
     this.version = version;
   }
 
index 950eb020e2d96ba4bddbbebfc53541706ceda69e..466902b61c9bbaab5d941511a9bfe7ccae4478f5 100644 (file)
@@ -23,6 +23,7 @@ import org.apache.commons.lang.StringUtils;
 import org.apache.commons.lang.builder.ToStringBuilder;
 import org.apache.maven.project.MavenProject;
 import org.sonar.api.CoreProperties;
+import org.sonar.api.batch.fs.FileSystem;
 import org.sonar.api.component.Component;
 import org.sonar.api.config.Settings;
 
@@ -85,13 +86,15 @@ public class Project extends Resource implements Component {
   private String analysisVersion;
   private Settings settings;
 
+  // For internal use
+  private java.io.File baseDir;
+
   // modules tree
   private Project parent;
   private List<Project> modules = new ArrayList<Project>();
 
   public Project(String key) {
     setKey(key);
-    setDeprecatedKey(key);
     setEffectiveKey(key);
   }
 
@@ -103,7 +106,6 @@ public class Project extends Resource implements Component {
       setKey(key);
       this.name = name;
     }
-    setDeprecatedKey(getKey());
     setEffectiveKey(getKey());
     this.branch = branch;
   }
@@ -373,7 +375,7 @@ public class Project extends Resource implements Component {
 
   /**
    * Note: it's better to get a reference on ProjectFileSystem as an IoC dependency (constructor parameter)
-   * @deprecated replaced by {@link org.sonar.api.scan.filesystem.ModuleFileSystem} in 3.5
+   * @deprecated since 3.5 use {@link FileSystem} instead
    */
   @Deprecated
   public ProjectFileSystem getFileSystem() {
@@ -458,4 +460,13 @@ public class Project extends Resource implements Component {
   public String qualifier() {
     return getQualifier();
   }
+
+  // For internal use
+  public void setBaseDir(java.io.File baseDir) {
+    this.baseDir = baseDir;
+  }
+
+  java.io.File getBaseDir() {
+    return baseDir;
+  }
 }
index ea393f5805c211f9a4933a672232c8203fce0ed9..3aad72f7531ae13af20e3106f0bea61f08039c69 100644 (file)
@@ -29,7 +29,7 @@ import java.util.List;
 
 /**
  * @since 1.10
- * @deprecated since 3.5 replaced by {@link org.sonar.api.scan.filesystem.ModuleFileSystem}
+ * @deprecated since 3.5 replaced by {@link FileSystem}
  */
 @Deprecated
 public interface ProjectFileSystem extends BatchComponent {
index 4f655cf5b510c22b796dc3a1dc63823a9b8e0e5b..4634708b4a8d599936f66e605ac9f136e1c681f8 100644 (file)
@@ -129,8 +129,6 @@ public abstract class Resource implements Serializable {
 
   private String uuid;
 
-  private String deprecatedKey;
-
   private String path;
 
   private String effectiveKey;
@@ -163,21 +161,6 @@ public abstract class Resource implements Serializable {
     this.uuid = s;
   }
 
-  /**
-   * @return the resource deprecated key. Should not be used except to deal with backward compatibility.
-   * @since 4.2
-   */
-  public final String getDeprecatedKey() {
-    return deprecatedKey;
-  }
-
-  /**
-   * For internal use only
-   */
-  public void setDeprecatedKey(String s) {
-    this.deprecatedKey = s;
-  }
-
   /**
    * @return the resource name
    */
@@ -321,15 +304,11 @@ public abstract class Resource implements Serializable {
     }
 
     Resource resource = (Resource) o;
-    if (key != null) {
-      return key.equals(resource.key);
-    } else {
-      return resource.key == null && deprecatedKey.equals(resource.deprecatedKey);
-    }
+    return key.equals(resource.key);
   }
 
   @Override
   public int hashCode() {
-    return key != null ? key.hashCode() : deprecatedKey.hashCode();
+    return key.hashCode();
   }
 }
index be5e14bad82e69179cc96c9bf3103a86c21a545a..f80cad292c7110e12d2de85aca19f4c60f204dc9 100644 (file)
@@ -20,6 +20,7 @@
 package org.sonar.api.scan.filesystem;
 
 import org.sonar.api.BatchExtension;
+import org.sonar.api.batch.fs.InputFileFilter;
 
 import java.io.File;
 
@@ -44,10 +45,9 @@ public interface FileSystemFilter extends BatchExtension {
 
     FileType type();
 
-    File relativeDir();
-
     /**
-     * File path relative to source directory. Never return null.
+     * Changed in 5.1 as we don't keep track of relative path to source dir
+     * File path relative to module base directory. Never return null.
      */
     String relativePath();
 
index 5ddb1e79afcef6378030c14dcade9edaa9416905..dd280ef2ab1eb969488ab46b8117e1de1be0bf10 100644 (file)
  */
 package org.sonar.api.task;
 
-
 /**
  * Implement this interface to provide the behavior of a task.
  * @since 3.6
+ * @deprecated since 5.1 all tasks (devcockpit, views) will be moved to server side
  */
+@Deprecated
 public interface Task extends TaskExtension {
 
   void execute();
index 4032034a56c061520ed8b6af6df05b7c7f207475..65d5e05509375f273e8697bc06547dcaf1bd207d 100644 (file)
@@ -23,6 +23,8 @@ package org.sonar.api.task;
  * All the classes implementing this interface can be injected in public constructors of {@link TaskExtension}.
  *
  * @since 3.6
+ * @deprecated since 5.1 all tasks (devcockpit, views) will be moved to server side
  */
+@Deprecated
 public interface TaskComponent {
 }
index 15dbe6cb28f71e04b23a3aff1e7a329b27145f60..fa8fd07f79bd7d0b23711c339dafd92af0c3b38c 100644 (file)
@@ -28,7 +28,9 @@ import java.util.regex.Pattern;
  * Register and describe a {@link TaskExtension}.
  *
  * @since 3.6
+ * @deprecated since 5.1 all tasks (devcockpit, views) will be moved to server side
  */
+@Deprecated
 public class TaskDefinition implements TaskExtension, Comparable<TaskDefinition> {
   static final String KEY_PATTERN = "[a-zA-Z0-9\\-\\_]+";
 
index 7d393d37c2b5cd4f1be3cc8aa12abc629e980361..f389d069dcf3b0e3a78897905b43af733001a8e2 100644 (file)
@@ -25,6 +25,8 @@ import org.sonar.api.Extension;
  * Task extension point
  *
  * @since 3.6
+ * @deprecated since 5.1 all tasks (devcockpit, views) will be moved to server side
  */
+@Deprecated
 public interface TaskExtension extends Extension, TaskComponent {
 }
index a9ae07f0b80894ef0b0f95e1d5c73b4e81598343..4fdabac2ad9ebae9b7435ab209bf7843ad4f9a27 100644 (file)
@@ -45,9 +45,9 @@ public class DefaultFilePredicatesTest {
 
   @Before
   public void before() throws IOException {
-    predicates = new DefaultFilePredicates(temp.newFolder());
+    predicates = new DefaultFilePredicates(temp.newFolder().toPath());
     javaFile = new DefaultInputFile("foo", "src/main/java/struts/Action.java")
-      .setFile(temp.newFile("Action.java"))
+      .setModuleBaseDir(temp.newFolder().toPath())
       .setLanguage("java")
       .setStatus(InputFile.Status.ADDED);
   }
index 6f118683460da1780cc7749e35d460706b47d6a3..6c7a5bd9f0d7f86e278c583a562e7e50d3212d4e 100644 (file)
@@ -45,7 +45,7 @@ public class DefaultFileSystemTest {
   @Before
   public void prepare() throws Exception {
     basedir = temp.newFolder();
-    fs = new DefaultFileSystem(basedir);
+    fs = new DefaultFileSystem(basedir.toPath());
   }
 
   @Test
@@ -81,12 +81,12 @@ public class DefaultFileSystemTest {
   public void files() throws Exception {
     assertThat(fs.inputFiles(fs.predicates().all())).isEmpty();
 
-    fs.add(new DefaultInputFile("foo", "src/Foo.php").setLanguage("php").setFile(temp.newFile()));
-    fs.add(new DefaultInputFile("foo", "src/Bar.java").setLanguage("java").setFile(temp.newFile()));
-    fs.add(new DefaultInputFile("foo", "src/Baz.java").setLanguage("java").setFile(temp.newFile()));
+    fs.add(new DefaultInputFile("foo", "src/Foo.php").setLanguage("php"));
+    fs.add(new DefaultInputFile("foo", "src/Bar.java").setLanguage("java"));
+    fs.add(new DefaultInputFile("foo", "src/Baz.java").setLanguage("java"));
 
     // no language
-    fs.add(new DefaultInputFile("foo", "src/readme.txt").setFile(temp.newFile()));
+    fs.add(new DefaultInputFile("foo", "src/readme.txt"));
 
     assertThat(fs.inputFile(fs.predicates().hasRelativePath("src/Bar.java"))).isNotNull();
     assertThat(fs.inputFile(fs.predicates().hasRelativePath("does/not/exist"))).isNull();
@@ -118,15 +118,15 @@ public class DefaultFileSystemTest {
     thrown.expect(IllegalArgumentException.class);
     thrown.expectMessage("expected one element");
 
-    fs.add(new DefaultInputFile("foo", "src/Bar.java").setLanguage("java").setFile(temp.newFile()));
-    fs.add(new DefaultInputFile("foo", "src/Baz.java").setLanguage("java").setFile(temp.newFile()));
+    fs.add(new DefaultInputFile("foo", "src/Bar.java").setLanguage("java"));
+    fs.add(new DefaultInputFile("foo", "src/Baz.java").setLanguage("java"));
 
     fs.inputFile(fs.predicates().all());
   }
 
   @Test
   public void input_file_supports_non_indexed_predicates() throws Exception {
-    fs.add(new DefaultInputFile("foo", "src/Bar.java").setLanguage("java").setFile(temp.newFile()));
+    fs.add(new DefaultInputFile("foo", "src/Bar.java").setLanguage("java"));
 
     // it would fail if more than one java file
     assertThat(fs.inputFile(fs.predicates().hasLanguage("java"))).isNotNull();
index ce4aa0398979ab7618cf6606add8b3c988155273..3da8d5f023cd574d1e80ddab6b3a48184a072d09 100644 (file)
@@ -34,12 +34,12 @@ public class DefaultInputDirTest {
 
   @Test
   public void test() throws Exception {
-    File dir = temp.newFolder("src");
+    File baseDir = temp.newFolder();
     DefaultInputDir inputDir = new DefaultInputDir("ABCDE", "src")
-      .setFile(dir);
+      .setModuleBaseDir(baseDir.toPath());
 
     assertThat(inputDir.key()).isEqualTo("ABCDE:src");
-    assertThat(inputDir.file().getAbsolutePath()).isEqualTo(dir.getAbsolutePath());
+    assertThat(inputDir.file().getAbsolutePath()).isEqualTo(new File(baseDir, "src").getAbsolutePath());
     assertThat(inputDir.relativePath()).isEqualTo("src");
     assertThat(new File(inputDir.relativePath())).isRelative();
     assertThat(inputDir.absolutePath()).endsWith("src");
@@ -48,13 +48,9 @@ public class DefaultInputDirTest {
 
   @Test
   public void testEqualsAndHashCode() throws Exception {
-    File dir1 = temp.newFolder("src");
-    DefaultInputDir inputDir1 = new DefaultInputDir("ABCDE", "src")
-      .setFile(dir1);
+    DefaultInputDir inputDir1 = new DefaultInputDir("ABCDE", "src");
 
-    File dir2 = temp.newFolder("src2");
-    DefaultInputDir inputDir2 = new DefaultInputDir("ABCDE", "src")
-      .setFile(dir2);
+    DefaultInputDir inputDir2 = new DefaultInputDir("ABCDE", "src");
 
     assertThat(inputDir1.equals(inputDir1)).isTrue();
     assertThat(inputDir1.equals(inputDir2)).isTrue();
@@ -62,7 +58,7 @@ public class DefaultInputDirTest {
 
     assertThat(inputDir1.hashCode()).isEqualTo(63545559);
 
-    assertThat(inputDir1.toString()).contains("[moduleKey=ABCDE, relative=src, abs=");
+    assertThat(inputDir1.toString()).contains("[moduleKey=ABCDE, relative=src, basedir=null");
 
   }
 
index c474328c4203e3b3c005b1dfb8a5bc378dde9648..36201064c61ab35aae43d2ebb88b72ff60b2ee8d 100644 (file)
@@ -25,6 +25,7 @@ import org.junit.rules.TemporaryFolder;
 import org.sonar.api.batch.fs.InputFile;
 
 import java.io.File;
+import java.nio.file.Paths;
 
 import static org.assertj.core.api.Assertions.assertThat;
 
@@ -36,8 +37,7 @@ public class DefaultInputFileTest {
   @Test
   public void test() throws Exception {
     DefaultInputFile inputFile = new DefaultInputFile("ABCDE", "src/Foo.php")
-      .setFile(temp.newFile("Foo.php"))
-      .setHash("1234")
+      .setModuleBaseDir(temp.newFolder().toPath())
       .setLines(42)
       .setLanguage("php")
       .setStatus(InputFile.Status.ADDED)
@@ -51,7 +51,6 @@ public class DefaultInputFileTest {
     assertThat(inputFile.status()).isEqualTo(InputFile.Status.ADDED);
     assertThat(inputFile.type()).isEqualTo(InputFile.Type.TEST);
     assertThat(inputFile.lines()).isEqualTo(42);
-    assertThat(inputFile.hash()).isEqualTo("1234");
   }
 
   @Test
@@ -72,7 +71,7 @@ public class DefaultInputFileTest {
 
   @Test
   public void test_toString() throws Exception {
-    DefaultInputFile file = new DefaultInputFile("ABCDE", "src/Foo.php").setAbsolutePath("/path/to/src/Foo.php");
-    assertThat(file.toString()).isEqualTo("[moduleKey=ABCDE, relative=src/Foo.php, abs=/path/to/src/Foo.php]");
+    DefaultInputFile file = new DefaultInputFile("ABCDE", "src/Foo.php").setModuleBaseDir(Paths.get("/path/to/"));
+    assertThat(file.toString()).isEqualTo("[moduleKey=ABCDE, relative=src/Foo.php, basedir=/path/to]");
   }
 }
index 5aebeb9c0d24da8143e07b73fb093a93b560685c..c7007cef6873da6aab38f25e2b03b08c9dde6e0f 100644 (file)
@@ -26,6 +26,7 @@ import org.junit.rules.TemporaryFolder;
 import org.sonar.api.batch.fs.InputFile;
 
 import java.io.File;
+import java.nio.file.Paths;
 
 import static org.assertj.core.api.Assertions.assertThat;
 
@@ -37,10 +38,7 @@ public class DeprecatedDefaultInputFileTest {
   @Test
   public void test() throws Exception {
     DeprecatedDefaultInputFile inputFile = (DeprecatedDefaultInputFile) new DeprecatedDefaultInputFile("ABCDE", "src/Foo.php")
-      .setPathRelativeToSourceDir("Foo.php")
-      .setDeprecatedKey("deprecated")
-      .setFile(temp.newFile("Foo.php"))
-      .setHash("1234")
+      .setModuleBaseDir(temp.newFolder().toPath())
       .setLines(42)
       .setLanguage("php")
       .setStatus(InputFile.Status.ADDED)
@@ -48,7 +46,7 @@ public class DeprecatedDefaultInputFileTest {
 
     assertThat(inputFile.relativePath()).isEqualTo("src/Foo.php");
     // deprecated method is different -> path relative to source dir
-    assertThat(inputFile.getRelativePath()).isEqualTo("Foo.php");
+    assertThat(inputFile.getRelativePath()).isEqualTo("src/Foo.php");
     assertThat(new File(inputFile.relativePath())).isRelative();
     assertThat(inputFile.absolutePath()).endsWith("Foo.php");
     assertThat(new File(inputFile.absolutePath())).isAbsolute();
@@ -56,7 +54,6 @@ public class DeprecatedDefaultInputFileTest {
     assertThat(inputFile.status()).isEqualTo(InputFile.Status.ADDED);
     assertThat(inputFile.type()).isEqualTo(InputFile.Type.TEST);
     assertThat(inputFile.lines()).isEqualTo(42);
-    assertThat(inputFile.hash()).isEqualTo("1234");
   }
 
   @Test
@@ -77,7 +74,8 @@ public class DeprecatedDefaultInputFileTest {
 
   @Test
   public void test_toString() throws Exception {
-    DefaultInputFile file = new DefaultInputFile("ABCDE", "src/Foo.php").setAbsolutePath("/path/to/src/Foo.php");
-    assertThat(file.toString()).isEqualTo("[moduleKey=ABCDE, relative=src/Foo.php, abs=/path/to/src/Foo.php]");
+    DefaultInputFile file = new DefaultInputFile("ABCDE", "src/Foo.php")
+      .setModuleBaseDir(Paths.get("/foo/bar/"));
+    assertThat(file.toString()).isEqualTo("[moduleKey=ABCDE, relative=src/Foo.php, basedir=/foo/bar]");
   }
 }
index ea893912661a8571258abf4803b9c6311346c248..aa0e0c4abe534734ee5d9005754a81fb9c5d62a2 100644 (file)
@@ -24,7 +24,7 @@ import org.junit.Test;
 import org.junit.rules.TemporaryFolder;
 import org.sonar.api.batch.fs.InputFile;
 
-import java.io.File;
+import java.nio.file.Path;
 
 import static org.assertj.core.api.Assertions.assertThat;
 
@@ -37,17 +37,14 @@ public class PathPatternTest {
     PathPattern pattern = PathPattern.create("**/*Foo.java");
     assertThat(pattern.toString()).isEqualTo("**/*Foo.java");
 
-    File file = new File(temp.newFolder(), "src/main/java/org/MyFoo.java");
-    InputFile inputFile = new DefaultInputFile("ABCDE", "src/main/java/org/MyFoo.java").setFile(file);
+    InputFile inputFile = new DefaultInputFile("ABCDE", "src/main/java/org/MyFoo.java");
     assertThat(pattern.match(inputFile)).isTrue();
 
     // case sensitive by default
-    file = new File(temp.newFolder(), "src/main/java/org/MyFoo.JAVA");
-    inputFile = new DefaultInputFile("ABCDE", "src/main/java/org/MyFoo.JAVA").setFile(file);
+    inputFile = new DefaultInputFile("ABCDE", "src/main/java/org/MyFoo.JAVA");
     assertThat(pattern.match(inputFile)).isFalse();
 
-    file = new File(temp.newFolder(), "src/main/java/org/Other.java");
-    inputFile = new DefaultInputFile("ABCDE", "src/main/java/org/Other.java").setFile(file);
+    inputFile = new DefaultInputFile("ABCDE", "src/main/java/org/Other.java");
     assertThat(pattern.match(inputFile)).isFalse();
   }
 
@@ -55,12 +52,11 @@ public class PathPatternTest {
   public void match_relative_path_and_insensitive_file_extension() throws Exception {
     PathPattern pattern = PathPattern.create("**/*Foo.java");
 
-    File file = new File(temp.newFolder(), "src/main/java/org/MyFoo.JAVA");
-    InputFile inputFile = new DefaultInputFile("ABCDE", "src/main/java/org/MyFoo.JAVA").setFile(file);
+    Path moduleBaseDir = temp.newFolder().toPath();
+    InputFile inputFile = new DefaultInputFile("ABCDE", "src/main/java/org/MyFoo.JAVA").setModuleBaseDir(moduleBaseDir);
     assertThat(pattern.match(inputFile, false)).isTrue();
 
-    file = new File(temp.newFolder(), "src/main/java/org/Other.java");
-    inputFile = new DefaultInputFile("ABCDE", "src/main/java/org/Other.java").setFile(file);
+    inputFile = new DefaultInputFile("ABCDE", "src/main/java/org/Other.java").setModuleBaseDir(moduleBaseDir);
     assertThat(pattern.match(inputFile, false)).isFalse();
   }
 
@@ -69,17 +65,15 @@ public class PathPatternTest {
     PathPattern pattern = PathPattern.create("file:**/src/main/**Foo.java");
     assertThat(pattern.toString()).isEqualTo("file:**/src/main/**Foo.java");
 
-    File file = new File(temp.newFolder(), "src/main/java/org/MyFoo.java");
-    InputFile inputFile = new DefaultInputFile("ABCDE", "src/main/java/org/MyFoo.java").setFile(file);
+    Path moduleBaseDir = temp.newFolder().toPath();
+    InputFile inputFile = new DefaultInputFile("ABCDE", "src/main/java/org/MyFoo.java").setModuleBaseDir(moduleBaseDir);
     assertThat(pattern.match(inputFile)).isTrue();
 
     // case sensitive by default
-    file = new File(temp.newFolder(), "src/main/java/org/MyFoo.JAVA");
-    inputFile = new DefaultInputFile("ABCDE", "src/main/java/org/MyFoo.JAVA").setFile(file);
+    inputFile = new DefaultInputFile("ABCDE", "src/main/java/org/MyFoo.JAVA").setModuleBaseDir(moduleBaseDir);
     assertThat(pattern.match(inputFile)).isFalse();
 
-    file = new File(temp.newFolder(), "src/main/java/org/Other.java");
-    inputFile = new DefaultInputFile("ABCDE", "src/main/java/org/Other.java").setFile(file);
+    inputFile = new DefaultInputFile("ABCDE", "src/main/java/org/Other.java").setModuleBaseDir(moduleBaseDir);
     assertThat(pattern.match(inputFile)).isFalse();
   }
 
@@ -88,12 +82,11 @@ public class PathPatternTest {
     PathPattern pattern = PathPattern.create("file:**/src/main/**Foo.java");
     assertThat(pattern.toString()).isEqualTo("file:**/src/main/**Foo.java");
 
-    File file = new File(temp.newFolder(), "src/main/java/org/MyFoo.JAVA");
-    InputFile inputFile = new DefaultInputFile("ABCDE", "src/main/java/org/MyFoo.JAVA").setFile(file);
+    Path moduleBaseDir = temp.newFolder().toPath();
+    InputFile inputFile = new DefaultInputFile("ABCDE", "src/main/java/org/MyFoo.JAVA").setModuleBaseDir(moduleBaseDir);
     assertThat(pattern.match(inputFile, false)).isTrue();
 
-    file = new File(temp.newFolder(), "src/main/java/org/Other.JAVA");
-    inputFile = new DefaultInputFile("ABCDE", "src/main/java/org/Other.JAVA").setFile(file);
+    inputFile = new DefaultInputFile("ABCDE", "src/main/java/org/Other.JAVA").setModuleBaseDir(moduleBaseDir);
     assertThat(pattern.match(inputFile, false)).isFalse();
   }
 
index e7d1fe8242e12f573f74f1f72d0a481808b3795e..9512005a6c427c127ab8effc5733a3226d911653 100644 (file)
@@ -77,7 +77,7 @@ public class DefaultTestCaseCoverageTest {
 
     assertThat(testCaseCoverage1.toString())
       .isEqualTo(
-        "DefaultTestCaseCoverage[testFile=[moduleKey=foo, relative=test/FooTest.php, abs=null],mainFile=[moduleKey=foo, relative=src/Foo.php, abs=null],name=myTest,lines=[1, 2, 3]]");
+        "DefaultTestCaseCoverage[testFile=[moduleKey=foo, relative=test/FooTest.php, basedir=null],mainFile=[moduleKey=foo, relative=src/Foo.php, basedir=null],name=myTest,lines=[1, 2, 3]]");
     assertThat(testCaseCoverage1.hashCode()).isEqualTo(testCaseCoverage1a.hashCode());
   }
 }
index 2a5548061c7cb9d1566df77cb0817ee5c79cd95a..c1e723895239f3db7c3167bd9262eff47c0e8b39 100644 (file)
@@ -116,7 +116,7 @@ public class DefaultTestCaseExecutionTest {
     assertThat(testCase1).isNotEqualTo("foo");
 
     assertThat(testCase1.toString()).isEqualTo(
-      "DefaultTestCaseExecution[testFile=[moduleKey=foo, relative=src/Foo.php, abs=null],name=myTest,duration=1,status=ERROR,message=message,type=UNIT,stackTrace=stack]");
+      "DefaultTestCaseExecution[testFile=[moduleKey=foo, relative=src/Foo.php, basedir=null],name=myTest,duration=1,status=ERROR,message=message,type=UNIT,stackTrace=stack]");
     assertThat(testCase1.hashCode()).isEqualTo(testCase1a.hashCode());
   }
 
index 405d4f9d696a9db383f1fd8e11ddc803e513e3c4..e4a9c96f57c2c8f1b5de93125f095a34a432b9ae 100644 (file)
@@ -139,7 +139,7 @@ public class AverageFormulaTest {
   public void test_calculation_for_file() {
     when(data.getMeasure(CoreMetrics.COMPLEXITY)).thenReturn(new Measure(CoreMetrics.COMPLEXITY, 60.0));
     when(data.getMeasure(CoreMetrics.FUNCTIONS)).thenReturn(new Measure(CoreMetrics.FUNCTIONS, 20.0));
-    when(context.getResource()).thenReturn(new File("foo"));
+    when(context.getResource()).thenReturn(File.create("foo"));
 
     Measure measure = AverageFormula.create(CoreMetrics.COMPLEXITY, CoreMetrics.FUNCTIONS).calculate(data, context);
     assertThat(measure.getValue()).isEqualTo(3.0);
@@ -150,7 +150,7 @@ public class AverageFormulaTest {
     when(data.getMeasure(CoreMetrics.COMPLEXITY_IN_FUNCTIONS)).thenReturn(null);
     when(data.getMeasure(CoreMetrics.COMPLEXITY)).thenReturn(new Measure(CoreMetrics.COMPLEXITY, 60.0));
     when(data.getMeasure(CoreMetrics.FUNCTIONS)).thenReturn(new Measure(CoreMetrics.FUNCTIONS, 20.0));
-    when(context.getResource()).thenReturn(new File("foo"));
+    when(context.getResource()).thenReturn(File.create("foo"));
 
     Measure measure = AverageFormula.create(CoreMetrics.COMPLEXITY_IN_FUNCTIONS, CoreMetrics.FUNCTIONS)
       .setFallbackForMainMetric(CoreMetrics.COMPLEXITY)
@@ -163,7 +163,7 @@ public class AverageFormulaTest {
     when(data.getMeasure(CoreMetrics.COMPLEXITY_IN_FUNCTIONS)).thenReturn(new Measure(CoreMetrics.COMPLEXITY, 60.0));
     when(data.getMeasure(CoreMetrics.COMPLEXITY)).thenReturn(new Measure(CoreMetrics.COMPLEXITY, 42.0));
     when(data.getMeasure(CoreMetrics.FUNCTIONS)).thenReturn(new Measure(CoreMetrics.FUNCTIONS, 20.0));
-    when(context.getResource()).thenReturn(new File("foo"));
+    when(context.getResource()).thenReturn(File.create("foo"));
 
     Measure measure = AverageFormula.create(CoreMetrics.COMPLEXITY_IN_FUNCTIONS, CoreMetrics.FUNCTIONS)
       .setFallbackForMainMetric(CoreMetrics.COMPLEXITY)
index 8d31362cf1deda927814cbcc38fa3bebbec17e76..6129400fede3721ca003edd1c170e89e1b42c9ad 100644 (file)
@@ -30,9 +30,9 @@ import java.util.Collections;
 import java.util.List;
 
 import static junit.framework.Assert.assertNull;
+import static org.hamcrest.MatcherAssert.assertThat;
 import static org.hamcrest.Matchers.is;
 import static org.hamcrest.Matchers.nullValue;
-import static org.hamcrest.MatcherAssert.assertThat;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
@@ -45,7 +45,7 @@ public class SumChildDistributionFormulaTest {
   public void init() {
     formula = new SumChildDistributionFormula();
     context = mock(FormulaContext.class);
-    when(context.getResource()).thenReturn(new File("foo"));
+    when(context.getResource()).thenReturn(File.create("foo"));
     data = mock(FormulaData.class);
   }
 
@@ -97,7 +97,7 @@ public class SumChildDistributionFormulaTest {
 
   @Test
   public void shouldNotPersistWhenScopeLowerThanMinimun() throws Exception {
-    when(context.getResource()).thenReturn(new File("org/Foo.java"));
+    when(context.getResource()).thenReturn(File.create("org/Foo.java"));
 
     initContextWithChildren();
     formula.setMinimumScopeToPersist(Scopes.DIRECTORY);
@@ -108,7 +108,7 @@ public class SumChildDistributionFormulaTest {
 
   @Test
   public void shouldPersistWhenScopeEqualsMinimun() throws Exception {
-    when(context.getResource()).thenReturn(new File("org/Foo.java"));
+    when(context.getResource()).thenReturn(File.create("org/Foo.java"));
 
     initContextWithChildren();
     formula.setMinimumScopeToPersist(Scopes.FILE);
@@ -119,7 +119,7 @@ public class SumChildDistributionFormulaTest {
 
   @Test
   public void shouldPersistWhenScopeHigherThanMinimun() throws Exception {
-    when(context.getResource()).thenReturn(new Directory("org/foo"));
+    when(context.getResource()).thenReturn(Directory.create("org/foo"));
 
     initContextWithChildren();
     formula.setMinimumScopeToPersist(Scopes.FILE);
index 0c83e6a8ba994d28081093ec0e4bc60cd7715c1a..054c6c4868918c475bd3be88f1d4e2a2ad14e807 100644 (file)
@@ -25,9 +25,7 @@ import org.junit.rules.TemporaryFolder;
 
 import java.io.IOException;
 
-import static org.hamcrest.Matchers.is;
-import static org.hamcrest.Matchers.nullValue;
-import static org.junit.Assert.assertThat;
+import static org.assertj.core.api.Assertions.assertThat;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
@@ -40,71 +38,55 @@ public class DirectoryTest {
   public void createFromIoFileShouldComputeCorrectKey() throws IOException {
     java.io.File baseDir = temp.newFolder();
     Project project = mock(Project.class);
-    ProjectFileSystem fileSystem = mock(ProjectFileSystem.class);
-    when(project.getFileSystem()).thenReturn(fileSystem);
-    when(fileSystem.getBasedir()).thenReturn(baseDir);
+    when(project.getBaseDir()).thenReturn(baseDir);
     Resource dir = Directory.fromIOFile(new java.io.File(baseDir, "src/foo/bar/"), project);
-    assertThat(dir.getKey(), is("src/foo/bar"));
+    assertThat(dir.getKey()).isEqualTo("src/foo/bar");
   }
 
   @Test
-  public void shouldStartBySlashAndNotEndBySlash() {
-    Resource dir = Directory.create("src/foo/bar/", "      /foo/bar/  ");
-    assertThat(dir.getKey(), is("src/foo/bar"));
-    assertThat(dir.getDeprecatedKey(), is("foo/bar"));
-    assertThat(dir.getName(), is("src/foo/bar"));
-  }
-
-  @Test
-  public void shouldNotStartOrEndBySlashDeprecatedConstructor() {
-    Resource dir = new Directory("      /foo/bar/  ");
-    assertThat(dir.getDeprecatedKey(), is("foo/bar"));
-  }
-
-  @Test
-  public void rootDirectoryDeprecatedConstructor() {
-    assertThat(new Directory(null).getDeprecatedKey(), is(Directory.ROOT));
-    assertThat(new Directory("").getDeprecatedKey(), is(Directory.ROOT));
-    assertThat(new Directory("   ").getDeprecatedKey(), is(Directory.ROOT));
+  public void shouldNotStartBySlashAndNotEndBySlash() {
+    Resource dir = Directory.create("src/foo/bar/");
+    assertThat(dir.getKey()).isEqualTo("src/foo/bar");
+    assertThat(dir.getName()).isEqualTo("src/foo/bar");
   }
 
   @Test
   public void backSlashesShouldBeReplacedBySlashes() {
-    Resource dir = new Directory("  foo\\bar\\     ");
-    assertThat(dir.getDeprecatedKey(), is("foo/bar"));
+    Resource dir = Directory.create("  foo\\bar\\     ");
+    assertThat(dir.getKey()).isEqualTo("foo/bar");
   }
 
   @Test
   public void directoryHasNoParents() {
-    Resource dir = new Directory("foo/bar");
-    assertThat(dir.getParent(), nullValue());
+    Resource dir = Directory.create("foo/bar");
+    assertThat(dir.getParent()).isNull();
   }
 
   @Test
   public void shouldHaveOnlyOneLevelOfDirectory() {
-    assertThat(new Directory("one/two/third").getParent(), nullValue());
-    assertThat(new Directory("one").getParent(), nullValue());
+    assertThat(Directory.create("one/two/third").getParent()).isNull();
+    assertThat(Directory.create("one").getParent()).isNull();
   }
 
   @Test
   public void parseDirectoryKey() {
-    assertThat(Directory.parseKey("/foo/bar"), is("foo/bar"));
+    assertThat(Directory.parseKey("/foo/bar")).isEqualTo("foo/bar");
   }
 
   @Test
   public void matchExclusionPatterns() {
-    Directory directory = Directory.create("src/one/two/third", "one/two/third");
-    assertThat(directory.matchFilePattern("one/two/*.java"), is(false));
-    assertThat(directory.matchFilePattern("false"), is(false));
-    assertThat(directory.matchFilePattern("two/one/**"), is(false));
-    assertThat(directory.matchFilePattern("other*/**"), is(false));
+    Directory directory = Directory.create("src/one/two/third");
+    assertThat(directory.matchFilePattern("one/two/*.java")).isFalse();
+    assertThat(directory.matchFilePattern("false")).isFalse();
+    assertThat(directory.matchFilePattern("two/one/**")).isFalse();
+    assertThat(directory.matchFilePattern("other*/**")).isFalse();
 
-    assertThat(directory.matchFilePattern("src/one*/**"), is(true));
-    assertThat(directory.matchFilePattern("src/one/t?o/**"), is(true));
-    assertThat(directory.matchFilePattern("**/*"), is(true));
-    assertThat(directory.matchFilePattern("**"), is(true));
-    assertThat(directory.matchFilePattern("src/one/two/*"), is(true));
-    assertThat(directory.matchFilePattern("/src/one/two/*"), is(true));
-    assertThat(directory.matchFilePattern("src/one/**"), is(true));
+    assertThat(directory.matchFilePattern("src/one*/**")).isTrue();
+    assertThat(directory.matchFilePattern("src/one/t?o/**")).isTrue();
+    assertThat(directory.matchFilePattern("**/*")).isTrue();
+    assertThat(directory.matchFilePattern("**")).isTrue();
+    assertThat(directory.matchFilePattern("src/one/two/*")).isTrue();
+    assertThat(directory.matchFilePattern("/src/one/two/*")).isTrue();
+    assertThat(directory.matchFilePattern("src/one/**")).isTrue();
   }
 }
index dbd04f48202f24028bdccc2be2b1b1436cd69294..62c5d7a503a2515a12020a049ce63f98a602ac20 100644 (file)
@@ -26,9 +26,6 @@ import org.junit.rules.TemporaryFolder;
 import java.io.IOException;
 
 import static org.assertj.core.api.Assertions.assertThat;
-import static org.hamcrest.Matchers.is;
-import static org.hamcrest.Matchers.nullValue;
-import static org.junit.Assert.assertThat;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
@@ -41,68 +38,34 @@ public class FileTest {
   public void createFromIoFileShouldComputeCorrectKey() throws IOException {
     java.io.File baseDir = temp.newFolder();
     Project project = mock(Project.class);
-    ProjectFileSystem fileSystem = mock(ProjectFileSystem.class);
-    when(project.getFileSystem()).thenReturn(fileSystem);
-    when(fileSystem.getBasedir()).thenReturn(baseDir);
+    when(project.getBaseDir()).thenReturn(baseDir);
     Resource file = File.fromIOFile(new java.io.File(baseDir, "src/foo/bar/toto.sql"), project);
-    assertThat(file.getKey(), is("src/foo/bar/toto.sql"));
+    assertThat(file.getKey()).isEqualTo("src/foo/bar/toto.sql");
   }
 
   @Test
   public void trimKeyAndName() {
-    File file = new File("   foo/bar/  ", "  toto.sql  ");
-    assertThat(file.getDeprecatedKey(), is("foo/bar/toto.sql"));
-    assertThat(file.getName(), is("toto.sql"));
+    File file = File.create("   foo/bar/toto.sql  ");
+    assertThat(file.getKey()).isEqualTo("foo/bar/toto.sql");
+    assertThat(file.getName()).isEqualTo("toto.sql");
   }
 
   @Test
   public void parentIsDirectory() {
-    File file = File.create("src/foo/bar/toto.sql", "foo/bar/toto.sql", null, false);
-    assertThat(file.getKey(), is("src/foo/bar/toto.sql"));
-    assertThat(file.getDeprecatedKey(), is("foo/bar/toto.sql"));
-    assertThat(file.getLongName(), is("src/foo/bar/toto.sql"));
-    assertThat(file.getName(), is("toto.sql"));
-    assertThat(file.getParent().getKey(), is("src/foo/bar"));
-    assertThat(ResourceUtils.isSpace(file.getParent()), is(true));
-  }
-
-  @Test
-  public void parentIsDirectoryWithDeprecatedKey() {
-    File file = new File("   foo/bar/", "toto.sql  ");
-    assertThat(file.getDeprecatedKey(), is("foo/bar/toto.sql"));
-    assertThat(file.getParent().getDeprecatedKey(), is("foo/bar"));
-    assertThat(ResourceUtils.isSpace(file.getParent()), is(true));
+    File file = File.create("src/foo/bar/toto.sql", null, false);
+    assertThat(file.getKey()).isEqualTo("src/foo/bar/toto.sql");
+    assertThat(file.getLongName()).isEqualTo("src/foo/bar/toto.sql");
+    assertThat(file.getName()).isEqualTo("toto.sql");
+    assertThat(file.getParent().getKey()).isEqualTo("src/foo/bar");
+    assertThat(ResourceUtils.isSpace(file.getParent())).isEqualTo(true);
   }
 
   @Test
   public void rootFilesHaveParent() {
-    File file = File.create("toto.sql", "toto.sql", null, false);
-    assertThat(file.getKey(), is("toto.sql"));
-    assertThat(file.getDeprecatedKey(), is("toto.sql"));
-    assertThat(file.getName(), is("toto.sql"));
-    assertThat(file.getParent().getKey(), is("/"));
-    assertThat(file.getParent().getDeprecatedKey(), is(Directory.ROOT));
-  }
-
-  @Test
-  public void newFileByDeprecatedKey() {
-    File file = new File("toto.sql");
-    assertThat(file.getDeprecatedKey(), is("toto.sql"));
-    assertThat(file.getName(), is("toto.sql"));
-    assertThat(file.language()).isNull();
-    assertThat(file.getParent().getDeprecatedKey(), is(Directory.ROOT));
-    assertThat(file.getScope(), is(Resource.SCOPE_ENTITY));
-    assertThat(file.getQualifier(), is(Resource.QUALIFIER_FILE));
-
-    file = new File("foo/bar/toto.sql");
-    assertThat(file.getDeprecatedKey(), is("foo/bar/toto.sql"));
-    assertThat(file.getName(), is("toto.sql"));
-    assertThat(file.getParent().getDeprecatedKey(), is("foo/bar"));
-
-    file = new File("/foo/bar/toto.sql ");
-    assertThat(file.getDeprecatedKey(), is("foo/bar/toto.sql"));
-    assertThat(file.getName(), is("toto.sql"));
-    assertThat(file.getParent().getDeprecatedKey(), is("foo/bar"));
+    File file = File.create("toto.sql", null, false);
+    assertThat(file.getKey()).isEqualTo("toto.sql");
+    assertThat(file.getName()).isEqualTo("toto.sql");
+    assertThat(file.getParent().getKey()).isEqualTo("/");
   }
 
   @Test
@@ -114,18 +77,19 @@ public class FileTest {
         return null;
       }
     };
-    File file = new File(lang, "Foo.java");
-    assertThat(file.getLanguage(), is(lang));
 
-    file = new File(lang, "org/sonar", "Foo.java");
-    assertThat(file.getLanguage(), is(lang));
+    File file = File.create("Foo.java", lang, false);
+    assertThat(file.getLanguage()).isEqualTo(lang);
+
+    file = File.create("org/sonar/Foo.java", lang, false);
+    assertThat(file.getLanguage()).isEqualTo(lang);
     assertThat(file.language()).isEqualTo("java");
-    assertThat(file.getParent().getLanguage(), nullValue());
+    assertThat(file.getParent().getLanguage()).isNull();
   }
 
   @Test
   public void matchAntPatterns() {
-    File file = File.create("src/one/two/foo.sql", "one/two/foo.sql", null, false);
+    File file = File.create("src/one/two/foo.sql", null, false);
     assertThat(file.matchFilePattern("/src/one/two/*.java")).isFalse();
     assertThat(file.matchFilePattern("false")).isFalse();
     assertThat(file.matchFilePattern("two/one/**")).isFalse();
index 966c3d7e6c2182c27f058c82e96b9346cd56b066..14b0b7bf6badf3cda57ff6aab25e603af6855e47 100644 (file)
@@ -29,7 +29,7 @@ public class ResourceUtilsTest {
 
   @Test
   public void checkFile() {
-    File file = new File("hello.Foo");
+    File file = File.create("hello.Foo");
     assertThat(ResourceUtils.isClass(file)).isFalse();
     assertThat(ResourceUtils.isPackage(file)).isFalse();
     assertThat(ResourceUtils.isModuleProject(file)).isFalse();
@@ -42,7 +42,7 @@ public class ResourceUtilsTest {
 
   @Test
   public void checkUnitTest() {
-    File utFile = new File("hello.Foo");
+    File utFile = File.create("hello.Foo");
     utFile.setQualifier(Qualifiers.UNIT_TEST_FILE);
     assertThat(ResourceUtils.isClass(utFile)).isFalse();
     assertThat(ResourceUtils.isPackage(utFile)).isFalse();
@@ -56,7 +56,7 @@ public class ResourceUtilsTest {
 
   @Test
   public void checkDirectory() {
-    Directory dir = new Directory("hello");
+    Directory dir = Directory.create("hello");
     assertThat(ResourceUtils.isClass(dir)).isFalse();
     assertThat(ResourceUtils.isPackage(dir)).isFalse();
     assertThat(ResourceUtils.isModuleProject(dir)).isFalse();
@@ -69,8 +69,8 @@ public class ResourceUtilsTest {
 
   @Test
   public void shouldBePersistable() {
-    assertThat(ResourceUtils.isPersistable(new File("Foo.java"))).isTrue();
-    assertThat(ResourceUtils.isPersistable(new Directory("bar/Foo.java"))).isTrue();
+    assertThat(ResourceUtils.isPersistable(File.create("Foo.java"))).isTrue();
+    assertThat(ResourceUtils.isPersistable(Directory.create("bar/Foo.java"))).isTrue();
     assertThat(ResourceUtils.isPersistable(new Project("foo"))).isTrue();
     assertThat(ResourceUtils.isPersistable(new Library("foo", "1.2"))).isTrue();
   }
index 5de04c830a9ce6c92af28244ef331d9dfe3cc988..8364aed52c1b3acc6c49550245a6352f0e1f4034 100644 (file)
@@ -48,7 +48,7 @@ public class ScopesTest {
 
   @Test
   public void testDirectory() {
-    Resource resource = new Directory("org/foo");
+    Resource resource = Directory.create("org/foo");
     assertThat(Scopes.isProject(resource), is(false));
     assertThat(Scopes.isDirectory(resource), is(true));
     assertThat(Scopes.isFile(resource), is(false));
@@ -58,7 +58,7 @@ public class ScopesTest {
 
   @Test
   public void testFile() {
-    Resource resource = new File("org/foo/Bar.java");
+    Resource resource = File.create("org/foo/Bar.java");
     assertThat(Scopes.isProject(resource), is(false));
     assertThat(Scopes.isDirectory(resource), is(false));
     assertThat(Scopes.isFile(resource), is(true));
index 05ab197db794af99e87f31948709d7005a078583..57ca2ae1ae3dc79c236435efcd2ae509a564c991 100644 (file)
@@ -76,6 +76,7 @@ public class PathResolverTest {
     File world = new File(hello, "World.java");
 
     assertThat(resolver.relativePath(rootDir, world)).isEqualTo("org/hello/World.java");
+    assertThat(resolver.relativePath(new File(rootDir, "."), world)).isEqualTo("org/hello/World.java");
   }
 
   @Test
@@ -140,4 +141,13 @@ public class PathResolverTest {
 
     assertThat(resolver.relativePath(rootDir, new File("Elsewhere.java"))).isNull();
   }
+
+  @Test
+  public void supportSymlink() {
+    PathResolver resolver = new PathResolver();
+    File rootDir = new File("src/test/resources/org/sonar/api/scan/filesystem/sample-with-symlink");
+
+    assertThat(resolver.relativePath(rootDir, new File("src/test/resources/org/sonar/api/scan/filesystem/sample-with-symlink/testx/ClassOneTest.java"))).isEqualTo(
+      "testx/ClassOneTest.java");
+  }
 }
index 1d040904eb41203725216ab5318fca947f8c982d..cdd8822a61a2706d47ead9ad33b75bf767aee77c 100644 (file)
@@ -20,7 +20,6 @@
 package org.sonar.api.test;
 
 import org.apache.commons.lang.ObjectUtils;
-import org.apache.commons.lang.StringUtils;
 import org.mockito.ArgumentMatcher;
 import org.sonar.api.resources.Resource;
 
@@ -43,7 +42,6 @@ public class IsResource extends ArgumentMatcher<Resource> {
   @Override
   public boolean matches(Object o) {
     Resource r = (Resource) o;
-    boolean keyMatch = (key != null) ? StringUtils.equals(r.getKey() != null ? r.getKey() : r.getDeprecatedKey(), key) : true;
-    return ObjectUtils.equals(r.getScope(), scope) && ObjectUtils.equals(r.getQualifier(), qualifier) && keyMatch;
+    return ObjectUtils.equals(r.getScope(), scope) && ObjectUtils.equals(r.getQualifier(), qualifier) && r.getKey().equals(key);
   }
 }
diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample-with-symlink/.gitignore b/sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample-with-symlink/.gitignore
new file mode 100644 (file)
index 0000000..ecbefd4
--- /dev/null
@@ -0,0 +1 @@
+.sonar
diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample-with-symlink/sonar-project.properties b/sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample-with-symlink/sonar-project.properties
new file mode 100644 (file)
index 0000000..8810e37
--- /dev/null
@@ -0,0 +1,6 @@
+sonar.projectKey=sample
+sonar.projectName=Sample
+sonar.projectVersion=0.1-SNAPSHOT
+sonar.sources=xources
+sonar.tests=testx
+sonar.language=xoo
diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample-with-symlink/testx b/sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample-with-symlink/testx
new file mode 120000 (symlink)
index 0000000..7385ebd
--- /dev/null
@@ -0,0 +1 @@
+../sample/testx/
\ No newline at end of file
diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample-with-symlink/xources b/sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample-with-symlink/xources
new file mode 120000 (symlink)
index 0000000..15dca9d
--- /dev/null
@@ -0,0 +1 @@
+../sample/xources/
\ No newline at end of file
diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample/sonar-project.properties b/sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample/sonar-project.properties
new file mode 100644 (file)
index 0000000..8810e37
--- /dev/null
@@ -0,0 +1,6 @@
+sonar.projectKey=sample
+sonar.projectName=Sample
+sonar.projectVersion=0.1-SNAPSHOT
+sonar.sources=xources
+sonar.tests=testx
+sonar.language=xoo
diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample/testx/ClassOneTest.xoo b/sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample/testx/ClassOneTest.xoo
new file mode 100644 (file)
index 0000000..8c0967e
--- /dev/null
@@ -0,0 +1,11 @@
+package org.sonar.tests;
+
+import org.junit.Test;
+
+public class ClassOneTest  {
+
+  @Test
+  public void nothing() {
+
+  }
+}
diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample/testx/ClassOneTest.xoo.measures b/sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample/testx/ClassOneTest.xoo.measures
new file mode 100644 (file)
index 0000000..23b08dc
--- /dev/null
@@ -0,0 +1,7 @@
+lines:11
+ncloc:7
+tests:1
+test_execution_time:1
+skipped_tests:0
+test_errors:0
+test_failures:0
diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample/testx/ClassOneTest.xoo.scm b/sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample/testx/ClassOneTest.xoo.scm
new file mode 100644 (file)
index 0000000..2cec35b
--- /dev/null
@@ -0,0 +1,11 @@
+1,user1,2013-01-04
+1,user1,2013-01-04
+1,user1,2013-01-04
+1,user1,2013-01-04
+2,user2,2013-01-05
+2,user2,2013-01-05
+3,user3,2013-01-06
+4,user4,2013-01-07
+4,user4,2013-01-07
+4,user4,2013-01-07
+4,user4,2013-01-07
\ No newline at end of file
diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample/xources/hello/HelloJava.xoo b/sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample/xources/hello/HelloJava.xoo
new file mode 100644 (file)
index 0000000..1d9c60d
--- /dev/null
@@ -0,0 +1,8 @@
+package hello;
+
+public class HelloJava {
+
+  public static void main(String[] args) {
+    System.out.println("Hello");
+  }
+}
\ No newline at end of file
diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample/xources/hello/HelloJava.xoo.measures b/sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample/xources/hello/HelloJava.xoo.measures
new file mode 100644 (file)
index 0000000..9eaf8ba
--- /dev/null
@@ -0,0 +1,2 @@
+ncloc:3
+complexity:1
diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample/xources/hello/HelloJava.xoo.scm b/sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample/xources/hello/HelloJava.xoo.scm
new file mode 100644 (file)
index 0000000..03a9de2
--- /dev/null
@@ -0,0 +1,8 @@
+1,user1,2013-01-04
+1,user1,2013-01-04
+1,user1,2013-01-04
+1,user1,2013-01-04
+2,user2,2013-01-05
+2,user2,2013-01-05
+3,user3,2013-01-06
+4,user4,2013-01-07
\ No newline at end of file
diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample/xources/hello/helloscala.xoo b/sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample/xources/hello/helloscala.xoo
new file mode 100644 (file)
index 0000000..53cb085
--- /dev/null
@@ -0,0 +1,6 @@
+  object HelloWorld {
+    def main(args: Array[String]) {
+      println("Hello, world of xoo!")
+    }
+  }
+  
\ No newline at end of file
diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample/xources/hello/helloscala.xoo.measures b/sonar-plugin-api/src/test/resources/org/sonar/api/scan/filesystem/sample/xources/hello/helloscala.xoo.measures
new file mode 100644 (file)
index 0000000..d2c8386
--- /dev/null
@@ -0,0 +1,2 @@
+ncloc:5
+complexity:2