From: Duarte Meneses Date: Fri, 22 Jun 2018 14:03:36 +0000 (+0200) Subject: SONAR-10138 Remove support for API < 5.6 X-Git-Tag: 7.5~913 X-Git-Url: https://source.dussan.org/?a=commitdiff_plain;h=ca183f7f3f45e1ae2338f3a5c37d44fc0e295111;p=sonarqube.git SONAR-10138 Remove support for API < 5.6 --- diff --git a/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/XooPlugin.java b/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/XooPlugin.java index 639d51c2172..82162851aa8 100644 --- a/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/XooPlugin.java +++ b/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/XooPlugin.java @@ -37,13 +37,10 @@ import org.sonar.xoo.lang.MeasureSensor; import org.sonar.xoo.lang.SignificantCodeSensor; import org.sonar.xoo.lang.SymbolReferencesSensor; import org.sonar.xoo.lang.SyntaxHighlightingSensor; -import org.sonar.xoo.lang.XooCpdMapping; -import org.sonar.xoo.lang.XooTokenizer; import org.sonar.xoo.rule.AnalysisErrorSensor; import org.sonar.xoo.rule.ChecksSensor; import org.sonar.xoo.rule.CreateIssueByInternalKeySensor; import org.sonar.xoo.rule.CustomMessageSensor; -import org.sonar.xoo.rule.DeprecatedResourceApiSensor; import org.sonar.xoo.rule.HasTagSensor; import org.sonar.xoo.rule.MultilineIssuesSensor; import org.sonar.xoo.rule.NoSonarSensor; @@ -114,10 +111,6 @@ public class XooPlugin implements Plugin { XooScmProvider.class, XooBlameCommand.class, - // CPD - XooCpdMapping.class, - XooTokenizer.class, - // sensors HasTagSensor.class, LineMeasureSensor.class, @@ -127,6 +120,7 @@ public class XooPlugin implements Plugin { RandomAccessSensor.class, SaveDataTwiceSensor.class, NoSonarSensor.class, + CpdTokenizerSensor.class, OneBlockerIssuePerFileSensor.class, OneIssuePerLineSensor.class, @@ -161,13 +155,9 @@ public class XooPlugin implements Plugin { XooPostJob.class); if (context.getRuntime().getProduct() != SonarProduct.SONARLINT) { - context.addExtensions(MeasureSensor.class, - DeprecatedResourceApiSensor.class); + context.addExtension(MeasureSensor.class); } - if (context.getSonarQubeVersion().isGreaterThanOrEqual(Version.create(5, 5))) { - context.addExtension(CpdTokenizerSensor.class); - } if (context.getSonarQubeVersion().isGreaterThanOrEqual(Version.create(6, 6))) { context.addExtension(XooBuiltInQualityProfilesDefinition.class); } diff --git a/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/lang/CpdTokenizerSensor.java b/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/lang/CpdTokenizerSensor.java index 591112eede2..9cf73d13429 100644 --- a/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/lang/CpdTokenizerSensor.java +++ b/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/lang/CpdTokenizerSensor.java @@ -35,8 +35,6 @@ import org.sonar.xoo.Xoo; */ public class CpdTokenizerSensor implements Sensor { - public static final String ENABLE_PROP = "sonar.xoo.useNewCpdTokenizerApi"; - private void tokenize(InputFile inputFile, SensorContext context) { int lineIdx = 1; NewCpdTokens newCpdTokens = context.newCpdTokens().onFile(inputFile); @@ -74,7 +72,6 @@ public class CpdTokenizerSensor implements Sensor { public void describe(SensorDescriptor descriptor) { descriptor .name("Xoo Cpd Tokenizer Sensor") - .onlyWhenConfiguration(conf -> conf.hasKey(ENABLE_PROP) || conf.hasKey(ENABLE_PROP + ".old")) .onlyOnLanguages(Xoo.KEY); } diff --git a/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/lang/LineMeasureSensor.java b/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/lang/LineMeasureSensor.java index fd43be898ac..1cf154658ad 100644 --- a/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/lang/LineMeasureSensor.java +++ b/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/lang/LineMeasureSensor.java @@ -65,7 +65,7 @@ public class LineMeasureSensor implements Sensor { if (StringUtils.isBlank(line) || line.startsWith("#")) { continue; } - processMeasure(inputFile, linesContext, measureFile, lineNumber, line); + processMeasure(linesContext, measureFile, lineNumber, line); } linesContext.save(); } catch (IOException e) { @@ -74,18 +74,18 @@ public class LineMeasureSensor implements Sensor { } } - private void processMeasure(InputFile inputFile, FileLinesContext context, File measureFile, int lineNumber, String line) { + private void processMeasure(FileLinesContext context, File measureFile, int lineNumber, String line) { try { String metricKey = StringUtils.substringBefore(line, ":"); String value = line.substring(metricKey.length() + 1); - saveMeasure(context, inputFile, metricKey, KeyValueFormat.parseIntInt(value)); + saveMeasure(context, metricKey, KeyValueFormat.parseIntInt(value)); } catch (Exception e) { LOG.error("Error processing line " + lineNumber + " of file " + measureFile.getAbsolutePath(), e); throw new IllegalStateException("Error processing line " + lineNumber + " of file " + measureFile.getAbsolutePath(), e); } } - private void saveMeasure(FileLinesContext context, InputFile xooFile, String metricKey, Map values) { + private void saveMeasure(FileLinesContext context, String metricKey, Map values) { for (Map.Entry entry : values.entrySet()) { context.setIntValue(metricKey, entry.getKey(), entry.getValue()); } diff --git a/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/lang/SymbolReferencesSensor.java b/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/lang/SymbolReferencesSensor.java index 7eb5f8289d2..d3882c3f15b 100644 --- a/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/lang/SymbolReferencesSensor.java +++ b/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/lang/SymbolReferencesSensor.java @@ -30,9 +30,8 @@ import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.sensor.Sensor; import org.sonar.api.batch.sensor.SensorContext; import org.sonar.api.batch.sensor.SensorDescriptor; -import org.sonar.api.component.ResourcePerspectives; -import org.sonar.api.source.Symbol; -import org.sonar.api.source.Symbolizable; +import org.sonar.api.batch.sensor.symbol.NewSymbol; +import org.sonar.api.batch.sensor.symbol.NewSymbolTable; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; import org.sonar.xoo.Xoo; @@ -43,15 +42,8 @@ import org.sonar.xoo.Xoo; public class SymbolReferencesSensor implements Sensor { private static final Logger LOG = Loggers.get(SymbolReferencesSensor.class); - private static final String SYMBOL_EXTENSION = ".symbol"; - private ResourcePerspectives perspectives; - - public SymbolReferencesSensor(ResourcePerspectives perspectives) { - this.perspectives = perspectives; - } - private void processFileSymbol(InputFile inputFile, SensorContext context) { File ioFile = inputFile.file(); File symbolFile = new File(ioFile.getParentFile(), ioFile.getName() + SYMBOL_EXTENSION); @@ -60,57 +52,55 @@ public class SymbolReferencesSensor implements Sensor { try { List lines = FileUtils.readLines(symbolFile, context.fileSystem().encoding().name()); int lineNumber = 0; - Symbolizable symbolizable = perspectives.as(Symbolizable.class, inputFile); - if (symbolizable != null) { - Symbolizable.SymbolTableBuilder symbolTableBuilder = symbolizable.newSymbolTableBuilder(); - for (String line : lines) { - lineNumber++; - if (StringUtils.isBlank(line) || line.startsWith("#")) { - continue; - } - processLine(symbolFile, lineNumber, symbolTableBuilder, line); + NewSymbolTable symbolTable = context.newSymbolTable() + .onFile(inputFile); + + for (String line : lines) { + lineNumber++; + if (StringUtils.isBlank(line) || line.startsWith("#")) { + continue; } - symbolizable.setSymbolTable(symbolTableBuilder.build()); + processLine(symbolFile, lineNumber, symbolTable, line); } + symbolTable.save(); } catch (IOException e) { throw new IllegalStateException(e); } } } - private static void processLine(File symbolFile, int lineNumber, Symbolizable.SymbolTableBuilder symbolTableBuilder, String line) { + private static void processLine(File symbolFile, int lineNumber, NewSymbolTable symbolTable, String line) { try { Iterator split = Splitter.on(",").split(line).iterator(); + Iterator symbolOffsets = Splitter.on(":").split(split.next()).iterator(); + + int startOffset = Integer.parseInt(symbolOffsets.next()); + int endOffset = Integer.parseInt(symbolOffsets.next()); + int defaultLen = endOffset - startOffset; + + NewSymbol s = symbolTable.newSymbol(startOffset, endOffset); - Symbol s = addSymbol(symbolTableBuilder, split.next()); while (split.hasNext()) { - addReference(symbolTableBuilder, s, split.next()); + addReference(s, split.next(), defaultLen); } } catch (Exception e) { throw new IllegalStateException("Error processing line " + lineNumber + " of file " + symbolFile.getAbsolutePath(), e); } } - private static void addReference(Symbolizable.SymbolTableBuilder symbolTableBuilder, Symbol s, String str) { + private static void addReference(NewSymbol s, String str, int defaultLen) { if (str.contains(":")) { Iterator split = Splitter.on(":").split(str).iterator(); int startOffset = Integer.parseInt(split.next()); int toOffset = Integer.parseInt(split.next()); - symbolTableBuilder.newReference(s, startOffset, toOffset); + + s.newReference(startOffset, toOffset); } else { - symbolTableBuilder.newReference(s, Integer.parseInt(str)); + int startOffset = Integer.parseInt(str); + s.newReference(startOffset, startOffset + defaultLen); } } - private static Symbol addSymbol(Symbolizable.SymbolTableBuilder symbolTableBuilder, String str) { - Iterator split = Splitter.on(":").split(str).iterator(); - - int startOffset = Integer.parseInt(split.next()); - int endOffset = Integer.parseInt(split.next()); - - return symbolTableBuilder.newSymbol(startOffset, endOffset); - } - @Override public void describe(SensorDescriptor descriptor) { descriptor diff --git a/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/lang/SyntaxHighlightingSensor.java b/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/lang/SyntaxHighlightingSensor.java index c1a848a1c28..8012f6152e3 100644 --- a/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/lang/SyntaxHighlightingSensor.java +++ b/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/lang/SyntaxHighlightingSensor.java @@ -30,9 +30,8 @@ import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.sensor.Sensor; import org.sonar.api.batch.sensor.SensorContext; import org.sonar.api.batch.sensor.SensorDescriptor; -import org.sonar.api.component.ResourcePerspectives; -import org.sonar.api.source.Highlightable; -import org.sonar.api.source.Highlightable.HighlightingBuilder; +import org.sonar.api.batch.sensor.highlighting.NewHighlighting; +import org.sonar.api.batch.sensor.highlighting.TypeOfText; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; import org.sonar.xoo.Xoo; @@ -43,15 +42,8 @@ import org.sonar.xoo.Xoo; public class SyntaxHighlightingSensor implements Sensor { private static final Logger LOG = Loggers.get(SyntaxHighlightingSensor.class); - private static final String HIGHLIGHTING_EXTENSION = ".highlighting"; - private final ResourcePerspectives perspectives; - - public SyntaxHighlightingSensor(ResourcePerspectives perspectives) { - this.perspectives = perspectives; - } - private void processFileHighlighting(InputFile inputFile, SensorContext context) { File ioFile = inputFile.file(); File highlightingFile = new File(ioFile.getParentFile(), ioFile.getName() + HIGHLIGHTING_EXTENSION); @@ -60,30 +52,28 @@ public class SyntaxHighlightingSensor implements Sensor { try { List lines = FileUtils.readLines(highlightingFile, context.fileSystem().encoding().name()); int lineNumber = 0; - Highlightable highlightable = perspectives.as(Highlightable.class, inputFile); - if (highlightable != null) { - HighlightingBuilder highlightingBuilder = highlightable.newHighlighting(); - for (String line : lines) { - lineNumber++; - if (StringUtils.isBlank(line) || line.startsWith("#")) { - continue; - } - processLine(highlightingFile, lineNumber, highlightingBuilder, line); + NewHighlighting highlighting = context.newHighlighting() + .onFile(inputFile); + for (String line : lines) { + lineNumber++; + if (StringUtils.isBlank(line) || line.startsWith("#")) { + continue; } - highlightingBuilder.done(); + processLine(highlightingFile, lineNumber, highlighting, line); } + highlighting.save(); } catch (IOException e) { throw new IllegalStateException(e); } } } - private static void processLine(File highlightingFile, int lineNumber, HighlightingBuilder highlightingBuilder, String line) { + private static void processLine(File highlightingFile, int lineNumber, NewHighlighting highlighting, String line) { try { Iterator split = Splitter.on(":").split(line).iterator(); int startOffset = Integer.parseInt(split.next()); int endOffset = Integer.parseInt(split.next()); - highlightingBuilder.highlight(startOffset, endOffset, split.next()); + highlighting.highlight(startOffset, endOffset, TypeOfText.forCssClass(split.next())); } catch (Exception e) { throw new IllegalStateException("Error processing line " + lineNumber + " of file " + highlightingFile.getAbsolutePath(), e); } diff --git a/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/lang/XooCpdMapping.java b/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/lang/XooCpdMapping.java deleted file mode 100644 index 44f51bd292b..00000000000 --- a/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/lang/XooCpdMapping.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.xoo.lang; - -import net.sourceforge.pmd.cpd.Tokenizer; -import org.sonar.api.batch.AbstractCpdMapping; -import org.sonar.api.resources.Language; -import org.sonar.xoo.Xoo; - -public class XooCpdMapping extends AbstractCpdMapping { - - private Xoo xoo; - private XooTokenizer xooTokenizer; - - public XooCpdMapping(Xoo xoo, XooTokenizer xooTokenizer) { - this.xoo = xoo; - this.xooTokenizer = xooTokenizer; - } - - @Override - public Tokenizer getTokenizer() { - return xooTokenizer; - } - - @Override - public Language getLanguage() { - return xoo; - } -} diff --git a/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/lang/XooTokenizer.java b/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/lang/XooTokenizer.java deleted file mode 100644 index 896ff1bd27f..00000000000 --- a/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/lang/XooTokenizer.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.xoo.lang; - -import com.google.common.base.Splitter; -import java.io.File; -import java.io.IOException; -import net.sourceforge.pmd.cpd.SourceCode; -import net.sourceforge.pmd.cpd.TokenEntry; -import net.sourceforge.pmd.cpd.Tokenizer; -import net.sourceforge.pmd.cpd.Tokens; -import org.apache.commons.io.FileUtils; -import org.sonar.api.batch.ScannerSide; -import org.sonar.api.batch.fs.FileSystem; -import org.sonar.api.utils.log.Logger; -import org.sonar.api.utils.log.Loggers; - -@ScannerSide -public class XooTokenizer implements Tokenizer { - - private static final Logger LOG = Loggers.get(XooTokenizer.class); - - private FileSystem fs; - - public XooTokenizer(FileSystem fs) { - this.fs = fs; - } - - @Override - public final void tokenize(SourceCode source, Tokens cpdTokens) { - String fileName = source.getFileName(); - LOG.info("Using deprecated tokenizer extension point to tokenize {}", fileName); - int lineIdx = 1; - for (String line : source.getCode()) { - for (String token : Splitter.on(" ").split(line)) { - TokenEntry cpdToken = new TokenEntry(token, fileName, lineIdx); - cpdTokens.add(cpdToken); - } - lineIdx++; - } - cpdTokens.add(TokenEntry.getEOF()); - } -} diff --git a/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/AbstractDeprecatedXooRuleSensor.java b/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/AbstractDeprecatedXooRuleSensor.java deleted file mode 100644 index 23fa6922d94..00000000000 --- a/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/AbstractDeprecatedXooRuleSensor.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.xoo.rule; - -import org.sonar.api.batch.Sensor; -import org.sonar.api.batch.SensorContext; -import org.sonar.api.batch.fs.FileSystem; -import org.sonar.api.batch.fs.InputFile; -import org.sonar.api.batch.rule.ActiveRules; -import org.sonar.api.resources.File; -import org.sonar.api.resources.Project; -import org.sonar.api.rule.RuleKey; -import org.sonar.xoo.Xoo; - -/** - * @deprecated to be replaced by {@link org.sonar.api.batch.sensor.Sensor} - */ -public abstract class AbstractDeprecatedXooRuleSensor implements Sensor { - - private final FileSystem fs; - private final ActiveRules activeRules; - - public AbstractDeprecatedXooRuleSensor(FileSystem fs, ActiveRules activeRules) { - this.fs = fs; - this.activeRules = activeRules; - } - - protected abstract String getRuleKey(); - - @Override - public boolean shouldExecuteOnProject(Project project) { - return fs.hasFiles(fs.predicates().hasLanguages(Xoo.KEY)) - && (activeRules.find(RuleKey.of(XooRulesDefinition.XOO_REPOSITORY, getRuleKey())) != null); - } - - @Override - public final void analyse(Project project, SensorContext context) { - doAnalyse(context, Xoo.KEY); - } - - private void doAnalyse(SensorContext context, String languageKey) { - RuleKey ruleKey = RuleKey.of(XooRulesDefinition.XOO_REPOSITORY, getRuleKey()); - if (activeRules.find(ruleKey) == null) { - return; - } - for (InputFile inputFile : fs.inputFiles(fs.predicates().hasLanguage(languageKey))) { - File sonarFile = File.create(inputFile.relativePath()); - sonarFile = context.getResource(sonarFile); - processFile(inputFile, sonarFile, context, ruleKey, languageKey); - } - } - - protected abstract void processFile(InputFile inputFile, File sonarFile, SensorContext context, RuleKey ruleKey, String languageKey); -} diff --git a/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/CustomMessageSensor.java b/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/CustomMessageSensor.java index 5032cd45eaa..f7d22a4c4e2 100644 --- a/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/CustomMessageSensor.java +++ b/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/CustomMessageSensor.java @@ -19,27 +19,25 @@ */ package org.sonar.xoo.rule; -import org.sonar.api.batch.SensorContext; import org.sonar.api.batch.fs.FileSystem; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.rule.ActiveRules; -import org.sonar.api.component.ResourcePerspectives; -import org.sonar.api.config.Settings; -import org.sonar.api.issue.Issuable; +import org.sonar.api.batch.sensor.SensorContext; +import org.sonar.api.batch.sensor.issue.NewIssue; +import org.sonar.api.batch.sensor.issue.NewIssueLocation; +import org.sonar.api.config.Configuration; import org.sonar.api.rule.RuleKey; -public class CustomMessageSensor extends AbstractDeprecatedXooRuleSensor { +public class CustomMessageSensor extends AbstractXooRuleSensor { public static final String RULE_KEY = "CustomMessage"; private static final String MESSAGE_PROPERTY = "sonar.customMessage.message"; - private final ResourcePerspectives perspectives; - private final Settings settings; + private final Configuration settings; - public CustomMessageSensor(ResourcePerspectives perspectives, Settings settings, FileSystem fs, ActiveRules activeRules) { + public CustomMessageSensor(Configuration settings, FileSystem fs, ActiveRules activeRules) { super(fs, activeRules); - this.perspectives = perspectives; this.settings = settings; } @@ -48,14 +46,15 @@ public class CustomMessageSensor extends AbstractDeprecatedXooRuleSensor { return RULE_KEY; } - @Override - protected void processFile(InputFile inputFile, org.sonar.api.resources.File sonarFile, SensorContext context, RuleKey ruleKey, String languageKey) { - Issuable issuable = perspectives.as(Issuable.class, sonarFile); - if (issuable != null) { - issuable.addIssue(issuable.newIssueBuilder() - .ruleKey(ruleKey) - .message(settings.getString(MESSAGE_PROPERTY)) - .build()); - } + @Override protected void processFile(InputFile inputFile, SensorContext context, RuleKey ruleKey, String languageKey) { + NewIssue newIssue = context.newIssue() + .forRule(ruleKey); + + NewIssueLocation location = newIssue.newLocation().on(inputFile); + settings.get(MESSAGE_PROPERTY).ifPresent(location::message); + + newIssue + .at(location) + .save(); } } diff --git a/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/DeprecatedResourceApiSensor.java b/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/DeprecatedResourceApiSensor.java deleted file mode 100644 index df3f9fc21c3..00000000000 --- a/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/DeprecatedResourceApiSensor.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.xoo.rule; - -import java.io.File; -import org.sonar.api.batch.Sensor; -import org.sonar.api.batch.fs.FileSystem; -import org.sonar.api.batch.fs.InputFile.Type; -import org.sonar.api.batch.rule.ActiveRules; -import org.sonar.api.component.ResourcePerspectives; -import org.sonar.api.issue.Issuable; -import org.sonar.api.resources.Directory; -import org.sonar.api.resources.Project; -import org.sonar.api.rule.RuleKey; -import org.sonar.api.scan.filesystem.PathResolver; -import org.sonar.xoo.Xoo; - -@SuppressWarnings("deprecation") -public class DeprecatedResourceApiSensor implements Sensor { - - public static final String RULE_KEY = "DeprecatedResourceApi"; - private final FileSystem fs; - private final ResourcePerspectives perspectives; - private final ActiveRules activeRules; - - public DeprecatedResourceApiSensor(FileSystem fileSystem, ResourcePerspectives perspectives, ActiveRules activeRules) { - this.fs = fileSystem; - this.perspectives = perspectives; - this.activeRules = activeRules; - } - - @Override - public boolean shouldExecuteOnProject(Project project) { - return fs.hasFiles(fs.predicates().and(fs.predicates().hasType(Type.MAIN), fs.predicates().hasLanguage(Xoo.KEY))) - && activeRules.find(RuleKey.of(XooRulesDefinition.XOO_REPOSITORY, RULE_KEY)) != null; - } - - @Override - public void analyse(Project module, org.sonar.api.batch.SensorContext context) { - for (File f : fs.files(fs.predicates().and(fs.predicates().hasType(Type.MAIN), fs.predicates().hasLanguage(Xoo.KEY)))) { - String relativePathFromBaseDir = new PathResolver().relativePath(fs.baseDir(), f); - org.sonar.api.resources.File sonarFile = org.sonar.api.resources.File.create(relativePathFromBaseDir); - Issuable issuable = perspectives.as(Issuable.class, sonarFile); - issuable.addIssue(issuable.newIssueBuilder() - .ruleKey(RuleKey.of(XooRulesDefinition.XOO_REPOSITORY, RULE_KEY)) - .message("Issue created using deprecated API") - .line(1) - .build()); - - // Message and line are nullable - issuable.addIssue(issuable.newIssueBuilder() - .ruleKey(RuleKey.of(XooRulesDefinition.XOO_REPOSITORY, RULE_KEY)) - .message(null) - .line(null) - .build()); - - sonarFile = context.getResource(sonarFile); - Directory parent = sonarFile.getParent(); - createIssueOnDir(parent); - } - - } - - private Directory createIssueOnDir(Directory dir) { - Issuable issuable = perspectives.as(Issuable.class, dir); - issuable.addIssue(issuable.newIssueBuilder() - .ruleKey(RuleKey.of(XooRulesDefinition.XOO_REPOSITORY, RULE_KEY)) - .message("Issue created using deprecated API") - .build()); - return dir; - } - -} diff --git a/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/OneBlockerIssuePerFileSensor.java b/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/OneBlockerIssuePerFileSensor.java index 4eb1d9c5ba9..9766d528389 100644 --- a/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/OneBlockerIssuePerFileSensor.java +++ b/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/OneBlockerIssuePerFileSensor.java @@ -19,24 +19,20 @@ */ package org.sonar.xoo.rule; -import org.sonar.api.batch.SensorContext; import org.sonar.api.batch.fs.FileSystem; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.rule.ActiveRules; -import org.sonar.api.component.ResourcePerspectives; -import org.sonar.api.issue.Issuable; +import org.sonar.api.batch.rule.Severity; +import org.sonar.api.batch.sensor.SensorContext; +import org.sonar.api.batch.sensor.issue.NewIssue; import org.sonar.api.rule.RuleKey; -import org.sonar.api.rule.Severity; -public class OneBlockerIssuePerFileSensor extends AbstractDeprecatedXooRuleSensor { +public class OneBlockerIssuePerFileSensor extends AbstractXooRuleSensor { public static final String RULE_KEY = "OneBlockerIssuePerFile"; - private final ResourcePerspectives perspectives; - - public OneBlockerIssuePerFileSensor(ResourcePerspectives perspectives, FileSystem fs, ActiveRules activeRules) { + public OneBlockerIssuePerFileSensor(FileSystem fs, ActiveRules activeRules) { super(fs, activeRules); - this.perspectives = perspectives; } @Override @@ -44,14 +40,13 @@ public class OneBlockerIssuePerFileSensor extends AbstractDeprecatedXooRuleSenso return RULE_KEY; } - @Override - protected void processFile(InputFile inputFile, org.sonar.api.resources.File sonarFile, SensorContext context, RuleKey ruleKey, String languageKey) { - Issuable issuable = perspectives.as(Issuable.class, sonarFile); - issuable.addIssue(issuable.newIssueBuilder() - .ruleKey(ruleKey) - .severity(Severity.BLOCKER) - .message("This issue is generated on each file. Severity is blocker, whatever quality profile") - .build()); + @Override protected void processFile(InputFile inputFile, SensorContext context, RuleKey ruleKey, String languageKey) { + NewIssue newIssue = context.newIssue() + .overrideSeverity(Severity.BLOCKER) + .forRule(ruleKey); + newIssue.at(newIssue.newLocation() + .on(inputFile) + .message("This issue is generated on each file. Severity is blocker, whatever quality profile")) + .save(); } - } diff --git a/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/OneDayDebtPerFileSensor.java b/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/OneDayDebtPerFileSensor.java index 03619e69b0f..022feef7fc9 100644 --- a/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/OneDayDebtPerFileSensor.java +++ b/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/OneDayDebtPerFileSensor.java @@ -19,23 +19,19 @@ */ package org.sonar.xoo.rule; -import org.sonar.api.batch.SensorContext; import org.sonar.api.batch.fs.FileSystem; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.rule.ActiveRules; -import org.sonar.api.component.ResourcePerspectives; -import org.sonar.api.issue.Issuable; +import org.sonar.api.batch.sensor.SensorContext; +import org.sonar.api.batch.sensor.issue.NewIssue; import org.sonar.api.rule.RuleKey; -public class OneDayDebtPerFileSensor extends AbstractDeprecatedXooRuleSensor { +public class OneDayDebtPerFileSensor extends AbstractXooRuleSensor { public static final String RULE_KEY = "OneDayDebtPerFile"; - private final ResourcePerspectives perspectives; - - public OneDayDebtPerFileSensor(ResourcePerspectives perspectives, FileSystem fs, ActiveRules activeRules) { + public OneDayDebtPerFileSensor(FileSystem fs, ActiveRules activeRules) { super(fs, activeRules); - this.perspectives = perspectives; } @Override @@ -43,15 +39,13 @@ public class OneDayDebtPerFileSensor extends AbstractDeprecatedXooRuleSensor { return RULE_KEY; } - @Override - protected void processFile(InputFile inputFile, org.sonar.api.resources.File sonarFile, SensorContext context, RuleKey ruleKey, String languageKey) { - Issuable issuable = perspectives.as(Issuable.class, sonarFile); - if (issuable != null) { - issuable.addIssue(issuable.newIssueBuilder() - .ruleKey(ruleKey) - .message("This issue is generated on each file with a debt of one day") - .build()); - } + @Override protected void processFile(InputFile inputFile, SensorContext context, RuleKey ruleKey, String languageKey) { + NewIssue newIssue = context.newIssue() + .forRule(ruleKey); + newIssue.at(newIssue.newLocation() + .on(inputFile) + .message("This issue is generated on each file with a debt of one day")) + .save(); } } diff --git a/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/OneIssuePerFileSensor.java b/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/OneIssuePerFileSensor.java index b5de515d953..162fff4fced 100644 --- a/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/OneIssuePerFileSensor.java +++ b/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/OneIssuePerFileSensor.java @@ -19,27 +19,24 @@ */ package org.sonar.xoo.rule; -import org.sonar.api.batch.SensorContext; import org.sonar.api.batch.fs.FileSystem; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.rule.ActiveRules; -import org.sonar.api.component.ResourcePerspectives; -import org.sonar.api.config.Settings; -import org.sonar.api.issue.Issuable; +import org.sonar.api.batch.sensor.SensorContext; +import org.sonar.api.batch.sensor.issue.NewIssue; +import org.sonar.api.config.Configuration; import org.sonar.api.rule.RuleKey; -public class OneIssuePerFileSensor extends AbstractDeprecatedXooRuleSensor { +public class OneIssuePerFileSensor extends AbstractXooRuleSensor { public static final String RULE_KEY = "OneIssuePerFile"; private static final String EFFORT_TO_FIX_PROPERTY = "sonar.oneIssuePerFile.effortToFix"; - private final ResourcePerspectives perspectives; - private final Settings settings; + private final Configuration settings; - public OneIssuePerFileSensor(ResourcePerspectives perspectives, Settings settings, FileSystem fs, ActiveRules activeRules) { + public OneIssuePerFileSensor(Configuration settings, FileSystem fs, ActiveRules activeRules) { super(fs, activeRules); - this.perspectives = perspectives; this.settings = settings; } @@ -48,13 +45,13 @@ public class OneIssuePerFileSensor extends AbstractDeprecatedXooRuleSensor { return RULE_KEY; } - @Override - protected void processFile(InputFile inputFile, org.sonar.api.resources.File sonarFile, SensorContext context, RuleKey ruleKey, String languageKey) { - Issuable issuable = perspectives.as(Issuable.class, sonarFile); - issuable.addIssue(issuable.newIssueBuilder() - .ruleKey(ruleKey) - .effortToFix(settings.getDouble(EFFORT_TO_FIX_PROPERTY)) - .message("This issue is generated on each file") - .build()); + @Override protected void processFile(InputFile inputFile, SensorContext context, RuleKey ruleKey, String languageKey) { + NewIssue newIssue = context.newIssue() + .forRule(ruleKey) + .gap(settings.getDouble(EFFORT_TO_FIX_PROPERTY).orElse(0.0)); + newIssue.at(newIssue.newLocation() + .on(inputFile) + .message("This issue is generated on each file")) + .save(); } } diff --git a/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/OneIssuePerLineSensor.java b/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/OneIssuePerLineSensor.java index f7467f9f4b2..33f2a8fc6a6 100644 --- a/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/OneIssuePerLineSensor.java +++ b/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/OneIssuePerLineSensor.java @@ -76,7 +76,7 @@ public class OneIssuePerLineSensor implements Sensor { if (context.getSonarQubeVersion().isGreaterThanOrEqual(Version.create(5, 5))) { newIssue.gap(context.settings().getDouble(EFFORT_TO_FIX_PROPERTY)); } else { - newIssue.effortToFix(context.settings().getDouble(EFFORT_TO_FIX_PROPERTY)); + newIssue.gap(context.settings().getDouble(EFFORT_TO_FIX_PROPERTY)); } newIssue.save(); } diff --git a/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/XooRulesDefinition.java b/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/XooRulesDefinition.java index 4f119f9ebe0..5b072445cf4 100644 --- a/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/XooRulesDefinition.java +++ b/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/rule/XooRulesDefinition.java @@ -125,9 +125,6 @@ public class XooRulesDefinition implements RulesDefinition { repo.createRule(RandomAccessSensor.RULE_KEY).setName("One Issue Per File with Random Access") .setHtmlDescription("This issue is generated on each file"); - repo.createRule(DeprecatedResourceApiSensor.RULE_KEY).setName("Issue created using deprecated API") - .setHtmlDescription("Issue created using deprecated API"); - repo.createRule(MultilineIssuesSensor.RULE_KEY).setName("Creates issues with ranges/multiple locations") .setHtmlDescription("Issue with range and multiple locations"); diff --git a/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/test/TestExecutionSensor.java b/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/test/TestExecutionSensor.java index 19aff15e8f9..eb5543bb8c9 100644 --- a/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/test/TestExecutionSensor.java +++ b/plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/test/TestExecutionSensor.java @@ -37,7 +37,7 @@ import org.sonar.api.batch.sensor.SensorDescriptor; import org.sonar.api.component.ResourcePerspectives; import org.sonar.api.test.MutableTestCase; import org.sonar.api.test.MutableTestPlan; -import org.sonar.api.test.TestCase.Status; +import org.sonar.api.test.TestCase; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; import org.sonar.xoo.Xoo; @@ -88,7 +88,7 @@ public class TestExecutionSensor implements Sensor { testCase.setDurationInMs(duration); testCase.setMessage(msg); testCase.setStackTrace(stack); - testCase.setStatus(Status.valueOf(status)); + testCase.setStatus(TestCase.Status.valueOf(status)); testCase.setType(type); } catch (Exception e) { throw new IllegalStateException("Error processing line " + lineNumber + " of file " + testExecutionFile.getAbsolutePath(), e); @@ -115,4 +115,5 @@ public class TestExecutionSensor implements Sensor { } } + } diff --git a/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/XooPluginTest.java b/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/XooPluginTest.java index e66d56e45c8..3efce09bee8 100644 --- a/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/XooPluginTest.java +++ b/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/XooPluginTest.java @@ -28,25 +28,18 @@ import org.sonar.api.internal.SonarRuntimeImpl; import org.sonar.api.utils.Version; import org.sonar.xoo.lang.CpdTokenizerSensor; import org.sonar.xoo.rule.OneExternalIssuePerLineSensor; +import org.sonar.xoo.rule.XooBuiltInQualityProfilesDefinition; import static org.assertj.core.api.Assertions.assertThat; public class XooPluginTest { @Test - public void provide_extensions_for_5_4() { + public void provide_extensions_for_5_6() { SonarRuntime runtime = SonarRuntimeImpl.forSonarLint(Version.parse("5.4")); Plugin.Context context = new PluginContextImpl.Builder().setSonarRuntime(runtime).build(); new XooPlugin().define(context); - assertThat(context.getExtensions()).hasSize(47).doesNotContain(CpdTokenizerSensor.class); - } - - @Test - public void provide_extensions_for_5_5() { - SonarRuntime runtime = SonarRuntimeImpl.forSonarQube(Version.parse("5.5"), SonarQubeSide.SCANNER); - Plugin.Context context = new PluginContextImpl.Builder().setSonarRuntime(runtime).build(); - new XooPlugin().define(context); - assertThat(context.getExtensions()).hasSize(50).contains(CpdTokenizerSensor.class); + assertThat(context.getExtensions()).hasSize(46).doesNotContain(XooBuiltInQualityProfilesDefinition.class); } @Test @@ -54,7 +47,7 @@ public class XooPluginTest { SonarRuntime runtime = SonarRuntimeImpl.forSonarQube(Version.parse("6.6"), SonarQubeSide.SCANNER); Plugin.Context context = new PluginContextImpl.Builder().setSonarRuntime(runtime).build(); new XooPlugin().define(context); - assertThat(context.getExtensions()).hasSize(52).contains(CpdTokenizerSensor.class); + assertThat(context.getExtensions()).hasSize(49).contains(XooBuiltInQualityProfilesDefinition.class); } @Test @@ -62,6 +55,6 @@ public class XooPluginTest { SonarRuntime runtime = SonarRuntimeImpl.forSonarQube(Version.parse("7.2"), SonarQubeSide.SCANNER); Plugin.Context context = new PluginContextImpl.Builder().setSonarRuntime(runtime).build(); new XooPlugin().define(context); - assertThat(context.getExtensions()).hasSize(55).contains(OneExternalIssuePerLineSensor.class); + assertThat(context.getExtensions()).hasSize(52).contains(OneExternalIssuePerLineSensor.class); } } diff --git a/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/lang/SymbolReferencesSensorTest.java b/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/lang/SymbolReferencesSensorTest.java index 9dc9f998316..cff6a4d332f 100644 --- a/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/lang/SymbolReferencesSensorTest.java +++ b/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/lang/SymbolReferencesSensorTest.java @@ -27,32 +27,27 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.sonar.api.batch.fs.InputFile; +import org.sonar.api.batch.fs.internal.DefaultTextPointer; +import org.sonar.api.batch.fs.internal.DefaultTextRange; import org.sonar.api.batch.fs.internal.TestInputFileBuilder; import org.sonar.api.batch.sensor.internal.DefaultSensorDescriptor; import org.sonar.api.batch.sensor.internal.SensorContextTester; -import org.sonar.api.component.ResourcePerspectives; -import org.sonar.api.source.Symbol; -import org.sonar.api.source.Symbolizable; +import org.sonar.xoo.Xoo; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; +import static org.assertj.core.api.Assertions.assertThat; public class SymbolReferencesSensorTest { - private SymbolReferencesSensor sensor; + private SymbolReferencesSensor sensor = new SymbolReferencesSensor(); private SensorContextTester context; @Rule public TemporaryFolder temp = new TemporaryFolder(); private File baseDir; - private ResourcePerspectives perspectives; @Before public void prepare() throws IOException { baseDir = temp.newFolder(); - perspectives = mock(ResourcePerspectives.class); - sensor = new SymbolReferencesSensor(perspectives); context = SensorContextTester.create(baseDir); } @@ -72,24 +67,19 @@ public class SymbolReferencesSensorTest { public void testExecution() throws IOException { File symbol = new File(baseDir, "src/foo.xoo.symbol"); FileUtils.write(symbol, "1:4,7\n12:15,23:33\n\n#comment"); - InputFile inputFile = new TestInputFileBuilder("foo", "src/foo.xoo").setLanguage("xoo").setModuleBaseDir(baseDir.toPath()).build(); + InputFile inputFile = new TestInputFileBuilder("foo", "src/foo.xoo") + .initMetadata("xoo file with some source code and length over 33") + .setLanguage(Xoo.KEY) + .setModuleBaseDir(baseDir.toPath()) + .build(); context.fileSystem().add(inputFile); - Symbolizable symbolizable = mock(Symbolizable.class); - when(perspectives.as(Symbolizable.class, inputFile)).thenReturn(symbolizable); - Symbolizable.SymbolTableBuilder symbolTableBuilder = mock(Symbolizable.SymbolTableBuilder.class); - when(symbolizable.newSymbolTableBuilder()).thenReturn(symbolTableBuilder); - - Symbol symbol1 = mock(Symbol.class); - when(symbolTableBuilder.newSymbol(1, 4)).thenReturn(symbol1); - Symbol symbol2 = mock(Symbol.class); - when(symbolTableBuilder.newSymbol(12, 15)).thenReturn(symbol2); sensor.execute(context); - verify(symbolTableBuilder).newSymbol(1, 4); - verify(symbolTableBuilder).newReference(symbol1, 7); - verify(symbolTableBuilder).newSymbol(12, 15); - verify(symbolTableBuilder).newReference(symbol2, 23, 33); + assertThat(context.referencesForSymbolAt("foo:src/foo.xoo", 1, 2)) + .containsOnly(new DefaultTextRange(new DefaultTextPointer(1, 7), new DefaultTextPointer(1,10))); + assertThat(context.referencesForSymbolAt("foo:src/foo.xoo", 1, 13)) + .containsOnly(new DefaultTextRange(new DefaultTextPointer(1, 23), new DefaultTextPointer(1,33))); } } diff --git a/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/lang/SyntaxHighlightingSensorTest.java b/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/lang/SyntaxHighlightingSensorTest.java index 97f90433469..861f1ebee21 100644 --- a/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/lang/SyntaxHighlightingSensorTest.java +++ b/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/lang/SyntaxHighlightingSensorTest.java @@ -28,15 +28,11 @@ import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.api.batch.fs.internal.TestInputFileBuilder; +import org.sonar.api.batch.sensor.highlighting.TypeOfText; import org.sonar.api.batch.sensor.internal.DefaultSensorDescriptor; import org.sonar.api.batch.sensor.internal.SensorContextTester; -import org.sonar.api.component.ResourcePerspectives; -import org.sonar.api.source.Highlightable; -import org.sonar.api.source.Highlightable.HighlightingBuilder; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; +import static org.assertj.core.api.Assertions.assertThat; public class SyntaxHighlightingSensorTest { @@ -46,13 +42,11 @@ public class SyntaxHighlightingSensorTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); private File baseDir; - private ResourcePerspectives perspectives; @Before public void prepare() throws IOException { baseDir = temp.newFolder(); - perspectives = mock(ResourcePerspectives.class); - sensor = new SyntaxHighlightingSensor(perspectives); + sensor = new SyntaxHighlightingSensor(); context = SensorContextTester.create(baseDir); } @@ -74,7 +68,7 @@ public class SyntaxHighlightingSensorTest { @Test 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"); + FileUtils.write(symbol, "1:4:k\n12:15:cd\n\n#comment"); DefaultInputFile inputFile = new TestInputFileBuilder("foo", "src/foo.xoo") .setLanguage("xoo") .setModuleBaseDir(baseDir.toPath()) @@ -82,15 +76,9 @@ public class SyntaxHighlightingSensorTest { .build(); context.fileSystem().add(inputFile); - Highlightable highlightable = mock(Highlightable.class); - when(perspectives.as(Highlightable.class, inputFile)).thenReturn(highlightable); - HighlightingBuilder builder = mock(Highlightable.HighlightingBuilder.class); - when(highlightable.newHighlighting()).thenReturn(builder); - sensor.execute(context); - verify(builder).highlight(1, 4, "k"); - verify(builder).highlight(12, 15, "cppd"); - verify(builder).done(); + assertThat(context.highlightingTypeAt("foo:src/foo.xoo", 1, 2)).containsOnly(TypeOfText.KEYWORD); + assertThat(context.highlightingTypeAt("foo:src/foo.xoo", 2, 8)).containsOnly(TypeOfText.COMMENT); } } diff --git a/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/lang/XooTokenizerTest.java b/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/lang/XooTokenizerTest.java deleted file mode 100644 index 0b0cbbae932..00000000000 --- a/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/lang/XooTokenizerTest.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.xoo.lang; - -import java.io.File; -import java.io.IOException; -import java.io.InputStreamReader; -import java.nio.charset.StandardCharsets; -import net.sourceforge.pmd.cpd.SourceCode; -import net.sourceforge.pmd.cpd.TokenEntry; -import net.sourceforge.pmd.cpd.Tokens; -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.DefaultFileSystem; -import org.sonar.api.batch.fs.internal.DefaultInputFile; -import org.sonar.api.batch.fs.internal.TestInputFileBuilder; -import org.sonar.api.batch.sensor.SensorContext; -import org.sonar.api.config.Settings; -import org.sonar.api.config.internal.MapSettings; -import org.sonar.duplications.cpd.FileCodeLoaderWithoutCache; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class XooTokenizerTest { - - private SensorContext context = mock(SensorContext.class); - private DefaultFileSystem fileSystem; - - @Rule - public TemporaryFolder temp = new TemporaryFolder(); - private File baseDir; - private Settings settings; - - @Before - public void prepare() throws IOException { - baseDir = temp.newFolder(); - fileSystem = new DefaultFileSystem(baseDir.toPath()); - when(context.fileSystem()).thenReturn(fileSystem); - settings = new MapSettings(); - when(context.settings()).thenReturn(settings); - } - - @Test - public void testExecution() throws IOException { - File source = new File(baseDir, "src/foo.xoo"); - FileUtils.write(source, "token1 token2 token3\ntoken4", StandardCharsets.UTF_8); - DefaultInputFile inputFile = new TestInputFileBuilder("foo", "src/foo.xoo") - .setLanguage("xoo") - .setModuleBaseDir(baseDir.toPath()) - .setCharset(StandardCharsets.UTF_8) - .build(); - fileSystem.add(inputFile); - - XooTokenizer tokenizer = new XooTokenizer(fileSystem); - Tokens cpdTokens = new Tokens(); - try (InputStreamReader reader = new InputStreamReader(inputFile.inputStream(), inputFile.charset())) { - SourceCode sourceCode = new SourceCode(new FileCodeLoaderWithoutCache(inputFile.absolutePath(), reader)); - tokenizer.tokenize(sourceCode, cpdTokens); - } - - // 4 tokens + EOF - assertThat(cpdTokens.getTokens()).hasSize(5); - assertThat(cpdTokens.getTokens().get(3)).isEqualTo(new TokenEntry("token4", "src/foo.xoo", 2)); - } -} diff --git a/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/rule/XooRulesDefinitionTest.java b/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/rule/XooRulesDefinitionTest.java index 9658ab8e3a4..48d04ccc20e 100644 --- a/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/rule/XooRulesDefinitionTest.java +++ b/plugins/sonar-xoo-plugin/src/test/java/org/sonar/xoo/rule/XooRulesDefinitionTest.java @@ -42,7 +42,7 @@ public class XooRulesDefinitionTest { assertThat(repo).isNotNull(); assertThat(repo.name()).isEqualTo("Xoo"); assertThat(repo.language()).isEqualTo("xoo"); - assertThat(repo.rules()).hasSize(19); + assertThat(repo.rules()).hasSize(18); RulesDefinition.Rule rule = repo.rule(OneIssuePerLineSensor.RULE_KEY); assertThat(rule.name()).isNotEmpty(); diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/measurecomputer/MeasureComputerContextImplTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/measurecomputer/MeasureComputerContextImplTest.java index af5e394d745..c0a84122968 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/measurecomputer/MeasureComputerContextImplTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/api/measurecomputer/MeasureComputerContextImplTest.java @@ -268,7 +268,7 @@ public class MeasureComputerContextImplTest { assertThat(result.severity()).isEqualTo("MAJOR"); assertThat(result.status()).isEqualTo("CLOSED"); assertThat(result.resolution()).isEqualTo("FIXED"); - assertThat(result.debt()).isEqualTo(Duration.create(10l)); + assertThat(result.effort()).isEqualTo(Duration.create(10l)); } private MeasureComputerContextImpl newContext(int componentRef) { diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/IssueLifecycleTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/IssueLifecycleTest.java index 04d1268c18a..e76865e0c92 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/IssueLifecycleTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/IssueLifecycleTest.java @@ -79,7 +79,7 @@ public class IssueLifecycleTest { assertThat(issue.creationDate()).isNotNull(); assertThat(issue.updateDate()).isNotNull(); assertThat(issue.status()).isEqualTo(STATUS_OPEN); - assertThat(issue.debt()).isEqualTo(DEFAULT_DURATION); + assertThat(issue.effort()).isEqualTo(DEFAULT_DURATION); assertThat(issue.isNew()).isTrue(); assertThat(issue.isCopied()).isFalse(); } @@ -192,7 +192,7 @@ public class IssueLifecycleTest { assertThat(raw.assignee()).isEqualTo("base assignee uuid"); assertThat(raw.authorLogin()).isEqualTo("base author"); assertThat(raw.tags()).containsOnly("base tag"); - assertThat(raw.debt()).isEqualTo(DEFAULT_DURATION); + assertThat(raw.effort()).isEqualTo(DEFAULT_DURATION); assertThat(raw.isOnDisabledRule()).isTrue(); assertThat(raw.selectedAt()).isEqualTo(1000L); assertThat(raw.changes().get(0).get(IssueFieldsSetter.FROM_LONG_BRANCH).oldValue()).isEqualTo("master"); @@ -259,7 +259,7 @@ public class IssueLifecycleTest { assertThat(raw.assignee()).isEqualTo("base assignee uuid"); assertThat(raw.authorLogin()).isEqualTo("base author"); assertThat(raw.tags()).containsOnly("base tag"); - assertThat(raw.debt()).isEqualTo(DEFAULT_DURATION); + assertThat(raw.effort()).isEqualTo(DEFAULT_DURATION); assertThat(raw.isOnDisabledRule()).isTrue(); assertThat(raw.selectedAt()).isEqualTo(1000L); diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/TrackerRawInputFactoryTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/TrackerRawInputFactoryTest.java index a485e760570..e98c64d0125 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/TrackerRawInputFactoryTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/TrackerRawInputFactoryTest.java @@ -128,7 +128,6 @@ public class TrackerRawInputFactoryTest { assertThat(issue.ruleKey()).isEqualTo(ruleKey); assertThat(issue.severity()).isEqualTo(Severity.BLOCKER); assertThat(issue.line()).isEqualTo(2); - assertThat(issue.effortToFix()).isEqualTo(3.14); assertThat(issue.gap()).isEqualTo(3.14); assertThat(issue.message()).isEqualTo("the message"); @@ -136,7 +135,7 @@ public class TrackerRawInputFactoryTest { assertThat(issue.checksum()).isEqualTo(input.getLineHashSequence().getHashForLine(2)); assertThat(issue.tags()).isEmpty(); assertInitializedIssue(issue); - assertThat(issue.debt()).isNull(); + assertThat(issue.effort()).isNull(); } // SONAR-10781 @@ -351,7 +350,6 @@ public class TrackerRawInputFactoryTest { assertThat(issue.authorLogin()).isNull(); assertThat(issue.effort()).isNull(); assertThat(issue.effortInMinutes()).isNull(); - assertThat(issue.debt()).isNull(); } private void assertInitializedExternalIssue(DefaultIssue issue) { diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/commonrule/CommentDensityRuleTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/commonrule/CommentDensityRuleTest.java index ec4f71a2567..b4db79a6b99 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/commonrule/CommentDensityRuleTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/commonrule/CommentDensityRuleTest.java @@ -94,7 +94,7 @@ public class CommentDensityRuleTest { assertThat(issue.severity()).isEqualTo(Severity.CRITICAL); // min_comments = (min_percent * ncloc) / (1 - min_percent) // -> threshold of 25% for 360 ncloc is 120 comment lines. 40 are already written. - assertThat(issue.effortToFix()).isEqualTo(120.0 - 40.0); + assertThat(issue.gap()).isEqualTo(120.0 - 40.0); assertThat(issue.message()).isEqualTo("80 more comment lines need to be written to reach the minimum threshold of 25.0% comment density."); } @@ -110,7 +110,7 @@ public class CommentDensityRuleTest { assertThat(issue.ruleKey()).isEqualTo(RULE_KEY); assertThat(issue.severity()).isEqualTo(Severity.CRITICAL); // 1 ncloc requires 1 comment line to reach 25% of comment density - assertThat(issue.effortToFix()).isEqualTo(1.0); + assertThat(issue.gap()).isEqualTo(1.0); assertThat(issue.message()).isEqualTo("1 more comment lines need to be written to reach the minimum threshold of 25.0% comment density."); } diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/commonrule/CoverageRuleTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/commonrule/CoverageRuleTest.java index c55caee50fd..8324ae7e1ab 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/commonrule/CoverageRuleTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/commonrule/CoverageRuleTest.java @@ -106,7 +106,7 @@ public abstract class CoverageRuleTest { assertThat(issue.ruleKey()).isEqualTo(getRuleKey()); assertThat(issue.severity()).isEqualTo(Severity.CRITICAL); // FIXME explain - assertThat(issue.effortToFix()).isEqualTo(23.0); + assertThat(issue.gap()).isEqualTo(23.0); assertThat(issue.message()).isEqualTo(getExpectedIssueMessage()); } diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/commonrule/DuplicatedBlockRuleTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/commonrule/DuplicatedBlockRuleTest.java index a42debf60b1..b90cc1556bf 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/commonrule/DuplicatedBlockRuleTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/commonrule/DuplicatedBlockRuleTest.java @@ -83,7 +83,7 @@ public class DuplicatedBlockRuleTest { assertThat(issue.ruleKey()).isEqualTo(RULE_KEY); assertThat(issue.severity()).isEqualTo(Severity.CRITICAL); - assertThat(issue.effortToFix()).isEqualTo(3.0); + assertThat(issue.gap()).isEqualTo(3.0); assertThat(issue.message()).isEqualTo("3 duplicated blocks of code must be removed."); } } diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/commonrule/SkippedTestRuleTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/commonrule/SkippedTestRuleTest.java index d2ac27d05d0..80c7dda0685 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/commonrule/SkippedTestRuleTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/commonrule/SkippedTestRuleTest.java @@ -74,7 +74,7 @@ public class SkippedTestRuleTest { assertThat(issue.ruleKey()).isEqualTo(RULE_KEY); assertThat(issue.severity()).isEqualTo(Severity.CRITICAL); - assertThat(issue.effortToFix()).isEqualTo(2.0); + assertThat(issue.gap()).isEqualTo(2.0); assertThat(issue.message()).isEqualTo("Fix or remove skipped unit tests in file \"FooTest.java\"."); } diff --git a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/commonrule/TestErrorRuleTest.java b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/commonrule/TestErrorRuleTest.java index e8338296601..b58fea4996e 100644 --- a/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/commonrule/TestErrorRuleTest.java +++ b/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/commonrule/TestErrorRuleTest.java @@ -77,7 +77,7 @@ public class TestErrorRuleTest { assertThat(issue.ruleKey()).isEqualTo(RULE_KEY); assertThat(issue.severity()).isEqualTo(Severity.CRITICAL); - assertThat(issue.effortToFix()).isEqualTo(3.0); + assertThat(issue.gap()).isEqualTo(3.0); assertThat(issue.message()).isEqualTo("Fix failing unit tests on file \"FooTest.java\"."); } diff --git a/server/sonar-ce/src/main/java/org/sonar/ce/container/ComputeEngineContainerImpl.java b/server/sonar-ce/src/main/java/org/sonar/ce/container/ComputeEngineContainerImpl.java index b84b88fd678..0d4bb529195 100644 --- a/server/sonar-ce/src/main/java/org/sonar/ce/container/ComputeEngineContainerImpl.java +++ b/server/sonar-ce/src/main/java/org/sonar/ce/container/ComputeEngineContainerImpl.java @@ -161,8 +161,6 @@ import org.sonar.server.setting.DatabaseSettingLoader; import org.sonar.server.setting.DatabaseSettingsEnabler; import org.sonar.server.setting.ThreadLocalSettings; import org.sonar.server.test.index.TestIndexer; -import org.sonar.server.user.DefaultUserFinder; -import org.sonar.server.user.DeprecatedUserFinder; import org.sonar.server.user.index.UserIndex; import org.sonar.server.user.index.UserIndexer; import org.sonar.server.util.OkHttpClientProvider; @@ -404,9 +402,6 @@ public class ComputeEngineContainerImpl implements ComputeEngineContainer { DefaultMetricFinder.class, ProjectMeasuresIndex.class, - // users - DeprecatedUserFinder.class, - DefaultUserFinder.class, UserIndexer.class, UserIndex.class, diff --git a/server/sonar-ce/src/test/java/org/sonar/ce/container/ComputeEngineContainerImplTest.java b/server/sonar-ce/src/test/java/org/sonar/ce/container/ComputeEngineContainerImplTest.java index f0149992fe5..d86e30af7fc 100644 --- a/server/sonar-ce/src/test/java/org/sonar/ce/container/ComputeEngineContainerImplTest.java +++ b/server/sonar-ce/src/test/java/org/sonar/ce/container/ComputeEngineContainerImplTest.java @@ -94,7 +94,7 @@ public class ComputeEngineContainerImplTest { assertThat(picoContainer.getComponentAdapters()) .hasSize( CONTAINER_ITSELF - + 84 // level 4 + + 82 // level 4 + 21 // content of QualityGateModule + 6 // content of CeConfigurationModule + 4 // content of CeQueueModule diff --git a/server/sonar-db-dao/src/main/java/org/sonar/db/issue/IssueDto.java b/server/sonar-db-dao/src/main/java/org/sonar/db/issue/IssueDto.java index 6cf1a9bed02..0ec0627178f 100644 --- a/server/sonar-db-dao/src/main/java/org/sonar/db/issue/IssueDto.java +++ b/server/sonar-db-dao/src/main/java/org/sonar/db/issue/IssueDto.java @@ -33,17 +33,14 @@ import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; -import org.sonar.api.resources.Project; import org.sonar.api.rule.RuleKey; import org.sonar.api.rules.RuleType; import org.sonar.api.utils.Duration; import org.sonar.api.utils.KeyValueFormat; import org.sonar.core.issue.DefaultIssue; -import org.sonar.core.util.Uuids; import org.sonar.db.component.ComponentDto; import org.sonar.db.protobuf.DbIssues; import org.sonar.db.rule.RuleDefinitionDto; -import org.sonar.db.rule.RuleDto; import static com.google.common.base.Preconditions.checkArgument; import static org.sonar.api.utils.DateUtils.dateToLong; @@ -185,14 +182,6 @@ public final class IssueDto implements Serializable { .setUpdatedAt(now); } - public static IssueDto createFor(Project project, RuleDto rule) { - return new IssueDto() - .setProjectUuid(project.getUuid()) - .setExternal(rule.isExternal()) - .setRuleId(rule.getId()) - .setKee(Uuids.create()); - } - public String getKey() { return getKee(); } diff --git a/server/sonar-server/src/main/java/org/sonar/server/notification/email/EmailNotificationChannel.java b/server/sonar-server/src/main/java/org/sonar/server/notification/email/EmailNotificationChannel.java index 3bc7ac8f557..ca2236d682c 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/notification/email/EmailNotificationChannel.java +++ b/server/sonar-server/src/main/java/org/sonar/server/notification/email/EmailNotificationChannel.java @@ -21,6 +21,7 @@ package org.sonar.server.notification.email; import java.net.MalformedURLException; import java.net.URL; +import javax.annotation.CheckForNull; import org.apache.commons.lang.StringUtils; import org.apache.commons.mail.EmailException; import org.apache.commons.mail.SimpleEmail; @@ -28,10 +29,12 @@ import org.sonar.api.config.EmailSettings; import org.sonar.api.notifications.Notification; import org.sonar.api.notifications.NotificationChannel; import org.sonar.api.user.User; -import org.sonar.api.user.UserFinder; import org.sonar.api.utils.SonarException; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; +import org.sonar.db.DbClient; +import org.sonar.db.DbSession; +import org.sonar.db.user.UserDto; import org.sonar.plugins.emailnotifications.api.EmailMessage; import org.sonar.plugins.emailnotifications.api.EmailTemplate; @@ -81,19 +84,19 @@ public class EmailNotificationChannel extends NotificationChannel { private static final String SUBJECT_DEFAULT = "Notification"; - private EmailSettings configuration; - private EmailTemplate[] templates; - private UserFinder userFinder; + private final EmailSettings configuration; + private final EmailTemplate[] templates; + private final DbClient dbClient; - public EmailNotificationChannel(EmailSettings configuration, EmailTemplate[] templates, UserFinder userFinder) { + public EmailNotificationChannel(EmailSettings configuration, EmailTemplate[] templates, DbClient dbClient) { this.configuration = configuration; this.templates = templates; - this.userFinder = userFinder; + this.dbClient = dbClient; } @Override public void deliver(Notification notification, String username) { - User user = userFinder.findByLogin(username); + User user = findByLogin(username); if (user == null || StringUtils.isBlank(user.email())) { LOG.debug("User does not exist or has no email: {}", username); return; @@ -105,6 +108,14 @@ public class EmailNotificationChannel extends NotificationChannel { } } + @CheckForNull + private User findByLogin(String login) { + try (DbSession dbSession = dbClient.openSession(false)) { + UserDto dto = dbClient.userDao().selectActiveUserByLogin(dbSession, login); + return dto != null ? dto.toUser() : null; + } + } + private EmailMessage format(Notification notification) { for (EmailTemplate template : templates) { EmailMessage email = template.format(notification); diff --git a/server/sonar-server/src/main/java/org/sonar/server/platform/platformlevel/PlatformLevel4.java b/server/sonar-server/src/main/java/org/sonar/server/platform/platformlevel/PlatformLevel4.java index beac5301928..eb0f3591501 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/platform/platformlevel/PlatformLevel4.java +++ b/server/sonar-server/src/main/java/org/sonar/server/platform/platformlevel/PlatformLevel4.java @@ -211,8 +211,6 @@ import org.sonar.server.ui.PageDecorations; import org.sonar.server.ui.PageRepository; import org.sonar.server.ui.ws.NavigationWsModule; import org.sonar.server.updatecenter.UpdateCenterModule; -import org.sonar.server.user.DefaultUserFinder; -import org.sonar.server.user.DeprecatedUserFinder; import org.sonar.server.user.NewUserNotifier; import org.sonar.server.user.SecurityRealmFactory; import org.sonar.server.user.UserSessionFactoryImpl; @@ -371,9 +369,7 @@ public class PlatformLevel4 extends PlatformLevel { // users UserSessionFactoryImpl.class, SecurityRealmFactory.class, - DeprecatedUserFinder.class, NewUserNotifier.class, - DefaultUserFinder.class, UserIndexDefinition.class, UserIndexer.class, UserIndex.class, diff --git a/server/sonar-server/src/main/java/org/sonar/server/user/DefaultUserFinder.java b/server/sonar-server/src/main/java/org/sonar/server/user/DefaultUserFinder.java deleted file mode 100644 index 64d0af6ca76..00000000000 --- a/server/sonar-server/src/main/java/org/sonar/server/user/DefaultUserFinder.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.server.user; - -import com.google.common.collect.Lists; -import java.util.Collection; -import java.util.List; -import javax.annotation.CheckForNull; -import org.sonar.api.user.User; -import org.sonar.api.user.UserFinder; -import org.sonar.api.user.UserQuery; -import org.sonar.db.DbClient; -import org.sonar.db.DbSession; -import org.sonar.db.user.UserDto; - -/** - * @since 3.6 - */ -public class DefaultUserFinder implements UserFinder { - - private final DbClient dbClient; - - public DefaultUserFinder(DbClient dbClient) { - this.dbClient = dbClient; - } - - @Override - @CheckForNull - public User findByLogin(String login) { - try (DbSession dbSession = dbClient.openSession(false)) { - UserDto dto = dbClient.userDao().selectActiveUserByLogin(dbSession, login); - return dto != null ? dto.toUser() : null; - } - } - - @Override - public List findByLogins(List logins) { - try (DbSession dbSession = dbClient.openSession(false)) { - List dtos = dbClient.userDao().selectByLogins(dbSession, logins); - return toUsers(dtos); - } - } - - @Override - public List find(UserQuery query) { - try (DbSession dbSession = dbClient.openSession(false)) { - List dtos = dbClient.userDao().selectUsers(dbSession, query); - return toUsers(dtos); - } - } - - private static List toUsers(Collection dtos) { - List users = Lists.newArrayList(); - for (UserDto dto : dtos) { - users.add(dto.toUser()); - } - return users; - } -} diff --git a/server/sonar-server/src/main/java/org/sonar/server/user/DeprecatedUserFinder.java b/server/sonar-server/src/main/java/org/sonar/server/user/DeprecatedUserFinder.java deleted file mode 100644 index 7d170b730b3..00000000000 --- a/server/sonar-server/src/main/java/org/sonar/server/user/DeprecatedUserFinder.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.server.user; - -import javax.annotation.Nullable; -import org.sonar.api.database.model.User; -import org.sonar.api.security.UserFinder; -import org.sonar.db.DbClient; -import org.sonar.db.DbSession; -import org.sonar.db.user.UserDto; - -/** - * @since 2.10 - */ -public class DeprecatedUserFinder implements UserFinder { - - private final DbClient dbClient; - - public DeprecatedUserFinder(DbClient dbClient) { - this.dbClient = dbClient; - } - - @Override - public User findById(int id) { - try (DbSession dbSession = dbClient.openSession(false)) { - return copy(dbClient.userDao().selectUserById(dbSession, id)); - } - } - - @Override - public User findByLogin(String login) { - try (DbSession dbSession = dbClient.openSession(false)) { - return copy(dbClient.userDao().selectActiveUserByLogin(dbSession, login)); - } - } - - private static User copy(@Nullable UserDto dto) { - if (dto != null) { - User user = new User().setEmail(dto.getEmail()).setLogin(dto.getLogin()).setName(dto.getName()); - user.setId(dto.getId()); - return user; - } - return null; - } - -} diff --git a/server/sonar-server/src/test/java/org/sonar/server/debt/DebtModelPluginRepositoryTest.java b/server/sonar-server/src/test/java/org/sonar/server/debt/DebtModelPluginRepositoryTest.java index 050e12a2548..9cf3896d427 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/debt/DebtModelPluginRepositoryTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/debt/DebtModelPluginRepositoryTest.java @@ -32,7 +32,7 @@ import org.apache.commons.io.IOUtils; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import org.sonar.api.SonarPlugin; +import org.sonar.api.Plugin; import org.sonar.core.platform.PluginInfo; import org.sonar.core.platform.PluginRepository; @@ -127,9 +127,9 @@ public class DebtModelPluginRepositoryTest { return loader; } - class FakePlugin extends SonarPlugin { - public List getExtensions() { - return null; + class FakePlugin implements Plugin { + @Override public void define(Context context) { + } } diff --git a/server/sonar-server/src/test/java/org/sonar/server/issue/IssueFieldsSetterTest.java b/server/sonar-server/src/test/java/org/sonar/server/issue/IssueFieldsSetterTest.java index 1d9d4e86f1f..0be2e028f14 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/issue/IssueFieldsSetterTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/issue/IssueFieldsSetterTest.java @@ -348,30 +348,30 @@ public class IssueFieldsSetterTest { } @Test - public void set_effort_to_fix() { + public void set_gap_to_fix() { boolean updated = underTest.setGap(issue, 3.14, context); assertThat(updated).isTrue(); assertThat(issue.isChanged()).isTrue(); - assertThat(issue.effortToFix()).isEqualTo(3.14); + assertThat(issue.gap()).isEqualTo(3.14); assertThat(issue.mustSendNotifications()).isFalse(); } @Test - public void not_set_effort_to_fix_if_unchanged() { + public void not_set_gap_to_fix_if_unchanged() { issue.setGap(3.14); boolean updated = underTest.setGap(issue, 3.14, context); assertThat(updated).isFalse(); assertThat(issue.isChanged()).isFalse(); - assertThat(issue.effortToFix()).isEqualTo(3.14); + assertThat(issue.gap()).isEqualTo(3.14); assertThat(issue.mustSendNotifications()).isFalse(); } @Test - public void set_past_effort() { + public void set_past_gap() { issue.setGap(3.14); boolean updated = underTest.setPastGap(issue, 1.0, context); assertThat(updated).isTrue(); - assertThat(issue.effortToFix()).isEqualTo(3.14); + assertThat(issue.gap()).isEqualTo(3.14); // do not save change assertThat(issue.currentChange()).isNull(); @@ -385,7 +385,7 @@ public class IssueFieldsSetterTest { issue.setEffort(newDebt); boolean updated = underTest.setPastEffort(issue, previousDebt, context); assertThat(updated).isTrue(); - assertThat(issue.debt()).isEqualTo(newDebt); + assertThat(issue.effort()).isEqualTo(newDebt); assertThat(issue.mustSendNotifications()).isFalse(); FieldDiffs.Diff diff = issue.currentChange().get(TECHNICAL_DEBT); @@ -399,7 +399,7 @@ public class IssueFieldsSetterTest { issue.setEffort(newDebt); boolean updated = underTest.setPastEffort(issue, null, context); assertThat(updated).isTrue(); - assertThat(issue.debt()).isEqualTo(newDebt); + assertThat(issue.effort()).isEqualTo(newDebt); assertThat(issue.mustSendNotifications()).isFalse(); FieldDiffs.Diff diff = issue.currentChange().get(TECHNICAL_DEBT); @@ -413,7 +413,7 @@ public class IssueFieldsSetterTest { Duration previousDebt = Duration.create(10 * 8 * 60); boolean updated = underTest.setPastEffort(issue, previousDebt, context); assertThat(updated).isTrue(); - assertThat(issue.debt()).isNull(); + assertThat(issue.effort()).isNull(); assertThat(issue.mustSendNotifications()).isFalse(); FieldDiffs.Diff diff = issue.currentChange().get(TECHNICAL_DEBT); diff --git a/server/sonar-server/src/test/java/org/sonar/server/user/DeprecatedUserFinderTest.java b/server/sonar-server/src/test/java/org/sonar/server/user/DeprecatedUserFinderTest.java deleted file mode 100644 index ac9fd1d769a..00000000000 --- a/server/sonar-server/src/test/java/org/sonar/server/user/DeprecatedUserFinderTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.server.user; - -import org.junit.Rule; -import org.junit.Test; -import org.sonar.api.database.model.User; -import org.sonar.api.utils.System2; -import org.sonar.db.DbTester; -import org.sonar.db.user.UserDto; - -import static org.assertj.core.api.Java6Assertions.assertThat; - -public class DeprecatedUserFinderTest { - - @Rule - public DbTester db = DbTester.create(System2.INSTANCE); - - private DeprecatedUserFinder underTest = new DeprecatedUserFinder(db.getDbClient()); - - @Test - public void shouldFindUserByLogin() { - UserDto user1 = db.users().insertUser(); - UserDto user2 = db.users().insertUser(); - - User user = underTest.findByLogin(user1.getLogin()); - assertThat(user.getId()).isEqualTo(user1.getId()); - assertThat(user.getLogin()).isEqualTo(user1.getLogin()); - assertThat(user.getName()).isEqualTo(user1.getName()); - assertThat(user.getEmail()).isEqualTo(user1.getEmail()); - - assertThat(underTest.findByLogin("unknown")).isNull(); - } - - @Test - public void shouldFindUserById() { - UserDto user1 = db.users().insertUser(); - UserDto user2 = db.users().insertUser(); - - User user = underTest.findById(user1.getId()); - assertThat(user.getId()).isEqualTo(user1.getId()); - assertThat(user.getLogin()).isEqualTo(user1.getLogin()); - assertThat(user.getName()).isEqualTo(user1.getName()); - assertThat(user.getEmail()).isEqualTo(user1.getEmail()); - - assertThat(underTest.findById(321)).isNull(); - } - -} diff --git a/server/sonar-server/src/test/projects/fake-report-plugin/src/BasePlugin.java b/server/sonar-server/src/test/projects/fake-report-plugin/src/BasePlugin.java index 8cb4dcf451d..4e3a7d41b71 100644 --- a/server/sonar-server/src/test/projects/fake-report-plugin/src/BasePlugin.java +++ b/server/sonar-server/src/test/projects/fake-report-plugin/src/BasePlugin.java @@ -17,14 +17,14 @@ * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -import org.sonar.api.SonarPlugin; +import org.sonar.api.Plugin; import java.util.Collections; import java.util.List; -public class BasePlugin extends SonarPlugin { +public class BasePlugin extends Plugin { + + public void define(Plugin.Context context) { - public List getExtensions() { - return Collections.emptyList(); } } diff --git a/server/sonar-server/src/test/projects/fake-sqale-plugin/src/BasePlugin.java b/server/sonar-server/src/test/projects/fake-sqale-plugin/src/BasePlugin.java index 8cb4dcf451d..4e3a7d41b71 100644 --- a/server/sonar-server/src/test/projects/fake-sqale-plugin/src/BasePlugin.java +++ b/server/sonar-server/src/test/projects/fake-sqale-plugin/src/BasePlugin.java @@ -17,14 +17,14 @@ * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -import org.sonar.api.SonarPlugin; +import org.sonar.api.Plugin; import java.util.Collections; import java.util.List; -public class BasePlugin extends SonarPlugin { +public class BasePlugin extends Plugin { + + public void define(Plugin.Context context) { - public List getExtensions() { - return Collections.emptyList(); } } diff --git a/server/sonar-server/src/test/projects/fake-views-plugin/src/BasePlugin.java b/server/sonar-server/src/test/projects/fake-views-plugin/src/BasePlugin.java index 8cb4dcf451d..4e3a7d41b71 100644 --- a/server/sonar-server/src/test/projects/fake-views-plugin/src/BasePlugin.java +++ b/server/sonar-server/src/test/projects/fake-views-plugin/src/BasePlugin.java @@ -17,14 +17,14 @@ * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -import org.sonar.api.SonarPlugin; +import org.sonar.api.Plugin; import java.util.Collections; import java.util.List; -public class BasePlugin extends SonarPlugin { +public class BasePlugin extends Plugin { + + public void define(Plugin.Context context) { - public List getExtensions() { - return Collections.emptyList(); } } diff --git a/server/sonar-server/src/test/projects/test-base-plugin-v2/src/BasePlugin.java b/server/sonar-server/src/test/projects/test-base-plugin-v2/src/BasePlugin.java index 8cb4dcf451d..4e3a7d41b71 100644 --- a/server/sonar-server/src/test/projects/test-base-plugin-v2/src/BasePlugin.java +++ b/server/sonar-server/src/test/projects/test-base-plugin-v2/src/BasePlugin.java @@ -17,14 +17,14 @@ * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -import org.sonar.api.SonarPlugin; +import org.sonar.api.Plugin; import java.util.Collections; import java.util.List; -public class BasePlugin extends SonarPlugin { +public class BasePlugin extends Plugin { + + public void define(Plugin.Context context) { - public List getExtensions() { - return Collections.emptyList(); } } diff --git a/server/sonar-server/src/test/projects/test-base-plugin/src/BasePlugin.java b/server/sonar-server/src/test/projects/test-base-plugin/src/BasePlugin.java index 8cb4dcf451d..4e3a7d41b71 100644 --- a/server/sonar-server/src/test/projects/test-base-plugin/src/BasePlugin.java +++ b/server/sonar-server/src/test/projects/test-base-plugin/src/BasePlugin.java @@ -17,14 +17,14 @@ * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -import org.sonar.api.SonarPlugin; +import org.sonar.api.Plugin; import java.util.Collections; import java.util.List; -public class BasePlugin extends SonarPlugin { +public class BasePlugin extends Plugin { + + public void define(Plugin.Context context) { - public List getExtensions() { - return Collections.emptyList(); } } diff --git a/server/sonar-server/src/test/projects/test-core-plugin/src/CorePlugin.java b/server/sonar-server/src/test/projects/test-core-plugin/src/CorePlugin.java index 02e3a2fd84a..8798c174d6a 100644 --- a/server/sonar-server/src/test/projects/test-core-plugin/src/CorePlugin.java +++ b/server/sonar-server/src/test/projects/test-core-plugin/src/CorePlugin.java @@ -17,14 +17,14 @@ * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -import org.sonar.api.SonarPlugin; +import org.sonar.api.Plugin; import java.util.Collections; import java.util.List; -public class CorePlugin extends SonarPlugin { +public class CorePlugin extends Plugin { + + public void define(Plugin.Context context) { - public List getExtensions() { - return Collections.emptyList(); } } diff --git a/server/sonar-server/src/test/projects/test-extend-plugin/src/ExtendPlugin.java b/server/sonar-server/src/test/projects/test-extend-plugin/src/ExtendPlugin.java index bbe5a773e5a..4845145c415 100644 --- a/server/sonar-server/src/test/projects/test-extend-plugin/src/ExtendPlugin.java +++ b/server/sonar-server/src/test/projects/test-extend-plugin/src/ExtendPlugin.java @@ -17,14 +17,14 @@ * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -import org.sonar.api.SonarPlugin; +import org.sonar.api.Plugin; import java.util.Collections; import java.util.List; -public class ExtendPlugin extends SonarPlugin { +public class ExtendPlugin extends Plugin { + + public void define(Plugin.Context context) { - public List getExtensions() { - return Collections.emptyList(); } } diff --git a/server/sonar-server/src/test/projects/test-libs-plugin/src/LibsPlugin.java b/server/sonar-server/src/test/projects/test-libs-plugin/src/LibsPlugin.java index fe80fff892e..9a027aca6b7 100644 --- a/server/sonar-server/src/test/projects/test-libs-plugin/src/LibsPlugin.java +++ b/server/sonar-server/src/test/projects/test-libs-plugin/src/LibsPlugin.java @@ -17,14 +17,14 @@ * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -import org.sonar.api.SonarPlugin; +import org.sonar.api.Plugin; import java.util.Collections; import java.util.List; -public class LibsPlugin extends SonarPlugin { +public class LibsPlugin extends Plugin { + + public void define(Plugin.Context context) { - public List getExtensions() { - return Collections.emptyList(); } } diff --git a/server/sonar-server/src/test/projects/test-require-plugin/src/RequirePlugin.java b/server/sonar-server/src/test/projects/test-require-plugin/src/RequirePlugin.java index c096dc856b6..a6b4500fcd6 100644 --- a/server/sonar-server/src/test/projects/test-require-plugin/src/RequirePlugin.java +++ b/server/sonar-server/src/test/projects/test-require-plugin/src/RequirePlugin.java @@ -17,19 +17,20 @@ * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -import org.sonar.api.SonarPlugin; + +import org.sonar.api.Plugin; import java.util.Collections; import java.util.List; -public class RequirePlugin extends SonarPlugin { +public class RequirePlugin extends Plugin { public RequirePlugin() { // call a class that is in the api published by the base plugin new org.sonar.plugins.testbase.api.BaseApi().doNothing(); } - public List getExtensions() { - return Collections.emptyList(); + public void define(Plugin.Context context) { + } } diff --git a/server/sonar-server/src/test/projects/test-requirenew-plugin/src/RequirePlugin.java b/server/sonar-server/src/test/projects/test-requirenew-plugin/src/RequirePlugin.java index c096dc856b6..78e41086c6a 100644 --- a/server/sonar-server/src/test/projects/test-requirenew-plugin/src/RequirePlugin.java +++ b/server/sonar-server/src/test/projects/test-requirenew-plugin/src/RequirePlugin.java @@ -17,19 +17,21 @@ * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -import org.sonar.api.SonarPlugin; + +import org.sonar.api.Plugin; import java.util.Collections; import java.util.List; -public class RequirePlugin extends SonarPlugin { +public class RequirePlugin extends Plugin { public RequirePlugin() { // call a class that is in the api published by the base plugin new org.sonar.plugins.testbase.api.BaseApi().doNothing(); } - public List getExtensions() { - return Collections.emptyList(); + public void define(Plugin.Context context) { + } + } diff --git a/sonar-core/src/main/java/org/sonar/core/component/ComponentKeys.java b/sonar-core/src/main/java/org/sonar/core/component/ComponentKeys.java index ea751749ca9..04e2e494ad3 100644 --- a/sonar-core/src/main/java/org/sonar/core/component/ComponentKeys.java +++ b/sonar-core/src/main/java/org/sonar/core/component/ComponentKeys.java @@ -22,8 +22,6 @@ package org.sonar.core.component; import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; import org.sonar.api.batch.fs.InputPath; -import org.sonar.api.resources.Resource; -import org.sonar.api.resources.Scopes; import static com.google.common.base.Preconditions.checkArgument; @@ -48,21 +46,6 @@ public final class ComponentKeys { // only static stuff } - /** - * @return the full key of a component, based on its parent projects' key and own key - */ - public static String createEffectiveKey(String moduleKey, Resource resource) { - if (!StringUtils.equals(Scopes.PROJECT, resource.getScope())) { - // not a project nor a library - return new StringBuilder(MAX_COMPONENT_KEY_LENGTH) - .append(moduleKey) - .append(':') - .append(resource.getKey()) - .toString(); - } - return resource.getKey(); - } - public static String createEffectiveKey(String moduleKey, InputPath inputPath) { return createEffectiveKey(moduleKey, inputPath.relativePath()); } diff --git a/sonar-core/src/main/java/org/sonar/core/i18n/I18nClassloader.java b/sonar-core/src/main/java/org/sonar/core/i18n/I18nClassloader.java index 4471e59626f..2077b53f896 100644 --- a/sonar-core/src/main/java/org/sonar/core/i18n/I18nClassloader.java +++ b/sonar-core/src/main/java/org/sonar/core/i18n/I18nClassloader.java @@ -25,7 +25,6 @@ import java.net.URL; import java.net.URLClassLoader; import java.util.List; import org.sonar.api.Plugin; -import org.sonar.api.SonarPlugin; import org.sonar.core.platform.PluginInfo; import org.sonar.core.platform.PluginRepository; diff --git a/sonar-core/src/main/java/org/sonar/core/issue/DefaultIssue.java b/sonar-core/src/main/java/org/sonar/core/issue/DefaultIssue.java index f74bcb71e1e..04513564a03 100644 --- a/sonar-core/src/main/java/org/sonar/core/issue/DefaultIssue.java +++ b/sonar-core/src/main/java/org/sonar/core/issue/DefaultIssue.java @@ -273,16 +273,6 @@ public class DefaultIssue implements Issue, Trackable, org.sonar.api.ce.measure. return this; } - /** - * @deprecated since5.5, replaced by {@link #gap()} - */ - @Deprecated - @Override - @CheckForNull - public Double effortToFix() { - return gap(); - } - @Override @CheckForNull public Double gap() { @@ -295,16 +285,6 @@ public class DefaultIssue implements Issue, Trackable, org.sonar.api.ce.measure. return this; } - /** - * @deprecated since5.5, replaced by {@link #effort()} - */ - @Deprecated - @Override - @CheckForNull - public Duration debt() { - return effort(); - } - /** * Elapsed time to fix the issue */ @@ -346,16 +326,6 @@ public class DefaultIssue implements Issue, Trackable, org.sonar.api.ce.measure. return this; } - /** - * @deprecated since 5.5, manual issue feature has been dropped. - */ - @Deprecated - @Override - @CheckForNull - public String reporter() { - return null; - } - @Override @CheckForNull public String assignee() { @@ -517,13 +487,6 @@ public class DefaultIssue implements Issue, Trackable, org.sonar.api.ce.measure. return this; } - @Override - @CheckForNull - public String actionPlanKey() { - // In 5.5, action plan is dropped. - return null; - } - public DefaultIssue setFieldChange(IssueChangeContext context, String field, @Nullable Serializable oldValue, @Nullable Serializable newValue) { if (!Objects.equals(oldValue, newValue)) { if (currentChange == null) { diff --git a/sonar-core/src/main/java/org/sonar/core/issue/DefaultIssueBuilder.java b/sonar-core/src/main/java/org/sonar/core/issue/DefaultIssueBuilder.java deleted file mode 100644 index a8df4846429..00000000000 --- a/sonar-core/src/main/java/org/sonar/core/issue/DefaultIssueBuilder.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.core.issue; - -import com.google.common.base.MoreObjects; -import com.google.common.base.Preconditions; -import com.google.common.collect.Maps; -import java.util.Map; -import javax.annotation.Nullable; -import org.sonar.api.batch.sensor.issue.NewIssueLocation; -import org.sonar.api.issue.Issuable; -import org.sonar.api.issue.Issuable.IssueBuilder; -import org.sonar.api.issue.Issue; -import org.sonar.api.rule.RuleKey; -import org.sonar.api.rules.RuleType; -import org.sonar.core.util.Uuids; - -public class DefaultIssueBuilder implements Issuable.IssueBuilder { - - private String componentKey; - private String projectKey; - private RuleKey ruleKey; - private Integer line; - private String message; - private String severity; - private Double effortToFix; - private String assigneeUuid; - private RuleType type; - private Map attributes; - private boolean isFromExternalRuleEngine; - - public DefaultIssueBuilder componentKey(String componentKey) { - this.componentKey = componentKey; - return this; - } - - public DefaultIssueBuilder projectKey(String projectKey) { - this.projectKey = projectKey; - return this; - } - - public DefaultIssueBuilder fromExternalRuleEngine(boolean fromExternalRuleEngine) { - isFromExternalRuleEngine = fromExternalRuleEngine; - return this; - } - - @Override - public DefaultIssueBuilder ruleKey(RuleKey ruleKey) { - this.ruleKey = ruleKey; - return this; - } - - @Override - public DefaultIssueBuilder line(@Nullable Integer line) { - this.line = line; - return this; - } - - @Override - public DefaultIssueBuilder message(@Nullable String s) { - this.message = s; - return this; - } - - @Override - public NewIssueLocation newLocation() { - throw unsupported(); - } - - @Override - public IssueBuilder addLocation(NewIssueLocation secondaryLocation) { - throw unsupported(); - } - - @Override - public IssueBuilder addFlow(Iterable flow) { - throw unsupported(); - } - - @Override - public IssueBuilder at(NewIssueLocation location) { - throw unsupported(); - } - - private static UnsupportedOperationException unsupported() { - return new UnsupportedOperationException("Not supported for manual issues"); - } - - @Override - public DefaultIssueBuilder severity(@Nullable String severity) { - this.severity = severity; - return this; - } - - @Override - public DefaultIssueBuilder effortToFix(@Nullable Double d) { - this.effortToFix = d; - return this; - } - - /** - * @deprecated since 5.5, manual issue feature has been dropped. - */ - @Deprecated - @Override - public DefaultIssueBuilder reporter(@Nullable String s) { - return this; - } - - public DefaultIssueBuilder assigneeUuid(@Nullable String s) { - this.assigneeUuid = s; - return this; - } - - public DefaultIssueBuilder type(@Nullable RuleType type) { - this.type = type; - return this; - } - - @Override - public DefaultIssueBuilder attribute(String key, @Nullable String value) { - if (attributes == null) { - attributes = Maps.newLinkedHashMap(); - } - attributes.put(key, value); - return this; - } - - @Override - public DefaultIssue build() { - Preconditions.checkNotNull(projectKey, "Project key must be set"); - Preconditions.checkNotNull(componentKey, "Component key must be set"); - Preconditions.checkNotNull(ruleKey, "Rule key must be set"); - - DefaultIssue issue = new DefaultIssue(); - String key = Uuids.create(); - issue.setKey(key); - issue.setType(MoreObjects.firstNonNull(type, RuleType.CODE_SMELL)); - issue.setComponentKey(componentKey); - issue.setProjectKey(projectKey); - issue.setRuleKey(ruleKey); - issue.setMessage(message); - issue.setSeverity(severity); - issue.setManualSeverity(false); - issue.setGap(effortToFix); - issue.setLine(line); - issue.setAssigneeUuid(assigneeUuid); - issue.setAttributes(attributes); - issue.setResolution(null); - issue.setStatus(Issue.STATUS_OPEN); - issue.setCloseDate(null); - issue.setNew(true); - issue.setCopied(false); - issue.setBeingClosed(false); - issue.setOnDisabledRule(false); - issue.setIsFromExternalRuleEngine(isFromExternalRuleEngine); - return issue; - } -} diff --git a/sonar-core/src/test/java/org/sonar/core/component/ComponentKeysTest.java b/sonar-core/src/test/java/org/sonar/core/component/ComponentKeysTest.java index 43533c48dbb..3d7c0d6f193 100644 --- a/sonar-core/src/test/java/org/sonar/core/component/ComponentKeysTest.java +++ b/sonar-core/src/test/java/org/sonar/core/component/ComponentKeysTest.java @@ -26,10 +26,7 @@ import static org.mockito.Mockito.when; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.batch.bootstrap.ProjectDefinition; import org.sonar.api.batch.fs.InputFile; -import org.sonar.api.resources.Directory; -import org.sonar.api.resources.Project; public class ComponentKeysTest { @Rule @@ -37,12 +34,6 @@ public class ComponentKeysTest { @Test public void create_effective_key() { - Project project = new Project(ProjectDefinition.create().setKey("my_project")); - assertThat(ComponentKeys.createEffectiveKey("my_project", project)).isEqualTo("my_project"); - - Directory dir = Directory.create("src/org/foo"); - assertThat(ComponentKeys.createEffectiveKey("my_project", dir)).isEqualTo("my_project:src/org/foo"); - InputFile file = mock(InputFile.class); when(file.relativePath()).thenReturn("foo/Bar.php"); assertThat(ComponentKeys.createEffectiveKey("my_project", file)).isEqualTo("my_project:foo/Bar.php"); diff --git a/sonar-core/src/test/java/org/sonar/core/issue/DefaultIssueBuilderTest.java b/sonar-core/src/test/java/org/sonar/core/issue/DefaultIssueBuilderTest.java deleted file mode 100644 index 8c214f89873..00000000000 --- a/sonar-core/src/test/java/org/sonar/core/issue/DefaultIssueBuilderTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.core.issue; - -import org.junit.Test; -import org.sonar.api.issue.Issue; -import org.sonar.api.rule.RuleKey; -import org.sonar.api.rule.Severity; - -import static org.assertj.core.api.Assertions.assertThat; - -public class DefaultIssueBuilderTest { - - @Test - public void build_new_issue() { - String componentKey = "org.apache.struts:struts-core:Action.java"; - String projectKey = "org.apache.struts"; - DefaultIssue issue = (DefaultIssue) new DefaultIssueBuilder() - .componentKey(componentKey) - .projectKey(projectKey) - .message("the message") - .line(123) - .effortToFix(10000.0) - .ruleKey(RuleKey.of("squid", "NullDereference")) - .fromExternalRuleEngine(false) - .severity(Severity.CRITICAL) - .attribute("JIRA", "FOO-123") - .attribute("YOUTRACK", "YT-123") - .build(); - - assertThat(issue).isNotNull(); - assertThat(issue.key()).isNotNull(); - assertThat(issue.effortToFix()).isEqualTo(10000.0); - assertThat(issue.componentKey()).isEqualTo(componentKey); - assertThat(issue.projectKey()).isEqualTo(projectKey); - assertThat(issue.message()).isEqualTo("the message"); - assertThat(issue.line()).isEqualTo(123); - assertThat(issue.ruleKey().repository()).isEqualTo("squid"); - assertThat(issue.ruleKey().rule()).isEqualTo("NullDereference"); - assertThat(issue.isFromExternalRuleEngine()).isFalse(); - assertThat(issue.severity()).isEqualTo(Severity.CRITICAL); - assertThat(issue.assignee()).isNull(); - assertThat(issue.isNew()).isTrue(); - assertThat(issue.resolution()).isNull(); - assertThat(issue.status()).isEqualTo(Issue.STATUS_OPEN); - assertThat(issue.attribute("JIRA")).isEqualTo("FOO-123"); - assertThat(issue.attribute("YOUTRACK")).isEqualTo("YT-123"); - assertThat(issue.attributes()).hasSize(2); - } - - @Test - public void not_set_default_severity() { - DefaultIssue issue = (DefaultIssue) new DefaultIssueBuilder() - .componentKey("Action.java") - .projectKey("org.apache.struts") - .ruleKey(RuleKey.of("squid", "NullDereference")) - .build(); - - assertThat(issue.severity()).isNull(); - } -} diff --git a/sonar-core/src/test/java/org/sonar/core/platform/PluginLoaderTest.java b/sonar-core/src/test/java/org/sonar/core/platform/PluginLoaderTest.java index 432296e40fc..76a1268f933 100644 --- a/sonar-core/src/test/java/org/sonar/core/platform/PluginLoaderTest.java +++ b/sonar-core/src/test/java/org/sonar/core/platform/PluginLoaderTest.java @@ -24,19 +24,14 @@ import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.Collections; -import java.util.List; -import java.util.Map; import org.assertj.core.data.MapEntry; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; -import org.sonar.api.Plugin; -import org.sonar.api.SonarPlugin; import org.sonar.updatecenter.common.Version; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; -import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; public class PluginLoaderTest { @@ -47,29 +42,6 @@ public class PluginLoaderTest { private PluginClassloaderFactory classloaderFactory = mock(PluginClassloaderFactory.class); private PluginLoader loader = new PluginLoader(new FakePluginExploder(), classloaderFactory); - @Test - public void instantiate_plugin_entry_point() { - PluginClassLoaderDef def = new PluginClassLoaderDef("fake"); - def.addMainClass("fake", FakePlugin.class.getName()); - - Map instances = loader.instantiatePluginClasses(ImmutableMap.of(def, getClass().getClassLoader())); - assertThat(instances).containsOnlyKeys("fake"); - assertThat(instances.get("fake")).isInstanceOf(FakePlugin.class); - } - - @Test - public void plugin_entry_point_must_be_no_arg_public() { - PluginClassLoaderDef def = new PluginClassLoaderDef("fake"); - def.addMainClass("fake", IncorrectPlugin.class.getName()); - - try { - loader.instantiatePluginClasses(ImmutableMap.of(def, getClass().getClassLoader())); - fail(); - } catch (IllegalStateException e) { - assertThat(e).hasMessage("Fail to instantiate class [org.sonar.core.platform.PluginLoaderTest$IncorrectPlugin] of plugin [fake]"); - } - } - @Test public void define_classloader() throws Exception { File jarFile = temp.newFile(); @@ -172,27 +144,7 @@ public class PluginLoaderTest { private static class FakePluginExploder extends PluginJarExploder { @Override public ExplodedPlugin explode(PluginInfo info) { - return new ExplodedPlugin(info.getKey(), info.getNonNullJarFile(), Collections.emptyList()); - } - } - - public static class FakePlugin extends SonarPlugin { - @Override - public List getExtensions() { - return Collections.emptyList(); - } - } - - /** - * No public empty-param constructor - */ - public static class IncorrectPlugin extends SonarPlugin { - public IncorrectPlugin(String s) { - } - - @Override - public List getExtensions() { - return Collections.emptyList(); + return new ExplodedPlugin(info.getKey(), info.getNonNullJarFile(), Collections.emptyList()); } } } diff --git a/sonar-core/src/test/projects/base-plugin/pom.xml b/sonar-core/src/test/projects/base-plugin/pom.xml index 484d5b78dea..95c772b15c4 100644 --- a/sonar-core/src/test/projects/base-plugin/pom.xml +++ b/sonar-core/src/test/projects/base-plugin/pom.xml @@ -13,7 +13,7 @@ org.sonarsource.sonarqube sonar-plugin-api - 5.2-SNAPSHOT + 7.2-SNAPSHOT provided diff --git a/sonar-core/src/test/projects/base-plugin/src/org/sonar/plugins/base/BasePlugin.java b/sonar-core/src/test/projects/base-plugin/src/org/sonar/plugins/base/BasePlugin.java index 6afa10ce96c..d6619367f09 100644 --- a/sonar-core/src/test/projects/base-plugin/src/org/sonar/plugins/base/BasePlugin.java +++ b/sonar-core/src/test/projects/base-plugin/src/org/sonar/plugins/base/BasePlugin.java @@ -2,11 +2,11 @@ package org.sonar.plugins.base; import java.util.Collections; import java.util.List; -import org.sonar.api.SonarPlugin; +import org.sonar.api.Plugin; -public class BasePlugin extends SonarPlugin { +public class BasePlugin implements Plugin { + + public void define(Plugin.Context context) { - public List getExtensions() { - return Collections.emptyList(); } } diff --git a/sonar-core/src/test/projects/base-plugin/target/base-plugin-0.1-SNAPSHOT.jar b/sonar-core/src/test/projects/base-plugin/target/base-plugin-0.1-SNAPSHOT.jar index c2bdb08c95c..87f9e2899cd 100644 Binary files a/sonar-core/src/test/projects/base-plugin/target/base-plugin-0.1-SNAPSHOT.jar and b/sonar-core/src/test/projects/base-plugin/target/base-plugin-0.1-SNAPSHOT.jar differ diff --git a/sonar-core/src/test/projects/dependent-plugin/pom.xml b/sonar-core/src/test/projects/dependent-plugin/pom.xml index dcb4754e3fc..9bd5580863d 100644 --- a/sonar-core/src/test/projects/dependent-plugin/pom.xml +++ b/sonar-core/src/test/projects/dependent-plugin/pom.xml @@ -13,7 +13,7 @@ org.sonarsource.sonarqube sonar-plugin-api - 5.2-SNAPSHOT + 7.2-SNAPSHOT provided diff --git a/sonar-core/src/test/projects/dependent-plugin/src/org/sonar/plugins/dependent/DependentPlugin.java b/sonar-core/src/test/projects/dependent-plugin/src/org/sonar/plugins/dependent/DependentPlugin.java index 2b7783ae4fe..907a09ee83f 100644 --- a/sonar-core/src/test/projects/dependent-plugin/src/org/sonar/plugins/dependent/DependentPlugin.java +++ b/sonar-core/src/test/projects/dependent-plugin/src/org/sonar/plugins/dependent/DependentPlugin.java @@ -2,17 +2,17 @@ package org.sonar.plugins.dependent; import java.util.Collections; import java.util.List; -import org.sonar.api.SonarPlugin; +import org.sonar.api.Plugin; import org.sonar.plugins.base.api.BaseApi; -public class DependentPlugin extends SonarPlugin { +public class DependentPlugin implements Plugin { public DependentPlugin() { // uses a class that is exported by base-plugin new BaseApi().doNothing(); } - public List getExtensions() { - return Collections.emptyList(); + public void define(Plugin.Context context) { + } } diff --git a/sonar-core/src/test/projects/dependent-plugin/target/dependent-plugin-0.1-SNAPSHOT.jar b/sonar-core/src/test/projects/dependent-plugin/target/dependent-plugin-0.1-SNAPSHOT.jar index b828a8c6386..81b8475944e 100644 Binary files a/sonar-core/src/test/projects/dependent-plugin/target/dependent-plugin-0.1-SNAPSHOT.jar and b/sonar-core/src/test/projects/dependent-plugin/target/dependent-plugin-0.1-SNAPSHOT.jar differ diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/BatchExtension.java b/sonar-plugin-api/src/main/java/org/sonar/api/BatchExtension.java deleted file mode 100644 index b4d4e04bab0..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/BatchExtension.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api; - -import org.sonar.api.batch.ScannerSide; - -/** - * Marker interface for all the batch extension points, which are aimed to be implemented - * by plugins. - * - * @since 1.10 - * @deprecated since 5.2 replaced by {@link ScannerSide} and {@link ExtensionPoint} annotations - */ -@Deprecated -public interface BatchExtension extends Extension, BatchComponent { - -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/CoreProperties.java b/sonar-plugin-api/src/main/java/org/sonar/api/CoreProperties.java index 51ff7cab643..3b225c59e77 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/CoreProperties.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/CoreProperties.java @@ -362,6 +362,7 @@ public interface CoreProperties { /** * @since 3.6 */ + //TODO remove? String PROFILING_LOG_PROPERTY = "sonar.showProfiling"; /** diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/Extension.java b/sonar-plugin-api/src/main/java/org/sonar/api/Extension.java deleted file mode 100644 index 6c7165c3f07..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/Extension.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api; - -/** - * Plugin extension point - * - * @since 1.10 - * @deprecated since 5.2 replaced by {@link ExtensionPoint} annotation - */ -@Deprecated -@ExtensionPoint -public interface Extension { -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/ExtensionProvider.java b/sonar-plugin-api/src/main/java/org/sonar/api/ExtensionProvider.java index e09f804b972..9e4bdca9e59 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/ExtensionProvider.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/ExtensionProvider.java @@ -19,7 +19,6 @@ */ package org.sonar.api; -import org.sonar.api.batch.BatchSide; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.server.ServerSide; diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/ServerComponent.java b/sonar-plugin-api/src/main/java/org/sonar/api/ServerComponent.java deleted file mode 100644 index e3658619457..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/ServerComponent.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api; - -import org.sonar.api.server.ServerSide; - -/** - * Same than {@link org.sonar.api.BatchComponent} but for server-side components. - * - * @since 2.2 - * @deprecated in 5.2. Use {@link ServerSide} annotation instead. - */ -@Deprecated -@ServerSide -public interface ServerComponent { -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/ServerExtension.java b/sonar-plugin-api/src/main/java/org/sonar/api/ServerExtension.java deleted file mode 100644 index 75ecd2bcaee..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/ServerExtension.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api; - -import org.sonar.api.ce.ComputeEngineSide; -import org.sonar.api.server.ServerSide; - -/** - * Server extension point. - * - * @since 1.10 - * @deprecated since 5.2. Use annotations {@link ServerSide} or {@link ComputeEngineSide} and {@link ExtensionPoint} - */ -@Deprecated -public interface ServerExtension extends Extension, ServerComponent { -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/AbstractCpdMapping.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/AbstractCpdMapping.java deleted file mode 100644 index 8e26d7ce35b..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/AbstractCpdMapping.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.batch; - -import java.util.List; -import org.sonar.api.resources.Resource; - -/** - * A pre-implementation of the CpdMapping extension point - * - * @since 1.10 - * @deprecated since 5.6 use {@link org.sonar.api.batch.sensor.SensorContext#newCpdTokens()} - */ -@Deprecated -public abstract class AbstractCpdMapping implements CpdMapping { - - /** - * {@inheritDoc} - */ - @Override - public Resource createResource(java.io.File file, List sourceDirs) { - throw new UnsupportedOperationException("Deprecated since 4.2"); - } -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/BatchSide.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/BatchSide.java deleted file mode 100644 index 95234202e39..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/BatchSide.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.batch; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Marker annotation for all the components available in container of batch (code analyzer). Note that - * injection of dependencies by constructor is used : - *
- *   {@literal @}BatchSide
- *   public class Foo {
- *
- *   }
- *   {@literal @}BatchSide
- *   public class Bar {
- *     private final Foo foo;
- *     public Bar(Foo f) {
- *       this.foo = f;
- *     }
- *   }
- *
- * 
- * @deprecated since 6.0. Use {@link ScannerSide} instead. - * @since 5.2 - */ -@Deprecated -@Documented -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.TYPE) -public @interface BatchSide { -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/BuildBreaker.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/BuildBreaker.java deleted file mode 100644 index 72f441526f9..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/BuildBreaker.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.batch; - -import org.sonar.api.utils.SonarException; - -/** - * @since 1.10 - * @deprecated since 5.6 - */ -@Deprecated -@Phase(name = Phase.Name.POST) -public abstract class BuildBreaker implements PostJob { - - /** - * Execute this method to fail the build. - */ - protected void fail(String message) { - throw new SonarException(message); - } -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/CheckProject.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/CheckProject.java deleted file mode 100644 index 608012fa205..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/CheckProject.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.batch; - -import org.sonar.api.resources.Project; - -/** - * @since 1.10 - * @deprecated since 5.6 - */ -@Deprecated -public interface CheckProject { - - boolean shouldExecuteOnProject(Project project); - -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/CoverageExtension.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/CoverageExtension.java deleted file mode 100644 index f7beea09238..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/CoverageExtension.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.batch; - -import org.sonar.api.ExtensionPoint; - -/** - * @since 2.6 - * @deprecated since 5.2 not used anymore - */ -@Deprecated -@ScannerSide -@ExtensionPoint -public interface CoverageExtension { - -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/CpdMapping.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/CpdMapping.java deleted file mode 100644 index e6c47fb3abe..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/CpdMapping.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.batch; - -import java.io.File; -import java.util.List; -import net.sourceforge.pmd.cpd.Tokenizer; -import org.sonar.api.ExtensionPoint; -import org.sonar.api.resources.Language; -import org.sonar.api.resources.Resource; - -/** - * Implement this extension to get Copy/Paste detection for your language. - * @since 1.10 - * @deprecated since 5.5 use {@link SensorContext#newCpdTokens()} - */ -@ScannerSide -@ExtensionPoint -@Deprecated -public interface CpdMapping { - - Tokenizer getTokenizer(); - - Language getLanguage(); - - /** - * @deprecated since 4.2 not used anymore - */ - @Deprecated - default Resource createResource(File file, List sourceDirs) { - throw new UnsupportedOperationException("Never called by the platform"); - } - -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/Decorator.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/Decorator.java deleted file mode 100644 index 775d9dfd50c..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/Decorator.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.batch; - -import org.sonar.api.resources.Resource; - -/** - * @since 1.10 - * @deprecated since 5.2 there's no more decorator on batch side. Use {@link org.sonar.api.ce.measure.MeasureComputer} instead - */ -@Deprecated -public interface Decorator extends CheckProject { - - /** - * @param resource resource that is currently decorated, equivalent of context.getResource() - */ - void decorate(Resource resource, DecoratorContext context); - -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/DecoratorBarriers.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/DecoratorBarriers.java deleted file mode 100644 index f7269fbf506..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/DecoratorBarriers.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.batch; - -/** - * Barriers are used to define the order of execution of Decorators. Decorators must be annotated with the following : - *
- *
    - *
  • {@code @DependsUpon(BARRIER)} in order to be executed after BARRIER
  • - *
  • {@code @DependedUpon(BARRIER)} in order to be executed before BARRIER
  • - *
- * - * @since 2.3 - * @deprecated since 5.6 as {@link Decorator} is deprecated - */ -@Deprecated -public interface DecoratorBarriers { - - /** - * This barrier is before {@link #ISSUES_TRACKED}. The decorators that register issues must be declared before this - * barrier : {@code @DependedUpon(value=DecoratorBarriers.ISSUES_ADDED)} - * - * @since 3.6 - */ - String ISSUES_ADDED = "END_OF_VIOLATIONS_GENERATION"; - - /** - * This barrier is after {@link #ISSUES_ADDED}. The decorators that need to list all issues must be declared - * after this barrier : {@code @DependsUpon(value=DecoratorBarriers.ISSUES_TRACKED)} - * - * @since 3.6 - */ - String ISSUES_TRACKED = "END_OF_VIOLATION_TRACKING"; - - /** - * @deprecated in 3.6. Not required anymore. - */ - @Deprecated - String START_VIOLATIONS_GENERATION = "START_VIOLATIONS_GENERATION"; - - /** - * This barrier is used by a decorator in order to : - *
    - *
  • be executed after all the decorators which generate violations : - * {@code @DependsUpon(value=DecoratorBarriers.END_OF_VIOLATIONS_GENERATION}
  • - *
  • declare that it generates violations : {@code @DependedUpon(value=DecoratorBarriers.END_OF_VIOLATIONS_GENERATION}
  • - *
- * - * @deprecated in 3.6. Replaced by {@link #ISSUES_ADDED} - */ - @Deprecated - String END_OF_VIOLATIONS_GENERATION = "END_OF_VIOLATIONS_GENERATION"; - - /** - * Extensions which call the method {@code Violation#setSwitchedOff} must be executed before this barrier - * ({@code @DependedUpon(value=DecoratorBarriers.VIOLATION_TRACKING}) - *
- * This barrier is after {@code END_OF_VIOLATIONS_GENERATION} - * - * @since 2.8 - * @deprecated in 3.6. Not required anymore. - */ - @Deprecated - String START_VIOLATION_TRACKING = "START_VIOLATION_TRACKING"; - - /** - * This barrier is after {@code END_OF_VIOLATIONS_GENERATION} and {@code START_VIOLATION_TRACKING}. - * Decorators executed after this barrier ({@code @DependsUpon(value=DecoratorBarriers.END_OF_VIOLATION_TRACKING}) - * can benefit from all the features of violation tracking : - *
    - *
  • {@code Violation#getCreatedAt()}
  • - *
  • {@code Violation#isSwitchedOff()}, usually to know if a violation has been flagged as false-positives in UI
  • - *
- * - * @since 2.8 - * @deprecated in 3.6. Replaced by {@link #ISSUES_TRACKED} - */ - @Deprecated - String END_OF_VIOLATION_TRACKING = "END_OF_VIOLATION_TRACKING"; - - /** - * @since 2.13 - * @deprecated in 3.6. Issues are persisted at the end of analysis. - */ - @Deprecated - String START_VIOLATION_PERSISTENCE = "START_VIOLATION_PERSISTENCE"; - - /** - * @since 2.13 - * @deprecated in 3.6. Issues are persisted at the end of analysis - */ - @Deprecated - String END_OF_VIOLATION_PERSISTENCE = "END_OF_VIOLATION_PERSISTENCE"; - - /** - * Any kinds of time machine data are calculated before this barrier. Decorators executed after this barrier can use - * Measure#getVariationValue() method. - * - * @since 2.5 - */ - String END_OF_TIME_MACHINE = "END_OF_TIME_MACHINE"; -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/DecoratorContext.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/DecoratorContext.java deleted file mode 100644 index d5e563473a4..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/DecoratorContext.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.batch; - -import java.util.Collection; -import java.util.List; -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.Project; -import org.sonar.api.resources.Resource; - -/** - * @since 1.10 - * @deprecated since 5.6 as {@link Decorator} is deprecated - */ -@Deprecated -public interface DecoratorContext { - - /** - * @return the project in which the decorator is - */ - Project getProject(); - - /** - * @return the resource that is currently decorated - */ - Resource getResource(); - - /** - * Child contexts are read only - */ - List getChildren(); - - // MEASURES - - /** - * Find a measure for the resource - */ - Measure getMeasure(Metric metric); - - /** - * Never return null. - */ - M getMeasures(MeasuresFilter filter); - - /** - * Never return null. - */ - Collection getChildrenMeasures(MeasuresFilter filter); - - /** - * @return the resource children measures for the given metric - */ - Collection getChildrenMeasures(Metric metric); - - /** - * Add a new measure on the current resource. It can not be executed from children contexts. - * - * @return the same context - */ - DecoratorContext saveMeasure(Measure measure); - - /** - * Add a new measure on the current resource. It can not be executed from children contexts. - * - * @return the current object - */ - DecoratorContext saveMeasure(Metric metric, Double value); - - // DEPENDENCIES - /** - * @deprecated since 5.2 No more design features. No-op. - */ - @Deprecated - Dependency saveDependency(Dependency dependency); - -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/DefaultFormulaContext.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/DefaultFormulaContext.java deleted file mode 100644 index 15a5456a8f6..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/DefaultFormulaContext.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.batch; - -import org.sonar.api.measures.Formula; -import org.sonar.api.measures.FormulaContext; -import org.sonar.api.measures.Metric; -import org.sonar.api.resources.Resource; - -/** - * @since 1.11 - * @deprecated since 5.2. Aggregation of measures is provided by {@link org.sonar.api.ce.measure.MeasureComputer}. {@link org.sonar.api.batch.Decorator} - * and {@link Formula} are no more supported. - */ -@Deprecated -public class DefaultFormulaContext implements FormulaContext { - - public DefaultFormulaContext(Metric metric) { - } - - @Override - public Metric getTargetMetric() { - throw fail(); - } - - @Override - public Resource getResource() { - throw fail(); - } - - public void setMetric(Metric metric) { - throw fail(); - } - - public void setDecoratorContext(DecoratorContext decoratorContext) { - throw fail(); - } - - private static RuntimeException fail() { - throw new UnsupportedOperationException( - "Unsupported since version 5.2. Decorators and formulas are not used anymore for aggregation measures. Please use org.sonar.api.ce.measure.MeasureComputer."); - } -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/DefaultFormulaData.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/DefaultFormulaData.java deleted file mode 100644 index 8ffccfe56e6..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/DefaultFormulaData.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.batch; - -import java.util.Collection; -import org.sonar.api.measures.Formula; -import org.sonar.api.measures.FormulaData; -import org.sonar.api.measures.Measure; -import org.sonar.api.measures.MeasuresFilter; -import org.sonar.api.measures.Metric; - -/** - * @since 1.11 - * @deprecated since 5.2. Aggregation of measures is provided by {@link org.sonar.api.ce.measure.MeasureComputer}. {@link org.sonar.api.batch.Decorator} - * and {@link Formula} are no more supported. - */ -@Deprecated -public class DefaultFormulaData implements FormulaData { - - public DefaultFormulaData(DecoratorContext unused) { - } - - @Override - public Measure getMeasure(Metric metric) { - throw fail(); - } - - @Override - public M getMeasures(MeasuresFilter filter) { - throw fail(); - } - - @Override - public Collection getChildrenMeasures(MeasuresFilter filter) { - throw fail(); - } - - @Override - public Collection getChildrenMeasures(Metric metric) { - throw fail(); - } - - @Override - public Collection getChildren() { - throw fail(); - } - - private static RuntimeException fail() { - throw new UnsupportedOperationException( - "Unsupported since version 5.2. Decorators and formulas are not used anymore for aggregation measures. Please use org.sonar.api.ce.measure.MeasureComputer."); - } -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/Initializer.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/Initializer.java deleted file mode 100644 index 914d2ecc37f..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/Initializer.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.batch; - -import org.sonar.api.ExtensionPoint; -import org.sonar.api.batch.fs.FileSystem; -import org.sonar.api.resources.Project; - -/** - *

- * Initializer are executed at the very beginning of each module analysis, prior the core listing files to be analyzed. It means {@link FileSystem} should not be accessed. - *

- * @since 2.6 - * @deprecated since 6.6 no known valid use case - */ -@ScannerSide -@ExtensionPoint -@Deprecated -public abstract class Initializer implements CheckProject { - - /** - * @deprecated since 5.6 should no more be implemented by plugins - */ - @Deprecated - @Override - public boolean shouldExecuteOnProject(Project project) { - return true; - } - - /** - * @deprecated since 5.6 override {@link #execute()} instead - */ - @Deprecated - public void execute(Project project) { - execute(); - } - - public void execute() { - // To be implemented by client - } - - @Override - public String toString() { - return getClass().getSimpleName(); - } - -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/PostJob.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/PostJob.java deleted file mode 100644 index 56c5a5e540c..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/PostJob.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.batch; - -import org.sonar.api.ExtensionPoint; -import org.sonar.api.resources.Project; - -/** - * PostJobs are executed at the very end of batch analysis. A PostJob can't do any modification - * since everything is already computed (issues, measures,...).
- * WANRING: Do not rely on the fact that analysis results are available on server side. Starting from 5.x - * it is an asynchronous processing on server side. - * - * @since 1.10 - * @deprecated since 5.6 use {@link org.sonar.api.batch.postjob.PostJob} - */ -@Deprecated -@ScannerSide -@ExtensionPoint -public interface PostJob { - - void executeOn(Project project, SensorContext context); - -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/Sensor.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/Sensor.java deleted file mode 100644 index e58ce566195..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/Sensor.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.batch; - -import org.sonar.api.ExtensionPoint; -import org.sonar.api.resources.Project; - -/** - *

- * A Sensor is invoked once during the analysis of a project. The sensor can parse a flat file, connect to a web server... Sensor are - * generally used to add measure at the lowest level of the resource tree. A sensor can access and save measures on the whole tree of - * resources. - * - * - *

- * For example the Cobertura Sensor parses Cobertura report and saves the first-level of measures on resources. - * - * - *

- * A particular attention should be given to resource exclusion. Sonar already manages exclusions at file level : if you try to save a - * measure on a resource that is excluded in the settings, then Sonar will not save the measure. When handling a plugin or an external tool, - * you should make sure that exclusions are passed if you are going to get back consolidated data. - * - * - * @since 1.10 - * @deprecated since 5.6 use org.sonar.api.batch.sensor.Sensor - */ -@Deprecated -@ScannerSide -@ExtensionPoint -public interface Sensor extends CheckProject { - - /** - * Sensors that depend upon Squid must declare the following method : - * - *

-   * @DependsUpon
-   * public String dependsUponSquidAnalysis() {
-   *   return Sensor.FLAG_SQUID_ANALYSIS;
-   * }
-   * 
- */ - String FLAG_SQUID_ANALYSIS = "squid"; - - /** - * The method that is going to be run when the sensor is called - * - * @param module the module the sensor runs on - * @param context the context - */ - void analyse(Project module, SensorContext context); - -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/SensorContext.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/SensorContext.java deleted file mode 100644 index df73cc514f6..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/SensorContext.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.batch; - -import java.io.Serializable; -import java.util.Collection; -import javax.annotation.CheckForNull; -import org.sonar.api.batch.fs.InputFile; -import org.sonar.api.batch.fs.InputPath; -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.Resource; - -/** - * @since 1.10 - * @deprecated since 5.6 use {@link org.sonar.api.batch.sensor.Sensor} - */ -@Deprecated -public interface SensorContext extends org.sonar.api.batch.sensor.SensorContext { - - /** - * Search for an indexed resource. - * - * @param reference the resource reference - * @return the indexed resource, null if it's not indexed - * @since 1.10. Generic types since 2.6. - */ - @CheckForNull - R getResource(R reference); - - /** - * @since 2.6 - */ - Resource getParent(Resource reference); - - /** - * @since 2.6 - */ - - Collection getChildren(Resource reference); - - // ----------- MEASURES ON PROJECT -------------- - - /** - * @deprecated since 5.1 Sensors should not read but only save data - */ - @Deprecated - Measure getMeasure(Metric metric); - - /** - * @deprecated since 5.1 Sensors should not read but only save data - */ - @Deprecated - M getMeasures(MeasuresFilter filter); - - /** - * Add a measure on project - */ - Measure saveMeasure(Measure measure); - - /** - * Add a measure on project - */ - Measure saveMeasure(Metric metric, Double value); - - // ----------- MEASURES ON RESOURCES -------------- - - /** - * @deprecated since 5.1 Sensors should not read but only save data - */ - @Deprecated - Measure getMeasure(Resource resource, Metric metric); - - /** - * Key is updated when saving the resource. - * - * @return the key as saved in database. Null if the resource is set as excluded. - * @deprecated use the methods index() - */ - @Deprecated - String saveResource(Resource resource); - - /** - * @deprecated since 5.1 Sensors should not read but only save data - */ - @Deprecated - M getMeasures(Resource resource, MeasuresFilter filter); - - /** - * Add or update a measure. - *

- * The resource is automatically saved, so there is no need to execute the method saveResource(). Does nothing if the resource is set as - * excluded. - * - */ - Measure saveMeasure(Resource resource, Metric metric, Double value); - - /** - * Add or update a measure. - *

- * The resource is automatically saved, so there is no need to execute the method saveResource(). Does nothing if the resource is set as - * excluded. - * - */ - Measure saveMeasure(Resource resource, Measure measure); - - // ----------- DEPENDENCIES BETWEEN RESOURCES -------------- - - /** - * @deprecated since 5.2 No more design features. No-op - */ - @Deprecated - Dependency saveDependency(Dependency dependency); - - /** - * Save measure on {@link InputFile} - * @since 4.2 - */ - Measure saveMeasure(InputFile inputFile, Metric metric, Double value); - - /** - * Save measure on {@link InputFile} - * @since 4.2 - */ - Measure saveMeasure(InputFile inputFile, Measure measure); - - /** - * Allow to get {@link Resource} corresponding to provided {@link InputPath}. - * @since 4.5.2 - */ - Resource getResource(InputPath inputPath); -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/debt/DebtCharacteristic.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/debt/DebtCharacteristic.java deleted file mode 100644 index b0761d4ec56..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/debt/DebtCharacteristic.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.batch.debt; - -import javax.annotation.CheckForNull; - -/** - * @since 4.3 - * @deprecated since 5.1 debt model will soon be unavailable on batch side - */ -@Deprecated -public interface DebtCharacteristic { - String key(); - - String name(); - - @CheckForNull - Integer order(); - - boolean isSub(); -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/debt/DebtModel.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/debt/DebtModel.java deleted file mode 100644 index 790f5501d8c..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/debt/DebtModel.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.batch.debt; - -import java.util.List; -import javax.annotation.CheckForNull; - -/** - * This class can be used to retrieve characteristics or sub-characteristics from the technical debt model during analysis. - * - * Unfortunately, this class cannot be used to set characteristic on {@link org.sonar.api.measures.Measure}, - * because the Measure API still uses deprecated {@code org.sonar.api.technicaldebt.batch.Characteristic}. - * - * @since 4.3 - * @deprecated since 5.1 debt model will soon be unavailable on batch side - */ -@Deprecated -public interface DebtModel { - - /** - * Return only characteristics - */ - List characteristics(); - - /** - * Return sub-characteristics of a characteristic - */ - List subCharacteristics(String characteristicKey); - - /** - * Return characteristics and sub-characteristics - */ - List allCharacteristics(); - - /** - * Return a characteristic or a sub-characteristic by a key - */ - @CheckForNull - DebtCharacteristic characteristicByKey(String key); - -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/debt/DebtRemediationFunction.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/debt/DebtRemediationFunction.java deleted file mode 100644 index 814bcc69a6a..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/debt/DebtRemediationFunction.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.batch.debt; - -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.sonar.api.utils.Duration; -import javax.annotation.concurrent.Immutable; - -/** - * @since 4.3 - * @deprecated since 6.5 debt model will soon be unavailable on batch side - */ -@Deprecated -@Immutable -public class DebtRemediationFunction { - - public enum Type { - LINEAR, LINEAR_OFFSET, CONSTANT_ISSUE - } - - private Type type; - private Duration coefficient; - private Duration offset; - - private DebtRemediationFunction(Type type, @Nullable Duration coefficient, @Nullable Duration offset) { - this.type = type; - this.coefficient = coefficient; - this.offset = offset; - } - - public static DebtRemediationFunction create(Type type, @Nullable Duration coefficient, @Nullable Duration offset) { - return new DebtRemediationFunction(type, coefficient, offset); - } - - public static DebtRemediationFunction createLinear(Duration coefficient) { - return new DebtRemediationFunction(Type.LINEAR, coefficient, null); - } - - public static DebtRemediationFunction createLinearWithOffset(Duration coefficient, Duration offset) { - return new DebtRemediationFunction(Type.LINEAR_OFFSET, coefficient, offset); - } - - public static DebtRemediationFunction createConstantPerIssue(Duration offset) { - return new DebtRemediationFunction(Type.CONSTANT_ISSUE, null, offset); - } - - public Type type() { - return type; - } - - @CheckForNull - public Duration coefficient() { - return coefficient; - } - - @CheckForNull - public Duration offset() { - return offset; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - DebtRemediationFunction that = (DebtRemediationFunction) o; - if (type != that.type) { - return false; - } - if ((coefficient != null) ? !coefficient.equals(that.coefficient) : (that.coefficient != null)) { - return false; - } - return (offset != null) ? offset.equals(that.offset) : (that.offset == null); - } - - @Override - public int hashCode() { - int result = type.hashCode(); - result = 31 * result + (coefficient != null ? coefficient.hashCode() : 0); - result = 31 * result + (offset != null ? offset.hashCode() : 0); - return result; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("DebtRemediationFunction{"); - sb.append("type=").append(type); - sb.append(", coefficient=").append(coefficient); - sb.append(", offset=").append(offset); - sb.append('}'); - return sb.toString(); - } -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/debt/internal/DefaultDebtModel.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/debt/internal/DefaultDebtModel.java deleted file mode 100644 index 384dbeee173..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/debt/internal/DefaultDebtModel.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.batch.debt.internal; - -import java.util.Collections; -import java.util.List; -import javax.annotation.CheckForNull; -import org.sonar.api.batch.debt.DebtCharacteristic; -import org.sonar.api.batch.debt.DebtModel; - -public class DefaultDebtModel implements DebtModel { - - @Override - public List characteristics() { - return Collections.emptyList(); - } - - @Override - public List subCharacteristics(String characteristicKey) { - return Collections.emptyList(); - } - - @Override - public List allCharacteristics() { - return Collections.emptyList(); - } - - @Override - @CheckForNull - public DebtCharacteristic characteristicByKey(final String key) { - return null; - } - - @CheckForNull - public DebtCharacteristic characteristicById(int id) { - return null; - } -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/debt/internal/package-info.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/debt/internal/package-info.java deleted file mode 100644 index a93f4c9ae9a..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/debt/internal/package-info.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.batch.debt.internal; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/debt/package-info.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/debt/package-info.java deleted file mode 100644 index 34077af951b..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/debt/package-info.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.batch.debt; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/events/DecoratorExecutionHandler.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/events/DecoratorExecutionHandler.java deleted file mode 100644 index 9959f5bded7..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/events/DecoratorExecutionHandler.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.batch.events; - -import org.sonar.api.batch.Decorator; - -/** - * @since 2.8 - * @deprecated since 5.2 no more decorator - */ -@Deprecated -public interface DecoratorExecutionHandler extends EventHandler { - - /** - * This interface is not intended to be implemented by clients. - */ - interface DecoratorExecutionEvent { - - Decorator getDecorator(); - - boolean isStart(); - - boolean isEnd(); - - } - - /** - * Called before and after execution of {@link Decorator}. - */ - void onDecoratorExecution(DecoratorExecutionEvent event); - -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/events/DecoratorsPhaseHandler.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/events/DecoratorsPhaseHandler.java deleted file mode 100644 index 9bec86df8e1..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/events/DecoratorsPhaseHandler.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.batch.events; - -import java.util.List; -import org.sonar.api.batch.Decorator; - -/** - * @since 2.8 - * @deprecated since 5.2 no more decorator - */ -@Deprecated -public interface DecoratorsPhaseHandler extends EventHandler { - - /** - * This interface is not intended to be implemented by clients. - */ - interface DecoratorsPhaseEvent { - - /** - * @return list of Decorators in the order of execution - */ - List getDecorators(); - - boolean isStart(); - - boolean isEnd(); - - } - - /** - * Called before and after execution of all {@link Decorator}s. - */ - void onDecoratorsPhase(DecoratorsPhaseEvent event); - -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/events/EventHandler.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/events/EventHandler.java deleted file mode 100644 index 8f696763bf5..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/events/EventHandler.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.batch.events; - -import org.sonar.api.batch.ScannerSide; -import org.sonar.api.ExtensionPoint; - -/** - * Common interface for event handlers. - * This interface is not intended to be implemented by clients. - * - * @since 2.8 - */ -@ScannerSide -@ExtensionPoint -public interface EventHandler { - -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/events/InitializerExecutionHandler.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/events/InitializerExecutionHandler.java deleted file mode 100644 index f15ebdad784..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/events/InitializerExecutionHandler.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.batch.events; - -import org.sonar.api.batch.Initializer; - -/** - * @since 3.7 - * @deprecated since 6.0 - */ -@Deprecated -@FunctionalInterface -public interface InitializerExecutionHandler extends EventHandler { - - /** - * This interface is not intended to be implemented by clients. - */ - interface InitializerExecutionEvent { - - Initializer getInitializer(); - - boolean isStart(); - - boolean isEnd(); - - } - - /** - * Called before and after execution of {@link Initializer}. - */ - void onInitializerExecution(InitializerExecutionEvent event); - -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/events/InitializersPhaseHandler.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/events/InitializersPhaseHandler.java deleted file mode 100644 index e9a74d7a29d..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/events/InitializersPhaseHandler.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.batch.events; - -import java.util.List; -import org.sonar.api.batch.Initializer; - -/** - * @since 3.7 - * @deprecated since 6.0 - */ -@Deprecated -@FunctionalInterface -public interface InitializersPhaseHandler extends EventHandler { - - /** - * This interface is not intended to be implemented by clients. - */ - interface InitializersPhaseEvent { - - /** - * @return list of Initializers in the order of execution - */ - List getInitializers(); - - boolean isStart(); - - boolean isEnd(); - - } - - /** - * Called before and after execution of all {@link Initializer}s. - */ - void onInitializersPhase(InitializersPhaseEvent event); - -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/events/PostJobExecutionHandler.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/events/PostJobExecutionHandler.java deleted file mode 100644 index 4c905a77ca6..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/events/PostJobExecutionHandler.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.batch.events; - -import org.sonar.api.batch.PostJob; - -/** - * @since 3.6 - * @deprecated since 6.0 - */ -@Deprecated -@FunctionalInterface -public interface PostJobExecutionHandler extends EventHandler { - - /** - * This interface is not intended to be implemented by clients. - */ - interface PostJobExecutionEvent { - - PostJob getPostJob(); - - boolean isStart(); - - boolean isEnd(); - - } - - /** - * Called before and after execution of {@link PostJob}. - */ - void onPostJobExecution(PostJobExecutionEvent event); - -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/events/PostJobsPhaseHandler.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/events/PostJobsPhaseHandler.java deleted file mode 100644 index c9da6717f84..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/events/PostJobsPhaseHandler.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.batch.events; - -import java.util.List; -import org.sonar.api.batch.PostJob; - -/** - * @since 3.6 - * @deprecated since 6.0 - */ -@Deprecated -@FunctionalInterface -public interface PostJobsPhaseHandler extends EventHandler { - - /** - * This interface is not intended to be implemented by clients. - */ - interface PostJobsPhaseEvent { - - /** - * @return list of PostJob in the order of execution - */ - List getPostJobs(); - - boolean isStart(); - - boolean isEnd(); - - } - - /** - * Called before and after execution of all {@link PostJob}s. - */ - void onPostJobsPhase(PostJobsPhaseEvent event); - -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/events/ProjectAnalysisHandler.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/events/ProjectAnalysisHandler.java deleted file mode 100644 index 7b1d7364fb0..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/events/ProjectAnalysisHandler.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.batch.events; - -import org.sonar.api.resources.Project; - -/** - * @since 2.8 - * @deprecated since 6.0 - */ -@Deprecated -@FunctionalInterface -public interface ProjectAnalysisHandler extends EventHandler { - - /** - * This interface is not intended to be implemented by clients. - */ - interface ProjectAnalysisEvent { - - Project getProject(); - - boolean isStart(); - - boolean isEnd(); - - } - - /** - * Called before and after analysis of project. - */ - void onProjectAnalysis(ProjectAnalysisEvent event); - -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/events/SensorExecutionHandler.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/events/SensorExecutionHandler.java deleted file mode 100644 index feb7a1490f0..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/events/SensorExecutionHandler.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.batch.events; - -import org.sonar.api.batch.Sensor; - -/** - * @since 2.8 - * @deprecated since 6.0 - */ -@Deprecated -@FunctionalInterface -public interface SensorExecutionHandler extends EventHandler { - - /** - * This interface is not intended to be implemented by clients. - */ - interface SensorExecutionEvent { - - Sensor getSensor(); - - boolean isStart(); - - boolean isEnd(); - - } - - /** - * Called before and after execution of {@link Sensor}. - */ - void onSensorExecution(SensorExecutionEvent event); - -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/events/SensorsPhaseHandler.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/events/SensorsPhaseHandler.java deleted file mode 100644 index ab836b479d7..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/events/SensorsPhaseHandler.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.batch.events; - -import java.util.List; -import org.sonar.api.batch.Sensor; - -/** - * @since 2.8 - */ -@FunctionalInterface -public interface SensorsPhaseHandler extends EventHandler { - - /** - * This interface is not intended to be implemented by clients. - */ - interface SensorsPhaseEvent { - - /** - * @return list of Sensors in the order of execution - */ - List getSensors(); - - boolean isStart(); - - boolean isEnd(); - - } - - /** - * Called before and after execution of all {@link Sensor}s. - */ - void onSensorsPhase(SensorsPhaseEvent event); - -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/rule/Rule.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/rule/Rule.java index 65c18d07018..28a7c9c6329 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/rule/Rule.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/batch/rule/Rule.java @@ -21,7 +21,6 @@ package org.sonar.api.batch.rule; import java.util.Collection; import javax.annotation.CheckForNull; -import org.sonar.api.batch.debt.DebtRemediationFunction; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; @@ -48,21 +47,4 @@ public interface Rule { Collection params(); RuleStatus status(); - - /** - * @since 4.3 - * @deprecated since 5.2 as any computation of data are moved to server's Compute Engine. Calling this method throws an exception. - */ - @CheckForNull - @Deprecated - String debtSubCharacteristic(); - - /** - * @since 4.3 - * @deprecated since 5.2 as any computation of data are moved to server's Compute Engine. Calling this method throws an exception. - */ - @CheckForNull - @Deprecated - DebtRemediationFunction debtRemediationFunction(); - } diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/rule/internal/DefaultRule.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/rule/internal/DefaultRule.java index dd0cfe176cf..fc76ea1b943 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/rule/internal/DefaultRule.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/batch/rule/internal/DefaultRule.java @@ -25,7 +25,6 @@ import java.util.HashMap; import java.util.Map; import javax.annotation.CheckForNull; import javax.annotation.concurrent.Immutable; -import org.sonar.api.batch.debt.DebtRemediationFunction; import org.sonar.api.batch.rule.Rule; import org.sonar.api.batch.rule.RuleParam; import org.sonar.api.rule.RuleKey; @@ -101,16 +100,6 @@ public class DefaultRule implements Rule { return status; } - @Override - public String debtSubCharacteristic() { - throw new UnsupportedOperationException("Debt characteristic is not available by analyzer since version 5.2 (data computation moved to server)"); - } - - @Override - public DebtRemediationFunction debtRemediationFunction() { - throw new UnsupportedOperationException("Debt remediation function is not available by analyzer since version 5.2 (data computation moved to server)"); - } - @Override public RuleParam param(String paramKey) { return params.get(paramKey); diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/sensor/issue/Issue.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/sensor/issue/Issue.java index cb4deefe53a..cd638e4fb75 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/sensor/issue/Issue.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/batch/sensor/issue/Issue.java @@ -37,14 +37,6 @@ public interface Issue extends IIssue { List locations(); } - /** - * Effort to fix the issue. Used by technical debt model. - * @deprecated since 5.5 use {@link #gap()} - */ - @CheckForNull - @Deprecated - Double effortToFix(); - /** * Gap used to compute the effort for fixing the issue. * @since 5.5 diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/sensor/issue/NewIssue.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/sensor/issue/NewIssue.java index cb0531094d7..7490e0c112f 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/sensor/issue/NewIssue.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/batch/sensor/issue/NewIssue.java @@ -36,13 +36,6 @@ public interface NewIssue { */ NewIssue forRule(RuleKey ruleKey); - /** - * Effort to fix the issue. - * @deprecated since 5.5 use {@link #gap(Double)} - */ - @Deprecated - NewIssue effortToFix(@Nullable Double effortToFix); - /** * Gap used for the computation of the effort. * @since 5.5 diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/batch/sensor/issue/internal/DefaultIssue.java b/sonar-plugin-api/src/main/java/org/sonar/api/batch/sensor/issue/internal/DefaultIssue.java index 19f53a68af1..65bebee580d 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/batch/sensor/issue/internal/DefaultIssue.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/batch/sensor/issue/internal/DefaultIssue.java @@ -43,11 +43,6 @@ public class DefaultIssue extends AbstractDefaultIssue implements super(storage); } - @Override - public DefaultIssue effortToFix(@Nullable Double effortToFix) { - return gap(effortToFix); - } - @Override public DefaultIssue gap(@Nullable Double gap) { Preconditions.checkArgument(gap == null || gap >= 0, format("Gap must be greater than or equal 0 (got %s)", gap)); @@ -71,11 +66,6 @@ public class DefaultIssue extends AbstractDefaultIssue implements return this.gap; } - @Override - public Double effortToFix() { - return this.gap; - } - @Override public IssueLocation primaryLocation() { return primaryLocation; diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/ce/measure/Issue.java b/sonar-plugin-api/src/main/java/org/sonar/api/ce/measure/Issue.java index 7dec97ca078..c79f6b0c1bc 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/ce/measure/Issue.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/ce/measure/Issue.java @@ -51,12 +51,6 @@ public interface Issue { */ String severity(); - /** - * @deprecated since 5.5, replaced by {@link #effort()} - */ - @Deprecated - Duration debt(); - /** * @since 5.5 */ diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/ce/measure/test/TestIssue.java b/sonar-plugin-api/src/main/java/org/sonar/api/ce/measure/test/TestIssue.java index 1a76ddcc58e..00195068bb9 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/ce/measure/test/TestIssue.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/ce/measure/test/TestIssue.java @@ -78,16 +78,6 @@ public class TestIssue implements Issue { return severity; } - /** - * @deprecated since 5.5, replaced by {@link #effort} - */ - @Override - @CheckForNull - @Deprecated - public Duration debt() { - return effort(); - } - /** * @since 5.5 */ @@ -138,14 +128,6 @@ public class TestIssue implements Issue { return this; } - /** - * @deprecated since 5.5, use {@link #setEffort(Duration)} instead - */ - @Deprecated - public Builder setDebt(@Nullable Duration debt) { - return setEffort(debt); - } - /** * @since 5.5 */ diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/component/Component.java b/sonar-plugin-api/src/main/java/org/sonar/api/component/Component.java deleted file mode 100644 index a0f887e187d..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/component/Component.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.component; - -import javax.annotation.CheckForNull; - -/** - * @deprecated since 5.2 - */ -@Deprecated -public interface Component { - String key(); - - /** - * Path of the component relative to basedir of the parent module. - * @return null if this component is not a child of a module - * @since 4.2 - */ - @CheckForNull - String path(); - - String name(); - - String longName(); - - String qualifier(); -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/component/Module.java b/sonar-plugin-api/src/main/java/org/sonar/api/component/Module.java deleted file mode 100644 index 2b8082ee4cf..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/component/Module.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.component; - -/** - * @deprecated since 5.6 - */ -@Deprecated -public interface Module extends Component { - String getDescription(); - - String getBranch(); -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/component/ResourcePerspectives.java b/sonar-plugin-api/src/main/java/org/sonar/api/component/ResourcePerspectives.java index 284f45f421a..d551937bdd5 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/component/ResourcePerspectives.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/component/ResourcePerspectives.java @@ -23,7 +23,6 @@ import javax.annotation.CheckForNull; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.fs.InputPath; import org.sonar.api.batch.sensor.SensorContext; -import org.sonar.api.resources.Resource; /** * @since 3.5 @@ -32,13 +31,10 @@ import org.sonar.api.resources.Resource; @Deprecated public interface ResourcePerspectives { - @CheckForNull -

P as(Class

perspectiveClass, Resource resource); - /** * Allow to create perspective from {@link InputPath}. In particular from {@link InputFile}. + * * @since 4.5.2 */ - @CheckForNull -

P as(Class

perspectiveClass, InputPath inputPath); + @CheckForNull

P as(Class

perspectiveClass, InputPath inputPath); } diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/component/SourceFile.java b/sonar-plugin-api/src/main/java/org/sonar/api/component/SourceFile.java deleted file mode 100644 index 8c80d5442d4..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/component/SourceFile.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.component; - -/** - * @deprecated since 5.6 - */ -@Deprecated -public interface SourceFile extends Component { -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/component/mock/MockSourceFile.java b/sonar-plugin-api/src/main/java/org/sonar/api/component/mock/MockSourceFile.java deleted file mode 100644 index 5c5a2561fe2..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/component/mock/MockSourceFile.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.component.mock; - -import org.sonar.api.component.SourceFile; - -/** - * @deprecated since 5.6 - */ -@Deprecated -public class MockSourceFile implements SourceFile { - private String key; - private String path; - private String qualifier; - private String language; - private String name; - private String longName; - - private MockSourceFile() { - } - - @Override - public String key() { - return key; - } - - public MockSourceFile setKey(String key) { - this.key = key; - return this; - } - - @Override - public String path() { - return path; - } - - public MockSourceFile setPath(String path) { - this.path = path; - return this; - } - - @Override - public String qualifier() { - return qualifier; - } - - public MockSourceFile setQualifier(String qualifier) { - this.qualifier = qualifier; - return this; - } - - public String language() { - return language; - } - - public MockSourceFile setLanguage(String language) { - this.language = language; - return this; - } - - @Override - public String name() { - return name; - } - - public MockSourceFile setName(String name) { - this.name = name; - return this; - } - - @Override - public String longName() { - return longName; - } - - public MockSourceFile setLongName(String longName) { - this.longName = longName; - return this; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - MockSourceFile that = (MockSourceFile) o; - return !(key != null ? !key.equals(that.key) : (that.key != null)); - } - - @Override - public int hashCode() { - return key != null ? key.hashCode() : 0; - } - - public static MockSourceFile createMain(String key) { - return new MockSourceFile().setKey(key).setQualifier("FIL"); - } -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/component/mock/package-info.java b/sonar-plugin-api/src/main/java/org/sonar/api/component/mock/package-info.java deleted file mode 100644 index 6b0fcf489c1..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/component/mock/package-info.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.component.mock; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/design/Dependency.java b/sonar-plugin-api/src/main/java/org/sonar/api/design/Dependency.java deleted file mode 100644 index bfcdcefa7e3..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/design/Dependency.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.design; - -import org.sonar.api.resources.Resource; -import org.sonar.graph.Edge; - -/** - * @deprecated since 5.2 No more design features - */ -@Deprecated -public class Dependency implements Edge { - - private Resource from; - private Resource to; - private String usage; - private int weight; - private Dependency parent; - private Long id; - - public Dependency(Resource from, Resource to) { - if (from == null) { - throw new IllegalArgumentException("Dependency source is null"); - } - if (to == null) { - throw new IllegalArgumentException("Dependency target is null"); - } - this.from = from; - this.to = to; - } - - @Override - public Resource getFrom() { - return from; - } - - /** - * For internal use only - */ - public void setFrom(Resource from) { - this.from = from; - } - - @Override - public Resource getTo() { - return to; - } - - /** - * For internal use only - */ - public void setTo(Resource to) { - this.to = to; - } - - public String getUsage() { - return usage; - } - - public Dependency setUsage(String usage) { - this.usage = usage; - return this; - } - - @Override - public int getWeight() { - return weight; - } - - public Dependency setWeight(int weight) { - this.weight = weight; - return this; - } - - public Dependency getParent() { - return parent; - } - - public Dependency setParent(Dependency parent) { - this.parent = parent; - return this; - } - - public Long getId() { - return id; - } - - /** - * Internal use only. - */ - public Dependency setId(Long id) { - this.id = id; - return this; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Dependency that = (Dependency) o; - if (!from.equals(that.from)) { - return false; - } - return to.equals(that.to); - } - - @Override - public int hashCode() { - int result = from.hashCode(); - result = 31 * result + to.hashCode(); - return result; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("Dependency{"); - sb.append("from=").append(from); - sb.append(", to=").append(to); - sb.append(", usage='").append(usage).append('\''); - sb.append(", weight=").append(weight); - sb.append(", parent=").append(parent); - sb.append(", id=").append(id); - sb.append('}'); - return sb.toString(); - } -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/issue/Issuable.java b/sonar-plugin-api/src/main/java/org/sonar/api/issue/Issuable.java deleted file mode 100644 index ffa2d91379e..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/issue/Issuable.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.issue; - -import java.util.List; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.sonar.api.batch.sensor.issue.NewIssue; -import org.sonar.api.batch.sensor.issue.NewIssueLocation; -import org.sonar.api.component.Perspective; -import org.sonar.api.rule.RuleKey; - -/** - * This perspective allows to add issues related to the selected component. It can be used from - * {@link org.sonar.api.batch.Sensor}s. - *
- * Example: - *

- *   import org.sonar.api.component.ResourcePerspectives;
- *   public class MySensor extends Sensor {
- *     private final ResourcePerspectives perspectives;
- *
- *     public MySensor(ResourcePerspectives p) {
- *       this.perspectives = p;
- *     }
- *
- *     public void analyse(Project project, SensorContext context) {
- *       Resource myResource; // to be set
- *       Issuable issuable = perspectives.as(Issuable.class, myResource);
- *       if (issuable != null) {
- *         // can be used
- *         Issue issue = issuable.newIssueBuilder()
- *           .setRuleKey(RuleKey.of("pmd", "AvoidArrayLoops")
- *           .setLine(10)
- *           .build();
- *         issuable.addIssue(issue);
- *       }
- *     }
- *   }
- * 
- * @since 3.6 - */ -public interface Issuable extends Perspective { - - interface IssueBuilder { - /** - * The rule key is mandatory. Example: {@code RuleKey.of("pmd", "AvoidArrayLoops")} - */ - IssueBuilder ruleKey(RuleKey ruleKey); - - /** - * Optional line index, starting from 1. It must not be zero or negative. - * @deprecated since 5.2 use {@link #at(NewIssueLocation)} - */ - @Deprecated - IssueBuilder line(@Nullable Integer line); - - /** - * Optional, but recommended, plain-text message. - *
- * Formats like Markdown or HTML are not supported. Size must not be greater than {@link Issue#MESSAGE_MAX_SIZE} characters. - * @deprecated since 5.2 use {@link #at(NewIssueLocation)} - */ - @Deprecated - IssueBuilder message(@Nullable String message); - - /** - * @since 5.2 - * Create a new location for this issue. First registered location is considered as primary location. - */ - NewIssueLocation newLocation(); - - /** - * @since 5.2 - * Register primary location for this issue. - */ - IssueBuilder at(NewIssueLocation primaryLocation); - - /** - * @since 5.2 - * @see NewIssue#addLocation(NewIssueLocation) - */ - IssueBuilder addLocation(NewIssueLocation secondaryLocation); - - /** - * @since 5.2 - * @see NewIssue#addFlow(Iterable) - */ - IssueBuilder addFlow(Iterable flowLocations); - - /** - * Overrides the severity declared in Quality profile. Do not execute in standard use-cases. - * @see org.sonar.api.rule.Severity - */ - IssueBuilder severity(@Nullable String severity); - - /** - * @deprecated since 5.5, manual issue feature has been dropped. - */ - @Deprecated - @CheckForNull - IssueBuilder reporter(@Nullable String reporter); - - IssueBuilder effortToFix(@Nullable Double d); - - /** - * No more supported from batch side since 5.2 - */ - IssueBuilder attribute(String key, @Nullable String value); - - Issue build(); - } - - /** - * Builder is used to create the issue to be passed to {@link #addIssue(Issue)} - */ - IssueBuilder newIssueBuilder(); - - /** - * Register an issue created with {@link #newIssueBuilder()}. - *
- * This method is usually called from {@link org.sonar.api.batch.Sensor}s. {@link org.sonar.api.batch.Decorator}s calling this - * method must be annotated with {@code @DependedUpon(DecoratorBarriers.ISSUES_ADDED)}. - * - * @return true if the new issue is registered, false if the related rule does not exist or is disabled in the Quality profile. - */ - boolean addIssue(Issue issue); - - /** - * @deprecated since 5.2 no more decorators on batch side - */ - @Deprecated - List issues(); - - /** - * @deprecated since 5.2 no more decorators on batch side - */ - @Deprecated - List resolvedIssues(); -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/issue/Issue.java b/sonar-plugin-api/src/main/java/org/sonar/api/issue/Issue.java index c7326428d4d..5baf0c3ef2f 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/issue/Issue.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/issue/Issue.java @@ -112,13 +112,6 @@ public interface Issue extends Serializable { @CheckForNull Integer line(); - /** - * @deprecated since 5.5, replaced by {@link #gap()} - */ - @Deprecated - @CheckForNull - Double effortToFix(); - /** * Arbitrary distance to threshold for resolving the issue. *
@@ -145,13 +138,6 @@ public interface Issue extends Serializable { @CheckForNull String resolution(); - /** - * @deprecated since 5.5, manual issue feature has been dropped. - */ - @Deprecated - @CheckForNull - String reporter(); - /** * UUID of the user who is assigned to this issue. Null if the issue is not assigned. */ @@ -184,13 +170,6 @@ public interface Issue extends Serializable { @CheckForNull String authorLogin(); - /** - * @deprecated since 5.5 Action plans are dropped in 5.5. This field has no effect - */ - @Deprecated - @CheckForNull - String actionPlanKey(); - /** * Non-null list of comments, ordered by chronological order. *
@@ -215,12 +194,6 @@ public interface Issue extends Serializable { */ boolean isCopied(); - /** - * @deprecated since 5.5, replaced by {@link #effort()} - */ - @Deprecated - Duration debt(); - /** * @since 5.5 */ diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/issue/batch/IssueFilter.java b/sonar-plugin-api/src/main/java/org/sonar/api/issue/batch/IssueFilter.java deleted file mode 100644 index d0a55f69f73..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/issue/batch/IssueFilter.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.issue.batch; - -import org.sonar.api.ExtensionPoint; -import org.sonar.api.batch.ScannerSide; -import org.sonar.api.issue.Issue; -import org.sonarsource.api.sonarlint.SonarLintSide; - -/** - *

An issue filter is an object that allows filtering of {@link Issue}s on batch side, preventing them from being persisted. - * @since 4.0 - * @deprecated since 5.3. Use {@link org.sonar.api.scan.issue.filter.IssueFilter} instead. - */ -@ScannerSide -@SonarLintSide -@ExtensionPoint -@Deprecated -public interface IssueFilter { - - /** - * The accept method is called for each {@link Issue} created during analysis, to check if it has to be persisted. Examples of use cases are: - *

    - *
  • Ignoring or enforcing rules on specific resources
  • - *
  • Switching-off an issue based on its context (//NOSONAR comments, semantic annotations)
  • - *
- * The chain parameter allows for fine control of the filtering logic: it is each filter's duty to either pass the issue to the next filter, by calling - * the {@link IssueFilterChain#accept(org.sonar.api.issue.Issue)} method, or return directly if the issue has to be accepted or not - * @param issue the issue being filtered - * @param chain the rest of the filters - * @return true to accept the issue, false to reject it, {@link IssueFilterChain#accept(org.sonar.api.issue.Issue)} to let the other filters decide. - */ - boolean accept(Issue issue, IssueFilterChain chain); -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/issue/batch/IssueFilterChain.java b/sonar-plugin-api/src/main/java/org/sonar/api/issue/batch/IssueFilterChain.java deleted file mode 100644 index 05bb5132243..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/issue/batch/IssueFilterChain.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.issue.batch; - -import org.sonar.api.issue.Issue; - -/** - * A filter chain is an object provided to issues filters for fine control over the filtering logic. Each filter has the choice to: - *
    - *
  • Accept the issue
  • - *
  • Reject the issue
  • - *
  • Let downstream filters decide by passing the issue to the rest of the chain
  • - *
- * @since 4.0 - * @deprecated since 5.3. Use {@link org.sonar.api.scan.issue.filter.IssueFilterChain} instead. - */ -@Deprecated -public interface IssueFilterChain { - - /** - * Called by a filter to let downstream filters decide the fate of the issue - */ - boolean accept(Issue issue); -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/issue/batch/package-info.java b/sonar-plugin-api/src/main/java/org/sonar/api/issue/batch/package-info.java deleted file mode 100644 index c535128a900..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/issue/batch/package-info.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.issue.batch; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/measures/AverageFormula.java b/sonar-plugin-api/src/main/java/org/sonar/api/measures/AverageFormula.java deleted file mode 100644 index 2be13b9ce88..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/measures/AverageFormula.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.measures; - -import java.util.List; - -/** - * @since 3.0 - * @deprecated since 5.2. Aggregation of measures is provided by {@link org.sonar.api.ce.measure.MeasureComputer}. {@link org.sonar.api.batch.Decorator} - * and {@link Formula} are no more supported. - */ -@Deprecated -public class AverageFormula implements Formula { - - /** - * Creates a new {@link AverageFormula} class. - * - * @param main The metric on which average should be calculated (ex.: "complexity") - * @param by The metric used to divide the main metric to compute average (ex.: "file" for "complexity by file") - */ - public static AverageFormula create(Metric main, Metric by) { - return new AverageFormula(); - } - - /** - * Set a fallback metric if no measures found for the main metric. - * - * @param fallbackMetric The fallback metric - * @since 3.6 - */ - public AverageFormula setFallbackForMainMetric(Metric fallbackMetric) { - throw fail(); - } - - /** - * {@inheritDoc} - */ - @Override - public List dependsUponMetrics() { - throw fail(); - } - - /** - * {@inheritDoc} - */ - @Override - public Measure calculate(FormulaData data, FormulaContext context) { - throw fail(); - } - - private static RuntimeException fail() { - throw new UnsupportedOperationException("Unsupported since version 5.2. Decorators and formulas are not used anymore for aggregation measures. " + - "Please use org.sonar.api.ce.measure.MeasureComputer."); - } -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/measures/CoreMetrics.java b/sonar-plugin-api/src/main/java/org/sonar/api/measures/CoreMetrics.java index 1bf18339e21..f746645a91b 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/measures/CoreMetrics.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/measures/CoreMetrics.java @@ -24,7 +24,6 @@ import java.lang.reflect.Modifier; import java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException; -import org.sonar.api.test.MutableTestPlan; import org.sonar.api.utils.SonarException; /** @@ -2235,73 +2234,6 @@ public final class CoreMetrics { .setDeleteHistoricalData(true) .create(); - // -------------------------------------------------------------------------------------------------------------------- - // - // SCM - // - // -------------------------------------------------------------------------------------------------------------------- - - /** - * @since 2.7 - * @deprecated since 5.0 SCM data will no more be stored as measures - */ - @Deprecated - public static final String SCM_AUTHORS_BY_LINE_KEY = "authors_by_line"; - - /** - * Key-value pairs, where key - is a number of line, and value - is an author for this line. - * - * @see org.sonar.api.utils.KeyValueFormat#formatIntString(java.util.Map) - * @see org.sonar.api.utils.KeyValueFormat#parseIntString(String) - * @since 2.7 - * @deprecated since 5.0 SCM data will no more be stored as measures - */ - @Deprecated - public static final transient Metric SCM_AUTHORS_BY_LINE = new Metric.Builder(SCM_AUTHORS_BY_LINE_KEY, "Authors by Line", Metric.ValueType.DATA) - .setDomain(DOMAIN_SCM) - .create(); - - /** - * @since 2.7 - * @deprecated since 5.0 SCM data will no more be stored as measures - */ - @Deprecated - public static final String SCM_REVISIONS_BY_LINE_KEY = "revisions_by_line"; - - /** - * Key-value pairs, where key - is a number of line, and value - is a revision for this line. - * - * @see org.sonar.api.utils.KeyValueFormat#formatIntString(java.util.Map) - * @see org.sonar.api.utils.KeyValueFormat#parseIntString(String) - * @since 2.7 - * @deprecated since 5.0 SCM data will no more be stored as measures - */ - @Deprecated - public static final transient Metric SCM_REVISIONS_BY_LINE = new Metric.Builder(SCM_REVISIONS_BY_LINE_KEY, "Revisions by Line", Metric.ValueType.DATA) - .setDomain(DOMAIN_SCM) - .create(); - - /** - * @since 2.7 - * @deprecated since 5.0 SCM data will no more be stored as measures - */ - @Deprecated - public static final String SCM_LAST_COMMIT_DATETIMES_BY_LINE_KEY = "last_commit_datetimes_by_line"; - - /** - * Key-value pairs, where key - is a number of line, and value - is a date of last commit for this line. - * - * @see org.sonar.api.utils.KeyValueFormat#formatIntDateTime(java.util.Map) - * @see org.sonar.api.utils.KeyValueFormat#parseIntDateTime(String) - * @since 2.7 - * @deprecated since 5.0 SCM data will no more be stored as measures - */ - @Deprecated - public static final transient Metric SCM_LAST_COMMIT_DATETIMES_BY_LINE = new Metric.Builder(SCM_LAST_COMMIT_DATETIMES_BY_LINE_KEY, "Last Commit Dates by Line", - Metric.ValueType.DATA) - .setDomain(DOMAIN_SCM) - .create(); - // -------------------------------------------------------------------------------------------------------------------- // // MAINTAINABILITY CHARACTERISTIC diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/measures/CountDistributionBuilder.java b/sonar-plugin-api/src/main/java/org/sonar/api/measures/CountDistributionBuilder.java deleted file mode 100644 index 5d2a010c5a8..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/measures/CountDistributionBuilder.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.measures; - -import com.google.common.collect.Multiset; -import com.google.common.collect.TreeMultiset; -import java.util.Map; -import javax.annotation.Nullable; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang.math.NumberUtils; -import org.sonar.api.utils.KeyValueFormat; -import org.sonar.api.utils.SonarException; - -/** - * Utility to build a distribution based on discrete values - * - *

An example of usage : you wish to record the number of violations for each level of rules priority - * - * @since 1.10 - * @deprecated since 5.6. Scanner side is not responsible to aggregate measures since 5.2. - */ -@Deprecated -public class CountDistributionBuilder implements MeasureBuilder { - - private final Metric metric; - private final Multiset countBag = TreeMultiset.create(); - - /** - * Creates an empty CountDistributionBuilder for a specified metric - * - * @param metric the metric - */ - public CountDistributionBuilder(Metric metric) { - if (metric == null || !metric.isDataType()) { - throw new SonarException("Metric is null or has invalid type"); - } - this.metric = metric; - } - - /** - * Increments an entry - * - * @param value the value that should be incremented - * @param count the number by which to increment - * @return the current object - */ - public CountDistributionBuilder add(Object value, int count) { - if (count == 0) { - addZero(value); - - } else { - if (this.countBag.add(value, count) == 0) { - // hack - this.countBag.add(value, 1); - } - } - return this; - } - - /** - * Increments an entry by one - * - * @param value the value that should be incremented - * @return the current object - */ - public CountDistributionBuilder add(Object value) { - return add(value, 1); - } - - /** - * Adds an entry without a zero count if it does not exist - * - * @param value the entry to be added - * @return the current object - */ - public CountDistributionBuilder addZero(Object value) { - if (!countBag.contains(value)) { - countBag.add(value, 1); - } - return this; - } - - /** - * Adds an existing Distribution to the current one. - * It will create the entries if they don't exist. - * Can be used to add the values of children resources for example - * - * @param measure the measure to add to the current one - * @return the current object - */ - public CountDistributionBuilder add(@Nullable Measure measure) { - if (measure != null && measure.getData() != null) { - Map map = KeyValueFormat.parse(measure.getData()); - for (Map.Entry entry : map.entrySet()) { - String key = entry.getKey(); - int value = StringUtils.isBlank(entry.getValue()) ? 0 : Integer.parseInt(entry.getValue()); - if (NumberUtils.isNumber(key)) { - add(NumberUtils.toInt(key), value); - } else { - add(key, value); - } - } - } - return this; - } - - /** - * @return whether the current object is empty or not - */ - public boolean isEmpty() { - return countBag.isEmpty(); - } - - /** - * Resets all entries to zero - * - * @return the current object - */ - public CountDistributionBuilder clear() { - countBag.clear(); - return this; - } - - /** - * Shortcut for build(true) - * - * @return the built measure - */ - @Override - public Measure build() { - return build(true); - } - - /** - * Used to build a measure from the current object - * - * @param allowEmptyData should be built if current object is empty - * @return the built measure - */ - public Measure build(boolean allowEmptyData) { - if (!isEmpty() || allowEmptyData) { - return new Measure(metric, MultisetDistributionFormat.format(countBag)); - } - return null; - } -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/measures/CoverageMeasuresBuilder.java b/sonar-plugin-api/src/main/java/org/sonar/api/measures/CoverageMeasuresBuilder.java deleted file mode 100644 index 61012817b82..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/measures/CoverageMeasuresBuilder.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.measures; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.SortedMap; -import java.util.TreeMap; -import org.sonar.api.batch.sensor.SensorContext; -import org.sonar.api.utils.KeyValueFormat; - -/** - * @since 2.7 - * @deprecated since 5.2 use {@link SensorContext#newCoverage()} - */ -@Deprecated -public final class CoverageMeasuresBuilder { - - /** - * Metrics of generated measures - */ - public static final List METRICS = Arrays.asList( - CoreMetrics.LINES_TO_COVER, CoreMetrics.UNCOVERED_LINES, CoreMetrics.COVERAGE_LINE_HITS_DATA, - CoreMetrics.CONDITIONS_TO_COVER, CoreMetrics.UNCOVERED_CONDITIONS, CoreMetrics.CONDITIONS_BY_LINE, - CoreMetrics.COVERED_CONDITIONS_BY_LINE); - - private int totalCoveredLines = 0; - private int totalConditions = 0; - private int totalCoveredConditions = 0; - private SortedMap hitsByLine = new TreeMap<>(); - private SortedMap conditionsByLine = new TreeMap<>(); - private SortedMap coveredConditionsByLine = new TreeMap<>(); - - private CoverageMeasuresBuilder() { - // use the factory - } - - public CoverageMeasuresBuilder reset() { - totalCoveredLines = 0; - totalConditions = 0; - totalCoveredConditions = 0; - hitsByLine.clear(); - conditionsByLine.clear(); - coveredConditionsByLine.clear(); - return this; - } - - public CoverageMeasuresBuilder setHits(int lineId, int hits) { - if (!hitsByLine.containsKey(lineId)) { - hitsByLine.put(lineId, hits); - if (hits > 0) { - totalCoveredLines += 1; - } - } - return this; - } - - public CoverageMeasuresBuilder setConditions(int lineId, int conditions, int coveredConditions) { - if (conditions > 0 && !conditionsByLine.containsKey(lineId)) { - totalConditions += conditions; - totalCoveredConditions += coveredConditions; - conditionsByLine.put(lineId, conditions); - coveredConditionsByLine.put(lineId, coveredConditions); - } - return this; - } - - public int getCoveredLines() { - return totalCoveredLines; - } - - public int getLinesToCover() { - return hitsByLine.size(); - } - - public int getConditions() { - return totalConditions; - } - - public int getCoveredConditions() { - return totalCoveredConditions; - } - - public SortedMap getHitsByLine() { - return Collections.unmodifiableSortedMap(hitsByLine); - } - - public SortedMap getConditionsByLine() { - return Collections.unmodifiableSortedMap(conditionsByLine); - } - - public SortedMap getCoveredConditionsByLine() { - return Collections.unmodifiableSortedMap(coveredConditionsByLine); - } - - public Collection createMeasures() { - Collection measures = new ArrayList<>(); - if (getLinesToCover() > 0) { - measures.add(new Measure(CoreMetrics.LINES_TO_COVER, (double) getLinesToCover())); - measures.add(new Measure(CoreMetrics.UNCOVERED_LINES, (double) (getLinesToCover() - getCoveredLines()))); - measures.add(new Measure(CoreMetrics.COVERAGE_LINE_HITS_DATA).setData(KeyValueFormat.format(hitsByLine))); - } - if (getConditions() > 0) { - measures.add(new Measure(CoreMetrics.CONDITIONS_TO_COVER, (double) getConditions())); - measures.add(new Measure(CoreMetrics.UNCOVERED_CONDITIONS, (double) (getConditions() - getCoveredConditions()))); - measures.add(createConditionsByLine()); - measures.add(createCoveredConditionsByLine()); - } - return measures; - } - - private Measure createCoveredConditionsByLine() { - return new Measure(CoreMetrics.COVERED_CONDITIONS_BY_LINE) - .setData(KeyValueFormat.format(coveredConditionsByLine)); - } - - private Measure createConditionsByLine() { - return new Measure(CoreMetrics.CONDITIONS_BY_LINE) - .setData(KeyValueFormat.format(conditionsByLine)); - } - - public static CoverageMeasuresBuilder create() { - return new CoverageMeasuresBuilder(); - } - -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/measures/FileLinesContext.java b/sonar-plugin-api/src/main/java/org/sonar/api/measures/FileLinesContext.java index 991d744b65d..d16737964ea 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/measures/FileLinesContext.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/measures/FileLinesContext.java @@ -44,25 +44,11 @@ public interface FileLinesContext { */ void setIntValue(String metricKey, int line, int value); - /** - * @return value, or null if no such metric for given line - * @deprecated since 5.0 sensors should not read data - */ - @Deprecated - Integer getIntValue(String metricKey, int line); - /** * @throws UnsupportedOperationException on attempt to update already saved data */ void setStringValue(String metricKey, int line, String value); - /** - * @return value, or null if no such metric for given line - * @deprecated since 5.0 sensors should not read data - */ - @Deprecated - String getStringValue(String metricKey, int line); - /** * Saves unsaved values. */ diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/measures/Formula.java b/sonar-plugin-api/src/main/java/org/sonar/api/measures/Formula.java deleted file mode 100644 index 3c91dfd93ba..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/measures/Formula.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.measures; - -import java.util.List; - -/** - * @since 1.11 - * @deprecated since 5.2 there's no more decorator on batch side, please use {@link org.sonar.api.ce.measure.MeasureComputer} instead - */ -@Deprecated -public interface Formula { - - List dependsUponMetrics(); - - Measure calculate(FormulaData data, FormulaContext context); - -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/measures/FormulaContext.java b/sonar-plugin-api/src/main/java/org/sonar/api/measures/FormulaContext.java deleted file mode 100644 index ef192e52f48..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/measures/FormulaContext.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.measures; - -import org.sonar.api.resources.Resource; - -/** - * @since 1.11 - * @deprecated since 5.2. Aggregation of measures is provided by {@link org.sonar.api.ce.measure.MeasureComputer}. {@link org.sonar.api.batch.Decorator} - * and {@link Formula} are no more supported. - */ -@Deprecated -public interface FormulaContext { - - Metric getTargetMetric(); - - Resource getResource(); - -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/measures/FormulaData.java b/sonar-plugin-api/src/main/java/org/sonar/api/measures/FormulaData.java deleted file mode 100644 index dfe61d8ba31..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/measures/FormulaData.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.measures; - -import java.util.Collection; - -/** - * @since 1.11 - * @deprecated since 5.2. Aggregation of measures is provided by {@link org.sonar.api.ce.measure.MeasureComputer}. {@link org.sonar.api.batch.Decorator} - * and {@link Formula} are no more supported. - */ -@Deprecated -public interface FormulaData { - - Measure getMeasure(Metric metric); - - M getMeasures(MeasuresFilter filter); - - Collection getChildrenMeasures(MeasuresFilter filter); - - Collection getChildrenMeasures(Metric metric); - - Collection getChildren(); -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/measures/MeanAggregationFormula.java b/sonar-plugin-api/src/main/java/org/sonar/api/measures/MeanAggregationFormula.java deleted file mode 100644 index 1942aaa85e5..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/measures/MeanAggregationFormula.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.measures; - -import java.util.List; - -/** - * @since 2.0 - * @deprecated since 5.2. Aggregation of measures is provided by {@link org.sonar.api.ce.measure.MeasureComputer}. {@link org.sonar.api.batch.Decorator} - * and {@link Formula} are no more supported. - */ -@Deprecated -public class MeanAggregationFormula implements Formula { - - public MeanAggregationFormula(boolean unused) { - } - - public MeanAggregationFormula() { - this(false); - } - - @Override - public List dependsUponMetrics() { - throw fail(); - } - - @Override - public Measure calculate(FormulaData data, FormulaContext context) { - throw fail(); - } - - private static RuntimeException fail() { - throw new UnsupportedOperationException( - "Unsupported since version 5.2. Decorators and formulas are not used anymore for aggregation measures. Please use org.sonar.api.ce.measure.MeasureComputer."); - } -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/measures/Measure.java b/sonar-plugin-api/src/main/java/org/sonar/api/measures/Measure.java deleted file mode 100644 index 8523785a074..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/measures/Measure.java +++ /dev/null @@ -1,650 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.measures; - -import java.io.Serializable; -import java.util.Date; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.apache.commons.lang.builder.ReflectionToStringBuilder; -import org.apache.commons.lang.math.NumberUtils; -import org.sonar.api.batch.sensor.SensorContext; - -/** - * A class to handle measures. - * - * @since 1.10 - * @deprecated since 5.6. To create a new measure on scanner side use {@link SensorContext#newMeasure()} - */ -@Deprecated -public class Measure implements Serializable { - private static final String INDEX_SHOULD_BE_IN_RANGE_FROM_1_TO_5 = "Index should be in range from 1 to 5"; - - protected static final int MAX_TEXT_SIZE = 96; - - /** - * Default precision when saving a float type metric - * @deprecated in 5.3. Decimal scale is provided by metric, not by measure. - */ - @Deprecated - public static final int DEFAULT_PRECISION = 1; - - protected String metricKey; - protected Metric metric; - protected Double value; - protected String data; - protected String description; - protected Metric.Level alertStatus; - protected String alertText; - protected Date date; - protected Double variation1; - protected Double variation2; - protected Double variation3; - protected Double variation4; - protected Double variation5; - protected String url; - - public Measure(String metricKey) { - this.metricKey = metricKey; - } - - /** - * Creates a measure with a metric - * - * @param metric the metric - */ - public Measure(Metric metric) { - this.metric = metric; - this.metricKey = metric.getKey(); - } - - /** - * Creates a measure with a metric and a value - * - * @param metric the metric - * @param value its value - */ - public Measure(Metric metric, Double value) { - this.metric = metric; - this.metricKey = metric.getKey(); - setValue(value); - } - - /** - * Creates a measure with a metric, a value and a precision for the value - * - * @param metric the metric - * @param value its value - * @param precision the value precision - */ - public Measure(Metric metric, Double value, int precision) { - this.metric = metric; - this.metricKey = metric.getKey(); - setValue(value, precision); - } - - /** - * Creates a measure with a metric, a value and a data field - * - * @param metric the metric - * @param value the value - * @param data the data field - */ - public Measure(Metric metric, Double value, String data) { - this.metric = metric; - this.metricKey = metric.getKey(); - setValue(value); - setData(data); - } - - /** - * * Creates a measure with a metric and a data field - * - * @param metric the metric - * @param data the data field - */ - public Measure(Metric metric, String data) { - this.metric = metric; - this.metricKey = metric.getKey(); - setData(data); - } - - /** - * Creates a measure with a metric and an alert level - * - * @param metric the metric - * @param level the alert level - */ - public Measure(Metric metric, @Nullable Metric.Level level) { - this.metric = metric; - this.metricKey = metric.getKey(); - if (level != null) { - this.data = level.toString(); - } - } - - /** - * Creates an empty measure - */ - public Measure() { - } - - /** - * @return return the measures underlying metric - */ - public Metric getMetric() { - return metric; - } - - public String getMetricKey() { - return metricKey; - } - - /** - * Set the underlying metric - * - * @param metric the metric - * @return the measure object instance - */ - public Measure setMetric(Metric metric) { - this.metric = metric; - this.metricKey = metric.getKey(); - return this; - } - - /** - * @return transforms and returns the data fields as a level of alert - */ - public Metric.Level getDataAsLevel() { - if (data != null) { - return Metric.Level.valueOf(data); - } - return null; - } - - public boolean hasData() { - return data != null; - } - - /** - * @return the date of the measure, i.e. the date the measure was taken. Used only in TimeMachine queries - */ - public Date getDate() { - return date; - } - - /** - * Sets the date of the measure - Used only in TimeMachine queries - * - * @param date the date - * @return the measure object instance - */ - public Measure setDate(Date date) { - this.date = date; - return this; - } - - /** - * @return the value of the measure as a double - */ - @CheckForNull - public Double getValue() { - return value; - } - - /** - * For internal use. - */ - public G value() { - if (value == null) { - return null; - } - switch (getMetric().getType()) { - case BOOL: - return (G) Boolean.valueOf(Double.doubleToRawLongBits(value) != 0L); - case INT: - case MILLISEC: - case RATING: - return (G) Integer.valueOf(value.intValue()); - case FLOAT: - case PERCENT: - case STRING: - case LEVEL: - case DATA: - case DISTRIB: - return (G) data; - case WORK_DUR: - return (G) Long.valueOf(value.longValue()); - default: - if (getMetric().isNumericType() || getMetric().isDataType()) { - return (G) value; - } - throw new UnsupportedOperationException("Unsupported type :" + getMetric().getType()); - } - } - - /** - * @return the value of the measure as an int - */ - public Integer getIntValue() { - if (value == null) { - return null; - } - return value.intValue(); - } - - /** - * Sets the measure value with the default precision of 1 - * - * @param v the measure value - * @return the measure object instance - */ - public Measure setValue(@Nullable Double v) { - return setValue(v, DEFAULT_PRECISION); - } - - /** - * For internal use - */ - public Measure setRawValue(@Nullable Double v) { - this.value = v; - return this; - } - - /** - * Sets the measure value as an int - * - * @param i the value - * @return the measure object instance - */ - public Measure setIntValue(@Nullable Integer i) { - if (i == null) { - this.value = null; - } else { - this.value = Double.valueOf(i); - } - return this; - } - - /** - * Sets the measure value with a given precision - * - * @return {@code this} - * @deprecated in 5.3. The decimal scale is given by the metric, not by the measure. Anyway this parameter was enforced to 1 before version 5.3. - */ - @Deprecated - public Measure setValue(@Nullable Double v, int decimalScale) { - if (v != null) { - if (Double.isNaN(v)) { - throw new IllegalArgumentException("Measure value can not be NaN"); - } - this.value = v; - } else { - this.value = null; - } - return this; - } - - /** - * @return the data field of the measure - */ - @CheckForNull - public String getData() { - return data; - } - - /** - * Sets the data field of the measure. - * - * @param s the data - * @return the measure object instance - */ - public Measure setData(String s) { - this.data = s; - return this; - } - - /** - * Sets an alert level as the data field - * - * @param level the alert level - * @return the measure object instance - */ - public Measure setData(@Nullable Metric.Level level) { - if (level == null) { - this.data = null; - } else { - this.data = level.toString(); - } - return this; - } - - /** - * @since 2.7 - */ - public Measure unsetData() { - this.data = null; - return this; - } - - /** - * @return the description of the measure - */ - public String getDescription() { - return description; - } - - /** - * Sets the measure description - * - * @param description the description - * @return the measure object instance - */ - public Measure setDescription(String description) { - this.description = description; - return this; - } - - /** - * @return the alert status of the measure - */ - public Metric.Level getAlertStatus() { - return alertStatus; - } - - /** - * Set the alert status of the measure - * - * @param status the status - * @return the measure object instance - */ - public Measure setAlertStatus(@Nullable Metric.Level status) { - this.alertStatus = status; - return this; - } - - /** - * @return the text associated to the alert on the measure - */ - public String getAlertText() { - return alertText; - } - - /** - * Sets the text associated to the alert on the measure - * - * @param alertText the text - * @return the measure object instance - */ - public Measure setAlertText(@Nullable String alertText) { - this.alertText = alertText; - return this; - } - - /** - * Concept of measure trend is dropped. - * @deprecated since 5.2. See https://jira.sonarsource.com/browse/SONAR-6392 - * @return {@code null} since version 5.2 - */ - @Deprecated - @CheckForNull - public Integer getTendency() { - return null; - } - - /** - * Concept of measure trend is dropped. This method does nothing. - * @deprecated since 5.2. See https://jira.sonarsource.com/browse/SONAR-6392 - * @return the measure object instance - */ - @Deprecated - public Measure setTendency(@Nullable Integer tendency) { - return this; - } - - /** - * @return the first variation value - * @since 2.5 - */ - public Double getVariation1() { - return variation1; - } - - /** - * Internal use only - * - * @since 2.5 - */ - public Measure setVariation1(@Nullable Double d) { - this.variation1 = d; - return this; - } - - /** - * @return the second variation value - * @since 2.5 - */ - public Double getVariation2() { - return variation2; - } - - /** - * Internal use only - * - * @since 2.5 - */ - public Measure setVariation2(@Nullable Double d) { - this.variation2 = d; - return this; - } - - /** - * @return the third variation value - * @since 2.5 - */ - public Double getVariation3() { - return variation3; - } - - /** - * Internal use only - * - * @since 2.5 - */ - public Measure setVariation3(@Nullable Double d) { - this.variation3 = d; - return this; - } - - /** - * @return the third variation value - * @since 2.5 - */ - public Double getVariation4() { - return variation4; - } - - /** - * Internal use only - * - * @since 2.5 - */ - public Measure setVariation4(@Nullable Double d) { - this.variation4 = d; - return this; - } - - /** - * @return the third variation value - * @since 2.5 - */ - public Double getVariation5() { - return variation5; - } - - /** - * Internal use only - * - * @since 2.5 - */ - public Measure setVariation5(@Nullable Double d) { - this.variation5 = d; - return this; - } - - /** - * @since 2.5 - */ - public Double getVariation(int index) { - switch (index) { - case 1: - return variation1; - case 2: - return variation2; - case 3: - return variation3; - case 4: - return variation4; - case 5: - return variation5; - default: - throw new IndexOutOfBoundsException(INDEX_SHOULD_BE_IN_RANGE_FROM_1_TO_5); - } - } - - /** - * Internal use only - * - * @since 2.5 - */ - public Measure setVariation(int index, Double d) { - switch (index) { - case 1: - variation1 = d; - break; - case 2: - variation2 = d; - break; - case 3: - variation3 = d; - break; - case 4: - variation4 = d; - break; - case 5: - variation5 = d; - break; - default: - throw new IndexOutOfBoundsException(INDEX_SHOULD_BE_IN_RANGE_FROM_1_TO_5); - } - return this; - } - - /** - * @return the url of the measure - */ - public String getUrl() { - return url; - } - - /** - * Sets the URL of the measure - * - * @param url the url - * @return the measure object instance - */ - public Measure setUrl(String url) { - this.url = url; - return this; - } - - /** - * @since 2.14 - * @deprecated in 6.5 with end of support of Developer cockpit plugin. Always return {@code null}. - */ - @CheckForNull - @Deprecated - public Integer getPersonId() { - return null; - } - - /** - * @since 2.14 - * @deprecated in 6.5 with end of support of Developer cockpit plugin. - */ - @Deprecated - public Measure setPersonId(@Nullable Integer i) { - return this; - } - - /** - * @since 3.2 - */ - public boolean isBestValue() { - Double bestValue = metric.getBestValue(); - return metric.isOptimizedBestValue() == Boolean.TRUE - && bestValue != null - && (value == null || NumberUtils.compare(bestValue, value) == 0) - && allNull(alertStatus, description, url, data) - && isZeroVariation(variation1, variation2, variation3, variation4, variation5); - } - - private static boolean isZeroVariation(Double... variations) { - for (Double variation : variations) { - if (variation != null && NumberUtils.compare(variation, 0.0) != 0) { - return false; - } - } - return true; - } - - private static boolean allNull(Object... values) { - for (Object value : values) { - if (null != value) { - return false; - } - } - return true; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - Measure measure = (Measure) o; - return metricKey != null ? metricKey.equals(measure.metricKey) : (measure.metricKey == null); - } - - @Override - public int hashCode() { - return metricKey != null ? metricKey.hashCode() : 0; - } - - @Override - public String toString() { - return ReflectionToStringBuilder.toString(this); - } - -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/measures/MeasureBuilder.java b/sonar-plugin-api/src/main/java/org/sonar/api/measures/MeasureBuilder.java deleted file mode 100644 index cdf6dfcd9b7..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/measures/MeasureBuilder.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.measures; - -import org.sonar.api.batch.sensor.SensorContext; - -/** - * MeasureBuilder helps to build complex measures. - * - * @since 1.10 - * @deprecated since 5.6. To create a new measure on scanner side use {@link SensorContext#newMeasure()} - */ -@Deprecated -public interface MeasureBuilder { - Measure build(); -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/measures/MeasureUtils.java b/sonar-plugin-api/src/main/java/org/sonar/api/measures/MeasureUtils.java deleted file mode 100644 index 61879060e38..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/measures/MeasureUtils.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.measures; - -import java.util.Collection; -import javax.annotation.Nullable; -import org.apache.commons.lang.StringUtils; - -/** - * An utility class to manipulate measures - * - * @since 1.10 - * @deprecated since 5.6. {@link Measure} is deprecated. - */ -@Deprecated -public final class MeasureUtils { - - /** - * Class cannot be instantiated, it should only be access through static methods - */ - private MeasureUtils() { - } - - /** - * Return true if all measures have numeric value - * - * @param measures the measures - * @return true if all measures numeric values - */ - public static boolean haveValues(Measure... measures) { - if (measures.length == 0) { - return false; - } - for (Measure measure : measures) { - if (!hasValue(measure)) { - return false; - } - } - return true; - } - - /** - * Get the value of a measure, or alternatively a default value - * - * @param measure the measure - * @param defaultValue the default value - * @return defaultValue if measure is null or has no values. - */ - - public static Double getValue(Measure measure, @Nullable Double defaultValue) { - if (MeasureUtils.hasValue(measure)) { - return measure.getValue(); - } - return defaultValue; - } - - public static Long getValueAsLong(Measure measure, Long defaultValue) { - if (MeasureUtils.hasValue(measure)) { - return measure.getValue().longValue(); - } - return defaultValue; - } - - public static Double getVariation(@Nullable Measure measure, int periodIndex) { - return getVariation(measure, periodIndex, null); - } - - public static Double getVariation(@Nullable Measure measure, int periodIndex, @Nullable Double defaultValue) { - Double result = null; - if (measure != null) { - result = measure.getVariation(periodIndex); - } - return result != null ? result : defaultValue; - } - - public static Long getVariationAsLong(@Nullable Measure measure, int periodIndex) { - return getVariationAsLong(measure, periodIndex, null); - } - - public static Long getVariationAsLong(@Nullable Measure measure, int periodIndex, @Nullable Long defaultValue) { - Double result = null; - if (measure != null) { - result = measure.getVariation(periodIndex); - } - return result == null ? defaultValue : Long.valueOf(result.longValue()); - } - - /** - * Tests if a measure has a value - * - * @param measure the measure - * @return whether the measure has a value - */ - public static boolean hasValue(@Nullable Measure measure) { - return measure != null && measure.getValue() != null; - } - - /** - * Tests if a measure has a data field - * - * @param measure the measure - * @return whether the measure has a data field - */ - public static boolean hasData(@Nullable Measure measure) { - return measure != null && StringUtils.isNotBlank(measure.getData()); - } - - /** - * Sums a series of measures - * - * @param zeroIfNone whether to return 0 or null in case measures is null - * @param measures the series of measures - * @return the sum of the measure series - */ - public static Double sum(boolean zeroIfNone, @Nullable Collection measures) { - if (measures != null) { - return sum(zeroIfNone, measures.toArray(new Measure[measures.size()])); - } - return zeroIfNone(zeroIfNone); - } - - /** - * Sums a series of measures - * - * @param zeroIfNone whether to return 0 or null in case measures is null - * @param measures the series of measures - * @return the sum of the measure series - */ - public static Double sum(boolean zeroIfNone, Measure... measures) { - Double sum = 0d; - boolean hasValue = false; - for (Measure measure : measures) { - if (measure != null && measure.getValue() != null) { - hasValue = true; - sum += measure.getValue(); - } - } - - if (hasValue) { - return sum; - } - return zeroIfNone(zeroIfNone); - } - - /** - * Sums a series of measures for the given variation index - * - * @param zeroIfNone whether to return 0 or null in case measures is null - * @param variationIndex the index of the variation to use - * @param measures the series of measures - * @return the sum of the variations for the measure series - */ - public static Double sumOnVariation(boolean zeroIfNone, int variationIndex, @Nullable Collection measures) { - if (measures == null) { - return zeroIfNone(zeroIfNone); - } - Double sum = 0d; - for (Measure measure : measures) { - Double var = measure.getVariation(variationIndex); - if (var != null) { - sum += var; - } - } - return sum; - } - - private static Double zeroIfNone(boolean zeroIfNone) { - return zeroIfNone ? 0d : null; - } -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/measures/MeasuresFilter.java b/sonar-plugin-api/src/main/java/org/sonar/api/measures/MeasuresFilter.java deleted file mode 100644 index e7a4006f1dd..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/measures/MeasuresFilter.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.measures; - -import java.util.Collection; -import javax.annotation.Nullable; - -/** - * @since 1.10 - * @deprecated since 5.6. Sensor should only save measures and not read them. - */ -@Deprecated -public interface MeasuresFilter { - - M filter(@Nullable Collection measures); - -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/measures/MeasuresFilters.java b/sonar-plugin-api/src/main/java/org/sonar/api/measures/MeasuresFilters.java deleted file mode 100644 index 0f11ba03043..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/measures/MeasuresFilters.java +++ /dev/null @@ -1,196 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.measures; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import javax.annotation.Nullable; -import org.sonar.api.rule.RuleKey; -import org.sonar.api.rules.Rule; - -/** - * @since 1.10 - * @deprecated since 5.6. Sensor should only save measures and not read them. - */ -@Deprecated -public final class MeasuresFilters { - - private MeasuresFilters() { - } - - public static MeasuresFilter> all() { - return new MeasuresFilter>() { - @Override - public Collection filter(Collection measures) { - Collection all = new ArrayList<>(); - for (Measure measure : measures) { - if (measure != null) { - all.add(measure); - } - } - return all; - } - }; - } - - public static MeasuresFilter metric(final org.sonar.api.batch.measure.Metric metric) { - return metric(metric.key()); - } - - public static MeasuresFilter metric(final String metricKey) { - return new MetricFilter(metricKey) { - @Override - public Measure filter(@Nullable Collection measures) { - if (measures == null) { - return null; - } - for (Measure measure : measures) { - if (measure.getClass().equals(Measure.class) && - measure.getMetricKey().equals(metricKey)) { - return measure; - } - } - return null; - } - }; - } - - /** - * @since 2.0 - */ - public static MeasuresFilter measure(final Measure measure) { - return new MeasuresFilter() { - @Override - public Measure filter(@Nullable Collection measures) { - if (measures == null) { - return null; - } - for (Measure m : measures) { - if (m.equals(measure)) { - return m; - } - } - return null; - } - }; - } - - public static MeasuresFilter rule(final Metric metric, final RuleKey ruleKey) { - return new RuleFilter(metric, ruleKey); - } - - public static MeasuresFilter rule(final Metric metric, final Rule rule) { - return rule(metric, rule.ruleKey()); - } - - public static MeasuresFilter> rules(final Metric metric) { - return new MetricFilter>(metric) { - - private boolean apply(Measure measure) { - return measure instanceof RuleMeasure && metric.equals(measure.getMetric()) - && ((RuleMeasure) measure).ruleKey() != null; - } - - @Override - public Collection filter(@Nullable Collection measures) { - if (measures == null) { - return null; - } - List result = new ArrayList<>(); - for (Measure measure : measures) { - if (apply(measure)) { - result.add((RuleMeasure) measure); - } - } - return result; - } - }; - } - - /** - * Used for internal optimizations. - */ - public abstract static class MetricFilter implements MeasuresFilter { - private final String metricKey; - - protected MetricFilter(Metric metric) { - this.metricKey = metric.getKey(); - } - - protected MetricFilter(String metricKey) { - this.metricKey = metricKey; - } - - public String filterOnMetricKey() { - return metricKey; - } - } - - /** - * @deprecated since 5.2. The measures related to rules are computed on server side by Compute Engine. - */ - @Deprecated - private abstract static class AbstractRuleMeasureFilter extends MetricFilter { - protected AbstractRuleMeasureFilter(Metric metric) { - super(metric); - } - - private boolean apply(Measure measure) { - return measure instanceof RuleMeasure - && filterOnMetricKey().equals(measure.getMetricKey()) - && doApply((RuleMeasure) measure); - } - - abstract boolean doApply(RuleMeasure ruleMeasure); - - @Override - public M filter(@Nullable Collection measures) { - if (measures == null) { - return null; - } - for (Measure measure : measures) { - if (apply(measure)) { - return (M) measure; - } - } - return null; - } - } - - /** - * @deprecated since 5.2. Useless by design because of Compute Engine - */ - @Deprecated - private static class RuleFilter extends AbstractRuleMeasureFilter { - private RuleKey ruleKey; - - protected RuleFilter(Metric metric, RuleKey ruleKey) { - super(metric); - this.ruleKey = ruleKey; - } - - @Override - boolean doApply(RuleMeasure measure) { - return measure.ruleKey() != null - && ruleKey.equals(measure.ruleKey()); - } - } -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/measures/Metric.java b/sonar-plugin-api/src/main/java/org/sonar/api/measures/Metric.java index 6e9f57ab479..4f1c4b7c0ab 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/measures/Metric.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/measures/Metric.java @@ -128,7 +128,6 @@ public class Metric implements Serializable, org.sonar.a } private Integer id; - private transient Formula formula; private String key; private String description; private ValueType type; @@ -158,7 +157,6 @@ public class Metric implements Serializable, org.sonar.a this.optimizedBestValue = builder.optimizedBestValue; this.bestValue = builder.bestValue; this.hidden = builder.hidden; - this.formula = builder.formula; this.userManaged = builder.userManaged; this.deleteHistoricalData = builder.deleteHistoricalData; this.decimalScale = builder.decimalScale; @@ -251,28 +249,6 @@ public class Metric implements Serializable, org.sonar.a return this; } - /** - * @return the metric formula - * @deprecated since 5.2 there's no more decorator on batch side, please use {@link org.sonar.api.ce.measure.MeasureComputer} instead - */ - @Deprecated - public Formula getFormula() { - return formula; - } - - /** - * Sets the metric formula - * - * @param formula the formula - * @return this - * @deprecated since 5.2 there's no more decorator on batch side, please use {@link org.sonar.api.ce.measure.MeasureComputer} instead - */ - @Deprecated - public Metric setFormula(Formula formula) { - this.formula = formula; - return this; - } - /** * @return wether the metric is qualitative */ @@ -582,7 +558,6 @@ public class Metric implements Serializable, org.sonar.a private Integer direction = DIRECTION_NONE; private Boolean qualitative = Boolean.FALSE; private String domain = null; - private Formula formula; private Double worstValue; private Double bestValue; private boolean optimizedBestValue = false; @@ -664,25 +639,6 @@ public class Metric implements Serializable, org.sonar.a return this; } - /** - * Specifies the formula used by Sonar to automatically aggregate measures stored on files up to the project level. - *
- *
- * By default, no formula is defined, which means that it's up to a sensor/decorator to compute measures on appropriate levels. - *
- * When a formula is set, sensors/decorators just need to store measures at a specific level and let Sonar run the formula to store - * measures on the remaining levels. - * - * @param f the formula - * @return the builder - * @deprecated since 5.2, it's no more possible to define a formula on a metric, please use {@link org.sonar.api.ce.measure.MeasureComputer} instead - */ - @Deprecated - public Builder setFormula(Formula f) { - this.formula = f; - return this; - } - /** * Sets the worst value that the metric can get (example: 0.0 for code coverage). No worst value is set by default. * diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/measures/PropertiesBuilder.java b/sonar-plugin-api/src/main/java/org/sonar/api/measures/PropertiesBuilder.java deleted file mode 100644 index 3eb7a5cb997..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/measures/PropertiesBuilder.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.measures; - -import java.util.Map; -import java.util.TreeMap; -import org.sonar.api.utils.KeyValueFormat; - -/** - * @since 1.10 - * @deprecated since 5.6. Use directly {@link KeyValueFormat}. - */ -@Deprecated -public class PropertiesBuilder { - private Metric metric; - private Map props; - - public PropertiesBuilder(Metric metric, Map map) { - this.props = new TreeMap<>(map); - this.metric = metric; - } - - public PropertiesBuilder(Metric metric) { - this.props = new TreeMap<>(); - this.metric = metric; - } - - public PropertiesBuilder() { - this.props = new TreeMap<>(); - } - - public PropertiesBuilder clear() { - this.props.clear(); - return this; - } - - public Map getProps() { - return props; - } - - public Metric getMetric() { - return metric; - } - - public PropertiesBuilder setMetric(Metric metric) { - this.metric = metric; - return this; - } - - public PropertiesBuilder add(K key, V value) { - props.put(key, value); - return this; - } - - public PropertiesBuilder addAll(Map map) { - props.putAll(map); - return this; - } - - public Measure build() { - return new Measure(metric, buildData()); - } - - public String buildData() { - return KeyValueFormat.format(props); - } -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/measures/RangeDistributionBuilder.java b/sonar-plugin-api/src/main/java/org/sonar/api/measures/RangeDistributionBuilder.java deleted file mode 100644 index 228c40c240d..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/measures/RangeDistributionBuilder.java +++ /dev/null @@ -1,248 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.measures; - -import com.google.common.collect.SortedMultiset; -import com.google.common.collect.TreeMultiset; -import java.util.Arrays; -import java.util.Collections; -import java.util.Map; -import java.util.Set; -import java.util.function.Function; -import javax.annotation.Nullable; -import org.apache.commons.lang.NumberUtils; -import org.sonar.api.utils.KeyValueFormat; - -import static com.google.common.base.Preconditions.checkArgument; -import static java.util.Objects.requireNonNull; - -/** - * Utility to build a distribution based on defined ranges - *
- *

An example of usage : you wish to record the percentage of lines of code that belong to method - * with pre-defined ranges of complexity. - * - * @since 1.10 - * @deprecated since 5.2 use {@link org.sonar.api.ce.measure.RangeDistributionBuilder instead} - */ -@Deprecated -public class RangeDistributionBuilder implements MeasureBuilder { - - private final Metric metric; - private final SortedMultiset countBag = TreeMultiset.create(); - private boolean isEmpty = true; - private Number[] bottomLimits; - private RangeTransformer rangeValueTransformer; - private boolean isValid = true; - - /** - * RangeDistributionBuilder for a metric and a defined range - * Each entry is initialized at zero - * - * @param metric the metric to record the measure against - * @param bottomLimits the bottom limits of ranges to be used - */ - public RangeDistributionBuilder(Metric metric, Number[] bottomLimits) { - requireNonNull(metric, "Metric must not be null"); - checkArgument(metric.isDataType(), "Metric %s must have data type", metric.key()); - this.metric = metric; - init(bottomLimits); - } - - public RangeDistributionBuilder(Metric metric) { - this.metric = metric; - } - - private void init(Number[] bottomLimits) { - this.bottomLimits = new Number[bottomLimits.length]; - System.arraycopy(bottomLimits, 0, this.bottomLimits, 0, this.bottomLimits.length); - Arrays.sort(this.bottomLimits); - changeDoublesToInts(); - doClear(); - this.rangeValueTransformer = new RangeTransformer(); - } - - private void changeDoublesToInts() { - boolean onlyInts = true; - for (Number bottomLimit : bottomLimits) { - if (NumberUtils.compare(bottomLimit.intValue(), bottomLimit.doubleValue()) != 0) { - onlyInts = false; - } - } - if (onlyInts) { - for (int i = 0; i < bottomLimits.length; i++) { - bottomLimits[i] = bottomLimits[i].intValue(); - } - } - } - - /** - * Gives the bottom limits of ranges used - * - * @return the bottom limits of defined range for the distribution - */ - public Number[] getBottomLimits() { - return bottomLimits; - } - - /** - * Increments an entry by 1 - * - * @param value the value to use to pick the entry to increment - * @return the current object - */ - public RangeDistributionBuilder add(Number value) { - return add(value, 1); - } - - /** - * Increments an entry - * - * @param value the value to use to pick the entry to increment - * @param count the number by which to increment - * @return the current object - */ - public RangeDistributionBuilder add(@Nullable Number value, int count) { - if (value != null && greaterOrEqualsThan(value, bottomLimits[0])) { - this.countBag.add(rangeValueTransformer.apply(value), count); - isEmpty = false; - } - return this; - } - - private RangeDistributionBuilder addLimitCount(Number limit, int count) { - for (Number bottomLimit : bottomLimits) { - if (NumberUtils.compare(bottomLimit.doubleValue(), limit.doubleValue()) == 0) { - this.countBag.add(rangeValueTransformer.apply(limit), count); - isEmpty = false; - return this; - } - } - isValid = false; - return this; - } - - /** - * Adds an existing Distribution to the current one. - * It will create the entries if they don't exist. - * Can be used to add the values of children resources for example - *
- * Since 2.2, the distribution returned will be invalidated in case the - * measure given does not use the same bottom limits - * - * @param measure the measure to add to the current one - * @return the current object - */ - public RangeDistributionBuilder add(@Nullable Measure measure) { - if (measure != null && measure.getData() != null) { - Map map = KeyValueFormat.parse(measure.getData(), KeyValueFormat.newDoubleConverter(), KeyValueFormat.newDoubleConverter()); - Number[] limits = map.keySet().toArray(new Number[map.size()]); - if (bottomLimits == null) { - init(limits); - - } else if (!areSameLimits(bottomLimits, map.keySet())) { - isValid = false; - } - - if (isValid) { - for (Map.Entry entry : map.entrySet()) { - addLimitCount(entry.getKey(), entry.getValue().intValue()); - } - } - } - return this; - } - - private static boolean areSameLimits(Number[] bottomLimits, Set limits) { - if (limits.size() == bottomLimits.length) { - for (Number l : bottomLimits) { - if (!limits.contains(l.doubleValue())) { - return false; - } - } - return true; - } - return false; - } - - /** - * Resets all entries to zero - * - * @return the current object - */ - public RangeDistributionBuilder clear() { - doClear(); - return this; - } - - private void doClear() { - countBag.clear(); - if (bottomLimits != null) { - Collections.addAll(countBag, bottomLimits); - } - isEmpty = true; - } - - /** - * @return whether the current object is empty or not - */ - public boolean isEmpty() { - return isEmpty; - } - - /** - * Shortcut for build(true) - * - * @return the built measure - */ - @Override - public Measure build() { - return build(true); - } - - /** - * Used to build a measure from the current object - * - * @param allowEmptyData should be built if current object is empty - * @return the built measure - */ - public Measure build(boolean allowEmptyData) { - if (isValid && (!isEmpty || allowEmptyData)) { - return new Measure<>(metric, MultisetDistributionFormat.format(countBag)); - } - return null; - } - - private class RangeTransformer implements Function { - @Override - public Number apply(Number n) { - for (int i = bottomLimits.length - 1; i >= 0; i--) { - if (greaterOrEqualsThan(n, bottomLimits[i])) { - return bottomLimits[i]; - } - } - return null; - } - } - - private static boolean greaterOrEqualsThan(Number n1, Number n2) { - return NumberUtils.compare(n1.doubleValue(), n2.doubleValue()) >= 0; - } -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/measures/RuleMeasure.java b/sonar-plugin-api/src/main/java/org/sonar/api/measures/RuleMeasure.java deleted file mode 100644 index 57ff4de15e0..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/measures/RuleMeasure.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.measures; - -import org.apache.commons.lang.builder.EqualsBuilder; -import org.apache.commons.lang.builder.HashCodeBuilder; -import org.apache.commons.lang.builder.ToStringBuilder; -import org.sonar.api.rule.RuleKey; -import org.sonar.api.rules.Rule; -import org.sonar.api.rules.RulePriority; - -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; - -/** - * @since 1.10 - * @deprecated since 5.2. Ignored by design because of Compute Engine. - */ -@Deprecated -public class RuleMeasure extends Measure { - - private RuleKey ruleKey; - private RulePriority rulePriority; - - /** - * This constructor is for internal use only. Please use static methods createForXXX(). - * @deprecated since 4.4 use {@link #RuleMeasure(Metric, RuleKey, RulePriority, Integer)} - */ - @Deprecated - public RuleMeasure(Metric metric, @Nullable Rule rule, @Nullable RulePriority rulePriority, @Nullable Integer ruleCategory) { - this(metric, rule != null ? rule.ruleKey() : null, rulePriority, ruleCategory); - } - - /** - * This constructor is for internal use only. Please use static methods createForXXX(). - */ - public RuleMeasure(Metric metric, @Nullable RuleKey ruleKey, @Nullable RulePriority rulePriority, @Nullable Integer ruleCategory) { - super(metric); - this.ruleKey = ruleKey; - this.rulePriority = rulePriority; - } - - @CheckForNull - public RuleKey ruleKey() { - return ruleKey; - } - - public RuleMeasure setRuleKey(RuleKey ruleKey) { - this.ruleKey = ruleKey; - return this; - } - - /** - * @deprecated since 4.4 use {@link #ruleKey()} - */ - @Deprecated - public Rule getRule() { - return Rule.create(ruleKey.repository(), ruleKey.rule()); - } - - /** - * @deprecated since 4.4 use {@link #setRuleKey(org.sonar.api.rule.RuleKey)} - */ - @Deprecated - public RuleMeasure setRule(Rule rule) { - this.ruleKey = rule.ruleKey(); - return this; - } - - /** - * @deprecated since 2.14 use {@link #getSeverity()} instead. See SONAR-1829. - */ - @Deprecated - @CheckForNull - public RulePriority getRulePriority() { - return rulePriority; - } - - /** - * @since 2.14 - */ - @CheckForNull - public RulePriority getSeverity() { - return rulePriority; - } - - /** - * @deprecated since 2.14 use {@link #setSeverity(org.sonar.api.rules.RulePriority)} instead. See SONAR-1829. - */ - @Deprecated - public RuleMeasure setRulePriority(RulePriority rulePriority) { - this.rulePriority = rulePriority; - return this; - } - - /** - * @since 2.14 - */ - public RuleMeasure setSeverity(RulePriority severity) { - this.rulePriority = severity; - return this; - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (!(obj.getClass().equals(RuleMeasure.class))) { - // for the moment. - return false; - } - if (this == obj) { - return true; - } - RuleMeasure other = (RuleMeasure) obj; - return new EqualsBuilder() - .append(getMetric(), other.getMetric()) - .append(ruleKey, other.ruleKey) - .isEquals(); - } - - @Override - public RuleMeasure setValue(@Nullable Double v) { - return (RuleMeasure) super.setValue(v); - } - - @Override - public int hashCode() { - return new HashCodeBuilder(17, 37) - .append(getMetric()) - .append(ruleKey) - .toHashCode(); - } - - @Override - public String toString() { - return new ToStringBuilder(this) - .append("metric", metric) - .append("ruleKey", ruleKey) - .append("value", value) - .append("data", data) - .append("description", description) - .append("alertStatus", alertStatus) - .append("alertText", alertText) - .append("severity", rulePriority) - .toString(); - } - - /** - * @deprecated since 4.4 use {@link #createForRule(Metric, RuleKey, Double)} - */ - @Deprecated - public static RuleMeasure createForRule(Metric metric, Rule rule, @Nullable Double value) { - return new RuleMeasure(metric, rule, null, null).setValue(value); - } - - public static RuleMeasure createForRule(Metric metric, RuleKey ruleKey, @Nullable Double value) { - return new RuleMeasure(metric, ruleKey, null, null).setValue(value); - } - - public static RuleMeasure createForPriority(Metric metric, RulePriority priority, @Nullable Double value) { - return new RuleMeasure(metric, (RuleKey) null, priority, null).setValue(value); - } - - /** - * @deprecated since 2.5. See SONAR-2007. - */ - @Deprecated - public static RuleMeasure createForCategory(Metric metric, Integer category, @Nullable Double value) { - return new RuleMeasure(metric, (RuleKey) null, null, category).setValue(value); - } -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/measures/SumChildDistributionFormula.java b/sonar-plugin-api/src/main/java/org/sonar/api/measures/SumChildDistributionFormula.java deleted file mode 100644 index 1594a10d5a5..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/measures/SumChildDistributionFormula.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.measures; - -import java.util.List; - -/** - * @since 2.0 - * - * Used to consolidate a distribution measure throughout the resource tree - * @deprecated since 5.2. Aggregation of measures is provided by {@link org.sonar.api.ce.measure.MeasureComputer}. {@link org.sonar.api.batch.Decorator} - * and {@link Formula} are no more supported. - */ -@Deprecated -public class SumChildDistributionFormula implements Formula { - - @Override - public List dependsUponMetrics() { - throw fail(); - } - - public String getMinimumScopeToPersist() { - throw fail(); - } - - public SumChildDistributionFormula setMinimumScopeToPersist(String s) { - throw fail(); - } - - @Override - public Measure calculate(FormulaData data, FormulaContext context) { - throw fail(); - } - - private static RuntimeException fail() { - throw new UnsupportedOperationException( - "Unsupported since version 5.2. Decorators and formulas are not used anymore for aggregation measures. Please use org.sonar.api.ce.measure.MeasureComputer."); - } -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/measures/SumChildValuesFormula.java b/sonar-plugin-api/src/main/java/org/sonar/api/measures/SumChildValuesFormula.java deleted file mode 100644 index dc9490f202e..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/measures/SumChildValuesFormula.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.measures; - -import java.util.List; - -/** - * @since 1.11 - * @deprecated since 5.2. Aggregation of measures is provided by {@link org.sonar.api.ce.measure.MeasureComputer}. {@link org.sonar.api.batch.Decorator} - * and {@link Formula} are no more supported. - */ -@Deprecated -public class SumChildValuesFormula implements Formula { - - public SumChildValuesFormula(boolean unused) { - } - - @Override - public List dependsUponMetrics() { - throw fail(); - } - - @Override - public Measure calculate(FormulaData data, FormulaContext context) { - throw fail(); - } - - private static RuntimeException fail() { - throw new UnsupportedOperationException( - "Unsupported since version 5.2. Decorators and formulas are not used anymore for aggregation measures. Please use org.sonar.api.ce.measure.MeasureComputer."); - } -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/measures/WeightedMeanAggregationFormula.java b/sonar-plugin-api/src/main/java/org/sonar/api/measures/WeightedMeanAggregationFormula.java deleted file mode 100644 index b8c1ade7358..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/measures/WeightedMeanAggregationFormula.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.measures; - -import java.util.List; - -/** - * @since 2.0 - * @deprecated since 5.2. Aggregation of measures is provided by {@link org.sonar.api.ce.measure.MeasureComputer}. {@link org.sonar.api.batch.Decorator} - * and {@link Formula} are no more supported. - */ -@Deprecated -public class WeightedMeanAggregationFormula implements Formula { - - public WeightedMeanAggregationFormula(Metric weightingMetric, boolean zeroIfNoValues) { - } - - @Override - public List dependsUponMetrics() { - throw fail(); - } - - @Override - public Measure calculate(FormulaData data, FormulaContext context) { - throw fail(); - } - - private static RuntimeException fail() { - throw new UnsupportedOperationException( - "Unsupported since version 5.2. Decorators and formulas are not used anymore for aggregation measures. Please use org.sonar.api.ce.measure.MeasureComputer."); - } -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/resources/Directory.java b/sonar-plugin-api/src/main/java/org/sonar/api/resources/Directory.java deleted file mode 100644 index aaa7a61811c..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/resources/Directory.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.resources; - -import javax.annotation.CheckForNull; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang.builder.ToStringBuilder; -import org.sonar.api.batch.fs.FileSystem; -import org.sonar.api.batch.fs.InputDir; -import org.sonar.api.scan.filesystem.PathResolver; -import org.sonar.api.utils.WildcardPattern; - -/** - * @since 1.10 - * @deprecated since 5.6 replaced by {@link InputDir}. - */ -@Deprecated -public class Directory extends Resource { - - public static final String SEPARATOR = "/"; - public static final String ROOT = "[root]"; - - private final String relativePathFromSourceDir; - - Directory() { - // Used by factory - this.relativePathFromSourceDir = null; - } - - /** - * Internal. - */ - public String relativePathFromSourceDir() { - return relativePathFromSourceDir; - } - - @Override - public String getName() { - return getKey(); - } - - @Override - public String getLongName() { - return null; - } - - @Override - public String getDescription() { - return null; - } - - @Override - public Language getLanguage() { - return null; - } - - @Override - public String getScope() { - return Scopes.DIRECTORY; - } - - @Override - public String getQualifier() { - return Qualifiers.DIRECTORY; - } - - @Override - public Resource getParent() { - return null; - } - - @Override - public boolean matchFilePattern(String antPattern) { - WildcardPattern matcher = WildcardPattern.create(antPattern, "/"); - return matcher.match(getKey()); - } - - public static String parseKey(String key) { - if (StringUtils.isBlank(key)) { - return ROOT; - } - String normalizedKey = key; - normalizedKey = normalizedKey.replace('\\', '/'); - normalizedKey = StringUtils.trim(normalizedKey); - normalizedKey = StringUtils.removeStart(normalizedKey, Directory.SEPARATOR); - normalizedKey = StringUtils.removeEnd(normalizedKey, Directory.SEPARATOR); - return normalizedKey; - } - - /** - * @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.getBaseDir(), dir); - if (relativePathFromBasedir != null) { - return Directory.create(relativePathFromBasedir); - } - return null; - } - - /** - * 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); - d.setKey(normalizedPath == null ? SEPARATOR : normalizedPath); - d.setPath(normalizedPath == null ? "" : normalizedPath); - return d; - } - - @Override - public String toString() { - return new ToStringBuilder(this) - .append("key", getKey()) - .append("path", getPath()) - .toString(); - } - -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/resources/DuplicatedSourceException.java b/sonar-plugin-api/src/main/java/org/sonar/api/resources/DuplicatedSourceException.java deleted file mode 100644 index f6f7a8f7fe1..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/resources/DuplicatedSourceException.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.resources; - -import org.apache.commons.lang.ObjectUtils; -import org.sonar.api.utils.SonarException; - -/** - * @since 2.6 - * @deprecated since 5.6 should not be used in any API - */ -@Deprecated -public final class DuplicatedSourceException extends SonarException { - - public DuplicatedSourceException(Resource resource) { - super("Duplicate source for resource: " + ObjectUtils.toString(resource)); - } -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/resources/File.java b/sonar-plugin-api/src/main/java/org/sonar/api/resources/File.java deleted file mode 100644 index 186fa61aeb9..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/resources/File.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.resources; - -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang.builder.ToStringBuilder; -import org.sonar.api.batch.fs.FileSystem; -import org.sonar.api.batch.fs.InputFile; -import org.sonar.api.utils.WildcardPattern; - -/** - * @since 1.10 - * @deprecated since 5.6 replaced by {@link InputFile}. - */ -@Deprecated -public class File extends Resource { - - public static final String SCOPE = Scopes.FILE; - - private String filename; - private Language language; - private Directory parent; - private String qualifier = Qualifiers.FILE; - - protected File() { - // Used by factory method - } - - /** - * {@inheritDoc} - * - * @see Resource#getParent() - */ - @Override - public Directory getParent() { - return parent; - } - - /** - * {@inheritDoc} - * - * @see Resource#matchFilePattern(String) - */ - @Override - public boolean matchFilePattern(String antPattern) { - WildcardPattern matcher = WildcardPattern.create(antPattern, Directory.SEPARATOR); - return matcher.match(getKey()); - } - - /** - * {@inheritDoc} - * - * @see Resource#getName() - */ - @Override - public String getName() { - return filename; - } - - /** - * {@inheritDoc} - * - * @see Resource#getLongName() - */ - @Override - public String getLongName() { - return StringUtils.defaultIfBlank(getPath(), getKey()); - } - - /** - * {@inheritDoc} - * - * @see Resource#getDescription() - */ - @Override - public String getDescription() { - return null; - } - - /** - * {@inheritDoc} - * - * @see Resource#getLanguage() - */ - @Override - public Language getLanguage() { - return language; - } - - /** - * Sets the language of the file - */ - public void setLanguage(Language language) { - this.language = language; - } - - /** - * @return SCOPE_ENTITY - */ - @Override - public final String getScope() { - return SCOPE; - } - - /** - * Returns the qualifier associated to this File. Should be QUALIFIER_FILE or QUALIFIER_UNIT_TEST_CLASS - */ - @Override - public String getQualifier() { - return qualifier; - } - - public void setQualifier(String qualifier) { - this.qualifier = qualifier; - } - - /** - * Internal use only. - * @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); - file.setKey(normalizedPath); - file.setPath(normalizedPath); - 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; - } - - /** - * Internal use only. - * @deprecated since 5.1 use {@link FileSystem#inputFile(org.sonar.api.batch.fs.FilePredicate)} - */ - @Deprecated - public static File create(String relativePathFromBasedir, Language language, boolean unitTest) { - File file = create(relativePathFromBasedir); - file.setLanguage(language); - if (unitTest) { - file.setQualifier(Qualifiers.UNIT_TEST_FILE); - } - return file; - } - - @Override - public String toString() { - return new ToStringBuilder(this) - .append("key", getKey()) - .append("path", getPath()) - .append("filename", filename) - .append("language", language) - .toString(); - } -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/resources/Library.java b/sonar-plugin-api/src/main/java/org/sonar/api/resources/Library.java deleted file mode 100644 index 1260bcb6810..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/resources/Library.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.resources; - -import org.apache.commons.lang.builder.ToStringBuilder; - -/** - * @deprecated since 5.2 No more design features - */ -@Deprecated -public final class Library extends Resource { - - private String name; - private String description; - private String version; - - public Library(String key, String version) { - setKey(key); - this.version = version; - } - - public String getVersion() { - return version; - } - - public Library setName(String name) { - this.name = name; - return this; - } - - public Library setDescription(String description) { - this.description = description; - return this; - } - - @Override - public String getName() { - return name; - } - - @Override - public String getLongName() { - return null; - } - - @Override - public String getDescription() { - return description; - } - - @Override - public Language getLanguage() { - return null; - } - - @Override - public String getScope() { - return Scopes.PROJECT; - } - - @Override - public String getQualifier() { - return Qualifiers.LIBRARY; - } - - @Override - public Resource getParent() { - return null; - } - - @Override - public boolean matchFilePattern(String antPattern) { - return false; - } - - public static Library createFromMavenIds(String groupId, String artifactId, String version) { - return new Library(String.format("%s:%s", groupId, artifactId), version); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Library library = (Library) o; - if (!getKey().equals(library.getKey())) { - return false; - } - return version.equals(library.version); - } - - @Override - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + getKey().hashCode(); - result = 31 * result + version.hashCode(); - return result; - } - - @Override - public String toString() { - return new ToStringBuilder(this) - .append("key", getKey()) - .append("name", getName()) - .append("version", version) - .toString(); - } -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/resources/Project.java b/sonar-plugin-api/src/main/java/org/sonar/api/resources/Project.java deleted file mode 100644 index bf31c410eda..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/resources/Project.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.resources; - -import java.util.List; -import java.util.stream.Collectors; - -import javax.annotation.CheckForNull; - -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang.builder.ToStringBuilder; -import org.sonar.api.batch.bootstrap.ProjectDefinition; -import org.sonar.api.batch.fs.InputModule; -import org.sonar.api.batch.fs.internal.DefaultInputModule; -import org.sonar.api.component.Component; -import org.sonar.api.scan.filesystem.PathResolver; - -/** - * @since 1.10 - * @deprecated since 5.6 replaced by {@link InputModule}. - */ -@Deprecated -public class Project extends Resource implements Component { - private final ProjectDefinition definition; - - public Project(DefaultInputModule module) { - this(module.definition()); - } - - public Project(ProjectDefinition definition) { - this.definition = definition; - this.setKey(definition.getKey()); - this.setEffectiveKey(definition.getKeyWithBranch()); - } - - public ProjectDefinition definition() { - return definition; - } - - @Override - public String key() { - return definition.getKey(); - } - - @Override - public String path() { - ProjectDefinition parent = definition.getParent(); - if (parent == null) { - return null; - } - return new PathResolver().relativePath(parent.getBaseDir(), definition.getBaseDir()); - } - - public String getBranch() { - return definition.getBranch(); - } - - @CheckForNull - public String getOriginalName() { - String name = definition.getOriginalName(); - if (StringUtils.isNotEmpty(getBranch())) { - name = name + " " + getBranch(); - } - return name; - } - - java.io.File getBaseDir() { - return definition.getBaseDir(); - } - - @Override - public String name() { - String name = definition.getName(); - if (StringUtils.isNotEmpty(getBranch())) { - name = name + " " + getBranch(); - } - return name; - } - - @Override - public String longName() { - return definition.getName(); - } - - @Override - public String qualifier() { - return getParent() == null ? Qualifiers.PROJECT : Qualifiers.MODULE; - } - - @Override - public String getName() { - return name(); - } - - public boolean isRoot() { - return getParent() == null; - } - - public Project getRoot() { - return getParent() == null ? this : getParent().getRoot(); - } - - /** - * @return whether the current project is a module - */ - public boolean isModule() { - return !isRoot(); - } - - @Override - public String getLongName() { - return longName(); - } - - @Override - public String getDescription() { - return definition.getDescription(); - } - - /** - * @deprecated since 4.2 use {@link org.sonar.api.batch.fs.FileSystem#languages()} - */ - @Override - public Language getLanguage() { - throw new UnsupportedOperationException(); - } - - @Override - public String getScope() { - return Scopes.PROJECT; - } - - @Override - public String getQualifier() { - return qualifier(); - } - - @Override - public Project getParent() { - ProjectDefinition parent = definition.getParent(); - if (parent == null) { - return null; - } - return new Project(parent); - } - - /** - * @return the list of modules - */ - public List getModules() { - return definition.getSubProjects().stream() - .map(Project::new) - .collect(Collectors.toList()); - } - - @Override - public boolean matchFilePattern(String antPattern) { - return false; - } - - @Override - public String toString() { - return new ToStringBuilder(this) - .append("id", getId()) - .append("key", key()) - .append("qualifier", getQualifier()) - .toString(); - } - -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/resources/Qualifiers.java b/sonar-plugin-api/src/main/java/org/sonar/api/resources/Qualifiers.java index 8605fd9798c..51348e6d17a 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/resources/Qualifiers.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/resources/Qualifiers.java @@ -20,7 +20,6 @@ package org.sonar.api.resources; import java.util.List; -import java.util.Objects; import static java.util.Arrays.asList; import static java.util.Collections.unmodifiableList; @@ -86,55 +85,4 @@ public final class Qualifiers { private Qualifiers() { // only static methods } - - /** - * @param resource not nullable - */ - public static boolean isView(final Resource resource, final boolean acceptSubViews) { - boolean isView = Objects.equals(VIEW, resource.getQualifier()); - if (!isView && acceptSubViews) { - isView = Objects.equals(SUBVIEW, resource.getQualifier()); - } - - return isView; - } - - /** - * @param resource not nullable - */ - public static boolean isSubview(final Resource resource) { - return Objects.equals(SUBVIEW, resource.getScope()); - } - - /** - * @param resource not nullable - */ - public static boolean isProject(final Resource resource, final boolean acceptModules) { - boolean isProject = Objects.equals(PROJECT, resource.getQualifier()); - if (!isProject && acceptModules) { - isProject = Objects.equals(MODULE, resource.getQualifier()); - } - return isProject; - } - - /** - * @param resource not nullable - */ - public static boolean isModule(final Resource resource) { - return Objects.equals(MODULE, resource.getQualifier()); - } - - /** - * @param resource not nullable - */ - public static boolean isDirectory(final Resource resource) { - return Objects.equals(DIRECTORY, resource.getQualifier()); - } - - /** - * @param resource not nullable - */ - public static boolean isFile(final Resource resource) { - return Objects.equals(FILE, resource.getQualifier()); - } } diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/resources/Resource.java b/sonar-plugin-api/src/main/java/org/sonar/api/resources/Resource.java deleted file mode 100644 index 6ff4e52507c..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/resources/Resource.java +++ /dev/null @@ -1,284 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.resources; - -import java.io.Serializable; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import org.apache.commons.lang.StringUtils; -import org.sonar.api.batch.fs.InputComponent; - -/** - * @since 1.10 - * @deprecated since 5.6 replaced by {@link InputComponent} - */ -@Deprecated -public abstract class Resource implements Serializable { - - /** - * @deprecated since 2.6. Use Scopes.PROJECT. - */ - @Deprecated - public static final String SCOPE_SET = Scopes.PROJECT; - - /** - * @deprecated since 2.6. Use Scopes.DIRECTORY. - */ - @Deprecated - public static final String SCOPE_SPACE = Scopes.DIRECTORY; - - /** - * @deprecated since 2.6. Use Scopes.FILE. - */ - @Deprecated - public static final String SCOPE_ENTITY = Scopes.FILE; - - /** - * @deprecated since 2.6. Use Qualifiers.VIEW. - */ - @Deprecated - public static final String QUALIFIER_VIEW = Qualifiers.VIEW; - - /** - * @deprecated since 2.6. Use Qualifiers.SUBVIEW. - */ - @Deprecated - public static final String QUALIFIER_SUBVIEW = Qualifiers.SUBVIEW; - - /** - * @deprecated since 2.6. Use Qualifiers.LIBRARY. - */ - @Deprecated - public static final String QUALIFIER_LIB = Qualifiers.LIBRARY; - - /** - * @deprecated since 2.6. Use Qualifiers.PROJECT. - */ - @Deprecated - public static final String QUALIFIER_PROJECT = Qualifiers.PROJECT; - - /** - * @deprecated since 2.6. Use Qualifiers.MODULE. - */ - @Deprecated - public static final String QUALIFIER_MODULE = Qualifiers.MODULE; - - /** - * @deprecated since 2.6. Use Qualifiers.DIRECTORY. - */ - @Deprecated - public static final String QUALIFIER_DIRECTORY = Qualifiers.DIRECTORY; - - /** - * @deprecated since 2.6. Use Qualifiers.FILE. - */ - @Deprecated - public static final String QUALIFIER_FILE = Qualifiers.FILE; - - private Integer id; - - private String key; - - private String uuid; - - private String path; - - private String effectiveKey; - - /** - * @return the resource key - */ - public final String getKey() { - return key; - } - - /** - * Internal use only - */ - public void setKey(String s) { - this.key = s; - } - - /** - * @since 5.0 - */ - public final String getUuid() { - return uuid; - } - - /** - * Internal use only - */ - public void setUuid(String s) { - this.uuid = s; - } - - /** - * @return the resource name - */ - public abstract String getName(); - - /** - * @return the resource long name - */ - public abstract String getLongName(); - - /** - * @return the resource description - */ - public abstract String getDescription(); - - /** - * @return the language of the resource. Only {@link File}s may have a non null value. - * @deprecated since 5.1 use {@link #language()} - */ - @Deprecated - @CheckForNull - public abstract Language getLanguage(); - - /** - * @return the language of the resource. Only {@link File}s may have a non null value. - */ - @CheckForNull - public String language() { - Language l = getLanguage(); - return l != null ? l.getKey() : null; - } - - /** - * @return the scope - */ - public abstract String getScope(); - - /** - * The qualifier tells the type of the resource. For example, it can be a File, a Class, a Project, a Unit Test... - * - * @return the qualifier - * @see org.sonar.api.resources.Qualifiers for the list of qualifiers - * @see org.sonar.api.resources.ResourceUtils to find out if a resource if a class, a unit test,... from its qualifier - */ - public abstract String getQualifier(); - - /** - * The parent is used to build the resources tree, for example for relations between files, directories and projects. - *

- * Return null if the parent is the current project (or module in case of multi-module). - * - */ - @CheckForNull - public abstract Resource getParent(); - - /** - * Check resource against an Ant pattern, like mypackag?/*Foo.java. It's used for example to match resource exclusions. - * - * @param antPattern Ant-like pattern (with **, * and ?). It includes file suffixes. - * @return true if the resource matches the Ant pattern - */ - public abstract boolean matchFilePattern(String antPattern); - - public final Integer getId() { - return id; - } - - /** - * Internal use only - */ - public Resource setId(Integer id) { - this.id = id; - return this; - } - - public String getPath() { - return path; - } - - public Resource setPath(@Nullable String path) { - this.path = normalize(path); - return this; - } - - @CheckForNull - protected static String normalize(@Nullable String path) { - if (StringUtils.isBlank(path)) { - return null; - } - String normalizedPath = path; - normalizedPath = normalizedPath.replace('\\', '/'); - normalizedPath = StringUtils.trim(normalizedPath); - if (Directory.SEPARATOR.equals(normalizedPath)) { - return Directory.SEPARATOR; - } - normalizedPath = StringUtils.removeStart(normalizedPath, Directory.SEPARATOR); - normalizedPath = StringUtils.removeEnd(normalizedPath, Directory.SEPARATOR); - return normalizedPath; - } - - public String getEffectiveKey() { - return effectiveKey; - } - - /** - * Internal use only - */ - public final Resource setEffectiveKey(String effectiveKey) { - this.effectiveKey = effectiveKey; - return this; - } - - /** - * @deprecated since 2.6. - */ - @Deprecated - public final boolean isExcluded() { - return false; - } - - /** - * Internal use only - * - * @deprecated since 2.6 should use SensorContext#isExcluded(resource). It will make inheritance of Resource easier. - */ - @Deprecated - public final Resource setExcluded(boolean b) { - return this; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null) { - return false; - } - if (getClass() != o.getClass()) { - return false; - } - - Resource resource = (Resource) o; - return key.equals(resource.key); - } - - @Override - public int hashCode() { - // For File and Directory using deprecatedKey, key can be null - return key != null ? key.hashCode() : super.hashCode(); - } -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/resources/ResourceUtils.java b/sonar-plugin-api/src/main/java/org/sonar/api/resources/ResourceUtils.java deleted file mode 100644 index 0fbcaa0c573..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/resources/ResourceUtils.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.resources; - -import org.apache.commons.lang.StringUtils; - -/** - * @since 1.10 - * @deprecated since 5.6 as {@link Resource} is deprecated - */ -@Deprecated -public final class ResourceUtils { - - private ResourceUtils() { - } - - /** - * @return whether the resource is a view - */ - public static boolean isView(Resource resource) { - return isSet(resource) && Qualifiers.VIEW.equals(resource.getQualifier()); - } - - /** - * @return whether the resource is a subview (in the view tree) - */ - public static boolean isSubview(Resource resource) { - return isSet(resource) && Qualifiers.SUBVIEW.equals(resource.getQualifier()); - } - - /** - * @return whether the resource is the root project - */ - public static boolean isRootProject(Resource resource) { - return Qualifiers.PROJECT.equals(resource.getQualifier()); - } - - /** - * @return whether a resource is a maven module of project - */ - public static boolean isModuleProject(Resource resource) { - return Qualifiers.MODULE.equals(resource.getQualifier()); - } - - /** - * @return whether a resource is a set - */ - public static boolean isSet(Resource resource) { - return resource != null && Scopes.PROJECT.equals(resource.getScope()); - } - - /** - * @return whether a resource is a space - */ - public static boolean isSpace(Resource resource) { - return resource != null && Scopes.DIRECTORY.equals(resource.getScope()); - } - - /** - * @return whether a resource is an entity. - */ - public static boolean isEntity(Resource resource) { - return resource != null && Scopes.FILE.equals(resource.getScope()); - } - - /** - * This method equal isRootProject(resource) or isModuleProject(resource) or isView(resource) or isSubview(resource) - */ - public static boolean isProject(Resource resource) { - return isSet(resource); - } - - /** - * Alias for {@link #isSpace(Resource)} - */ - public static boolean isDirectory(Resource resource) { - return isSpace(resource); - } - - /** - * Alias for {@link #isEntity(Resource)} - */ - public static boolean isFile(Resource resource) { - return isEntity(resource); - } - - /* QUALIFIERS */ - - /** - * @return whether a resource is a unit test class - * @deprecated since 5.1 use {@link #isUnitTestFile(Resource)} - */ - @Deprecated - public static boolean isUnitTestClass(Resource resource) { - return isUnitTestFile(resource); - } - - /** - * @return whether a resource is a unit test class - */ - public static boolean isUnitTestFile(Resource resource) { - return Qualifiers.UNIT_TEST_FILE.equals(resource.getQualifier()); - } - - /** - * @deprecated since 5.2 No more design features - */ - @Deprecated - public static boolean isLibrary(Resource resource) { - return Qualifiers.LIBRARY.equals(resource.getQualifier()); - } - - /** - * @param resource not nullable - * @return true if this type of resource is persisted in database - * @since 2.6 - */ - public static boolean isPersistable(Resource resource) { - return StringUtils.equals(Scopes.PROJECT, resource.getScope()) || StringUtils.equals(Scopes.DIRECTORY, resource.getScope()) || - StringUtils.equals(Scopes.FILE, resource.getScope()); - } - -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/resources/Scopes.java b/sonar-plugin-api/src/main/java/org/sonar/api/resources/Scopes.java index c06f858f46c..2d8ae3cf76d 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/resources/Scopes.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/resources/Scopes.java @@ -20,7 +20,6 @@ package org.sonar.api.resources; import org.apache.commons.lang.ArrayUtils; -import org.apache.commons.lang.StringUtils; /** * Resource scopes are used to group some types of resources. For example Java methods, Flex methods, C functions @@ -71,51 +70,12 @@ public final class Scopes { // only static methods } - public static boolean isProject(final Resource resource) { - return StringUtils.equals(PROJECT, resource.getScope()); - } - - public static boolean isDirectory(final Resource resource) { - return StringUtils.equals(DIRECTORY, resource.getScope()); - } - - /** - * This scope is sometimes called a "compilation unit". - */ - public static boolean isFile(final Resource resource) { - return StringUtils.equals(FILE, resource.getScope()); - } - - /** - * A program unit can be a Java class. - * @deprecated since 4.3 resources under FILE level are no more be supported since 4.2. - */ - @Deprecated - public static boolean isProgramUnit(final Resource resource) { - return StringUtils.equals(PROGRAM_UNIT, resource.getScope()); - } - - /** - * @deprecated since 4.3 resources under FILE level are no more be supported since 4.2. - */ - @Deprecated - public static boolean isBlockUnit(final Resource resource) { - return StringUtils.equals(BLOCK_UNIT, resource.getScope()); - } - - public static boolean isHigherThan(final Resource resource, final String than) { - return isHigherThan(resource.getScope(), than); - } - public static boolean isHigherThan(final String scope, final String than) { int index = ArrayUtils.indexOf(SORTED_SCOPES, scope); int thanIndex = ArrayUtils.indexOf(SORTED_SCOPES, than); return index < thanIndex; } - public static boolean isHigherThanOrEquals(final Resource resource, final String than) { - return isHigherThanOrEquals(resource.getScope(), than); - } public static boolean isHigherThanOrEquals(final String scope, final String than) { int index = ArrayUtils.indexOf(SORTED_SCOPES, scope); diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/scan/issue/filter/FilterableIssue.java b/sonar-plugin-api/src/main/java/org/sonar/api/scan/issue/filter/FilterableIssue.java index 4731cd18615..14a62c88886 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/scan/issue/filter/FilterableIssue.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/scan/issue/filter/FilterableIssue.java @@ -52,12 +52,6 @@ public interface FilterableIssue { @CheckForNull TextRange textRange(); - /** - * @deprecated since 5.5 use {@link #gap()} - */ - @Deprecated - Double effortToFix(); - /** * @since 5.5 */ diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/security/UserFinder.java b/sonar-plugin-api/src/main/java/org/sonar/api/security/UserFinder.java deleted file mode 100644 index 5d8f0f827b3..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/security/UserFinder.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.security; - -import org.sonar.api.database.model.User; -import org.sonar.api.ce.ComputeEngineSide; -import org.sonar.api.server.ServerSide; - -/** - * @since 2.10 - * @deprecated since 5.1 DB access will soon be removed from batch side - */ -@Deprecated -@ServerSide -@ComputeEngineSide -public interface UserFinder { - - User findById(int id); - - User findByLogin(String login); - -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/source/Highlightable.java b/sonar-plugin-api/src/main/java/org/sonar/api/source/Highlightable.java deleted file mode 100644 index 5fcaaf31919..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/source/Highlightable.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.source; - -import org.sonar.api.batch.sensor.SensorContext; -import org.sonar.api.component.Perspective; -import org.sonar.api.component.ResourcePerspectives; - -/** - * Use this perspective to save syntax highlighting on files. - * See {@link ResourcePerspectives}. - * @since 3.6 - * @deprecated since 5.6 use {@link SensorContext#newHighlighting()} - */ -@Deprecated -public interface Highlightable extends Perspective { - - interface HighlightingBuilder { - - HighlightingBuilder highlight(int startOffset, int endOffset, String typeOfText); - - /** - * @since 5.6 - */ - HighlightingBuilder highlight(int startLine, int startLineOffset, int endLine, int endLineOffset, String typeOfText); - - void done(); - } - - HighlightingBuilder newHighlighting(); -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/source/Symbol.java b/sonar-plugin-api/src/main/java/org/sonar/api/source/Symbol.java deleted file mode 100644 index 9920c725a35..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/source/Symbol.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.source; - -import org.sonar.api.batch.sensor.SensorContext; - -/** - * @deprecated since 5.6 use {@link SensorContext#newSymbolTable()} - */ -@Deprecated -public interface Symbol { - - /** - * @deprecated in 5.2 not used. - */ - @Deprecated - int getDeclarationStartOffset(); - - /** - * @deprecated in 5.2 not used. - */ - @Deprecated - int getDeclarationEndOffset(); - - /** - * @deprecated in 4.3 not used. - */ - @Deprecated - String getFullyQualifiedName(); -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/source/Symbolizable.java b/sonar-plugin-api/src/main/java/org/sonar/api/source/Symbolizable.java deleted file mode 100644 index 6aee743c4dd..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/source/Symbolizable.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.source; - -import java.util.List; -import org.sonar.api.batch.sensor.SensorContext; -import org.sonar.api.component.Perspective; -import org.sonar.api.component.ResourcePerspectives; - -/** - * Use this perspective to save symbol references on files. - * See {@link ResourcePerspectives}. - * @since 3.6 - * @deprecated since 5.6 use {@link SensorContext#newSymbolTable()} - */ -@Deprecated -public interface Symbolizable extends Perspective { - - interface SymbolTableBuilder { - - /** - * Creates a new Symbol. - * The offsets are global in the file. - */ - Symbol newSymbol(int fromOffset, int toOffset); - - /** - * @since 5.6 - */ - Symbol newSymbol(int startLine, int startLineOffset, int endLine, int endLineOffset); - - /** - * Creates a new reference for a symbol. - * The length of the reference is assumed to be the same as the symbol's length. - */ - void newReference(Symbol symbol, int fromOffset); - - /** - * Creates a new reference for a symbol. - * The offsets are global in the file. - * - * @since 5.3 - */ - void newReference(Symbol symbol, int fromOffset, int toOffset); - - /** - * @since 5.6 - */ - void newReference(Symbol symbol, int startLine, int startLineOffset, int endLine, int endLineOffset); - - /** - * Creates a {@link SymbolTable} containing all symbols and references previously created in this file. - */ - SymbolTable build(); - - } - - interface SymbolTable { - - List symbols(); - - /** - * @deprecated since 5.2 not used - */ - @Deprecated - List references(Symbol symbol); - } - - SymbolTableBuilder newSymbolTableBuilder(); - - void setSymbolTable(SymbolTable symbolTable); -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/source/package-info.java b/sonar-plugin-api/src/main/java/org/sonar/api/source/package-info.java deleted file mode 100644 index 9fff4ab3fbe..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/source/package-info.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.source; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/user/UserFinder.java b/sonar-plugin-api/src/main/java/org/sonar/api/user/UserFinder.java deleted file mode 100644 index 6db21a7cd0f..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/user/UserFinder.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.user; - -import java.util.List; -import javax.annotation.CheckForNull; -import org.sonar.api.ce.ComputeEngineSide; -import org.sonar.api.server.ServerSide; - -/** - * @since 3.6 - * @deprecated since 5.1 DB access will soon be removed from batch side - */ -@Deprecated -@ServerSide -@ComputeEngineSide -public interface UserFinder { - - @CheckForNull - User findByLogin(String login); - - List findByLogins(List logins); - - List find(UserQuery query); -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/utils/StaxParser.java b/sonar-plugin-api/src/main/java/org/sonar/api/utils/StaxParser.java deleted file mode 100644 index efac3ee61ca..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/utils/StaxParser.java +++ /dev/null @@ -1,210 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.utils; - -import com.ctc.wstx.stax.WstxInputFactory; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.Reader; -import java.net.URL; -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLResolver; -import javax.xml.stream.XMLStreamException; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang.StringUtils; -import org.codehaus.staxmate.SMInputFactory; -import org.codehaus.staxmate.in.SMHierarchicCursor; - -/** - * @since 1.10 - * @deprecated since 5.6 plugins should use their own dependencies - */ -@Deprecated -public class StaxParser { - - private SMInputFactory inf; - private XmlStreamHandler streamHandler; - private boolean isoControlCharsAwareParser; - - /** - * Stax parser for a given stream handler and iso control chars set awarness to off - * - * @param streamHandler the xml stream handler - */ - public StaxParser(XmlStreamHandler streamHandler) { - this(streamHandler, false); - } - - /** - * Stax parser for a given stream handler and iso control chars set awarness to on. - * The iso control chars in the xml file will be replaced by simple spaces, usefull for - * potentially bogus XML files to parse, this has a small perfs overhead so use it only when necessary - * - * @param streamHandler the xml stream handler - * @param isoControlCharsAwareParser true or false - */ - public StaxParser(XmlStreamHandler streamHandler, boolean isoControlCharsAwareParser) { - this.streamHandler = streamHandler; - XMLInputFactory xmlFactory = XMLInputFactory.newInstance(); - if (xmlFactory instanceof WstxInputFactory) { - WstxInputFactory wstxInputfactory = (WstxInputFactory) xmlFactory; - wstxInputfactory.configureForLowMemUsage(); - wstxInputfactory.getConfig().setUndeclaredEntityResolver(new UndeclaredEntitiesXMLResolver()); - } - xmlFactory.setProperty(XMLInputFactory.IS_VALIDATING, false); - xmlFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); - xmlFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, false); - this.isoControlCharsAwareParser = isoControlCharsAwareParser; - inf = new SMInputFactory(xmlFactory); - } - - public void parse(File xmlFile) throws XMLStreamException { - FileInputStream input = null; - try { - input = new FileInputStream(xmlFile); - parse(input); - } catch (FileNotFoundException e) { - throw new XMLStreamException(e); - } finally { - IOUtils.closeQuietly(input); - } - } - - public void parse(InputStream xmlInput) throws XMLStreamException { - xmlInput = isoControlCharsAwareParser ? new ISOControlCharAwareInputStream(xmlInput) : xmlInput; - parse(inf.rootElementCursor(xmlInput)); - } - - public void parse(Reader xmlReader) throws XMLStreamException { - if (isoControlCharsAwareParser) { - throw new SonarException("Method call not supported when isoControlCharsAwareParser=true"); - } - parse(inf.rootElementCursor(xmlReader)); - } - - public void parse(URL xmlUrl) throws XMLStreamException { - try { - parse(xmlUrl.openStream()); - } catch (IOException e) { - throw new XMLStreamException(e); - } - } - - private void parse(SMHierarchicCursor rootCursor) throws XMLStreamException { - try { - streamHandler.stream(rootCursor); - } finally { - rootCursor.getStreamReader().closeCompletely(); - } - } - - private static class UndeclaredEntitiesXMLResolver implements XMLResolver { - @Override - public Object resolveEntity(String arg0, String arg1, String fileName, String undeclaredEntity) throws XMLStreamException { - // avoid problems with XML docs containing undeclared entities.. return the entity under its raw form if not an unicode expression - if (StringUtils.startsWithIgnoreCase(undeclaredEntity, "u") && undeclaredEntity.length() == 5) { - int unicodeCharHexValue = Integer.parseInt(undeclaredEntity.substring(1), 16); - if (Character.isDefined(unicodeCharHexValue)) { - undeclaredEntity = new String(new char[] {(char) unicodeCharHexValue}); - } - } - return undeclaredEntity; - } - } - - /** - * Simple interface for handling XML stream to parse - */ - public interface XmlStreamHandler { - void stream(SMHierarchicCursor rootCursor) throws XMLStreamException; - } - - private static class ISOControlCharAwareInputStream extends InputStream { - - private InputStream inputToCheck; - - public ISOControlCharAwareInputStream(InputStream inputToCheck) { - super(); - this.inputToCheck = inputToCheck; - } - - @Override - public int read() throws IOException { - return inputToCheck.read(); - } - - @Override - public int available() throws IOException { - return inputToCheck.available(); - } - - @Override - public void close() throws IOException { - inputToCheck.close(); - } - - @Override - public synchronized void mark(int readlimit) { - inputToCheck.mark(readlimit); - } - - @Override - public boolean markSupported() { - return inputToCheck.markSupported(); - } - - @Override - public int read(byte[] b, int off, int len) throws IOException { - int readen = inputToCheck.read(b, off, len); - checkBufferForISOControlChars(b, off, len); - return readen; - } - - @Override - public int read(byte[] b) throws IOException { - int readen = inputToCheck.read(b); - checkBufferForISOControlChars(b, 0, readen); - return readen; - } - - @Override - public synchronized void reset() throws IOException { - inputToCheck.reset(); - } - - @Override - public long skip(long n) throws IOException { - return inputToCheck.skip(n); - } - - private static void checkBufferForISOControlChars(byte[] buffer, int off, int len) { - for (int i = off; i < len; i++) { - char streamChar = (char) buffer[i]; - if (Character.isISOControl(streamChar) && streamChar != '\n') { - // replace control chars by a simple space - buffer[i] = ' '; - } - } - } - } -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/utils/TempFileUtils.java b/sonar-plugin-api/src/main/java/org/sonar/api/utils/TempFileUtils.java deleted file mode 100644 index e19f0323785..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/utils/TempFileUtils.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.utils; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; - -/** - * @deprecated since 4.0 use {@link TempFolder} - */ -@Deprecated -public final class TempFileUtils { - - private TempFileUtils() { - // only static methods - } - - /** - * Create a temporary directory. This directory is NOT deleted when the JVM stops, because using File#deleteOnExit() - * is evil (google "deleteonExit evil"). Copied from http://stackoverflow.com/questions/617414/create-a-temporary-directory-in-java : - *

    - *
  1. deleteOnExit() only deletes for normal JVM shutdowns, not crashes or killing the JVM process
  2. - *
  3. deleteOnExit() only deletes on JVM shutdown - not good for long running server processes because 3 :
  4. - *
  5. The most evil of all - deleteOnExit() consumes memory for each temp file entry. If your process is running for months, - * or creates a lot of temp files in a short time, you consume memory and never release it until the JVM - * shuts down.
  6. - *
- */ - public static File createTempDirectory() throws IOException { - return createTempDirectory("temp"); - } - - public static File createTempDirectory(String prefix) throws IOException { - Path dir = Files.createTempDirectory(prefix); - return dir.toFile(); - } -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/utils/TimeProfiler.java b/sonar-plugin-api/src/main/java/org/sonar/api/utils/TimeProfiler.java deleted file mode 100644 index 07da3f332fa..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/utils/TimeProfiler.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.utils; - -import org.slf4j.LoggerFactory; - -/** - * A very simple profiler to log the time elapsed performing some tasks. - * This implementation is not thread-safe. - * - * @deprecated since 5.1. Replaced by {@link org.sonar.api.utils.log.Profiler} - * @since 2.0 - */ -@Deprecated -public class TimeProfiler { - - private org.slf4j.Logger logger; - private long start = 0; - private String name; - private boolean debug = false; - - public TimeProfiler(org.slf4j.Logger logger) { - this.logger = logger; - } - - public TimeProfiler(Class clazz) { - this.logger = LoggerFactory.getLogger(clazz); - } - - /** - * Use the default Sonar logger - */ - public TimeProfiler() { - this.logger = LoggerFactory.getLogger(getClass()); - } - - public TimeProfiler start(String name) { - this.name = name; - this.start = System.currentTimeMillis(); - if (debug) { - logger.debug("{} ...", name); - } else { - logger.info("{}...", name); - } - return this; - } - - public TimeProfiler setLogger(org.slf4j.Logger logger) { - this.logger = logger; - return this; - } - - public org.slf4j.Logger getLogger() { - return logger; - } - - /** - * @since 2.4 - */ - public TimeProfiler setLevelToDebug() { - debug = true; - return this; - } - - public TimeProfiler stop() { - if (start > 0) { - String format = "{} done: {} ms"; - if (debug) { - logger.debug(format, name, System.currentTimeMillis() - start); - } else { - logger.info(format, name, System.currentTimeMillis() - start); - } - } - start = 0; - return this; - } -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/utils/WorkUnit.java b/sonar-plugin-api/src/main/java/org/sonar/api/utils/WorkUnit.java deleted file mode 100644 index 4829368c541..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/utils/WorkUnit.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.utils; - -import org.apache.commons.lang.ArrayUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang.builder.ToStringBuilder; -import org.apache.commons.lang.builder.ToStringStyle; - -import javax.annotation.Nullable; - -import java.io.Serializable; - -/** - * @deprecated since 4.2. Use WorkDuration instead - */ -@Deprecated -public final class WorkUnit implements Serializable { - - public static final String DAYS = "d"; - public static final String MINUTES = "mn"; - public static final String HOURS = "h"; - public static final String DEFAULT_UNIT = DAYS; - private static final String[] UNITS = {DAYS, MINUTES, HOURS}; - - public static final double DEFAULT_VALUE = 0.0; - - private double value = 0d; - private String unit = DEFAULT_UNIT; - - WorkUnit(double value, String unit) { - this.value = value; - this.unit = unit; - } - - public double getValue() { - return value; - } - - public String getUnit() { - return unit; - } - - public static WorkUnit create(@Nullable Double value, @Nullable String unit) { - String defaultIfEmptyUnit = StringUtils.defaultIfEmpty(unit, DEFAULT_UNIT); - if (!ArrayUtils.contains(UNITS, defaultIfEmptyUnit)) { - throw new IllegalArgumentException("Unit can not be: " + defaultIfEmptyUnit + ". Possible values are " + ArrayUtils.toString(UNITS)); - } - double d = value != null ? value : DEFAULT_VALUE; - if (d < 0.0) { - throw new IllegalArgumentException("Value can not be negative: " + d); - } - return new WorkUnit(d, defaultIfEmptyUnit); - } - - public static WorkUnit create() { - return create(0d, DEFAULT_UNIT); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - WorkUnit workUnit = (WorkUnit) o; - - if (Double.compare(workUnit.value, value) != 0) { - return false; - } - return unit.equals(workUnit.unit); - - } - - @Override - public int hashCode() { - int result; - long temp; - temp = Double.doubleToLongBits(value); - result = (int) (temp ^ (temp >>> 32)); - result = 31 * result + unit.hashCode(); - return result; - } - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); - } -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/utils/XmlParserException.java b/sonar-plugin-api/src/main/java/org/sonar/api/utils/XmlParserException.java deleted file mode 100644 index 5999b33868d..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/utils/XmlParserException.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.utils; - -/** - * @since 1.10 - * @deprecated since 5.6 - */ -@Deprecated -public class XmlParserException extends SonarException { - public XmlParserException() { - } - - public XmlParserException(String s) { - super(s); - } - - public XmlParserException(String s, Throwable throwable) { - super(s, throwable); - } - - public XmlParserException(Throwable throwable) { - super(throwable); - } -} diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/utils/XpathParser.java b/sonar-plugin-api/src/main/java/org/sonar/api/utils/XpathParser.java deleted file mode 100644 index 0f1de6452dd..00000000000 --- a/sonar-plugin-api/src/main/java/org/sonar/api/utils/XpathParser.java +++ /dev/null @@ -1,280 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.utils; - -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import javax.annotation.Nullable; -import javax.xml.namespace.QName; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.xpath.XPath; -import javax.xml.xpath.XPathConstants; -import javax.xml.xpath.XPathExpression; -import javax.xml.xpath.XPathExpressionException; -import javax.xml.xpath.XPathFactory; -import org.apache.commons.io.IOUtils; -import org.sonar.api.utils.log.Logger; -import org.sonar.api.utils.log.Loggers; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.SAXException; - -/** - * XML Parsing tool using XPATH. It's recommended to use StaxParser when parsing big XML files. - * - * @since 1.10 - * @deprecated since 5.6 plugins should use their own dependencies - */ -@Deprecated -public class XpathParser { - - private static final String CAN_NOT_PARSE_XML = "can not parse xml : "; - private Element root = null; - private Document doc = null; - private DocumentBuilder builder; - private XPath xpath; - private Map compiledExprs = new HashMap<>(); - - public XpathParser() { - DocumentBuilderFactory bf = DocumentBuilderFactory.newInstance(); - try { - bf.setFeature("http://apache.org/xml/features/validation/schema", false); - bf.setFeature("http://xml.org/sax/features/external-general-entities", false); - bf.setFeature("http://xml.org/sax/features/validation", false); - bf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); - bf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); - bf.setFeature("http://apache.org/xml/features/allow-java-encodings", true); - } catch (ParserConfigurationException e) { - Logger log = Loggers.get(this.getClass().getName()); - log.error("Error occured during features set up.", e); - } - try { - bf.setNamespaceAware(false); - bf.setValidating(false); - builder = bf.newDocumentBuilder(); - } catch (ParserConfigurationException e) { - throw new XmlParserException("can not create a XML parser", e); - } - } - - public void parse(@Nullable File file) { - if (file == null || !file.exists()) { - throw new XmlParserException("File not found : " + file); - } - - BufferedReader buffer = null; - try { - buffer = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)); - parse(buffer); - - } catch (IOException e) { - throw new XmlParserException("can not parse the file " + file.getAbsolutePath(), e); - - } finally { - IOUtils.closeQuietly(buffer); - } - } - - public void parse(InputStream stream) { - BufferedReader buffer = null; - try { - buffer = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8)); - parse(buffer); - - } catch (IOException e) { - throw new XmlParserException("can not parse the stream", e); - - } finally { - IOUtils.closeQuietly(buffer); - } - } - - private void parse(BufferedReader buffer) throws IOException { - parse(IOUtils.toString(buffer)); - } - - public void parse(String xml) { - try { - String fixedXml = fixUnicodeChar(xml); - doc = builder.parse(new ByteArrayInputStream(fixedXml.getBytes(StandardCharsets.UTF_8))); - XPathFactory factory = XPathFactory.newInstance(); - xpath = factory.newXPath(); - - } catch (IOException | SAXException e) { - throw new XmlParserException(CAN_NOT_PARSE_XML + xml, e); - } - } - - public Element getRoot() { - if (root == null && doc != null) { - root = doc.getDocumentElement(); - } - return root; - } - - public Document getDocument() { - return doc; - } - - public Element getChildElement(Element base, String elementName) { - NodeList childrens = base.getElementsByTagName(elementName); - for (int i = 0; i < childrens.getLength(); i++) { - Node nde = childrens.item(i); - if (nde.getNodeType() == Node.ELEMENT_NODE) { - return (Element) nde; - } - } - return null; - } - - public Element getChildElement(String elementName) { - NodeList childrens = getRoot().getElementsByTagName(elementName); - for (int i = 0; i < childrens.getLength(); i++) { - Node nde = childrens.item(i); - if (nde.getNodeType() == Node.ELEMENT_NODE) { - return (Element) nde; - } - } - return null; - } - - public List getChildElements(String elementName) { - List rtrVal = new ArrayList<>(); - NodeList childrens = getRoot().getElementsByTagName(elementName); - for (int i = 0; i < childrens.getLength(); i++) { - Node nde = childrens.item(i); - if (nde.getNodeType() == Node.ELEMENT_NODE) { - rtrVal.add((Element) nde); - } - } - return rtrVal; - } - - public List getChildElements(Element base, String elementName) { - List rtrVal = new ArrayList<>(); - NodeList childrens = base.getElementsByTagName(elementName); - for (int i = 0; i < childrens.getLength(); i++) { - Node nde = childrens.item(i); - if (nde.getNodeType() == Node.ELEMENT_NODE) { - rtrVal.add((Element) nde); - } - } - return rtrVal; - } - - public String getChildElementValue(Element base, String elementName) { - NodeList childrens = base.getElementsByTagName(elementName); - for (int i = 0; i < childrens.getLength(); i++) { - if (childrens.item(i).getNodeType() == Node.ELEMENT_NODE) { - return childrens.item(i).getFirstChild().getNodeValue(); - } - } - return null; - } - - public String getElementValue(Node base) { - if (base.getNextSibling() != null && base.getNextSibling().getNodeType() == Node.TEXT_NODE) { - return base.getNextSibling().getNodeValue(); - } else if (base.getFirstChild() != null && base.getFirstChild().getNodeType() == Node.TEXT_NODE) { - return base.getFirstChild().getNodeValue(); - } - return null; - } - - public String getChildElementValue(String elementName) { - NodeList childrens = getRoot().getElementsByTagName(elementName); - for (int i = 0; i < childrens.getLength(); i++) { - if (childrens.item(i).getNodeType() == Node.ELEMENT_NODE) { - return childrens.item(i).getFirstChild().getNodeValue(); - } - } - return null; - } - - public Object executeXPath(Node node, QName qname, String xPathExpression) { - XPathExpression expr = compiledExprs.get(xPathExpression); - try { - if (expr == null) { - expr = xpath.compile(xPathExpression); - compiledExprs.put(xPathExpression, expr); - } - return expr.evaluate(node, qname); - - } catch (XPathExpressionException e) { - throw new XmlParserException("Unable to evaluate xpath expression :" + xPathExpression, e); - } - } - - public String executeXPath(String xPathExpression) { - return (String) executeXPath(doc, XPathConstants.STRING, xPathExpression); - } - - public String executeXPath(Node node, String xPathExpression) { - return (String) executeXPath(node, XPathConstants.STRING, xPathExpression); - } - - public NodeList executeXPathNodeList(String xPathExpression) { - return (NodeList) executeXPath(doc, XPathConstants.NODESET, xPathExpression); - } - - public NodeList executeXPathNodeList(Node node, String xPathExpression) { - return (NodeList) executeXPath(node, XPathConstants.NODESET, xPathExpression); - } - - public Node executeXPathNode(Node node, String xPathExpression) { - return (Node) executeXPath(node, XPathConstants.NODE, xPathExpression); - } - - /** - * Fix the error occured when parsing a string containing unicode character - * Example : {@code &u20ac;} will be replaced by {@code €} - */ - protected String fixUnicodeChar(String text) { - String unicode = "&u"; - StringBuilder replace = new StringBuilder(text); - if (text.indexOf(unicode) >= 0) { - Pattern p = Pattern.compile("&u([0-9a-fA-F]{1,4});"); - Matcher m = p.matcher(replace.toString()); - int nbFind = 0; - while (m.find()) { - // Add one index each time because we add one character each time (&u -> &#x) - replace.replace(m.start() + nbFind, m.end() + nbFind, "&#x" + m.group(1) + ";"); - nbFind++; - } - } - return replace.toString(); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/batch/DefaultFormulaDataTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/batch/DefaultFormulaDataTest.java deleted file mode 100644 index a138b7f6515..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/batch/DefaultFormulaDataTest.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.batch; - -import org.junit.Test; -import org.sonar.api.measures.MeasuresFilter; -import org.sonar.api.measures.Metric; - -public class DefaultFormulaDataTest { - - DefaultFormulaData underTest = new DefaultFormulaData(null); - - @Test(expected = UnsupportedOperationException.class) - public void fail_if_used_1() { - underTest.getChildren(); - } - - @Test(expected = UnsupportedOperationException.class) - public void fail_if_used_2() { - underTest.getChildrenMeasures((MeasuresFilter) null); - } - - @Test(expected = UnsupportedOperationException.class) - public void fail_if_used_3() { - underTest.getChildrenMeasures((Metric) null); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/batch/InitializerTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/batch/InitializerTest.java deleted file mode 100644 index 2101292a049..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/batch/InitializerTest.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.batch; - -import org.junit.Test; -import org.sonar.api.resources.Project; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -public class InitializerTest { - - @Test - public void shouldBeExecutedByDefault() { - Project project = mock(Project.class); - assertThat(new FakeInitializer().shouldExecuteOnProject(project)).isTrue(); - } - - private class FakeInitializer extends Initializer { - @Override - public void execute(Project project) { - } - } - -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/batch/debt/DebtRemediationFunctionTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/batch/debt/DebtRemediationFunctionTest.java deleted file mode 100644 index c76e0d4a81b..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/batch/debt/DebtRemediationFunctionTest.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.batch.debt; - -import org.junit.Test; -import org.sonar.api.utils.Duration; - -import static org.assertj.core.api.Assertions.assertThat; - -public class DebtRemediationFunctionTest { - - @Test - public void create_linear() { - DebtRemediationFunction function = DebtRemediationFunction.createLinear(Duration.create(10)); - assertThat(function.type()).isEqualTo(DebtRemediationFunction.Type.LINEAR); - assertThat(function.coefficient()).isEqualTo(Duration.create(10)); - assertThat(function.offset()).isNull(); - } - - @Test - public void create_linear_with_offset() { - DebtRemediationFunction function = DebtRemediationFunction.createLinearWithOffset(Duration.create(10), Duration.create(5)); - assertThat(function.type()).isEqualTo(DebtRemediationFunction.Type.LINEAR_OFFSET); - assertThat(function.coefficient()).isEqualTo(Duration.create(10)); - assertThat(function.offset()).isEqualTo(Duration.create(5)); - } - - @Test - public void create_constant_per_issue() { - DebtRemediationFunction function = DebtRemediationFunction.createConstantPerIssue(Duration.create(10)); - assertThat(function.type()).isEqualTo(DebtRemediationFunction.Type.CONSTANT_ISSUE); - assertThat(function.coefficient()).isNull(); - assertThat(function.offset()).isEqualTo(Duration.create(10)); - } - - @Test - public void test_equals_and_hashcode() throws Exception { - DebtRemediationFunction function = DebtRemediationFunction.createLinearWithOffset(Duration.create(10), Duration.create(5)); - DebtRemediationFunction functionWithSameValue = DebtRemediationFunction.createLinearWithOffset(Duration.create(10), Duration.create(5)); - DebtRemediationFunction functionWithDifferentType = DebtRemediationFunction.createConstantPerIssue(Duration.create(5)); - - assertThat(function).isEqualTo(function); - assertThat(function).isEqualTo(functionWithSameValue); - assertThat(function).isNotEqualTo(functionWithDifferentType); - assertThat(function).isNotEqualTo(DebtRemediationFunction.createLinearWithOffset(Duration.create(11), Duration.create(5))); - assertThat(function).isNotEqualTo(DebtRemediationFunction.createLinearWithOffset(Duration.create(10), Duration.create(6))); - assertThat(function).isNotEqualTo(DebtRemediationFunction.createLinear(Duration.create(10))); - assertThat(function).isNotEqualTo(DebtRemediationFunction.createConstantPerIssue(Duration.create(6))); - - assertThat(function.hashCode()).isEqualTo(function.hashCode()); - assertThat(function.hashCode()).isEqualTo(functionWithSameValue.hashCode()); - assertThat(function.hashCode()).isNotEqualTo(functionWithDifferentType.hashCode()); - } - - @Test - public void test_to_string() throws Exception { - assertThat(DebtRemediationFunction.createLinearWithOffset(Duration.create(10), Duration.create(5)).toString()) - .isEqualTo("DebtRemediationFunction{type=LINEAR_OFFSET, coefficient=Duration[durationInMinutes=10], offset=Duration[durationInMinutes=5]}"); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/batch/debt/internal/DefaultDebtModelTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/batch/debt/internal/DefaultDebtModelTest.java deleted file mode 100644 index b74ae0b1777..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/batch/debt/internal/DefaultDebtModelTest.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.batch.debt.internal; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class DefaultDebtModelTest { - - DefaultDebtModel underTest = new DefaultDebtModel(); - - @Test - public void is_Deprecated() { - assertThat(underTest.characteristicByKey("xxx")).isNull(); - assertThat(underTest.characteristicById(1)).isNull(); - assertThat(underTest.characteristics()).isEmpty(); - assertThat(underTest.allCharacteristics()).isEmpty(); - assertThat(underTest.subCharacteristics("xxx")).isEmpty(); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/batch/sensor/issue/internal/DefaultIssueTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/batch/sensor/issue/internal/DefaultIssueTest.java index 7cde1f0cbb6..c70a91e92a5 100644 --- a/sonar-plugin-api/src/test/java/org/sonar/api/batch/sensor/issue/internal/DefaultIssueTest.java +++ b/sonar-plugin-api/src/test/java/org/sonar/api/batch/sensor/issue/internal/DefaultIssueTest.java @@ -97,12 +97,12 @@ public class DefaultIssueTest { .on(inputModule) .message("Wrong way!")) .forRule(RuleKey.of("repo", "rule")) - .effortToFix(10.0); + .gap(10.0); assertThat(issue.primaryLocation().inputComponent()).isEqualTo(inputModule); assertThat(issue.ruleKey()).isEqualTo(RuleKey.of("repo", "rule")); assertThat(issue.primaryLocation().textRange()).isNull(); - assertThat(issue.effortToFix()).isEqualTo(10.0); + assertThat(issue.gap()).isEqualTo(10.0); assertThat(issue.primaryLocation().message()).isEqualTo("Wrong way!"); issue.save(); diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/ce/measure/test/TestIssueTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/ce/measure/test/TestIssueTest.java index 88f840352f2..160849eb11c 100644 --- a/sonar-plugin-api/src/test/java/org/sonar/api/ce/measure/test/TestIssueTest.java +++ b/sonar-plugin-api/src/test/java/org/sonar/api/ce/measure/test/TestIssueTest.java @@ -43,7 +43,7 @@ public class TestIssueTest { .setSeverity(Severity.BLOCKER) .setStatus(org.sonar.api.issue.Issue.STATUS_RESOLVED) .setResolution(org.sonar.api.issue.Issue.RESOLUTION_FIXED) - .setDebt(Duration.create(10L)) + .setEffort(Duration.create(10L)) .setType(RuleType.BUG) .build(); @@ -52,7 +52,7 @@ public class TestIssueTest { assertThat(issue.severity()).isEqualTo(Severity.BLOCKER); assertThat(issue.status()).isEqualTo(org.sonar.api.issue.Issue.STATUS_RESOLVED); assertThat(issue.resolution()).isEqualTo(org.sonar.api.issue.Issue.RESOLUTION_FIXED); - assertThat(issue.debt()).isEqualTo(Duration.create(10L)); + assertThat(issue.effort()).isEqualTo(Duration.create(10L)); } @Test @@ -66,7 +66,7 @@ public class TestIssueTest { .build(); assertThat(issue.resolution()).isNull(); - assertThat(issue.debt()).isNull(); + assertThat(issue.effort()).isNull(); } @Test diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/ce/measure/test/TestMeasureComputerContextTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/ce/measure/test/TestMeasureComputerContextTest.java index 0ef6cb0ae39..49be30e2a7f 100644 --- a/sonar-plugin-api/src/test/java/org/sonar/api/ce/measure/test/TestMeasureComputerContextTest.java +++ b/sonar-plugin-api/src/test/java/org/sonar/api/ce/measure/test/TestMeasureComputerContextTest.java @@ -203,7 +203,7 @@ public class TestMeasureComputerContextTest { .setSeverity(Severity.BLOCKER) .setStatus(org.sonar.api.issue.Issue.STATUS_RESOLVED) .setResolution(org.sonar.api.issue.Issue.RESOLUTION_FIXED) - .setDebt(Duration.create(10L)) + .setEffort(Duration.create(10L)) .setType(RuleType.BUG) .build(); underTest.setIssues(Arrays.asList(issue)); diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/measures/AverageFormulaTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/measures/AverageFormulaTest.java deleted file mode 100644 index c3a4636b539..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/measures/AverageFormulaTest.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.measures; - -import org.junit.Test; - -public class AverageFormulaTest { - - AverageFormula underTest = new AverageFormula(); - - @Test(expected = UnsupportedOperationException.class) - public void fail_if_used_1() { - underTest.calculate(null, null); - } - - @Test(expected = UnsupportedOperationException.class) - public void fail_if_used_2() { - underTest.dependsUponMetrics(); - } - - @Test(expected = UnsupportedOperationException.class) - public void fail_if_used_3() { - underTest.setFallbackForMainMetric(null); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/measures/CountDistributionBuilderTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/measures/CountDistributionBuilderTest.java deleted file mode 100644 index bc691cc8c9d..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/measures/CountDistributionBuilderTest.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.measures; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class CountDistributionBuilderTest { - @Test - public void buildDistribution() { - CountDistributionBuilder builder = new CountDistributionBuilder(CoreMetrics.CLASS_COMPLEXITY_DISTRIBUTION); - Measure measure = builder - .add("foo") - .add("bar") - .add("foo") - .add("hello") - .build(); - - assertThat(measure.getData()).isEqualTo("bar=1;foo=2;hello=1"); - } - - @Test - public void addZeroValues() { - CountDistributionBuilder builder = new CountDistributionBuilder(CoreMetrics.CLASS_COMPLEXITY_DISTRIBUTION); - Measure measure = builder - .addZero("foo") - .add("bar") - .add("foo") - .addZero("hello") - .build(); - - assertThat(measure.getData()).isEqualTo("bar=1;foo=1;hello=0"); - } - - @Test - public void addDistributionMeasureAsStrings() { - Measure measureToAdd = mock(Measure.class); - when(measureToAdd.getData()).thenReturn("foo=3;hello=5;none=0"); - - CountDistributionBuilder builder = new CountDistributionBuilder(CoreMetrics.CLASS_COMPLEXITY_DISTRIBUTION); - Measure measure = builder - .add("bar") - .add("foo") - .add(measureToAdd) - .build(); - - assertThat(measure.getData()).isEqualTo("bar=1;foo=4;hello=5;none=0"); - } - - @Test - public void intervalsAreSorted() { - Measure measureToAdd = mock(Measure.class); - when(measureToAdd.getData()).thenReturn("10=5;3=2;1=3"); - - CountDistributionBuilder builder = new CountDistributionBuilder(CoreMetrics.CLASS_COMPLEXITY_DISTRIBUTION); - Measure measure = builder - .add(10) - .add(measureToAdd) - .add(1) - .build(); - - assertThat(measure.getData()).isEqualTo("1=4;3=2;10=6"); - } - -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/measures/CoverageMeasuresBuilderTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/measures/CoverageMeasuresBuilderTest.java deleted file mode 100644 index 71b018785b8..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/measures/CoverageMeasuresBuilderTest.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.measures; - -import org.junit.Test; - -import java.util.Collection; - -import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertThat; - -public class CoverageMeasuresBuilderTest { - - @Test - public void shouldNotCreateIfNoValues() { - CoverageMeasuresBuilder builder = CoverageMeasuresBuilder.create(); - assertThat(builder.createMeasures().size(), is(0)); - } - - @Test - public void shouldCreateHitsByLineData() { - CoverageMeasuresBuilder builder = CoverageMeasuresBuilder.create(); - builder.setHits(1, 0); - builder.setHits(2, 3); - builder.setHits(4, 2); - assertThat(find(builder.createMeasures(), CoreMetrics.COVERAGE_LINE_HITS_DATA_KEY).getData(), is("1=0;2=3;4=2")); - } - - @Test - public void shouldCreateUncoveredLines() { - CoverageMeasuresBuilder builder = CoverageMeasuresBuilder.create(); - builder.setHits(1, 0); - builder.setHits(2, 3); - builder.setHits(3, 0); - assertThat(find(builder.createMeasures(), CoreMetrics.UNCOVERED_LINES_KEY).getIntValue(), is(2)); - } - - @Test - public void shouldCreateConditionsByLineData() { - CoverageMeasuresBuilder builder = CoverageMeasuresBuilder.create(); - builder.setConditions(1, 2, 2); - builder.setConditions(2, 1, 0); - assertThat(find(builder.createMeasures(), CoreMetrics.CONDITIONS_BY_LINE_KEY).getData(), is("1=2;2=1")); - assertThat(find(builder.createMeasures(), CoreMetrics.COVERED_CONDITIONS_BY_LINE_KEY).getData(), is("1=2;2=0")); - } - - @Test - public void shouldCreateNumberOfConditionsToCover() { - CoverageMeasuresBuilder builder = CoverageMeasuresBuilder.create(); - builder.setConditions(1, 2, 2); - builder.setConditions(2, 1, 0); - assertThat(find(builder.createMeasures(), CoreMetrics.CONDITIONS_TO_COVER_KEY).getIntValue(), is(3)); - } - - @Test - public void shouldCreateNumberOfUncoveredConditions() { - CoverageMeasuresBuilder builder = CoverageMeasuresBuilder.create(); - builder.setConditions(1, 2, 2); - builder.setConditions(2, 1, 0); - builder.setConditions(3, 3, 1); - assertThat(find(builder.createMeasures(), CoreMetrics.UNCOVERED_CONDITIONS_KEY).getIntValue(), is(3)); - } - - @Test - public void shouldSetOnlyPositiveConditions() { - CoverageMeasuresBuilder builder = CoverageMeasuresBuilder.create(); - builder.setConditions(1, 0, 0); - builder.setConditions(2, 1, 0); - assertThat(find(builder.createMeasures(), CoreMetrics.CONDITIONS_BY_LINE_KEY).getData(), is("2=1")); - assertThat(find(builder.createMeasures(), CoreMetrics.COVERED_CONDITIONS_BY_LINE_KEY).getData(), is("2=0")); - } - - @Test - public void shouldIgnoreDuplicatedSetHits() { - CoverageMeasuresBuilder builder = CoverageMeasuresBuilder.create(); - builder.setHits(2, 3); - builder.setHits(2, 5);// to ignore - assertThat(builder.getLinesToCover(), is(1)); - assertThat(builder.getCoveredLines(), is(1)); - assertThat(builder.getHitsByLine().get(2), is(3)); - } - - @Test - public void shouldIgnoreDuplicatedSetConditions() { - CoverageMeasuresBuilder builder = CoverageMeasuresBuilder.create(); - builder.setConditions(1, 3, 2); - builder.setConditions(1, 1, 0);// to ignore - assertThat(builder.getConditions(), is(3)); - assertThat(builder.getCoveredConditions(), is(2)); - assertThat(builder.getConditionsByLine().get(1), is(3)); - assertThat(builder.getCoveredConditionsByLine().get(1), is(2)); - } - - - @Test - public void shouldResetFields() { - CoverageMeasuresBuilder builder = CoverageMeasuresBuilder.create(); - builder.setHits(1, 4); - builder.setConditions(1, 3, 1); - builder.reset(); - assertThat(builder.getConditions(), is(0)); - assertThat(builder.getCoveredConditions(), is(0)); - assertThat(builder.getCoveredLines(), is(0)); - assertThat(builder.getHitsByLine().size(), is(0)); - assertThat(builder.getConditionsByLine().size(), is(0)); - assertThat(builder.getCoveredConditionsByLine().size(), is(0)); - } - - private Measure find(Collection measures, String metricKey) { - for (Measure measure : measures) { - if (metricKey.equals(measure.getMetricKey())) { - return measure; - } - } - return null; - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/measures/MeanAggregationFormulaTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/measures/MeanAggregationFormulaTest.java deleted file mode 100644 index 24c797bff04..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/measures/MeanAggregationFormulaTest.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.measures; - -import org.junit.Test; - -public class MeanAggregationFormulaTest { - - MeanAggregationFormula underTest = new MeanAggregationFormula(); - - @Test(expected = UnsupportedOperationException.class) - public void fail_if_used_1() { - underTest.calculate(null, null); - } - - @Test(expected = UnsupportedOperationException.class) - public void fail_if_used_2() { - underTest.dependsUponMetrics(); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/measures/MeasureTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/measures/MeasureTest.java deleted file mode 100644 index ddf9e4ded72..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/measures/MeasureTest.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.measures; - -import org.apache.commons.lang.StringUtils; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.sonar.api.measures.Metric.ValueType; -import org.sonar.api.rules.Rule; -import org.sonar.api.rules.RulePriority; - -import static org.assertj.core.api.Assertions.assertThat; - -public class MeasureTest { - - @org.junit.Rule - public ExpectedException thrown = ExpectedException.none(); - - @Test - public void valueCanBeNull() { - Measure measure = new Measure("metric_key").setValue(null); - assertThat(measure.getValue()).isNull(); - } - - @Test - public void valueShouldNotBeNaN() { - thrown.expect(IllegalArgumentException.class); - new Measure("metric_key").setValue(Double.NaN); - } - - @Test - public void measureWithLevelValue() { - assertThat(new Measure(CoreMetrics.ALERT_STATUS, Metric.Level.ERROR).getData()).isEqualTo("ERROR"); - assertThat(new Measure(CoreMetrics.ALERT_STATUS, Metric.Level.ERROR).getDataAsLevel()).isEqualTo(Metric.Level.ERROR); - assertThat(new Measure(CoreMetrics.ALERT_STATUS).setData(Metric.Level.ERROR).getDataAsLevel()).isEqualTo(Metric.Level.ERROR); - } - - @Test - public void measureWithIntegerValue() { - assertThat(new Measure(CoreMetrics.LINES).setIntValue(3).getValue()).isEqualTo(3.0); - assertThat(new Measure(CoreMetrics.LINES).setIntValue(null).getValue()).isNull(); - - assertThat(new Measure(CoreMetrics.LINES).setIntValue(3).getIntValue()).isEqualTo(3); - assertThat(new Measure(CoreMetrics.LINES).setIntValue(null).getIntValue()).isNull(); - - assertThat(new Measure(CoreMetrics.LINES).setValue(3.6).getIntValue()).isEqualTo(3); - } - - /** - * Proper definition of equality for measures is important, because used to store them. - */ - @Test - public void equalsAndHashCode() { - Measure measure1 = new Measure(); - Measure measure2 = new Measure(); - - assertThat(measure1.equals(null)).isFalse(); - - // another class - assertThat(measure1.equals("")).isFalse(); - - // same instance - assertThat(measure1.equals(measure1)).isTrue(); - assertThat(measure1.hashCode()).isEqualTo(measure2.hashCode()); - - // same key - null - assertThat(measure1.equals(measure2)).isTrue(); - assertThat(measure2.equals(measure1)).isTrue(); - assertThat(measure1.hashCode()).isEqualTo(measure2.hashCode()); - - // different keys - measure1.setMetric(CoreMetrics.COVERAGE); - assertThat(measure1.equals(measure2)).isFalse(); - assertThat(measure2.equals(measure1)).isFalse(); - assertThat(measure1.hashCode()).isNotEqualTo(measure2.hashCode()); - - measure2.setMetric(CoreMetrics.LINES); - assertThat(measure1.equals(measure2)).isFalse(); - assertThat(measure2.equals(measure1)).isFalse(); - assertThat(measure1.hashCode()).isNotEqualTo(measure2.hashCode()); - - // same key - measure2.setMetric(CoreMetrics.COVERAGE); - assertThat(measure1.equals(measure2)).isTrue(); - assertThat(measure2.equals(measure1)).isTrue(); - assertThat(measure1.hashCode()).isEqualTo(measure2.hashCode()); - - // value doesn't matter - measure1.setValue(1.0); - measure2.setValue(2.0); - assertThat(measure1.equals(measure2)).isTrue(); - assertThat(measure2.equals(measure1)).isTrue(); - assertThat(measure1.hashCode()).isEqualTo(measure2.hashCode()); - } - - @Test - public void longDataForDataMetric() { - new Measure(CoreMetrics.COVERAGE_LINE_HITS_DATA, StringUtils.repeat("x", Measure.MAX_TEXT_SIZE + 1)); - } - - @Test - public void shouldGetAndSetVariations() { - Measure measure = new Measure(CoreMetrics.LINES).setVariation1(1d).setVariation2(2d).setVariation3(3d); - assertThat(measure.getVariation1()).isEqualTo(1d); - assertThat(measure.getVariation2()).isEqualTo(2d); - assertThat(measure.getVariation3()).isEqualTo(3d); - } - - @Test - public void shouldSetVariationsWithIndex() { - Measure measure = new Measure(CoreMetrics.LINES).setVariation(2, 3.3); - assertThat(measure.getVariation1()).isNull(); - assertThat(measure.getVariation2()).isEqualTo(3.3); - assertThat(measure.getVariation3()).isNull(); - } - - @Test - public void notEqualRuleMeasures() { - Measure measure = new Measure(CoreMetrics.VIOLATIONS, 30.0); - RuleMeasure ruleMeasure = new RuleMeasure(CoreMetrics.VIOLATIONS, new Rule("foo", "bar"), RulePriority.CRITICAL, 3); - assertThat(measure.equals(ruleMeasure)).isFalse(); - assertThat(ruleMeasure.equals(measure)).isFalse(); - } - - @Test - public void shouldUnsetData() { - String data = "1=10;21=456"; - Measure measure = new Measure(CoreMetrics.CONDITIONS_BY_LINE).setData(data); - assertThat(measure.hasData()).isTrue(); - assertThat(measure.getData()).isEqualTo(data); - - measure.unsetData(); - - assertThat(measure.hasData()).isFalse(); - assertThat(measure.getData()).isNull(); - } - - @Test - public void null_value_and_null_variations_should_be_considered_as_best_value() { - assertThat(new Measure(CoreMetrics.VIOLATIONS).setVariation1(0.0).isBestValue()).isTrue(); - assertThat(new Measure(CoreMetrics.VIOLATIONS).setVariation1(1.0).isBestValue()).isFalse(); - assertThat(new Measure(CoreMetrics.VIOLATIONS).setVariation2(1.0).isBestValue()).isFalse(); - assertThat(new Measure(CoreMetrics.VIOLATIONS).setVariation3(1.0).isBestValue()).isFalse(); - assertThat(new Measure(CoreMetrics.VIOLATIONS).setVariation4(1.0).isBestValue()).isFalse(); - assertThat(new Measure(CoreMetrics.VIOLATIONS).setVariation5(1.0).isBestValue()).isFalse(); - } - - @Test - public void testBooleanValue() { - assertThat(new Measure(new Metric.Builder("foo", "Sample boolean", ValueType.BOOL).create()).setValue(1.0).value()).isEqualTo(Boolean.TRUE); - assertThat(new Measure(new Metric.Builder("foo", "Sample boolean", ValueType.BOOL).create()).setValue(0.0).value()).isEqualTo(Boolean.FALSE); - } - -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/measures/MeasureUtilsTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/measures/MeasureUtilsTest.java deleted file mode 100644 index 4ef6cae36f7..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/measures/MeasureUtilsTest.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.measures; - -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class MeasureUtilsTest { - - @Test - public void getValue() { - assertThat(MeasureUtils.getValue(null, 3.0)).isEqualTo(3.0); - assertThat(MeasureUtils.getValue(new Measure(), 3.0)).isEqualTo(3.0); - assertThat(MeasureUtils.getValue(new Measure(CoreMetrics.LINES, 2.0), 3.0)).isEqualTo(2.0); - assertThat(MeasureUtils.getValue(new Measure(CoreMetrics.LINES, "data"), 3.0)).isEqualTo(3.0); - } - - @Test - public void sumNone() { - assertThat(MeasureUtils.sum(true)).isEqualTo(0d); - assertThat(MeasureUtils.sum(false)).isNull(); - } - - @Test - public void shouldNotFailIfDataMeasures() { - assertThat(MeasureUtils.sum(true, new Measure(CoreMetrics.ALERT_STATUS, "foo"), new Measure(CoreMetrics.LINES, 50.0))).isEqualTo(50d); - } - - @Test - public void sumNumericMeasures() { - assertThat(MeasureUtils.sum(true, new Measure(CoreMetrics.LINES, 80.0), new Measure(CoreMetrics.LINES, 50.0))).isEqualTo(130d); - assertThat(MeasureUtils.sum(true, Arrays.asList(new Measure(CoreMetrics.LINES, 80.0), new Measure(CoreMetrics.LINES, 50.0)))).isEqualTo(130d); - } - - @Test - public void sumNullMeasures() { - assertThat(MeasureUtils.sum(true)).isEqualTo(0.0); - assertThat(MeasureUtils.sum(true, (Collection) null)).isEqualTo(0.0); - assertThat(MeasureUtils.sum(false)).isNull(); - assertThat(MeasureUtils.sum(true, new Measure(CoreMetrics.LINES, 80.0), null, null, new Measure(CoreMetrics.LINES, 50.0))).isEqualTo(130d); - } - - @Test - public void hasValue() { - assertThat(MeasureUtils.hasValue(null)).isFalse(); - assertThat(MeasureUtils.hasValue(new Measure(CoreMetrics.CLASSES, (Double) null))).isFalse(); - assertThat(MeasureUtils.hasValue(new Measure(CoreMetrics.CLASSES, 3.2))).isTrue(); - } - - @Test - public void hasData() { - assertThat(MeasureUtils.hasData(null)).isFalse(); - assertThat(MeasureUtils.hasData(new Measure(CoreMetrics.CLASSES, 3.5))).isFalse(); - assertThat(MeasureUtils.hasData(new Measure(CoreMetrics.FUNCTION_COMPLEXITY_DISTRIBUTION, (String) null))).isFalse(); - assertThat(MeasureUtils.hasData(new Measure(CoreMetrics.FUNCTION_COMPLEXITY_DISTRIBUTION, ""))).isFalse(); - assertThat(MeasureUtils.hasData(new Measure(CoreMetrics.FUNCTION_COMPLEXITY_DISTRIBUTION, "1=10;2=20"))).isTrue(); - } - - @Test - public void shouldHaveValues() { - assertThat(MeasureUtils.haveValues()).isFalse(); - assertThat(MeasureUtils.haveValues(null, null)).isFalse(); - assertThat(MeasureUtils.haveValues(new Measure(CoreMetrics.CLASSES, (Double) null))).isFalse(); - assertThat(MeasureUtils.haveValues(new Measure(CoreMetrics.CLASSES, 3.2))).isTrue(); - assertThat(MeasureUtils.haveValues(new Measure(CoreMetrics.CLASSES, 3.2), new Measure(CoreMetrics.COMPLEXITY, "foo"))).isFalse(); - assertThat(MeasureUtils.haveValues(new Measure(CoreMetrics.CLASSES, 3.2), new Measure(CoreMetrics.COMPLEXITY, 2.5))).isTrue(); - } - - @Test - public void shouldGetVariation() { - assertThat(MeasureUtils.getVariation(null, 2, 3.14)).isEqualTo(3.14); - assertThat(MeasureUtils.getVariation(null, 2)).isNull(); - - assertThat(MeasureUtils.getVariation(new Measure(), 2, 3.14)).isEqualTo(3.14); - assertThat(MeasureUtils.getVariation(new Measure(), 2)).isNull(); - - assertThat(MeasureUtils.getVariation(new Measure().setVariation2(1.618), 2, 3.14)).isEqualTo(1.618); - } - - @Test - public void shouldGetVariationAsLong() { - assertThat(MeasureUtils.getVariationAsLong(null, 2, 3L)).isEqualTo(3L); - assertThat(MeasureUtils.getVariationAsLong(null, 2)).isNull(); - - assertThat(MeasureUtils.getVariationAsLong(new Measure(), 2, 3L)).isEqualTo(3L); - assertThat(MeasureUtils.getVariationAsLong(new Measure(), 2)).isNull(); - - assertThat(MeasureUtils.getVariationAsLong(new Measure().setVariation2(222.0), 2, 3L)).isEqualTo(222L); - } - - @Test - public void shouldSumOnVariation() { - Measure measure1 = new Measure(CoreMetrics.NEW_VIOLATIONS).setVariation1(1.0).setVariation2(1.0).setVariation3(3.0); - Measure measure2 = new Measure(CoreMetrics.NEW_VIOLATIONS).setVariation1(1.0).setVariation2(2.0).setVariation3(3.0); - List children = Arrays.asList(measure1, measure2); - - assertThat(MeasureUtils.sumOnVariation(true, 1, children)).isEqualTo(2d); - assertThat(MeasureUtils.sumOnVariation(true, 2, children)).isEqualTo(3d); - assertThat(MeasureUtils.sumOnVariation(true, 3, children)).isEqualTo(6d); - } - -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/measures/MeasuresFiltersTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/measures/MeasuresFiltersTest.java deleted file mode 100644 index 579a2cdd461..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/measures/MeasuresFiltersTest.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.measures; - -import org.junit.Test; -import org.sonar.api.rules.Rule; -import org.sonar.api.rules.RulePriority; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; - -import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertThat; - -public class MeasuresFiltersTest { - - @Test - public void metric() { - MeasuresFilter filter = MeasuresFilters.metric(CoreMetrics.VIOLATIONS); - - Collection measures = Arrays.asList( - RuleMeasure.createForPriority(CoreMetrics.VIOLATIONS, RulePriority.CRITICAL, 50.0), - new Measure(CoreMetrics.VIOLATIONS, 500.0)); - - assertThat(filter.filter(measures).getValue(), is(500.0)); - } - - @Test - public void all() { - Collection measures = Arrays.asList( - RuleMeasure.createForPriority(CoreMetrics.VIOLATIONS, RulePriority.CRITICAL, 50.0), - new Measure(CoreMetrics.VIOLATIONS, 500.0)); - - Iterator filteredMeasures = MeasuresFilters.all().filter(measures).iterator(); - filteredMeasures.next(); - filteredMeasures.next(); - assertThat(filteredMeasures.hasNext(), is(false)); - } - - @Test - public void rule() { - Rule rule1 = new Rule("pmd", "key1"); - Rule rule2 = new Rule("pmd", "key2"); - MeasuresFilter filter = MeasuresFilters.rule(CoreMetrics.VIOLATIONS, rule1); - List measures = Arrays.asList( - RuleMeasure.createForRule(CoreMetrics.VIOLATIONS, rule1, 50.0), - RuleMeasure.createForRule(CoreMetrics.VIOLATIONS, rule2, 10.0), - RuleMeasure.createForRule(CoreMetrics.INFO_VIOLATIONS, rule2, 3.3), - - RuleMeasure.createForPriority(CoreMetrics.VIOLATIONS, RulePriority.CRITICAL, 400.0), - RuleMeasure.createForPriority(CoreMetrics.COVERAGE, RulePriority.CRITICAL, 400.0), - new Measure(CoreMetrics.VIOLATIONS, 500.0)); - - assertThat(filter.filter(measures).getValue(), is(50.0)); - } - - @Test - public void rules() { - Rule rule1 = new Rule("pmd", "key1"); - Rule rule2 = new Rule("pmd", "key2"); - MeasuresFilter> filter = MeasuresFilters.rules(CoreMetrics.VIOLATIONS); - List measures = Arrays.asList( - RuleMeasure.createForRule(CoreMetrics.VIOLATIONS, rule1, 50.0), - RuleMeasure.createForRule(CoreMetrics.VIOLATIONS, rule2, 10.0), - RuleMeasure.createForRule(CoreMetrics.INFO_VIOLATIONS, rule2, 3.3), - - RuleMeasure.createForPriority(CoreMetrics.VIOLATIONS, RulePriority.CRITICAL, 400.0), - RuleMeasure.createForPriority(CoreMetrics.COVERAGE, RulePriority.CRITICAL, 400.0), - new Measure(CoreMetrics.VIOLATIONS, 500.0)); - - assertThat(filter.filter(measures).size(), is(2)); - } - - @Test - public void measure() { - MeasuresFilter filter = MeasuresFilters.measure(new Measure(CoreMetrics.VIOLATIONS)); - List measures = Arrays.asList( - new Measure(CoreMetrics.COMMENT_LINES, 50.0), - new Measure(CoreMetrics.VIOLATIONS, 10.0), - RuleMeasure.createForCategory(CoreMetrics.VIOLATIONS, 2, 12.0), - new Measure(CoreMetrics.COVERAGE, 15.0)); - - assertThat(filter.filter(measures).getValue(), is(10.0)); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/measures/MetricTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/measures/MetricTest.java index a0164124211..7bea6b4042b 100644 --- a/sonar-plugin-api/src/test/java/org/sonar/api/measures/MetricTest.java +++ b/sonar-plugin-api/src/test/java/org/sonar/api/measures/MetricTest.java @@ -51,7 +51,6 @@ public class MetricTest { assertThat(metric.getWorstValue()).isNull(); assertThat(metric.getDirection()).isEqualTo(Metric.DIRECTION_NONE); assertThat(metric.getEnabled()).isTrue(); - assertThat(metric.getFormula()).isNull(); assertThat(metric.getId()).isNull(); assertThat(metric.getUserManaged()).isFalse(); assertThat(metric.isHidden()).isFalse(); diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/measures/PropertiesBuilderTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/measures/PropertiesBuilderTest.java deleted file mode 100644 index 1937275d174..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/measures/PropertiesBuilderTest.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.measures; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class PropertiesBuilderTest { - @Test - public void buildMeasure() { - PropertiesBuilder builder = new PropertiesBuilder<>(CoreMetrics.CLASS_COMPLEXITY_DISTRIBUTION); - Measure measure = builder - .add(1, 30) - .add(2, 27) - .add(4, 50) - .build(); - assertThat(measure.getData()).isEqualTo("1=30;2=27;4=50"); - } - - @Test - public void sortKeys() { - PropertiesBuilder builder = new PropertiesBuilder<>(CoreMetrics.CLASS_COMPLEXITY_DISTRIBUTION); - Measure measure = builder - .add("foo", "fooooo") - .add("bar", "baaaaar") - .add("hello", "world") - .build(); - assertThat(measure.getData()).isEqualTo("bar=baaaaar;foo=fooooo;hello=world"); - } - - @Test - public void valueIsOptional() { - PropertiesBuilder builder = new PropertiesBuilder<>(CoreMetrics.CLASS_COMPLEXITY_DISTRIBUTION); - Measure measure = builder - .add("foo", null) - .add("bar", "bar") - .add("hello", "world") - .build(); - assertThat(measure.getData()).isEqualTo("bar=bar;foo=;hello=world"); - } - - @Test - public void clearBeforeBuildingOtherMeasure() { - PropertiesBuilder builder = new PropertiesBuilder<>(CoreMetrics.CLASS_COMPLEXITY_DISTRIBUTION); - builder - .add("foo", "foo") - .add("bar", "bar") - .add("hello", "world") - .build(); - - builder.clear(); - Measure measure = builder - .add("1", "1") - .add("2", "2") - .add("foo", "other") - .build(); - assertThat(measure.getData()).isEqualTo("1=1;2=2;foo=other"); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/measures/RangeDistributionBuilderTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/measures/RangeDistributionBuilderTest.java deleted file mode 100644 index 91b7e852aa8..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/measures/RangeDistributionBuilderTest.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.measures; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class RangeDistributionBuilderTest { - - @Test - public void workOnAnLimitsArrayCopy() { - Integer[] limits = new Integer[] {4, 2, 0}; - RangeDistributionBuilder builder = new RangeDistributionBuilder(CoreMetrics.CLASS_COMPLEXITY_DISTRIBUTION, limits); - builder.add(3.2).add(2.0).add(6.2).build(); - - assertThat(builder.getBottomLimits()).isNotSameAs(limits); - assertThat(limits[0]).isEqualTo(4); - assertThat(limits[1]).isEqualTo(2); - assertThat(limits[2]).isEqualTo(0); - } - - @Test - public void buildIntegerDistribution() { - RangeDistributionBuilder builder = new RangeDistributionBuilder(CoreMetrics.CLASS_COMPLEXITY_DISTRIBUTION, new Integer[] {0, 2, 4}); - Measure measure = builder - .add(3.2) - .add(2.0) - .add(6.2) - .build(); - - assertThat(measure.getData()).isEqualTo("0=0;2=2;4=1"); - } - - @Test - public void buildDoubleDistribution() { - RangeDistributionBuilder builder = new RangeDistributionBuilder(CoreMetrics.CLASS_COMPLEXITY_DISTRIBUTION, new Double[] {0.0, 2.0, 4.0}); - Measure measure = builder - .add(3.2) - .add(2.0) - .add(6.2) - .build(); - - assertThat(measure.getData()).isEqualTo("0=0;2=2;4=1"); - } - - @Test - public void valueLesserThanMinimumIsIgnored() { - RangeDistributionBuilder builder = new RangeDistributionBuilder(CoreMetrics.CLASS_COMPLEXITY_DISTRIBUTION, new Integer[] {0, 2, 4}); - Measure measure = builder - .add(3.2) - .add(2.0) - .add(-3.0) - .build(); - - assertThat(measure.getData()).isEqualTo("0=0;2=2;4=0"); - } - - @Test - public void addDistributionMeasureWithIdenticalLimits() { - Measure measureToAdd = mock(Measure.class); - when(measureToAdd.getData()).thenReturn("0=3;2=5"); - - RangeDistributionBuilder builder = new RangeDistributionBuilder(CoreMetrics.CLASS_COMPLEXITY_DISTRIBUTION, new Integer[] {0, 2}); - builder.clear(); - Measure measure = builder - .add(1) - .add(measureToAdd) - .build(); - - assertThat(measure.getData()).isEqualTo("0=4;2=5"); - } - - @Test - public void addDistributionMeasureWithDifferentIntLimits() { - Measure measureToAdd = mock(Measure.class); - when(measureToAdd.getData()).thenReturn("0=3;2=5"); - - RangeDistributionBuilder builder = new RangeDistributionBuilder(CoreMetrics.CLASS_COMPLEXITY_DISTRIBUTION, new Integer[] {0, 2, 4}); - builder.clear(); - Measure measure = builder - .add(1) - .add(measureToAdd) - .build(); - - assertThat(measure).isNull(); - } - - @Test - public void addDistributionMeasureWithDifferentDoubleLimits() { - Measure measureToAdd = mock(Measure.class); - when(measureToAdd.getData()).thenReturn("0.0=3;3.0=5;6.0=9"); - - RangeDistributionBuilder builder = new RangeDistributionBuilder(CoreMetrics.CLASS_COMPLEXITY_DISTRIBUTION, new Double[] {0.0, 2.0, 4.0}); - builder.clear(); - Measure measure = builder - .add(measureToAdd) - .build(); - - assertThat(measure).isNull(); - } - - @Test - public void initLimitsAtTheFirstAdd() { - Measure m1 = mock(Measure.class); - when(m1.getData()).thenReturn("0.5=3;3.5=5;6.5=9"); - - Measure m2 = mock(Measure.class); - when(m2.getData()).thenReturn("0.5=0;3.5=2;6.5=1"); - - RangeDistributionBuilder builder = new RangeDistributionBuilder(CoreMetrics.CLASS_COMPLEXITY_DISTRIBUTION); - builder.clear(); - Measure measure = builder - .add(m1) - .add(m2) - .build(); - - assertThat(measure.getData()).isEqualTo("0.5=3;3.5=7;6.5=10"); - } - - @Test - public void keepIntRangesWhenMergingDistributions() { - Measure m1 = mock(Measure.class); - when(m1.getData()).thenReturn("0=3;3=5;6=9"); - - Measure m2 = mock(Measure.class); - when(m2.getData()).thenReturn("0=0;3=2;6=1"); - - RangeDistributionBuilder builder = new RangeDistributionBuilder(CoreMetrics.CLASS_COMPLEXITY_DISTRIBUTION); - builder.clear(); - Measure measure = builder - .add(m1) - .add(m2) - .build(); - - assertThat(measure.getData()).isEqualTo("0=3;3=7;6=10"); - } - - @Test - public void nullIfEmptyData() { - RangeDistributionBuilder builder = new RangeDistributionBuilder(CoreMetrics.CLASS_COMPLEXITY_DISTRIBUTION, new Integer[] {0, 2, 4}); - - assertThat(builder.isEmpty()).isTrue(); - Measure measure = builder.build(false); - assertThat(measure).isNull(); - - measure = builder.build(true); - assertThat(measure.getData()).isEqualTo("0=0;2=0;4=0"); - } - - @Test - public void aggregateEmptyDistribution() { - RangeDistributionBuilder builder = new RangeDistributionBuilder(CoreMetrics.CLASS_COMPLEXITY_DISTRIBUTION); - builder.add(new Measure(CoreMetrics.CLASS_COMPLEXITY_DISTRIBUTION, (String) null)); - Measure distribution = builder.build(); - assertThat(distribution.getData()).isEmpty(); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/measures/RuleMeasureTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/measures/RuleMeasureTest.java deleted file mode 100644 index afd6c088312..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/measures/RuleMeasureTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.measures; - -import org.junit.Test; -import org.sonar.api.rules.Rule; -import org.sonar.api.rules.RulePriority; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; - -public class RuleMeasureTest { - - @Test - public void shouldEquals() { - assertEquals( - RuleMeasure.createForPriority(CoreMetrics.CLASSES, RulePriority.CRITICAL, 4.5), - RuleMeasure.createForPriority(CoreMetrics.CLASSES, RulePriority.CRITICAL, 3.4)); - - assertEquals( - RuleMeasure.createForRule(CoreMetrics.CLASSES, new Rule("pmd", "abc1"), 4.5), - RuleMeasure.createForRule(CoreMetrics.CLASSES, new Rule("pmd", "abc1"), 3.4)); - - } - - @Test - public void shouldNotEquals() { - assertNotEquals( - RuleMeasure.createForRule(CoreMetrics.BLOCKER_VIOLATIONS, new Rule("pmd", "abc1"), 4.5), - RuleMeasure.createForRule(CoreMetrics.BLOCKER_VIOLATIONS, new Rule("pmd", "def2"), 3.4)); - - assertNotEquals( - RuleMeasure.createForRule(CoreMetrics.INFO_VIOLATIONS, new Rule("pmd", "abc1"), 4.5), - RuleMeasure.createForRule(CoreMetrics.BLOCKER_VIOLATIONS, new Rule("pmd", "abc1"), 3.4)); - } - - private void assertNotEquals(RuleMeasure rm1, RuleMeasure rm2) { - assertFalse(rm1.equals(rm2)); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/measures/SumChildDistributionFormulaTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/measures/SumChildDistributionFormulaTest.java deleted file mode 100644 index 6997373ac3f..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/measures/SumChildDistributionFormulaTest.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.measures; - -import org.junit.Test; - -public class SumChildDistributionFormulaTest { - - SumChildDistributionFormula underTest = new SumChildDistributionFormula(); - - @Test(expected = UnsupportedOperationException.class) - public void fail_if_used_1() { - underTest.calculate(null, null); - } - - @Test(expected = UnsupportedOperationException.class) - public void fail_if_used_2() { - underTest.dependsUponMetrics(); - } - - @Test(expected = UnsupportedOperationException.class) - public void fail_if_used_3() { - underTest.getMinimumScopeToPersist(); - } - - @Test(expected = UnsupportedOperationException.class) - public void fail_if_used_4() { - underTest.setMinimumScopeToPersist(null); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/measures/WeightedMeanAggregationFormulaTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/measures/WeightedMeanAggregationFormulaTest.java deleted file mode 100644 index 081159dad87..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/measures/WeightedMeanAggregationFormulaTest.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.measures; - -import org.junit.Test; - -public class WeightedMeanAggregationFormulaTest { - WeightedMeanAggregationFormula underTest = new WeightedMeanAggregationFormula(null, false); - - @Test(expected = UnsupportedOperationException.class) - public void fail_if_used_1() { - underTest.calculate(null, null); - } - - @Test(expected = UnsupportedOperationException.class) - public void fail_if_used_2() { - underTest.dependsUponMetrics(); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/resources/DirectoryTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/resources/DirectoryTest.java deleted file mode 100644 index 9585861844f..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/resources/DirectoryTest.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.resources; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; - -import java.io.IOException; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class DirectoryTest { - - @Rule - public TemporaryFolder temp = new TemporaryFolder(); - - @Test - public void createFromIoFileShouldComputeCorrectKey() throws IOException { - java.io.File baseDir = temp.newFolder(); - Project project = mock(Project.class); - when(project.getBaseDir()).thenReturn(baseDir); - Resource dir = Directory.fromIOFile(new java.io.File(baseDir, "src/foo/bar/"), project); - assertThat(dir.getKey()).isEqualTo("src/foo/bar"); - } - - @Test - 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 = Directory.create(" foo\\bar\\ "); - assertThat(dir.getKey()).isEqualTo("foo/bar"); - } - - @Test - public void directoryHasNoParents() { - Resource dir = Directory.create("foo/bar"); - assertThat(dir.getParent()).isNull(); - } - - @Test - public void shouldHaveOnlyOneLevelOfDirectory() { - assertThat(Directory.create("one/two/third").getParent()).isNull(); - assertThat(Directory.create("one").getParent()).isNull(); - } - - @Test - public void parseDirectoryKey() { - assertThat(Directory.parseKey("/foo/bar")).isEqualTo("foo/bar"); - } - - @Test - public void matchExclusionPatterns() { - 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*/**")).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(); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/resources/FileTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/resources/FileTest.java deleted file mode 100644 index 91d4b6036a6..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/resources/FileTest.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.resources; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class FileTest { - - @Test - public void trimKeyAndName() { - 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", 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", null, false); - assertThat(file.getKey()).isEqualTo("toto.sql"); - assertThat(file.getName()).isEqualTo("toto.sql"); - assertThat(file.getParent().getKey()).isEqualTo("/"); - } - - @Test - public void setLanguage() { - Language lang = new AbstractLanguage("java", "Java") { - - @Override - public String[] getFileSuffixes() { - return null; - } - }; - - 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()).isNull(); - } - - @Test - public void matchAntPatterns() { - 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(); - assertThat(file.matchFilePattern("other*/**")).isFalse(); - - assertThat(file.matchFilePattern("/src/one*/**/*.sql")).isTrue(); - assertThat(file.matchFilePattern("/src/one/t?o/**/*")).isTrue(); - assertThat(file.matchFilePattern("**/*")).isTrue(); - assertThat(file.matchFilePattern("src/one/two/*")).isTrue(); - assertThat(file.matchFilePattern("/src/one/two/*")).isTrue(); - assertThat(file.matchFilePattern("src/**")).isTrue(); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/resources/LibraryTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/resources/LibraryTest.java deleted file mode 100644 index 6864eb2a377..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/resources/LibraryTest.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.resources; - -import org.junit.Test; - -import static junit.framework.Assert.assertFalse; -import static junit.framework.Assert.assertTrue; -import static org.hamcrest.core.Is.is; -import static org.hamcrest.core.IsNot.not; -import static org.junit.Assert.assertThat; - -public class LibraryTest { - - @Test - public void equalsOnKeyAndVersion() { - assertTrue(new Library("commons-lang", "1.1").equals(new Library("commons-lang", "1.1"))); - assertFalse(new Library("commons-lang", "1.1").equals(new Library("commons-lang", "1.0"))); - } - - @Test - public void testHashCode() { - assertThat(new Library("commons-lang", "1.1").hashCode(), is(new Library("commons-lang", "1.1").hashCode())); - assertThat(new Library("commons-lang", "1.1").hashCode(), not(is(new Library("commons-lang", "1.0").hashCode()))); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/resources/ProjectTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/resources/ProjectTest.java deleted file mode 100644 index d27e8db5faa..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/resources/ProjectTest.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.resources; - -import org.junit.Test; -import org.sonar.api.CoreProperties; -import org.sonar.api.batch.bootstrap.ProjectDefinition; - -import static org.assertj.core.api.Assertions.assertThat; - -public class ProjectTest { - @Test - public void effectiveKeyShouldEqualKeyWithBranch() { - - ProjectDefinition definition = ProjectDefinition.create() - .setKey("mykey") - .setProperty(CoreProperties.PROJECT_BRANCH_PROPERTY, "branch"); - assertThat(new Project(definition).getEffectiveKey()).isEqualTo("mykey:branch"); - assertThat(new Project(definition).getKey()).isEqualTo("mykey"); - } - - @Test - public void setNameWithBranch() { - ProjectDefinition definition = ProjectDefinition.create() - .setProperty(CoreProperties.PROJECT_BRANCH_PROPERTY, "branch") - .setKey("key") - .setName("name"); - Project project = new Project(definition); - assertThat(project.getName()).isEqualTo("name branch"); - assertThat(project.getOriginalName()).isEqualTo("name branch"); - } - - @Test - public void setNameWithoutBranch() { - ProjectDefinition definition = ProjectDefinition.create() - .setKey("key") - .setName("name"); - Project project = new Project(definition); - assertThat(project.getName()).isEqualTo("name"); - assertThat(project.getOriginalName()).isEqualTo("name"); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/resources/QualifiersTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/resources/QualifiersTest.java deleted file mode 100644 index d57e05ace23..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/resources/QualifiersTest.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.resources; - -import org.junit.Test; -import org.sonar.api.batch.bootstrap.ProjectDefinition; - -import static org.assertj.core.api.Assertions.assertThat; - -public class QualifiersTest { - - @Test - public void testRootView() { - View root = View.createRootView(); - assertThat(Qualifiers.isView(root, true)).isTrue(); - assertThat(Qualifiers.isView(root, false)).isTrue(); - assertThat(Qualifiers.isProject(root, true)).isFalse(); - assertThat(Qualifiers.isProject(root, false)).isFalse(); - } - - @Test - public void application() { - View root = View.createRootApp(); - assertThat(Qualifiers.isView(root, true)).isFalse(); - assertThat(Qualifiers.isView(root, false)).isFalse(); - assertThat(Qualifiers.isProject(root, true)).isFalse(); - assertThat(Qualifiers.isProject(root, false)).isFalse(); - } - - @Test - public void testSubView() { - View subview = View.createSubView(); - assertThat(Qualifiers.isView(subview, true)).isTrue(); - assertThat(Qualifiers.isView(subview, false)).isFalse(); - assertThat(Qualifiers.isProject(subview, true)).isFalse(); - assertThat(Qualifiers.isProject(subview, false)).isFalse(); - } - - @Test - public void testProject() { - ProjectDefinition rootDef = ProjectDefinition.create(); - ProjectDefinition moduleDef = ProjectDefinition.create(); - rootDef.addSubProject(moduleDef); - Resource root = new Project(rootDef); - assertThat(Qualifiers.isView(root, true)).isFalse(); - assertThat(Qualifiers.isView(root, false)).isFalse(); - assertThat(Qualifiers.isProject(root, true)).isTrue(); - assertThat(Qualifiers.isProject(root, false)).isTrue(); - } - - @Test - public void testModule() { - ProjectDefinition rootDef = ProjectDefinition.create(); - ProjectDefinition moduleDef = ProjectDefinition.create(); - rootDef.addSubProject(moduleDef); - Resource sub = new Project(moduleDef); - assertThat(Qualifiers.isView(sub, true)).isFalse(); - assertThat(Qualifiers.isView(sub, false)).isFalse(); - assertThat(Qualifiers.isProject(sub, true)).isTrue(); - assertThat(Qualifiers.isProject(sub, false)).isFalse(); - } - - private static class View extends Resource { - - private String qualifier; - - private View(String qualifier) { - this.qualifier = qualifier; - } - - static View createRootView() { - return new View(Qualifiers.VIEW); - } - - static View createRootApp() { - return new View(Qualifiers.APP); - } - - static View createSubView() { - return new View(Qualifiers.SUBVIEW); - } - - @Override - public String getName() { - return null; - } - - @Override - public String getLongName() { - return null; - } - - @Override - public String getDescription() { - return null; - } - - @Override - public Language getLanguage() { - return null; - } - - @Override - public String getScope() { - return Scopes.PROJECT; - } - - @Override - public String getQualifier() { - return qualifier; - } - - @Override - public Resource getParent() { - return null; - } - - @Override - public boolean matchFilePattern(String antPattern) { - return false; - } - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/resources/ResourceUtilsTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/resources/ResourceUtilsTest.java deleted file mode 100644 index 16c4dbb61f3..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/resources/ResourceUtilsTest.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.resources; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class ResourceUtilsTest { - - @Test - public void checkFile() { - File file = File.create("hello.Foo"); - assertThat(ResourceUtils.isModuleProject(file)).isFalse(); - assertThat(ResourceUtils.isSpace(file)).isFalse(); - assertThat(ResourceUtils.isEntity(file)).isTrue(); - assertThat(ResourceUtils.isSet(file)).isFalse(); - assertThat(ResourceUtils.isRootProject(file)).isFalse(); - assertThat(ResourceUtils.isUnitTestClass(file)).isFalse(); - } - - @Test - public void checkUnitTest() { - File utFile = File.create("hello.Foo"); - utFile.setQualifier(Qualifiers.UNIT_TEST_FILE); - assertThat(ResourceUtils.isModuleProject(utFile)).isFalse(); - assertThat(ResourceUtils.isSpace(utFile)).isFalse(); - assertThat(ResourceUtils.isEntity(utFile)).isTrue(); - assertThat(ResourceUtils.isSet(utFile)).isFalse(); - assertThat(ResourceUtils.isRootProject(utFile)).isFalse(); - assertThat(ResourceUtils.isUnitTestClass(utFile)).isTrue(); - } - - @Test - public void checkDirectory() { - Directory dir = Directory.create("hello"); - assertThat(ResourceUtils.isModuleProject(dir)).isFalse(); - assertThat(ResourceUtils.isSpace(dir)).isTrue(); - assertThat(ResourceUtils.isEntity(dir)).isFalse(); - assertThat(ResourceUtils.isSet(dir)).isFalse(); - assertThat(ResourceUtils.isRootProject(dir)).isFalse(); - assertThat(ResourceUtils.isUnitTestClass(dir)).isFalse(); - } - - @Test - public void shouldBePersistable() { - assertThat(ResourceUtils.isPersistable(File.create("Foo.java"))).isTrue(); - assertThat(ResourceUtils.isPersistable(Directory.create("bar/Foo.java"))).isTrue(); - } - - @Test - public void shouldNotBePersistable() { - Resource javaClass = mock(Resource.class); - when(javaClass.getScope()).thenReturn(Scopes.PROGRAM_UNIT); - Resource javaMethod = mock(Resource.class); - when(javaMethod.getScope()).thenReturn(Scopes.BLOCK_UNIT); - - assertThat(ResourceUtils.isPersistable(javaClass)).isFalse(); - assertThat(ResourceUtils.isPersistable(javaMethod)).isFalse(); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/resources/ScopesTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/resources/ScopesTest.java deleted file mode 100644 index 44e060d7018..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/resources/ScopesTest.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.resources; - -import org.junit.Test; -import org.sonar.api.batch.bootstrap.ProjectDefinition; - -import static org.assertj.core.api.Assertions.assertThat; - -public class ScopesTest { - - @Test - public void testProject() { - Project resource = new Project(ProjectDefinition.create()); - assertThat(Scopes.isProject(resource)).isTrue(); - assertThat(Scopes.isDirectory(resource)).isFalse(); - assertThat(Scopes.isFile(resource)).isFalse(); - assertThat(Scopes.isBlockUnit(resource)).isFalse(); - assertThat(Scopes.isProgramUnit(resource)).isFalse(); - } - - @Test - public void testDirectory() { - Resource resource = Directory.create("org/foo"); - assertThat(Scopes.isProject(resource)).isFalse(); - assertThat(Scopes.isDirectory(resource)).isTrue(); - assertThat(Scopes.isFile(resource)).isFalse(); - assertThat(Scopes.isBlockUnit(resource)).isFalse(); - assertThat(Scopes.isProgramUnit(resource)).isFalse(); - } - - @Test - public void testFile() { - Resource resource = File.create("org/foo/Bar.java"); - assertThat(Scopes.isProject(resource)).isFalse(); - assertThat(Scopes.isDirectory(resource)).isFalse(); - assertThat(Scopes.isFile(resource)).isTrue(); - assertThat(Scopes.isBlockUnit(resource)).isFalse(); - assertThat(Scopes.isProgramUnit(resource)).isFalse(); - } - - @Test - public void shouldBeHigherThan() { - assertThat(Scopes.isHigherThan(Scopes.PROJECT, Scopes.PROJECT)).isFalse(); - assertThat(Scopes.isHigherThan(Scopes.PROJECT, Scopes.DIRECTORY)).isTrue(); - assertThat(Scopes.isHigherThan(Scopes.PROJECT, Scopes.BLOCK_UNIT)).isTrue(); - - assertThat(Scopes.isHigherThan(Scopes.FILE, Scopes.FILE)).isFalse(); - assertThat(Scopes.isHigherThan(Scopes.FILE, Scopes.DIRECTORY)).isFalse(); - assertThat(Scopes.isHigherThan(Scopes.FILE, Scopes.BLOCK_UNIT)).isTrue(); - } - - @Test - public void shouldBeHigherThanOrEquals() { - assertThat(Scopes.isHigherThanOrEquals(Scopes.PROJECT, Scopes.PROJECT)).isTrue(); - assertThat(Scopes.isHigherThanOrEquals(Scopes.PROJECT, Scopes.DIRECTORY)).isTrue(); - assertThat(Scopes.isHigherThanOrEquals(Scopes.PROJECT, Scopes.BLOCK_UNIT)).isTrue(); - - assertThat(Scopes.isHigherThanOrEquals(Scopes.FILE, Scopes.FILE)).isTrue(); - assertThat(Scopes.isHigherThanOrEquals(Scopes.FILE, Scopes.DIRECTORY)).isFalse(); - assertThat(Scopes.isHigherThanOrEquals(Scopes.FILE, Scopes.BLOCK_UNIT)).isTrue(); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/test/IsMeasure.java b/sonar-plugin-api/src/test/java/org/sonar/api/test/IsMeasure.java deleted file mode 100644 index 7f73103808c..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/test/IsMeasure.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.test; - -import org.apache.commons.lang.ObjectUtils; -import org.apache.commons.lang.math.NumberUtils; -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; -import org.sonar.api.measures.Measure; -import org.sonar.api.measures.Metric; - -public class IsMeasure extends BaseMatcher { - - private Metric metric = null; - private Double value = null; - private String data = null; - private String mismatchTxt; - - public IsMeasure(Metric metric, Double value, String data) { - this.metric = metric; - this.value = value; - this.data = data; - } - - public IsMeasure(Metric metric) { - this.metric = metric; - } - - public IsMeasure(Metric metric, Double value) { - this.metric = metric; - this.value = value; - } - - public IsMeasure(Metric metric, String data) { - this.metric = metric; - this.data = data; - } - - public boolean matches(Object o) { - Measure m = (Measure) o; - if (metric != null && !ObjectUtils.equals(metric, m.getMetric())) { - mismatchTxt = "metric: " + metric.getKey(); - return false; - } - - if (value != null && NumberUtils.compare(value, m.getValue()) != 0) { - mismatchTxt = "value: " + value; - return false; - } - - if (data != null && !ObjectUtils.equals(data, m.getData())) { - mismatchTxt = "data: " + data; - return false; - } - return true; - } - - public void describeTo(Description description) { - description.appendText(mismatchTxt); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/StaxParserTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/StaxParserTest.java deleted file mode 100644 index 2c995443c8c..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/StaxParserTest.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.utils; - -import org.codehaus.staxmate.in.SMHierarchicCursor; -import org.junit.Test; -import org.sonar.api.utils.StaxParser.XmlStreamHandler; - -import javax.xml.stream.XMLStreamException; - -public class StaxParserTest { - - @Test - public void testXMLWithDTD() throws XMLStreamException { - StaxParser parser = new StaxParser(getTestHandler()); - parser.parse(getClass().getClassLoader().getResourceAsStream("org/sonar/api/utils/StaxParserTest/xml-dtd-test.xml")); - } - - @Test - public void testXMLWithXSD() throws XMLStreamException { - StaxParser parser = new StaxParser(getTestHandler()); - parser.parse(getClass().getClassLoader().getResourceAsStream("org/sonar/api/utils/StaxParserTest/xml-xsd-test.xml")); - } - - private XmlStreamHandler getTestHandler() { - return new XmlStreamHandler() { - public void stream(SMHierarchicCursor rootCursor) throws XMLStreamException { - rootCursor.advance(); - while (rootCursor.getNext() != null) { - } - } - }; - } - -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/TempFileUtilsTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/TempFileUtilsTest.java deleted file mode 100644 index 837407e8e64..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/TempFileUtilsTest.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.utils; - -import org.apache.commons.io.FileUtils; -import org.junit.Test; - -import java.io.File; -import java.io.IOException; - -import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertThat; - -public class TempFileUtilsTest { - - @Test - public void createTempDirectory() throws IOException { - - File dir = TempFileUtils.createTempDirectory(); - try { - assertThat(dir.exists(), is(true)); - assertThat(dir.isDirectory(), is(true)); - assertThat(dir.listFiles().length, is(0)); - - } finally { - FileUtils.deleteDirectory(dir); - } - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/TimeProfilerTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/TimeProfilerTest.java deleted file mode 100644 index 37305706239..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/TimeProfilerTest.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.utils; - -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; - -import static org.mockito.Mockito.*; - -public class TimeProfilerTest { - - private Logger logger; - - @Before - public void before() { - logger = mock(Logger.class); - } - - @Test - public void testBasicProfiling() { - TimeProfiler profiler = new TimeProfiler(logger); - profiler.start("Cycle analysis"); - verify(logger).info(eq("{}..."), eq("Cycle analysis")); - - profiler.stop(); - verify(logger).info(eq("{} done: {} ms"), eq("Cycle analysis"), anyLong()); - } - - @Test - public void stopOnce() { - TimeProfiler profiler = new TimeProfiler(logger); - - profiler.start("Cycle analysis"); - profiler.stop(); - profiler.stop(); - profiler.stop(); - verify(logger, times(1)).info(anyString(), anyString()); // start() executes log() with 1 parameter - verify(logger, times(1)).info(anyString(), anyString(), anyLong()); // stop() executes log() with 3 parameters - } - - @Test - public void doNotLogNeverEndedTask() { - TimeProfiler profiler = new TimeProfiler(logger); - - profiler.start("Cycle analysis"); - profiler.start("New task"); - profiler.stop(); - profiler.stop(); - verify(logger, never()).info(eq("{} done: {} ms"), eq("Cycle analysis"), anyLong()); - verify(logger, times(1)).info(eq("{} done: {} ms"), eq("New task"), anyLong()); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/WorkUnitTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/WorkUnitTest.java deleted file mode 100644 index 6fa3b2fee0e..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/WorkUnitTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.utils; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class WorkUnitTest { - - @Test - public void create() { - WorkUnit workUnit = WorkUnit.create(2.0, "mn"); - assertThat(workUnit.getUnit()).isEqualTo("mn"); - assertThat(workUnit.getValue()).isEqualTo(2.0); - } - - @Test - public void create_default() { - WorkUnit workUnit = WorkUnit.create(); - assertThat(workUnit.getUnit()).isEqualTo("d"); - assertThat(workUnit.getValue()).isEqualTo(0.0); - } - - @Test - public void test_equals() throws Exception { - assertThat(WorkUnit.create(2.0, "mn")).isEqualTo(WorkUnit.create(2.0, "mn")); - assertThat(WorkUnit.create(3.0, "mn")).isNotEqualTo(WorkUnit.create(2.0, "mn")); - assertThat(WorkUnit.create(2.0, "h")).isNotEqualTo(WorkUnit.create(2.0, "mn")); - } - - @Test - public void fail_with_bad_unit() { - try { - WorkUnit.create(2.0, "z"); - } catch (Exception e) { - assertThat(e).isInstanceOf(IllegalArgumentException.class); - } - } - - @Test - public void fail_with_bad_value() { - try { - WorkUnit.create(-2.0, "mn"); - } catch (Exception e) { - assertThat(e).isInstanceOf(IllegalArgumentException.class); - } - } - -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/XpathParserTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/XpathParserTest.java deleted file mode 100644 index 862a854ee98..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/XpathParserTest.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.api.utils; - -import org.apache.commons.io.IOUtils; -import org.junit.Test; - -import java.io.InputStream; - -import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertThat; - -public class XpathParserTest { - - @Test - public void parseXml() { - InputStream xml = getClass().getResourceAsStream("/org/sonar/api/utils/XpathParserTest/sample.xml"); - try { - XpathParser parser = new XpathParser(); - parser.parse(xml); - assertThat(parser.getRoot().getNodeName(), is("samples")); - assertThat(parser.getChildElements("sample").size(), is(2)); - assertThat(parser.getChildElements("sample").get(0).getAttribute("name"), is("one")); - assertThat(parser.getChildElements("sample").get(1).getAttribute("name"), is("two")); - - } finally { - IOUtils.closeQuietly(xml); - } - } - - @Test(expected=XmlParserException.class) - public void unvalidXml() { - InputStream xml = getClass().getResourceAsStream("/org/sonar/api/utils/XpathParserTest/unvalid.xml"); - try { - XpathParser parser = new XpathParser(); - parser.parse(xml); - - } finally { - IOUtils.closeQuietly(xml); - } - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/LoggersTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/LoggersTest.java index 4619c4125a6..87ffbdb095d 100644 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/LoggersTest.java +++ b/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/LoggersTest.java @@ -20,7 +20,7 @@ package org.sonar.api.utils.log; import org.junit.Test; -import org.sonar.api.SonarPlugin; +import org.sonar.api.Plugin; import static org.assertj.core.api.Assertions.assertThat; @@ -32,6 +32,6 @@ public class LoggersTest { assertThat(Loggers.getFactory()).isInstanceOf(LogbackLoggers.class); assertThat(Loggers.get("foo")).isInstanceOf(LogbackLogger.class); - assertThat(Loggers.get(SonarPlugin.class)).isInstanceOf(LogbackLogger.class); + assertThat(Loggers.get(Plugin.class)).isInstanceOf(LogbackLogger.class); } } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/batch/bootstrapper/LoggingConfiguration.java b/sonar-scanner-engine/src/main/java/org/sonar/batch/bootstrapper/LoggingConfiguration.java index 081cc152c5e..41b1bac7f56 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/batch/bootstrapper/LoggingConfiguration.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/batch/bootstrapper/LoggingConfiguration.java @@ -66,13 +66,11 @@ public final class LoggingConfiguration { } public LoggingConfiguration setProperties(Map properties) { - setShowSql(properties, null); setVerbose(properties, null); return this; } public LoggingConfiguration setProperties(Map properties, @Nullable Map fallback) { - setShowSql(properties, fallback); setVerbose(properties, fallback); return this; } @@ -117,22 +115,6 @@ public final class LoggingConfiguration { return addSubstitutionVariable(PROPERTY_ROOT_LOGGER_LEVEL, level); } - /** - * @deprecated since 5.2 there is no more db access from scanner side - */ - @Deprecated - public LoggingConfiguration setShowSql(boolean showSql) { - return this; - } - - /** - * @deprecated since 5.2 there is no more db access from scanner side - */ - @Deprecated - public LoggingConfiguration setShowSql(Map properties, @Nullable Map fallback) { - return this; - } - @VisibleForTesting LoggingConfiguration setFormat(String format) { return addSubstitutionVariable(PROPERTY_FORMAT, StringUtils.defaultIfBlank(format, FORMAT_DEFAULT)); diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/DefaultFileLinesContext.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/DefaultFileLinesContext.java index 021514056d1..b71a4adbebd 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/DefaultFileLinesContext.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/DefaultFileLinesContext.java @@ -70,7 +70,6 @@ public class DefaultFileLinesContext implements FileLinesContext { Preconditions.checkArgument(line <= inputFile.lines(), "Line %s is out of range for file %s. File has %s lines.", line, inputFile, inputFile.lines()); } - @Override public Integer getIntValue(String metricKey, int line) { Preconditions.checkNotNull(metricKey); checkLineRange(line); @@ -87,7 +86,6 @@ public class DefaultFileLinesContext implements FileLinesContext { setValue(metricKey, line, value); } - @Override public String getStringValue(String metricKey, int line) { Preconditions.checkNotNull(metricKey); checkLineRange(line); @@ -122,7 +120,7 @@ public class DefaultFileLinesContext implements FileLinesContext { if (CoreMetrics.NCLOC_DATA_KEY.equals(metricKey) || CoreMetrics.COMMENT_LINES_DATA_KEY.equals(metricKey) || CoreMetrics.EXECUTABLE_LINES_DATA_KEY.equals(metricKey)) { return lines.entrySet().stream() .filter(entry -> !entry.getValue().equals(0)) - .collect(toMap(Entry::getKey, Entry::getValue)); + .collect(toMap(Entry::getKey, Entry::getValue)); } return lines; } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/DefaultFileLinesContextFactory.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/DefaultFileLinesContextFactory.java index 97ed8f9d69d..157efee502a 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/DefaultFileLinesContextFactory.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/DefaultFileLinesContextFactory.java @@ -20,9 +20,9 @@ package org.sonar.scanner; import javax.annotation.concurrent.Immutable; -import org.sonar.api.batch.SensorContext; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.measure.MetricFinder; +import org.sonar.api.batch.sensor.SensorContext; import org.sonar.api.measures.FileLinesContext; import org.sonar.api.measures.FileLinesContextFactory; import org.sonar.scanner.scan.measure.MeasureCache; diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/BatchComponents.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/BatchComponents.java index 9331e3cf5f8..9e1087f9519 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/BatchComponents.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/BatchComponents.java @@ -25,7 +25,6 @@ import java.util.List; import org.sonar.core.component.DefaultResourceTypes; import org.sonar.core.config.CorePropertyDefinitions; import org.sonar.core.issue.tracking.Tracker; -import org.sonar.scanner.cpd.CpdComponents; import org.sonar.scanner.externalissue.ExternalIssuesImportSensor; import org.sonar.scanner.genericcoverage.GenericCoverageSensor; import org.sonar.scanner.genericcoverage.GenericTestExecutionSensor; @@ -65,9 +64,6 @@ public class BatchComponents { components.add(ZeroCoverageSensor.class); - // CPD - components.addAll(CpdComponents.all()); - // Generic coverage components.add(GenericCoverageSensor.class); components.addAll(GenericCoverageSensor.properties()); diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/ExtensionUtils.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/ExtensionUtils.java index 64f9db336df..0dc53079c22 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/ExtensionUtils.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/ExtensionUtils.java @@ -19,7 +19,6 @@ */ package org.sonar.scanner.bootstrap; -import org.sonar.api.batch.BatchSide; import org.sonar.api.batch.InstantiationStrategy; import org.sonar.api.batch.ScannerSide; import org.sonar.api.utils.AnnotationUtils; @@ -39,8 +38,7 @@ public class ExtensionUtils { } public static boolean isScannerSide(Object extension) { - return AnnotationUtils.getAnnotation(extension, BatchSide.class) != null || - AnnotationUtils.getAnnotation(extension, ScannerSide.class) != null; + return AnnotationUtils.getAnnotation(extension, ScannerSide.class) != null; } public static boolean isType(Object extension, Class extensionClass) { diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/GlobalContainer.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/GlobalContainer.java index bc49833ec6f..c56a8447b70 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/GlobalContainer.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/GlobalContainer.java @@ -33,7 +33,6 @@ import org.sonar.api.utils.Version; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; import org.sonar.core.extension.CoreExtensionRepositoryImpl; -import org.sonar.core.extension.CoreExtensionsInstaller; import org.sonar.core.extension.CoreExtensionsLoader; import org.sonar.core.platform.ComponentContainer; import org.sonar.core.platform.PluginClassloaderFactory; diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/ScannerExtensionDictionnary.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/ScannerExtensionDictionnary.java index d492d1f7c5a..036b9c1134a 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/ScannerExtensionDictionnary.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/ScannerExtensionDictionnary.java @@ -26,27 +26,22 @@ import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; -import java.util.Iterator; import java.util.List; import java.util.stream.Collectors; import javax.annotation.Nullable; import org.apache.commons.lang.ClassUtils; -import org.sonar.api.batch.CheckProject; import org.sonar.api.batch.DependedUpon; import org.sonar.api.batch.DependsUpon; import org.sonar.api.batch.Phase; -import org.sonar.api.batch.fs.internal.DefaultInputModule; import org.sonar.api.batch.postjob.PostJob; import org.sonar.api.batch.postjob.PostJobContext; import org.sonar.api.batch.sensor.Sensor; import org.sonar.api.batch.sensor.SensorContext; -import org.sonar.api.resources.Project; import org.sonar.api.utils.AnnotationUtils; import org.sonar.api.utils.dag.DirectAcyclicGraph; import org.sonar.core.platform.ComponentContainer; import org.sonar.scanner.postjob.PostJobOptimizer; import org.sonar.scanner.postjob.PostJobWrapper; -import org.sonar.scanner.sensor.DefaultSensorContext; import org.sonar.scanner.sensor.SensorOptimizer; import org.sonar.scanner.sensor.SensorWrapper; @@ -58,101 +53,76 @@ public class ScannerExtensionDictionnary { private final ComponentContainer componentContainer; private final SensorContext sensorContext; private final SensorOptimizer sensorOptimizer; - private final PostJobContext postJobContext; private final PostJobOptimizer postJobOptimizer; + private final PostJobContext postJobContext; - public ScannerExtensionDictionnary(ComponentContainer componentContainer, DefaultSensorContext sensorContext, - SensorOptimizer sensorOptimizer, PostJobContext postJobContext, PostJobOptimizer postJobOptimizer) { + public ScannerExtensionDictionnary(ComponentContainer componentContainer, SensorContext sensorContext, SensorOptimizer sensorOptimizer, + PostJobOptimizer postJobOptimizer, PostJobContext postJobContext) { this.componentContainer = componentContainer; this.sensorContext = sensorContext; this.sensorOptimizer = sensorOptimizer; - this.postJobContext = postJobContext; this.postJobOptimizer = postJobOptimizer; + this.postJobContext = postJobContext; } - public Collection select(Class type, @Nullable DefaultInputModule module, boolean sort, @Nullable ExtensionMatcher matcher) { - List result = getFilteredExtensions(type, module, matcher); + public Collection select(Class type, boolean sort, @Nullable ExtensionMatcher matcher) { + List result = getFilteredExtensions(type, matcher); if (sort) { return sort(result); } return result; } - public Collection selectSensors(@Nullable DefaultInputModule module, boolean global) { - List result = getFilteredExtensions(org.sonar.api.batch.Sensor.class, module, null); - - Iterator iterator = result.iterator(); - while (iterator.hasNext()) { - org.sonar.api.batch.Sensor sensor = iterator.next(); - if (sensor instanceof SensorWrapper) { - if (global != ((SensorWrapper) sensor).isGlobal()) { - iterator.remove(); - } - } else if (global) { - // only old sensors are not wrapped, and old sensors are never global -> exclude - iterator.remove(); - } - } + public Collection selectSensors(boolean global) { + Collection result = sort(getFilteredExtensions(Sensor.class, null)); + return result.stream() + .map(s -> new SensorWrapper(s, sensorContext, sensorOptimizer)) + .filter(s -> global == s.isGlobal() && s.shouldExecute()) + .collect(Collectors.toList()); + } - return sort(result); + public Collection selectPostJobs() { + Collection result = sort(getFilteredExtensions(PostJob.class, null)); + return result.stream() + .map(j -> new PostJobWrapper(j, postJobContext, postJobOptimizer)) + .filter(PostJobWrapper::shouldExecute) + .collect(Collectors.toList()); } private static Phase.Name evaluatePhase(Object extension) { - Object extensionToEvaluate; - if (extension instanceof SensorWrapper) { - extensionToEvaluate = ((SensorWrapper) extension).wrappedSensor(); - } else if (extension instanceof PostJobWrapper) { - extensionToEvaluate = ((PostJobWrapper) extension).wrappedPostJob(); - } else { - extensionToEvaluate = extension; - } - Phase phaseAnnotation = AnnotationUtils.getAnnotation(extensionToEvaluate, Phase.class); + Phase phaseAnnotation = AnnotationUtils.getAnnotation(extension, Phase.class); if (phaseAnnotation != null) { return phaseAnnotation.name(); } return Phase.Name.DEFAULT; } - private List getFilteredExtensions(Class type, @Nullable DefaultInputModule module, @Nullable ExtensionMatcher matcher) { + private List getFilteredExtensions(Class type, @Nullable ExtensionMatcher matcher) { List result = new ArrayList<>(); - List candidates = new ArrayList<>(); - candidates.addAll(getExtensions(type)); - if (org.sonar.api.batch.Sensor.class.equals(type)) { - candidates.addAll(getExtensions(Sensor.class)); - } - if (org.sonar.api.batch.PostJob.class.equals(type)) { - candidates.addAll(getExtensions(PostJob.class)); - } - for (Object extension : candidates) { - if (org.sonar.api.batch.Sensor.class.equals(type) && extension instanceof Sensor) { - extension = new SensorWrapper((Sensor) extension, sensorContext, sensorOptimizer); - } - if (org.sonar.api.batch.PostJob.class.equals(type) && extension instanceof PostJob) { - extension = new PostJobWrapper((PostJob) extension, postJobContext, postJobOptimizer); - } - if (shouldKeep(type, extension, module, matcher)) { + for (Object extension : getExtensions(type)) { + if (shouldKeep(type, extension, matcher)) { result.add((T) extension); } } return result; } - protected List getExtensions(Class type) { + private List getExtensions(Class type) { List extensions = new ArrayList<>(); - completeBatchExtensions(componentContainer, extensions, type); + completeScannerExtensions(componentContainer, extensions, type); return extensions; } - private static void completeBatchExtensions(ComponentContainer container, List extensions, Class type) { + private static void completeScannerExtensions(ComponentContainer container, List extensions, Class type) { extensions.addAll(container.getComponentsByType(type)); ComponentContainer parentContainer = container.getParent(); if (parentContainer != null) { - completeBatchExtensions(parentContainer, extensions, type); + completeScannerExtensions(parentContainer, extensions, type); } } - public Collection sort(Collection extensions) { + private Collection sort(Collection extensions) { DirectAcyclicGraph dag = new DirectAcyclicGraph(); for (T extension : extensions) { @@ -176,18 +146,14 @@ public class ScannerExtensionDictionnary { * Extension dependencies */ private List getDependencies(T extension) { - List result = new ArrayList<>(); - result.addAll(evaluateAnnotatedClasses(extension, DependsUpon.class)); - return result; + return new ArrayList<>(evaluateAnnotatedClasses(extension, DependsUpon.class)); } /** * Objects that depend upon this extension. */ - public List getDependents(T extension) { - List result = new ArrayList<>(); - result.addAll(evaluateAnnotatedClasses(extension, DependedUpon.class)); - return result; + private List getDependents(T extension) { + return new ArrayList<>(evaluateAnnotatedClasses(extension, DependedUpon.class)); } private static void completePhaseDependencies(DirectAcyclicGraph dag, Object extension) { @@ -202,9 +168,9 @@ public class ScannerExtensionDictionnary { } } - protected List evaluateAnnotatedClasses(Object extension, Class annotation) { + List evaluateAnnotatedClasses(Object extension, Class annotation) { List results = new ArrayList<>(); - Class aClass = extension.getClass(); + Class aClass = extension.getClass(); while (aClass != null) { evaluateClass(aClass, annotation, results); @@ -270,13 +236,7 @@ public class ScannerExtensionDictionnary { } } - private static boolean shouldKeep(Class type, Object extension, @Nullable DefaultInputModule module, @Nullable ExtensionMatcher matcher) { - boolean keep = (ClassUtils.isAssignable(extension.getClass(), type) - || (org.sonar.api.batch.Sensor.class.equals(type) && ClassUtils.isAssignable(extension.getClass(), Sensor.class))) - && (matcher == null || matcher.accept(extension)); - if (keep && module != null && ClassUtils.isAssignable(extension.getClass(), CheckProject.class)) { - keep = ((CheckProject) extension).shouldExecuteOnProject(new Project(module)); - } - return keep; + private static boolean shouldKeep(Class type, Object extension, @Nullable ExtensionMatcher matcher) { + return ClassUtils.isAssignable(extension.getClass(), type) && (matcher == null || matcher.accept(extension)); } } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/CpdComponents.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/CpdComponents.java deleted file mode 100644 index 45b54682937..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/CpdComponents.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.cpd; - -import com.google.common.collect.ImmutableList; -import java.util.List; -import org.sonar.scanner.cpd.deprecated.CpdMappings; -import org.sonar.scanner.cpd.deprecated.DefaultCpdBlockIndexer; -import org.sonar.scanner.cpd.deprecated.DeprecatedCpdBlockIndexerSensor; -import org.sonar.scanner.cpd.deprecated.JavaCpdBlockIndexer; - -public final class CpdComponents { - - private CpdComponents() { - } - - public static List> all() { - return ImmutableList.of( - DeprecatedCpdBlockIndexerSensor.class, - CpdMappings.class, - JavaCpdBlockIndexer.class, - DefaultCpdBlockIndexer.class); - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/CpdExecutor.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/CpdExecutor.java index b143361ec41..d4c2e40041d 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/CpdExecutor.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/CpdExecutor.java @@ -20,8 +20,6 @@ package org.sonar.scanner.cpd; import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; -import com.google.common.base.Predicate; import java.util.Collection; import java.util.Iterator; import java.util.List; @@ -30,6 +28,9 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Collectors; import org.sonar.api.batch.fs.InputComponent; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.fs.internal.DefaultInputComponent; @@ -49,12 +50,10 @@ import org.sonar.scanner.scan.branch.BranchConfiguration; import org.sonar.scanner.scan.filesystem.InputComponentStore; import org.sonar.scanner.util.ProgressReport; -import static com.google.common.collect.FluentIterable.from; - /** * Runs on the root module, at the end of the project analysis. - * It executes copy paste detection involving all files of all modules, which were indexed during sensors execution for each module - * by {@link CpdSensor). The sensor is responsible for handling exclusions and block sizes. + * It executes copy paste detection involving all files of all modules, which were indexed during sensors execution for each module. + * The sensors are responsible for handling exclusions and block sizes. */ public class CpdExecutor { private static final Logger LOG = Loggers.get(CpdExecutor.class); @@ -148,7 +147,9 @@ public class CpdExecutor { if (!"java".equalsIgnoreCase(inputFile.language())) { int minTokens = settings.getMinimumTokens(inputFile.language()); Predicate minimumTokensPredicate = DuplicationPredicates.numberOfUnitsNotLessThan(minTokens); - filtered = from(duplications).filter(minimumTokensPredicate).toList(); + filtered = duplications.stream() + .filter(minimumTokensPredicate) + .collect(Collectors.toList()); } else { filtered = duplications; } @@ -156,16 +157,15 @@ public class CpdExecutor { saveDuplications(component, filtered); } - @VisibleForTesting - final void saveDuplications(final DefaultInputComponent component, List duplications) { + @VisibleForTesting final void saveDuplications(final DefaultInputComponent component, List duplications) { if (duplications.size() > MAX_CLONE_GROUP_PER_FILE) { LOG.warn("Too many duplication groups on file " + component + ". Keep only the first " + MAX_CLONE_GROUP_PER_FILE + " groups."); } - Iterable reportDuplications = from(duplications) + Iterable reportDuplications = duplications.stream() .limit(MAX_CLONE_GROUP_PER_FILE) - .transform( - new Function() { + .map( + new Function() { private final ScannerReport.Duplication.Builder dupBuilder = ScannerReport.Duplication.newBuilder(); private final ScannerReport.Duplicate.Builder blockBuilder = ScannerReport.Duplicate.newBuilder(); @@ -174,7 +174,7 @@ public class CpdExecutor { return toReportDuplication(component, dupBuilder, blockBuilder, input); } - }); + })::iterator; publisher.getWriter().writeComponentDuplications(component.batchId(), reportDuplications); } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/CpdSettings.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/CpdSettings.java index b93ba17659d..6ccbed5e395 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/CpdSettings.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/CpdSettings.java @@ -43,8 +43,6 @@ public class CpdSettings { /** * Not applicable to Java, as the {@link BlockChunker} that it uses does not record start and end units of each block. * Also, it uses statements instead of tokens. - * @param languageKey - * @return */ int getMinimumTokens(String languageKey) { return settings.getInt("sonar.cpd." + languageKey + ".minimumTokens").orElse(100); diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/DuplicationPredicates.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/DuplicationPredicates.java index 5a12df6dca2..089c41b113d 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/DuplicationPredicates.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/DuplicationPredicates.java @@ -19,8 +19,7 @@ */ package org.sonar.scanner.cpd; -import com.google.common.base.Predicate; -import javax.annotation.Nullable; +import java.util.function.Predicate; import org.sonar.duplications.index.CloneGroup; public final class DuplicationPredicates { @@ -29,20 +28,6 @@ public final class DuplicationPredicates { } public static Predicate numberOfUnitsNotLessThan(int min) { - return new NumberOfUnitsNotLessThan(min); + return input -> input != null && input.getLengthInUnits() >= min; } - - private static class NumberOfUnitsNotLessThan implements Predicate { - private final int min; - - public NumberOfUnitsNotLessThan(int min) { - this.min = min; - } - - @Override - public boolean apply(@Nullable CloneGroup input) { - return input != null && input.getLengthInUnits() >= min; - } - } - } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/deprecated/CpdBlockIndexer.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/deprecated/CpdBlockIndexer.java deleted file mode 100644 index c5bc362b578..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/deprecated/CpdBlockIndexer.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.cpd.deprecated; - -import org.sonar.api.batch.ScannerSide; -import org.sonar.api.utils.log.Logger; -import org.sonar.api.utils.log.Loggers; - -@ScannerSide -public abstract class CpdBlockIndexer { - - private static final Logger LOG = Loggers.get(CpdBlockIndexer.class); - - abstract boolean isLanguageSupported(String language); - - abstract void index(String language); - - protected void logExclusions(String[] exclusions) { - if (exclusions.length > 0) { - StringBuilder message = new StringBuilder("Copy-paste detection exclusions:"); - for (String exclusion : exclusions) { - message.append("\n "); - message.append(exclusion); - } - - LOG.info(message.toString()); - } - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/deprecated/CpdMappings.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/deprecated/CpdMappings.java deleted file mode 100644 index 11e25c30f4e..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/deprecated/CpdMappings.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.cpd.deprecated; - -import javax.annotation.CheckForNull; -import org.sonar.api.batch.CpdMapping; -import org.sonar.api.batch.ScannerSide; - -@ScannerSide -public class CpdMappings { - - private final CpdMapping[] mappings; - - public CpdMappings(CpdMapping[] mappings) { - this.mappings = mappings; - } - - public CpdMappings() { - this(new CpdMapping[0]); - } - - @CheckForNull - public CpdMapping getMapping(String language) { - if (mappings != null) { - for (CpdMapping cpdMapping : mappings) { - if (cpdMapping.getLanguage().getKey().equals(language)) { - return cpdMapping; - } - } - } - return null; - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/deprecated/DefaultCpdBlockIndexer.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/deprecated/DefaultCpdBlockIndexer.java deleted file mode 100644 index e58d52f2881..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/deprecated/DefaultCpdBlockIndexer.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.cpd.deprecated; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.collect.Lists; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.List; -import org.sonar.api.CoreProperties; -import org.sonar.api.batch.CpdMapping; -import org.sonar.api.batch.fs.FilePredicates; -import org.sonar.api.batch.fs.FileSystem; -import org.sonar.api.batch.fs.InputFile; -import org.sonar.api.batch.fs.internal.DefaultInputFile; -import org.sonar.api.config.Configuration; -import org.sonar.api.utils.log.Logger; -import org.sonar.api.utils.log.Loggers; -import org.sonar.duplications.block.Block; -import org.sonar.duplications.internal.pmd.TokenizerBridge; -import org.sonar.scanner.cpd.index.SonarCpdBlockIndex; - -public class DefaultCpdBlockIndexer extends CpdBlockIndexer { - - private static final Logger LOG = Loggers.get(DefaultCpdBlockIndexer.class); - - private final CpdMappings mappings; - private final FileSystem fs; - private final Configuration settings; - private final SonarCpdBlockIndex index; - - public DefaultCpdBlockIndexer(CpdMappings mappings, FileSystem fs, Configuration settings, SonarCpdBlockIndex index) { - this.mappings = mappings; - this.fs = fs; - this.settings = settings; - this.index = index; - } - - @Override - public boolean isLanguageSupported(String language) { - return true; - } - - @Override - public void index(String languageKey) { - CpdMapping mapping = mappings.getMapping(languageKey); - if (mapping == null) { - LOG.debug("No CpdMapping for language {}", languageKey); - return; - } - - String[] cpdExclusions = settings.getStringArray(CoreProperties.CPD_EXCLUSIONS); - logExclusions(cpdExclusions); - FilePredicates p = fs.predicates(); - List sourceFiles = Lists.newArrayList(fs.inputFiles(p.and( - p.hasType(InputFile.Type.MAIN), - p.hasLanguage(languageKey), - p.doesNotMatchPathPatterns(cpdExclusions)))); - if (sourceFiles.isEmpty()) { - return; - } - - // Create index - populateIndex(languageKey, sourceFiles, mapping); - } - - private void populateIndex(String languageKey, List sourceFiles, CpdMapping mapping) { - TokenizerBridge bridge = new TokenizerBridge(mapping.getTokenizer(), getBlockSize(languageKey)); - for (InputFile inputFile : sourceFiles) { - if (!index.isIndexed(inputFile)) { - LOG.debug("Populating index from {}", inputFile.absolutePath()); - String resourceEffectiveKey = ((DefaultInputFile) inputFile).key(); - List blocks; - try (InputStreamReader isr = new InputStreamReader(inputFile.inputStream(), inputFile.charset())) { - blocks = bridge.chunk(resourceEffectiveKey, inputFile.absolutePath(), isr); - } catch (IOException e) { - throw new IllegalStateException("Unable to read content of file " + inputFile.absolutePath(), e); - } - index.insert(inputFile, blocks); - } - } - } - - @VisibleForTesting - int getBlockSize(String languageKey) { - return settings.getInt("sonar.cpd." + languageKey + ".minimumLines").orElse(getDefaultBlockSize(languageKey)); - } - - @VisibleForTesting - public static int getDefaultBlockSize(String languageKey) { - if ("cobol".equals(languageKey)) { - return 30; - } else if ("abap".equals(languageKey)) { - return 20; - } else { - return 10; - } - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/deprecated/DeprecatedCpdBlockIndexerSensor.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/deprecated/DeprecatedCpdBlockIndexerSensor.java deleted file mode 100644 index 0b4f6111566..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/deprecated/DeprecatedCpdBlockIndexerSensor.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.cpd.deprecated; - -import com.google.common.annotations.VisibleForTesting; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.sonar.api.batch.CpdMapping; -import org.sonar.api.batch.Phase; -import org.sonar.api.batch.fs.FileSystem; -import org.sonar.api.batch.sensor.Sensor; -import org.sonar.api.batch.sensor.SensorContext; -import org.sonar.api.batch.sensor.SensorDescriptor; - -/** - * Feed block index using deprecated {@link CpdMapping} extension point if not already - * fed by another Sensor using {@link SensorContext#newCpdTokens()}. Special case for Java - * that use a dedicated block indexer. - * Can be removed when {@link CpdMapping} extension is removed and Java specific part moved to Java plugin. - */ -@Phase(name = Phase.Name.POST) -public class DeprecatedCpdBlockIndexerSensor implements Sensor { - - private static final Logger LOG = LoggerFactory.getLogger(DeprecatedCpdBlockIndexerSensor.class); - - private CpdBlockIndexer javaCpdBlockIndexer; - private CpdBlockIndexer defaultCpdBlockIndexer; - private FileSystem fs; - - public DeprecatedCpdBlockIndexerSensor(JavaCpdBlockIndexer javaCpdBlockIndexer, DefaultCpdBlockIndexer defaultCpdBlockIndexer, FileSystem fs) { - this.javaCpdBlockIndexer = javaCpdBlockIndexer; - this.defaultCpdBlockIndexer = defaultCpdBlockIndexer; - this.fs = fs; - } - - @Override - public void describe(SensorDescriptor descriptor) { - descriptor.name("CPD Block Indexer") - .global(); - } - - @VisibleForTesting - CpdBlockIndexer getBlockIndexer(String language) { - if (javaCpdBlockIndexer.isLanguageSupported(language)) { - return javaCpdBlockIndexer; - } - return defaultCpdBlockIndexer; - } - - @Override - public void execute(SensorContext context) { - for (String language : fs.languages()) { - CpdBlockIndexer blockIndexer = getBlockIndexer(language); - if (!blockIndexer.isLanguageSupported(language)) { - LOG.debug("Detection of duplicated code is not supported for {}", language); - continue; - } - LOG.debug("{} is used for {}", blockIndexer.getClass().getName(), language); - blockIndexer.index(language); - } - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/deprecated/JavaCpdBlockIndexer.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/deprecated/JavaCpdBlockIndexer.java deleted file mode 100644 index ed072e65063..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/deprecated/JavaCpdBlockIndexer.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.cpd.deprecated; - -import com.google.common.collect.Lists; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.util.List; -import org.sonar.api.CoreProperties; -import org.sonar.api.batch.fs.FilePredicates; -import org.sonar.api.batch.fs.FileSystem; -import org.sonar.api.batch.fs.InputFile; -import org.sonar.api.batch.fs.internal.DefaultInputFile; -import org.sonar.api.config.Configuration; -import org.sonar.api.utils.log.Logger; -import org.sonar.api.utils.log.Loggers; -import org.sonar.duplications.block.Block; -import org.sonar.duplications.block.BlockChunker; -import org.sonar.duplications.java.JavaStatementBuilder; -import org.sonar.duplications.java.JavaTokenProducer; -import org.sonar.duplications.statement.Statement; -import org.sonar.duplications.statement.StatementChunker; -import org.sonar.duplications.token.TokenChunker; -import org.sonar.scanner.cpd.index.SonarCpdBlockIndex; - -public class JavaCpdBlockIndexer extends CpdBlockIndexer { - - private static final Logger LOG = Loggers.get(JavaCpdBlockIndexer.class); - - private static final int BLOCK_SIZE = 10; - - private final FileSystem fs; - private final Configuration settings; - private final SonarCpdBlockIndex index; - - public JavaCpdBlockIndexer(FileSystem fs, Configuration settings, SonarCpdBlockIndex index) { - this.fs = fs; - this.settings = settings; - this.index = index; - } - - @Override - public boolean isLanguageSupported(String language) { - return "java".equals(language); - } - - @Override - public void index(String languageKey) { - String[] cpdExclusions = settings.getStringArray(CoreProperties.CPD_EXCLUSIONS); - logExclusions(cpdExclusions); - FilePredicates p = fs.predicates(); - List sourceFiles = Lists.newArrayList(fs.inputFiles(p.and( - p.hasType(InputFile.Type.MAIN), - p.hasLanguage(languageKey), - p.doesNotMatchPathPatterns(cpdExclusions)))); - if (sourceFiles.isEmpty()) { - return; - } - createIndex(sourceFiles); - } - - private void createIndex(Iterable sourceFiles) { - TokenChunker tokenChunker = JavaTokenProducer.build(); - StatementChunker statementChunker = JavaStatementBuilder.build(); - BlockChunker blockChunker = new BlockChunker(BLOCK_SIZE); - - for (InputFile inputFile : sourceFiles) { - LOG.debug("Populating index from {}", inputFile); - String resourceEffectiveKey = ((DefaultInputFile) inputFile).key(); - - List statements; - - try (InputStream is = inputFile.inputStream(); - Reader reader = new InputStreamReader(is, inputFile.charset())) { - statements = statementChunker.chunk(tokenChunker.chunk(reader)); - } catch (FileNotFoundException e) { - throw new IllegalStateException("Cannot find file " + inputFile.file(), e); - } catch (IOException e) { - throw new IllegalStateException("Exception handling file: " + inputFile.file(), e); - } - - List blocks; - try { - blocks = blockChunker.chunk(resourceEffectiveKey, statements); - } catch (Exception e) { - throw new IllegalStateException("Cannot process file " + inputFile.file(), e); - } - index.insert(inputFile, blocks); - } - } -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/deprecated/package-info.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/deprecated/package-info.java deleted file mode 100644 index b57e1437132..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/cpd/deprecated/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.cpd.deprecated; - -import javax.annotation.ParametersAreNonnullByDefault; - diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/deprecated/DeprecatedSensorContext.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/deprecated/DeprecatedSensorContext.java deleted file mode 100644 index 70938b8595d..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/deprecated/DeprecatedSensorContext.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.deprecated; - -import java.io.Serializable; -import java.util.Collection; -import javax.annotation.Nullable; -import org.sonar.api.SonarRuntime; -import org.sonar.api.batch.AnalysisMode; -import org.sonar.api.batch.SensorContext; -import org.sonar.api.batch.fs.FileSystem; -import org.sonar.api.batch.fs.InputFile; -import org.sonar.api.batch.fs.InputModule; -import org.sonar.api.batch.fs.InputPath; -import org.sonar.api.batch.rule.ActiveRules; -import org.sonar.api.batch.sensor.internal.SensorStorage; -import org.sonar.api.config.Configuration; -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.Resource; -import org.sonar.api.resources.ResourceUtils; -import org.sonar.core.component.ComponentKeys; -import org.sonar.scanner.index.DefaultIndex; -import org.sonar.scanner.scan.branch.BranchConfiguration; -import org.sonar.scanner.sensor.DefaultSensorContext; - -public class DeprecatedSensorContext extends DefaultSensorContext implements SensorContext { - private final DefaultIndex index; - private final InputModule module; - - public DeprecatedSensorContext(InputModule module, DefaultIndex index, Configuration config, org.sonar.api.config.Settings mutableSettings, - FileSystem fs, ActiveRules activeRules, AnalysisMode analysisMode, SensorStorage sensorStorage, SonarRuntime sonarRuntime, - BranchConfiguration branchConfiguration) { - super(module, config, mutableSettings, fs, activeRules, analysisMode, sensorStorage, sonarRuntime, branchConfiguration); - this.index = index; - this.module = module; - } - - @Override - public Resource getParent(Resource reference) { - return index.getParent(getComponentKey(reference)); - } - - @Override - public Collection getChildren(Resource reference) { - return index.getChildren(getComponentKey(reference)); - } - - @Override - public Measure getMeasure(Metric metric) { - return index.getMeasure(module.key(), metric); - } - - /** - * Returns effective key of a resource, without branch. - */ - private String getComponentKey(Resource r) { - if (ResourceUtils.isProject(r) || /* For technical projects */ResourceUtils.isRootProject(r)) { - return r.getKey(); - } else { - return ComponentKeys.createEffectiveKey(module.key(), r); - } - } - - @Override - public M getMeasures(MeasuresFilter filter) { - return index.getMeasures(module.key(), filter); - } - - @Override - public Measure saveMeasure(Measure measure) { - return index.addMeasure(module.key(), measure); - } - - @Override - public Measure saveMeasure(Metric metric, Double value) { - return index.addMeasure(module.key(), new Measure(metric, value)); - } - - @Override - public Measure getMeasure(Resource resource, Metric metric) { - return index.getMeasure(getComponentKey(resource), metric); - } - - @Override - public String saveResource(Resource resource) { - throw new UnsupportedOperationException("No longer possible to save resources"); - } - - @Override - public Resource getResource(Resource resource) { - return index.getResource(getComponentKey(resource)); - } - - @Override - public M getMeasures(Resource resource, MeasuresFilter filter) { - return index.getMeasures(getComponentKey(resource), filter); - } - - @Override - public Measure saveMeasure(Resource resource, Metric metric, Double value) { - Measure measure = new Measure(metric, value); - return saveMeasure(resource, measure); - } - - @Override - public Measure saveMeasure(@Nullable Resource resource, Measure measure) { - Resource resourceOrProject = resourceOrProject(resource); - return index.addMeasure(getComponentKey(resourceOrProject), measure); - } - - @Override - public Dependency saveDependency(Dependency dependency) { - return null; - } - - private Resource resourceOrProject(@Nullable Resource resource) { - if (resource == null) { - return index.getResource(module.key()); - } - Resource indexedResource = getResource(resource); - return indexedResource != null ? indexedResource : resource; - } - - @Override - public Measure saveMeasure(InputFile inputFile, Metric metric, Double value) { - Measure measure = new Measure(metric, value); - return saveMeasure(inputFile, measure); - } - - @Override - public Measure saveMeasure(InputFile inputFile, Measure measure) { - return index.addMeasure(inputFile.key(), measure); - } - - @Override - public Resource getResource(InputPath inputPath) { - Resource r = index.toResource(inputPath); - return getResource(r); - } -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/deprecated/package-info.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/deprecated/package-info.java deleted file mode 100644 index 0ebe52d7c92..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/deprecated/package-info.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.deprecated; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/deprecated/perspectives/PerspectiveNotFoundException.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/deprecated/perspectives/PerspectiveNotFoundException.java deleted file mode 100644 index 445946b2411..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/deprecated/perspectives/PerspectiveNotFoundException.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.deprecated.perspectives; - -public class PerspectiveNotFoundException extends RuntimeException { - public PerspectiveNotFoundException(String message) { - super(message); - } -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/deprecated/perspectives/ScannerPerspectives.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/deprecated/perspectives/ScannerPerspectives.java index d5ea18fc2e1..5daaff7f584 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/deprecated/perspectives/ScannerPerspectives.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/deprecated/perspectives/ScannerPerspectives.java @@ -21,51 +21,20 @@ package org.sonar.scanner.deprecated.perspectives; import com.google.common.collect.Maps; import java.util.Map; -import javax.annotation.CheckForNull; -import org.sonar.api.batch.fs.InputComponent; import org.sonar.api.batch.fs.InputPath; -import org.sonar.api.batch.fs.internal.DefaultInputModule; import org.sonar.api.component.Perspective; import org.sonar.api.component.ResourcePerspectives; -import org.sonar.api.resources.Resource; -import org.sonar.api.resources.ResourceUtils; -import org.sonar.core.component.ComponentKeys; -import org.sonar.scanner.scan.filesystem.InputComponentStore; public class ScannerPerspectives implements ResourcePerspectives { private final Map, PerspectiveBuilder> builders = Maps.newHashMap(); - private final InputComponentStore componentStore; - private final DefaultInputModule module; - - public ScannerPerspectives(PerspectiveBuilder[] builders, DefaultInputModule module, InputComponentStore componentStore) { - this.componentStore = componentStore; - this.module = module; + public ScannerPerspectives(PerspectiveBuilder[] builders) { for (PerspectiveBuilder builder : builders) { this.builders.put(builder.getPerspectiveClass(), builder); } } - @Override - @CheckForNull - public

P as(Class

perspectiveClass, Resource resource) { - InputComponent component = componentStore.getByKey(getComponentKey(resource)); - if (component != null) { - PerspectiveBuilder

builder = builderFor(perspectiveClass); - return builder.loadPerspective(perspectiveClass, component); - } - return null; - } - - private String getComponentKey(Resource r) { - if (ResourceUtils.isProject(r) || /* For technical projects */ResourceUtils.isRootProject(r)) { - return r.getKey(); - } else { - return ComponentKeys.createEffectiveKey(module.key(), r); - } - } - @Override public

P as(Class

perspectiveClass, InputPath inputPath) { PerspectiveBuilder

builder = builderFor(perspectiveClass); @@ -75,7 +44,7 @@ public class ScannerPerspectives implements ResourcePerspectives { private PerspectiveBuilder builderFor(Class clazz) { PerspectiveBuilder builder = (PerspectiveBuilder) builders.get(clazz); if (builder == null) { - throw new PerspectiveNotFoundException("Perspective class is not registered: " + clazz); + throw new IllegalStateException("Perspective class is not registered: " + clazz); } return builder; } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/deprecated/perspectives/package-info.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/deprecated/perspectives/package-info.java index 416669493ef..90c2fc2ff50 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/deprecated/perspectives/package-info.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/deprecated/perspectives/package-info.java @@ -21,3 +21,4 @@ package org.sonar.scanner.deprecated.perspectives; import javax.annotation.ParametersAreNonnullByDefault; + diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/events/BatchEvent.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/events/BatchEvent.java deleted file mode 100644 index 5fbf73cdc52..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/events/BatchEvent.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.events; - -import org.sonar.api.batch.events.EventHandler; - -/** - * Root of all Sonar Batch events. - * - * @param handler type - */ -public abstract class BatchEvent { - - protected BatchEvent() { - } - - /** - * Do not call directly - should be called only by {@link EventBus}. - * Typically should be implemented as following: handler.onEvent(this) - */ - protected abstract void dispatch(H handler); - - /** - * Returns class of associated handler. Used by {@link EventBus} to dispatch events to the correct handlers. - */ - protected abstract Class getType(); - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/events/BatchStepEvent.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/events/BatchStepEvent.java deleted file mode 100644 index 82ec00b1a76..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/events/BatchStepEvent.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.events; - -import org.sonar.scanner.phases.AbstractPhaseEvent; - -/** - * Generic event for some steps of project scan. - * @since 3.7 - * - */ -public class BatchStepEvent extends AbstractPhaseEvent - implements BatchStepHandler.BatchStepEvent { - - private String stepName; - - public BatchStepEvent(String stepName, boolean start) { - super(start); - this.stepName = stepName; - } - - @Override - public String stepName() { - return stepName; - } - - @Override - protected void dispatch(BatchStepHandler handler) { - handler.onBatchStep(this); - } - - @Override - protected Class getType() { - return BatchStepHandler.class; - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/events/BatchStepHandler.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/events/BatchStepHandler.java deleted file mode 100644 index 7ef2f285eca..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/events/BatchStepHandler.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.events; - -import org.sonar.api.batch.events.EventHandler; - -/** - * @since 3.7 - */ -@FunctionalInterface -public interface BatchStepHandler extends EventHandler { - - /** - * This interface is not intended to be implemented by clients. - */ - interface BatchStepEvent { - - String stepName(); - - boolean isStart(); - - boolean isEnd(); - - } - - /** - * Called before and after execution of each final step of project analysis - */ - void onBatchStep(BatchStepEvent event); - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/events/EventBus.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/events/EventBus.java deleted file mode 100644 index 73fd4928b9a..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/events/EventBus.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.events; - -import java.util.ArrayList; -import java.util.List; -import org.sonar.api.batch.events.EventHandler; - -/** - * Dispatches {@link BatchEvent}s. Eases decoupling by allowing objects to interact without having direct dependencies upon one another, and - * without requiring event sources to deal with maintaining handler lists. - */ -public class EventBus { - - private EventHandler[] registeredHandlers; - - public EventBus(EventHandler[] handlers) { - this.registeredHandlers = handlers; - } - - /** - * Fires the given event. - */ - public void fireEvent(BatchEvent event) { - doFireEvent(event); - } - - private void doFireEvent(BatchEvent event) { - List handlers = getDispatchList(event.getType()); - for (EventHandler handler : handlers) { - event.dispatch(handler); - } - } - - private List getDispatchList(Class handlerType) { - List result = new ArrayList<>(registeredHandlers.length); - for (EventHandler handler : registeredHandlers) { - if (handlerType.isAssignableFrom(handler.getClass())) { - result.add(handler); - } - } - return result; - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/events/package-info.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/events/package-info.java deleted file mode 100644 index 560cdbe163b..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/events/package-info.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.events; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/genericcoverage/GenericCoverageReportParser.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/genericcoverage/GenericCoverageReportParser.java index 2e0fdad66d0..4b84db6f6d4 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/genericcoverage/GenericCoverageReportParser.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/genericcoverage/GenericCoverageReportParser.java @@ -34,7 +34,6 @@ import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.sensor.SensorContext; import org.sonar.api.batch.sensor.coverage.NewCoverage; import org.sonar.api.utils.MessageException; -import org.sonar.api.utils.StaxParser; public class GenericCoverageReportParser { diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/genericcoverage/GenericTestExecutionReportParser.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/genericcoverage/GenericTestExecutionReportParser.java index 91f0c287f3f..c0c50365e41 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/genericcoverage/GenericTestExecutionReportParser.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/genericcoverage/GenericTestExecutionReportParser.java @@ -36,7 +36,6 @@ import org.sonar.api.test.MutableTestCase; import org.sonar.api.test.MutableTestPlan; import org.sonar.api.test.TestCase; import org.sonar.api.utils.MessageException; -import org.sonar.api.utils.StaxParser; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; import org.sonar.scanner.deprecated.test.TestPlanBuilder; diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/genericcoverage/StaxParser.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/genericcoverage/StaxParser.java new file mode 100644 index 00000000000..d71d8fafd9a --- /dev/null +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/genericcoverage/StaxParser.java @@ -0,0 +1,205 @@ +/* + * SonarQube + * Copyright (C) 2009-2018 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program 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. + * + * This program 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.scanner.genericcoverage; + +import com.ctc.wstx.stax.WstxInputFactory; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.net.URL; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLResolver; +import javax.xml.stream.XMLStreamException; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang.StringUtils; +import org.codehaus.staxmate.SMInputFactory; +import org.codehaus.staxmate.in.SMHierarchicCursor; + +public class StaxParser { + + private SMInputFactory inf; + private XmlStreamHandler streamHandler; + private boolean isoControlCharsAwareParser; + + /** + * Stax parser for a given stream handler and iso control chars set awarness to off + * + * @param streamHandler the xml stream handler + */ + public StaxParser(XmlStreamHandler streamHandler) { + this(streamHandler, false); + } + + /** + * Stax parser for a given stream handler and iso control chars set awarness to on. + * The iso control chars in the xml file will be replaced by simple spaces, usefull for + * potentially bogus XML files to parse, this has a small perfs overhead so use it only when necessary + * + * @param streamHandler the xml stream handler + * @param isoControlCharsAwareParser true or false + */ + public StaxParser(XmlStreamHandler streamHandler, boolean isoControlCharsAwareParser) { + this.streamHandler = streamHandler; + XMLInputFactory xmlFactory = XMLInputFactory.newInstance(); + if (xmlFactory instanceof WstxInputFactory) { + WstxInputFactory wstxInputfactory = (WstxInputFactory) xmlFactory; + wstxInputfactory.configureForLowMemUsage(); + wstxInputfactory.getConfig().setUndeclaredEntityResolver(new UndeclaredEntitiesXMLResolver()); + } + xmlFactory.setProperty(XMLInputFactory.IS_VALIDATING, false); + xmlFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); + xmlFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, false); + this.isoControlCharsAwareParser = isoControlCharsAwareParser; + inf = new SMInputFactory(xmlFactory); + } + + public void parse(File xmlFile) throws XMLStreamException { + FileInputStream input = null; + try { + input = new FileInputStream(xmlFile); + parse(input); + } catch (FileNotFoundException e) { + throw new XMLStreamException(e); + } finally { + IOUtils.closeQuietly(input); + } + } + + public void parse(InputStream xmlInput) throws XMLStreamException { + xmlInput = isoControlCharsAwareParser ? new ISOControlCharAwareInputStream(xmlInput) : xmlInput; + parse(inf.rootElementCursor(xmlInput)); + } + + public void parse(Reader xmlReader) throws XMLStreamException { + if (isoControlCharsAwareParser) { + throw new IllegalStateException("Method call not supported when isoControlCharsAwareParser=true"); + } + parse(inf.rootElementCursor(xmlReader)); + } + + public void parse(URL xmlUrl) throws XMLStreamException { + try { + parse(xmlUrl.openStream()); + } catch (IOException e) { + throw new XMLStreamException(e); + } + } + + private void parse(SMHierarchicCursor rootCursor) throws XMLStreamException { + try { + streamHandler.stream(rootCursor); + } finally { + rootCursor.getStreamReader().closeCompletely(); + } + } + + private static class UndeclaredEntitiesXMLResolver implements XMLResolver { + @Override + public Object resolveEntity(String arg0, String arg1, String fileName, String undeclaredEntity) throws XMLStreamException { + // avoid problems with XML docs containing undeclared entities.. return the entity under its raw form if not an unicode expression + if (StringUtils.startsWithIgnoreCase(undeclaredEntity, "u") && undeclaredEntity.length() == 5) { + int unicodeCharHexValue = Integer.parseInt(undeclaredEntity.substring(1), 16); + if (Character.isDefined(unicodeCharHexValue)) { + undeclaredEntity = new String(new char[] {(char) unicodeCharHexValue}); + } + } + return undeclaredEntity; + } + } + + /** + * Simple interface for handling XML stream to parse + */ + public interface XmlStreamHandler { + void stream(SMHierarchicCursor rootCursor) throws XMLStreamException; + } + + private static class ISOControlCharAwareInputStream extends InputStream { + + private InputStream inputToCheck; + + public ISOControlCharAwareInputStream(InputStream inputToCheck) { + super(); + this.inputToCheck = inputToCheck; + } + + @Override + public int read() throws IOException { + return inputToCheck.read(); + } + + @Override + public int available() throws IOException { + return inputToCheck.available(); + } + + @Override + public void close() throws IOException { + inputToCheck.close(); + } + + @Override + public synchronized void mark(int readlimit) { + inputToCheck.mark(readlimit); + } + + @Override + public boolean markSupported() { + return inputToCheck.markSupported(); + } + + @Override + public int read(byte[] b, int off, int len) throws IOException { + int readen = inputToCheck.read(b, off, len); + checkBufferForISOControlChars(b, off, len); + return readen; + } + + @Override + public int read(byte[] b) throws IOException { + int readen = inputToCheck.read(b); + checkBufferForISOControlChars(b, 0, readen); + return readen; + } + + @Override + public synchronized void reset() throws IOException { + inputToCheck.reset(); + } + + @Override + public long skip(long n) throws IOException { + return inputToCheck.skip(n); + } + + private static void checkBufferForISOControlChars(byte[] buffer, int off, int len) { + for (int i = off; i < len; i++) { + char streamChar = (char) buffer[i]; + if (Character.isISOControl(streamChar) && streamChar != '\n') { + // replace control chars by a simple space + buffer[i] = ' '; + } + } + } + } +} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/index/DefaultIndex.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/index/DefaultIndex.java deleted file mode 100644 index ceef4526627..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/index/DefaultIndex.java +++ /dev/null @@ -1,210 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.index; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.stream.Collectors; -import javax.annotation.CheckForNull; -import org.sonar.api.batch.fs.InputComponent; -import org.sonar.api.batch.fs.InputDir; -import org.sonar.api.batch.fs.InputFile; -import org.sonar.api.batch.fs.InputModule; -import org.sonar.api.batch.fs.internal.DefaultInputModule; -import org.sonar.api.batch.fs.internal.InputComponentTree; -import org.sonar.api.batch.measure.MetricFinder; -import org.sonar.api.batch.sensor.measure.internal.DefaultMeasure; -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.Metric.ValueType; -import org.sonar.api.resources.Directory; -import org.sonar.api.resources.File; -import org.sonar.api.resources.Project; -import org.sonar.api.resources.Resource; -import org.sonar.scanner.scan.filesystem.InputComponentStore; -import org.sonar.scanner.scan.measure.MeasureCache; -import org.sonar.scanner.sensor.DefaultSensorStorage; - -public class DefaultIndex { - private final InputComponentStore componentStore; - private final MeasureCache measureCache; - private final MetricFinder metricFinder; - // caches - private DefaultSensorStorage sensorStorage; - - private InputComponentTree tree; - - public DefaultIndex(InputComponentStore componentStore, InputComponentTree tree, MeasureCache measureCache, MetricFinder metricFinder) { - this.componentStore = componentStore; - this.tree = tree; - this.measureCache = measureCache; - this.metricFinder = metricFinder; - } - - public void setCurrentStorage(DefaultSensorStorage sensorStorage) { - // the following components depend on the current module, so they need to be reloaded. - this.sensorStorage = sensorStorage; - } - - @CheckForNull - public Measure getMeasure(String key, org.sonar.api.batch.measure.Metric metric) { - return getMeasures(key, MeasuresFilters.metric(metric)); - } - - @CheckForNull - public M getMeasures(String key, MeasuresFilter filter) { - Collection> unfiltered = new ArrayList<>(); - if (filter instanceof MeasuresFilters.MetricFilter) { - // optimization - DefaultMeasure byMetric = measureCache.byMetric(key, ((MeasuresFilters.MetricFilter) filter).filterOnMetricKey()); - if (byMetric != null) { - unfiltered.add(byMetric); - } - } else { - for (DefaultMeasure measure : measureCache.byComponentKey(key)) { - unfiltered.add(measure); - } - } - return filter.filter(unfiltered.stream().map(DefaultIndex::toDeprecated).collect(Collectors.toList())); - } - - private static Measure toDeprecated(org.sonar.api.batch.sensor.measure.Measure measure) { - Measure deprecatedMeasure = new Measure((Metric) measure.metric()); - setValueAccordingToMetricType(measure, deprecatedMeasure); - return deprecatedMeasure; - } - - private static void setValueAccordingToMetricType(org.sonar.api.batch.sensor.measure.Measure measure, Measure measureToSave) { - ValueType deprecatedType = ((Metric) measure.metric()).getType(); - switch (deprecatedType) { - case BOOL: - measureToSave.setValue(Boolean.TRUE.equals(measure.value()) ? 1.0 : 0.0); - break; - case INT: - case MILLISEC: - case WORK_DUR: - case FLOAT: - case PERCENT: - case RATING: - measureToSave.setValue(((Number) measure.value()).doubleValue()); - break; - case STRING: - case LEVEL: - case DATA: - case DISTRIB: - measureToSave.setData((String) measure.value()); - break; - default: - throw new UnsupportedOperationException("Unsupported type :" + deprecatedType); - } - } - - public Measure addMeasure(String key, Measure measure) { - InputComponent component = componentStore.getByKey(key); - if (component == null) { - throw new IllegalStateException("Invalid component key: " + key); - } - if (DefaultSensorStorage.isDeprecatedMetric(measure.getMetricKey())) { - // Ignore deprecated metrics - return measure; - } - org.sonar.api.batch.measure.Metric metric = metricFinder.findByKey(measure.getMetricKey()); - if (metric == null) { - throw new UnsupportedOperationException("Unknown metric: " + measure.getMetricKey()); - } - DefaultMeasure newMeasure; - if (Boolean.class.equals(metric.valueType())) { - newMeasure = new DefaultMeasure().forMetric((Metric) metric) - .withValue(measure.getValue() != 0.0); - } else if (Integer.class.equals(metric.valueType())) { - newMeasure = new DefaultMeasure().forMetric((Metric) metric) - .withValue(measure.getValue().intValue()); - } else if (Double.class.equals(metric.valueType())) { - newMeasure = new DefaultMeasure().forMetric((Metric) metric) - .withValue(measure.getValue()); - } else if (String.class.equals(metric.valueType())) { - newMeasure = new DefaultMeasure().forMetric((Metric) metric) - .withValue(measure.getData()); - } else if (Long.class.equals(metric.valueType())) { - newMeasure = new DefaultMeasure().forMetric((Metric) metric) - .withValue(measure.getValue().longValue()); - } else { - throw new UnsupportedOperationException("Unsupported type :" + metric.valueType()); - } - sensorStorage.saveMeasure(component, newMeasure); - return measure; - } - - /** - * @param key Effective key, without branch - */ - @CheckForNull - public Resource getParent(String key) { - InputComponent component = componentStore.getByKey(key); - if (component == null) { - return null; - } - InputComponent parent = tree.getParent(component); - if (parent == null) { - return null; - } - - return toResource(parent); - } - - /** - * @param key Effective key, without branch - */ - public Collection getChildren(String key) { - InputComponent component = componentStore.getByKey(key); - Collection children = tree.getChildren(component); - return children.stream().map(this::toResource).collect(Collectors.toList()); - } - - public Resource toResource(InputComponent inputComponent) { - Resource r; - if (inputComponent instanceof InputDir) { - r = Directory.create(((InputDir) inputComponent).relativePath()); - } else if (inputComponent instanceof InputFile) { - r = File.create(((InputFile) inputComponent).relativePath()); - } else if (inputComponent instanceof InputModule) { - r = new Project(((DefaultInputModule) inputComponent)); - } else { - throw new IllegalArgumentException("Unknow input path type: " + inputComponent); - } - - return r; - } - - /** - * Gets a component from the store as a resource. - * @param key Effective key, without branch - */ - @CheckForNull - public Resource getResource(String key) { - InputComponent component = componentStore.getByKey(key); - if (component == null) { - return null; - } - return toResource(component); - } -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/index/package-info.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/index/package-info.java deleted file mode 100644 index a3820802e8a..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/index/package-info.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.index; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/DefaultFilterableIssue.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/DefaultFilterableIssue.java index b1b9cbc0477..41998556700 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/DefaultFilterableIssue.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/DefaultFilterableIssue.java @@ -91,11 +91,6 @@ public class DefaultFilterableIssue implements FilterableIssue { return rawIssue.getGap() != 0 ? rawIssue.getGap() : null; } - @Override - public Double effortToFix() { - return gap(); - } - @Override public Date creationDate() { return projectAnalysisInfo.analysisDate(); diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/DefaultIssuable.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/DefaultIssuable.java deleted file mode 100644 index cbbb9dfc34f..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/DefaultIssuable.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.issue; - -import java.util.Collections; -import java.util.List; -import org.sonar.api.batch.fs.InputComponent; -import org.sonar.api.batch.sensor.SensorContext; -import org.sonar.api.batch.sensor.issue.internal.DefaultIssue; -import org.sonar.api.issue.Issuable; -import org.sonar.api.issue.Issue; - -/** - * @since 3.6 - */ -public class DefaultIssuable implements Issuable { - - private final InputComponent component; - private final SensorContext sensorContext; - - DefaultIssuable(InputComponent component, SensorContext sensorContext) { - this.component = component; - this.sensorContext = sensorContext; - } - - @Override - public IssueBuilder newIssueBuilder() { - DefaultIssue newIssue = (DefaultIssue) sensorContext.newIssue(); - return new DeprecatedIssueBuilderWrapper(component, newIssue); - } - - @Override - public boolean addIssue(Issue issue) { - ((DeprecatedIssueWrapper) issue).wrapped().save(); - return true; - } - - @Override - public List resolvedIssues() { - return Collections.emptyList(); - } - - @Override - public List issues() { - return Collections.emptyList(); - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/DeprecatedIssueAdapterForFilter.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/DeprecatedIssueAdapterForFilter.java deleted file mode 100644 index e311931e46b..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/DeprecatedIssueAdapterForFilter.java +++ /dev/null @@ -1,202 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.issue; - -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.List; -import java.util.Map; -import org.sonar.api.batch.fs.internal.DefaultInputModule; -import org.sonar.api.issue.Issue; -import org.sonar.api.issue.IssueComment; -import org.sonar.api.rule.RuleKey; -import org.sonar.api.utils.Duration; -import org.sonar.scanner.ProjectAnalysisInfo; - -/** - * @deprecated since 5.3 - */ -@Deprecated -class DeprecatedIssueAdapterForFilter implements Issue { - private final org.sonar.scanner.protocol.output.ScannerReport.Issue rawIssue; - private final String componentKey; - private DefaultInputModule module; - private ProjectAnalysisInfo projectAnalysisInfo; - - DeprecatedIssueAdapterForFilter(DefaultInputModule module, ProjectAnalysisInfo projectAnalysisInfo, org.sonar.scanner.protocol.output.ScannerReport.Issue rawIssue, - String componentKey) { - this.module = module; - this.projectAnalysisInfo = projectAnalysisInfo; - this.rawIssue = rawIssue; - this.componentKey = componentKey; - } - - @Override - public String key() { - throw unsupported(); - } - - @Override - public String componentKey() { - return componentKey; - } - - @Override - public RuleKey ruleKey() { - return RuleKey.of(rawIssue.getRuleRepository(), rawIssue.getRuleKey()); - } - - @Override - public String language() { - throw unsupported(); - } - - @Override - public String severity() { - return rawIssue.getSeverity().name(); - } - - @Override - public String message() { - return rawIssue.getMsg(); - } - - @Override - public Integer line() { - return rawIssue.hasTextRange() ? rawIssue.getTextRange().getStartLine() : null; - } - - @Override - @Deprecated - public Double effortToFix() { - return gap(); - } - - @Override - public Double gap() { - return rawIssue.getGap() != 0 ? rawIssue.getGap() : null; - } - - @Override - public String status() { - return Issue.STATUS_OPEN; - } - - @Override - public String resolution() { - return null; - } - - @Override - public String reporter() { - throw unsupported(); - } - - @Override - public String assignee() { - return null; - } - - @Override - public Date creationDate() { - return projectAnalysisInfo.analysisDate(); - } - - @Override - public Date updateDate() { - return null; - } - - @Override - public Date closeDate() { - return null; - } - - @Override - public String attribute(String key) { - return attributes().get(key); - } - - @Override - public Map attributes() { - return Collections.emptyMap(); - } - - @Override - public String authorLogin() { - throw unsupported(); - } - - @Override - public String actionPlanKey() { - throw unsupported(); - } - - @Override - public List comments() { - throw unsupported(); - } - - @Override - public boolean isNew() { - throw unsupported(); - } - - @Override - public boolean isCopied() { - throw unsupported(); - } - - @Deprecated - @Override - public Duration debt() { - return effort(); - } - - @Override - public Duration effort() { - throw unsupported(); - } - - @Override - public String projectKey() { - return module.definition().getKeyWithBranch(); - } - - @Override - public String projectUuid() { - throw unsupported(); - } - - @Override - public String componentUuid() { - throw unsupported(); - } - - @Override - public Collection tags() { - throw unsupported(); - } - - private static UnsupportedOperationException unsupported() { - return new UnsupportedOperationException("Not available for issues filters"); - } -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/DeprecatedIssueBuilderWrapper.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/DeprecatedIssueBuilderWrapper.java deleted file mode 100644 index 02bfaac9965..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/DeprecatedIssueBuilderWrapper.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.issue; - -import com.google.common.base.Preconditions; -import javax.annotation.Nullable; -import org.sonar.api.batch.fs.InputComponent; -import org.sonar.api.batch.fs.InputFile; -import org.sonar.api.batch.fs.TextRange; -import org.sonar.api.batch.rule.Severity; -import org.sonar.api.batch.sensor.issue.NewIssueLocation; -import org.sonar.api.batch.sensor.issue.internal.DefaultIssue; -import org.sonar.api.batch.sensor.issue.internal.DefaultIssueLocation; -import org.sonar.api.issue.Issuable; -import org.sonar.api.issue.Issuable.IssueBuilder; -import org.sonar.api.issue.Issue; -import org.sonar.api.rule.RuleKey; - -public class DeprecatedIssueBuilderWrapper implements Issuable.IssueBuilder { - - private final DefaultIssue newIssue; - private final InputComponent primaryComponent; - private TextRange primaryRange = null; - private String primaryMessage = null; - - public DeprecatedIssueBuilderWrapper(InputComponent primaryComponent, DefaultIssue newIssue) { - this.primaryComponent = primaryComponent; - this.newIssue = newIssue; - } - - @Override - public IssueBuilder ruleKey(RuleKey ruleKey) { - newIssue.forRule(ruleKey); - return this; - } - - @Override - public IssueBuilder line(@Nullable Integer line) { - Preconditions.checkState(newIssue.primaryLocation() == null, "Do not use line() and at() for the same issue"); - if (primaryComponent.isFile()) { - if (line != null) { - this.primaryRange = ((InputFile) primaryComponent).selectLine(line.intValue()); - } - return this; - } else { - throw new IllegalArgumentException("Unable to set line for issues on project or directory"); - } - } - - @Override - public IssueBuilder message(String message) { - Preconditions.checkState(newIssue.primaryLocation() == null, "Do not use message() and at() for the same issue"); - this.primaryMessage = message; - return this; - } - - @Override - public NewIssueLocation newLocation() { - return new DefaultIssueLocation(); - } - - @Override - public IssueBuilder at(NewIssueLocation primaryLocation) { - Preconditions.checkState(primaryMessage == null && primaryRange == null, "Do not use message() or line() and at() for the same issue"); - newIssue.at(primaryLocation); - return this; - } - - @Override - public IssueBuilder addLocation(NewIssueLocation secondaryLocation) { - newIssue.addLocation(secondaryLocation); - return this; - } - - @Override - public IssueBuilder addFlow(Iterable flowLocations) { - newIssue.addFlow(flowLocations); - return this; - } - - @Override - public IssueBuilder severity(String severity) { - newIssue.overrideSeverity(Severity.valueOf(severity)); - return this; - } - - @Override - public IssueBuilder reporter(String reporter) { - throw new UnsupportedOperationException("Not supported during sensor phase"); - } - - @Override - public IssueBuilder effortToFix(Double d) { - newIssue.effortToFix(d); - return this; - } - - @Override - public IssueBuilder attribute(String key, String value) { - throw new UnsupportedOperationException("Not supported during sensor phase"); - } - - @Override - public Issue build() { - if (newIssue.primaryLocation() == null) { - NewIssueLocation newLocation = newIssue.newLocation().on(primaryComponent); - if (primaryMessage != null) { - newLocation.message(primaryMessage); - } - if (primaryComponent.isFile() && primaryRange != null) { - newLocation.at(primaryRange); - } - newIssue.at(newLocation); - } - return new DeprecatedIssueWrapper(newIssue); - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/DeprecatedIssueFilterChain.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/DeprecatedIssueFilterChain.java deleted file mode 100644 index e43ffd6b100..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/DeprecatedIssueFilterChain.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.issue; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import org.sonar.api.issue.Issue; -import org.sonar.api.issue.batch.IssueFilter; -import org.sonar.api.issue.batch.IssueFilterChain; - -/** - * @deprecated since 5.3 - */ -@Deprecated -public class DeprecatedIssueFilterChain implements IssueFilterChain { - - private final List filters; - - public DeprecatedIssueFilterChain(IssueFilter... filters) { - this.filters = Arrays.asList(filters); - } - - public DeprecatedIssueFilterChain() { - this.filters = Collections.emptyList(); - } - - private DeprecatedIssueFilterChain(List filters) { - this.filters = filters; - } - - @Override - public boolean accept(Issue issue) { - if (filters.isEmpty()) { - return true; - } else { - return filters.get(0).accept(issue, new DeprecatedIssueFilterChain(filters.subList(1, filters.size()))); - } - } -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/DeprecatedIssueWrapper.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/DeprecatedIssueWrapper.java deleted file mode 100644 index 3edf90fa85c..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/DeprecatedIssueWrapper.java +++ /dev/null @@ -1,198 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.issue; - -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.List; -import java.util.Map; -import org.sonar.api.batch.fs.TextRange; -import org.sonar.api.batch.rule.Severity; -import org.sonar.api.batch.sensor.issue.internal.DefaultIssue; -import org.sonar.api.issue.Issue; -import org.sonar.api.issue.IssueComment; -import org.sonar.api.rule.RuleKey; -import org.sonar.api.utils.Duration; - -public class DeprecatedIssueWrapper implements Issue { - - private final DefaultIssue newIssue; - - public DeprecatedIssueWrapper(DefaultIssue newIssue) { - this.newIssue = newIssue; - } - - public DefaultIssue wrapped() { - return newIssue; - } - - @Override - public String key() { - return null; - } - - @Override - public String componentKey() { - return null; - } - - @Override - public RuleKey ruleKey() { - return newIssue.ruleKey(); - } - - @Override - public String language() { - return null; - } - - @Override - public String severity() { - Severity overriddenSeverity = newIssue.overriddenSeverity(); - return overriddenSeverity != null ? overriddenSeverity.name() : null; - } - - @Override - public String message() { - return newIssue.primaryLocation().message(); - } - - @Override - public Integer line() { - TextRange textRange = newIssue.primaryLocation().textRange(); - return textRange != null ? textRange.start().line() : null; - } - - /** - * @deprecated since 5.5, replaced by {@link #gap()} - */ - @Override - @Deprecated - public Double effortToFix() { - return gap(); - } - - @Override - public Double gap() { - return newIssue.effortToFix(); - } - - @Override - public String status() { - return null; - } - - @Override - public String resolution() { - return null; - } - - @Override - public String reporter() { - return null; - } - - @Override - public String assignee() { - return null; - } - - @Override - public Date creationDate() { - return null; - } - - @Override - public Date updateDate() { - return null; - } - - @Override - public Date closeDate() { - return null; - } - - @Override - public String attribute(String key) { - return null; - } - - @Override - public Map attributes() { - return Collections.emptyMap(); - } - - @Override - public String authorLogin() { - return null; - } - - @Override - public String actionPlanKey() { - return null; - } - - @Override - public List comments() { - return Collections.emptyList(); - } - - @Override - public boolean isNew() { - return false; - } - - @Override - public boolean isCopied() { - return false; - } - - @Override - public Duration debt() { - return null; - } - - @Override - public Duration effort() { - return null; - } - - @Override - public String projectKey() { - return null; - } - - @Override - public String projectUuid() { - return null; - } - - @Override - public String componentUuid() { - return null; - } - - @Override - public Collection tags() { - return Collections.emptyList(); - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/IssuableFactory.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/IssuableFactory.java deleted file mode 100644 index 65a7694b529..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/IssuableFactory.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.issue; - -import org.sonar.api.batch.fs.InputComponent; -import org.sonar.api.batch.sensor.SensorContext; -import org.sonar.api.issue.Issuable; -import org.sonar.scanner.deprecated.perspectives.PerspectiveBuilder; -import org.sonar.scanner.sensor.DefaultSensorContext; - -/** - * Create the perspective {@link Issuable} on components. - * @since 3.6 - */ -public class IssuableFactory extends PerspectiveBuilder { - - private final SensorContext sensorContext; - - public IssuableFactory(DefaultSensorContext sensorContext) { - super(Issuable.class); - this.sensorContext = sensorContext; - } - - @Override - public Issuable loadPerspective(Class perspectiveClass, InputComponent component) { - return new DefaultIssuable(component, sensorContext); - } -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/IssueFilters.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/IssueFilters.java index b213dd00284..ad562e8d3fc 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/IssueFilters.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/IssueFilters.java @@ -21,7 +21,6 @@ package org.sonar.scanner.issue; import org.sonar.api.batch.ScannerSide; import org.sonar.api.batch.fs.internal.DefaultInputModule; -import org.sonar.api.issue.Issue; import org.sonar.api.scan.issue.filter.FilterableIssue; import org.sonar.api.scan.issue.filter.IssueFilter; import org.sonar.api.scan.issue.filter.IssueFilterChain; @@ -31,40 +30,22 @@ import org.sonar.scanner.protocol.output.ScannerReport; @ScannerSide public class IssueFilters { private final IssueFilterChain filterChain; - private final org.sonar.api.issue.batch.IssueFilter[] deprecatedFilters; private final DefaultInputModule module; private final ProjectAnalysisInfo projectAnalysisInfo; - public IssueFilters(DefaultInputModule module, ProjectAnalysisInfo projectAnalysisInfo, IssueFilter[] exclusionFilters, org.sonar.api.issue.batch.IssueFilter[] filters) { + public IssueFilters(DefaultInputModule module, ProjectAnalysisInfo projectAnalysisInfo, IssueFilter[] exclusionFilters) { this.module = module; this.filterChain = new DefaultIssueFilterChain(exclusionFilters); - this.deprecatedFilters = filters; this.projectAnalysisInfo = projectAnalysisInfo; } - public IssueFilters(DefaultInputModule module, ProjectAnalysisInfo projectAnalysisInfo, IssueFilter[] filters) { - this(module, projectAnalysisInfo, filters, new org.sonar.api.issue.batch.IssueFilter[0]); - } - - public IssueFilters(DefaultInputModule module, ProjectAnalysisInfo projectAnalysisInfo, org.sonar.api.issue.batch.IssueFilter[] deprecatedFilters) { - this(module, projectAnalysisInfo, new IssueFilter[0], deprecatedFilters); - } - public IssueFilters(DefaultInputModule module, ProjectAnalysisInfo projectAnalysisInfo) { - this(module, projectAnalysisInfo, new IssueFilter[0], new org.sonar.api.issue.batch.IssueFilter[0]); + this(module, projectAnalysisInfo, new IssueFilter[0]); } public boolean accept(String componentKey, ScannerReport.Issue rawIssue) { FilterableIssue fIssue = new DefaultFilterableIssue(module, projectAnalysisInfo, rawIssue, componentKey); - if (filterChain.accept(fIssue)) { - return acceptDeprecated(componentKey, rawIssue); - } - - return false; + return filterChain.accept(fIssue); } - public boolean acceptDeprecated(String componentKey, ScannerReport.Issue rawIssue) { - Issue issue = new DeprecatedIssueAdapterForFilter(module, projectAnalysisInfo, rawIssue, componentKey); - return new DeprecatedIssueFilterChain(deprecatedFilters).accept(issue); - } } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/TrackedIssueAdapter.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/TrackedIssueAdapter.java index 254a078f956..78d525c7aab 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/TrackedIssueAdapter.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/issue/TrackedIssueAdapter.java @@ -25,7 +25,6 @@ import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; -import javax.annotation.CheckForNull; import org.sonar.api.issue.Issue; import org.sonar.api.issue.IssueComment; import org.sonar.api.rule.RuleKey; @@ -69,15 +68,6 @@ public class TrackedIssueAdapter implements Issue { return issue.startLine(); } - /** - * @deprecated since 5.5, replaced by {@link #gap()} - */ - @Override - @Deprecated - public Double effortToFix() { - return gap(); - } - @Override public Double gap() { return issue.gap(); @@ -93,16 +83,6 @@ public class TrackedIssueAdapter implements Issue { return issue.resolution(); } - /** - * @deprecated since 5.5, manual issue feature has been dropped. - */ - @Deprecated - @CheckForNull - @Override - public String reporter() { - return null; - } - @Override public String assignee() { return issue.assignee(); @@ -153,25 +133,11 @@ public class TrackedIssueAdapter implements Issue { return null; } - @Override - public String actionPlanKey() { - return null; - } - @Override public List comments() { return new ArrayList<>(); } - /** - * @deprecated since 5.5, replaced by {@link #effort()} - */ - @Override - @Deprecated - public Duration debt() { - return null; - } - @Override public Duration effort() { return null; diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/AbstractPhaseEvent.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/AbstractPhaseEvent.java deleted file mode 100644 index 32c42043267..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/AbstractPhaseEvent.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.phases; - -import org.sonar.api.batch.events.EventHandler; -import org.sonar.scanner.events.BatchEvent; - -public abstract class AbstractPhaseEvent extends BatchEvent { - - private final boolean start; - - public AbstractPhaseEvent(boolean start) { - this.start = start; - } - - public final boolean isStart() { - return start; - } - - public final boolean isEnd() { - return !start; - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/AbstractPhaseExecutor.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/AbstractPhaseExecutor.java index 56c3534f684..e866623b2de 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/AbstractPhaseExecutor.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/AbstractPhaseExecutor.java @@ -19,15 +19,12 @@ */ package org.sonar.scanner.phases; -import org.sonar.api.batch.SensorContext; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.api.batch.fs.internal.DefaultInputModule; import org.sonar.api.batch.fs.internal.InputModuleHierarchy; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; -import org.sonar.scanner.events.BatchStepEvent; -import org.sonar.scanner.events.EventBus; import org.sonar.scanner.issue.ignore.scanner.IssueExclusionsLoader; import org.sonar.scanner.rule.QProfileVerifier; import org.sonar.scanner.scan.filesystem.DefaultModuleFileSystem; @@ -37,11 +34,8 @@ public abstract class AbstractPhaseExecutor { private static final Logger LOG = Loggers.get(AbstractPhaseExecutor.class); - private final EventBus eventBus; private final PostJobsExecutor postJobsExecutor; - private final InitializersExecutor initializersExecutor; private final SensorsExecutor sensorsExecutor; - private final SensorContext sensorContext; private final DefaultModuleFileSystem fs; private final QProfileVerifier profileVerifier; private final IssueExclusionsLoader issueExclusionsLoader; @@ -49,14 +43,10 @@ public abstract class AbstractPhaseExecutor { private final FileIndexer fileIndexer; private final CoverageExclusions coverageExclusions; - public AbstractPhaseExecutor(InitializersExecutor initializersExecutor, PostJobsExecutor postJobsExecutor, SensorsExecutor sensorsExecutor, - SensorContext sensorContext, InputModuleHierarchy hierarchy, EventBus eventBus, DefaultModuleFileSystem fs, QProfileVerifier profileVerifier, - IssueExclusionsLoader issueExclusionsLoader, FileIndexer fileIndexer, CoverageExclusions coverageExclusions) { + public AbstractPhaseExecutor(PostJobsExecutor postJobsExecutor, SensorsExecutor sensorsExecutor, InputModuleHierarchy hierarchy, DefaultModuleFileSystem fs, + QProfileVerifier profileVerifier, IssueExclusionsLoader issueExclusionsLoader, FileIndexer fileIndexer, CoverageExclusions coverageExclusions) { this.postJobsExecutor = postJobsExecutor; - this.initializersExecutor = initializersExecutor; this.sensorsExecutor = sensorsExecutor; - this.sensorContext = sensorContext; - this.eventBus = eventBus; this.fs = fs; this.profileVerifier = profileVerifier; this.issueExclusionsLoader = issueExclusionsLoader; @@ -69,12 +59,8 @@ public abstract class AbstractPhaseExecutor { * Executed on each module */ public final void execute(DefaultInputModule module) { - eventBus.fireEvent(new ProjectAnalysisEvent(module, true)); - - executeInitializersPhase(); - // Index the filesystem - indexFs(); + fileIndexer.index(); // Log detected languages and their profiles after FS is indexed and languages detected profileVerifier.execute(); @@ -85,21 +71,18 @@ public abstract class AbstractPhaseExecutor { // Initialize coverage exclusions initCoverageExclusions(); - sensorsExecutor.execute(sensorContext); + sensorsExecutor.execute(); afterSensors(); if (hierarchy.isRoot(module)) { executeOnRoot(); - postJobsExecutor.execute(sensorContext); + postJobsExecutor.execute(); } - eventBus.fireEvent(new ProjectAnalysisEvent(module, false)); } private void initCoverageExclusions() { if (coverageExclusions.shouldExecute()) { - String stepName = "Init coverage exclusions"; - eventBus.fireEvent(new BatchStepEvent(stepName, true)); coverageExclusions.log(); for (InputFile inputFile : fs.inputFiles(fs.predicates().all())) { @@ -110,9 +93,7 @@ public abstract class AbstractPhaseExecutor { } } - eventBus.fireEvent(new BatchStepEvent(stepName, false)); } - } protected void afterSensors() { @@ -122,25 +103,9 @@ public abstract class AbstractPhaseExecutor { private void initIssueExclusions() { if (issueExclusionsLoader.shouldExecute()) { - String stepName = "Init issue exclusions"; - eventBus.fireEvent(new BatchStepEvent(stepName, true)); - for (InputFile inputFile : fs.inputFiles(fs.predicates().all())) { issueExclusionsLoader.addMulticriteriaPatterns(((DefaultInputFile) inputFile).getModuleRelativePath(), inputFile.key()); } - - eventBus.fireEvent(new BatchStepEvent(stepName, false)); } } - - private void indexFs() { - String stepName = "Index filesystem"; - eventBus.fireEvent(new BatchStepEvent(stepName, true)); - fileIndexer.index(); - eventBus.fireEvent(new BatchStepEvent(stepName, false)); - } - - private void executeInitializersPhase() { - initializersExecutor.execute(); - } } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/InitializerExecutionEvent.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/InitializerExecutionEvent.java deleted file mode 100644 index 1f23109b869..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/InitializerExecutionEvent.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.phases; - -import org.sonar.api.batch.Initializer; -import org.sonar.api.batch.events.InitializerExecutionHandler; - -class InitializerExecutionEvent extends AbstractPhaseEvent - implements InitializerExecutionHandler.InitializerExecutionEvent { - - private final Initializer initializer; - - InitializerExecutionEvent(Initializer initializer, boolean start) { - super(start); - this.initializer = initializer; - } - - @Override - public Initializer getInitializer() { - return initializer; - } - - @Override - public void dispatch(InitializerExecutionHandler handler) { - handler.onInitializerExecution(this); - } - - @Override - public Class getType() { - return InitializerExecutionHandler.class; - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/InitializersExecutor.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/InitializersExecutor.java deleted file mode 100644 index dc617584f79..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/InitializersExecutor.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.phases; - -import java.util.Collection; - -import org.apache.commons.lang.StringUtils; -import org.sonar.api.batch.Initializer; -import org.sonar.api.batch.fs.internal.DefaultInputModule; -import org.sonar.api.resources.Project; -import org.sonar.api.utils.log.Logger; -import org.sonar.api.utils.log.Loggers; -import org.sonar.api.utils.log.Profiler; -import org.sonar.scanner.bootstrap.ScannerExtensionDictionnary; -import org.sonar.scanner.events.EventBus; - -import com.google.common.collect.Lists; - -public class InitializersExecutor { - - private static final Logger LOG = Loggers.get(SensorsExecutor.class); - - private final DefaultInputModule module; - private final ScannerExtensionDictionnary selector; - private final EventBus eventBus; - - public InitializersExecutor(ScannerExtensionDictionnary selector, DefaultInputModule module, EventBus eventBus) { - this.selector = selector; - this.module = module; - this.eventBus = eventBus; - } - - public void execute() { - Collection initializers = selector.select(Initializer.class, module, true, null); - eventBus.fireEvent(new InitializersPhaseEvent(Lists.newArrayList(initializers), true)); - if (LOG.isDebugEnabled()) { - LOG.debug("Initializers : {}", StringUtils.join(initializers, " -> ")); - } - - Project project = new Project(module); - for (Initializer initializer : initializers) { - eventBus.fireEvent(new InitializerExecutionEvent(initializer, true)); - - Profiler profiler = Profiler.create(LOG).startInfo("Initializer " + initializer); - initializer.execute(project); - profiler.stopInfo(); - eventBus.fireEvent(new InitializerExecutionEvent(initializer, false)); - } - - eventBus.fireEvent(new InitializersPhaseEvent(Lists.newArrayList(initializers), false)); - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/InitializersPhaseEvent.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/InitializersPhaseEvent.java deleted file mode 100644 index 2018c3bc975..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/InitializersPhaseEvent.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.phases; - -import java.util.List; -import org.sonar.api.batch.Initializer; -import org.sonar.api.batch.events.InitializersPhaseHandler; - -class InitializersPhaseEvent extends AbstractPhaseEvent - implements InitializersPhaseHandler.InitializersPhaseEvent { - - private final List initializers; - - InitializersPhaseEvent(List initializers, boolean start) { - super(start); - this.initializers = initializers; - } - - @Override - public List getInitializers() { - return initializers; - } - - @Override - protected void dispatch(InitializersPhaseHandler handler) { - handler.onInitializersPhase(this); - } - - @Override - protected Class getType() { - return InitializersPhaseHandler.class; - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/IssuesPhaseExecutor.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/IssuesPhaseExecutor.java index 610140e6ac1..c2f70c9e77d 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/IssuesPhaseExecutor.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/IssuesPhaseExecutor.java @@ -21,10 +21,7 @@ package org.sonar.scanner.phases; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.sonar.api.batch.SensorContext; import org.sonar.api.batch.fs.internal.InputModuleHierarchy; -import org.sonar.scanner.events.BatchStepEvent; -import org.sonar.scanner.events.EventBus; import org.sonar.scanner.issue.ignore.scanner.IssueExclusionsLoader; import org.sonar.scanner.issue.tracking.IssueTransition; import org.sonar.scanner.rule.QProfileVerifier; @@ -36,40 +33,23 @@ public final class IssuesPhaseExecutor extends AbstractPhaseExecutor { private static final Logger LOG = LoggerFactory.getLogger(IssuesPhaseExecutor.class); - private final EventBus eventBus; private final IssuesReports issuesReport; private final IssueTransition localIssueTracking; - public IssuesPhaseExecutor(InitializersExecutor initializersExecutor, PostJobsExecutor postJobsExecutor, SensorsExecutor sensorsExecutor, SensorContext sensorContext, - EventBus eventBus, IssuesReports jsonReport, DefaultModuleFileSystem fs, QProfileVerifier profileVerifier, + public IssuesPhaseExecutor(PostJobsExecutor postJobsExecutor, SensorsExecutor sensorsExecutor, + IssuesReports jsonReport, DefaultModuleFileSystem fs, QProfileVerifier profileVerifier, IssueExclusionsLoader issueExclusionsLoader, IssueTransition localIssueTracking, InputModuleHierarchy moduleHierarchy, FileIndexer fileIndexer, CoverageExclusions coverageExclusions) { - super(initializersExecutor, postJobsExecutor, sensorsExecutor, sensorContext, moduleHierarchy, eventBus, fs, profileVerifier, issueExclusionsLoader, fileIndexer, + super(postJobsExecutor, sensorsExecutor, moduleHierarchy, fs, profileVerifier, issueExclusionsLoader, fileIndexer, coverageExclusions); - this.eventBus = eventBus; this.issuesReport = jsonReport; this.localIssueTracking = localIssueTracking; } @Override protected void executeOnRoot() { - localIssueTracking(); - issuesReport(); - LOG.info("ANALYSIS SUCCESSFUL"); - } - - private void localIssueTracking() { - String stepName = "Local Issue Tracking"; - eventBus.fireEvent(new BatchStepEvent(stepName, true)); localIssueTracking.execute(); - eventBus.fireEvent(new BatchStepEvent(stepName, false)); - } - - private void issuesReport() { - String stepName = "Issues Reports"; - eventBus.fireEvent(new BatchStepEvent(stepName, true)); issuesReport.execute(); - eventBus.fireEvent(new BatchStepEvent(stepName, false)); + LOG.info("ANALYSIS SUCCESSFUL"); } - } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/PhasesTimeProfiler.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/PhasesTimeProfiler.java deleted file mode 100644 index 4a5a523b2d8..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/PhasesTimeProfiler.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.phases; - -import org.apache.commons.lang.StringUtils; -import org.sonar.api.batch.Sensor; -import org.sonar.api.batch.events.SensorExecutionHandler; -import org.sonar.api.batch.events.SensorsPhaseHandler; -import org.sonar.api.utils.log.Logger; -import org.sonar.api.utils.log.Loggers; -import org.sonar.api.utils.log.Profiler; -import org.sonar.scanner.bootstrap.ScannerPluginRepository; -import org.sonar.scanner.sensor.SensorWrapper; -import org.sonar.scanner.util.ScannerUtils; - -public class PhasesTimeProfiler implements SensorExecutionHandler, SensorsPhaseHandler { - - private static final Logger LOG = Loggers.get(PhasesTimeProfiler.class); - private Profiler profiler = Profiler.create(LOG); - private final ScannerPluginRepository pluginRepo; - - public PhasesTimeProfiler(ScannerPluginRepository pluginRepo) { - this.pluginRepo = pluginRepo; - } - - @Override - public void onSensorsPhase(SensorsPhaseEvent event) { - if (event.isStart()) { - LOG.debug("Sensors : {}", StringUtils.join(event.getSensors(), " -> ")); - } - } - - @Override - public void onSensorExecution(SensorExecutionEvent event) { - if (event.isStart()) { - ClassLoader cl = getSensorClassLoader(event.getSensor()); - String pluginKey = pluginRepo.getPluginKey(cl); - String suffix = ""; - if (pluginKey != null) { - suffix = " [" + pluginKey + "]"; - } - profiler.startInfo("Sensor " + ScannerUtils.describe(event.getSensor()) + suffix); - } else { - profiler.stopInfo(); - } - } - - private static ClassLoader getSensorClassLoader(Sensor sensor) { - if (sensor instanceof SensorWrapper) { - SensorWrapper wrapper = (SensorWrapper) sensor; - return wrapper.wrappedSensor().getClass().getClassLoader(); - } else { - return sensor.getClass().getClassLoader(); - } - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/PostJobExecutionEvent.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/PostJobExecutionEvent.java deleted file mode 100644 index 1f05da3935f..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/PostJobExecutionEvent.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.phases; - -import org.sonar.api.batch.PostJob; -import org.sonar.api.batch.events.PostJobExecutionHandler; - -class PostJobExecutionEvent extends AbstractPhaseEvent - implements PostJobExecutionHandler.PostJobExecutionEvent { - - private final PostJob postJob; - - PostJobExecutionEvent(PostJob postJob, boolean start) { - super(start); - this.postJob = postJob; - } - - @Override - public PostJob getPostJob() { - return postJob; - } - - @Override - public void dispatch(PostJobExecutionHandler handler) { - handler.onPostJobExecution(this); - } - - @Override - public Class getType() { - return PostJobExecutionHandler.class; - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/PostJobPhaseEvent.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/PostJobPhaseEvent.java deleted file mode 100644 index 256634238bc..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/PostJobPhaseEvent.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.phases; - -import java.util.List; -import org.sonar.api.batch.PostJob; -import org.sonar.api.batch.events.PostJobsPhaseHandler; - -class PostJobPhaseEvent extends AbstractPhaseEvent - implements PostJobsPhaseHandler.PostJobsPhaseEvent { - - private final List postJobs; - - PostJobPhaseEvent(List postJobs, boolean start) { - super(start); - this.postJobs = postJobs; - } - - @Override - public List getPostJobs() { - return postJobs; - } - - @Override - protected void dispatch(PostJobsPhaseHandler handler) { - handler.onPostJobsPhase(this); - } - - @Override - protected Class getType() { - return PostJobsPhaseHandler.class; - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/PostJobsExecutor.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/PostJobsExecutor.java index 0c3b816a419..7d8580a2f14 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/PostJobsExecutor.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/PostJobsExecutor.java @@ -19,58 +19,43 @@ */ package org.sonar.scanner.phases; -import java.util.ArrayList; import java.util.Collection; - -import org.apache.commons.lang.StringUtils; -import org.sonar.api.batch.PostJob; +import java.util.stream.Collectors; import org.sonar.api.batch.ScannerSide; -import org.sonar.api.batch.SensorContext; -import org.sonar.api.batch.fs.internal.DefaultInputModule; -import org.sonar.api.resources.Project; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; import org.sonar.scanner.bootstrap.ScannerExtensionDictionnary; -import org.sonar.scanner.events.EventBus; -import org.sonar.scanner.util.ScannerUtils; +import org.sonar.scanner.postjob.PostJobWrapper; @ScannerSide public class PostJobsExecutor { private static final Logger LOG = Loggers.get(PostJobsExecutor.class); private final ScannerExtensionDictionnary selector; - private final DefaultInputModule module; - private final EventBus eventBus; - public PostJobsExecutor(ScannerExtensionDictionnary selector, DefaultInputModule module, EventBus eventBus) { + public PostJobsExecutor(ScannerExtensionDictionnary selector) { this.selector = selector; - this.module = module; - this.eventBus = eventBus; } - public void execute(SensorContext context) { - Collection postJobs = selector.select(PostJob.class, module, true, null); - - eventBus.fireEvent(new PostJobPhaseEvent(new ArrayList<>(postJobs), true)); - execute(context, postJobs); - eventBus.fireEvent(new PostJobPhaseEvent(new ArrayList<>(postJobs), false)); + public void execute() { + Collection postJobs = selector.selectPostJobs(); + execute(postJobs); } - private void execute(SensorContext context, Collection postJobs) { + private static void execute(Collection postJobs) { logPostJobs(postJobs); - Project project = new Project(module); - for (PostJob postJob : postJobs) { - LOG.info("Executing post-job {}", ScannerUtils.describe(postJob)); - eventBus.fireEvent(new PostJobExecutionEvent(postJob, true)); - postJob.executeOn(project, context); - eventBus.fireEvent(new PostJobExecutionEvent(postJob, false)); + for (PostJobWrapper postJob : postJobs) { + if (postJob.shouldExecute()) { + LOG.info("Executing post-job '{}'", postJob); + postJob.execute(); + } } } - private static void logPostJobs(Collection postJobs) { + private static void logPostJobs(Collection postJobs) { if (LOG.isDebugEnabled()) { - LOG.debug(() -> "Post-jobs : " + StringUtils.join(postJobs, " -> ")); + LOG.debug(() -> "Post-jobs : " + postJobs.stream().map(Object::toString).collect(Collectors.joining(" -> "))); } } } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/ProjectAnalysisEvent.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/ProjectAnalysisEvent.java deleted file mode 100644 index fa4ee3571a1..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/ProjectAnalysisEvent.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.phases; - -import org.sonar.api.batch.events.ProjectAnalysisHandler; -import org.sonar.api.batch.fs.internal.DefaultInputModule; -import org.sonar.api.resources.Project; - -class ProjectAnalysisEvent extends AbstractPhaseEvent - implements ProjectAnalysisHandler.ProjectAnalysisEvent { - private DefaultInputModule module; - - ProjectAnalysisEvent(DefaultInputModule module, boolean start) { - super(start); - this.module = module; - } - - @Override - public Project getProject() { - return new Project(module); - } - - @Override - protected void dispatch(ProjectAnalysisHandler handler) { - handler.onProjectAnalysis(this); - } - - @Override - protected Class getType() { - return ProjectAnalysisHandler.class; - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/PublishPhaseExecutor.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/PublishPhaseExecutor.java index 41addc0b824..7ce85b92bed 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/PublishPhaseExecutor.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/PublishPhaseExecutor.java @@ -19,11 +19,8 @@ */ package org.sonar.scanner.phases; -import org.sonar.api.batch.SensorContext; import org.sonar.api.batch.fs.internal.InputModuleHierarchy; import org.sonar.scanner.cpd.CpdExecutor; -import org.sonar.scanner.events.BatchStepEvent; -import org.sonar.scanner.events.EventBus; import org.sonar.scanner.issue.ignore.scanner.IssueExclusionsLoader; import org.sonar.scanner.report.ReportPublisher; import org.sonar.scanner.rule.QProfileVerifier; @@ -33,17 +30,14 @@ import org.sonar.scanner.scm.ScmPublisher; public final class PublishPhaseExecutor extends AbstractPhaseExecutor { - private final EventBus eventBus; private final ReportPublisher reportPublisher; private final CpdExecutor cpdExecutor; private final ScmPublisher scm; - public PublishPhaseExecutor(InitializersExecutor initializersExecutor, PostJobsExecutor postJobsExecutor, SensorsExecutor sensorsExecutor, SensorContext sensorContext, - EventBus eventBus, ReportPublisher reportPublisher, DefaultModuleFileSystem fs, QProfileVerifier profileVerifier, - IssueExclusionsLoader issueExclusionsLoader, CpdExecutor cpdExecutor, ScmPublisher scm, InputModuleHierarchy hierarchy, FileIndexer fileIndexer, - CoverageExclusions coverageExclusions) { - super(initializersExecutor, postJobsExecutor, sensorsExecutor, sensorContext, hierarchy, eventBus, fs, profileVerifier, issueExclusionsLoader, fileIndexer, coverageExclusions); - this.eventBus = eventBus; + public PublishPhaseExecutor(PostJobsExecutor postJobsExecutor, SensorsExecutor sensorsExecutor, + ReportPublisher reportPublisher, DefaultModuleFileSystem fs, QProfileVerifier profileVerifier, IssueExclusionsLoader issueExclusionsLoader, + CpdExecutor cpdExecutor, ScmPublisher scm, InputModuleHierarchy hierarchy, FileIndexer fileIndexer, CoverageExclusions coverageExclusions) { + super(postJobsExecutor, sensorsExecutor, hierarchy, fs, profileVerifier, issueExclusionsLoader, fileIndexer, coverageExclusions); this.reportPublisher = reportPublisher; this.cpdExecutor = cpdExecutor; this.scm = scm; @@ -51,26 +45,12 @@ public final class PublishPhaseExecutor extends AbstractPhaseExecutor { @Override protected void executeOnRoot() { - computeDuplications(); - publishReportJob(); + cpdExecutor.execute(); + reportPublisher.execute(); } @Override protected void afterSensors() { scm.publish(); } - - private void computeDuplications() { - String stepName = "Computing duplications"; - eventBus.fireEvent(new BatchStepEvent(stepName, true)); - cpdExecutor.execute(); - eventBus.fireEvent(new BatchStepEvent(stepName, false)); - } - - private void publishReportJob() { - String stepName = "Publish report"; - eventBus.fireEvent(new BatchStepEvent(stepName, true)); - this.reportPublisher.execute(); - eventBus.fireEvent(new BatchStepEvent(stepName, false)); - } } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/SensorExecutionEvent.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/SensorExecutionEvent.java deleted file mode 100644 index 7867031d921..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/SensorExecutionEvent.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.phases; - -import org.sonar.api.batch.Sensor; -import org.sonar.api.batch.events.SensorExecutionHandler; - -class SensorExecutionEvent extends AbstractPhaseEvent - implements SensorExecutionHandler.SensorExecutionEvent { - - private final Sensor sensor; - - SensorExecutionEvent(Sensor sensor, boolean start) { - super(start); - this.sensor = sensor; - } - - @Override - public Sensor getSensor() { - return sensor; - } - - @Override - public void dispatch(SensorExecutionHandler handler) { - handler.onSensorExecution(this); - } - - @Override - public Class getType() { - return SensorExecutionHandler.class; - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/SensorsExecutor.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/SensorsExecutor.java index a20bb3497b6..2d9e06f6eb6 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/SensorsExecutor.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/SensorsExecutor.java @@ -19,73 +19,87 @@ */ package org.sonar.scanner.phases; -import com.google.common.collect.Lists; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; +import java.util.stream.Collectors; +import java.util.stream.Stream; import org.sonar.api.batch.ScannerSide; -import org.sonar.api.batch.Sensor; -import org.sonar.api.batch.SensorContext; import org.sonar.api.batch.fs.internal.DefaultInputModule; import org.sonar.api.batch.fs.internal.InputModuleHierarchy; import org.sonar.api.batch.fs.internal.SensorStrategy; -import org.sonar.api.resources.Project; +import org.sonar.api.utils.log.Logger; +import org.sonar.api.utils.log.Loggers; +import org.sonar.core.util.logs.Profiler; import org.sonar.scanner.bootstrap.ScannerExtensionDictionnary; -import org.sonar.scanner.events.EventBus; +import org.sonar.scanner.bootstrap.ScannerPluginRepository; +import org.sonar.scanner.sensor.SensorWrapper; @ScannerSide public class SensorsExecutor { + private static final Logger LOG = Loggers.get(SensorsExecutor.class); + private static final Profiler profiler = Profiler.create(LOG); private final ScannerExtensionDictionnary selector; - private final DefaultInputModule module; - private final EventBus eventBus; private final SensorStrategy strategy; + private final ScannerPluginRepository pluginRepo; private final boolean isRoot; - public SensorsExecutor(ScannerExtensionDictionnary selector, DefaultInputModule module, InputModuleHierarchy hierarchy, EventBus eventBus, SensorStrategy strategy) { + public SensorsExecutor(ScannerExtensionDictionnary selector, DefaultInputModule module, InputModuleHierarchy hierarchy, + SensorStrategy strategy, ScannerPluginRepository pluginRepo) { this.selector = selector; - this.module = module; - this.eventBus = eventBus; this.strategy = strategy; + this.pluginRepo = pluginRepo; this.isRoot = hierarchy.isRoot(module); } - public void execute(SensorContext context) { - Collection perModuleSensors = selector.selectSensors(module, false); - Collection globalSensors; + public void execute() { + Collection moduleSensors = selector.selectSensors(false); + Collection globalSensors = new ArrayList<>(); if (isRoot) { - boolean orig = strategy.isGlobal(); - strategy.setGlobal(true); - globalSensors = selector.selectSensors(module, true); - strategy.setGlobal(orig); - } else { - globalSensors = Collections.emptyList(); + withGlobalStrategy(() -> globalSensors.addAll(selector.selectSensors(true))); } - Collection allSensors = new ArrayList<>(perModuleSensors); - allSensors.addAll(globalSensors); - eventBus.fireEvent(new SensorsPhaseEvent(Lists.newArrayList(allSensors), true)); - - execute(context, perModuleSensors); + printSensors(moduleSensors, globalSensors); + execute(moduleSensors); if (isRoot) { - boolean orig = strategy.isGlobal(); - strategy.setGlobal(true); - execute(context, globalSensors); - strategy.setGlobal(orig); + withGlobalStrategy(() -> execute(globalSensors)); } + } + + private void printSensors(Collection moduleSensors, Collection globalSensors) { + String sensors = Stream + .concat(moduleSensors.stream(), globalSensors.stream()) + .map(Object::toString) + .collect(Collectors.joining(" -> ")); + LOG.debug("Sensors : {}", sensors); + } - eventBus.fireEvent(new SensorsPhaseEvent(Lists.newArrayList(allSensors), false)); + private void withGlobalStrategy(Runnable r) { + boolean orig = strategy.isGlobal(); + strategy.setGlobal(true); + r.run(); + strategy.setGlobal(orig); + } + + private void execute(Collection sensors) { + for (SensorWrapper sensor : sensors) { + String sensorName = getSensorName(sensor); + profiler.startInfo("Sensor " + sensorName); + sensor.analyse(); + profiler.stopInfo(); + } } - private void execute(SensorContext context, Collection sensors) { - for (Sensor sensor : sensors) { - executeSensor(context, sensor); + private String getSensorName(SensorWrapper sensor) { + ClassLoader cl = getSensorClassLoader(sensor); + String pluginKey = pluginRepo.getPluginKey(cl); + if (pluginKey != null) { + return sensor.toString() + " [" + pluginKey + "]"; } + return sensor.toString(); } - private void executeSensor(SensorContext context, Sensor sensor) { - eventBus.fireEvent(new SensorExecutionEvent(sensor, true)); - sensor.analyse(new Project(module), context); - eventBus.fireEvent(new SensorExecutionEvent(sensor, false)); + private static ClassLoader getSensorClassLoader(SensorWrapper sensor) { + return sensor.wrappedSensor().getClass().getClassLoader(); } } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/SensorsPhaseEvent.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/SensorsPhaseEvent.java deleted file mode 100644 index 8866875286e..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/phases/SensorsPhaseEvent.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.phases; - -import java.util.List; -import org.sonar.api.batch.Sensor; -import org.sonar.api.batch.events.SensorsPhaseHandler; - -class SensorsPhaseEvent extends AbstractPhaseEvent - implements org.sonar.api.batch.events.SensorsPhaseHandler.SensorsPhaseEvent { - - private final List sensors; - - SensorsPhaseEvent(List sensors, boolean start) { - super(start); - this.sensors = sensors; - } - - @Override - public List getSensors() { - return sensors; - } - - @Override - protected void dispatch(SensorsPhaseHandler handler) { - handler.onSensorsPhase(this); - } - - @Override - protected Class getType() { - return SensorsPhaseHandler.class; - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/postjob/PostJobOptimizer.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/postjob/PostJobOptimizer.java index 4838120ad67..c5845662c78 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/postjob/PostJobOptimizer.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/postjob/PostJobOptimizer.java @@ -23,16 +23,16 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.batch.ScannerSide; import org.sonar.api.batch.postjob.internal.DefaultPostJobDescriptor; -import org.sonar.api.config.Settings; +import org.sonar.api.config.Configuration; @ScannerSide public class PostJobOptimizer { private static final Logger LOG = LoggerFactory.getLogger(PostJobOptimizer.class); - private final Settings settings; + private final Configuration settings; - public PostJobOptimizer(Settings settings) { + public PostJobOptimizer(Configuration settings) { this.settings = settings; } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/postjob/PostJobWrapper.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/postjob/PostJobWrapper.java index 304953b255c..5565ea0caba 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/postjob/PostJobWrapper.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/postjob/PostJobWrapper.java @@ -19,17 +19,11 @@ */ package org.sonar.scanner.postjob; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.sonar.api.batch.CheckProject; import org.sonar.api.batch.postjob.PostJob; import org.sonar.api.batch.postjob.PostJobContext; import org.sonar.api.batch.postjob.internal.DefaultPostJobDescriptor; -import org.sonar.api.resources.Project; -public class PostJobWrapper implements org.sonar.api.batch.PostJob, CheckProject { - - private static final Logger LOG = LoggerFactory.getLogger(PostJobWrapper.class); +public class PostJobWrapper { private PostJob wrappedPostJob; private PostJobContext adaptor; @@ -44,22 +38,16 @@ public class PostJobWrapper implements org.sonar.api.batch.PostJob, CheckProject this.adaptor = adaptor; } - public PostJob wrappedPostJob() { - return wrappedPostJob; - } - - @Override - public boolean shouldExecuteOnProject(Project project) { + public boolean shouldExecute() { return optimizer.shouldExecute(descriptor); } - @Override - public void executeOn(Project project, org.sonar.api.batch.SensorContext context) { + public void execute() { wrappedPostJob.execute(adaptor); } @Override public String toString() { - return descriptor.name() + (LOG.isDebugEnabled() ? " (wrapped)" : ""); + return descriptor.name(); } } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/profiling/AbstractTimeProfiling.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/profiling/AbstractTimeProfiling.java deleted file mode 100644 index 98af2fb197b..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/profiling/AbstractTimeProfiling.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.profiling; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import javax.annotation.Nullable; -import org.sonar.api.utils.System2; -import org.sonar.api.utils.TimeUtils; - -public abstract class AbstractTimeProfiling { - - private final long startTime; - - private long totalTime; - - private System2 system; - - public AbstractTimeProfiling(System2 system) { - this.system = system; - this.startTime = system.now(); - } - - protected System2 system() { - return system; - } - - public long startTime() { - return startTime; - } - - public void stop() { - this.totalTime = system.now() - startTime; - } - - public long totalTime() { - return totalTime; - } - - public String totalTimeAsString() { - return TimeUtils.formatDuration(totalTime); - } - - public void setTotalTime(long totalTime) { - this.totalTime = totalTime; - } - - protected void add(AbstractTimeProfiling other) { - this.setTotalTime(this.totalTime() + other.totalTime()); - } - - static Map sortByDescendingTotalTime(Map unsorted) { - List> entries = new ArrayList<>(unsorted.entrySet()); - Collections.sort(entries, (o1, o2) -> Long.valueOf(o2.getValue().totalTime()).compareTo(o1.getValue().totalTime())); - Map sortedMap = new LinkedHashMap<>(); - for (Map.Entry entry : entries) { - sortedMap.put(entry.getKey(), entry.getValue()); - } - return sortedMap; - } - - static List truncate(Collection sortedList) { - int maxSize = 10; - List result = new ArrayList<>(maxSize); - int i = 0; - for (G item : sortedList) { - if (i >= maxSize || item.totalTime() == 0) { - return result; - } - i++; - result.add(item); - } - return result; - } - - protected void println(String msg) { - PhasesSumUpTimeProfiler.println(msg); - } - - protected void println(String text, @Nullable Double percent, AbstractTimeProfiling phaseProfiling) { - PhasesSumUpTimeProfiler.println(text, percent, phaseProfiling); - } - - protected void println(String text, AbstractTimeProfiling phaseProfiling) { - println(text, null, phaseProfiling); - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/profiling/ItemProfiling.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/profiling/ItemProfiling.java deleted file mode 100644 index 0d0bbc5b668..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/profiling/ItemProfiling.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.profiling; - -import org.sonar.api.utils.System2; - -public class ItemProfiling extends AbstractTimeProfiling { - - private final String itemName; - - public ItemProfiling(System2 system, String itemName) { - super(system); - this.itemName = itemName; - } - - public String itemName() { - return itemName; - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/profiling/ModuleProfiling.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/profiling/ModuleProfiling.java deleted file mode 100644 index b9f6f7e5b90..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/profiling/ModuleProfiling.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.profiling; - -import com.google.common.collect.Maps; -import java.util.EnumMap; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Properties; -import javax.annotation.Nullable; -import org.sonar.api.resources.Project; -import org.sonar.api.utils.System2; - -public class ModuleProfiling extends AbstractTimeProfiling { - - private Map profilingPerPhase = new EnumMap<>(Phase.class); - private Map profilingPerBatchStep = new LinkedHashMap<>(); - private final Project module; - - public ModuleProfiling(@Nullable Project module, System2 system) { - super(system); - this.module = module; - } - - public String moduleName() { - if (module != null) { - return module.getName(); - } - return null; - } - - public PhaseProfiling getProfilingPerPhase(Phase phase) { - return profilingPerPhase.get(phase); - } - - public ItemProfiling getProfilingPerBatchStep(String stepName) { - return profilingPerBatchStep.get(stepName); - } - - public void addPhaseProfiling(Phase phase) { - profilingPerPhase.put(phase, PhaseProfiling.create(system(), phase)); - } - - public void addBatchStepProfiling(String stepName) { - profilingPerBatchStep.put(stepName, new ItemProfiling(system(), stepName)); - } - - public void dump(Properties props) { - double percent = this.totalTime() / 100.0; - Map categories = Maps.newLinkedHashMap(); - categories.putAll(profilingPerPhase); - categories.putAll(profilingPerBatchStep); - - for (Map.Entry batchStep : categories.entrySet()) { - props.setProperty(batchStep.getKey().toString(), Long.toString(batchStep.getValue().totalTime())); - } - - for (Map.Entry batchStep : sortByDescendingTotalTime(categories).entrySet()) { - println(" * " + batchStep.getKey() + " execution time: ", percent, batchStep.getValue()); - } - // Breakdown per phase - for (Phase phase : Phase.values()) { - if (profilingPerPhase.containsKey(phase) && getProfilingPerPhase(phase).hasItems()) { - println(""); - println(" * " + phase + " execution time breakdown: ", getProfilingPerPhase(phase)); - getProfilingPerPhase(phase).dump(props); - } - } - } - - public void merge(ModuleProfiling other) { - super.add(other); - for (Entry entry : other.profilingPerPhase.entrySet()) { - if (!this.profilingPerPhase.containsKey(entry.getKey())) { - this.addPhaseProfiling(entry.getKey()); - } - this.getProfilingPerPhase(entry.getKey()).merge(entry.getValue()); - } - for (Map.Entry entry : other.profilingPerBatchStep.entrySet()) { - if (!this.profilingPerBatchStep.containsKey(entry.getKey())) { - profilingPerBatchStep.put(entry.getKey(), new ItemProfiling(system(), entry.getKey())); - } - this.getProfilingPerBatchStep(entry.getKey()).add(entry.getValue()); - } - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/profiling/Phase.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/profiling/Phase.java deleted file mode 100644 index cab9afd4576..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/profiling/Phase.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.profiling; - -public enum Phase { - - INIT("Initializers"), SENSOR("Sensors"), DECORATOR("Decorators"), PERSISTER("Persisters"), POSTJOB("Post-Jobs"); - - private final String label; - - Phase(String label) { - this.label = label; - } - - @Override - public String toString() { - return label; - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/profiling/PhaseProfiling.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/profiling/PhaseProfiling.java deleted file mode 100644 index 76d3ce40735..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/profiling/PhaseProfiling.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.profiling; - -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Properties; -import org.sonar.api.utils.System2; - -public class PhaseProfiling extends AbstractTimeProfiling { - - private final Phase phase; - - private Map profilingPerItem = new HashMap<>(); - - PhaseProfiling(System2 system, Phase phase) { - super(system); - this.phase = phase; - } - - public static PhaseProfiling create(System2 system, Phase phase) { - return new PhaseProfiling(system, phase); - } - - public Phase phase() { - return phase; - } - - public boolean hasItems() { - return !profilingPerItem.isEmpty(); - } - - public ItemProfiling getProfilingPerItem(Object item) { - String stringOrSimpleName = toStringOrSimpleName(item); - return profilingPerItem.get(stringOrSimpleName); - } - - public void newItemProfiling(Object item) { - String stringOrSimpleName = toStringOrSimpleName(item); - profilingPerItem.put(stringOrSimpleName, new ItemProfiling(system(), stringOrSimpleName)); - } - - public void newItemProfiling(String itemName) { - profilingPerItem.put(itemName, new ItemProfiling(system(), itemName)); - } - - public void merge(PhaseProfiling other) { - super.add(other); - for (Entry entry : other.profilingPerItem.entrySet()) { - if (!this.profilingPerItem.containsKey(entry.getKey())) { - newItemProfiling(entry.getKey()); - } - this.getProfilingPerItem(entry.getKey()).add(entry.getValue()); - } - } - - public void dump(Properties props) { - double percent = this.totalTime() / 100.0; - for (ItemProfiling itemProfiling : profilingPerItem.values()) { - props.setProperty(itemProfiling.itemName(), Long.toString(itemProfiling.totalTime())); - } - for (ItemProfiling itemProfiling : truncate(sortByDescendingTotalTime(profilingPerItem).values())) { - println(" o " + itemProfiling.itemName() + ": ", percent, itemProfiling); - } - } - - /** - * Try to use toString if it is not the default {@link Object#toString()}. Else use {@link Class#getSimpleName()} - * @param o - * @return - */ - private static String toStringOrSimpleName(Object o) { - String toString = o.toString(); - if (toString == null || toString.startsWith(o.getClass().getName())) { - return o.getClass().getSimpleName(); - } - return toString; - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/profiling/PhasesSumUpTimeProfiler.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/profiling/PhasesSumUpTimeProfiler.java deleted file mode 100644 index 4fbddb05f20..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/profiling/PhasesSumUpTimeProfiler.java +++ /dev/null @@ -1,218 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.profiling; - -import static org.sonar.scanner.profiling.AbstractTimeProfiling.sortByDescendingTotalTime; -import static org.sonar.scanner.profiling.AbstractTimeProfiling.truncate; - -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.OutputStream; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -import javax.annotation.Nullable; - -import org.apache.commons.lang.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.sonar.api.CoreProperties; -import org.sonar.api.batch.events.InitializerExecutionHandler; -import org.sonar.api.batch.events.InitializersPhaseHandler; -import org.sonar.api.batch.events.PostJobExecutionHandler; -import org.sonar.api.batch.events.PostJobsPhaseHandler; -import org.sonar.api.batch.events.ProjectAnalysisHandler; -import org.sonar.api.batch.events.SensorExecutionHandler; -import org.sonar.api.batch.events.SensorsPhaseHandler; -import org.sonar.api.resources.Project; -import org.sonar.api.utils.System2; -import org.sonar.api.utils.TimeUtils; -import org.sonar.scanner.bootstrap.GlobalProperties; -import org.sonar.scanner.events.BatchStepHandler; -import org.sonar.scanner.util.ScannerUtils; - -import com.google.common.annotations.VisibleForTesting; - -public class PhasesSumUpTimeProfiler implements ProjectAnalysisHandler, SensorExecutionHandler, PostJobExecutionHandler, - SensorsPhaseHandler, PostJobsPhaseHandler, InitializersPhaseHandler, InitializerExecutionHandler, BatchStepHandler { - - static final Logger LOG = LoggerFactory.getLogger(PhasesSumUpTimeProfiler.class); - private static final int TEXT_RIGHT_PAD = 60; - private static final int TIME_LEFT_PAD = 10; - - @VisibleForTesting - ModuleProfiling currentModuleProfiling; - - @VisibleForTesting - ModuleProfiling totalProfiling; - - private Map modulesProfilings = new HashMap<>(); - - private final System2 system; - private final File out; - - public PhasesSumUpTimeProfiler(System2 system, GlobalProperties bootstrapProps) { - String workingDirPath = StringUtils.defaultIfBlank(bootstrapProps.property(CoreProperties.WORKING_DIRECTORY), CoreProperties.WORKING_DIRECTORY_DEFAULT_VALUE); - File workingDir = new File(workingDirPath).getAbsoluteFile(); - this.out = new File(workingDir, "profiling"); - this.out.mkdirs(); - this.totalProfiling = new ModuleProfiling(null, system); - this.system = system; - } - - static void println(String msg) { - LOG.info(msg); - } - - static void println(String text, @Nullable Double percent, AbstractTimeProfiling phaseProfiling) { - StringBuilder sb = new StringBuilder(); - sb.append(StringUtils.rightPad(text, TEXT_RIGHT_PAD)).append(StringUtils.leftPad(phaseProfiling.totalTimeAsString(), TIME_LEFT_PAD)); - if (percent != null) { - sb.append(" (").append((int) (phaseProfiling.totalTime() / percent)).append("%)"); - } - println(sb.toString()); - } - - @Override - public void onProjectAnalysis(ProjectAnalysisEvent event) { - Project module = event.getProject(); - if (event.isStart()) { - currentModuleProfiling = new ModuleProfiling(module, system); - } else { - currentModuleProfiling.stop(); - modulesProfilings.put(module, currentModuleProfiling); - long moduleTotalTime = currentModuleProfiling.totalTime(); - println(""); - println(" -------- Profiling of module " + module.getName() + ": " + TimeUtils.formatDuration(moduleTotalTime) + " --------"); - println(""); - Properties props = new Properties(); - currentModuleProfiling.dump(props); - println(""); - println(" -------- End of profiling of module " + module.getName() + " --------"); - println(""); - String fileName = module.getKey() + "-profiler.properties"; - dumpToFile(props, ScannerUtils.cleanKeyForFilename(fileName)); - totalProfiling.merge(currentModuleProfiling); - if (module.getParent() == null && !module.getModules().isEmpty()) { - dumpTotalExecutionSummary(); - } - } - } - - private void dumpTotalExecutionSummary() { - totalProfiling.stop(); - long totalTime = totalProfiling.totalTime(); - println(""); - println(" ======== Profiling of total execution: " + TimeUtils.formatDuration(totalTime) + " ========"); - println(""); - println(" * Module execution time breakdown: "); - double percent = totalTime / 100.0; - for (ModuleProfiling modulesProfiling : truncate(sortByDescendingTotalTime(modulesProfilings).values())) { - println(" o " + modulesProfiling.moduleName() + " execution time: ", percent, modulesProfiling); - } - println(""); - Properties props = new Properties(); - totalProfiling.dump(props); - println(""); - println(" ======== End of profiling of total execution ========"); - println(""); - String fileName = "total-execution-profiler.properties"; - dumpToFile(props, fileName); - } - - private void dumpToFile(Properties props, String fileName) { - File file = new File(out, fileName); - try (OutputStream fos = new BufferedOutputStream(new FileOutputStream(file))) { - props.store(fos, "SonarQube"); - println("Profiling data stored in " + file.getAbsolutePath()); - } catch (Exception e) { - throw new IllegalStateException("Unable to store profiler output: " + file, e); - } - } - - @Override - public void onSensorsPhase(SensorsPhaseEvent event) { - if (event.isStart()) { - currentModuleProfiling.addPhaseProfiling(Phase.SENSOR); - } else { - currentModuleProfiling.getProfilingPerPhase(Phase.SENSOR).stop(); - } - } - - @Override - public void onSensorExecution(SensorExecutionEvent event) { - PhaseProfiling profiling = currentModuleProfiling.getProfilingPerPhase(Phase.SENSOR); - if (event.isStart()) { - profiling.newItemProfiling(event.getSensor()); - } else { - profiling.getProfilingPerItem(event.getSensor()).stop(); - } - } - - @Override - public void onPostJobsPhase(PostJobsPhaseEvent event) { - if (event.isStart()) { - currentModuleProfiling.addPhaseProfiling(Phase.POSTJOB); - } else { - currentModuleProfiling.getProfilingPerPhase(Phase.POSTJOB).stop(); - } - } - - @Override - public void onPostJobExecution(PostJobExecutionEvent event) { - PhaseProfiling profiling = currentModuleProfiling.getProfilingPerPhase(Phase.POSTJOB); - if (event.isStart()) { - profiling.newItemProfiling(event.getPostJob()); - } else { - profiling.getProfilingPerItem(event.getPostJob()).stop(); - } - } - - @Override - public void onInitializersPhase(InitializersPhaseEvent event) { - if (event.isStart()) { - currentModuleProfiling.addPhaseProfiling(Phase.INIT); - } else { - currentModuleProfiling.getProfilingPerPhase(Phase.INIT).stop(); - } - } - - @Override - public void onInitializerExecution(InitializerExecutionEvent event) { - PhaseProfiling profiling = currentModuleProfiling.getProfilingPerPhase(Phase.INIT); - if (event.isStart()) { - profiling.newItemProfiling(event.getInitializer()); - } else { - profiling.getProfilingPerItem(event.getInitializer()).stop(); - } - } - - @Override - public void onBatchStep(BatchStepEvent event) { - if (event.isStart()) { - currentModuleProfiling.addBatchStepProfiling(event.stepName()); - } else { - currentModuleProfiling.getProfilingPerBatchStep(event.stepName()).stop(); - } - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/profiling/package-info.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/profiling/package-info.java deleted file mode 100644 index 7b089c9308b..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/profiling/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.profiling; - -import javax.annotation.ParametersAreNonnullByDefault; - diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/report/CoveragePublisher.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/report/CoveragePublisher.java index 03918840be2..10fa64d3004 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/report/CoveragePublisher.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/report/CoveragePublisher.java @@ -19,10 +19,10 @@ */ package org.sonar.scanner.report; -import com.google.common.base.Function; -import com.google.common.collect.Iterables; import java.util.LinkedHashMap; import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; import javax.annotation.Nonnull; import org.apache.commons.lang.StringUtils; import org.sonar.api.batch.fs.internal.DefaultInputFile; @@ -57,7 +57,8 @@ public class CoveragePublisher implements ReportPublisherStep { (value, builder) -> builder.setConditions(Integer.parseInt(value))); applyLineMeasure(inputFile.key(), lineCount, CoreMetrics.COVERED_CONDITIONS_BY_LINE_KEY, coveragePerLine, (value, builder) -> builder.setCoveredConditions(Integer.parseInt(value))); - writer.writeComponentCoverage(inputFile.batchId(), Iterables.transform(coveragePerLine.values(), BuildCoverage.INSTANCE)); + + writer.writeComponentCoverage(inputFile.batchId(), coveragePerLine.values().stream().map(BuildCoverage.INSTANCE).collect(Collectors.toList())); } } @@ -87,7 +88,7 @@ public class CoveragePublisher implements ReportPublisherStep { void apply(String value, LineCoverage.Builder builder); } - private enum BuildCoverage implements Function { + private enum BuildCoverage implements Function { INSTANCE; @Override diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/report/MetadataPublisher.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/report/MetadataPublisher.java index 4cb964ab2c4..174ea26d78a 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/report/MetadataPublisher.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/report/MetadataPublisher.java @@ -43,8 +43,6 @@ import org.sonar.scanner.scan.ScanProperties; import org.sonar.scanner.scan.branch.BranchConfiguration; import org.sonar.scanner.scm.ScmConfiguration; -import static org.sonar.core.config.ScannerProperties.ORGANIZATION; - public class MetadataPublisher implements ReportPublisherStep { private static final Logger LOG = Loggers.get(MetadataPublisher.class); diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/rule/ModuleQProfiles.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/rule/ModuleQProfiles.java index 4e6874aebe0..83f26530f68 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/rule/ModuleQProfiles.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/rule/ModuleQProfiles.java @@ -19,18 +19,15 @@ */ package org.sonar.scanner.rule; -import org.sonar.api.utils.DateUtils; - -import org.sonarqube.ws.Qualityprofiles.SearchWsResponse.QualityProfile; -import org.sonar.api.batch.ScannerSide; - -import javax.annotation.CheckForNull; -import javax.annotation.concurrent.Immutable; - import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; +import javax.annotation.CheckForNull; +import javax.annotation.concurrent.Immutable; +import org.sonar.api.batch.ScannerSide; +import org.sonar.api.utils.DateUtils; +import org.sonarqube.ws.Qualityprofiles.SearchWsResponse.QualityProfile; /** * Lists the Quality profiles enabled on the current module. diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ModuleScanContainer.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ModuleScanContainer.java index 55a02047280..128e1fe30bc 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ModuleScanContainer.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ModuleScanContainer.java @@ -25,7 +25,6 @@ import org.sonar.api.batch.fs.internal.DefaultInputModule; import org.sonar.api.batch.fs.internal.FileMetadata; import org.sonar.api.batch.rule.CheckFactory; import org.sonar.api.issue.NoSonarFilter; -import org.sonar.api.resources.Project; import org.sonar.api.scan.filesystem.FileExclusions; import org.sonar.core.extension.CoreExtensionsInstaller; import org.sonar.core.platform.ComponentContainer; @@ -33,11 +32,7 @@ import org.sonar.scanner.DefaultFileLinesContextFactory; import org.sonar.scanner.bootstrap.ExtensionInstaller; import org.sonar.scanner.bootstrap.GlobalAnalysisMode; import org.sonar.scanner.bootstrap.ScannerExtensionDictionnary; -import org.sonar.scanner.deprecated.DeprecatedSensorContext; import org.sonar.scanner.deprecated.perspectives.ScannerPerspectives; -import org.sonar.scanner.events.EventBus; -import org.sonar.scanner.index.DefaultIndex; -import org.sonar.scanner.issue.IssuableFactory; import org.sonar.scanner.issue.IssueFilters; import org.sonar.scanner.issue.ModuleIssues; import org.sonar.scanner.issue.ignore.EnforceIssuesFilter; @@ -48,7 +43,6 @@ import org.sonar.scanner.issue.ignore.pattern.PatternMatcher; import org.sonar.scanner.issue.ignore.scanner.IssueExclusionsLoader; import org.sonar.scanner.phases.AbstractPhaseExecutor; import org.sonar.scanner.phases.CoverageExclusions; -import org.sonar.scanner.phases.InitializersExecutor; import org.sonar.scanner.phases.IssuesPhaseExecutor; import org.sonar.scanner.phases.PostJobsExecutor; import org.sonar.scanner.phases.PublishPhaseExecutor; @@ -67,10 +61,9 @@ import org.sonar.scanner.scan.filesystem.MetadataGenerator; import org.sonar.scanner.scan.filesystem.ModuleFileSystemInitializer; import org.sonar.scanner.scan.filesystem.ModuleInputComponentStore; import org.sonar.scanner.scan.report.IssuesReports; +import org.sonar.scanner.sensor.DefaultSensorContext; import org.sonar.scanner.sensor.DefaultSensorStorage; import org.sonar.scanner.sensor.SensorOptimizer; -import org.sonar.scanner.source.HighlightableBuilder; -import org.sonar.scanner.source.SymbolizableBuilder; import static org.sonar.api.batch.InstantiationStrategy.PER_PROJECT; import static org.sonar.core.extension.CoreExtensionsInstaller.noExtensionFilter; @@ -98,8 +91,6 @@ public class ModuleScanContainer extends ComponentContainer { private void addCoreComponents() { add( module.definition(), - // still injected by some plugins - new Project(module), module, MutableModuleSettings.class, new ModuleSettingsProvider()); @@ -114,11 +105,9 @@ public class ModuleScanContainer extends ComponentContainer { } add( - EventBus.class, RuleFinderCompatibility.class, PostJobsExecutor.class, SensorsExecutor.class, - InitializersExecutor.class, // file system ModuleInputComponentStore.class, @@ -138,7 +127,7 @@ public class ModuleScanContainer extends ComponentContainer { DefaultPostJobContext.class, DefaultSensorStorage.class, - DeprecatedSensorContext.class, + DefaultSensorContext.class, ScannerExtensionDictionnary.class, IssueFilters.class, CoverageExclusions.class, @@ -148,7 +137,6 @@ public class ModuleScanContainer extends ComponentContainer { CheckFactory.class, // issues - IssuableFactory.class, ModuleIssues.class, NoSonarFilter.class, @@ -162,8 +150,6 @@ public class ModuleScanContainer extends ComponentContainer { // Perspectives ScannerPerspectives.class, - HighlightableBuilder.class, - SymbolizableBuilder.class, DefaultFileLinesContextFactory.class); } @@ -177,9 +163,6 @@ public class ModuleScanContainer extends ComponentContainer { @Override protected void doAfterStart() { - DefaultIndex index = getComponentByType(DefaultIndex.class); - index.setCurrentStorage(getComponentByType(DefaultSensorStorage.class)); - getComponentByType(AbstractPhaseExecutor.class).execute(module); } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ProjectScanContainer.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ProjectScanContainer.java index 1fc6984136c..c079f64aff9 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ProjectScanContainer.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/ProjectScanContainer.java @@ -21,11 +21,9 @@ package org.sonar.scanner.scan; import com.google.common.annotations.VisibleForTesting; import javax.annotation.Nullable; -import org.sonar.api.CoreProperties; import org.sonar.api.batch.fs.internal.DefaultInputModule; import org.sonar.api.batch.fs.internal.InputModuleHierarchy; import org.sonar.api.batch.fs.internal.SensorStrategy; -import org.sonar.api.config.Settings; import org.sonar.api.resources.Languages; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.scan.filesystem.PathResolver; @@ -48,8 +46,6 @@ import org.sonar.scanner.cpd.CpdSettings; import org.sonar.scanner.cpd.index.SonarCpdBlockIndex; import org.sonar.scanner.deprecated.test.TestPlanBuilder; import org.sonar.scanner.deprecated.test.TestableBuilder; -import org.sonar.scanner.events.EventBus; -import org.sonar.scanner.index.DefaultIndex; import org.sonar.scanner.issue.DefaultProjectIssues; import org.sonar.scanner.issue.IssueCache; import org.sonar.scanner.issue.tracking.DefaultServerLineHashesLoader; @@ -58,8 +54,6 @@ import org.sonar.scanner.issue.tracking.LocalIssueTracking; import org.sonar.scanner.issue.tracking.ServerIssueRepository; import org.sonar.scanner.issue.tracking.ServerLineHashesLoader; import org.sonar.scanner.mediumtest.ScanTaskObservers; -import org.sonar.scanner.phases.PhasesTimeProfiler; -import org.sonar.scanner.profiling.PhasesSumUpTimeProfiler; import org.sonar.scanner.report.ActiveRulesPublisher; import org.sonar.scanner.report.AnalysisContextReportPublisher; import org.sonar.scanner.report.ComponentsPublisher; @@ -96,7 +90,6 @@ import org.sonar.scanner.scan.filesystem.BatchIdGenerator; import org.sonar.scanner.scan.filesystem.InputComponentStoreProvider; import org.sonar.scanner.scan.filesystem.StatusDetection; import org.sonar.scanner.scan.measure.DefaultMetricFinder; -import org.sonar.scanner.scan.measure.DeprecatedMetricFinder; import org.sonar.scanner.scan.measure.MeasureCache; import org.sonar.scanner.scm.ScmChangedFilesProvider; import org.sonar.scanner.storage.Storages; @@ -124,10 +117,6 @@ public class ProjectScanContainer extends ComponentContainer { ProjectLock lock = getComponentByType(ProjectLock.class); lock.tryLock(); getComponentByType(WorkDirectoriesInitializer.class).execute(); - Settings settings = getComponentByType(Settings.class); - if (settings != null && settings.getBoolean(CoreProperties.PROFILING_LOG_PROPERTY)) { - add(PhasesSumUpTimeProfiler.class); - } if (isTherePreviousAnalysis()) { addIssueTrackingComponents(); } @@ -142,13 +131,10 @@ public class ProjectScanContainer extends ComponentContainer { new MutableProjectReactorProvider(), ProjectBuildersExecutor.class, ProjectLock.class, - EventBus.class, - PhasesTimeProfiler.class, ResourceTypes.class, ProjectReactorValidator.class, MetricProvider.class, ProjectAnalysisInfo.class, - DefaultIndex.class, Storages.class, new RulesProvider(), new BranchConfigurationProvider(), @@ -181,7 +167,6 @@ public class ProjectScanContainer extends ComponentContainer { // metrics DefaultMetricFinder.class, - DeprecatedMetricFinder.class, // tests TestPlanBuilder.class, diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/ModuleFileSystemInitializer.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/ModuleFileSystemInitializer.java index 12872bb2e49..a1e1c5d7444 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/ModuleFileSystemInitializer.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/ModuleFileSystemInitializer.java @@ -102,7 +102,7 @@ public class ModuleFileSystemInitializer { private static void logPaths(String label, Path baseDir, List paths) { if (!paths.isEmpty()) { StringBuilder sb = new StringBuilder(label); - for (Iterator it = paths.iterator(); it.hasNext();) { + for (Iterator it = paths.iterator(); it.hasNext(); ) { Path file = it.next(); Optional relativePathToBaseDir = PathResolver.relativize(baseDir, file); if (!relativePathToBaseDir.isPresent()) { diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/StatusDetection.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/StatusDetection.java index 2479d4ec9f3..690b473464f 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/StatusDetection.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/filesystem/StatusDetection.java @@ -28,7 +28,9 @@ import org.sonar.scanner.repository.FileData; import org.sonar.scanner.repository.ProjectRepositories; import org.sonar.scanner.scm.ScmChangedFiles; -import static org.sonar.api.batch.fs.InputFile.Status.*; +import static org.sonar.api.batch.fs.InputFile.Status.ADDED; +import static org.sonar.api.batch.fs.InputFile.Status.CHANGED; +import static org.sonar.api.batch.fs.InputFile.Status.SAME; @Immutable public class StatusDetection { @@ -58,6 +60,7 @@ public class StatusDetection { /** * If possible, get the status of the provided file without initializing metadata of the file. + * * @return null if it was not possible to get the status without calculating metadata */ @CheckForNull diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/measure/DeprecatedMetricFinder.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/measure/DeprecatedMetricFinder.java deleted file mode 100644 index 792d6b5972f..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/scan/measure/DeprecatedMetricFinder.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.scan.measure; - -import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import org.sonar.api.measures.Metric; -import org.sonar.api.measures.MetricFinder; -import org.sonar.scanner.repository.MetricsRepository; - -public final class DeprecatedMetricFinder implements MetricFinder { - - private Map metricsByKey = new LinkedHashMap<>(); - private Map metricsById = new LinkedHashMap<>(); - - public DeprecatedMetricFinder(MetricsRepository metricsRepository) { - for (Metric metric : metricsRepository.metrics()) { - metricsByKey.put(metric.key(), metric); - metricsById.put(metric.getId(), metric); - } - } - - @Override - public Metric findById(int metricId) { - return metricsById.get(metricId); - } - - @Override - public Metric findByKey(String key) { - return metricsByKey.get(key); - } - - @Override - public Collection findAll(List metricKeys) { - List result = new LinkedList<>(); - for (String metricKey : metricKeys) { - Metric metric = findByKey(metricKey); - if (metric != null) { - result.add(metric); - } - } - return result; - } - - @Override - public Collection findAll() { - return metricsByKey.values(); - } -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/DefaultSensorStorage.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/DefaultSensorStorage.java index c4ca921f7ea..c798dcca98d 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/DefaultSensorStorage.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/DefaultSensorStorage.java @@ -55,7 +55,6 @@ import org.sonar.api.utils.log.Loggers; import org.sonar.core.metric.ScannerMetrics; import org.sonar.duplications.block.Block; import org.sonar.duplications.internal.pmd.PmdBlockChunker; -import org.sonar.scanner.cpd.deprecated.DefaultCpdBlockIndexer; import org.sonar.scanner.cpd.index.SonarCpdBlockIndex; import org.sonar.scanner.issue.ModuleIssues; import org.sonar.scanner.protocol.output.FileStructure; @@ -491,7 +490,18 @@ public class DefaultSensorStorage implements SensorStorage { @VisibleForTesting int getBlockSize(String languageKey) { - return settings.getInt("sonar.cpd." + languageKey + ".minimumLines").orElse(DefaultCpdBlockIndexer.getDefaultBlockSize(languageKey)); + return settings.getInt("sonar.cpd." + languageKey + ".minimumLines") + .orElse(getDefaultBlockSize(languageKey)); + } + + public static int getDefaultBlockSize(String languageKey) { + if ("cobol".equals(languageKey)) { + return 30; + } else if ("abap".equals(languageKey)) { + return 20; + } else { + return 10; + } } @Override diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/SensorWrapper.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/SensorWrapper.java index 2651d522ebb..3e42df9c1f0 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/SensorWrapper.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/sensor/SensorWrapper.java @@ -22,35 +22,31 @@ package org.sonar.scanner.sensor; import org.sonar.api.batch.sensor.Sensor; import org.sonar.api.batch.sensor.SensorContext; import org.sonar.api.batch.sensor.internal.DefaultSensorDescriptor; -import org.sonar.api.resources.Project; -public class SensorWrapper implements org.sonar.api.batch.Sensor { +public class SensorWrapper { + private final Sensor wrappedSensor; + private final SensorContext context; + private final DefaultSensorDescriptor descriptor; + private final SensorOptimizer optimizer; - private Sensor wrappedSensor; - private SensorContext adaptor; - private DefaultSensorDescriptor descriptor; - private SensorOptimizer optimizer; - - public SensorWrapper(Sensor newSensor, SensorContext adaptor, SensorOptimizer optimizer) { + public SensorWrapper(Sensor newSensor, SensorContext context, SensorOptimizer optimizer) { this.wrappedSensor = newSensor; this.optimizer = optimizer; - descriptor = new DefaultSensorDescriptor(); - newSensor.describe(descriptor); - this.adaptor = adaptor; + this.context = context; + this.descriptor = new DefaultSensorDescriptor(); + newSensor.describe(this.descriptor); } - public Sensor wrappedSensor() { - return wrappedSensor; + public boolean shouldExecute() { + return optimizer.shouldExecute(descriptor); } - @Override - public boolean shouldExecuteOnProject(Project project) { - return optimizer.shouldExecute(descriptor); + public void analyse() { + wrappedSensor.execute(context); } - @Override - public void analyse(Project module, org.sonar.api.batch.SensorContext context) { - wrappedSensor.execute(adaptor); + public Sensor wrappedSensor() { + return wrappedSensor; } @Override diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/source/DefaultHighlightable.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/source/DefaultHighlightable.java deleted file mode 100644 index f6bd026a006..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/source/DefaultHighlightable.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.source; - -import org.sonar.api.batch.AnalysisMode; -import org.sonar.api.batch.fs.InputFile; -import org.sonar.api.batch.sensor.highlighting.TypeOfText; -import org.sonar.api.batch.sensor.highlighting.internal.DefaultHighlighting; -import org.sonar.api.batch.sensor.internal.SensorStorage; -import org.sonar.api.source.Highlightable; - -/** - * @since 3.6 - */ -public class DefaultHighlightable implements Highlightable { - - private static final HighlightingBuilder NO_OP_BUILDER = new NoOpHighlightingBuilder(); - private final InputFile inputFile; - private final SensorStorage sensorStorage; - private final AnalysisMode analysisMode; - - public DefaultHighlightable(InputFile inputFile, SensorStorage sensorStorage, AnalysisMode analysisMode) { - this.inputFile = inputFile; - this.sensorStorage = sensorStorage; - this.analysisMode = analysisMode; - } - - @Override - public HighlightingBuilder newHighlighting() { - if (analysisMode.isIssues()) { - return NO_OP_BUILDER; - } - DefaultHighlighting defaultHighlighting = new DefaultHighlighting(sensorStorage); - defaultHighlighting.onFile(inputFile); - return new DefaultHighlightingBuilder(defaultHighlighting); - } - - private static final class NoOpHighlightingBuilder implements HighlightingBuilder { - @Override - public HighlightingBuilder highlight(int startOffset, int endOffset, String typeOfText) { - // Do nothing - return this; - } - - @Override - public HighlightingBuilder highlight(int startLine, int startLineOffset, int endLine, int endLineOffset, String typeOfText) { - // Do nothing - return this; - } - - @Override - public void done() { - // Do nothing - } - } - - private static class DefaultHighlightingBuilder implements HighlightingBuilder { - - private final DefaultHighlighting defaultHighlighting; - - public DefaultHighlightingBuilder(DefaultHighlighting defaultHighlighting) { - this.defaultHighlighting = defaultHighlighting; - } - - @Override - public HighlightingBuilder highlight(int startOffset, int endOffset, String typeOfText) { - TypeOfText type = TypeOfText.forCssClass(typeOfText); - defaultHighlighting.highlight(startOffset, endOffset, type); - return this; - } - - @Override - public HighlightingBuilder highlight(int startLine, int startLineOffset, int endLine, int endLineOffset, String typeOfText) { - TypeOfText type = TypeOfText.forCssClass(typeOfText); - defaultHighlighting.highlight(startLine, startLineOffset, endLine, endLineOffset, type); - return this; - } - - @Override - public void done() { - defaultHighlighting.save(); - } - } -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/source/DefaultSymbolizable.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/source/DefaultSymbolizable.java deleted file mode 100644 index ecfd5e4b350..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/source/DefaultSymbolizable.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.source; - -import java.util.Collections; -import java.util.List; -import org.sonar.api.batch.AnalysisMode; -import org.sonar.api.batch.fs.InputFile; -import org.sonar.api.batch.sensor.symbol.internal.DefaultSymbolTable; -import org.sonar.api.source.Symbol; -import org.sonar.api.source.Symbolizable; -import org.sonar.scanner.sensor.DefaultSensorStorage; - -public class DefaultSymbolizable implements Symbolizable { - - private static final NoOpSymbolTableBuilder NO_OP_SYMBOL_TABLE_BUILDER = new NoOpSymbolTableBuilder(); - private static final NoOpSymbolTable NO_OP_SYMBOL_TABLE = new NoOpSymbolTable(); - private static final NoOpSymbol NO_OP_SYMBOL = new NoOpSymbol(); - - private static final class NoOpSymbolTableBuilder implements SymbolTableBuilder { - @Override - public Symbol newSymbol(int fromOffset, int toOffset) { - return NO_OP_SYMBOL; - } - - @Override - public Symbol newSymbol(int startLine, int startLineOffset, int endLine, int endLineOffset) { - return NO_OP_SYMBOL; - } - - @Override - public void newReference(Symbol symbol, int fromOffset) { - // Do nothing - } - - @Override - public void newReference(Symbol symbol, int fromOffset, int toOffset) { - // Do nothing - } - - @Override - public void newReference(Symbol symbol, int startLine, int startLineOffset, int endLine, int endLineOffset) { - // Do nothing - } - - @Override - public SymbolTable build() { - return NO_OP_SYMBOL_TABLE; - } - } - - private static final class NoOpSymbolTable implements SymbolTable { - @Override - public List symbols() { - return Collections.emptyList(); - } - - @Override - public List references(Symbol symbol) { - return Collections.emptyList(); - } - } - - private static final class NoOpSymbol implements Symbol { - @Override - public String getFullyQualifiedName() { - return null; - } - - @Override - public int getDeclarationStartOffset() { - return 0; - } - - @Override - public int getDeclarationEndOffset() { - return 0; - } - } - - private final InputFile inputFile; - private final DefaultSensorStorage sensorStorage; - private final AnalysisMode analysisMode; - - public DefaultSymbolizable(InputFile inputFile, DefaultSensorStorage sensorStorage, AnalysisMode analysisMode) { - this.inputFile = inputFile; - this.sensorStorage = sensorStorage; - this.analysisMode = analysisMode; - } - - @Override - public SymbolTableBuilder newSymbolTableBuilder() { - if (analysisMode.isIssues()) { - return NO_OP_SYMBOL_TABLE_BUILDER; - } - return new DeprecatedDefaultSymbolTable.Builder(new DefaultSymbolTable(sensorStorage).onFile(inputFile)); - } - - @Override - public void setSymbolTable(SymbolTable symbolTable) { - if (analysisMode.isIssues()) { - // No need for symbols in issues mode - return; - } - ((DeprecatedDefaultSymbolTable) symbolTable).getWrapped().save(); - } -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/source/DeprecatedDefaultSymbol.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/source/DeprecatedDefaultSymbol.java deleted file mode 100644 index 218137fdcd3..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/source/DeprecatedDefaultSymbol.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.source; - -import org.sonar.api.batch.sensor.symbol.NewSymbol; - -public class DeprecatedDefaultSymbol implements org.sonar.api.source.Symbol { - - private final NewSymbol wrapped; - private final int length; - - public DeprecatedDefaultSymbol(NewSymbol newSymbol, int length) { - this.wrapped = newSymbol; - this.length = length; - } - - @Override - public int getDeclarationStartOffset() { - throw new UnsupportedOperationException("getDeclarationStartOffset"); - } - - @Override - public int getDeclarationEndOffset() { - throw new UnsupportedOperationException("getDeclarationEndOffset"); - } - - @Override - public String getFullyQualifiedName() { - throw new UnsupportedOperationException("getFullyQualifiedName"); - } - - public NewSymbol getWrapped() { - return wrapped; - } - - public int getLength() { - return length; - } - -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/source/DeprecatedDefaultSymbolTable.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/source/DeprecatedDefaultSymbolTable.java deleted file mode 100644 index 85fbc97e54d..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/source/DeprecatedDefaultSymbolTable.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.source; - -import java.util.List; -import org.sonar.api.batch.sensor.symbol.internal.DefaultSymbolTable; -import org.sonar.api.source.Symbol; -import org.sonar.api.source.Symbolizable; - -public class DeprecatedDefaultSymbolTable implements Symbolizable.SymbolTable { - - private final DefaultSymbolTable wrapped; - - public DeprecatedDefaultSymbolTable(DefaultSymbolTable wrapped) { - this.wrapped = wrapped; - } - - public DefaultSymbolTable getWrapped() { - return wrapped; - } - - @Override - public List symbols() { - throw new UnsupportedOperationException("symbols"); - } - - @Override - public List references(Symbol symbol) { - throw new UnsupportedOperationException("references"); - } - - public static class Builder implements Symbolizable.SymbolTableBuilder { - - private final DefaultSymbolTable symbolTable; - - public Builder(DefaultSymbolTable symbolTable) { - this.symbolTable = symbolTable; - } - - @Override - public Symbol newSymbol(int fromOffset, int toOffset) { - return new DeprecatedDefaultSymbol(symbolTable.newSymbol(fromOffset, toOffset), toOffset - fromOffset); - } - - @Override - public Symbol newSymbol(int startLine, int startLineOffset, int endLine, int endLineOffset) { - // This is wrong in case of multiline symbol bu I assume references will be added using start and end offsets so length is useless. - int length = endLineOffset - startLineOffset; - return new DeprecatedDefaultSymbol(symbolTable.newSymbol(startLine, startLineOffset, endLine, endLineOffset), length); - } - - @Override - public void newReference(Symbol symbol, int fromOffset) { - ((DeprecatedDefaultSymbol) symbol).getWrapped().newReference(fromOffset, fromOffset + ((DeprecatedDefaultSymbol) symbol).getLength()); - } - - @Override - public void newReference(Symbol symbol, int fromOffset, int toOffset) { - ((DeprecatedDefaultSymbol) symbol).getWrapped().newReference(fromOffset, toOffset); - } - - @Override - public void newReference(Symbol symbol, int startLine, int startLineOffset, int endLine, int endLineOffset) { - ((DeprecatedDefaultSymbol) symbol).getWrapped().newReference(startLine, startLineOffset, endLine, endLineOffset); - } - - @Override - public Symbolizable.SymbolTable build() { - return new DeprecatedDefaultSymbolTable(symbolTable); - } - - } -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/source/HighlightableBuilder.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/source/HighlightableBuilder.java deleted file mode 100644 index 35711ee2d9b..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/source/HighlightableBuilder.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.source; - -import javax.annotation.CheckForNull; -import org.sonar.api.batch.AnalysisMode; -import org.sonar.api.batch.fs.InputComponent; -import org.sonar.api.batch.fs.InputFile; -import org.sonar.api.batch.sensor.internal.SensorStorage; -import org.sonar.api.source.Highlightable; -import org.sonar.scanner.deprecated.perspectives.PerspectiveBuilder; - -public class HighlightableBuilder extends PerspectiveBuilder { - - private final SensorStorage sensorStorage; - private final AnalysisMode analysisMode; - - public HighlightableBuilder(SensorStorage sensorStorage, AnalysisMode analysisMode) { - super(Highlightable.class); - this.sensorStorage = sensorStorage; - this.analysisMode = analysisMode; - } - - @CheckForNull - @Override - public Highlightable loadPerspective(Class perspectiveClass, InputComponent component) { - if (component.isFile()) { - InputFile path = (InputFile) component; - return new DefaultHighlightable(path, sensorStorage, analysisMode); - } - return null; - } -} diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/source/SymbolizableBuilder.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/source/SymbolizableBuilder.java deleted file mode 100644 index 0cb3ca8a10a..00000000000 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/source/SymbolizableBuilder.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.source; - -import javax.annotation.CheckForNull; -import org.sonar.api.batch.AnalysisMode; -import org.sonar.api.batch.fs.InputComponent; -import org.sonar.api.batch.fs.InputFile; -import org.sonar.api.source.Symbolizable; -import org.sonar.scanner.deprecated.perspectives.PerspectiveBuilder; -import org.sonar.scanner.sensor.DefaultSensorStorage; - -public class SymbolizableBuilder extends PerspectiveBuilder { - - private final DefaultSensorStorage sensorStorage; - private final AnalysisMode analysisMode; - - public SymbolizableBuilder(DefaultSensorStorage sensorStorage, AnalysisMode analysisMode) { - super(Symbolizable.class); - this.sensorStorage = sensorStorage; - this.analysisMode = analysisMode; - } - - @CheckForNull - @Override - public Symbolizable loadPerspective(Class perspectiveClass, InputComponent component) { - if (component.isFile()) { - InputFile path = (InputFile) component; - return new DefaultSymbolizable(path, sensorStorage, analysisMode); - } - return null; - } -} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/ExtensionInstallerTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/ExtensionInstallerTest.java index 09cfc454a41..ef6113024c7 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/ExtensionInstallerTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/ExtensionInstallerTest.java @@ -20,13 +20,12 @@ package org.sonar.scanner.bootstrap; import java.util.Arrays; -import java.util.List; import org.apache.commons.lang.ClassUtils; import org.junit.Test; -import org.sonar.api.BatchExtension; import org.sonar.api.ExtensionProvider; -import org.sonar.api.SonarPlugin; +import org.sonar.api.Plugin; import org.sonar.api.SonarRuntime; +import org.sonar.api.batch.ScannerSide; import org.sonar.api.config.internal.MapSettings; import org.sonar.core.platform.ComponentContainer; import org.sonar.core.platform.PluginInfo; @@ -41,12 +40,8 @@ public class ExtensionInstallerTest { private GlobalAnalysisMode mode = mock(GlobalAnalysisMode.class); private ScannerPluginRepository pluginRepository = mock(ScannerPluginRepository.class); - private static SonarPlugin newPluginInstance(final Object... extensions) { - return new SonarPlugin() { - public List getExtensions() { - return Arrays.asList(extensions); - } - }; + private static Plugin newPluginInstance(final Object... extensions) { + return desc -> desc.addExtensions(Arrays.asList(extensions)); } @Test @@ -100,29 +95,34 @@ public class ExtensionInstallerTest { } } - public static class Foo implements BatchExtension { + @ScannerSide + public static class Foo { } - public static class Bar implements BatchExtension { + @ScannerSide + public static class Bar { } - public static class FooProvider extends ExtensionProvider implements BatchExtension { + @ScannerSide + public static class FooProvider extends ExtensionProvider { @Override public Object provide() { return new Foo(); } } - public static class BarProvider extends ExtensionProvider implements BatchExtension { + @ScannerSide + public static class BarProvider extends ExtensionProvider { @Override public Object provide() { return new Bar(); } } - public static class FooBarProvider extends ExtensionProvider implements BatchExtension { + @ScannerSide + public static class FooBarProvider extends ExtensionProvider { @Override public Object provide() { return Arrays.asList(new Foo(), new Bar()); diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/ExtensionUtilsTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/ExtensionUtilsTest.java index 31fe0177ac4..728ae8a1f79 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/ExtensionUtilsTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/ExtensionUtilsTest.java @@ -20,8 +20,6 @@ package org.sonar.scanner.bootstrap; import org.junit.Test; -import org.sonar.api.BatchComponent; -import org.sonar.api.batch.BatchSide; import org.sonar.api.batch.InstantiationStrategy; import org.sonar.api.batch.ScannerSide; import org.sonar.api.ce.ComputeEngineSide; @@ -33,8 +31,6 @@ public class ExtensionUtilsTest { @Test public void shouldBeBatchInstantiationStrategy() { - assertThat(ExtensionUtils.isInstantiationStrategy(BatchService.class, InstantiationStrategy.PER_BATCH)).isTrue(); - assertThat(ExtensionUtils.isInstantiationStrategy(new BatchService(), InstantiationStrategy.PER_BATCH)).isTrue(); assertThat(ExtensionUtils.isInstantiationStrategy(ProjectService.class, InstantiationStrategy.PER_BATCH)).isFalse(); assertThat(ExtensionUtils.isInstantiationStrategy(new ProjectService(), InstantiationStrategy.PER_BATCH)).isFalse(); assertThat(ExtensionUtils.isInstantiationStrategy(DefaultService.class, InstantiationStrategy.PER_BATCH)).isFalse(); @@ -46,8 +42,6 @@ public class ExtensionUtilsTest { @Test public void shouldBeProjectInstantiationStrategy() { - assertThat(ExtensionUtils.isInstantiationStrategy(BatchService.class, InstantiationStrategy.PER_PROJECT)).isFalse(); - assertThat(ExtensionUtils.isInstantiationStrategy(new BatchService(), InstantiationStrategy.PER_PROJECT)).isFalse(); assertThat(ExtensionUtils.isInstantiationStrategy(ProjectService.class, InstantiationStrategy.PER_PROJECT)).isTrue(); assertThat(ExtensionUtils.isInstantiationStrategy(new ProjectService(), InstantiationStrategy.PER_PROJECT)).isTrue(); assertThat(ExtensionUtils.isInstantiationStrategy(DefaultService.class, InstantiationStrategy.PER_PROJECT)).isTrue(); @@ -59,10 +53,7 @@ public class ExtensionUtilsTest { @Test public void testIsScannerSide() { - assertThat(ExtensionUtils.isScannerSide(BatchService.class)).isTrue(); assertThat(ExtensionUtils.isScannerSide(ScannerService.class)).isTrue(); - assertThat(ExtensionUtils.isScannerSide(new BatchService())).isTrue(); - assertThat(ExtensionUtils.isScannerSide(DeprecatedBatchService.class)).isTrue(); assertThat(ExtensionUtils.isScannerSide(ServerService.class)).isFalse(); assertThat(ExtensionUtils.isScannerSide(new ServerService())).isFalse(); @@ -70,29 +61,19 @@ public class ExtensionUtilsTest { assertThat(ExtensionUtils.isScannerSide(new ComputeEngineService())).isFalse(); } - @BatchSide - @InstantiationStrategy(InstantiationStrategy.PER_BATCH) - public static class BatchService { - - } - @ScannerSide @InstantiationStrategy(InstantiationStrategy.PER_BATCH) public static class ScannerService { } - public static class DeprecatedBatchService implements BatchComponent { - - } - - @BatchSide + @ScannerSide @InstantiationStrategy(InstantiationStrategy.PER_PROJECT) public static class ProjectService { } - @BatchSide + @ScannerSide public static class DefaultService { } diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/GlobalContainerTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/GlobalContainerTest.java index 5f15584a72e..a05a8b00f51 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/GlobalContainerTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/GlobalContainerTest.java @@ -28,7 +28,7 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.sonar.api.CoreProperties; -import org.sonar.api.batch.BatchSide; +import org.sonar.api.batch.ScannerSide; import org.sonar.api.utils.TempFolder; import org.sonar.core.util.UuidFactory; @@ -71,12 +71,12 @@ public class GlobalContainerTest { assertThat(GlobalContainer.formatTime(400)).isEqualTo("0.400 s"); } - @BatchSide + @ScannerSide public static class Foo { } - @BatchSide + @ScannerSide public static class Bar { } diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/ScannerExtensionDictionnaryTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/ScannerExtensionDictionnaryTest.java index 4621f232652..9b4956e912c 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/ScannerExtensionDictionnaryTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/bootstrap/ScannerExtensionDictionnaryTest.java @@ -20,51 +20,52 @@ package org.sonar.scanner.bootstrap; import com.google.common.collect.Lists; -import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.List; -import org.junit.Rule; +import org.junit.Before; import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.sonar.api.BatchExtension; -import org.sonar.api.batch.BuildBreaker; -import org.sonar.api.batch.CheckProject; -import org.sonar.api.batch.Decorator; +import org.picocontainer.behaviors.FieldDecorated; import org.sonar.api.batch.DependedUpon; import org.sonar.api.batch.DependsUpon; import org.sonar.api.batch.Phase; -import org.sonar.api.batch.PostJob; -import org.sonar.api.batch.Sensor; -import org.sonar.api.batch.SensorContext; -import org.sonar.api.batch.bootstrap.ProjectDefinition; -import org.sonar.api.batch.fs.internal.DefaultInputModule; +import org.sonar.api.batch.ScannerSide; +import org.sonar.api.batch.postjob.PostJob; import org.sonar.api.batch.postjob.PostJobContext; import org.sonar.api.batch.postjob.PostJobDescriptor; +import org.sonar.api.batch.postjob.internal.DefaultPostJobDescriptor; +import org.sonar.api.batch.sensor.Sensor; +import org.sonar.api.batch.sensor.SensorContext; import org.sonar.api.batch.sensor.SensorDescriptor; -import org.sonar.api.resources.Project; +import org.sonar.api.batch.sensor.internal.DefaultSensorDescriptor; import org.sonar.core.platform.ComponentContainer; import org.sonar.scanner.postjob.PostJobOptimizer; import org.sonar.scanner.sensor.DefaultSensorContext; import org.sonar.scanner.sensor.SensorOptimizer; +import org.sonar.scanner.sensor.SensorWrapper; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; public class ScannerExtensionDictionnaryTest { + private SensorOptimizer sensorOptimizer = mock(SensorOptimizer.class); + private PostJobOptimizer postJobOptimizer = mock(PostJobOptimizer.class); - @Rule - public TemporaryFolder temp = new TemporaryFolder(); + @Before + public void setUp() { + when(sensorOptimizer.shouldExecute(any(DefaultSensorDescriptor.class))).thenReturn(true); + when(postJobOptimizer.shouldExecute(any(DefaultPostJobDescriptor.class))).thenReturn(true); + } private ScannerExtensionDictionnary newSelector(Object... extensions) { ComponentContainer iocContainer = new ComponentContainer(); for (Object extension : extensions) { iocContainer.addSingleton(extension); } - return new ScannerExtensionDictionnary(iocContainer, mock(DefaultSensorContext.class), mock(SensorOptimizer.class), - mock(PostJobContext.class), - mock(PostJobOptimizer.class)); + return new ScannerExtensionDictionnary(iocContainer, mock(DefaultSensorContext.class), sensorOptimizer, postJobOptimizer, mock(PostJobContext.class)); } @Test @@ -73,13 +74,7 @@ public class ScannerExtensionDictionnaryTest { final Sensor sensor2 = new FakeSensor(); ScannerExtensionDictionnary selector = newSelector(sensor1, sensor2); - Collection sensors = selector.select(Sensor.class, null, true, new ExtensionMatcher() { - @Override - public boolean accept(Object extension) { - return extension.equals(sensor1); - } - }); - + Collection sensors = selector.select(Sensor.class, true, extension -> extension.equals(sensor1)); assertThat(sensors).contains(sensor1); assertEquals(1, sensors.size()); } @@ -88,10 +83,10 @@ public class ScannerExtensionDictionnaryTest { public void testGetFilteredExtensions() { Sensor sensor1 = new FakeSensor(); Sensor sensor2 = new FakeSensor(); - Decorator decorator = mock(Decorator.class); + FieldDecorated.Decorator decorator = mock(FieldDecorated.Decorator.class); ScannerExtensionDictionnary selector = newSelector(sensor1, sensor2, decorator); - Collection sensors = selector.select(Sensor.class, null, true, null); + Collection sensors = selector.select(Sensor.class, false, null); assertThat(sensors).containsOnly(sensor1, sensor2); } @@ -112,19 +107,18 @@ public class ScannerExtensionDictionnaryTest { child.addSingleton(c); ScannerExtensionDictionnary dictionnary = new ScannerExtensionDictionnary(child, mock(DefaultSensorContext.class), - mock(SensorOptimizer.class), mock(PostJobContext.class), - mock(PostJobOptimizer.class)); - assertThat(dictionnary.select(Sensor.class, null, true, null)).containsOnly(a, b, c); + mock(SensorOptimizer.class), mock(PostJobOptimizer.class), mock(PostJobContext.class)); + assertThat(dictionnary.select(Sensor.class, true, null)).containsOnly(a, b, c); } @Test public void sortExtensionsByDependency() { - BatchExtension a = new MethodDependentOf(null); - BatchExtension b = new MethodDependentOf(a); - BatchExtension c = new MethodDependentOf(b); + Object a = new MethodDependentOf(null); + Object b = new MethodDependentOf(a); + Object c = new MethodDependentOf(b); ScannerExtensionDictionnary selector = newSelector(b, c, a); - List extensions = Lists.newArrayList(selector.select(BatchExtension.class, null, true, null)); + List extensions = Lists.newArrayList(selector.select(Marker.class, true, null)); assertThat(extensions).hasSize(3); assertThat(extensions.get(0)).isEqualTo(a); @@ -134,11 +128,11 @@ public class ScannerExtensionDictionnaryTest { @Test public void useMethodAnnotationsToSortExtensions() { - BatchExtension a = new GeneratesSomething("foo"); - BatchExtension b = new MethodDependentOf("foo"); + Object a = new GeneratesSomething("foo"); + Object b = new MethodDependentOf("foo"); ScannerExtensionDictionnary selector = newSelector(a, b); - List extensions = Lists.newArrayList(selector.select(BatchExtension.class, null, true, null)); + List extensions = Lists.newArrayList(selector.select(Marker.class, true, null)); assertThat(extensions.size()).isEqualTo(2); assertThat(extensions.get(0)).isEqualTo(a); @@ -146,7 +140,7 @@ public class ScannerExtensionDictionnaryTest { // different initial order selector = newSelector(b, a); - extensions = Lists.newArrayList(selector.select(BatchExtension.class, null, true, null)); + extensions = Lists.newArrayList(selector.select(Marker.class, true, null)); assertThat(extensions).hasSize(2); assertThat(extensions.get(0)).isEqualTo(a); @@ -155,11 +149,11 @@ public class ScannerExtensionDictionnaryTest { @Test public void methodDependsUponCollection() { - BatchExtension a = new GeneratesSomething("foo"); - BatchExtension b = new MethodDependentOf(Arrays.asList("foo")); + Object a = new GeneratesSomething("foo"); + Object b = new MethodDependentOf(Arrays.asList("foo")); ScannerExtensionDictionnary selector = newSelector(a, b); - List extensions = Lists.newArrayList(selector.select(BatchExtension.class, null, true, null)); + List extensions = Lists.newArrayList(selector.select(Marker.class, true, null)); assertThat(extensions).hasSize(2); assertThat(extensions.get(0)).isEqualTo(a); @@ -167,7 +161,7 @@ public class ScannerExtensionDictionnaryTest { // different initial order selector = newSelector(b, a); - extensions = Lists.newArrayList(selector.select(BatchExtension.class, null, true, null)); + extensions = Lists.newArrayList(selector.select(Marker.class, true, null)); assertThat(extensions).hasSize(2); assertThat(extensions.get(0)).isEqualTo(a); @@ -176,11 +170,11 @@ public class ScannerExtensionDictionnaryTest { @Test public void methodDependsUponArray() { - BatchExtension a = new GeneratesSomething("foo"); - BatchExtension b = new MethodDependentOf(new String[] {"foo"}); + Object a = new GeneratesSomething("foo"); + Object b = new MethodDependentOf(new String[] {"foo"}); ScannerExtensionDictionnary selector = newSelector(a, b); - List extensions = Lists.newArrayList(selector.select(BatchExtension.class, null, true, null)); + List extensions = Lists.newArrayList(selector.select(Marker.class, true, null)); assertThat(extensions).hasSize(2); assertThat(extensions.get(0)).isEqualTo(a); @@ -188,7 +182,7 @@ public class ScannerExtensionDictionnaryTest { // different initial order selector = newSelector(b, a); - extensions = Lists.newArrayList(selector.select(BatchExtension.class, null, true, null)); + extensions = Lists.newArrayList(selector.select(Marker.class, true, null)); assertThat(extensions).hasSize(2); assertThat(extensions.get(0)).isEqualTo(a); @@ -197,11 +191,11 @@ public class ScannerExtensionDictionnaryTest { @Test public void useClassAnnotationsToSortExtensions() { - BatchExtension a = new ClassDependedUpon(); - BatchExtension b = new ClassDependsUpon(); + Object a = new ClassDependedUpon(); + Object b = new ClassDependsUpon(); ScannerExtensionDictionnary selector = newSelector(a, b); - List extensions = Lists.newArrayList(selector.select(BatchExtension.class, null, true, null)); + List extensions = Lists.newArrayList(selector.select(Marker.class, true, null)); assertThat(extensions).hasSize(2); assertThat(extensions.get(0)).isEqualTo(a); @@ -209,7 +203,7 @@ public class ScannerExtensionDictionnaryTest { // different initial order selector = newSelector(b, a); - extensions = Lists.newArrayList(selector.select(BatchExtension.class, null, true, null)); + extensions = Lists.newArrayList(selector.select(Marker.class, true, null)); assertThat(extensions).hasSize(2); assertThat(extensions.get(0)).isEqualTo(a); @@ -218,13 +212,13 @@ public class ScannerExtensionDictionnaryTest { @Test public void useClassAnnotationsOnInterfaces() { - BatchExtension a = new InterfaceDependedUpon() { + Object a = new InterfaceDependedUpon() { }; - BatchExtension b = new InterfaceDependsUpon() { + Object b = new InterfaceDependsUpon() { }; ScannerExtensionDictionnary selector = newSelector(a, b); - List extensions = Lists.newArrayList(selector.select(BatchExtension.class, null, true, null)); + List extensions = Lists.newArrayList(selector.select(Marker.class, true, null)); assertThat(extensions).hasSize(2); assertThat(extensions.get(0)).isEqualTo(a); @@ -232,33 +226,20 @@ public class ScannerExtensionDictionnaryTest { // different initial order selector = newSelector(b, a); - extensions = Lists.newArrayList(selector.select(BatchExtension.class, null, true, null)); + extensions = Lists.newArrayList(selector.select(Marker.class, true, null)); assertThat(extensions).hasSize(2); assertThat(extensions.get(0)).isEqualTo(a); assertThat(extensions.get(1)).isEqualTo(b); } - @Test - public void checkProject() throws IOException { - BatchExtension ok = new CheckProjectOK(); - BatchExtension ko = new CheckProjectKO(); - - ScannerExtensionDictionnary selector = newSelector(ok, ko); - List extensions = Lists.newArrayList(selector.select(BatchExtension.class, - new DefaultInputModule(ProjectDefinition.create().setKey("foo").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder())), true, null)); - - assertThat(extensions).hasSize(1); - assertThat(extensions.get(0)).isInstanceOf(CheckProjectOK.class); - } - @Test public void inheritAnnotations() { - BatchExtension a = new SubClass("foo"); - BatchExtension b = new MethodDependentOf("foo"); + Object a = new SubClass("foo"); + Object b = new MethodDependentOf("foo"); ScannerExtensionDictionnary selector = newSelector(b, a); - List extensions = Lists.newArrayList(selector.select(BatchExtension.class, null, true, null)); + List extensions = Lists.newArrayList(selector.select(Marker.class, true, null)); assertThat(extensions).hasSize(2); assertThat(extensions.get(0)).isEqualTo(a); @@ -266,7 +247,7 @@ public class ScannerExtensionDictionnaryTest { // change initial order selector = newSelector(a, b); - extensions = Lists.newArrayList(selector.select(BatchExtension.class, null, true, null)); + extensions = Lists.newArrayList(selector.select(Marker.class, true, null)); assertThat(extensions).hasSize(2); assertThat(extensions.get(0)).isEqualTo(a); @@ -276,7 +257,7 @@ public class ScannerExtensionDictionnaryTest { @Test(expected = IllegalStateException.class) public void annotatedMethodsCanNotBePrivate() { ScannerExtensionDictionnary selector = newSelector(); - BatchExtension wrong = new BatchExtension() { + Object wrong = new Object() { @DependsUpon private Object foo() { return "foo"; @@ -286,30 +267,22 @@ public class ScannerExtensionDictionnaryTest { } @Test - public void dependsUponPhaseForNewSensors() { + public void dependsUponPhaseForSensors() { PreSensor pre = new PreSensor(); NormalSensor normal = new NormalSensor(); PostSensor post = new PostSensor(); ScannerExtensionDictionnary selector = newSelector(normal, post, pre); - List extensions = Lists.newArrayList(selector.select(org.sonar.api.batch.sensor.Sensor.class, null, true, null)); - assertThat(extensions).containsExactly(pre, normal, post); - - List oldExtensions = Lists.newArrayList(selector.select(Sensor.class, null, true, null)); - assertThat(oldExtensions).extracting("wrappedSensor").containsExactly(pre, normal, post); + assertThat(selector.selectSensors(false)).extracting("wrappedSensor").containsExactly(pre, normal, post); } @Test - public void dependsUponPhaseForNewPostJob() { + public void dependsUponPhaseForPostJob() { PrePostJob pre = new PrePostJob(); NormalPostJob normal = new NormalPostJob(); ScannerExtensionDictionnary selector = newSelector(normal, pre); - List extensions = Lists.newArrayList(selector.select(org.sonar.api.batch.postjob.PostJob.class, null, true, null)); - assertThat(extensions).containsExactly(pre, normal); - - List oldExtensions = Lists.newArrayList(selector.select(PostJob.class, null, true, null)); - assertThat(oldExtensions).extracting("wrappedPostJob").containsExactly(pre, normal); + assertThat(selector.selectPostJobs()).extracting("wrappedPostJob").containsExactly(pre, normal); } @Test @@ -319,68 +292,43 @@ public class ScannerExtensionDictionnaryTest { PostSensorSubclass post = new PostSensorSubclass(); ScannerExtensionDictionnary selector = newSelector(normal, post, pre); - List extensions = Lists.newArrayList(selector.select(org.sonar.api.batch.sensor.Sensor.class, null, true, null)); + List extensions = Lists.newArrayList(selector.select(Sensor.class, true, null)); assertThat(extensions).containsExactly(pre, normal, post); } - @Test - public void buildStatusCheckersAreExecutedAfterOtherPostJobs() { - BuildBreaker checker = new BuildBreaker() { - public void executeOn(Project project, SensorContext context) { - } - }; - - ScannerExtensionDictionnary selector = newSelector(new FakePostJob(), checker, new FakePostJob()); - List extensions = Lists.newArrayList(selector.select(PostJob.class, null, true, null)); - - assertThat(extensions).hasSize(3); - assertThat(extensions.get(2)).isEqualTo(checker); - } - @Test public void selectSensors() { - FakeSensor oldSensor = new FakeSensor(); - FakeNewSensor nonGlobalSensor = new FakeNewSensor(); - FakeNewGlobalSensor globalSensor = new FakeNewGlobalSensor(); - ScannerExtensionDictionnary selector = newSelector(oldSensor, nonGlobalSensor, globalSensor); + FakeSensor nonGlobalSensor = new FakeSensor(); + FakeGlobalSensor globalSensor = new FakeGlobalSensor(); + ScannerExtensionDictionnary selector = newSelector(nonGlobalSensor, globalSensor); - // verify non-global sensors - Collection extensions = selector.selectSensors(null, false); - assertThat(extensions).hasSize(2); - assertThat(extensions).contains(oldSensor); - extensions.remove(oldSensor); + // verify non-global sensor + Collection extensions = selector.selectSensors(false); + assertThat(extensions).hasSize(1); assertThat(extensions).extracting("wrappedSensor").containsExactly(nonGlobalSensor); - // verify global sensors - extensions = selector.selectSensors(null, true); + // verify global sensor + extensions = selector.selectSensors(true); assertThat(extensions).extracting("wrappedSensor").containsExactly(globalSensor); } - class FakeSensor implements Sensor { - - public void analyse(Project project, SensorContext context) { - - } + interface Marker { - public boolean shouldExecuteOnProject(Project project) { - return true; - } } - class FakeNewSensor implements org.sonar.api.batch.sensor.Sensor { + class FakeSensor implements Sensor { - @Override - public void describe(SensorDescriptor descriptor) { - } + @Override public void describe(SensorDescriptor descriptor) { - @Override - public void execute(org.sonar.api.batch.sensor.SensorContext context) { } + @Override public void execute(SensorContext context) { + + } } - class FakeNewGlobalSensor implements org.sonar.api.batch.sensor.Sensor { + class FakeGlobalSensor implements Sensor { @Override public void describe(SensorDescriptor descriptor) { @@ -388,12 +336,12 @@ public class ScannerExtensionDictionnaryTest { } @Override - public void execute(org.sonar.api.batch.sensor.SensorContext context) { + public void execute(SensorContext context) { } } - class MethodDependentOf implements BatchExtension { + @ScannerSide class MethodDependentOf implements Marker { private Object dep; MethodDependentOf(Object o) { @@ -406,23 +354,23 @@ public class ScannerExtensionDictionnaryTest { } } - @DependsUpon("flag") - class ClassDependsUpon implements BatchExtension { + @ScannerSide + @DependsUpon("flag") class ClassDependsUpon implements Marker { } - @DependedUpon("flag") - class ClassDependedUpon implements BatchExtension { + @ScannerSide + @DependedUpon("flag") class ClassDependedUpon implements Marker { } - @DependsUpon("flag") - interface InterfaceDependsUpon extends BatchExtension { + @ScannerSide + @DependsUpon("flag") interface InterfaceDependsUpon extends Marker { } - @DependedUpon("flag") - interface InterfaceDependedUpon extends BatchExtension { + @ScannerSide + @DependedUpon("flag") interface InterfaceDependedUpon extends Marker { } - class GeneratesSomething implements BatchExtension { + @ScannerSide class GeneratesSomething implements Marker { private Object gen; GeneratesSomething(Object o) { @@ -435,33 +383,32 @@ public class ScannerExtensionDictionnaryTest { } } - class SubClass extends GeneratesSomething { + class SubClass extends GeneratesSomething implements Marker { SubClass(Object o) { super(o); } } - class NormalSensor implements org.sonar.api.batch.sensor.Sensor { + class NormalSensor implements Sensor { @Override public void describe(SensorDescriptor descriptor) { } @Override - public void execute(org.sonar.api.batch.sensor.SensorContext context) { + public void execute(SensorContext context) { } } - @Phase(name = Phase.Name.PRE) - class PreSensor implements org.sonar.api.batch.sensor.Sensor { + @Phase(name = Phase.Name.PRE) class PreSensor implements Sensor { @Override public void describe(SensorDescriptor descriptor) { } @Override - public void execute(org.sonar.api.batch.sensor.SensorContext context) { + public void execute(SensorContext context) { } } @@ -470,15 +417,14 @@ public class ScannerExtensionDictionnaryTest { } - @Phase(name = Phase.Name.POST) - class PostSensor implements org.sonar.api.batch.sensor.Sensor { + @Phase(name = Phase.Name.POST) class PostSensor implements Sensor { @Override public void describe(SensorDescriptor descriptor) { } @Override - public void execute(org.sonar.api.batch.sensor.SensorContext context) { + public void execute(SensorContext context) { } } @@ -487,24 +433,7 @@ public class ScannerExtensionDictionnaryTest { } - class CheckProjectOK implements BatchExtension, CheckProject { - public boolean shouldExecuteOnProject(Project project) { - return true; - } - } - - class CheckProjectKO implements BatchExtension, CheckProject { - public boolean shouldExecuteOnProject(Project project) { - return false; - } - } - - private class FakePostJob implements PostJob { - public void executeOn(Project project, SensorContext context) { - } - } - - class NormalPostJob implements org.sonar.api.batch.postjob.PostJob { + class NormalPostJob implements PostJob { @Override public void describe(PostJobDescriptor descriptor) { @@ -516,8 +445,7 @@ public class ScannerExtensionDictionnaryTest { } - @Phase(name = Phase.Name.PRE) - class PrePostJob implements org.sonar.api.batch.postjob.PostJob { + @Phase(name = Phase.Name.PRE) class PrePostJob implements PostJob { @Override public void describe(PostJobDescriptor descriptor) { @@ -528,5 +456,4 @@ public class ScannerExtensionDictionnaryTest { } } - } diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/cpd/CpdComponentsTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/cpd/CpdComponentsTest.java deleted file mode 100644 index 66dc7900646..00000000000 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/cpd/CpdComponentsTest.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.cpd; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class CpdComponentsTest { - - @Test - public void getExtensions() { - assertThat(CpdComponents.all().size()).isGreaterThan(0); - } -} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/cpd/DuplicationPredicatesTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/cpd/DuplicationPredicatesTest.java index 8d4947e43ef..c5a865e0f3d 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/cpd/DuplicationPredicatesTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/cpd/DuplicationPredicatesTest.java @@ -19,7 +19,7 @@ */ package org.sonar.scanner.cpd; -import com.google.common.base.Predicate; +import java.util.function.Predicate; import org.junit.Test; import org.sonar.duplications.index.CloneGroup; @@ -30,9 +30,9 @@ public class DuplicationPredicatesTest { @Test public void testNumberOfUnitsNotLessThan() { Predicate predicate = DuplicationPredicates.numberOfUnitsNotLessThan(5); - assertThat(predicate.apply(CloneGroup.builder().setLengthInUnits(6).build())).isTrue(); - assertThat(predicate.apply(CloneGroup.builder().setLengthInUnits(5).build())).isTrue(); - assertThat(predicate.apply(CloneGroup.builder().setLengthInUnits(4).build())).isFalse(); + assertThat(predicate.test(CloneGroup.builder().setLengthInUnits(6).build())).isTrue(); + assertThat(predicate.test(CloneGroup.builder().setLengthInUnits(5).build())).isTrue(); + assertThat(predicate.test(CloneGroup.builder().setLengthInUnits(4).build())).isFalse(); } } diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/cpd/deprecated/DefaultCpdBlockIndexerTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/cpd/deprecated/DefaultCpdBlockIndexerTest.java deleted file mode 100644 index 3203d77980d..00000000000 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/cpd/deprecated/DefaultCpdBlockIndexerTest.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.cpd.deprecated; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.sonar.api.config.internal.MapSettings; -import org.sonar.api.utils.log.LogTester; - -import static org.assertj.core.api.Assertions.assertThat; - -public class DefaultCpdBlockIndexerTest { - - private DefaultCpdBlockIndexer engine; - private MapSettings settings; - - @Rule - public LogTester logTester = new LogTester(); - - @Before - public void init() { - settings = new MapSettings(); - engine = new DefaultCpdBlockIndexer(null, null, settings.asConfig(), null); - } - - @Test - public void shouldLogExclusions() { - engine.logExclusions(new String[0]); - assertThat(logTester.logs()).isEmpty(); - - engine.logExclusions(new String[] {"Foo*", "**/Bar*"}); - - String message = "Copy-paste detection exclusions:" - + "\n Foo*" - + "\n **/Bar*"; - assertThat(logTester.logs()).containsExactly(message); - } - - @Test - public void shouldReturnDefaultBlockSize() { - assertThat(DefaultCpdBlockIndexer.getDefaultBlockSize("cobol")).isEqualTo(30); - assertThat(DefaultCpdBlockIndexer.getDefaultBlockSize("abap")).isEqualTo(20); - assertThat(DefaultCpdBlockIndexer.getDefaultBlockSize("other")).isEqualTo(10); - } - - @Test - public void defaultBlockSize() { - - assertThat(engine.getBlockSize("java")).isEqualTo(10); - } - - @Test - public void blockSizeForCobol() { - settings.setProperty("sonar.cpd.cobol.minimumLines", "42"); - - assertThat(engine.getBlockSize("cobol")).isEqualTo(42); - } - -} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/cpd/deprecated/DeprecatedCpdBlockIndexerSensorTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/cpd/deprecated/DeprecatedCpdBlockIndexerSensorTest.java deleted file mode 100644 index b5f8d4c5229..00000000000 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/cpd/deprecated/DeprecatedCpdBlockIndexerSensorTest.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.cpd.deprecated; - -import java.io.IOException; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.sonar.api.batch.fs.internal.DefaultFileSystem; -import org.sonar.scanner.FakeJava; - -import static org.assertj.core.api.Assertions.assertThat; - -public class DeprecatedCpdBlockIndexerSensorTest { - - @Rule - public TemporaryFolder temp = new TemporaryFolder(); - - JavaCpdBlockIndexer sonarEngine; - DefaultCpdBlockIndexer sonarBridgeEngine; - DeprecatedCpdBlockIndexerSensor sensor; - - @Before - public void setUp() throws IOException { - sonarEngine = new JavaCpdBlockIndexer(null, null, null); - sonarBridgeEngine = new DefaultCpdBlockIndexer(new CpdMappings(), null, null, null); - - DefaultFileSystem fs = new DefaultFileSystem(temp.newFolder().toPath()); - sensor = new DeprecatedCpdBlockIndexerSensor(sonarEngine, sonarBridgeEngine, fs); - } - - @Test - public void test_engine() { - assertThat(sensor.getBlockIndexer(FakeJava.KEY)).isSameAs(sonarEngine); - assertThat(sensor.getBlockIndexer("PHP")).isSameAs(sonarBridgeEngine); - } - -} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/cpd/deprecated/JavaCpdBlockIndexerTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/cpd/deprecated/JavaCpdBlockIndexerTest.java deleted file mode 100644 index 4acf685f008..00000000000 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/cpd/deprecated/JavaCpdBlockIndexerTest.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.cpd.deprecated; - -import java.io.File; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.List; -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.ArgumentCaptor; -import org.mockito.Captor; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.sonar.api.CoreProperties; -import org.sonar.api.batch.fs.FileSystem; -import org.sonar.api.batch.fs.InputFile; -import org.sonar.api.batch.fs.internal.DefaultFileSystem; -import org.sonar.api.batch.fs.internal.TestInputFileBuilder; -import org.sonar.api.config.internal.MapSettings; -import org.sonar.duplications.block.Block; -import org.sonar.scanner.cpd.index.SonarCpdBlockIndex; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; - -public class JavaCpdBlockIndexerTest { - private static final String JAVA = "java"; - - @Mock - private SonarCpdBlockIndex index; - - @Captor - private ArgumentCaptor> blockCaptor; - - private MapSettings settings; - private JavaCpdBlockIndexer engine; - private InputFile file; - - @Rule - public TemporaryFolder temp = new TemporaryFolder(); - - @Before - public void setUp() throws IOException { - MockitoAnnotations.initMocks(this); - - File baseDir = temp.newFolder(); - DefaultFileSystem fs = new DefaultFileSystem(baseDir); - file = new TestInputFileBuilder("foo", "src/ManyStatements.java") - .setModuleBaseDir(baseDir.toPath()) - .setCharset(StandardCharsets.UTF_8) - .setLanguage(JAVA).build(); - fs.add(file); - File ioFile = file.file(); - FileUtils.copyURLToFile(this.getClass().getResource("ManyStatements.java"), ioFile); - - settings = new MapSettings(); - engine = new JavaCpdBlockIndexer(fs, settings.asConfig(), index); - } - - @Test - public void languageSupported() { - JavaCpdBlockIndexer engine = new JavaCpdBlockIndexer(mock(FileSystem.class), new MapSettings().asConfig(), index); - assertThat(engine.isLanguageSupported(JAVA)).isTrue(); - assertThat(engine.isLanguageSupported("php")).isFalse(); - } - - @Test - public void testExclusions() { - settings.setProperty(CoreProperties.CPD_EXCLUSIONS, "**"); - engine.index(JAVA); - verifyZeroInteractions(index); - } - - @Test - public void testJavaIndexing() throws Exception { - engine.index(JAVA); - - verify(index).insert(eq(file), blockCaptor.capture()); - List blockList = blockCaptor.getValue(); - - assertThat(blockList).hasSize(26); - } -} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/events/BatchStepEventTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/events/BatchStepEventTest.java deleted file mode 100644 index b6cb755f70e..00000000000 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/events/BatchStepEventTest.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.events; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -public class BatchStepEventTest { - - private BatchStepEvent batchStepEvent = new BatchStepEvent("foo", true); - - @Test - public void testGetType() { - assertThat(batchStepEvent.getType()).isEqualTo(BatchStepHandler.class); - } - - @Test - public void testDispatch() { - BatchStepHandler handler = mock(BatchStepHandler.class); - batchStepEvent.dispatch(handler); - - verify(handler).onBatchStep(batchStepEvent); - } - -} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/events/EventBusTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/events/EventBusTest.java deleted file mode 100644 index cc0b5d0f2a4..00000000000 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/events/EventBusTest.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.events; - -import org.junit.Test; -import org.sonar.api.batch.events.EventHandler; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -public class EventBusTest { - - @Test - public void shouldNotifyAboutEvent() { - FirstHandler firstHandler = mock(FirstHandler.class); - SecondHandler secondHandler = mock(SecondHandler.class); - EventBus eventBus = new EventBus(new EventHandler[] { firstHandler, secondHandler }); - - FirstEvent firstEvent = new FirstEvent(); - eventBus.fireEvent(firstEvent); - SecondEvent secondEvent = new SecondEvent(); - eventBus.fireEvent(secondEvent); - - verify(firstHandler).onEvent(firstEvent); - verify(secondHandler).onEvent(secondEvent); - } - - interface FirstHandler extends EventHandler { - void onEvent(FirstEvent event); - } - - static class FirstEvent extends BatchEvent { - @Override - protected void dispatch(FirstHandler handler) { - handler.onEvent(this); - } - - @Override - public Class getType() { - return FirstHandler.class; - } - } - - interface SecondHandler extends EventHandler { - void onEvent(SecondEvent event); - } - - static class SecondEvent extends BatchEvent { - @Override - protected void dispatch(SecondHandler handler) { - handler.onEvent(this); - } - - @Override - public Class getType() { - return SecondHandler.class; - } - } - -} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/genericcoverage/StaxParserTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/genericcoverage/StaxParserTest.java new file mode 100644 index 00000000000..445cc45e90c --- /dev/null +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/genericcoverage/StaxParserTest.java @@ -0,0 +1,51 @@ +/* + * SonarQube + * Copyright (C) 2009-2018 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program 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. + * + * This program 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.scanner.genericcoverage; + +import org.codehaus.staxmate.in.SMHierarchicCursor; +import org.junit.Test; + +import javax.xml.stream.XMLStreamException; + +public class StaxParserTest { + + @Test + public void testXMLWithDTD() throws XMLStreamException { + StaxParser parser = new StaxParser(getTestHandler()); + parser.parse(getClass().getClassLoader().getResourceAsStream("org/sonar/api/utils/StaxParserTest/xml-dtd-test.xml")); + } + + @Test + public void testXMLWithXSD() throws XMLStreamException { + StaxParser parser = new StaxParser(getTestHandler()); + parser.parse(getClass().getClassLoader().getResourceAsStream("org/sonar/api/utils/StaxParserTest/xml-xsd-test.xml")); + } + + private StaxParser.XmlStreamHandler getTestHandler() { + return new StaxParser.XmlStreamHandler() { + public void stream(SMHierarchicCursor rootCursor) throws XMLStreamException { + rootCursor.advance(); + while (rootCursor.getNext() != null) { + } + } + }; + } + +} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/index/DefaultIndexTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/index/DefaultIndexTest.java deleted file mode 100644 index d76119595f2..00000000000 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/index/DefaultIndexTest.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.index; - -import java.io.IOException; -import java.util.Collections; -import org.junit.Before; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.sonar.api.CoreProperties; -import org.sonar.api.batch.bootstrap.ProjectDefinition; -import org.sonar.api.batch.fs.InputComponent; -import org.sonar.api.batch.fs.InputDir; -import org.sonar.api.batch.fs.InputFile; -import org.sonar.api.batch.fs.internal.DefaultInputDir; -import org.sonar.api.batch.fs.internal.DefaultInputModule; -import org.sonar.api.batch.fs.internal.InputComponentTree; -import org.sonar.api.batch.fs.internal.TestInputFileBuilder; -import org.sonar.api.batch.measure.MetricFinder; -import org.sonar.api.profiles.RulesProfile; -import org.sonar.api.resources.Directory; -import org.sonar.api.resources.File; -import org.sonar.api.resources.Project; -import org.sonar.api.rules.Rule; -import org.sonar.api.rules.RuleFinder; -import org.sonar.scanner.scan.filesystem.InputComponentStore; -import org.sonar.scanner.scan.measure.MeasureCache; -import org.sonar.scanner.sensor.DefaultSensorStorage; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class DefaultIndexTest { - - @org.junit.Rule - public TemporaryFolder temp = new TemporaryFolder(); - - private DefaultIndex index = null; - private Rule rule; - private RuleFinder ruleFinder; - private Project project; - private Project moduleA; - private Project moduleB; - private Project moduleB1; - private InputComponentStore componentStore; - private InputComponentTree componentTree; - - private java.io.File baseDir; - - @Before - public void createIndex() throws IOException { - ruleFinder = mock(RuleFinder.class); - componentStore = mock(InputComponentStore.class); - componentTree = mock(InputComponentTree.class); - index = new DefaultIndex(componentStore, componentTree, mock(MeasureCache.class), mock(MetricFinder.class)); - - baseDir = temp.newFolder(); - - ProjectDefinition rootDef = ProjectDefinition.create().setKey("project").setBaseDir(baseDir).setWorkDir(temp.newFolder()); - java.io.File moduleABaseDir = new java.io.File(baseDir, "moduleA"); - moduleABaseDir.mkdir(); - ProjectDefinition moduleADef = ProjectDefinition.create().setKey("moduleA").setBaseDir(moduleABaseDir).setWorkDir(temp.newFolder()); - java.io.File moduleBBaseDir = new java.io.File(baseDir, "moduleB"); - moduleBBaseDir.mkdir(); - ProjectDefinition moduleBDef = ProjectDefinition.create().setKey("moduleB").setBaseDir(moduleBBaseDir).setWorkDir(temp.newFolder()); - java.io.File moduleB1BaseDir = new java.io.File(baseDir, "moduleB/moduleB1"); - moduleB1BaseDir.mkdir(); - ProjectDefinition moduleB1Def = ProjectDefinition.create().setKey("moduleB1").setBaseDir(moduleB1BaseDir).setWorkDir(temp.newFolder()); - - rootDef.addSubProject(moduleADef); - rootDef.addSubProject(moduleBDef); - moduleBDef.addSubProject(moduleB1Def); - - project = new Project(new DefaultInputModule(rootDef)); - moduleA = new Project(new DefaultInputModule(moduleADef)); - moduleB = new Project(new DefaultInputModule(moduleBDef)); - moduleB1 = new Project(new DefaultInputModule(moduleB1Def)); - - RulesProfile rulesProfile = RulesProfile.create(); - rule = Rule.create("repoKey", "ruleKey", "Rule"); - rule.setId(1); - rulesProfile.activateRule(rule, null); - index.setCurrentStorage(mock(DefaultSensorStorage.class)); - } - - @Test - public void shouldGetHierarchy() throws IOException { - InputComponent component = new DefaultInputModule(ProjectDefinition.create().setKey("module1").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder())); - InputFile file1 = new TestInputFileBuilder("module1", "src/org/foo/Bar.java").build(); - - when(componentStore.getByKey("module1")).thenReturn(component); - when(componentStore.getByKey("module1:src/org/foo/Bar.java")).thenReturn(file1); - when(componentTree.getParent(file1)).thenReturn(component); - when(componentTree.getChildren(component)).thenReturn(Collections.singleton(file1)); - - assertThat(index.getParent("module1:src/org/foo/Bar.java").getKey()).isEqualTo("module1"); - assertThat(index.getParent("module1")).isNull(); - - assertThat(index.getChildren("module1")).containsOnly(File.create("src/org/foo/Bar.java")); - assertThat(index.getChildren("module1:src/org/foo/Bar.java")).isEmpty(); - } - - @Test - public void shouldTransformToResource() throws IOException { - DefaultInputModule component = new DefaultInputModule(ProjectDefinition.create() - .setKey("module1") - .setProperty(CoreProperties.PROJECT_BRANCH_PROPERTY, "branch1") - .setBaseDir(temp.newFolder()) - .setWorkDir(temp.newFolder()), 1); - InputFile file1 = new TestInputFileBuilder("module1", "src/org/foo/Bar.java").build(); - InputDir dir = new DefaultInputDir("module1", "src"); - - assertThat(index.toResource(component)).isInstanceOf(Project.class); - assertThat(index.toResource(component).getKey()).isEqualTo("module1"); - assertThat(index.toResource(component).getEffectiveKey()).isEqualTo("module1:branch1"); - - assertThat(index.toResource(file1)).isInstanceOf(File.class); - assertThat(index.toResource(file1).getKey()).isEqualTo("src/org/foo/Bar.java"); - assertThat(index.toResource(file1).getPath()).isEqualTo("src/org/foo/Bar.java"); - - assertThat(index.toResource(dir)).isInstanceOf(Directory.class); - assertThat(index.toResource(dir).getKey()).isEqualTo("src"); - assertThat(index.toResource(dir).getPath()).isEqualTo("src"); - } -} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/DefaultFilterableIssueTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/DefaultFilterableIssueTest.java index b7cba5eb550..4bcb8443cbe 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/DefaultFilterableIssueTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/DefaultFilterableIssueTest.java @@ -81,7 +81,7 @@ public class DefaultFilterableIssueTest { assertThat(issue.textRange().end().line()).isEqualTo(31); assertThat(issue.textRange().end().lineOffset()).isEqualTo(3); assertThat(issue.projectKey()).isEqualTo("projectKey"); - assertThat(issue.effortToFix()).isEqualTo(3.0); + assertThat(issue.gap()).isEqualTo(3.0); assertThat(issue.severity()).isEqualTo("MAJOR"); } @@ -91,6 +91,6 @@ public class DefaultFilterableIssueTest { issue = new DefaultFilterableIssue(mockedProject, projectAnalysisInfo, rawIssue, componentKey); assertThat(issue.line()).isNull(); - assertThat(issue.effortToFix()).isNull(); + assertThat(issue.gap()).isNull(); } } diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/DeprecatedIssueAdapterForFilterTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/DeprecatedIssueAdapterForFilterTest.java deleted file mode 100644 index bb2a61f3c20..00000000000 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/DeprecatedIssueAdapterForFilterTest.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.issue; - -import java.io.IOException; -import java.util.Date; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.sonar.api.batch.bootstrap.ProjectDefinition; -import org.sonar.api.batch.fs.internal.DefaultInputModule; -import org.sonar.api.issue.Issue; -import org.sonar.api.rule.RuleKey; -import org.sonar.scanner.ProjectAnalysisInfo; -import org.sonar.scanner.protocol.Constants.Severity; -import org.sonar.scanner.protocol.output.ScannerReport.TextRange; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class DeprecatedIssueAdapterForFilterTest { - - @Rule - public TemporaryFolder temp = new TemporaryFolder(); - - private static final String PROJECT_KEY = "foo"; - private static final Date ANALYSIS_DATE = new Date(); - private static final String COMPONENT_KEY = "foo:src/Foo.java"; - - @Test - public void improve_coverage() throws IOException { - DefaultInputModule module = new DefaultInputModule(ProjectDefinition.create().setKey(PROJECT_KEY).setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder())); - ProjectAnalysisInfo projectAnalysisInfo = mock(ProjectAnalysisInfo.class); - when(projectAnalysisInfo.analysisDate()).thenReturn(ANALYSIS_DATE); - - DeprecatedIssueAdapterForFilter issue = new DeprecatedIssueAdapterForFilter(module, projectAnalysisInfo, - org.sonar.scanner.protocol.output.ScannerReport.Issue.newBuilder() - .setRuleRepository("repo") - .setRuleKey("key") - .setSeverity(Severity.BLOCKER) - .setMsg("msg") - .build(), - COMPONENT_KEY); - - DeprecatedIssueAdapterForFilter issue2 = new DeprecatedIssueAdapterForFilter(module, projectAnalysisInfo, - org.sonar.scanner.protocol.output.ScannerReport.Issue.newBuilder() - .setRuleRepository("repo") - .setRuleKey("key") - .setSeverity(Severity.BLOCKER) - .setMsg("msg") - .setTextRange(TextRange.newBuilder().setStartLine(1)) - .setGap(2.0) - .build(), - COMPONENT_KEY); - - try { - issue.key(); - fail("Should be unsupported"); - } catch (Exception e) { - assertThat(e).isExactlyInstanceOf(UnsupportedOperationException.class).hasMessage("Not available for issues filters"); - } - - assertThat(issue.componentKey()).isEqualTo(COMPONENT_KEY); - assertThat(issue.ruleKey()).isEqualTo(RuleKey.of("repo", "key")); - - try { - issue.language(); - fail("Should be unsupported"); - } catch (Exception e) { - assertThat(e).isExactlyInstanceOf(UnsupportedOperationException.class).hasMessage("Not available for issues filters"); - } - - assertThat(issue.severity()).isEqualTo("BLOCKER"); - assertThat(issue.message()).isEqualTo("msg"); - assertThat(issue.line()).isNull(); - assertThat(issue2.line()).isEqualTo(1); - assertThat(issue.effortToFix()).isNull(); - assertThat(issue2.effortToFix()).isEqualTo(2.0); - assertThat(issue.status()).isEqualTo(Issue.STATUS_OPEN); - assertThat(issue.resolution()).isNull(); - - try { - issue.reporter(); - fail("Should be unsupported"); - } catch (Exception e) { - assertThat(e).isExactlyInstanceOf(UnsupportedOperationException.class).hasMessage("Not available for issues filters"); - } - - assertThat(issue.assignee()).isNull(); - assertThat(issue.creationDate()).isEqualTo(ANALYSIS_DATE); - assertThat(issue.updateDate()).isNull(); - assertThat(issue.closeDate()).isNull(); - assertThat(issue.attribute(PROJECT_KEY)).isNull(); - - try { - issue.authorLogin(); - fail("Should be unsupported"); - } catch (Exception e) { - assertThat(e).isExactlyInstanceOf(UnsupportedOperationException.class).hasMessage("Not available for issues filters"); - } - - try { - issue.comments(); - fail("Should be unsupported"); - } catch (Exception e) { - assertThat(e).isExactlyInstanceOf(UnsupportedOperationException.class).hasMessage("Not available for issues filters"); - } - - try { - issue.isNew(); - fail("Should be unsupported"); - } catch (Exception e) { - assertThat(e).isExactlyInstanceOf(UnsupportedOperationException.class).hasMessage("Not available for issues filters"); - } - - try { - issue.debt(); - fail("Should be unsupported"); - } catch (Exception e) { - assertThat(e).isExactlyInstanceOf(UnsupportedOperationException.class).hasMessage("Not available for issues filters"); - } - - assertThat(issue.projectKey()).isEqualTo(PROJECT_KEY); - - try { - issue.projectUuid(); - fail("Should be unsupported"); - } catch (Exception e) { - assertThat(e).isExactlyInstanceOf(UnsupportedOperationException.class).hasMessage("Not available for issues filters"); - } - - try { - issue.componentUuid(); - fail("Should be unsupported"); - } catch (Exception e) { - assertThat(e).isExactlyInstanceOf(UnsupportedOperationException.class).hasMessage("Not available for issues filters"); - } - - try { - issue.tags(); - fail("Should be unsupported"); - } catch (Exception e) { - assertThat(e).isExactlyInstanceOf(UnsupportedOperationException.class).hasMessage("Not available for issues filters"); - } - } - -} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/DeprecatedIssueFilterChainTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/DeprecatedIssueFilterChainTest.java deleted file mode 100644 index 1492f46f2f2..00000000000 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/DeprecatedIssueFilterChainTest.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.issue; - -import org.junit.Test; -import org.sonar.api.issue.Issue; -import org.sonar.api.issue.batch.IssueFilter; -import org.sonar.api.issue.batch.IssueFilterChain; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.mock; - -public class DeprecatedIssueFilterChainTest { - - private final Issue issue = mock(Issue.class); - - @Test - public void should_accept_when_no_filter() { - assertThat(new DeprecatedIssueFilterChain().accept(issue)).isTrue(); - } - - class PassingFilter implements IssueFilter { - @Override - public boolean accept(Issue issue, IssueFilterChain chain) { - return chain.accept(issue); - } - } - - class AcceptingFilter implements IssueFilter { - @Override - public boolean accept(Issue issue, IssueFilterChain chain) { - return true; - } - } - - class RefusingFilter implements IssueFilter { - @Override - public boolean accept(Issue issue, IssueFilterChain chain) { - return false; - } - } - - class FailingFilter implements IssueFilter { - @Override - public boolean accept(Issue issue, IssueFilterChain chain) { - fail(); - return false; - } - - } - - @Test - public void should_accept_if_all_filters_pass() { - assertThat(new DeprecatedIssueFilterChain( - new PassingFilter(), - new PassingFilter(), - new PassingFilter() - ).accept(issue)).isTrue(); - } - - @Test - public void should_accept_and_not_go_further_if_filter_accepts() { - assertThat(new DeprecatedIssueFilterChain( - new PassingFilter(), - new AcceptingFilter(), - new FailingFilter() - ).accept(issue)).isTrue(); - } - - @Test - public void should_refuse_and_not_go_further_if_filter_refuses() { - assertThat(new DeprecatedIssueFilterChain( - new PassingFilter(), - new RefusingFilter(), - new FailingFilter() - ).accept(issue)).isFalse(); - } -} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/IssuableFactoryTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/IssuableFactoryTest.java deleted file mode 100644 index 6223ce31320..00000000000 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/issue/IssuableFactoryTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.issue; - -import java.io.IOException; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.sonar.api.batch.bootstrap.ProjectDefinition; -import org.sonar.api.batch.fs.internal.DefaultInputModule; -import org.sonar.api.batch.fs.internal.TestInputFileBuilder; -import org.sonar.api.issue.Issuable; -import org.sonar.scanner.sensor.DefaultSensorContext; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -public class IssuableFactoryTest { - - @Rule - public TemporaryFolder temp = new TemporaryFolder(); - - @Test - public void file_should_be_issuable() { - IssuableFactory factory = new IssuableFactory(mock(DefaultSensorContext.class)); - Issuable issuable = factory.loadPerspective(Issuable.class, new TestInputFileBuilder("foo", "src/Foo.java").build()); - - assertThat(issuable).isNotNull(); - assertThat(issuable.issues()).isEmpty(); - } - - @Test - public void project_should_be_issuable() throws IOException { - IssuableFactory factory = new IssuableFactory(mock(DefaultSensorContext.class)); - Issuable issuable = factory.loadPerspective(Issuable.class, - new DefaultInputModule(ProjectDefinition.create().setKey("foo").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()))); - - assertThat(issuable).isNotNull(); - assertThat(issuable.issues()).isEmpty(); - } -} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/ScannerMediumTester.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/ScannerMediumTester.java index 896df555431..bae2b4a81f7 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/ScannerMediumTester.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/ScannerMediumTester.java @@ -43,7 +43,6 @@ import javax.annotation.Nullable; import org.apache.commons.io.FileUtils; import org.junit.rules.ExternalResource; import org.sonar.api.Plugin; -import org.sonar.api.batch.debt.internal.DefaultDebtModel; import org.sonar.api.measures.CoreMetrics; import org.sonar.api.measures.Metric; import org.sonar.api.rule.RuleKey; @@ -303,7 +302,6 @@ public class ScannerMediumTester extends ExternalResource { tester.projectRefProvider, tester.activeRules, tester.serverIssues, - new DefaultDebtModel(), new FakeSettingsLoader(), result) .setLogOutput(tester.logOutput) diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/coverage/CoverageMediumTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/coverage/CoverageMediumTest.java index 3099de627a8..7dcc9d5b876 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/coverage/CoverageMediumTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/coverage/CoverageMediumTest.java @@ -40,7 +40,7 @@ import static org.assertj.core.api.Assertions.tuple; public class CoverageMediumTest { - @org.junit.Rule + @Rule public TemporaryFolder temp = new TemporaryFolder(); @Rule diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/cpd/CpdMediumTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/cpd/CpdMediumTest.java index ce7764db915..06f8a143d68 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/cpd/CpdMediumTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/cpd/CpdMediumTest.java @@ -22,8 +22,7 @@ package org.sonar.scanner.mediumtest.cpd; import com.google.common.collect.ImmutableMap; import java.io.File; import java.io.IOException; -import java.util.Arrays; -import java.util.Collection; +import java.nio.charset.StandardCharsets; import java.util.List; import org.apache.commons.io.FileUtils; import org.junit.Before; @@ -31,11 +30,7 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; import org.sonar.api.batch.fs.InputFile; -import org.sonar.api.batch.fs.internal.DefaultInputFile; import org.sonar.scanner.mediumtest.LogOutputRecorder; import org.sonar.scanner.mediumtest.ScannerMediumTester; import org.sonar.scanner.mediumtest.TaskResult; @@ -46,16 +41,7 @@ import org.sonar.xoo.rule.XooRulesDefinition; import static org.assertj.core.api.Assertions.assertThat; -@RunWith(Parameterized.class) public class CpdMediumTest { - - @Parameters(name = "new api: {0}") - public static Collection data() { - return Arrays.asList(new Object[][] { - {true, false}, {true, true}, {false, false} - }); - } - @Rule public TemporaryFolder temp = new TemporaryFolder(); @@ -63,6 +49,7 @@ public class CpdMediumTest { public ExpectedException thrown = ExpectedException.none(); private LogOutputRecorder logRecorder = new LogOutputRecorder(); + private File baseDir; @Rule public ScannerMediumTester tester = new ScannerMediumTester() @@ -73,23 +60,12 @@ public class CpdMediumTest { .addActiveRule("xoo", "xoo:OneIssuePerFile", null, "One Issue Per File", null, null, null) .setLogOutput(logRecorder); - private File baseDir; - private ImmutableMap.Builder builder; - private boolean useNewSensorApi; - private boolean useDeprecatedProperty; - - public CpdMediumTest(boolean useNewSensorApi, boolean useDeprecatedProperty) { - this.useNewSensorApi = useNewSensorApi; - this.useDeprecatedProperty = useDeprecatedProperty; - } - @Before - public void prepare() throws IOException { - logRecorder.getAll().clear(); - + public void prepare() { baseDir = temp.getRoot(); + logRecorder.getAll().clear(); builder = ImmutableMap.builder() .put("sonar.task", "scan") @@ -98,9 +74,6 @@ public class CpdMediumTest { .put("sonar.projectName", "Foo Project") .put("sonar.projectVersion", "1.0-SNAPSHOT") .put("sonar.projectDescription", "Description of Foo Project"); - if (useNewSensorApi) { - builder.put(CpdTokenizerSensor.ENABLE_PROP + (useDeprecatedProperty ? ".deprecated" : ""), "true"); - } } @Test @@ -146,23 +119,23 @@ public class CpdMediumTest { InputFile inputFile2 = result.inputFile("module2/sample2.xoo"); // One clone group on each file - List duplicationGroupsFile1 = result.duplicationsFor(inputFile1); + List duplicationGroupsFile1 = result.duplicationsFor(inputFile1); assertThat(duplicationGroupsFile1).hasSize(1); - org.sonar.scanner.protocol.output.ScannerReport.Duplication cloneGroupFile1 = duplicationGroupsFile1.get(0); + ScannerReport.Duplication cloneGroupFile1 = duplicationGroupsFile1.get(0); assertThat(cloneGroupFile1.getOriginPosition().getStartLine()).isEqualTo(1); assertThat(cloneGroupFile1.getOriginPosition().getEndLine()).isEqualTo(17); assertThat(cloneGroupFile1.getDuplicateList()).hasSize(1); - assertThat(cloneGroupFile1.getDuplicate(0).getOtherFileRef()).isEqualTo(result.getReportComponent(((DefaultInputFile) inputFile2).key()).getRef()); + assertThat(cloneGroupFile1.getDuplicate(0).getOtherFileRef()).isEqualTo(result.getReportComponent((inputFile2).key()).getRef()); - List duplicationGroupsFile2 = result.duplicationsFor(inputFile2); + List duplicationGroupsFile2 = result.duplicationsFor(inputFile2); assertThat(duplicationGroupsFile2).hasSize(1); - org.sonar.scanner.protocol.output.ScannerReport.Duplication cloneGroupFile2 = duplicationGroupsFile2.get(0); + ScannerReport.Duplication cloneGroupFile2 = duplicationGroupsFile2.get(0); assertThat(cloneGroupFile2.getOriginPosition().getStartLine()).isEqualTo(1); assertThat(cloneGroupFile2.getOriginPosition().getEndLine()).isEqualTo(17); assertThat(cloneGroupFile2.getDuplicateList()).hasSize(1); - assertThat(cloneGroupFile2.getDuplicate(0).getOtherFileRef()).isEqualTo(result.getReportComponent(((DefaultInputFile) inputFile1).key()).getRef()); + assertThat(cloneGroupFile2.getDuplicate(0).getOtherFileRef()).isEqualTo(result.getReportComponent((inputFile1).key()).getRef()); assertThat(result.duplicationBlocksFor(inputFile1)).isEmpty(); } @@ -179,10 +152,10 @@ public class CpdMediumTest { + "foo\nbar\ntoto\ntiti"; File xooFile1 = new File(srcDir, "sample1.xoo"); - FileUtils.write(xooFile1, duplicatedStuff); + FileUtils.write(xooFile1, duplicatedStuff, StandardCharsets.UTF_8); File xooFile2 = new File(srcDir, "sample2.xoo"); - FileUtils.write(xooFile2, duplicatedStuff); + FileUtils.write(xooFile2, duplicatedStuff, StandardCharsets.UTF_8); TaskResult result = tester.newTask() .properties(builder @@ -198,23 +171,23 @@ public class CpdMediumTest { InputFile inputFile2 = result.inputFile("src/sample2.xoo"); // One clone group on each file - List duplicationGroupsFile1 = result.duplicationsFor(inputFile1); + List duplicationGroupsFile1 = result.duplicationsFor(inputFile1); assertThat(duplicationGroupsFile1).hasSize(1); - org.sonar.scanner.protocol.output.ScannerReport.Duplication cloneGroupFile1 = duplicationGroupsFile1.get(0); + ScannerReport.Duplication cloneGroupFile1 = duplicationGroupsFile1.get(0); assertThat(cloneGroupFile1.getOriginPosition().getStartLine()).isEqualTo(1); assertThat(cloneGroupFile1.getOriginPosition().getEndLine()).isEqualTo(17); assertThat(cloneGroupFile1.getDuplicateList()).hasSize(1); - assertThat(cloneGroupFile1.getDuplicate(0).getOtherFileRef()).isEqualTo(result.getReportComponent(((DefaultInputFile) inputFile2).key()).getRef()); + assertThat(cloneGroupFile1.getDuplicate(0).getOtherFileRef()).isEqualTo(result.getReportComponent((inputFile2).key()).getRef()); - List duplicationGroupsFile2 = result.duplicationsFor(inputFile2); + List duplicationGroupsFile2 = result.duplicationsFor(inputFile2); assertThat(duplicationGroupsFile2).hasSize(1); - org.sonar.scanner.protocol.output.ScannerReport.Duplication cloneGroupFile2 = duplicationGroupsFile2.get(0); + ScannerReport.Duplication cloneGroupFile2 = duplicationGroupsFile2.get(0); assertThat(cloneGroupFile2.getOriginPosition().getStartLine()).isEqualTo(1); assertThat(cloneGroupFile2.getOriginPosition().getEndLine()).isEqualTo(17); assertThat(cloneGroupFile2.getDuplicateList()).hasSize(1); - assertThat(cloneGroupFile2.getDuplicate(0).getOtherFileRef()).isEqualTo(result.getReportComponent(((DefaultInputFile) inputFile1).key()).getRef()); + assertThat(cloneGroupFile2.getDuplicate(0).getOtherFileRef()).isEqualTo(result.getReportComponent((inputFile1).key()).getRef()); assertThat(result.duplicationBlocksFor(inputFile1)).isEmpty(); } @@ -233,10 +206,10 @@ public class CpdMediumTest { String file2 = "string\n"; File xooFile1 = new File(srcDir, "sample1.xoo"); - FileUtils.write(xooFile1, file1); + FileUtils.write(xooFile1, file1, StandardCharsets.UTF_8); File xooFile2 = new File(srcDir, "sample2.xoo"); - FileUtils.write(xooFile2, file2); + FileUtils.write(xooFile2, file2, StandardCharsets.UTF_8); TaskResult result = tester.newTask() .properties(builder @@ -283,10 +256,10 @@ public class CpdMediumTest { InputFile inputFile1 = result.inputFile("src/sample1.xoo"); InputFile inputFile2 = result.inputFile("src/sample2.xoo"); - List duplicationGroupsFile1 = result.duplicationsFor(inputFile1); + List duplicationGroupsFile1 = result.duplicationsFor(inputFile1); assertThat(duplicationGroupsFile1).isEmpty(); - List duplicationGroupsFile2 = result.duplicationsFor(inputFile2); + List duplicationGroupsFile2 = result.duplicationsFor(inputFile2); assertThat(duplicationGroupsFile2).isEmpty(); } @@ -354,10 +327,10 @@ public class CpdMediumTest { InputFile inputFile = result.inputFile("src/sample.xoo"); // One clone group - List duplicationGroups = result.duplicationsFor(inputFile); + List duplicationGroups = result.duplicationsFor(inputFile); assertThat(duplicationGroups).hasSize(1); - org.sonar.scanner.protocol.output.ScannerReport.Duplication cloneGroup = duplicationGroups.get(0); + ScannerReport.Duplication cloneGroup = duplicationGroups.get(0); assertThat(cloneGroup.getOriginPosition().getStartLine()).isEqualTo(1); assertThat(cloneGroup.getOriginPosition().getEndLine()).isEqualTo(2); assertThat(cloneGroup.getDuplicateList()).hasSize(1); diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/deprecated/DeprecatedApiMediumTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/deprecated/DeprecatedApiMediumTest.java deleted file mode 100644 index 203dc7fc288..00000000000 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/deprecated/DeprecatedApiMediumTest.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.mediumtest.deprecated; - -import com.google.common.collect.ImmutableMap; -import java.io.File; -import java.io.IOException; -import org.apache.commons.io.FileUtils; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.sonar.scanner.mediumtest.ScannerMediumTester; -import org.sonar.scanner.mediumtest.TaskResult; -import org.sonar.xoo.XooPlugin; -import org.sonar.xoo.rule.XooRulesDefinition; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.groups.Tuple.tuple; - -public class DeprecatedApiMediumTest { - - @Rule - public TemporaryFolder temp = new TemporaryFolder(); - - @Rule - public ScannerMediumTester tester = new ScannerMediumTester() - .registerPlugin("xoo", new XooPlugin()) - .addRules(new XooRulesDefinition()) - .addDefaultQProfile("xoo", "Sonar Way") - .addActiveRule("xoo", "DeprecatedResourceApi", null, "One issue per line", "MAJOR", null, "xoo"); - - @Test - public void testIssueDetails() throws IOException { - - File baseDir = temp.getRoot(); - File srcDir = new File(baseDir, "src"); - srcDir.mkdir(); - - File xooFileInRootDir = new File(srcDir, "sample.xoo"); - FileUtils.write(xooFileInRootDir, "1\n2\n3\n4\n5\n6\n7\n8\n9\n10"); - - File xooFileInAnotherDir = new File(srcDir, "package/sample.xoo"); - FileUtils.write(xooFileInAnotherDir, "1\n2\n3\n4\n5\n6\n7\n8\n9\n10"); - - TaskResult result = tester.newTask() - .properties(ImmutableMap.builder() - .put("sonar.task", "scan") - .put("sonar.projectBaseDir", baseDir.getAbsolutePath()) - .put("sonar.projectKey", "com.foo.project") - .put("sonar.projectName", "Foo Project") - .put("sonar.projectVersion", "1.0-SNAPSHOT") - .put("sonar.projectDescription", "Description of Foo Project") - .put("sonar.sources", "src") - .build()) - .execute(); - - assertThat(result.issuesFor(result.inputFile("src/sample.xoo"))).extracting("msg", "textRange.startLine").containsOnly( - tuple("Issue created using deprecated API", 0), - tuple("Issue created using deprecated API", 1)); - assertThat(result.issuesFor(result.inputFile("src/package/sample.xoo"))).extracting("msg", "textRange.startLine").containsOnly( - tuple("Issue created using deprecated API", 0), - tuple("Issue created using deprecated API", 1)); - assertThat(result.issuesFor(result.inputDir("src"))).extracting("msg", "textRange.startLine").containsOnly( - tuple("Issue created using deprecated API", 0)); - assertThat(result.issuesFor(result.inputDir("src/package"))).extracting("msg", "textRange.startLine").containsOnly( - tuple("Issue created using deprecated API", 0)); - - } - - @Test - public void createIssueOnRootDir() throws IOException { - - File baseDir = temp.getRoot(); - - File xooFileInRootDir = new File(baseDir, "sample.xoo"); - FileUtils.write(xooFileInRootDir, "1\n2\n3\n4\n5\n6\n7\n8\n9\n10"); - - File xooFileInAnotherDir = new File(baseDir, "package/sample.xoo"); - FileUtils.write(xooFileInAnotherDir, "1\n2\n3\n4\n5\n6\n7\n8\n9\n10"); - - TaskResult result = tester.newTask() - .properties(ImmutableMap.builder() - .put("sonar.task", "scan") - .put("sonar.projectBaseDir", baseDir.getAbsolutePath()) - .put("sonar.projectKey", "com.foo.project") - .put("sonar.projectName", "Foo Project") - .put("sonar.projectVersion", "1.0-SNAPSHOT") - .put("sonar.projectDescription", "Description of Foo Project") - .put("sonar.sources", ".") - .build()) - .execute(); - - assertThat(result.issuesFor(result.inputFile("sample.xoo"))).extracting("msg", "textRange.startLine").containsOnly( - tuple("Issue created using deprecated API", 0), - tuple("Issue created using deprecated API", 1)); - assertThat(result.issuesFor(result.inputFile("package/sample.xoo"))).extracting("msg", "textRange.startLine").containsOnly( - tuple("Issue created using deprecated API", 0), - tuple("Issue created using deprecated API", 1)); - assertThat(result.issuesFor(result.inputDir(""))).extracting("msg", "textRange.startLine").containsOnly( - tuple("Issue created using deprecated API", 0)); - assertThat(result.issuesFor(result.inputDir("package"))).extracting("msg", "textRange.startLine").containsOnly( - tuple("Issue created using deprecated API", 0)); - - } - -} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/tasks/TasksMediumTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/tasks/TasksMediumTest.java index 189200a268c..c64aa5ef184 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/tasks/TasksMediumTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/tasks/TasksMediumTest.java @@ -20,13 +20,11 @@ package org.sonar.scanner.mediumtest.tasks; import com.google.common.collect.ImmutableMap; -import java.util.Arrays; -import java.util.List; import org.assertj.core.api.Condition; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.sonar.api.SonarPlugin; +import org.sonar.api.Plugin; import org.sonar.api.task.Task; import org.sonar.api.task.TaskDefinition; import org.sonar.api.utils.MessageException; @@ -83,13 +81,11 @@ public class TasksMediumTest { .execute(); } - private static class FakeTaskPlugin extends SonarPlugin { + private static class FakeTaskPlugin implements Plugin { - @Override - public List getExtensions() { - return Arrays.asList(FakeTask.DEF, FakeTask.class, BrokenTask.DEF, BrokenTask.class); + @Override public void define(Context context) { + context.addExtensions(FakeTask.DEF, FakeTask.class, BrokenTask.DEF, BrokenTask.class); } - } private static class FakeTask implements Task { diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/tests/CoveragePerTestMediumTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/tests/CoveragePerTestMediumTest.java index c37406032e7..7c31bdfdab5 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/tests/CoveragePerTestMediumTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/mediumtest/tests/CoveragePerTestMediumTest.java @@ -22,6 +22,7 @@ package org.sonar.scanner.mediumtest.tests; import com.google.common.collect.ImmutableMap; import java.io.File; import java.io.IOException; +import java.nio.charset.StandardCharsets; import org.apache.commons.io.FileUtils; import org.hamcrest.Description; import org.hamcrest.TypeSafeMatcher; @@ -56,7 +57,7 @@ public class CoveragePerTestMediumTest { File srcDir = new File(baseDir, "src"); File coverageFile = new File(srcDir, "sample.xoo.coverage"); - FileUtils.write(coverageFile, "0:2\n"); + FileUtils.write(coverageFile, "0:2\n", StandardCharsets.UTF_8); exception.expect(IllegalStateException.class); exception.expectMessage("Error processing line 1 of file"); @@ -84,11 +85,11 @@ public class CoveragePerTestMediumTest { File xooTestExecutionFile = new File(testDir, "sampleTest.xoo.test"); FileUtils.write(xooTestExecutionFile, "some test:4:::OK:UNIT\n" + "another test:10:::OK:UNIT\n" + - "test without coverage:10:::OK:UNIT\n"); + "test without coverage:10:::OK:UNIT\n", StandardCharsets.UTF_8); File xooCoveragePerTestFile = new File(testDir, "sampleTest.xoo.testcoverage"); FileUtils.write(xooCoveragePerTestFile, "some test;src/sample.xoo,10,11;src/sample2.xoo,1,2\n" + - "another test;src/sample.xoo,10,20\n"); + "another test;src/sample.xoo,10,20\n", StandardCharsets.UTF_8); TaskResult result = runTask(baseDir); @@ -129,16 +130,16 @@ public class CoveragePerTestMediumTest { testDir.mkdir(); File xooFile = new File(srcDir, "sample.xoo"); - FileUtils.write(xooFile, "foo"); + FileUtils.write(xooFile, "foo", StandardCharsets.UTF_8); File xooFile2 = new File(srcDir, "sample2.xoo"); - FileUtils.write(xooFile2, "foo"); + FileUtils.write(xooFile2, "foo", StandardCharsets.UTF_8); File xooTestFile = new File(testDir, "sampleTest.xoo"); - FileUtils.write(xooTestFile, "failure\nerror\nok\nskipped"); + FileUtils.write(xooTestFile, "failure\nerror\nok\nskipped", StandardCharsets.UTF_8); File xooTestFile2 = new File(testDir, "sample2Test.xoo"); - FileUtils.write(xooTestFile2, "test file tests"); + FileUtils.write(xooTestFile2, "test file tests", StandardCharsets.UTF_8); return baseDir; } diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/phases/PostJobsExecutorTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/phases/PostJobsExecutorTest.java index f8ef008f86e..4cd517ccd6c 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/phases/PostJobsExecutorTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/phases/PostJobsExecutorTest.java @@ -19,51 +19,38 @@ */ package org.sonar.scanner.phases; -import java.io.IOException; import java.util.Arrays; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.sonar.api.batch.PostJob; -import org.sonar.api.batch.SensorContext; -import org.sonar.api.batch.bootstrap.ProjectDefinition; -import org.sonar.api.batch.fs.internal.DefaultInputModule; -import org.sonar.api.resources.Project; import org.sonar.scanner.bootstrap.ScannerExtensionDictionnary; -import org.sonar.scanner.events.EventBus; +import org.sonar.scanner.postjob.PostJobWrapper; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; public class PostJobsExecutorTest { - @Rule - public TemporaryFolder temp = new TemporaryFolder(); - private PostJobsExecutor executor; - private DefaultInputModule module; private ScannerExtensionDictionnary selector = mock(ScannerExtensionDictionnary.class); - private PostJob job1 = mock(PostJob.class); - private PostJob job2 = mock(PostJob.class); - private SensorContext context = mock(SensorContext.class); + private PostJobWrapper job1 = mock(PostJobWrapper.class); + private PostJobWrapper job2 = mock(PostJobWrapper.class); @Before - public void setUp() throws IOException { - module = new DefaultInputModule(ProjectDefinition.create().setKey("project").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder())); - executor = new PostJobsExecutor(selector, module, mock(EventBus.class)); + public void setUp() { + executor = new PostJobsExecutor(selector); } @Test public void should_execute_post_jobs() { - when(selector.select(PostJob.class, module, true, null)).thenReturn(Arrays.asList(job1, job2)); - - executor.execute(context); - - verify(job1).executeOn(any(Project.class), eq(context)); - verify(job2).executeOn(any(Project.class), eq(context)); + when(selector.selectPostJobs()).thenReturn(Arrays.asList(job1, job2)); + when(job1.shouldExecute()).thenReturn(true); + executor.execute(); + + verify(job1).shouldExecute(); + verify(job2).shouldExecute(); + verify(job1).execute(); + verifyNoMoreInteractions(job1, job2); } } diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/phases/SensorsExecutorTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/phases/SensorsExecutorTest.java index 1ea486c1a90..1ad8061dc8f 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/phases/SensorsExecutorTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/phases/SensorsExecutorTest.java @@ -25,21 +25,20 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; -import org.sonar.api.batch.Sensor; -import org.sonar.api.batch.SensorContext; import org.sonar.api.batch.bootstrap.ProjectDefinition; import org.sonar.api.batch.fs.internal.DefaultInputModule; import org.sonar.api.batch.fs.internal.InputModuleHierarchy; import org.sonar.api.batch.fs.internal.SensorStrategy; import org.sonar.api.batch.fs.internal.TestInputFileBuilder; -import org.sonar.api.resources.Project; +import org.sonar.api.batch.sensor.Sensor; import org.sonar.scanner.bootstrap.ScannerExtensionDictionnary; -import org.sonar.scanner.events.EventBus; +import org.sonar.scanner.bootstrap.ScannerPluginRepository; +import org.sonar.scanner.sensor.SensorWrapper; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; public class SensorsExecutorTest { @@ -48,42 +47,26 @@ public class SensorsExecutorTest { private SensorsExecutor rootModuleExecutor; private SensorsExecutor subModuleExecutor; - private SensorContext context; private SensorStrategy strategy = new SensorStrategy(); - private TestSensor perModuleSensor = new TestSensor(strategy); - private TestSensor globalSensor = new TestSensor(strategy); - - static class TestSensor implements Sensor { - final SensorStrategy strategy; - - boolean called; - boolean global; - - TestSensor(SensorStrategy strategy) { - this.strategy = strategy; - } - - @Override - public boolean shouldExecuteOnProject(Project project) { - return true; - } - - @Override - public void analyse(Project module, SensorContext context) { - called = true; - global = strategy.isGlobal(); - } - } + private SensorWrapper perModuleSensor = mock(SensorWrapper.class); + private SensorWrapper globalSensor = mock(SensorWrapper.class); + private ScannerPluginRepository pluginRepository = mock(ScannerPluginRepository.class); @Before public void setUp() throws IOException { - context = mock(SensorContext.class); + when(perModuleSensor.isGlobal()).thenReturn(false); + when(perModuleSensor.shouldExecute()).thenReturn(true); + when(perModuleSensor.wrappedSensor()).thenReturn(mock(Sensor.class)); + + when(globalSensor.isGlobal()).thenReturn(true); + when(globalSensor.shouldExecute()).thenReturn(true); + when(globalSensor.wrappedSensor()).thenReturn(mock(Sensor.class)); ScannerExtensionDictionnary selector = mock(ScannerExtensionDictionnary.class); - when(selector.selectSensors(any(DefaultInputModule.class), eq(false))).thenReturn(Collections.singleton(perModuleSensor)); - when(selector.selectSensors(any(DefaultInputModule.class), eq(true))).thenReturn(Collections.singleton(globalSensor)); + when(selector.selectSensors(false)).thenReturn(Collections.singleton(perModuleSensor)); + when(selector.selectSensors(true)).thenReturn(Collections.singleton(globalSensor)); ProjectDefinition childDef = ProjectDefinition.create().setKey("sub").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()); ProjectDefinition rootDef = ProjectDefinition.create().setKey("root").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()); @@ -94,26 +77,31 @@ public class SensorsExecutorTest { InputModuleHierarchy hierarchy = mock(InputModuleHierarchy.class); when(hierarchy.isRoot(rootModule)).thenReturn(true); - rootModuleExecutor = new SensorsExecutor(selector, rootModule, hierarchy, mock(EventBus.class), strategy); - subModuleExecutor = new SensorsExecutor(selector, subModule, hierarchy, mock(EventBus.class), strategy); + rootModuleExecutor = new SensorsExecutor(selector, rootModule, hierarchy, strategy, pluginRepository); + subModuleExecutor = new SensorsExecutor(selector, subModule, hierarchy, strategy, pluginRepository); } @Test public void should_not_execute_global_sensor_for_submodule() { - subModuleExecutor.execute(context); + subModuleExecutor.execute(); + + verify(perModuleSensor).analyse(); + verify(perModuleSensor).wrappedSensor(); - assertThat(perModuleSensor.called).isTrue(); - assertThat(perModuleSensor.global).isFalse(); - assertThat(globalSensor.called).isFalse(); + verifyZeroInteractions(globalSensor); + verifyNoMoreInteractions(perModuleSensor, globalSensor); } @Test public void should_execute_all_sensors_for_root_module() { - rootModuleExecutor.execute(context); + rootModuleExecutor.execute(); + + verify(globalSensor).wrappedSensor(); + verify(perModuleSensor).wrappedSensor(); + + verify(globalSensor).analyse(); + verify(perModuleSensor).analyse(); - assertThat(perModuleSensor.called).isTrue(); - assertThat(perModuleSensor.global).isFalse(); - assertThat(globalSensor.called).isTrue(); - assertThat(globalSensor.global).isTrue(); + verifyNoMoreInteractions(perModuleSensor, globalSensor); } } diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/postjob/PostJobOptimizerTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/postjob/PostJobOptimizerTest.java index d51a0ea47f4..f148c43c809 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/postjob/PostJobOptimizerTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/postjob/PostJobOptimizerTest.java @@ -35,18 +35,18 @@ public class PostJobOptimizerTest { public ExpectedException thrown = ExpectedException.none(); private PostJobOptimizer optimizer; - private Settings settings; + private MapSettings settings; @Before public void prepare() { settings = new MapSettings(); - optimizer = new PostJobOptimizer(settings); } @Test public void should_run_analyzer_with_no_metadata() { DefaultPostJobDescriptor descriptor = new DefaultPostJobDescriptor(); + optimizer = new PostJobOptimizer(settings.asConfig()); assertThat(optimizer.shouldExecute(descriptor)).isTrue(); } @@ -54,9 +54,11 @@ public class PostJobOptimizerTest { public void should_optimize_on_settings() { DefaultPostJobDescriptor descriptor = new DefaultPostJobDescriptor() .requireProperty("sonar.foo.reportPath"); + optimizer = new PostJobOptimizer(settings.asConfig()); assertThat(optimizer.shouldExecute(descriptor)).isFalse(); settings.setProperty("sonar.foo.reportPath", "foo"); + optimizer = new PostJobOptimizer(settings.asConfig()); assertThat(optimizer.shouldExecute(descriptor)).isTrue(); } } diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/profiling/PhasesSumUpTimeProfilerTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/profiling/PhasesSumUpTimeProfilerTest.java deleted file mode 100644 index 07f47435daa..00000000000 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/profiling/PhasesSumUpTimeProfilerTest.java +++ /dev/null @@ -1,364 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.profiling; - -import com.google.common.collect.Maps; -import java.io.IOException; -import java.util.List; -import java.util.Map; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.sonar.api.CoreProperties; -import org.sonar.api.batch.Initializer; -import org.sonar.api.batch.PostJob; -import org.sonar.api.batch.Sensor; -import org.sonar.api.batch.SensorContext; -import org.sonar.api.batch.bootstrap.ProjectDefinition; -import org.sonar.api.batch.events.InitializerExecutionHandler; -import org.sonar.api.batch.events.InitializersPhaseHandler; -import org.sonar.api.batch.events.PostJobExecutionHandler; -import org.sonar.api.batch.events.PostJobsPhaseHandler; -import org.sonar.api.batch.events.ProjectAnalysisHandler; -import org.sonar.api.batch.events.ProjectAnalysisHandler.ProjectAnalysisEvent; -import org.sonar.api.batch.events.SensorExecutionHandler; -import org.sonar.api.batch.events.SensorExecutionHandler.SensorExecutionEvent; -import org.sonar.api.batch.events.SensorsPhaseHandler; -import org.sonar.api.batch.events.SensorsPhaseHandler.SensorsPhaseEvent; -import org.sonar.api.batch.fs.internal.DefaultInputModule; -import org.sonar.api.resources.Project; -import org.sonar.api.utils.System2; -import org.sonar.scanner.bootstrap.GlobalProperties; -import org.sonar.scanner.events.BatchStepEvent; - -import static org.assertj.core.api.Assertions.assertThat; - -public class PhasesSumUpTimeProfilerTest { - - @Rule - public TemporaryFolder temp = new TemporaryFolder(); - - private MockedSystem clock; - private PhasesSumUpTimeProfiler profiler; - - @Before - public void prepare() throws Exception { - clock = new MockedSystem(); - Map props = Maps.newHashMap(); - props.put(CoreProperties.WORKING_DIRECTORY, temp.newFolder().getAbsolutePath()); - profiler = new PhasesSumUpTimeProfiler(clock, new GlobalProperties(props)); - } - - @Test - public void testSimpleProject() throws Exception { - - final Project project = mockProject("my:project", true); - - fakeAnalysis(profiler, project); - - assertThat(profiler.currentModuleProfiling.getProfilingPerPhase(Phase.INIT).getProfilingPerItem(new FakeInitializer()).totalTime()).isEqualTo(7L); - assertThat(profiler.currentModuleProfiling.getProfilingPerPhase(Phase.SENSOR).getProfilingPerItem(new FakeSensor()).totalTime()).isEqualTo(10L); - assertThat(profiler.currentModuleProfiling.getProfilingPerPhase(Phase.POSTJOB).getProfilingPerItem(new FakePostJob()).totalTime()).isEqualTo(30L); - assertThat(profiler.currentModuleProfiling.getProfilingPerBatchStep("Free memory").totalTime()).isEqualTo(9L); - } - - @Test - public void testMultimoduleProject() throws Exception { - final Project project = mockProject("project root", true); - final Project moduleA = mockProject("moduleA", false); - final Project moduleB = mockProject("moduleB", false); - - project.definition().addSubProject(moduleA.definition()); - project.definition().addSubProject(moduleA.definition()); - - fakeAnalysis(profiler, moduleA); - fakeAnalysis(profiler, moduleB); - fakeAnalysis(profiler, project); - - assertThat(profiler.currentModuleProfiling.getProfilingPerPhase(Phase.INIT).getProfilingPerItem(new FakeInitializer()).totalTime()).isEqualTo(7L); - assertThat(profiler.currentModuleProfiling.getProfilingPerPhase(Phase.SENSOR).getProfilingPerItem(new FakeSensor()).totalTime()).isEqualTo(10L); - assertThat(profiler.currentModuleProfiling.getProfilingPerPhase(Phase.POSTJOB).getProfilingPerItem(new FakePostJob()).totalTime()).isEqualTo(30L); - - assertThat(profiler.totalProfiling.getProfilingPerPhase(Phase.INIT).getProfilingPerItem(new FakeInitializer()).totalTime()).isEqualTo(21L); - assertThat(profiler.totalProfiling.getProfilingPerPhase(Phase.SENSOR).getProfilingPerItem(new FakeSensor()).totalTime()).isEqualTo(30L); - assertThat(profiler.totalProfiling.getProfilingPerPhase(Phase.POSTJOB).getProfilingPerItem(new FakePostJob()).totalTime()).isEqualTo(90L); - } - - @Test - public void testDisplayTimings() { - AbstractTimeProfiling profiling = new AbstractTimeProfiling(System2.INSTANCE) { - }; - - profiling.setTotalTime(5); - assertThat(profiling.totalTimeAsString()).isEqualTo("5ms"); - - profiling.setTotalTime(5 * 1000 + 12); - assertThat(profiling.totalTimeAsString()).isEqualTo("5s"); - - profiling.setTotalTime(5 * 60 * 1000 + 12 * 1000); - assertThat(profiling.totalTimeAsString()).isEqualTo("5min 12s"); - - profiling.setTotalTime(5 * 60 * 1000); - assertThat(profiling.totalTimeAsString()).isEqualTo("5min"); - } - - private class MockedSystem extends System2 { - private long now = 0; - - @Override - public long now() { - return now; - } - - public void sleep(long duration) { - now += duration; - } - } - - private Project mockProject(String name, boolean isRoot) throws IOException { - return new Project(new DefaultInputModule(ProjectDefinition.create().setName(name).setKey(name).setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()))); - } - - private void fakeAnalysis(PhasesSumUpTimeProfiler profiler, final Project module) { - // Start of moduleA - profiler.onProjectAnalysis(projectEvent(module, true)); - initializerPhase(profiler); - sensorPhase(profiler); - postJobPhase(profiler); - batchStep(profiler); - // End of moduleA - profiler.onProjectAnalysis(projectEvent(module, false)); - } - - private void batchStep(PhasesSumUpTimeProfiler profiler) { - // Start of batch step - profiler.onBatchStep(new BatchStepEvent("Free memory", true)); - clock.sleep(9); - // End of batch step - profiler.onBatchStep(new BatchStepEvent("Free memory", false)); - } - - private void initializerPhase(PhasesSumUpTimeProfiler profiler) { - Initializer initializer = new FakeInitializer(); - // Start of initializer phase - profiler.onInitializersPhase(initializersEvent(true)); - // Start of an initializer - profiler.onInitializerExecution(initializerEvent(initializer, true)); - clock.sleep(7); - // End of an initializer - profiler.onInitializerExecution(initializerEvent(initializer, false)); - // End of initializer phase - profiler.onInitializersPhase(initializersEvent(false)); - } - - private void sensorPhase(PhasesSumUpTimeProfiler profiler) { - Sensor sensor = new FakeSensor(); - // Start of sensor phase - profiler.onSensorsPhase(sensorsEvent(true)); - // Start of a Sensor - profiler.onSensorExecution(sensorEvent(sensor, true)); - clock.sleep(10); - // End of a Sensor - profiler.onSensorExecution(sensorEvent(sensor, false)); - // End of sensor phase - profiler.onSensorsPhase(sensorsEvent(false)); - } - - private void postJobPhase(PhasesSumUpTimeProfiler profiler) { - PostJob postJob = new FakePostJob(); - // Start of sensor phase - profiler.onPostJobsPhase(postJobsEvent(true)); - // Start of a Sensor - profiler.onPostJobExecution(postJobEvent(postJob, true)); - clock.sleep(30); - // End of a Sensor - profiler.onPostJobExecution(postJobEvent(postJob, false)); - // End of sensor phase - profiler.onPostJobsPhase(postJobsEvent(false)); - } - - private SensorExecutionEvent sensorEvent(final Sensor sensor, final boolean start) { - return new SensorExecutionHandler.SensorExecutionEvent() { - - @Override - public boolean isStart() { - return start; - } - - @Override - public boolean isEnd() { - return !start; - } - - @Override - public Sensor getSensor() { - return sensor; - } - }; - } - - private InitializerExecutionHandler.InitializerExecutionEvent initializerEvent(final Initializer initializer, final boolean start) { - return new InitializerExecutionHandler.InitializerExecutionEvent() { - - @Override - public boolean isStart() { - return start; - } - - @Override - public boolean isEnd() { - return !start; - } - - @Override - public Initializer getInitializer() { - return initializer; - } - }; - } - - private PostJobExecutionHandler.PostJobExecutionEvent postJobEvent(final PostJob postJob, final boolean start) { - return new PostJobExecutionHandler.PostJobExecutionEvent() { - - @Override - public boolean isStart() { - return start; - } - - @Override - public boolean isEnd() { - return !start; - } - - @Override - public PostJob getPostJob() { - return postJob; - } - }; - } - - private SensorsPhaseEvent sensorsEvent(final boolean start) { - return new SensorsPhaseHandler.SensorsPhaseEvent() { - - @Override - public boolean isStart() { - return start; - } - - @Override - public boolean isEnd() { - return !start; - } - - @Override - public List getSensors() { - return null; - } - }; - } - - private InitializersPhaseHandler.InitializersPhaseEvent initializersEvent(final boolean start) { - return new InitializersPhaseHandler.InitializersPhaseEvent() { - - @Override - public boolean isStart() { - return start; - } - - @Override - public boolean isEnd() { - return !start; - } - - @Override - public List getInitializers() { - return null; - } - }; - } - - private PostJobsPhaseHandler.PostJobsPhaseEvent postJobsEvent(final boolean start) { - return new PostJobsPhaseHandler.PostJobsPhaseEvent() { - - @Override - public boolean isStart() { - return start; - } - - @Override - public boolean isEnd() { - return !start; - } - - @Override - public List getPostJobs() { - return null; - } - }; - } - - private ProjectAnalysisEvent projectEvent(final Project project, final boolean start) { - return new ProjectAnalysisHandler.ProjectAnalysisEvent() { - @Override - public boolean isStart() { - return start; - } - - @Override - public boolean isEnd() { - return !start; - } - - @Override - public Project getProject() { - return project; - } - }; - } - - public class FakeSensor implements Sensor { - @Override - public void analyse(Project project, SensorContext context) { - } - - @Override - public boolean shouldExecuteOnProject(Project project) { - return true; - } - } - - public class FakeInitializer extends Initializer { - @Override - public void execute(Project project) { - } - - @Override - public boolean shouldExecuteOnProject(Project project) { - return true; - } - } - - public class FakePostJob implements PostJob { - @Override - public void executeOn(Project project, SensorContext context) { - } - } -} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/ProjectScanContainerTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/ProjectScanContainerTest.java index 8ca3ebf301f..41405c4aaea 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/ProjectScanContainerTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/scan/ProjectScanContainerTest.java @@ -20,9 +20,9 @@ package org.sonar.scanner.scan; import org.junit.Test; -import org.sonar.api.BatchExtension; -import org.sonar.api.ServerExtension; import org.sonar.api.batch.InstantiationStrategy; +import org.sonar.api.batch.ScannerSide; +import org.sonar.api.server.ServerSide; import org.sonar.api.task.TaskExtension; import org.sonar.scanner.bootstrap.ExtensionMatcher; @@ -45,16 +45,20 @@ public class ProjectScanContainerTest { assertThat(filter.accept(MyTaskExtension.class)).isFalse(); } + @ScannerSide @InstantiationStrategy(InstantiationStrategy.PER_BATCH) - static class MyBatchExtension implements BatchExtension { + static class MyBatchExtension { } - static class MyProjectExtension implements BatchExtension { + @ScannerSide + @InstantiationStrategy(InstantiationStrategy.PER_PROJECT) + static class MyProjectExtension { } - static class MyServerExtension implements ServerExtension { + @ServerSide + static class MyServerExtension { } diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/source/DefaultHighlightableTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/source/DefaultHighlightableTest.java deleted file mode 100644 index 3ed515b227a..00000000000 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/source/DefaultHighlightableTest.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.source; - -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.mockito.ArgumentCaptor; -import org.sonar.api.batch.AnalysisMode; -import org.sonar.api.batch.fs.internal.DefaultInputFile; -import org.sonar.api.batch.fs.internal.TestInputFileBuilder; -import org.sonar.api.batch.sensor.highlighting.internal.DefaultHighlighting; -import org.sonar.api.batch.sensor.internal.SensorStorage; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -public class DefaultHighlightableTest { - - @Rule - public ExpectedException throwable = ExpectedException.none(); - - @Test - public void should_store_highlighting_rules() { - SensorStorage sensorStorage = mock(SensorStorage.class); - DefaultInputFile inputFile = new TestInputFileBuilder("foo", "src/Foo.php") - .initMetadata("azerty\nbla bla") - .build(); - DefaultHighlightable highlightablePerspective = new DefaultHighlightable(inputFile, sensorStorage, mock(AnalysisMode.class)); - highlightablePerspective.newHighlighting().highlight(0, 6, "k").highlight(7, 10, "cppd").done(); - - ArgumentCaptor argCaptor = ArgumentCaptor.forClass(DefaultHighlighting.class); - verify(sensorStorage).store(argCaptor.capture()); - assertThat(argCaptor.getValue().getSyntaxHighlightingRuleSet()).hasSize(2); - } - -} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/source/DefaultSymbolizableTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/source/DefaultSymbolizableTest.java deleted file mode 100644 index 89590ed7c34..00000000000 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/source/DefaultSymbolizableTest.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.source; - -import com.google.common.base.Strings; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.sonar.api.batch.AnalysisMode; -import org.sonar.api.batch.fs.internal.DefaultInputFile; -import org.sonar.api.batch.fs.internal.TestInputFileBuilder; -import org.sonar.api.batch.sensor.symbol.internal.DefaultSymbolTable; -import org.sonar.api.source.Symbol; -import org.sonar.api.source.Symbolizable; -import org.sonar.scanner.sensor.DefaultSensorStorage; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -public class DefaultSymbolizableTest { - - @Test - public void should_update_cache_when_done() { - - DefaultSensorStorage sensorStorage = mock(DefaultSensorStorage.class); - DefaultInputFile inputFile = new TestInputFileBuilder("foo", "src/Foo.php") - .initMetadata(Strings.repeat("azerty\n", 20)).build(); - - DefaultSymbolizable symbolPerspective = new DefaultSymbolizable(inputFile, sensorStorage, mock(AnalysisMode.class)); - Symbolizable.SymbolTableBuilder symbolTableBuilder = symbolPerspective.newSymbolTableBuilder(); - Symbol firstSymbol = symbolTableBuilder.newSymbol(4, 8); - symbolTableBuilder.newReference(firstSymbol, 12); - symbolTableBuilder.newReference(firstSymbol, 70); - Symbol otherSymbol = symbolTableBuilder.newSymbol(25, 33); - symbolTableBuilder.newReference(otherSymbol, 44); - symbolTableBuilder.newReference(otherSymbol, 60); - symbolTableBuilder.newReference(otherSymbol, 108); - Symbolizable.SymbolTable symbolTable = symbolTableBuilder.build(); - - symbolPerspective.setSymbolTable(symbolTable); - - ArgumentCaptor argCaptor = ArgumentCaptor.forClass(DefaultSymbolTable.class); - verify(sensorStorage).store(argCaptor.capture()); - // Map> - assertThat(argCaptor.getValue().getReferencesBySymbol().keySet()).hasSize(2); - } -} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/source/DeprecatedDefaultSymbolTableTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/source/DeprecatedDefaultSymbolTableTest.java deleted file mode 100644 index 642856057a0..00000000000 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/source/DeprecatedDefaultSymbolTableTest.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.source; - -import com.google.common.base.Strings; -import java.util.Set; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.sonar.api.batch.fs.TextRange; -import org.sonar.api.batch.fs.internal.DefaultInputFile; -import org.sonar.api.batch.fs.internal.TestInputFileBuilder; -import org.sonar.api.batch.sensor.symbol.internal.DefaultSymbolTable; -import org.sonar.api.source.Symbol; -import org.sonar.api.source.Symbolizable; - -import static org.assertj.core.api.Assertions.assertThat; - -public class DeprecatedDefaultSymbolTableTest { - - @Rule - public ExpectedException throwable = ExpectedException.none(); - private DefaultInputFile inputFile; - - @Before - public void prepare() { - inputFile = new TestInputFileBuilder("foo", "src/Foo.php") - .initMetadata(Strings.repeat("azerty\n", 20)) - .build(); - } - - @Test - public void should_order_symbol_and_references() { - - Symbolizable.SymbolTableBuilder symbolTableBuilder = new DeprecatedDefaultSymbolTable.Builder(new DefaultSymbolTable(null).onFile(inputFile)); - Symbol firstSymbol = symbolTableBuilder.newSymbol(10, 20); - symbolTableBuilder.newReference(firstSymbol, 32); - Symbol secondSymbol = symbolTableBuilder.newSymbol(84, 92); - symbolTableBuilder.newReference(secondSymbol, 124); - Symbol thirdSymbol = symbolTableBuilder.newSymbol(55, 62); - symbolTableBuilder.newReference(thirdSymbol, 70); - - DeprecatedDefaultSymbolTable symbolTable = (DeprecatedDefaultSymbolTable) symbolTableBuilder.build(); - - assertThat(symbolTable.getWrapped().getReferencesBySymbol().keySet()).containsExactly(range(10, 20), range(84, 92), range(55, 62)); - } - - @Test - public void variable_length_references() { - Symbolizable.SymbolTableBuilder symbolTableBuilder = new DeprecatedDefaultSymbolTable.Builder(new DefaultSymbolTable(null).onFile(inputFile)); - Symbol firstSymbol = symbolTableBuilder.newSymbol(10, 20); - symbolTableBuilder.newReference(firstSymbol, 32); - symbolTableBuilder.newReference(firstSymbol, 44, 47); - - DeprecatedDefaultSymbolTable symbolTable = (DeprecatedDefaultSymbolTable) symbolTableBuilder.build(); - - assertThat(symbolTable.getWrapped().getReferencesBySymbol().keySet()).containsExactly(range(10, 20)); - - Set references = symbolTable.getWrapped().getReferencesBySymbol().get(range(10, 20)); - assertThat(references).containsExactly(range(32, 42), range(44, 47)); - } - - private TextRange range(int start, int end) { - return inputFile.newRange(start, end); - } - - @Test - public void should_reject_reference_conflicting_with_declaration() { - throwable.expect(IllegalArgumentException.class); - - Symbolizable.SymbolTableBuilder symbolTableBuilder = new DeprecatedDefaultSymbolTable.Builder(new DefaultSymbolTable(null).onFile(inputFile)); - Symbol symbol = symbolTableBuilder.newSymbol(10, 20); - symbolTableBuilder.newReference(symbol, 15); - } - -} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/source/HighlightableBuilderTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/source/HighlightableBuilderTest.java deleted file mode 100644 index a17558fb014..00000000000 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/source/HighlightableBuilderTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.source; - -import java.io.IOException; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.sonar.api.batch.AnalysisMode; -import org.sonar.api.batch.bootstrap.ProjectDefinition; -import org.sonar.api.batch.fs.internal.DefaultInputModule; -import org.sonar.api.batch.fs.internal.TestInputFileBuilder; -import org.sonar.api.batch.sensor.internal.SensorStorage; -import org.sonar.api.source.Highlightable; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -public class HighlightableBuilderTest { - - @Rule - public TemporaryFolder temp = new TemporaryFolder(); - - @Test - public void should_load_default_perspective() { - HighlightableBuilder builder = new HighlightableBuilder(mock(SensorStorage.class), mock(AnalysisMode.class)); - Highlightable perspective = builder.loadPerspective(Highlightable.class, new TestInputFileBuilder("foo", "foo.c").build()); - - assertThat(perspective).isNotNull().isInstanceOf(DefaultHighlightable.class); - } - - @Test - public void project_should_not_be_highlightable() throws IOException { - HighlightableBuilder builder = new HighlightableBuilder(mock(SensorStorage.class), mock(AnalysisMode.class)); - Highlightable perspective = builder.loadPerspective(Highlightable.class, - new DefaultInputModule(ProjectDefinition.create().setKey("struts").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()))); - - assertThat(perspective).isNull(); - } -} diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/source/SymbolizableBuilderTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/source/SymbolizableBuilderTest.java deleted file mode 100644 index a0dfb2d5f03..00000000000 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/source/SymbolizableBuilderTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2018 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program 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. - * - * This program 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.scanner.source; - -import java.io.IOException; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.sonar.api.batch.AnalysisMode; -import org.sonar.api.batch.bootstrap.ProjectDefinition; -import org.sonar.api.batch.fs.internal.DefaultInputModule; -import org.sonar.api.batch.fs.internal.TestInputFileBuilder; -import org.sonar.api.component.Perspective; -import org.sonar.api.source.Symbolizable; -import org.sonar.scanner.sensor.DefaultSensorStorage; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -public class SymbolizableBuilderTest { - - @Rule - public TemporaryFolder temp = new TemporaryFolder(); - - @Test - public void should_load_perspective() { - SymbolizableBuilder perspectiveBuilder = new SymbolizableBuilder(mock(DefaultSensorStorage.class), mock(AnalysisMode.class)); - Perspective perspective = perspectiveBuilder.loadPerspective(Symbolizable.class, new TestInputFileBuilder("foo", "foo.c").build()); - - assertThat(perspective).isInstanceOf(Symbolizable.class); - } - - @Test - public void project_should_not_be_highlightable() throws IOException { - SymbolizableBuilder builder = new SymbolizableBuilder(mock(DefaultSensorStorage.class), mock(AnalysisMode.class)); - Perspective perspective = builder.loadPerspective(Symbolizable.class, - new DefaultInputModule(ProjectDefinition.create().setKey("struts").setBaseDir(temp.newFolder()).setWorkDir(temp.newFolder()))); - - assertThat(perspective).isNull(); - } -} diff --git a/sonar-ws/src/main/java/org/sonarqube/ws/client/resources/ResourcesService.java b/sonar-ws/src/main/java/org/sonarqube/ws/client/resources/ResourcesService.java index e40df6ee1b9..01fae0d833c 100644 --- a/sonar-ws/src/main/java/org/sonarqube/ws/client/resources/ResourcesService.java +++ b/sonar-ws/src/main/java/org/sonarqube/ws/client/resources/ResourcesService.java @@ -19,12 +19,10 @@ */ package org.sonarqube.ws.client.resources; -import java.util.stream.Collectors; import javax.annotation.Generated; import org.sonarqube.ws.MediaTypes; import org.sonarqube.ws.client.BaseService; import org.sonarqube.ws.client.GetRequest; -import org.sonarqube.ws.client.PostRequest; import org.sonarqube.ws.client.WsConnector; /**