*/
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;
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;
*/
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;
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;
*/
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;
*/
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 {
*/
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 {
*/
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;
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;
*/
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;
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;
*/
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;
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;
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 {
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));
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;
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;
@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);
@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);
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()));
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;
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));
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());
}
*/
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;
*/
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;
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;
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);
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);
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);
}
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")
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;
@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);
@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);
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);
}
@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);
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);
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);
}
@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);
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);
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>() {
@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);
}
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)
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);
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);
}
@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);
}
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);
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);
}
@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);
}
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);
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);
}
@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);
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);
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);
@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);
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);
@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);
@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);
@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);
}
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);
// Mockito.verifyZeroInteractions(manager);
// }
//}
+
<groupId>org.codehaus.sonar</groupId>
<artifactId>sonar-persistit</artifactId>
</dependency>
+
<dependency>
<groupId>org.codehaus.sonar</groupId>
<artifactId>sonar-core</artifactId>
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.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;
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.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);
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.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;
- }
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.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
- }
-
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.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;
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.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);
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.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();
- }
-}
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);
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.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));
- }
- }
-}
*/
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;
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;
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;
*/
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;
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;
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;
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;
return this;
}
- Integer getProjectSnapshotId() {
+ public Integer getProjectSnapshotId() {
return projectSnapshot != null ? projectSnapshot.getId() : null;
}
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;
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);
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.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);
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.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());
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.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));
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.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());
- }
-
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.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;
- }
-
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-package org.sonar.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;
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-package org.sonar.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;
- }
-
-}
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;
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;
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;
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.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);
+ }
+}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.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));
+ }
+ }
+}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.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;
+ }
+ }
+}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.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
+ }
+
+}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.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;
+ }
+}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.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);
+ }
+}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.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());
+ }
+}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.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));
+ }
+}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.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());
+ }
+
+}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.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;
+ }
+
+}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+package org.sonar.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;
+ }
+}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+package org.sonar.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;
+ }
+
+}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+@ParametersAreNonnullByDefault
+package org.sonar.batch.deprecated.components;
+
+import javax.annotation.ParametersAreNonnullByDefault;
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.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;
+ }
+}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.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);
+ }
+}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.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();
+ }
+}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+@ParametersAreNonnullByDefault
+package org.sonar.batch.deprecated;
+
+import javax.annotation.ParametersAreNonnullByDefault;
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.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();
+ }
+}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.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() + "'");
+ }
+ }
+ }
+}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+@ParametersAreNonnullByDefault
+package org.sonar.batch.deprecated.tasks;
+
+import javax.annotation.ParametersAreNonnullByDefault;
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;
// 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();
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) {
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;
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;
}
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;
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) {
}
}
- 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);
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) {
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)) {
}
}
+ 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)) {
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;
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("");
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;
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];
}
}
- 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()];
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++;
}
}
}
- 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) {
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
*/
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;
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;
});
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);
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) {
.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();
}
@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);
}
*/
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;
/**
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];
*/
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;
import javax.annotation.Nullable;
-public class IssueHandlers implements BatchExtension {
+public class IssueHandlers implements BatchComponent {
private final IssueHandler[] handlers;
private final DefaultContext context;
@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);
*/
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;
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;
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);
}
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;
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");
}
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;
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.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;
- }
-
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.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);
- }
-
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.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();
-
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-@javax.annotation.ParametersAreNonnullByDefault
-package org.sonar.batch.languages;
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;
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);
}
}
*/
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;
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;
import java.util.Arrays;
import java.util.Set;
+/**
+ * Used by views
+ */
public class Phases {
public static enum Phase {
/**
* Allow to filter sensors that will be executed.
+ * Used by views !!
* @since 3.6
*
*/
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.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;
+ }
+
+}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.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);
+ }
+
+}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.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();
+
+}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+@javax.annotation.ParametersAreNonnullByDefault
+package org.sonar.batch.repository.language;
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.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();
+ }
+
+}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.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();
+ }
+
+}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+@ParametersAreNonnullByDefault
+package org.sonar.batch.repository.user;
+
+import javax.annotation.ParametersAreNonnullByDefault;
*/
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;
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
*/
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;
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
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;
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;
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;
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;
ExclusionFilters.class,
DeprecatedFileFilters.class,
InputFileBuilderFactory.class,
+ FileMetadata.class,
StatusDetectionFactory.class,
LanguageDetectionFactory.class,
FileIndexer.class,
*/
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;
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;
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;
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;
// lang
Languages.class,
- DefaultLanguagesReferential.class,
+ DefaultLanguagesRepository.class,
HighlightableBuilder.class,
SymbolizableBuilder.class,
*/
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;
}
}
- 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());
- }
- }
}
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;
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();
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);
}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.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;
- }
-
-}
*/
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;
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 {
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());
}
}));
}
- 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);
}
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;
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
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;
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;
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) {
// 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) {
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) {
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() {
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;
* 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 {
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
}
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
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.
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))) {
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);
}
}
}
*/
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;
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 {
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;
this.fs = fs;
this.analysisMode = analysisMode;
this.settings = settings;
+ this.fileMetadata = fileMetadata;
}
String moduleKey() {
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)) {
}
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());
- }
- }
- }
- }
}
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;
}
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);
}
}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.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;
+ }
+
+}
*/
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
*/
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;
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;
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);
*/
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;
}
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);
}
}
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;
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;
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();
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;
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
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();
}
}
} 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);
}
}
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;
}
@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) {
} 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);
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
@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)
.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();
}
}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.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();
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.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() + "'");
- }
- }
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-@ParametersAreNonnullByDefault
-package org.sonar.batch.tasks;
-
-import javax.annotation.ParametersAreNonnullByDefault;
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.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();
- }
-
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.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();
- }
-
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-@ParametersAreNonnullByDefault
-package org.sonar.batch.user;
-
-import javax.annotation.ParametersAreNonnullByDefault;
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.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;
- }
- }
-}
@Test(expected = IllegalArgumentException.class)
public void shouldNotAllowCreationForDirectory() {
- new DefaultFileLinesContext(index, new Directory("key"));
+ new DefaultFileLinesContext(index, Directory.create("key"));
}
@Test
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.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);
- }
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.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();
- }
-}
*/
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;
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.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));
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.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;
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.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());
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.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();
- }
-
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.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();
- }
-
-}
*/
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;
*/
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;
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-
-package org.sonar.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);
- }
-}
*/
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;
// 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));
}
@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));
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;
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;
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);
}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.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();
+ }
+}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.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));
+ }
+}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.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;
+ }
+}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.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());
+ }
+}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.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();
+ }
+
+}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.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();
+ }
+
+}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+
+package org.sonar.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);
+ }
+}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.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;
+ }
+ }
+}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.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);
+ }
+ }
+}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.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() {
+ }
+ }
+}
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.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() {
+ }
+
+ }
+
+}
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);
@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>();
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);
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
@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();
@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();
@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");
}
@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();
@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();
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;
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);
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);
@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();
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;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
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);
}
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.");
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");
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;
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;
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);
}
@Test
public void consolidateData() throws Exception {
- byte[] bytes = sut.consolidateData(inputFile);
+ byte[] bytes = sut.consolidateData(inputFile, metadata);
assertThat(bytes).isNotEmpty();
}
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))
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();
.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");
.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");
.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");
.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");
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();
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");
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");
@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();
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);
@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);
}
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);
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);
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);
*/
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;
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;
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;
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);
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
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);
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));
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];
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;
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;
public class IssueTrackingTest {
+ @Rule
+ public TemporaryFolder temp = new TemporaryFolder();
+
IssueTracking tracking;
Resource project;
SourceHashHolder sourceHashHolder;
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];
*/
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;
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)});
}
@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);
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;
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) {
*/
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;
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;
@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());
}
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));
--- /dev/null
+/*
+ * SonarQube, open source software quality management tool.
+ * Copyright (C) 2008-2014 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * SonarQube is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * SonarQube is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.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"));
+ }
+}
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;
@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);
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);
}
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);
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);
@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);
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;
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
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 {
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();
- }
}
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 {
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() {
@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) {
@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);
}
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();
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
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();
}
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);
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);
}
}
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;
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();
}
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();
}
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();
}
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/**/*");
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();
}
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 {
@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();
}
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();
}
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
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
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
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
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
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
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
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
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
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
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
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);
}
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();
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;
.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());
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
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();
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");
-
- }
}
*/
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;
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;
@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();
+
}
}
*/
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();
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;
@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");
@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");
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);
@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");
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);
@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"));
@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/**");
@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");
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 {
@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);
@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);
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;
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;
@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");
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");
@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);
@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);
@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);
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))
@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);
@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);
*/
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;
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);
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);
}
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);
@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);
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.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() {
- }
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.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() {
- }
-
- }
-
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2014 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.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"));
- }
-}
+++ /dev/null
-<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>
+++ /dev/null
-<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>
+++ /dev/null
-<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
+++ /dev/null
-<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
+++ /dev/null
-<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
+++ /dev/null
-<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>
+++ /dev/null
-<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>
+++ /dev/null
-<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>
+++ /dev/null
-<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>
+++ /dev/null
-<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>
--- /dev/null
+<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>
--- /dev/null
+<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>
--- /dev/null
+<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
--- /dev/null
+<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
--- /dev/null
+<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
--- /dev/null
+<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>
--- /dev/null
+<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>
--- /dev/null
+<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>
--- /dev/null
+<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>
--- /dev/null
+<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>
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]"
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]"
*/
package org.sonar.batch.index;
+/**
+ * Used by views !!
+ */
public interface ResourceCopy {
int getCopyResourceId();
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");
@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");
}
@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) {
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;
}
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) {
@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);
}
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
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.
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
*/
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 {
/**
package org.sonar.api.batch.fs;
import java.io.File;
+import java.nio.file.Path;
/**
* Layer over {@link java.io.File} for directories.
@Override
File file();
+ /**
+ * The underlying absolute {@link Path}
+ */
+ @Override
+ Path path();
+
}
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.
@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.
*/
import java.io.File;
import java.io.Serializable;
+import java.nio.file.Path;
/**
* Layer over {@link java.io.File} for files or directories.
*/
File file();
+ /**
+ * @see InputFile#path()
+ * @see InputDir#path()
+ * @since 5.1
+ */
+ Path path();
+
}
import org.sonar.api.utils.PathUtils;
import java.io.File;
+import java.nio.file.Path;
import java.util.Arrays;
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);
}
@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();
}
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;
*/
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;
}
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;
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) {
}
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
@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;
}
* 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());
* 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;
}
import java.io.File;
import java.io.Serializable;
+import java.nio.file.Path;
/**
* @since 4.5
private final String relativePath;
private final String moduleKey;
- private String absolutePath;
+ private Path moduleBaseDir;
public DefaultInputDir(String moduleKey, String relativePath) {
this.moduleKey = moduleKey;
@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() {
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;
}
@Override
public String toString() {
- return "[moduleKey=" + moduleKey + ", relative=" + relativePath + ", abs=" + absolutePath + "]";
+ return "[moduleKey=" + moduleKey + ", relative=" + relativePath + ", basedir=" + moduleBaseDir + "]";
}
}
import java.io.File;
import java.io.Serializable;
+import java.nio.charset.Charset;
+import java.nio.file.Path;
/**
* @since 4.2
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;
@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
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.
*/
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;
}
return this;
}
- public DefaultInputFile setFile(File file) {
- setAbsolutePath(file.getAbsolutePath());
- return this;
- }
-
public DefaultInputFile setType(Type type) {
this.type = type;
return this;
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;
}
@Override
public String toString() {
- return "[moduleKey=" + moduleKey + ", relative=" + relativePath + ", abs=" + absolutePath + "]";
+ return "[moduleKey=" + moduleKey + ", relative=" + relativePath + ", basedir=" + moduleBaseDir + "]";
}
}
*/
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;
*/
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);
}
@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();
}
/**
@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
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;
// 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();
}
/**
- * 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);
}
}
/**
- * 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);
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();
}
import javax.annotation.CheckForNull;
-import java.util.List;
-
/**
* This class is an implementation of a resource of type FILE
*
public static final String SCOPE = Scopes.FILE;
- private String directoryDeprecatedKey;
private String filename;
private Language language;
private Directory parent;
// 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}
*
*/
@Override
public Directory getParent() {
- if (parent == null) {
- parent = new Directory(directoryDeprecatedKey);
- }
return parent;
}
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
@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);
}
}
/**
- * 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);
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;
}
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();
public Library(String key, String version) {
setKey(key);
- setDeprecatedKey(key);
this.version = version;
}
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;
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);
}
setKey(key);
this.name = name;
}
- setDeprecatedKey(getKey());
setEffectiveKey(getKey());
this.branch = branch;
}
/**
* 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() {
public String qualifier() {
return getQualifier();
}
+
+ // For internal use
+ public void setBaseDir(java.io.File baseDir) {
+ this.baseDir = baseDir;
+ }
+
+ java.io.File getBaseDir() {
+ return baseDir;
+ }
}
/**
* @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 {
private String uuid;
- private String deprecatedKey;
-
private String path;
private String effectiveKey;
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
*/
}
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();
}
}
package org.sonar.api.scan.filesystem;
import org.sonar.api.BatchExtension;
+import org.sonar.api.batch.fs.InputFileFilter;
import java.io.File;
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();
*/
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();
* 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 {
}
* 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\\-\\_]+";
* 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 {
}
@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);
}
@Before
public void prepare() throws Exception {
basedir = temp.newFolder();
- fs = new DefaultFileSystem(basedir);
+ fs = new DefaultFileSystem(basedir.toPath());
}
@Test
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();
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();
@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");
@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();
assertThat(inputDir1.hashCode()).isEqualTo(63545559);
- assertThat(inputDir1.toString()).contains("[moduleKey=ABCDE, relative=src, abs=");
+ assertThat(inputDir1.toString()).contains("[moduleKey=ABCDE, relative=src, basedir=null");
}
import org.sonar.api.batch.fs.InputFile;
import java.io.File;
+import java.nio.file.Paths;
import static org.assertj.core.api.Assertions.assertThat;
@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)
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
@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]");
}
}
import org.sonar.api.batch.fs.InputFile;
import java.io.File;
+import java.nio.file.Paths;
import static org.assertj.core.api.Assertions.assertThat;
@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)
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();
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
@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]");
}
}
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;
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();
}
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();
}
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();
}
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();
}
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());
}
}
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());
}
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);
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)
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)
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;
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);
}
@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);
@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);
@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);
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;
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();
}
}
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;
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
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();
@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();
@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();
@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();
@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();
}
@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));
@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));
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
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");
+ }
}
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;
@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);
}
}
--- /dev/null
+sonar.projectKey=sample
+sonar.projectName=Sample
+sonar.projectVersion=0.1-SNAPSHOT
+sonar.sources=xources
+sonar.tests=testx
+sonar.language=xoo
--- /dev/null
+../sample/testx/
\ No newline at end of file
--- /dev/null
+../sample/xources/
\ No newline at end of file
--- /dev/null
+sonar.projectKey=sample
+sonar.projectName=Sample
+sonar.projectVersion=0.1-SNAPSHOT
+sonar.sources=xources
+sonar.tests=testx
+sonar.language=xoo
--- /dev/null
+package org.sonar.tests;
+
+import org.junit.Test;
+
+public class ClassOneTest {
+
+ @Test
+ public void nothing() {
+
+ }
+}
--- /dev/null
+lines:11
+ncloc:7
+tests:1
+test_execution_time:1
+skipped_tests:0
+test_errors:0
+test_failures:0
--- /dev/null
+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
--- /dev/null
+package hello;
+
+public class HelloJava {
+
+ public static void main(String[] args) {
+ System.out.println("Hello");
+ }
+}
\ No newline at end of file
--- /dev/null
+ncloc:3
+complexity:1
--- /dev/null
+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
--- /dev/null
+ object HelloWorld {
+ def main(args: Array[String]) {
+ println("Hello, world of xoo!")
+ }
+ }
+
\ No newline at end of file
--- /dev/null
+ncloc:5
+complexity:2