diff options
Diffstat (limited to 'sonar-scanner-engine/src')
114 files changed, 662 insertions, 6065 deletions
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<String, String> properties) { - setShowSql(properties, null); setVerbose(properties, null); return this; } public LoggingConfiguration setProperties(Map<String, String> properties, @Nullable Map<String, String> 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<String, String> properties, @Nullable Map<String, String> 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<Integer, Object>::getKey, Entry<Integer, Object>::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 <T> Collection<T> select(Class<T> type, @Nullable DefaultInputModule module, boolean sort, @Nullable ExtensionMatcher matcher) { - List<T> result = getFilteredExtensions(type, module, matcher); + public <T> Collection<T> select(Class<T> type, boolean sort, @Nullable ExtensionMatcher matcher) { + List<T> result = getFilteredExtensions(type, matcher); if (sort) { return sort(result); } return result; } - public Collection<org.sonar.api.batch.Sensor> selectSensors(@Nullable DefaultInputModule module, boolean global) { - List<org.sonar.api.batch.Sensor> result = getFilteredExtensions(org.sonar.api.batch.Sensor.class, module, null); - - Iterator<org.sonar.api.batch.Sensor> 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<SensorWrapper> selectSensors(boolean global) { + Collection<Sensor> 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<PostJobWrapper> selectPostJobs() { + Collection<PostJob> 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 <T> List<T> getFilteredExtensions(Class<T> type, @Nullable DefaultInputModule module, @Nullable ExtensionMatcher matcher) { + private <T> List<T> getFilteredExtensions(Class<T> type, @Nullable ExtensionMatcher matcher) { List<T> result = new ArrayList<>(); - List<Object> 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 <T> List<T> getExtensions(Class<T> type) { + private <T> List<T> getExtensions(Class<T> type) { List<T> extensions = new ArrayList<>(); - completeBatchExtensions(componentContainer, extensions, type); + completeScannerExtensions(componentContainer, extensions, type); return extensions; } - private static <T> void completeBatchExtensions(ComponentContainer container, List<T> extensions, Class<T> type) { + private static <T> void completeScannerExtensions(ComponentContainer container, List<T> extensions, Class<T> type) { extensions.addAll(container.getComponentsByType(type)); ComponentContainer parentContainer = container.getParent(); if (parentContainer != null) { - completeBatchExtensions(parentContainer, extensions, type); + completeScannerExtensions(parentContainer, extensions, type); } } - public <T> Collection<T> sort(Collection<T> extensions) { + private <T> Collection<T> sort(Collection<T> extensions) { DirectAcyclicGraph dag = new DirectAcyclicGraph(); for (T extension : extensions) { @@ -176,18 +146,14 @@ public class ScannerExtensionDictionnary { * Extension dependencies */ private <T> List<Object> getDependencies(T extension) { - List<Object> 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 <T> List<Object> getDependents(T extension) { - List<Object> result = new ArrayList<>(); - result.addAll(evaluateAnnotatedClasses(extension, DependedUpon.class)); - return result; + private <T> List<Object> 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<Object> evaluateAnnotatedClasses(Object extension, Class<? extends Annotation> annotation) { + List<Object> evaluateAnnotatedClasses(Object extension, Class<? extends Annotation> annotation) { List<Object> results = new ArrayList<>(); - Class<? extends Object> 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<Class<? extends Object>> 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<CloneGroup> 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<CloneGroup> duplications) { + @VisibleForTesting final void saveDuplications(final DefaultInputComponent component, List<CloneGroup> 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<ScannerReport.Duplication> reportDuplications = from(duplications) + Iterable<ScannerReport.Duplication> reportDuplications = duplications.stream() .limit(MAX_CLONE_GROUP_PER_FILE) - .transform( - new Function<CloneGroup, ScannerReport.Duplication>() { + .map( + new Function<CloneGroup, Duplication>() { 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<CloneGroup> numberOfUnitsNotLessThan(int min) { - return new NumberOfUnitsNotLessThan(min); + return input -> input != null && input.getLengthInUnits() >= min; } - - private static class NumberOfUnitsNotLessThan implements Predicate<CloneGroup> { - 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<InputFile> 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<InputFile> 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<Block> 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<InputFile> 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<InputFile> 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<Statement> 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<Block> 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<Resource> getChildren(Resource reference) { - return index.getChildren(getComponentKey(reference)); - } - - @Override - public <G extends Serializable> Measure<G> getMeasure(Metric<G> 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> M getMeasures(MeasuresFilter<M> 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 <G extends Serializable> Measure<G> getMeasure(Resource resource, Metric<G> 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> M getMeasures(Resource resource, MeasuresFilter<M> 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,52 +21,21 @@ 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<Class<?>, 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 extends Perspective> P as(Class<P> perspectiveClass, Resource resource) { - InputComponent component = componentStore.getByKey(getComponentKey(resource)); - if (component != null) { - PerspectiveBuilder<P> 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 extends Perspective> P as(Class<P> perspectiveClass, InputPath inputPath) { PerspectiveBuilder<P> builder = builderFor(perspectiveClass); return builder.loadPerspective(perspectiveClass, inputPath); @@ -75,7 +44,7 @@ public class ScannerPerspectives implements ResourcePerspectives { private <T extends Perspective> PerspectiveBuilder<T> builderFor(Class<T> clazz) { PerspectiveBuilder<T> builder = (PerspectiveBuilder<T>) 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 <H> handler type - */ -public abstract class BatchEvent<H extends EventHandler> { - - protected BatchEvent() { - } - - /** - * Do not call directly - should be called only by {@link EventBus}. - * Typically should be implemented as following: <code>handler.onEvent(this)</code> - */ - 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<BatchStepHandler> - 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<EventHandler> handlers = getDispatchList(event.getType()); - for (EventHandler handler : handlers) { - event.dispatch(handler); - } - } - - private List<EventHandler> getDispatchList(Class<? extends EventHandler> handlerType) { - List<EventHandler> 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> M getMeasures(String key, MeasuresFilter<M> filter) { - Collection<DefaultMeasure<?>> unfiltered = new ArrayList<>(); - if (filter instanceof MeasuresFilters.MetricFilter) { - // optimization - DefaultMeasure<?> byMetric = measureCache.byMetric(key, ((MeasuresFilters.MetricFilter<M>) 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<Boolean>().forMetric((Metric<Boolean>) metric) - .withValue(measure.getValue() != 0.0); - } else if (Integer.class.equals(metric.valueType())) { - newMeasure = new DefaultMeasure<Integer>().forMetric((Metric<Integer>) metric) - .withValue(measure.getValue().intValue()); - } else if (Double.class.equals(metric.valueType())) { - newMeasure = new DefaultMeasure<Double>().forMetric((Metric<Double>) metric) - .withValue(measure.getValue()); - } else if (String.class.equals(metric.valueType())) { - newMeasure = new DefaultMeasure<String>().forMetric((Metric<String>) metric) - .withValue(measure.getData()); - } else if (Long.class.equals(metric.valueType())) { - newMeasure = new DefaultMeasure<Long>().forMetric((Metric<Long>) 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<Resource> getChildren(String key) { - InputComponent component = componentStore.getByKey(key); - Collection<InputComponent> 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 @@ -92,11 +92,6 @@ public class DefaultFilterableIssue implements FilterableIssue { } @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<Issue> resolvedIssues() { - return Collections.emptyList(); - } - - @Override - public List<Issue> 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<String, String> attributes() { - return Collections.emptyMap(); - } - - @Override - public String authorLogin() { - throw unsupported(); - } - - @Override - public String actionPlanKey() { - throw unsupported(); - } - - @Override - public List<IssueComment> 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<String> 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<NewIssueLocation> 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<IssueFilter> filters; - - public DeprecatedIssueFilterChain(IssueFilter... filters) { - this.filters = Arrays.asList(filters); - } - - public DeprecatedIssueFilterChain() { - this.filters = Collections.emptyList(); - } - - private DeprecatedIssueFilterChain(List<IssueFilter> 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<String, String> attributes() { - return Collections.emptyMap(); - } - - @Override - public String authorLogin() { - return null; - } - - @Override - public String actionPlanKey() { - return null; - } - - @Override - public List<IssueComment> 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<String> 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<Issuable> { - - private final SensorContext sensorContext; - - public IssuableFactory(DefaultSensorContext sensorContext) { - super(Issuable.class); - this.sensorContext = sensorContext; - } - - @Override - public Issuable loadPerspective(Class<Issuable> 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(); @@ -154,24 +134,10 @@ public class TrackedIssueAdapter implements Issue { } @Override - public String actionPlanKey() { - return null; - } - - @Override public List<IssueComment> 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<H extends EventHandler> extends BatchEvent<H> { - - 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<InitializerExecutionHandler> - 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<Initializer> 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<InitializersPhaseHandler> - implements InitializersPhaseHandler.InitializersPhaseEvent { - - private final List<Initializer> initializers; - - InitializersPhaseEvent(List<Initializer> initializers, boolean start) { - super(start); - this.initializers = initializers; - } - - @Override - public List<Initializer> 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<PostJobExecutionHandler> - 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<PostJobsPhaseHandler> - implements PostJobsPhaseHandler.PostJobsPhaseEvent { - - private final List<PostJob> postJobs; - - PostJobPhaseEvent(List<PostJob> postJobs, boolean start) { - super(start); - this.postJobs = postJobs; - } - - @Override - public List<PostJob> 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<PostJob> 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<PostJobWrapper> postJobs = selector.selectPostJobs(); + execute(postJobs); } - private void execute(SensorContext context, Collection<PostJob> postJobs) { + private static void execute(Collection<PostJobWrapper> 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<PostJob> postJobs) { + private static void logPostJobs(Collection<PostJobWrapper> 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<ProjectAnalysisHandler> - 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<SensorExecutionHandler> - 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<Sensor> perModuleSensors = selector.selectSensors(module, false); - Collection<Sensor> globalSensors; + public void execute() { + Collection<SensorWrapper> moduleSensors = selector.selectSensors(false); + Collection<SensorWrapper> 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<Sensor> 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<SensorWrapper> moduleSensors, Collection<SensorWrapper> 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<SensorWrapper> sensors) { + for (SensorWrapper sensor : sensors) { + String sensorName = getSensorName(sensor); + profiler.startInfo("Sensor " + sensorName); + sensor.analyse(); + profiler.stopInfo(); + } } - private void execute(SensorContext context, Collection<Sensor> 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<SensorsPhaseHandler> - implements org.sonar.api.batch.events.SensorsPhaseHandler.SensorsPhaseEvent { - - private final List<Sensor> sensors; - - SensorsPhaseEvent(List<Sensor> sensors, boolean start) { - super(start); - this.sensors = sensors; - } - - @Override - public List<Sensor> 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 <G extends AbstractTimeProfiling> Map<Object, G> sortByDescendingTotalTime(Map<?, G> unsorted) { - List<Map.Entry<?, G>> entries = new ArrayList<>(unsorted.entrySet()); - Collections.sort(entries, (o1, o2) -> Long.valueOf(o2.getValue().totalTime()).compareTo(o1.getValue().totalTime())); - Map<Object, G> sortedMap = new LinkedHashMap<>(); - for (Map.Entry<?, G> entry : entries) { - sortedMap.put(entry.getKey(), entry.getValue()); - } - return sortedMap; - } - - static <G extends AbstractTimeProfiling> List<G> truncate(Collection<G> sortedList) { - int maxSize = 10; - List<G> 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<Phase, PhaseProfiling> profilingPerPhase = new EnumMap<>(Phase.class); - private Map<String, ItemProfiling> 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<Object, AbstractTimeProfiling> categories = Maps.newLinkedHashMap(); - categories.putAll(profilingPerPhase); - categories.putAll(profilingPerBatchStep); - - for (Map.Entry<Object, AbstractTimeProfiling> batchStep : categories.entrySet()) { - props.setProperty(batchStep.getKey().toString(), Long.toString(batchStep.getValue().totalTime())); - } - - for (Map.Entry<Object, AbstractTimeProfiling> 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<Phase, PhaseProfiling> entry : other.profilingPerPhase.entrySet()) { - if (!this.profilingPerPhase.containsKey(entry.getKey())) { - this.addPhaseProfiling(entry.getKey()); - } - this.getProfilingPerPhase(entry.getKey()).merge(entry.getValue()); - } - for (Map.Entry<String, ItemProfiling> 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<String, ItemProfiling> 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<String, ItemProfiling> 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<Project, ModuleProfiling> 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<LineCoverage.Builder, LineCoverage> { + private enum BuildCoverage implements Function<Builder, LineCoverage> { 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<Path> paths) { if (!paths.isEmpty()) { StringBuilder sb = new StringBuilder(label); - for (Iterator<Path> it = paths.iterator(); it.hasNext();) { + for (Iterator<Path> it = paths.iterator(); it.hasNext(); ) { Path file = it.next(); Optional<String> 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<String, Metric> metricsByKey = new LinkedHashMap<>(); - private Map<Integer, Metric> 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<Metric> findAll(List<String> metricKeys) { - List<Metric> result = new LinkedList<>(); - for (String metricKey : metricKeys) { - Metric metric = findByKey(metricKey); - if (metric != null) { - result.add(metric); - } - } - return result; - } - - @Override - public Collection<Metric> 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<Symbol> symbols() { - return Collections.emptyList(); - } - - @Override - public List<Integer> 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<Symbol> symbols() { - throw new UnsupportedOperationException("symbols"); - } - - @Override - public List<Integer> 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<Highlightable> { - - 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<Highlightable> 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<Symbolizable> { - - 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<Symbolizable> 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<Sensor> sensors = selector.select(Sensor.class, null, true, new ExtensionMatcher() { - @Override - public boolean accept(Object extension) { - return extension.equals(sensor1); - } - }); - + Collection<Sensor> 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<Sensor> sensors = selector.select(Sensor.class, null, true, null); + Collection<Sensor> 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<BatchExtension> extensions = Lists.newArrayList(selector.select(BatchExtension.class, null, true, null)); + List<Object> 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<BatchExtension> extensions = Lists.newArrayList(selector.select(BatchExtension.class, null, true, null)); + List<Object> 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<BatchExtension> extensions = Lists.newArrayList(selector.select(BatchExtension.class, null, true, null)); + List<Object> 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<BatchExtension> extensions = Lists.newArrayList(selector.select(BatchExtension.class, null, true, null)); + List<Object> 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<BatchExtension> extensions = Lists.newArrayList(selector.select(BatchExtension.class, null, true, null)); + List<Object> 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<BatchExtension> extensions = Lists.newArrayList(selector.select(BatchExtension.class, null, true, null)); + List<Object> extensions = Lists.newArrayList(selector.select(Marker.class, true, null)); assertThat(extensions).hasSize(2); assertThat(extensions.get(0)).isEqualTo(a); @@ -232,7 +226,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); @@ -240,25 +234,12 @@ public class ScannerExtensionDictionnaryTest { } @Test - public void checkProject() throws IOException { - BatchExtension ok = new CheckProjectOK(); - BatchExtension ko = new CheckProjectKO(); - - ScannerExtensionDictionnary selector = newSelector(ok, ko); - List<BatchExtension> 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<BatchExtension> extensions = Lists.newArrayList(selector.select(BatchExtension.class, null, true, null)); + List<Object> 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<org.sonar.api.batch.sensor.Sensor> extensions = Lists.newArrayList(selector.select(org.sonar.api.batch.sensor.Sensor.class, null, true, null)); - assertThat(extensions).containsExactly(pre, normal, post); - - List<Sensor> 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<org.sonar.api.batch.postjob.PostJob> extensions = Lists.newArrayList(selector.select(org.sonar.api.batch.postjob.PostJob.class, null, true, null)); - assertThat(extensions).containsExactly(pre, normal); - - List<PostJob> 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<Sensor> extensions = selector.selectSensors(null, false); - assertThat(extensions).hasSize(2); - assertThat(extensions).contains(oldSensor); - extensions.remove(oldSensor); + // verify non-global sensor + Collection<SensorWrapper> 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<CloneGroup> 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<List<Block>> 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<Block> 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<FirstHandler> { - @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<SecondHandler> { - @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<Object[]> 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<String, String> 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.<String, String>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<org.sonar.scanner.protocol.output.ScannerReport.Duplication> duplicationGroupsFile1 = result.duplicationsFor(inputFile1); + List<ScannerReport.Duplication> 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<org.sonar.scanner.protocol.output.ScannerReport.Duplication> duplicationGroupsFile2 = result.duplicationsFor(inputFile2); + List<ScannerReport.Duplication> 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<org.sonar.scanner.protocol.output.ScannerReport.Duplication> duplicationGroupsFile1 = result.duplicationsFor(inputFile1); + List<ScannerReport.Duplication> 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<org.sonar.scanner.protocol.output.ScannerReport.Duplication> duplicationGroupsFile2 = result.duplicationsFor(inputFile2); + List<ScannerReport.Duplication> 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<org.sonar.scanner.protocol.output.ScannerReport.Duplication> duplicationGroupsFile1 = result.duplicationsFor(inputFile1); + List<ScannerReport.Duplication> duplicationGroupsFile1 = result.duplicationsFor(inputFile1); assertThat(duplicationGroupsFile1).isEmpty(); - List<org.sonar.scanner.protocol.output.ScannerReport.Duplication> duplicationGroupsFile2 = result.duplicationsFor(inputFile2); + List<ScannerReport.Duplication> 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<org.sonar.scanner.protocol.output.ScannerReport.Duplication> duplicationGroups = result.duplicationsFor(inputFile); + List<ScannerReport.Duplication> 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.<String, String>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.<String, String>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<String, String> 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<Sensor> 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<Initializer> 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<PostJob> 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<DefaultHighlighting> 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<DefaultSymbolTable> argCaptor = ArgumentCaptor.forClass(DefaultSymbolTable.class); - verify(sensorStorage).store(argCaptor.capture()); - // Map<Symbol, Set<TextRange>> - 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<TextRange> 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(); - } -} |