diff options
Diffstat (limited to 'sonar-scanner-engine/src/main')
81 files changed, 395 insertions, 4034 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; - } -} |