Skip to content

Commit

Permalink
Fix quality flaws
Browse files Browse the repository at this point in the history
  • Loading branch information
henryju authored and sonartech committed Jan 16, 2019
1 parent 55579a4 commit 532850a
Show file tree
Hide file tree
Showing 28 changed files with 242 additions and 172 deletions.
Expand Up @@ -32,7 +32,7 @@
import org.sonar.xoo.extensions.XooPostJob;
import org.sonar.xoo.extensions.XooProjectBuilder;
import org.sonar.xoo.global.DeprecatedGlobalSensor;
import org.sonar.xoo.global.GlobalSensor;
import org.sonar.xoo.global.GlobalProjectSensor;
import org.sonar.xoo.lang.CpdTokenizerSensor;
import org.sonar.xoo.lang.LineMeasureSensor;
import org.sonar.xoo.lang.MeasureSensor;
Expand Down Expand Up @@ -174,7 +174,7 @@ public void define(Context context) {
context.addExtension(DeprecatedGlobalSensor.class);
}
if (context.getSonarQubeVersion().isGreaterThanOrEqual(Version.create(7, 6))) {
context.addExtension(GlobalSensor.class);
context.addExtension(GlobalProjectSensor.class);
}
if (context.getSonarQubeVersion().isGreaterThanOrEqual(Version.create(7, 2))) {
context.addExtensions(
Expand Down
Expand Up @@ -19,15 +19,15 @@
*/
package org.sonar.xoo.global;

import org.sonar.api.scanner.sensor.Sensor;
import org.sonar.api.scanner.sensor.ProjectSensor;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;

public class GlobalSensor implements Sensor {
public class GlobalProjectSensor implements ProjectSensor {

private static final Logger LOG = Loggers.get(GlobalSensor.class);
private static final Logger LOG = Loggers.get(GlobalProjectSensor.class);
public static final String ENABLE_PROP = "sonar.scanner.mediumtest.globalSensor";

@Override
Expand Down
Expand Up @@ -20,8 +20,10 @@
package org.sonar.api.batch.sensor;

import org.sonar.api.ExtensionPoint;
import org.sonar.api.batch.InstantiationStrategy;
import org.sonar.api.batch.ScannerSide;
import org.sonar.api.batch.sensor.internal.SensorContextTester;
import org.sonar.api.scanner.sensor.ProjectSensor;
import org.sonarsource.api.sonarlint.SonarLintSide;

/**
Expand All @@ -33,12 +35,13 @@
*
* For testing purpose you can use {@link SensorContextTester}
* @since 5.1
* @since 7.6 use {@link org.sonar.api.scanner.sensor.Sensor} instead to make your Sensor run only once per analysis, and no more once per module
* @since 7.6 use {@link ProjectSensor} instead to make your Sensor run only once per analysis, and no more once per module
*/
@ScannerSide
@InstantiationStrategy(InstantiationStrategy.PER_PROJECT)
@SonarLintSide
@ExtensionPoint
public interface Sensor {
public interface Sensor extends ProjectSensor {

/**
* Populate {@link SensorDescriptor} of this sensor.
Expand Down
Expand Up @@ -43,6 +43,7 @@
import org.sonar.api.config.Configuration;
import org.sonar.api.config.Settings;
import org.sonar.api.scanner.fs.InputProject;
import org.sonar.api.scanner.sensor.ProjectSensor;
import org.sonar.api.utils.Version;

/**
Expand Down Expand Up @@ -77,7 +78,7 @@ public interface SensorContext {
/**
* @since 5.5
* @deprecated since 7.6 modules are deprecated. Use {@link #project()} instead.
* @throws UnsupportedOperationException for global {@link org.sonar.api.scanner.sensor.Sensor}s
* @throws UnsupportedOperationException for global {@link ProjectSensor}s
*/
@Deprecated
InputModule module();
Expand Down
Expand Up @@ -22,9 +22,10 @@
import java.util.function.Predicate;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.config.Configuration;
import org.sonar.api.scanner.sensor.ProjectSensor;

/**
* Describe what a {@link org.sonar.api.scanner.sensor.Sensor} is doing. Information may be used by the platform
* Describe what a {@link Sensor} is doing. Information may be used by the platform
* to log interesting information or perform some optimization.
* See {@link Sensor#describe(SensorDescriptor)}
* @since 5.1
Expand Down Expand Up @@ -88,7 +89,7 @@ public interface SensorDescriptor {
/**
* This sensor should be executed at the project level, instead of per-module.
* @since 6.4
* @deprecated since 7.6 change your {@link Sensor} to a {@link org.sonar.api.scanner.sensor.Sensor} instead
* @deprecated since 7.6 change your {@link Sensor} to a {@link ProjectSensor} instead
*/
@Deprecated
SensorDescriptor global();
Expand Down
Expand Up @@ -38,7 +38,7 @@
@ScannerSide
@SonarLintSide
@ExtensionPoint
public interface Sensor {
public interface ProjectSensor {

/**
* Populate {@link SensorDescriptor} of this sensor.
Expand Down
@@ -0,0 +1,71 @@
/*
* SonarQube
* Copyright (C) 2009-2018 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.api.batch.fs.internal;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.batch.bootstrap.ProjectDefinition;

import static org.assertj.core.api.Assertions.assertThat;

public class DefaultInputModuleTest {

private static final String FILE_1 = "file1";
private static final String TEST_1 = "test1";
@Rule
public TemporaryFolder temp = new TemporaryFolder();

@Test
public void testGetters() throws IOException {
ProjectDefinition def = ProjectDefinition.create();
def.setKey("moduleKey");
File baseDir = temp.newFolder();
Path src = baseDir.toPath().resolve(FILE_1);
Files.createFile(src);
Path test = baseDir.toPath().resolve(TEST_1);
Files.createFile(test);
def.setBaseDir(baseDir);
File workDir = temp.newFolder();
def.setWorkDir(workDir);
def.setSources(FILE_1);
def.setTests(TEST_1);
DefaultInputModule module = new DefaultInputModule(def);

assertThat(module.key()).isEqualTo("moduleKey");
assertThat(module.definition()).isEqualTo(def);
assertThat(module.getBranch()).isNull();
assertThat(module.getBaseDir()).isEqualTo(baseDir.toPath());
assertThat(module.getKeyWithBranch()).isEqualTo("moduleKey");
assertThat(module.getWorkDir()).isEqualTo(workDir.toPath());
assertThat(module.getEncoding()).isEqualTo(Charset.defaultCharset());
assertThat(module.getSourceDirsOrFiles()).containsExactlyInAnyOrder(src);
assertThat(module.getTestDirsOrFiles()).containsExactlyInAnyOrder(test);
assertThat(module.getEncoding()).isEqualTo(Charset.defaultCharset());

assertThat(module.isFile()).isFalse();
}

}
Expand Up @@ -21,6 +21,8 @@

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
Expand All @@ -46,23 +48,42 @@ public void testGetters() throws IOException {
def.setWorkDir(workDir);
def.setSources("file1");
def.setTests("test1");
AbstractProjectOrModule module = new DefaultInputProject(def);
AbstractProjectOrModule project = new DefaultInputProject(def);

assertThat(module.key()).isEqualTo("projectKey");
assertThat(module.getName()).isEqualTo("projectName");
assertThat(module.getOriginalName()).isEqualTo("projectName");
assertThat(module.definition()).isEqualTo(def);
assertThat(module.getBranch()).isNull();
assertThat(module.getBaseDir()).isEqualTo(baseDir.toPath());
assertThat(module.getKeyWithBranch()).isEqualTo("projectKey");
assertThat(module.getVersion()).isEqualTo("version");
assertThat(module.getOriginalVersion()).isEqualTo("version");
assertThat(module.getDescription()).isEqualTo("desc");
assertThat(module.getWorkDir()).isEqualTo(workDir.toPath());
assertThat(project.key()).isEqualTo("projectKey");
assertThat(project.getName()).isEqualTo("projectName");
assertThat(project.getOriginalName()).isEqualTo("projectName");
assertThat(project.definition()).isEqualTo(def);
assertThat(project.getBranch()).isNull();
assertThat(project.getBaseDir()).isEqualTo(baseDir.toPath());
assertThat(project.getKeyWithBranch()).isEqualTo("projectKey");
assertThat(project.getVersion()).isEqualTo("version");
assertThat(project.getOriginalVersion()).isEqualTo("version");
assertThat(project.getDescription()).isEqualTo("desc");
assertThat(project.getWorkDir()).isEqualTo(workDir.toPath());
assertThat(project.getEncoding()).isEqualTo(Charset.defaultCharset());

assertThat(module.properties()).hasSize(6);
assertThat(project.properties()).hasSize(6);

assertThat(module.isFile()).isFalse();
assertThat(project.isFile()).isFalse();
}

@Test
public void testEncoding() throws IOException {
ProjectDefinition def = ProjectDefinition.create();
def.setKey("projectKey");
def.setName("projectName");
File baseDir = temp.newFolder();
def.setBaseDir(baseDir);
def.setVersion("version");
def.setDescription("desc");
File workDir = temp.newFolder();
def.setWorkDir(workDir);
def.setSources("file1");
def.setProperty("sonar.sourceEncoding", "UTF-16");
AbstractProjectOrModule project = new DefaultInputProject(def);

assertThat(project.getEncoding()).isEqualTo(StandardCharsets.UTF_16);
}

}
Expand Up @@ -64,9 +64,9 @@ private static Phase.Name evaluatePhase(Object extension) {
protected <T> List<T> getFilteredExtensions(Class<T> type, @Nullable ExtensionMatcher matcher) {
List<T> result = new ArrayList<>();

for (Object extension : getExtensions(type)) {
for (T extension : getExtensions(type)) {
if (shouldKeep(type, extension, matcher)) {
result.add((T) extension);
result.add(extension);
}
}
return result;
Expand Down
Expand Up @@ -25,6 +25,7 @@
import org.sonar.core.component.DefaultResourceTypes;
import org.sonar.core.config.CorePropertyDefinitions;
import org.sonar.core.issue.tracking.Tracker;
import org.sonar.scanner.cpd.JavaCpdBlockIndexerSensor;
import org.sonar.scanner.externalissue.ExternalIssuesImportSensor;
import org.sonar.scanner.genericcoverage.GenericCoverageSensor;
import org.sonar.scanner.genericcoverage.GenericTestExecutionSensor;
Expand All @@ -44,6 +45,7 @@ public static Collection<Object> all(GlobalAnalysisMode analysisMode) {
components.addAll(CorePropertyDefinitions.all());
if (!analysisMode.isIssues()) {
components.add(ZeroCoverageSensor.class);
components.add(JavaCpdBlockIndexerSensor.class);

// Generic coverage
components.add(GenericCoverageSensor.class);
Expand Down
Expand Up @@ -61,8 +61,7 @@ public JavaCpdBlockIndexerSensor(SonarCpdBlockIndex index) {
@Override
public void describe(SensorDescriptor descriptor) {
descriptor.name("Java CPD Block Indexer")
.onlyOnLanguage("java")
.global();
.onlyOnLanguage("java");
}

@Override
Expand Down
Expand Up @@ -64,10 +64,8 @@ public class AnalysisContextReportPublisher {
private final InputModuleHierarchy hierarchy;
private final InputComponentStore store;

private ScannerReportWriter writer;

public AnalysisContextReportPublisher(ProjectServerSettings projectServerSettings, AnalysisMode mode, ScannerPluginRepository pluginRepo, System2 system,
GlobalServerSettings globalServerSettings, InputModuleHierarchy hierarchy, InputComponentStore store) {
GlobalServerSettings globalServerSettings, InputModuleHierarchy hierarchy, InputComponentStore store) {
this.projectServerSettings = projectServerSettings;
this.mode = mode;
this.pluginRepo = pluginRepo;
Expand All @@ -81,7 +79,6 @@ public void init(ScannerReportWriter writer) {
if (mode.isIssues()) {
return;
}
this.writer = writer;
File analysisLog = writer.getFileStructure().analysisLog();
try (BufferedWriter fileWriter = Files.newBufferedWriter(analysisLog.toPath(), StandardCharsets.UTF_8)) {
if (LOG.isDebugEnabled()) {
Expand Down
Expand Up @@ -27,7 +27,6 @@
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.utils.MessageException;
Expand All @@ -51,8 +50,11 @@ public DefaultProjectRepositoriesLoader(ScannerWsClient wsClient) {
public ProjectRepositories load(String projectKey, boolean issuesMode, @Nullable String branchBase) {
GetRequest request = new GetRequest(getUrl(projectKey, issuesMode, branchBase));
try (WsResponse response = wsClient.call(request)) {
InputStream is = response.contentStream();
return processStream(is, projectKey);
try (InputStream is = response.contentStream()) {
return processStream(is);
} catch (IOException e) {
throw new IllegalStateException("Couldn't load project repository for " + projectKey, e);
}
} catch (RuntimeException e) {
if (shouldThrow(e)) {
throw e;
Expand Down Expand Up @@ -91,26 +93,20 @@ private static boolean shouldThrow(Exception e) {
return false;
}

private ProjectRepositories processStream(InputStream is, String projectKey) {
try {
WsProjectResponse response = WsProjectResponse.parseFrom(is);
if (response.getFileDataByModuleAndPathCount() == 0) {
return new SingleProjectRepository(constructFileDataMap(response.getFileDataByPathMap()), new Date(response.getLastAnalysisDate()));
} else {
final Map<String, SingleProjectRepository> repositoriesPerModule = new HashMap<>();
response.getFileDataByModuleAndPathMap().keySet().forEach(moduleKey -> {
WsProjectResponse.FileDataByPath filePaths = response.getFileDataByModuleAndPathMap().get(moduleKey);
repositoriesPerModule.put(moduleKey, new SingleProjectRepository(
constructFileDataMap(filePaths.getFileDataByPathMap()), new Date(response.getLastAnalysisDate())));
});
return new MultiModuleProjectRepository(repositoriesPerModule, new Date(response.getLastAnalysisDate()));
}

} catch (IOException e) {
throw new IllegalStateException("Couldn't load project repository for " + projectKey, e);
} finally {
IOUtils.closeQuietly(is);
private static ProjectRepositories processStream(InputStream is) throws IOException {
WsProjectResponse response = WsProjectResponse.parseFrom(is);
if (response.getFileDataByModuleAndPathCount() == 0) {
return new SingleProjectRepository(constructFileDataMap(response.getFileDataByPathMap()), new Date(response.getLastAnalysisDate()));
} else {
final Map<String, SingleProjectRepository> repositoriesPerModule = new HashMap<>();
response.getFileDataByModuleAndPathMap().keySet().forEach(moduleKey -> {
WsProjectResponse.FileDataByPath filePaths = response.getFileDataByModuleAndPathMap().get(moduleKey);
repositoriesPerModule.put(moduleKey, new SingleProjectRepository(
constructFileDataMap(filePaths.getFileDataByPathMap()), new Date(response.getLastAnalysisDate())));
});
return new MultiModuleProjectRepository(repositoriesPerModule, new Date(response.getLastAnalysisDate()));
}

}

private static Map<String, FileData> constructFileDataMap(Map<String, WsProjectResponse.FileData> content) {
Expand Down
Expand Up @@ -28,18 +28,15 @@
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.scanner.bootstrap.GlobalAnalysisMode;
import org.sonar.scanner.bootstrap.GlobalConfiguration;
import org.sonar.scanner.report.AnalysisContextReportPublisher;

public class ModuleConfigurationProvider extends ProviderAdapter {

private ModuleConfiguration moduleConfiguration;

public ModuleConfiguration provide(GlobalConfiguration globalConfig, DefaultInputModule module, ProjectServerSettings projectServerSettings,
GlobalAnalysisMode analysisMode, AnalysisContextReportPublisher contextReportPublisher) {
public ModuleConfiguration provide(GlobalConfiguration globalConfig, DefaultInputModule module, ProjectServerSettings projectServerSettings, GlobalAnalysisMode analysisMode) {
if (moduleConfiguration == null) {

Map<String, String> settings = new LinkedHashMap<>();
settings.putAll(projectServerSettings.properties());
Map<String, String> settings = new LinkedHashMap<>(projectServerSettings.properties());
addScannerSideProperties(settings, module.definition());

moduleConfiguration = new ModuleConfiguration(globalConfig.getDefinitions(), globalConfig.getEncryption(), analysisMode, settings);
Expand Down
Expand Up @@ -20,7 +20,6 @@
package org.sonar.scanner.scan;

import org.picocontainer.Startable;
import org.sonar.api.batch.fs.internal.AbstractProjectOrModule;
import org.sonar.api.batch.fs.internal.DefaultInputModule;
import org.sonar.api.batch.fs.internal.InputModuleHierarchy;
import org.sonar.scanner.scan.filesystem.InputComponentStore;
Expand Down

0 comments on commit 532850a

Please sign in to comment.