diff options
-rw-r--r-- | pom.xml | 4 | ||||
-rw-r--r-- | sonar-runner-api/pom.xml | 69 | ||||
-rw-r--r-- | sonar-runner-api/src/main/java/org/sonar/runner/api/Command.java | 126 | ||||
-rw-r--r-- | sonar-runner-api/src/main/java/org/sonar/runner/api/CommandExecutor.java | 198 | ||||
-rw-r--r-- | sonar-runner-api/src/main/java/org/sonar/runner/api/Dirs.java | 14 | ||||
-rw-r--r-- | sonar-runner-api/src/main/java/org/sonar/runner/api/EmbeddedRunner.java | 206 | ||||
-rw-r--r-- | sonar-runner-api/src/main/java/org/sonar/runner/api/ForkedRunner.java | 243 | ||||
-rw-r--r-- | sonar-runner-api/src/main/java/org/sonar/runner/api/LogOutput.java (renamed from sonar-runner-api/src/main/java/org/sonar/runner/api/LogListener.java) | 5 | ||||
-rw-r--r-- | sonar-runner-api/src/main/java/org/sonar/runner/api/Os.java | 40 | ||||
-rw-r--r-- | sonar-runner-api/src/main/java/org/sonar/runner/api/PrintStreamConsumer.java | 41 | ||||
-rw-r--r-- | sonar-runner-api/src/main/java/org/sonar/runner/api/Runner.java | 181 | ||||
-rw-r--r-- | sonar-runner-api/src/main/java/org/sonar/runner/api/SourceEncoding.java | 47 | ||||
-rw-r--r-- | sonar-runner-api/src/main/java/org/sonar/runner/api/StdOutLogOutput.java (renamed from sonar-runner-api/src/main/java/org/sonar/runner/api/StreamConsumer.java) | 11 | ||||
-rw-r--r-- | sonar-runner-api/src/main/java/org/sonar/runner/impl/InternalProperties.java (renamed from sonar-runner-impl/src/main/java/org/sonar/runner/impl/InternalProperties.java) | 3 | ||||
-rw-r--r-- | sonar-runner-api/src/main/java/org/sonar/runner/impl/IsolatedClassloader.java (renamed from sonar-runner-impl/src/main/java/org/sonar/runner/impl/IsolatedClassloader.java) | 26 | ||||
-rw-r--r-- | sonar-runner-api/src/main/java/org/sonar/runner/impl/IsolatedLauncherFactory.java (renamed from sonar-runner-impl/src/main/java/org/sonar/runner/impl/IsolatedLauncherFactory.java) | 67 | ||||
-rw-r--r-- | sonar-runner-api/src/main/java/org/sonar/runner/impl/IsolatedLauncherProxy.java (renamed from sonar-runner-impl/src/main/java/org/sonar/runner/impl/IsolatedLauncherProxy.java) | 23 | ||||
-rw-r--r-- | sonar-runner-api/src/main/java/org/sonar/runner/impl/JarDownloader.java (renamed from sonar-runner-impl/src/main/java/org/sonar/runner/impl/JarDownloader.java) | 9 | ||||
-rw-r--r-- | sonar-runner-api/src/main/java/org/sonar/runner/impl/JarExtractor.java (renamed from sonar-runner-impl/src/main/java/org/sonar/runner/impl/JarExtractor.java) | 2 | ||||
-rw-r--r-- | sonar-runner-api/src/main/java/org/sonar/runner/impl/Jars.java (renamed from sonar-runner-impl/src/main/java/org/sonar/runner/impl/Jars.java) | 24 | ||||
-rw-r--r-- | sonar-runner-api/src/main/java/org/sonar/runner/impl/RunnerException.java (renamed from sonar-runner-impl/src/main/java/org/sonar/runner/impl/RunnerException.java) | 2 | ||||
-rw-r--r-- | sonar-runner-api/src/main/java/org/sonar/runner/impl/ServerConnection.java (renamed from sonar-runner-impl/src/main/java/org/sonar/runner/impl/ServerConnection.java) | 22 | ||||
-rw-r--r-- | sonar-runner-api/src/main/java/org/sonar/runner/impl/TempCleaning.java (renamed from sonar-runner-impl/src/main/java/org/sonar/runner/impl/TempCleaning.java) | 19 | ||||
-rw-r--r-- | sonar-runner-api/src/main/java/org/sonar/runner/impl/package-info.java (renamed from sonar-runner-impl/src/main/java/org/sonar/runner/impl/package-info.java) | 2 | ||||
-rw-r--r-- | sonar-runner-api/src/test/java/org/sonar/runner/api/CommandExecutorTest.java | 183 | ||||
-rw-r--r-- | sonar-runner-api/src/test/java/org/sonar/runner/api/CommandTest.java | 87 | ||||
-rw-r--r-- | sonar-runner-api/src/test/java/org/sonar/runner/api/DirsTest.java | 15 | ||||
-rw-r--r-- | sonar-runner-api/src/test/java/org/sonar/runner/api/EmbeddedRunnerTest.java | 103 | ||||
-rw-r--r-- | sonar-runner-api/src/test/java/org/sonar/runner/api/ForkedRunnerTest.java | 240 | ||||
-rw-r--r-- | sonar-runner-api/src/test/java/org/sonar/runner/api/OsTest.java | 47 | ||||
-rw-r--r-- | sonar-runner-api/src/test/java/org/sonar/runner/api/PrintStreamConsumerTest.java | 42 | ||||
-rw-r--r-- | sonar-runner-api/src/test/java/org/sonar/runner/api/SourceEncodingTest.java | 54 | ||||
-rw-r--r-- | sonar-runner-api/src/test/java/org/sonar/runner/impl/IsolatedClassloaderTest.java (renamed from sonar-runner-impl/src/test/java/org/sonar/runner/impl/IsolatedClassloaderTest.java) | 28 | ||||
-rw-r--r-- | sonar-runner-api/src/test/java/org/sonar/runner/impl/IsolatedLauncherFactoryTest.java (renamed from sonar-runner-impl/src/test/java/org/sonar/runner/impl/IsolatedLauncherFactoryTest.java) | 57 | ||||
-rw-r--r-- | sonar-runner-api/src/test/java/org/sonar/runner/impl/IsolatedLauncherProxyTest.java (renamed from sonar-runner-impl/src/test/java/org/sonar/runner/impl/IsolatedLauncherProxyTest.java) | 16 | ||||
-rw-r--r-- | sonar-runner-api/src/test/java/org/sonar/runner/impl/JarDownloaderTest.java (renamed from sonar-runner-impl/src/test/java/org/sonar/runner/impl/JarDownloaderTest.java) | 5 | ||||
-rw-r--r-- | sonar-runner-api/src/test/java/org/sonar/runner/impl/JarExtractorTest.java (renamed from sonar-runner-impl/src/test/java/org/sonar/runner/impl/JarExtractorTest.java) | 2 | ||||
-rw-r--r-- | sonar-runner-api/src/test/java/org/sonar/runner/impl/JarsTest.java (renamed from sonar-runner-impl/src/test/java/org/sonar/runner/impl/JarsTest.java) | 17 | ||||
-rw-r--r-- | sonar-runner-api/src/test/java/org/sonar/runner/impl/MockHttpServer.java (renamed from sonar-runner-impl/src/test/java/org/sonar/runner/impl/MockHttpServer.java) | 2 | ||||
-rw-r--r-- | sonar-runner-api/src/test/java/org/sonar/runner/impl/MockHttpServerInterceptor.java (renamed from sonar-runner-impl/src/test/java/org/sonar/runner/impl/MockHttpServerInterceptor.java) | 2 | ||||
-rw-r--r-- | sonar-runner-api/src/test/java/org/sonar/runner/impl/NetworkUtil.java (renamed from sonar-runner-impl/src/test/java/org/sonar/runner/impl/NetworkUtil.java) | 2 | ||||
-rw-r--r-- | sonar-runner-api/src/test/java/org/sonar/runner/impl/ServerConnectionTest.java (renamed from sonar-runner-impl/src/test/java/org/sonar/runner/impl/ServerConnectionTest.java) | 47 | ||||
-rw-r--r-- | sonar-runner-api/src/test/java/org/sonar/runner/impl/TempCleaningTest.java (renamed from sonar-runner-impl/src/test/java/org/sonar/runner/impl/TempCleaningTest.java) | 13 | ||||
-rw-r--r-- | sonar-runner-api/src/test/resources/fake.jar (renamed from sonar-runner-impl/src/test/resources/fake.jar) | 0 | ||||
-rw-r--r-- | sonar-runner-api/src/test/resources/org/sonar/runner/impl/BatchLauncherMainTest/props.properties (renamed from sonar-runner-impl/src/test/resources/org/sonar/runner/impl/BatchLauncherMainTest/props.properties) | 0 | ||||
-rw-r--r-- | sonar-runner-batch-interface/src/main/java/org/sonar/runner/batch/IsolatedLauncher.java | 8 | ||||
-rw-r--r-- | sonar-runner-batch-interface/src/main/java/org/sonar/runner/batch/LogOutput.java (renamed from sonar-runner-api/src/main/java/org/sonar/runner/api/CommandException.java) | 17 | ||||
-rw-r--r-- | sonar-runner-batch/pom.xml | 6 | ||||
-rw-r--r-- | sonar-runner-batch/src/main/java/org/sonar/runner/batch/BatchIsolatedLauncher.java | 40 | ||||
-rw-r--r-- | sonar-runner-batch/src/test/java/org/sonar/runner/batch/IsolatedLauncherTest.java | 3 | ||||
-rw-r--r-- | sonar-runner-cli/assembly.xml (renamed from sonar-runner-dist/assembly.xml) | 0 | ||||
-rw-r--r-- | sonar-runner-cli/pom.xml (renamed from sonar-runner-dist/pom.xml) | 16 | ||||
-rwxr-xr-x | sonar-runner-cli/src/main/assembly/bin/sonar-runner (renamed from sonar-runner-dist/src/main/assembly/bin/sonar-runner) | 6 | ||||
-rw-r--r-- | sonar-runner-cli/src/main/assembly/bin/sonar-runner.bat (renamed from sonar-runner-dist/src/main/assembly/bin/sonar-runner.bat) | 4 | ||||
-rw-r--r-- | sonar-runner-cli/src/main/assembly/conf/sonar-runner.properties (renamed from sonar-runner-dist/src/main/assembly/conf/sonar-runner.properties) | 0 | ||||
-rw-r--r-- | sonar-runner-cli/src/main/java/org/sonar/runner/cli/Cli.java (renamed from sonar-runner-dist/src/main/java/org/sonar/runner/Cli.java) | 10 | ||||
-rw-r--r-- | sonar-runner-cli/src/main/java/org/sonar/runner/cli/Conf.java (renamed from sonar-runner-dist/src/main/java/org/sonar/runner/Conf.java) | 6 | ||||
-rw-r--r-- | sonar-runner-cli/src/main/java/org/sonar/runner/cli/Exit.java (renamed from sonar-runner-dist/src/main/java/org/sonar/runner/Exit.java) | 4 | ||||
-rw-r--r-- | sonar-runner-cli/src/main/java/org/sonar/runner/cli/Logs.java | 66 | ||||
-rw-r--r-- | sonar-runner-cli/src/main/java/org/sonar/runner/cli/Main.java (renamed from sonar-runner-dist/src/main/java/org/sonar/runner/Main.java) | 29 | ||||
-rw-r--r-- | sonar-runner-cli/src/main/java/org/sonar/runner/cli/RunnerFactory.java (renamed from sonar-runner-dist/src/main/java/org/sonar/runner/RunnerFactory.java) | 43 | ||||
-rw-r--r-- | sonar-runner-cli/src/main/java/org/sonar/runner/cli/Shutdown.java (renamed from sonar-runner-dist/src/main/java/org/sonar/runner/Shutdown.java) | 4 | ||||
-rw-r--r-- | sonar-runner-cli/src/main/java/org/sonar/runner/cli/Stats.java (renamed from sonar-runner-dist/src/main/java/org/sonar/runner/Stats.java) | 6 | ||||
-rw-r--r-- | sonar-runner-cli/src/main/java/org/sonar/runner/cli/SystemInfo.java (renamed from sonar-runner-dist/src/main/java/org/sonar/runner/SystemInfo.java) | 6 | ||||
-rw-r--r-- | sonar-runner-cli/src/main/java/org/sonar/runner/cli/package-info.java (renamed from sonar-runner-dist/src/main/java/org/sonar/runner/package-info.java) | 4 | ||||
-rw-r--r-- | sonar-runner-cli/src/test/java/org/sonar/runner/cli/CliTest.java (renamed from sonar-runner-dist/src/test/java/org/sonar/runner/CliTest.java) | 7 | ||||
-rw-r--r-- | sonar-runner-cli/src/test/java/org/sonar/runner/cli/ConfTest.java (renamed from sonar-runner-dist/src/test/java/org/sonar/runner/ConfTest.java) | 7 | ||||
-rw-r--r-- | sonar-runner-cli/src/test/java/org/sonar/runner/cli/MainTest.java (renamed from sonar-runner-dist/src/test/java/org/sonar/runner/MainTest.java) | 27 | ||||
-rw-r--r-- | sonar-runner-cli/src/test/java/org/sonar/runner/cli/RunnerFactoryTest.java (renamed from sonar-runner-api/src/test/java/org/sonar/runner/api/SimpleRunner.java) | 29 | ||||
-rw-r--r-- | sonar-runner-cli/src/test/java/org/sonar/runner/cli/ShutdownTest.java (renamed from sonar-runner-dist/src/test/java/org/sonar/runner/ShutdownTest.java) | 6 | ||||
-rw-r--r-- | sonar-runner-cli/src/test/java/org/sonar/runner/cli/StatsTest.java (renamed from sonar-runner-dist/src/test/java/org/sonar/runner/StatsTest.java) | 47 | ||||
-rw-r--r-- | sonar-runner-cli/src/test/java/org/sonar/runner/cli/SystemInfoTest.java (renamed from sonar-runner-dist/src/test/java/org/sonar/runner/SystemInfoTest.java) | 5 | ||||
-rw-r--r-- | sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldLoadCompleteConfiguration/project/sonar-project.properties (renamed from sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldLoadCompleteConfiguration/project/sonar-project.properties) | 0 | ||||
-rw-r--r-- | sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldLoadCompleteConfiguration/runner/conf/sonar-runner.properties (renamed from sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldLoadCompleteConfiguration/runner/conf/sonar-runner.properties) | 0 | ||||
-rw-r--r-- | sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfiguration/project/module1/sonar-project.properties (renamed from sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfiguration/project/module1/sonar-project.properties) | 0 | ||||
-rw-r--r-- | sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfiguration/project/module2/sonar-project.properties (renamed from sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfiguration/project/module2/sonar-project.properties) | 0 | ||||
-rw-r--r-- | sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfiguration/project/sonar-project.properties (renamed from sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfiguration/project/sonar-project.properties) | 0 | ||||
-rw-r--r-- | sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfigurationOverrideBasedir/project/module2.properties (renamed from sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfigurationOverrideBasedir/project/module2.properties) | 0 | ||||
-rw-r--r-- | sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfigurationOverrideBasedir/project/module_1/sonar-project.properties (renamed from sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfigurationOverrideBasedir/project/module_1/sonar-project.properties) | 0 | ||||
-rw-r--r-- | sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfigurationOverrideBasedir/project/module_2/Sample.js (renamed from sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfigurationOverrideBasedir/project/module_2/Sample.js) | 0 | ||||
-rw-r--r-- | sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfigurationOverrideBasedir/project/module_3/sonar-project.properties (renamed from sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfigurationOverrideBasedir/project/module_3/sonar-project.properties) | 0 | ||||
-rw-r--r-- | sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfigurationOverrideBasedir/project/sonar-project.properties (renamed from sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfigurationOverrideBasedir/project/sonar-project.properties) | 0 | ||||
-rw-r--r-- | sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldLoadRunnerSettingsByDirectPath/other-conf.properties (renamed from sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldLoadRunnerSettingsByDirectPath/other-conf.properties) | 0 | ||||
-rw-r--r-- | sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldLoadRunnerSettingsByHome/conf/sonar-runner.properties (renamed from sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldLoadRunnerSettingsByHome/conf/sonar-runner.properties) | 0 | ||||
-rw-r--r-- | sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldSupportDeepModuleConfigurationInRoot/project/module1/module11/module111/placeholder.txt (renamed from sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldSupportDeepModuleConfigurationInRoot/project/module1/module11/module111/placeholder.txt) | 0 | ||||
-rw-r--r-- | sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldSupportDeepModuleConfigurationInRoot/project/module1/module11/module112/placeholder.txt (renamed from sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldSupportDeepModuleConfigurationInRoot/project/module1/module11/module112/placeholder.txt) | 0 | ||||
-rw-r--r-- | sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldSupportDeepModuleConfigurationInRoot/project/module1/module12/placeholder.txt (renamed from sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldSupportDeepModuleConfigurationInRoot/project/module1/module12/placeholder.txt) | 0 | ||||
-rw-r--r-- | sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldSupportDeepModuleConfigurationInRoot/project/module2/module21/placeholder.txt (renamed from sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldSupportDeepModuleConfigurationInRoot/project/module2/module21/placeholder.txt) | 0 | ||||
-rw-r--r-- | sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldSupportDeepModuleConfigurationInRoot/project/module2/module22/placeholder.txt (renamed from sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldSupportDeepModuleConfigurationInRoot/project/module2/module22/placeholder.txt) | 0 | ||||
-rw-r--r-- | sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldSupportDeepModuleConfigurationInRoot/project/sonar-project.properties (renamed from sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldSupportDeepModuleConfigurationInRoot/project/sonar-project.properties) | 0 | ||||
-rw-r--r-- | sonar-runner-cli/src/test/resources/org/sonar/runner/RunnerTest/shouldInitDirs/fake.txt (renamed from sonar-runner-dist/src/test/resources/org/sonar/runner/RunnerTest/shouldInitDirs/fake.txt) | 0 | ||||
-rw-r--r-- | sonar-runner-dist/src/test/java/org/sonar/runner/RunnerFactoryTest.java | 69 | ||||
-rw-r--r-- | sonar-runner-impl/pom.xml | 140 | ||||
-rw-r--r-- | sonar-runner-impl/src/main/java/org/sonar/runner/impl/BatchLauncherMain.java | 71 | ||||
-rw-r--r-- | sonar-runner-impl/src/main/java/org/sonar/runner/impl/Logs.java | 125 | ||||
-rw-r--r-- | sonar-runner-impl/src/test/java/org/sonar/runner/impl/BatchLauncherMainTest.java | 81 | ||||
-rw-r--r-- | sonar-runner-impl/src/test/java/org/sonar/runner/impl/LogsTest.java | 106 |
97 files changed, 653 insertions, 2691 deletions
@@ -27,8 +27,7 @@ <module>sonar-runner-api</module> <module>sonar-runner-batch</module> <module>sonar-runner-batch-interface</module> - <module>sonar-runner-dist</module> - <module>sonar-runner-impl</module> + <module>sonar-runner-cli</module> </modules> <organization> @@ -57,7 +56,6 @@ </issueManagement> <properties> - <sonar.buildVersion>3.5</sonar.buildVersion> <maven.test.redirectTestOutputToFile>true</maven.test.redirectTestOutputToFile> </properties> diff --git a/sonar-runner-api/pom.xml b/sonar-runner-api/pom.xml index b138660..6e94115 100644 --- a/sonar-runner-api/pom.xml +++ b/sonar-runner-api/pom.xml @@ -11,25 +11,37 @@ <dependencies> <!-- Dependencies with scope "compile" are shaded and removed from transitive dependencies--> - <dependency> - <groupId>${project.groupId}</groupId> - <artifactId>sonar-runner-impl</artifactId> - <version>${project.version}</version> - + <dependency> + <groupId>com.github.kevinsawicki</groupId> + <artifactId>http-request</artifactId> </dependency> <dependency> <groupId>com.google.code.findbugs</groupId> <artifactId>jsr305</artifactId> <scope>provided</scope> </dependency> - - <!-- Unit tests --> <dependency> - <groupId>commons-lang</groupId> - <artifactId>commons-lang</artifactId> - <scope>test</scope> + <groupId>org.codehaus.sonar</groupId> + <artifactId>sonar-home</artifactId> + </dependency> + <dependency> + <groupId>commons-io</groupId> + <artifactId>commons-io</artifactId> + </dependency> + <dependency> + <groupId>${project.groupId}</groupId> + <artifactId>sonar-runner-batch</artifactId> + <version>${project.version}</version> + <scope>provided</scope> </dependency> <dependency> + <groupId>${project.groupId}</groupId> + <artifactId>sonar-runner-batch-interface</artifactId> + <version>${project.version}</version> + </dependency> + + <!-- unit tests --> + <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> @@ -44,6 +56,23 @@ <artifactId>mockito-all</artifactId> <scope>test</scope> </dependency> + <dependency> + <groupId>org.assertj</groupId> + <artifactId>assertj-core</artifactId> + <version>1.7.1</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.mortbay.jetty</groupId> + <artifactId>jetty</artifactId> + <version>6.1.25</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>commons-lang</groupId> + <artifactId>commons-lang</artifactId> + <scope>test</scope> + </dependency> </dependencies> <build> @@ -81,12 +110,12 @@ <artifactItems> <artifactItem> <groupId>${project.groupId}</groupId> - <artifactId>sonar-runner-impl</artifactId> + <artifactId>sonar-runner-batch</artifactId> <version>${project.version}</version> <type>jar</type> <overWrite>false</overWrite> <outputDirectory>${project.build.outputDirectory}</outputDirectory> - <destFileName>sonar-runner-impl.jar</destFileName> + <destFileName>sonar-runner-batch.jar</destFileName> </artifactItem> </artifactItems> <overWriteReleases>true</overWriteReleases> @@ -107,6 +136,20 @@ <configuration> <createDependencyReducedPom>true</createDependencyReducedPom> <minimizeJar>true</minimizeJar> + <relocations> + <relocation> + <pattern>com.github.kevinsawicki.http</pattern> + <shadedPattern>org.sonar.runner.kevinsawicki</shadedPattern> + </relocation> + <relocation> + <pattern>org.apache.commons.io</pattern> + <shadedPattern>org.sonar.runner.commonsio</shadedPattern> + </relocation> + <relocation> + <pattern>org.sonar.home</pattern> + <shadedPattern>org.sonar.runner.home</shadedPattern> + </relocation> + </relocations> </configuration> </execution> </executions> @@ -120,7 +163,7 @@ <instructions> <Import-Package>!*</Import-Package> <Export-Package>!.,org.sonar.runner.api</Export-Package> - <Bundle-RequiredExecutionEnvironment>J2SE-1.5</Bundle-RequiredExecutionEnvironment> + <Bundle-RequiredExecutionEnvironment>JavaSE-1.7</Bundle-RequiredExecutionEnvironment> </instructions> </configuration> <executions> diff --git a/sonar-runner-api/src/main/java/org/sonar/runner/api/Command.java b/sonar-runner-api/src/main/java/org/sonar/runner/api/Command.java deleted file mode 100644 index b427c14..0000000 --- a/sonar-runner-api/src/main/java/org/sonar/runner/api/Command.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * SonarQube Runner - API - * Copyright (C) 2011 SonarSource - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.runner.api; - -import java.io.File; -import java.util.*; - -class Command { - private final String executable; - private final List<String> arguments; - private final Map<String, String> env; - private final File directory; - - private Command(Builder builder) { - this.executable = builder.executable; - this.arguments = Collections.unmodifiableList(builder.arguments); - this.env = Collections.unmodifiableMap(builder.env); - this.directory = builder.directory; - } - - File directory() { - return directory; - } - - String executable() { - return executable; - } - - List<String> arguments() { - return arguments; - } - - /** - * Environment variables that are propagated during command execution. - * - * @return a non-null and immutable map of variables - */ - Map<String, String> envVariables() { - return env; - } - - String[] toStrings() { - String[] strings = new String[1 + arguments.size()]; - strings[0] = executable; - for (int index = 0; index < arguments.size(); index++) { - strings[index + 1] = arguments.get(index); - } - return strings; - } - - @Override - public String toString() { - return Utils.join(toStrings(), " "); - } - - static Builder builder() { - return new Builder(); - } - - static class Builder { - private String executable; - private final List<String> arguments = new ArrayList<String>(); - private final Map<String, String> env = new HashMap<String, String>(); - private File directory; - - private Builder() { - } - - Builder setExecutable(String s) { - this.executable = s; - return this; - } - - Builder addArguments(String... args) { - return addArguments(Arrays.asList(args)); - } - - Builder addArguments(List<String> args) { - for (String arg : args) { - if (arg != null && !"".equals(arg.trim())) { - arguments.add(arg); - } - } - return this; - } - - Builder setEnvVariable(String key, String value) { - env.put(key, value); - return this; - } - - Builder addEnvVariables(Map<String, String> map) { - env.putAll(map); - return this; - } - - Builder setDirectory(File d) { - this.directory = d; - return this; - } - - Command build() { - if (executable == null) { - throw new IllegalArgumentException("Command executable is not defined"); - } - return new Command(this); - } - } -} diff --git a/sonar-runner-api/src/main/java/org/sonar/runner/api/CommandExecutor.java b/sonar-runner-api/src/main/java/org/sonar/runner/api/CommandExecutor.java deleted file mode 100644 index 27140b3..0000000 --- a/sonar-runner-api/src/main/java/org/sonar/runner/api/CommandExecutor.java +++ /dev/null @@ -1,198 +0,0 @@ -/* - * SonarQube Runner - API - * Copyright (C) 2011 SonarSource - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.runner.api; - -import org.sonar.runner.impl.Logs; - -import javax.annotation.Nullable; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -/** - * Synchronously execute a native command line. It's much more limited than the Apache Commons Exec library. - * For example it does not allow to run asynchronously or to automatically quote command-line arguments. - * - * @since 2.7 - */ -class CommandExecutor { - - private static final CommandExecutor INSTANCE = new CommandExecutor(); - - private CommandExecutor() { - } - - static CommandExecutor create() { - // stateless object, so a single singleton can be shared - return INSTANCE; - } - - int execute(Command command, StreamConsumer stdOut, StreamConsumer stdErr, long timeoutMilliseconds, @Nullable ProcessMonitor processMonitor) { - ExecutorService executorService = null; - Process process = null; - StreamGobbler outputGobbler = null; - StreamGobbler errorGobbler = null; - try { - ProcessBuilder builder = new ProcessBuilder(command.toStrings()); - builder.directory(command.directory()); - builder.environment().putAll(command.envVariables()); - process = builder.start(); - - outputGobbler = new StreamGobbler(process.getInputStream(), stdOut); - errorGobbler = new StreamGobbler(process.getErrorStream(), stdErr); - outputGobbler.start(); - errorGobbler.start(); - - executorService = Executors.newSingleThreadExecutor(); - final Future<Integer> futureTask = executeProcess(executorService, process); - if (processMonitor != null) { - monitorProcess(processMonitor, executorService, process); - } - - int exitCode = futureTask.get(timeoutMilliseconds, TimeUnit.MILLISECONDS); - waitUntilFinish(outputGobbler); - waitUntilFinish(errorGobbler); - verifyGobbler(command, outputGobbler, "stdOut"); - verifyGobbler(command, errorGobbler, "stdErr"); - return exitCode; - - } catch (TimeoutException te) { - if (process != null) { - process.destroy(); - } - throw new CommandException("Timeout exceeded: " + timeoutMilliseconds + " ms", command, te); - - } catch (CommandException e) { - throw e; - - } catch (Exception e) { - throw new CommandException("Fail to execute command", command, e); - - } finally { - waitUntilFinish(outputGobbler); - waitUntilFinish(errorGobbler); - closeStreams(process); - if (executorService != null) { - executorService.shutdown(); - } - } - } - - private static void monitorProcess(final ProcessMonitor processMonitor, final ExecutorService executor, final Process process) { - new Thread() { - @Override - public void run() { - while (!executor.isTerminated()) { - if (processMonitor.stop()) { - process.destroy(); - } - try { - Thread.sleep(100); - } catch (InterruptedException e) { - // ignore - } - } - } - }.start(); - } - - private Future<Integer> executeProcess(ExecutorService executorService, Process process) { - final Process finalProcess = process; - return executorService.submit(new Callable<Integer>() { - @Override - public Integer call() throws InterruptedException { - return finalProcess.waitFor(); - } - }); - } - - private static void verifyGobbler(Command command, StreamGobbler gobbler, String type) { - if (gobbler.getException() != null) { - throw new CommandException("Error inside " + type + " stream", command, gobbler.getException()); - } - } - - private static void closeStreams(Process process) { - if (process != null) { - Utils.closeQuietly(process.getInputStream()); - Utils.closeQuietly(process.getInputStream()); - Utils.closeQuietly(process.getOutputStream()); - Utils.closeQuietly(process.getErrorStream()); - } - } - - private static void waitUntilFinish(StreamGobbler thread) { - if (thread != null) { - try { - thread.join(); - } catch (InterruptedException e) { - Logs.error("InterruptedException while waiting finish of " + thread.toString(), e); - } - } - } - - private static class StreamGobbler extends Thread { - private final InputStream is; - private final StreamConsumer consumer; - private volatile Exception exception; - - StreamGobbler(InputStream is, StreamConsumer consumer) { - super("ProcessStreamGobbler"); - this.is = is; - this.consumer = consumer; - } - - @Override - public void run() { - try (InputStreamReader isr = new InputStreamReader(is); - BufferedReader br = new BufferedReader(isr)) { - String line; - while ((line = br.readLine()) != null) { - consumeLine(line); - } - } catch (IOException ioe) { - exception = ioe; - - } - } - - private void consumeLine(String line) { - if (exception == null) { - try { - consumer.consumeLine(line); - } catch (Exception e) { - exception = e; - } - } - } - - public Exception getException() { - return exception; - } - } -} diff --git a/sonar-runner-api/src/main/java/org/sonar/runner/api/Dirs.java b/sonar-runner-api/src/main/java/org/sonar/runner/api/Dirs.java index 2ab4d6c..c592237 100644 --- a/sonar-runner-api/src/main/java/org/sonar/runner/api/Dirs.java +++ b/sonar-runner-api/src/main/java/org/sonar/runner/api/Dirs.java @@ -19,17 +19,19 @@ */ package org.sonar.runner.api; -import org.sonar.runner.impl.Logs; - import java.io.File; import java.util.Properties; +import org.sonar.home.cache.Logger; class Dirs { - private Dirs() { + private final Logger logger; + + Dirs(Logger logger) { + this.logger = logger; } - static void init(Properties p) { + void init(Properties p) { boolean onProject = Utils.taskRequiresProject(p); if (onProject) { initProjectDirs(p); @@ -38,7 +40,7 @@ class Dirs { } } - private static void initProjectDirs(Properties p) { + private void initProjectDirs(Properties p) { String path = p.getProperty(ScanProperties.PROJECT_BASEDIR, "."); File projectDir = new File(path); if (!projectDir.isDirectory()) { @@ -59,7 +61,7 @@ class Dirs { } Utils.deleteQuietly(workDir); p.setProperty(RunnerProperties.WORK_DIR, workDir.getAbsolutePath()); - Logs.info("Work directory: " + workDir.getAbsolutePath()); + logger.info("Work directory: " + workDir.getAbsolutePath()); } /** diff --git a/sonar-runner-api/src/main/java/org/sonar/runner/api/EmbeddedRunner.java b/sonar-runner-api/src/main/java/org/sonar/runner/api/EmbeddedRunner.java index 4883ea0..d48ca77 100644 --- a/sonar-runner-api/src/main/java/org/sonar/runner/api/EmbeddedRunner.java +++ b/sonar-runner-api/src/main/java/org/sonar/runner/api/EmbeddedRunner.java @@ -19,110 +19,202 @@ */ package org.sonar.runner.api; -import org.sonar.home.log.LogListener; - -import org.sonar.runner.impl.Logs; +import java.io.File; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.nio.charset.Charset; +import java.util.Locale; +import java.util.Properties; +import javax.annotation.Nullable; +import org.sonar.home.cache.Logger; import org.sonar.runner.batch.IsolatedLauncher; +import org.sonar.runner.impl.InternalProperties; import org.sonar.runner.impl.IsolatedLauncherFactory; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Properties; - /** - * Implementation of {@link Runner} that is executed in the same JVM. The application can inject - * some extensions into Sonar IoC container (see {@link #addExtensions(Object...)}. It can be - * used for example in the Maven Sonar plugin to register Maven components like MavenProject - * or MavenPluginExecutor. + * Entry point to run SonarQube analysis programmatically. * @since 2.2 */ -public class EmbeddedRunner extends Runner<EmbeddedRunner> { +public class EmbeddedRunner { private final IsolatedLauncherFactory launcherFactory; private IsolatedLauncher launcher; - private final List<Object> extensions = new ArrayList<Object>(); - private static final String MASK_RULES_PROP = "sonarRunner.maskRules"; + private final LogOutput logOutput; + private final Properties globalProperties = new Properties(); + private final Logger logger; - EmbeddedRunner(IsolatedLauncherFactory bl) { + EmbeddedRunner(IsolatedLauncherFactory bl, Logger logger, LogOutput logOutput) { + this.logger = logger; this.launcherFactory = bl; + this.logOutput = logOutput; } - /** - * Create a new instance. - */ - public static EmbeddedRunner create() { - return new EmbeddedRunner(new IsolatedLauncherFactory()); + public static EmbeddedRunner create(final LogOutput logOutput) { + Logger logger = new Logger() { + + @Override + public void warn(String msg) { + logOutput.log(msg, LogOutput.Level.WARN); + } + + @Override + public void info(String msg) { + logOutput.log(msg, LogOutput.Level.INFO); + } + + @Override + public void error(String msg, Throwable t) { + StringWriter errors = new StringWriter(); + t.printStackTrace(new PrintWriter(errors)); + logOutput.log(msg + "\n" + errors.toString(), LogOutput.Level.ERROR); + } + + @Override + public void error(String msg) { + logOutput.log(msg, LogOutput.Level.ERROR); + } + + @Override + public void debug(String msg) { + logOutput.log(msg, LogOutput.Level.DEBUG); + } + }; + return new EmbeddedRunner(new IsolatedLauncherFactory(logger), logger, logOutput); + } + + public Properties globalProperties() { + Properties clone = new Properties(); + clone.putAll(globalProperties); + return clone; } - public static EmbeddedRunner create(LogListener logListener) { - Logs.setListener(logListener); - return new EmbeddedRunner(new IsolatedLauncherFactory()); + /** + * Declare Sonar properties, for example sonar.projectKey=>foo. + * + * @see #setProperty(String, String) + */ + public EmbeddedRunner addGlobalProperties(Properties p) { + globalProperties.putAll(p); + return this; } /** - * Sonar is executed in an almost fully isolated classloader (mask everything by default). This method allows to unmask some classes based on - * a prefix of their fully qualified name. It is related to the extensions provided by {@link #addExtensions(Object...)}. - * Complex mask/unmask rules can be defined by chaining several ordered calls to {@link #unmask(String)} and {@link #mask(String)}. - * Registered mask/unmask rules are considered in their registration order and as soon as a matching prefix is found - * the class is masked/unmasked accordingly. - * If no matching prefix can be found then by default class is masked. + * Declare a SonarQube property. + * + * @see RunnerProperties + * @see ScanProperties */ - public EmbeddedRunner unmask(String fqcnPrefix) { - return addMaskRule("UNMASK", fqcnPrefix); + public EmbeddedRunner setGlobalProperty(String key, String value) { + globalProperties.setProperty(key, value); + return this; + } + + public String globalProperty(String key, @Nullable String defaultValue) { + return globalProperties.getProperty(key, defaultValue); } /** - * @see EmbeddedRunner#unmask(String) + * User-agent used in the HTTP requests to the SonarQube server */ - public EmbeddedRunner mask(String fqcnPrefix) { - return addMaskRule("MASK", fqcnPrefix); + public EmbeddedRunner setApp(String app, String version) { + setGlobalProperty(InternalProperties.RUNNER_APP, app); + setGlobalProperty(InternalProperties.RUNNER_APP_VERSION, version); + return this; + } + + public String app() { + return globalProperty(InternalProperties.RUNNER_APP, null); + } + + public String appVersion() { + return globalProperty(InternalProperties.RUNNER_APP_VERSION, null); } - private EmbeddedRunner addMaskRule(String type, String fqcnPrefix) { - String existingRules = globalProperty(MASK_RULES_PROP, ""); - if (!"".equals(existingRules)) { - existingRules += ","; + public void runAnalysis(Properties analysisProperties) { + Properties copy = new Properties(); + copy.putAll(analysisProperties); + initAnalysisProperties(copy); + + String dumpToFile = copy.getProperty(InternalProperties.RUNNER_DUMP_TO_FILE); + if (dumpToFile != null) { + File dumpFile = new File(dumpToFile); + Utils.writeProperties(dumpFile, copy); + logger.info("Simulation mode. Configuration written to " + dumpFile.getAbsolutePath()); + } else { + doExecute(copy); } - existingRules += type + "|" + fqcnPrefix; - return setGlobalProperty(MASK_RULES_PROP, existingRules); + } + + public void start() { + initGlobalDefaultValues(); + doStart(); + } + + public void stop() { + doStop(); } /** - * @deprecated since 2.3 use {@link #unmask(String)} + * @deprecated since 2.5 use {@link #start()}, {@link #runAnalysis(Properties)} and then {@link #stop()} */ @Deprecated - public EmbeddedRunner setUnmaskedPackages(String... packages) { - for (String packagePrefix : packages) { - unmask(packagePrefix + "."); - } - return this; + public final void execute() { + start(); + runAnalysis(new Properties()); + stop(); } - public EmbeddedRunner addExtensions(Object... objects) { - extensions.addAll(Arrays.asList(objects)); - return this; + private void initGlobalDefaultValues() { + setGlobalDefaultValue(RunnerProperties.HOST_URL, "http://localhost:9000"); + setGlobalDefaultValue(InternalProperties.RUNNER_APP, "SonarQubeRunner"); + setGlobalDefaultValue(InternalProperties.RUNNER_APP_VERSION, RunnerVersion.version()); } - List<Object> extensions() { - return extensions; + private void initAnalysisProperties(Properties p) { + initSourceEncoding(p); + new Dirs(logger).init(p); + } + + void initSourceEncoding(Properties p) { + boolean onProject = Utils.taskRequiresProject(p); + if (onProject) { + String sourceEncoding = p.getProperty(ScanProperties.PROJECT_SOURCE_ENCODING, ""); + boolean platformDependent = false; + if ("".equals(sourceEncoding)) { + sourceEncoding = Charset.defaultCharset().name(); + platformDependent = true; + p.setProperty(ScanProperties.PROJECT_SOURCE_ENCODING, sourceEncoding); + } + logger.info("Default locale: \"" + Locale.getDefault() + "\", source code encoding: \"" + sourceEncoding + "\"" + + (platformDependent ? " (analysis is platform dependent)" : "")); + } + } + + private void setGlobalDefaultValue(String key, String value) { + if (!globalProperties.containsKey(key)) { + setGlobalProperty(key, value); + } } - @Override protected void doStart() { launcher = launcherFactory.createLauncher(globalProperties()); if (Utils.isAtLeast52(launcher.getVersion())) { - launcher.start(globalProperties(), extensions, Logs.getListener()); + launcher.start(globalProperties(), new org.sonar.runner.batch.LogOutput() { + + @Override + public void log(String formattedMessage, Level level) { + logOutput.log(formattedMessage, LogOutput.Level.valueOf(level.name())); + } + + }); } } - @Override protected void doStop() { if (Utils.isAtLeast52(launcher.getVersion())) { launcher.stop(); } } - @Override protected void doExecute(Properties analysisProperties) { if (Utils.isAtLeast52(launcher.getVersion())) { launcher.execute(analysisProperties); @@ -130,7 +222,7 @@ public class EmbeddedRunner extends Runner<EmbeddedRunner> { Properties prop = new Properties(); prop.putAll(globalProperties()); prop.putAll(analysisProperties); - launcher.executeOldVersion(prop, extensions); + launcher.executeOldVersion(prop); } } } diff --git a/sonar-runner-api/src/main/java/org/sonar/runner/api/ForkedRunner.java b/sonar-runner-api/src/main/java/org/sonar/runner/api/ForkedRunner.java deleted file mode 100644 index 2a3e2b5..0000000 --- a/sonar-runner-api/src/main/java/org/sonar/runner/api/ForkedRunner.java +++ /dev/null @@ -1,243 +0,0 @@ -/* - * SonarQube Runner - API - * Copyright (C) 2011 SonarSource - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.runner.api; - -import org.sonar.runner.impl.Logs; -import org.sonar.runner.impl.BatchLauncherMain; -import org.sonar.runner.impl.JarExtractor; - -import javax.annotation.Nullable; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -/** - * Runner executed in a new JVM. - * - * @since 2.2 - */ -public class ForkedRunner extends Runner<ForkedRunner> { - - private static final int ONE_DAY_IN_MILLISECONDS = 24 * 60 * 60 * 1000; - - private final Map<String, String> jvmEnvVariables = new HashMap<String, String>(); - private final List<String> jvmArguments = new ArrayList<String>(); - private String javaExecutable; - private StreamConsumer stdOut = null; - private StreamConsumer stdErr = null; - private final JarExtractor jarExtractor; - private final CommandExecutor commandExecutor; - - private ProcessMonitor processMonitor; - - ForkedRunner(JarExtractor jarExtractor, CommandExecutor commandExecutor, @Nullable ProcessMonitor processMonitor) { - this.jarExtractor = jarExtractor; - this.commandExecutor = commandExecutor; - this.processMonitor = processMonitor; - } - - ForkedRunner(JarExtractor jarExtractor, CommandExecutor commandExecutor) { - this(jarExtractor, commandExecutor, null); - } - - /** - * Create new instance. Never return null. - */ - public static ForkedRunner create() { - return new ForkedRunner(new JarExtractor(), CommandExecutor.create()); - } - - /** - * Create new instance. Never return null. - */ - public static ForkedRunner create(ProcessMonitor processMonitor) { - return new ForkedRunner(new JarExtractor(), CommandExecutor.create(), processMonitor); - } - - /** - * Path to the java executable. The JVM of the client app is used by default - * (see the system property java.home) - */ - public ForkedRunner setJavaExecutable(@Nullable String s) { - this.javaExecutable = s; - return this; - } - - public List<String> jvmArguments() { - return new ArrayList<String>(jvmArguments); - } - - /** - * See {@link #addJvmArguments(java.util.List)} - */ - public ForkedRunner addJvmArguments(String... s) { - return addJvmArguments(Arrays.asList(s)); - } - - /** - * JVM arguments, for example "-Xmx512m" - */ - public ForkedRunner addJvmArguments(List<String> args) { - jvmArguments.addAll(args); - return this; - } - - /** - * Set a JVM environment variable. By default no variables are set. - */ - public ForkedRunner setJvmEnvVariable(String key, String value) { - jvmEnvVariables.put(key, value); - return this; - } - - /** - * Add some JVM environment variables. By default no variables are set. - */ - public ForkedRunner addJvmEnvVariables(Map<String, String> map) { - jvmEnvVariables.putAll(map); - return this; - } - - /** - * @deprecated Since 2.5. Use {@link ForkedRunner#setLogListener} instead. - * Subscribe to the standard output from the forked process. By default, logs messages are sent with INFO level to the log listener set. - */ - public ForkedRunner setStdOut(@Nullable StreamConsumer stream) { - this.stdOut = stream; - return this; - } - - /** - * @deprecated Since 2.5. Use {@link ForkedRunner#setLogListener}instead. - * Subscribe to the error output from the forked process. By default, logs messages are sent with ERROR level to the log listener set. - */ - public ForkedRunner setStdErr(@Nullable StreamConsumer stream) { - this.stdErr = stream; - return this; - } - - @Override - protected void doExecute(Properties props) { - // merge both global and analysis-specific properties because it will be used both to start and to execute. - Properties p = new Properties(); - - p.putAll(globalProperties()); - p.putAll(props); - - ForkCommand forkCommand = createCommand(p); - try { - fork(forkCommand); - } finally { - deleteTempFiles(forkCommand); - } - } - - @Override - protected void doStop() { - // nothing to do - } - - @Override - protected void doStart() { - // nothing to do - } - - ForkCommand createCommand(Properties p) { - File propertiesFile = writeProperties(p); - File jarFile = jarExtractor.extractToTemp("sonar-runner-impl"); - if (javaExecutable == null) { - javaExecutable = new Os().thisJavaExe().getAbsolutePath(); - } - Command command = Command.builder() - .setExecutable(javaExecutable) - .addEnvVariables(jvmEnvVariables) - .addArguments(jvmArguments) - .addArguments("-cp", jarFile.getAbsolutePath(), BatchLauncherMain.class.getName(), propertiesFile.getAbsolutePath()) - .build(); - return new ForkCommand(command, jarFile, propertiesFile); - } - - File writeProperties(Properties p) { - try { - File file = File.createTempFile("sonar-project", ".properties"); - try (OutputStream output = new FileOutputStream(file)) { - p.store(output, "Generated by sonar-runner"); - return file; - } - } catch (Exception e) { - throw new IllegalStateException("Fail to export sonar-runner properties", e); - } - } - - private static void deleteTempFiles(ForkCommand forkCommand) { - Utils.deleteQuietly(forkCommand.jarFile); - Utils.deleteQuietly(forkCommand.propertiesFile); - } - - private void fork(ForkCommand forkCommand) { - if (stdOut == null) { - stdOut = new OutConsumer(); - } - if (stdErr == null) { - stdErr = new ErrConsumer(); - } - - int status = commandExecutor.execute(forkCommand.command, stdOut, stdErr, ONE_DAY_IN_MILLISECONDS, processMonitor); - if (status != 0) { - if (processMonitor != null && processMonitor.stop()) { - stdOut.consumeLine(String.format("SonarQube Runner was stopped [status=%s]", status)); - } else { - throw new IllegalStateException("Error status [command: " + forkCommand.command + "]: " + status); - } - } - } - - private static class OutConsumer implements StreamConsumer { - @Override - public void consumeLine(String line) { - Logs.info(line); - } - } - private static class ErrConsumer implements StreamConsumer { - @Override - public void consumeLine(String line) { - Logs.error(line); - } - } - - static class ForkCommand { - Command command; - File jarFile; - File propertiesFile; - - private ForkCommand(Command command, File jarFile, File propertiesFile) { - this.command = command; - this.jarFile = jarFile; - this.propertiesFile = propertiesFile; - } - } -} diff --git a/sonar-runner-api/src/main/java/org/sonar/runner/api/LogListener.java b/sonar-runner-api/src/main/java/org/sonar/runner/api/LogOutput.java index bfcfdc4..4dfe94e 100644 --- a/sonar-runner-api/src/main/java/org/sonar/runner/api/LogListener.java +++ b/sonar-runner-api/src/main/java/org/sonar/runner/api/LogOutput.java @@ -19,8 +19,9 @@ */ package org.sonar.runner.api; -public interface LogListener { - void log(String msg, Level level); +public interface LogOutput { + + void log(String formattedMessage, Level level); enum Level { ERROR, WARN, INFO, DEBUG, TRACE; diff --git a/sonar-runner-api/src/main/java/org/sonar/runner/api/Os.java b/sonar-runner-api/src/main/java/org/sonar/runner/api/Os.java deleted file mode 100644 index 168f722..0000000 --- a/sonar-runner-api/src/main/java/org/sonar/runner/api/Os.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * SonarQube Runner - API - * Copyright (C) 2011 SonarSource - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.runner.api; - -import java.io.File; - -class Os { - boolean isWindows() { - return System.getProperty("os.name").contains("Windows"); - } - - File thisJavaHome() { - return new File(System.getProperty("java.home")); - } - - /** - * Path to the java executable used by this VM - */ - File thisJavaExe() { - File bin = new File(thisJavaHome(), "bin"); - return new File(bin, isWindows() ? "java.exe" : "java"); - } -} diff --git a/sonar-runner-api/src/main/java/org/sonar/runner/api/PrintStreamConsumer.java b/sonar-runner-api/src/main/java/org/sonar/runner/api/PrintStreamConsumer.java deleted file mode 100644 index bab55a7..0000000 --- a/sonar-runner-api/src/main/java/org/sonar/runner/api/PrintStreamConsumer.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * SonarQube Runner - API - * Copyright (C) 2011 SonarSource - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.runner.api; - -import java.io.PrintStream; - -/** - * Implementation of StreamConsumer that prints lines to {@link java.io.PrintStream}. Generally used - * to forward to {@link System.out} or {@link System.err}. - * - * @since 2.2 - */ -public class PrintStreamConsumer implements StreamConsumer { - final PrintStream output; - - public PrintStreamConsumer(PrintStream output) { - this.output = output; - } - - @Override - public void consumeLine(String line) { - output.println(line); - } -} diff --git a/sonar-runner-api/src/main/java/org/sonar/runner/api/Runner.java b/sonar-runner-api/src/main/java/org/sonar/runner/api/Runner.java deleted file mode 100644 index 1bd0515..0000000 --- a/sonar-runner-api/src/main/java/org/sonar/runner/api/Runner.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * SonarQube Runner - API - * Copyright (C) 2011 SonarSource - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.runner.api; - -import org.sonar.runner.impl.Logs; -import org.sonar.runner.impl.InternalProperties; - -import javax.annotation.Nullable; - -import java.io.File; -import java.util.Properties; - -/** - * @since 2.2 - */ -public abstract class Runner<T extends Runner<?>> { - private final Properties globalProperties = new Properties(); - - protected Runner() { - } - - public Properties globalProperties() { - Properties clone = new Properties(); - clone.putAll(globalProperties); - return clone; - } - - /** - * Set a log stream. All log events will be redirected to the listener. - * By default, all logs are sent to stdout, except for logs of ERROR level, which are sent to stderr. - * If null is given, the default is behavior is set. - */ - public T setLogListener(LogListener stream) { - Logs.setListener(new LogListenerAdapter(stream)); - return (T) this; - } - - /** - * Declare Sonar properties, for example sonar.projectKey=>foo. - * - * @see #setProperty(String, String) - */ - public T addGlobalProperties(Properties p) { - globalProperties.putAll(p); - return (T) this; - } - - /** - * Declare a Sonar property. - * - * @see RunnerProperties - * @see ScanProperties - */ - public T setGlobalProperty(String key, String value) { - globalProperties.setProperty(key, value); - return (T) this; - } - - public String globalProperty(String key, @Nullable String defaultValue) { - return globalProperties.getProperty(key, defaultValue); - } - - /** - * User-agent used in the HTTP requests to the Sonar server - */ - public T setApp(String app, String version) { - setGlobalProperty(InternalProperties.RUNNER_APP, app); - setGlobalProperty(InternalProperties.RUNNER_APP_VERSION, version); - return (T) this; - } - - public String app() { - return globalProperty(InternalProperties.RUNNER_APP, null); - } - - public String appVersion() { - return globalProperty(InternalProperties.RUNNER_APP_VERSION, null); - } - - public void runAnalysis(Properties analysisProperties) { - Properties copy = new Properties(); - copy.putAll(analysisProperties); - initAnalysisProperties(copy); - - String dumpToFile = copy.getProperty(InternalProperties.RUNNER_DUMP_TO_FILE); - if (dumpToFile != null) { - File dumpFile = new File(dumpToFile); - Utils.writeProperties(dumpFile, copy); - Logs.info("Simulation mode. Configuration written to " + dumpFile.getAbsolutePath()); - } else { - doExecute(copy); - } - } - - public void start() { - initGlobalDefaultValues(); - doStart(); - } - - public void stop() { - doStop(); - } - - /** - * @deprecated since 2.5 use {@link #start()}, {@link #runAnalysis(Properties)} and then {@link #stop()} - */ - @Deprecated - public final void execute() { - start(); - runAnalysis(new Properties()); - stop(); - } - - protected abstract void doStart(); - - protected abstract void doStop(); - - protected abstract void doExecute(Properties analysisProperties); - - private void initGlobalDefaultValues() { - setGlobalDefaultValue(RunnerProperties.HOST_URL, "http://localhost:9000"); - setGlobalDefaultValue(InternalProperties.RUNNER_APP, "SonarQubeRunner"); - setGlobalDefaultValue(InternalProperties.RUNNER_APP_VERSION, RunnerVersion.version()); - } - - private static void initAnalysisProperties(Properties p) { - SourceEncoding.init(p); - Dirs.init(p); - } - - private void setGlobalDefaultValue(String key, String value) { - if (!globalProperties.containsKey(key)) { - setGlobalProperty(key, value); - } - } - - private class LogListenerAdapter implements org.sonar.home.log.LogListener { - private LogListener adaptedListener; - - LogListenerAdapter(LogListener listener) { - this.adaptedListener = listener; - } - - @Override - public void log(String msg, org.sonar.home.log.LogListener.Level level) { - this.adaptedListener.log(msg, translate(level)); - } - private LogListener.Level translate(org.sonar.home.log.LogListener.Level level) { - switch(level) { - case ERROR: - return LogListener.Level.ERROR; - case WARN: - return LogListener.Level.WARN; - case INFO: - return LogListener.Level.INFO; - case DEBUG: - default: - return LogListener.Level.DEBUG; - case TRACE: - return LogListener.Level.TRACE; - } - } - } -} diff --git a/sonar-runner-api/src/main/java/org/sonar/runner/api/SourceEncoding.java b/sonar-runner-api/src/main/java/org/sonar/runner/api/SourceEncoding.java deleted file mode 100644 index d21f9f3..0000000 --- a/sonar-runner-api/src/main/java/org/sonar/runner/api/SourceEncoding.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * SonarQube Runner - API - * Copyright (C) 2011 SonarSource - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.runner.api; - -import org.sonar.runner.impl.Logs; - -import java.nio.charset.Charset; -import java.util.Locale; -import java.util.Properties; - -class SourceEncoding { - private SourceEncoding() { - - } - - static void init(Properties p) { - boolean onProject = Utils.taskRequiresProject(p); - if (onProject) { - String sourceEncoding = p.getProperty(ScanProperties.PROJECT_SOURCE_ENCODING, ""); - boolean platformDependent = false; - if ("".equals(sourceEncoding)) { - sourceEncoding = Charset.defaultCharset().name(); - platformDependent = true; - p.setProperty(ScanProperties.PROJECT_SOURCE_ENCODING, sourceEncoding); - } - Logs.info("Default locale: \"" + Locale.getDefault() + "\", source code encoding: \"" + sourceEncoding + "\"" - + (platformDependent ? " (analysis is platform dependent)" : "")); - } - } -} diff --git a/sonar-runner-api/src/main/java/org/sonar/runner/api/StreamConsumer.java b/sonar-runner-api/src/main/java/org/sonar/runner/api/StdOutLogOutput.java index a1d0d7c..016e614 100644 --- a/sonar-runner-api/src/main/java/org/sonar/runner/api/StreamConsumer.java +++ b/sonar-runner-api/src/main/java/org/sonar/runner/api/StdOutLogOutput.java @@ -19,9 +19,10 @@ */ package org.sonar.runner.api; -/** - * @since 2.2 - */ -public interface StreamConsumer { - void consumeLine(String line); +public class StdOutLogOutput implements LogOutput { + + @Override + public void log(String formattedMessage, org.sonar.runner.api.LogOutput.Level level) { + System.out.println(level.name() + ": " + formattedMessage); + } } diff --git a/sonar-runner-impl/src/main/java/org/sonar/runner/impl/InternalProperties.java b/sonar-runner-api/src/main/java/org/sonar/runner/impl/InternalProperties.java index 1a856e9..48c3319 100644 --- a/sonar-runner-impl/src/main/java/org/sonar/runner/impl/InternalProperties.java +++ b/sonar-runner-api/src/main/java/org/sonar/runner/impl/InternalProperties.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - Implementation + * SonarQube Runner - API * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * @@ -22,6 +22,5 @@ package org.sonar.runner.impl; public interface InternalProperties { String RUNNER_APP = "sonarRunner.app"; String RUNNER_APP_VERSION = "sonarRunner.appVersion"; - String RUNNER_MASK_RULES = "sonarRunner.maskRules"; String RUNNER_DUMP_TO_FILE = "sonarRunner.dumpToFile"; } diff --git a/sonar-runner-impl/src/main/java/org/sonar/runner/impl/IsolatedClassloader.java b/sonar-runner-api/src/main/java/org/sonar/runner/impl/IsolatedClassloader.java index 71a9980..d5c52b3 100644 --- a/sonar-runner-impl/src/main/java/org/sonar/runner/impl/IsolatedClassloader.java +++ b/sonar-runner-api/src/main/java/org/sonar/runner/impl/IsolatedClassloader.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - Implementation + * SonarQube Runner - API * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * @@ -32,14 +32,11 @@ import java.util.List; */ class IsolatedClassloader extends URLClassLoader { - private final String[][] maskRules; - /** * The parent classloader is used only for loading classes and resources in unmasked packages */ - IsolatedClassloader(ClassLoader parent, String[][] maskRules) { + IsolatedClassloader(ClassLoader parent) { super(new URL[0], parent); - this.maskRules = maskRules; } void addFiles(List<File> files) { @@ -53,18 +50,6 @@ class IsolatedClassloader extends URLClassLoader { } /** - * @return true, if class can be loaded from parent ClassLoader - */ - boolean canLoadFromParent(String name) { - for (String[] maskRule : maskRules) { - if (name.startsWith(maskRule[1])) { - return "UNMASK".equals(maskRule[0]); - } - } - return false; - } - - /** * Same behavior as in {@link java.net.URLClassLoader#loadClass(String, boolean)}, except loading from parent. */ @Override @@ -74,9 +59,10 @@ class IsolatedClassloader extends URLClassLoader { if (c == null) { try { // Load from parent - if (getParent() != null && canLoadFromParent(name)) { + if (getParent() != null && fromSonarBatchPackage(name)) { c = getParent().loadClass(name); } else { + // Load from system // I don't know for other vendors, but for Oracle JVM : @@ -100,6 +86,10 @@ class IsolatedClassloader extends URLClassLoader { return c; } + private boolean fromSonarBatchPackage(String name) { + return name.startsWith("org.sonar.runner.batch"); + } + /** * Unlike {@link java.net.URLClassLoader#getResource(String)} don't return resource from parent. * See http://jira.codehaus.org/browse/SONAR-2276 diff --git a/sonar-runner-impl/src/main/java/org/sonar/runner/impl/IsolatedLauncherFactory.java b/sonar-runner-api/src/main/java/org/sonar/runner/impl/IsolatedLauncherFactory.java index 5a87996..601776d 100644 --- a/sonar-runner-impl/src/main/java/org/sonar/runner/impl/IsolatedLauncherFactory.java +++ b/sonar-runner-api/src/main/java/org/sonar/runner/impl/IsolatedLauncherFactory.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - Implementation + * SonarQube Runner - API * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * @@ -19,35 +19,37 @@ */ package org.sonar.runner.impl; -import org.sonar.runner.batch.IsolatedLauncher; -import org.sonar.home.cache.PersistentCacheBuilder; -import org.sonar.home.cache.PersistentCache; - import java.io.File; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.List; import java.util.Properties; +import org.sonar.home.cache.Logger; +import org.sonar.home.cache.PersistentCache; +import org.sonar.home.cache.PersistentCacheBuilder; +import org.sonar.runner.batch.IsolatedLauncher; public class IsolatedLauncherFactory { static final String ISOLATED_LAUNCHER_IMPL = "org.sonar.runner.batch.BatchIsolatedLauncher"; private final TempCleaning tempCleaning; private final String launcherImplClassName; + private final Logger logger; /** * For unit tests */ - IsolatedLauncherFactory(String isolatedLauncherClassName, TempCleaning tempCleaning) { + IsolatedLauncherFactory(String isolatedLauncherClassName, TempCleaning tempCleaning, Logger logger) { this.tempCleaning = tempCleaning; this.launcherImplClassName = isolatedLauncherClassName; + this.logger = logger; } - public IsolatedLauncherFactory() { - this(ISOLATED_LAUNCHER_IMPL, new TempCleaning()); + public IsolatedLauncherFactory(Logger logger) { + this(ISOLATED_LAUNCHER_IMPL, new TempCleaning(logger), logger); } - private static PersistentCache getCache(Properties props) { - PersistentCacheBuilder builder = new PersistentCacheBuilder(); + private PersistentCache getCache(Properties props) { + PersistentCacheBuilder builder = new PersistentCacheBuilder(logger); if (!"true".equals(props.getProperty("sonar.enableHttpCache"))) { builder.forceUpdate(true); @@ -56,56 +58,29 @@ public class IsolatedLauncherFactory { return builder.build(); } - static String[][] getMaskRules(final Properties props) { - String maskRulesProp = props.getProperty(InternalProperties.RUNNER_MASK_RULES, null); - String[] maskRulesConcat = maskRulesProp != null ? maskRulesProp.split(",") : (new String[0]); - String[][] maskRules = new String[maskRulesConcat.length][2]; - for (int i = 0; i < maskRulesConcat.length; i++) { - String[] splitted = maskRulesConcat[i].split("\\|"); - maskRules[i][0] = splitted[0]; - maskRules[i][1] = splitted.length > 1 ? splitted[1] : ""; - } - return maskRules; - } - - private static void addIsolatedLauncherMaskRule(Properties props) { - String unmask = "UNMASK|org.sonar.runner.batch.IsolatedLauncher,UNMASK|org.sonar.home.log.LogListener"; - String currentRules = (String) props.get(InternalProperties.RUNNER_MASK_RULES); - - if (currentRules == null) { - props.put(InternalProperties.RUNNER_MASK_RULES, unmask); - } else { - props.put(InternalProperties.RUNNER_MASK_RULES, currentRules + "," + unmask); - } - } - - private ClassLoader createClassLoader(List<File> jarFiles, final Properties props) { - Properties copy = new Properties(); - copy.putAll(props); - addIsolatedLauncherMaskRule(copy); - String[][] maskRules = getMaskRules(copy); - IsolatedClassloader classloader = new IsolatedClassloader(getClass().getClassLoader(), maskRules); + private ClassLoader createClassLoader(List<File> jarFiles) { + IsolatedClassloader classloader = new IsolatedClassloader(getClass().getClassLoader()); classloader.addFiles(jarFiles); return classloader; } public IsolatedLauncher createLauncher(Properties props) { - ServerConnection serverConnection = ServerConnection.create(props, getCache(props)); - JarDownloader jarDownloader = new JarDownloader(serverConnection); + ServerConnection serverConnection = ServerConnection.create(props, getCache(props), logger); + JarDownloader jarDownloader = new JarDownloader(serverConnection, logger); - return createLauncher(jarDownloader, props); + return createLauncher(jarDownloader); } - IsolatedLauncher createLauncher(final JarDownloader jarDownloader, final Properties props) { + IsolatedLauncher createLauncher(final JarDownloader jarDownloader) { return AccessController.doPrivileged(new PrivilegedAction<IsolatedLauncher>() { @Override public IsolatedLauncher run() { try { List<File> jarFiles = jarDownloader.download(); - Logs.debug("Create isolated classloader..."); - ClassLoader cl = createClassLoader(jarFiles, props); - IsolatedLauncher objProxy = IsolatedLauncherProxy.create(cl, IsolatedLauncher.class, launcherImplClassName); + logger.debug("Create isolated classloader..."); + ClassLoader cl = createClassLoader(jarFiles); + IsolatedLauncher objProxy = IsolatedLauncherProxy.create(cl, IsolatedLauncher.class, launcherImplClassName, logger); tempCleaning.clean(); return objProxy; diff --git a/sonar-runner-impl/src/main/java/org/sonar/runner/impl/IsolatedLauncherProxy.java b/sonar-runner-api/src/main/java/org/sonar/runner/impl/IsolatedLauncherProxy.java index 7d2a96b..411d731 100644 --- a/sonar-runner-impl/src/main/java/org/sonar/runner/impl/IsolatedLauncherProxy.java +++ b/sonar-runner-api/src/main/java/org/sonar/runner/impl/IsolatedLauncherProxy.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - Implementation + * SonarQube Runner - API * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * @@ -24,27 +24,30 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.lang.reflect.UndeclaredThrowableException; +import org.sonar.home.cache.Logger; public class IsolatedLauncherProxy implements InvocationHandler { - private Object proxied = null; - private ClassLoader cl = null; + private final Object proxied; + private final ClassLoader cl; + private final Logger logger; - private IsolatedLauncherProxy(ClassLoader cl, Object proxied) { + private IsolatedLauncherProxy(ClassLoader cl, Object proxied, Logger logger) { this.cl = cl; this.proxied = proxied; + this.logger = logger; } - public static <T> T create(ClassLoader cl, Class<T> interfaceClass, String proxiedClassName) throws ReflectiveOperationException { + public static <T> T create(ClassLoader cl, Class<T> interfaceClass, String proxiedClassName, Logger logger) throws ReflectiveOperationException { Object proxied = createProxiedObject(cl, proxiedClassName); // interfaceClass needs to be loaded with a parent ClassLoader (common to both ClassLoaders) // In addition, Proxy.newProxyInstance checks if the target ClassLoader sees the same class as the one given Class<?> loadedInterfaceClass = cl.loadClass(interfaceClass.getName()); - return (T) create(cl, proxied, loadedInterfaceClass); + return (T) create(cl, proxied, loadedInterfaceClass, logger); } - public static <T> T create(ClassLoader cl, Object proxied, Class<T> interfaceClass) { + public static <T> T create(ClassLoader cl, Object proxied, Class<T> interfaceClass, Logger logger) { Class<?>[] c = {interfaceClass}; - return (T) Proxy.newProxyInstance(cl, c, new IsolatedLauncherProxy(cl, proxied)); + return (T) Proxy.newProxyInstance(cl, c, new IsolatedLauncherProxy(cl, proxied, logger)); } @Override @@ -53,7 +56,7 @@ public class IsolatedLauncherProxy implements InvocationHandler { try { Thread.currentThread().setContextClassLoader(cl); - Logs.debug("Execution " + method.getName()); + logger.debug("Execution " + method.getName()); return method.invoke(proxied, args); } catch (UndeclaredThrowableException | InvocationTargetException e) { throw unwrapException(e); @@ -64,7 +67,7 @@ public class IsolatedLauncherProxy implements InvocationHandler { private static Throwable unwrapException(Throwable e) { Throwable cause = e; - + while (cause.getCause() != null) { if (cause instanceof UndeclaredThrowableException || cause instanceof InvocationTargetException) { cause = cause.getCause(); diff --git a/sonar-runner-impl/src/main/java/org/sonar/runner/impl/JarDownloader.java b/sonar-runner-api/src/main/java/org/sonar/runner/impl/JarDownloader.java index b64aa39..62fc157 100644 --- a/sonar-runner-impl/src/main/java/org/sonar/runner/impl/JarDownloader.java +++ b/sonar-runner-api/src/main/java/org/sonar/runner/impl/JarDownloader.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - Implementation + * SonarQube Runner - API * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * @@ -21,15 +21,18 @@ package org.sonar.runner.impl; import java.io.File; import java.util.List; +import org.sonar.home.cache.Logger; class JarDownloader { private final ServerConnection serverConnection; + private final Logger logger; - JarDownloader(ServerConnection conn) { + JarDownloader(ServerConnection conn, Logger logger) { this.serverConnection = conn; + this.logger = logger; } List<File> download() { - return new Jars(serverConnection, new JarExtractor()).download(); + return new Jars(serverConnection, new JarExtractor(), logger).download(); } } diff --git a/sonar-runner-impl/src/main/java/org/sonar/runner/impl/JarExtractor.java b/sonar-runner-api/src/main/java/org/sonar/runner/impl/JarExtractor.java index dc40f44..c4e3fa7 100644 --- a/sonar-runner-impl/src/main/java/org/sonar/runner/impl/JarExtractor.java +++ b/sonar-runner-api/src/main/java/org/sonar/runner/impl/JarExtractor.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - Implementation + * SonarQube Runner - API * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * diff --git a/sonar-runner-impl/src/main/java/org/sonar/runner/impl/Jars.java b/sonar-runner-api/src/main/java/org/sonar/runner/impl/Jars.java index 102ccdc..d181f23 100644 --- a/sonar-runner-impl/src/main/java/org/sonar/runner/impl/Jars.java +++ b/sonar-runner-api/src/main/java/org/sonar/runner/impl/Jars.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - Implementation + * SonarQube Runner - API * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * @@ -19,14 +19,13 @@ */ package org.sonar.runner.impl; -import org.sonar.home.cache.FileCache; -import org.sonar.home.cache.FileCacheBuilder; -import org.sonar.home.log.StandardLog; - import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; +import org.sonar.home.cache.FileCache; +import org.sonar.home.cache.FileCacheBuilder; +import org.sonar.home.cache.Logger; class Jars { private static final String BOOTSTRAP_INDEX_PATH = "/batch_bootstrap/index"; @@ -35,9 +34,11 @@ class Jars { private final FileCache fileCache; private final ServerConnection connection; private final JarExtractor jarExtractor; + private final Logger logger; - Jars(ServerConnection conn, JarExtractor jarExtractor) { - this.fileCache = new FileCacheBuilder().setLog(new StandardLog()).build(); + Jars(ServerConnection conn, JarExtractor jarExtractor, Logger logger) { + this.logger = logger; + this.fileCache = new FileCacheBuilder(logger).build(); this.connection = conn; this.jarExtractor = jarExtractor; } @@ -45,7 +46,8 @@ class Jars { /** * For unit tests */ - Jars(FileCache fileCache, ServerConnection conn, JarExtractor jarExtractor) { + Jars(FileCache fileCache, ServerConnection conn, JarExtractor jarExtractor, Logger logger) { + this.logger = logger; this.fileCache = fileCache; this.connection = conn; this.jarExtractor = jarExtractor; @@ -53,7 +55,7 @@ class Jars { List<File> download() { List<File> files = new ArrayList<File>(); - Logs.debug("Extract sonar-runner-batch in temp..."); + logger.debug("Extract sonar-runner-batch in temp..."); files.add(jarExtractor.extractToTemp("sonar-runner-batch")); files.addAll(dowloadFiles()); return files; @@ -62,9 +64,9 @@ class Jars { private List<File> dowloadFiles() { try { List<File> files = new ArrayList<File>(); - Logs.debug("Get bootstrap index..."); + logger.debug("Get bootstrap index..."); String libs = connection.downloadStringCache(BOOTSTRAP_INDEX_PATH); - Logs.debug("Get bootstrap completed"); + logger.debug("Get bootstrap completed"); String[] lines = libs.split("[\r\n]+"); BatchFileDownloader batchFileDownloader = new BatchFileDownloader(connection); for (String line : lines) { diff --git a/sonar-runner-impl/src/main/java/org/sonar/runner/impl/RunnerException.java b/sonar-runner-api/src/main/java/org/sonar/runner/impl/RunnerException.java index ff68d64..9d60947 100644 --- a/sonar-runner-impl/src/main/java/org/sonar/runner/impl/RunnerException.java +++ b/sonar-runner-api/src/main/java/org/sonar/runner/impl/RunnerException.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - Implementation + * SonarQube Runner - API * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * diff --git a/sonar-runner-impl/src/main/java/org/sonar/runner/impl/ServerConnection.java b/sonar-runner-api/src/main/java/org/sonar/runner/impl/ServerConnection.java index 915fba8..291ee30 100644 --- a/sonar-runner-impl/src/main/java/org/sonar/runner/impl/ServerConnection.java +++ b/sonar-runner-api/src/main/java/org/sonar/runner/impl/ServerConnection.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - Implementation + * SonarQube Runner - API * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * @@ -19,10 +19,7 @@ */ package org.sonar.runner.impl; -import org.sonar.home.cache.PersistentCache; import com.github.kevinsawicki.http.HttpRequest; -import org.apache.commons.io.FileUtils; - import java.io.File; import java.io.IOException; import java.net.ConnectException; @@ -33,6 +30,9 @@ import java.util.Properties; import java.util.concurrent.Callable; import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.apache.commons.io.FileUtils; +import org.sonar.home.cache.Logger; +import org.sonar.home.cache.PersistentCache; class ServerConnection { @@ -47,8 +47,10 @@ class ServerConnection { private final PersistentCache wsCache; private final boolean isModePreview; + private final Logger logger; - private ServerConnection(String serverUrl, String app, String appVersion, boolean preview, PersistentCache cache) { + private ServerConnection(String serverUrl, String app, String appVersion, boolean preview, PersistentCache cache, Logger logger) { + this.logger = logger; this.serverUrl = removeEndSlash(serverUrl); this.userAgent = app + "/" + appVersion; this.wsCache = cache; @@ -62,14 +64,14 @@ class ServerConnection { return url.endsWith("/") ? url.substring(0, url.length() - 1) : url; } - static ServerConnection create(Properties properties, PersistentCache cache) { + static ServerConnection create(Properties properties, PersistentCache cache, Logger logger) { String serverUrl = properties.getProperty("sonar.host.url"); String app = properties.getProperty(InternalProperties.RUNNER_APP); String appVersion = properties.getProperty(InternalProperties.RUNNER_APP_VERSION); String analysisMode = properties.getProperty("sonar.analysis.mode"); boolean preview = "preview".equalsIgnoreCase(analysisMode); - return new ServerConnection(serverUrl, app, appVersion, preview, cache); + return new ServerConnection(serverUrl, app, appVersion, preview, cache, logger); } private class StringDownloader implements Callable<String> { @@ -103,7 +105,7 @@ class ServerConnection { void download(String path, File toFile) { String fullUrl = serverUrl + path; try { - Logs.debug("Download " + fullUrl + " to " + toFile.getAbsolutePath()); + logger.debug("Download " + fullUrl + " to " + toFile.getAbsolutePath()); HttpRequest httpRequest = newHttpRequest(new URL(fullUrl)); if (!httpRequest.ok()) { throw new IOException(MessageFormat.format(STATUS_RETURNED_BY_URL_IS_INVALID, fullUrl, httpRequest.code())); @@ -112,7 +114,7 @@ class ServerConnection { } catch (Exception e) { if (e.getCause() instanceof ConnectException || e.getCause() instanceof UnknownHostException) { - Logs.error(MessageFormat.format(SONAR_SERVER_CAN_NOT_BE_REACHED, serverUrl)); + logger.error(MessageFormat.format(SONAR_SERVER_CAN_NOT_BE_REACHED, serverUrl)); } FileUtils.deleteQuietly(toFile); throw new IllegalStateException("Fail to download: " + fullUrl, e); @@ -129,7 +131,7 @@ class ServerConnection { } } catch (HttpRequest.HttpRequestException e) { if (e.getCause() instanceof ConnectException || e.getCause() instanceof UnknownHostException) { - Logs.error(MessageFormat.format(SONAR_SERVER_CAN_NOT_BE_REACHED, serverUrl)); + logger.error(MessageFormat.format(SONAR_SERVER_CAN_NOT_BE_REACHED, serverUrl)); } throw e; } diff --git a/sonar-runner-impl/src/main/java/org/sonar/runner/impl/TempCleaning.java b/sonar-runner-api/src/main/java/org/sonar/runner/impl/TempCleaning.java index 4067b96..045e36d 100644 --- a/sonar-runner-impl/src/main/java/org/sonar/runner/impl/TempCleaning.java +++ b/sonar-runner-api/src/main/java/org/sonar/runner/impl/TempCleaning.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - Implementation + * SonarQube Runner - API * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * @@ -25,6 +25,7 @@ import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.AgeFileFilter; import org.apache.commons.io.filefilter.AndFileFilter; import org.apache.commons.io.filefilter.PrefixFileFilter; +import org.sonar.home.cache.Logger; /** * The file sonar-runner-batch.jar is locked by the classloader on Windows and can't be dropped at the end of the execution. @@ -35,28 +36,30 @@ class TempCleaning { final File tempDir; - TempCleaning() { - this(new File(System.getProperty("java.io.tmpdir"))); + private final Logger logger; + + TempCleaning(Logger logger) { + this(new File(System.getProperty("java.io.tmpdir")), logger); } /** * For unit tests */ - TempCleaning(File tempDir) { + TempCleaning(File tempDir, Logger logger) { + this.logger = logger; this.tempDir = tempDir; } void clean() { - Logs.debug("Start temp cleaning..."); + logger.debug("Start temp cleaning..."); long cutoff = System.currentTimeMillis() - ONE_DAY_IN_MILLISECONDS; Collection<File> files = FileUtils.listFiles(tempDir, new AndFileFilter( new PrefixFileFilter("sonar-runner-batch"), - new AgeFileFilter(cutoff) - ), null); + new AgeFileFilter(cutoff)), null); for (File file : files) { FileUtils.deleteQuietly(file); } - Logs.debug("Temp cleaning done"); + logger.debug("Temp cleaning done"); } } diff --git a/sonar-runner-impl/src/main/java/org/sonar/runner/impl/package-info.java b/sonar-runner-api/src/main/java/org/sonar/runner/impl/package-info.java index eff9ce5..d7ac772 100644 --- a/sonar-runner-impl/src/main/java/org/sonar/runner/impl/package-info.java +++ b/sonar-runner-api/src/main/java/org/sonar/runner/impl/package-info.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - Implementation + * SonarQube Runner - API * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * diff --git a/sonar-runner-api/src/test/java/org/sonar/runner/api/CommandExecutorTest.java b/sonar-runner-api/src/test/java/org/sonar/runner/api/CommandExecutorTest.java deleted file mode 100644 index c585acf..0000000 --- a/sonar-runner-api/src/test/java/org/sonar/runner/api/CommandExecutorTest.java +++ /dev/null @@ -1,183 +0,0 @@ -/* - * SonarQube Runner - API - * Copyright (C) 2011 SonarSource - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.runner.api; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.rules.TemporaryFolder; -import org.junit.rules.TestName; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; - -import static org.fest.assertions.Assertions.assertThat; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.mock; - -public class CommandExecutorTest { - - public static final ProcessMonitor ACTIVITY_CONTROLLER = mock(ProcessMonitor.class); - - @Rule - public TemporaryFolder tempFolder = new TemporaryFolder(); - - @Rule - public TestName testName = new TestName(); - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - PrintStreamConsumer stdout = new PrintStreamConsumer(System.out); - PrintStreamConsumer stderr = new PrintStreamConsumer(System.err); - File workDir; - - @Before - public void setUp() throws IOException { - workDir = tempFolder.newFolder(testName.getMethodName()); - } - - @Test - public void should_consume_StdOut_and_StdErr() throws Exception { - final StringBuilder stdOutBuilder = new StringBuilder(); - StreamConsumer stdOutConsumer = new StreamConsumer() { - public void consumeLine(String line) { - stdOutBuilder.append(line).append(System.getProperty("line.separator")); - } - }; - final StringBuilder stdErrBuilder = new StringBuilder(); - StreamConsumer stdErrConsumer = new StreamConsumer() { - public void consumeLine(String line) { - stdErrBuilder.append(line).append(System.getProperty("line.separator")); - } - }; - Command command = Command.builder().setExecutable(getScript("output")).setDirectory(workDir).build(); - int exitCode = CommandExecutor.create().execute(command, stdOutConsumer, stdErrConsumer, 1000L, ACTIVITY_CONTROLLER); - assertThat(exitCode).isEqualTo(0); - - String stdOut = stdOutBuilder.toString(); - String stdErr = stdErrBuilder.toString(); - assertThat(stdOut).contains("stdOut: first line"); - assertThat(stdOut).contains("stdOut: second line"); - assertThat(stdErr).contains("stdErr: first line"); - assertThat(stdErr).contains("stdErr: second line"); - } - - @Test - public void stdOut_consumer_can_throw_exception() throws Exception { - Command command = Command.builder().setExecutable(getScript("output")).setDirectory(workDir).build(); - thrown.expect(CommandException.class); - thrown.expectMessage("Error inside stdOut stream"); - CommandExecutor.create().execute(command, BAD_CONSUMER, NOP_CONSUMER, 1000L, ACTIVITY_CONTROLLER); - } - - @Test - public void stdErr_consumer_can_throw_exception() throws Exception { - Command command = Command.builder().setExecutable(getScript("output")).setDirectory(workDir).build(); - thrown.expect(CommandException.class); - thrown.expectMessage("Error inside stdErr stream"); - CommandExecutor.create().execute(command, NOP_CONSUMER, BAD_CONSUMER, 1000L, ACTIVITY_CONTROLLER); - } - - private static final StreamConsumer NOP_CONSUMER = new StreamConsumer() { - public void consumeLine(String line) { - // nop - } - }; - - private static final StreamConsumer BAD_CONSUMER = new StreamConsumer() { - public void consumeLine(String line) { - throw new RuntimeException(); - } - }; - - @Test - public void should_use_working_directory_to_store_argument_and_environment_variable() throws Exception { - Command command = Command.builder() - .setDirectory(workDir) - .setExecutable(getScript("echo")) - .addArguments("1") - .setEnvVariable("ENVVAR", "2") - .build(); - int exitCode = CommandExecutor.create().execute(command, stdout, stderr, 1000L, ACTIVITY_CONTROLLER); - assertThat(exitCode).isEqualTo(0); - File logFile = new File(workDir, "echo.log"); - assertThat(logFile).exists(); - String log = new String(Files.readAllBytes(logFile.toPath())); - assertThat(log).contains(workDir.getAbsolutePath()); - assertThat(log).contains("Parameter: 1"); - assertThat(log).contains("Environment variable: 2"); - } - - @Test - public void should_stop_after_timeout() throws IOException { - String executable = getScript("forever"); - long start = System.currentTimeMillis(); - try { - Command command = Command.builder().setExecutable(executable).setDirectory(workDir).build(); - CommandExecutor.create().execute(command, stdout, stderr, 300L, ACTIVITY_CONTROLLER); - fail(); - } catch (CommandException e) { - long duration = System.currentTimeMillis() - start; - // should test >= 300 but it strangly fails during build on windows. - // The timeout is raised after 2xxms (??) - assertThat(duration).as(e.getMessage()).isGreaterThan(200L); - } - } - - @Test - public void test_should_stop_if_requested() throws Exception { - - String executable = getScript("forever"); - Command command = Command.builder().setExecutable(executable).setDirectory(workDir).build(); - - final long start = System.currentTimeMillis(); - int result = CommandExecutor.create().execute(command, stdout, stderr, 2000L, new ProcessMonitor() { - @Override - public boolean stop() { - // kill after 1 seconds - return System.currentTimeMillis() - start > 1000; - } - }); - - assertThat(System.currentTimeMillis() - start).isGreaterThan(1000); - assertThat(result).isNotEqualTo(0); - } - - @Test - public void should_fail_if_script_not_found() { - thrown.expect(CommandException.class); - Command command = Command.builder().setExecutable("notfound").setDirectory(workDir).build(); - CommandExecutor.create().execute(command, stdout, stderr, 1000L, ACTIVITY_CONTROLLER); - } - - private static String getScript(String name) throws IOException { - String filename; - if (new Os().isWindows()) { - filename = name + ".bat"; - } else { - filename = name + ".sh"; - } - return new File("src/test/scripts/" + filename).getCanonicalPath(); - } - -} diff --git a/sonar-runner-api/src/test/java/org/sonar/runner/api/CommandTest.java b/sonar-runner-api/src/test/java/org/sonar/runner/api/CommandTest.java deleted file mode 100644 index dcbd39c..0000000 --- a/sonar-runner-api/src/test/java/org/sonar/runner/api/CommandTest.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * SonarQube Runner - API - * Copyright (C) 2011 SonarSource - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.runner.api; - -import org.junit.Test; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -import static org.fest.assertions.Assertions.assertThat; -import static org.fest.assertions.Fail.fail; -import static org.fest.assertions.MapAssert.entry; - -public class CommandTest { - @Test - public void test_simple_build() throws Exception { - Command command = Command.builder().setExecutable("java").build(); - assertThat(command.executable()).isEqualTo("java"); - assertThat(command.envVariables()).isEmpty(); - assertThat(command.arguments()).isEmpty(); - assertThat(command.toStrings()).containsOnly("java"); - assertThat(command.toString()).isEqualTo("java"); - } - - @Test - public void test_arguments_and_env_variables() throws Exception { - Map<String, String> env = new HashMap<String, String>(); - env.put("USER_HOME", "/user"); - - Command command = Command.builder() - .setExecutable("java") - .addArguments("-Dfoo=bar", "-Djava.io.tmpdir=/tmp") - .addArguments(Arrays.asList("-Xmx512m")) - .setEnvVariable("JAVA_HOME", "/path/to/jdk") - .addEnvVariables(env) - .build(); - - assertThat(command.executable()).isEqualTo("java"); - assertThat(command.envVariables()).hasSize(2).includes( - entry("JAVA_HOME", "/path/to/jdk"), - entry("USER_HOME", "/user") - ); - assertThat(command.arguments()).containsSequence("-Dfoo=bar", "-Djava.io.tmpdir=/tmp", "-Xmx512m"); - assertThat(command.toStrings()).containsOnly("java", "-Dfoo=bar", "-Djava.io.tmpdir=/tmp", "-Xmx512m"); - assertThat(command.toString()).isEqualTo("java -Dfoo=bar -Djava.io.tmpdir=/tmp -Xmx512m"); - } - - @Test - public void should_ignore_blank_arguments() throws Exception { - // ProcessBuilder has strange side-effects where some arguments are blank - Command command = Command.builder() - .setExecutable("java") - .addArguments(null, "", " ") - .addArguments(Arrays.asList(null, "", " ")) - .build(); - - assertThat(command.arguments()).isEmpty(); - } - - @Test - public void executable_should_be_required() { - try { - Command.builder().build(); - fail(); - } catch (IllegalArgumentException e) { - // success - } - } -} diff --git a/sonar-runner-api/src/test/java/org/sonar/runner/api/DirsTest.java b/sonar-runner-api/src/test/java/org/sonar/runner/api/DirsTest.java index 8cd7630..3c45b32 100644 --- a/sonar-runner-api/src/test/java/org/sonar/runner/api/DirsTest.java +++ b/sonar-runner-api/src/test/java/org/sonar/runner/api/DirsTest.java @@ -19,14 +19,15 @@ */ package org.sonar.runner.api; +import java.io.File; +import java.util.Properties; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; - -import java.io.File; -import java.util.Properties; +import org.sonar.home.cache.Logger; import static org.fest.assertions.Assertions.assertThat; +import static org.mockito.Mockito.mock; public class DirsTest { @@ -38,7 +39,7 @@ public class DirsTest { @Test public void should_init_default_task_work_dir() throws Exception { p.setProperty("sonar.task", "views"); - Dirs.init(p); + new Dirs(mock(Logger.class)).init(p); File workDir = new File(p.getProperty(RunnerProperties.WORK_DIR, null)); assertThat(workDir).isNotNull().isDirectory(); @@ -49,7 +50,7 @@ public class DirsTest { public void should_use_parameterized_task_work_dir() throws Exception { p.setProperty("sonar.task", "views"); p.setProperty(RunnerProperties.WORK_DIR, "generated/reports"); - Dirs.init(p); + new Dirs(mock(Logger.class)).init(p); File workDir = new File(p.getProperty(RunnerProperties.WORK_DIR, null)); assertThat(workDir).isNotNull(); @@ -60,7 +61,7 @@ public class DirsTest { @Test public void should_init_default_project_dirs() throws Exception { p.setProperty("sonar.task", "scan"); - Dirs.init(p); + new Dirs(mock(Logger.class)).init(p); File projectDir = new File(p.getProperty(ScanProperties.PROJECT_BASEDIR, null)); File workDir = new File(p.getProperty(RunnerProperties.WORK_DIR, null)); @@ -79,7 +80,7 @@ public class DirsTest { p.setProperty("sonar.task", "scan"); p.setProperty(RunnerProperties.WORK_DIR, "relative/path"); p.setProperty(ScanProperties.PROJECT_BASEDIR, initialProjectDir.getAbsolutePath()); - Dirs.init(p); + new Dirs(mock(Logger.class)).init(p); File projectDir = new File(p.getProperty(ScanProperties.PROJECT_BASEDIR, null)); File workDir = new File(p.getProperty(RunnerProperties.WORK_DIR, null)); diff --git a/sonar-runner-api/src/test/java/org/sonar/runner/api/EmbeddedRunnerTest.java b/sonar-runner-api/src/test/java/org/sonar/runner/api/EmbeddedRunnerTest.java index 84a256a..386f669 100644 --- a/sonar-runner-api/src/test/java/org/sonar/runner/api/EmbeddedRunnerTest.java +++ b/sonar-runner-api/src/test/java/org/sonar/runner/api/EmbeddedRunnerTest.java @@ -19,29 +19,26 @@ */ package org.sonar.runner.api; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.nio.charset.Charset; +import java.util.Properties; import org.junit.Before; -import org.sonar.runner.batch.IsolatedLauncher; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.mockito.ArgumentMatcher; +import org.sonar.home.cache.Logger; +import org.sonar.runner.batch.IsolatedLauncher; import org.sonar.runner.impl.IsolatedLauncherFactory; -import org.sonar.runner.impl.InternalProperties; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.when; -import static org.mockito.Matchers.any; import static org.fest.assertions.Assertions.assertThat; +import static org.mockito.Matchers.any; import static org.mockito.Matchers.argThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; public class EmbeddedRunnerTest { @@ -50,7 +47,7 @@ public class EmbeddedRunnerTest { @Test public void should_create() { - assertThat(EmbeddedRunner.create()).isNotNull().isInstanceOf(EmbeddedRunner.class); + assertThat(EmbeddedRunner.create(mock(LogOutput.class))).isNotNull().isInstanceOf(EmbeddedRunner.class); } private IsolatedLauncherFactory batchLauncher; @@ -63,28 +60,23 @@ public class EmbeddedRunnerTest { launcher = mock(IsolatedLauncher.class); when(launcher.getVersion()).thenReturn("5.2"); when(batchLauncher.createLauncher(any(Properties.class))).thenReturn(launcher); - runner = new EmbeddedRunner(batchLauncher); + runner = new EmbeddedRunner(batchLauncher, mock(Logger.class), mock(LogOutput.class)); } @Test public void test_app() { - EmbeddedRunner runner = EmbeddedRunner.create().setApp("Eclipse", "3.1"); + EmbeddedRunner runner = EmbeddedRunner.create(mock(LogOutput.class)).setApp("Eclipse", "3.1"); assertThat(runner.app()).isEqualTo("Eclipse"); assertThat(runner.appVersion()).isEqualTo("3.1"); } - + @Test public void test_back_compatibility() { when(launcher.getVersion()).thenReturn("4.5"); - - final FakeExtension fakeExtension = new FakeExtension(); - List<Object> extensionList = new LinkedList<>(); - extensionList.add(fakeExtension); - + Properties analysisProps = new Properties(); analysisProps.put("sonar.dummy", "summy"); - - runner.addExtensions(fakeExtension); + runner.setGlobalProperty("sonar.projectKey", "foo"); runner.start(); runner.runAnalysis(analysisProps); @@ -112,44 +104,12 @@ public class EmbeddedRunnerTest { } return true; } - }), eq(extensionList)); - } - - @Test - public void should_set_unmasked_packages() { - EmbeddedRunner runner = EmbeddedRunner.create(); - assertThat(runner.globalProperty(InternalProperties.RUNNER_MASK_RULES, null)).isNull(); - - runner = EmbeddedRunner.create().setUnmaskedPackages("org.apache.ant", "org.ant"); - assertThat(runner.globalProperty(InternalProperties.RUNNER_MASK_RULES, null)).isEqualTo("UNMASK|org.apache.ant.,UNMASK|org.ant."); - } - - @Test - public void should_set_mask_rules() { - EmbeddedRunner runner = EmbeddedRunner.create(); - assertThat(runner.globalProperty(InternalProperties.RUNNER_MASK_RULES, null)).isNull(); - - runner = EmbeddedRunner.create() - .unmask("org.slf4j.Logger") - .mask("org.slf4j.") - .mask("ch.qos.logback.") - .unmask(""); - assertThat(runner.globalProperty(InternalProperties.RUNNER_MASK_RULES, null)).isEqualTo("UNMASK|org.slf4j.Logger,MASK|org.slf4j.,MASK|ch.qos.logback.,UNMASK|"); - } - - @Test - public void should_add_extensions() { - EmbeddedRunner runner = EmbeddedRunner.create(); - assertThat(runner.extensions()).isEmpty(); - - FakeExtension fakeExtension = new FakeExtension(); - runner.addExtensions(fakeExtension); - assertThat(runner.extensions()).containsExactly(fakeExtension); + })); } @Test public void should_set_properties() { - EmbeddedRunner runner = EmbeddedRunner.create(); + EmbeddedRunner runner = EmbeddedRunner.create(mock(LogOutput.class)); runner.setGlobalProperty("sonar.projectKey", "foo"); runner.addGlobalProperties(new Properties() { { @@ -166,8 +126,6 @@ public class EmbeddedRunnerTest { @Test public void should_launch_batch() { - final FakeExtension fakeExtension = new FakeExtension(); - runner.addExtensions(fakeExtension); runner.setGlobalProperty("sonar.projectKey", "foo"); runner.start(); runner.runAnalysis(new Properties()); @@ -199,8 +157,6 @@ public class EmbeddedRunnerTest { @Test public void should_launch_batch_analysisProperties() { - final FakeExtension fakeExtension = new FakeExtension(); - runner.addExtensions(fakeExtension); runner.setGlobalProperty("sonar.projectKey", "foo"); runner.start(); @@ -241,6 +197,29 @@ public class EmbeddedRunnerTest { assertThat(props.getProperty("sonar.projectKey")).isEqualTo("foo"); } - static class FakeExtension { + @Test + public void should_set_default_platform_encoding() throws Exception { + Properties p = new Properties(); + p.setProperty("sonar.task", "scan"); + runner.initSourceEncoding(p); + assertThat(p.getProperty("sonar.sourceEncoding", null)).isEqualTo(Charset.defaultCharset().name()); + } + + @Test + public void should_use_parameterized_encoding() throws Exception { + Properties p = new Properties(); + p.setProperty("sonar.task", "scan"); + p.setProperty("sonar.sourceEncoding", "THE_ISO_1234"); + runner.initSourceEncoding(p); + assertThat(p.getProperty("sonar.sourceEncoding", null)).isEqualTo("THE_ISO_1234"); + } + + @Test + public void should_not_init_encoding_if_not_project_task() throws Exception { + Properties p = new Properties(); + p.setProperty("sonar.task", "views"); + runner.initSourceEncoding(p); + assertThat(p.getProperty("sonar.sourceEncoding", null)).isNull(); } + } diff --git a/sonar-runner-api/src/test/java/org/sonar/runner/api/ForkedRunnerTest.java b/sonar-runner-api/src/test/java/org/sonar/runner/api/ForkedRunnerTest.java deleted file mode 100644 index a15cb86..0000000 --- a/sonar-runner-api/src/test/java/org/sonar/runner/api/ForkedRunnerTest.java +++ /dev/null @@ -1,240 +0,0 @@ -/* - * SonarQube Runner - API - * Copyright (C) 2011 SonarSource - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.runner.api; - -import org.sonar.home.log.LogListener.Level; -import org.sonar.home.log.LogListener; -import org.sonar.runner.impl.Logs; -import org.mockito.Mockito; -import org.mockito.ArgumentCaptor; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.mockito.ArgumentMatcher; -import org.sonar.runner.impl.JarExtractor; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; - -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.fest.assertions.Assertions.assertThat; -import static org.fest.assertions.Fail.fail; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyLong; -import static org.mockito.Matchers.argThat; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class ForkedRunnerTest { - - @Rule - public TemporaryFolder temp = new TemporaryFolder(); - - private ProcessMonitor processMonitor; - - private final StreamConsumer out = mock(StreamConsumer.class); - - private final StreamConsumer err = mock(StreamConsumer.class); - - @Before - public void prepare() { - processMonitor = mock(ProcessMonitor.class); - } - - @Test - public void should_create_forked_runner() { - ForkedRunner runner = ForkedRunner.create(); - assertThat(runner).isNotNull().isInstanceOf(ForkedRunner.class); - } - - @Test - public void should_create_forked_runner_with_activity_controller() { - ForkedRunner runner = ForkedRunner.create(processMonitor); - assertThat(runner).isNotNull().isInstanceOf(ForkedRunner.class); - } - - @Test - public void should_use_log_listener() throws IOException { - JarExtractor jarExtractor = createMockExtractor(); - - CommandExecutor commandExecutor = mock(CommandExecutor.class); - ForkedRunner runner = new ForkedRunner(jarExtractor, commandExecutor); - runner.execute(); - LogListener listener = mock(LogListener.class); - Logs.setListener(listener); - - ArgumentCaptor<StreamConsumer> arg1 = ArgumentCaptor.forClass(StreamConsumer.class); - ArgumentCaptor<StreamConsumer> arg2 = ArgumentCaptor.forClass(StreamConsumer.class); - - verify(commandExecutor).execute(any(Command.class), arg1.capture(), arg2.capture(), anyLong(), any(ProcessMonitor.class)); - arg1.getValue().consumeLine("test1"); - arg2.getValue().consumeLine("test2"); - - verify(listener).log("test1", Level.INFO); - verify(listener).log("test2", Level.ERROR); - verifyNoMoreInteractions(listener); - } - - @Test - public void should_print_to_consumers_by_default() throws IOException { - final List<String> printedLines = new LinkedList<>(); - StreamConsumer consumer = new StreamConsumer() { - @Override - public void consumeLine(String line) { - printedLines.add(line); - } - }; - JarExtractor jarExtractor = createMockExtractor(); - - CommandExecutor commandExecutor = mock(CommandExecutor.class); - ForkedRunner runner = new ForkedRunner(jarExtractor, commandExecutor); - runner.setStdOut(consumer); - runner.setStdErr(consumer); - runner.execute(); - - verify(commandExecutor).execute(any(Command.class), eq(consumer), eq(consumer), anyLong(), - any(ProcessMonitor.class)); - } - - @Test - public void properties_should_be_written_in_temp_file() throws Exception { - JarExtractor jarExtractor = createMockExtractor(); - - ForkedRunner runner = new ForkedRunner(jarExtractor, mock(CommandExecutor.class), any(ProcessMonitor.class)); - runner.setGlobalProperty("sonar.dynamicAnalysis", "false"); - runner.setGlobalProperty("sonar.login", "admin"); - runner.addJvmArguments("-Xmx512m"); - runner.addJvmEnvVariables(System.getenv()); - runner.setJvmEnvVariable("SONAR_HOME", "/path/to/sonar"); - - ForkedRunner.ForkCommand forkCommand = runner.createCommand(runner.globalProperties()); - - Properties properties = new Properties(); - properties.load(new FileInputStream(forkCommand.propertiesFile)); - assertThat(properties.size()).isEqualTo(2); - assertThat(properties.getProperty("sonar.dynamicAnalysis")).isEqualTo("false"); - assertThat(properties.getProperty("sonar.login")).isEqualTo("admin"); - assertThat(properties.getProperty("-Xmx512m")).isNull(); - assertThat(properties.getProperty("SONAR_HOME")).isNull(); - } - - @Test - public void should_merge_properties() throws IOException { - JarExtractor jarExtractor = createMockExtractor(); - ForkedRunner runner = new ForkedRunner(jarExtractor, mock(CommandExecutor.class), null); - - ForkedRunner spy = Mockito.spy(runner); - spy.setGlobalProperty("sonar.login", "admin"); - spy.execute(); - // generated analysis properties should have been added - ArgumentCaptor<Properties> properties = ArgumentCaptor.forClass(Properties.class); - verify(spy).writeProperties(properties.capture()); - assertThat(properties.getValue().keySet()).contains("sonar.working.directory", "sonar.host.url", "sonar.sourceEncoding", "sonar.login"); - } - - @Test - public void test_java_command() throws IOException { - JarExtractor jarExtractor = mock(JarExtractor.class); - final File jar = temp.newFile(); - when(jarExtractor.extractToTemp("sonar-runner-impl")).thenReturn(jar); - - CommandExecutor commandExecutor = mock(CommandExecutor.class); - - ForkedRunner runner = new ForkedRunner(jarExtractor, commandExecutor); - runner.setJavaExecutable("java"); - runner.setGlobalProperty("sonar.dynamicAnalysis", "false"); - runner.setGlobalProperty("sonar.login", "admin"); - runner.addJvmArguments("-Xmx512m"); - runner.addJvmEnvVariables(System.getenv()); - runner.setJvmEnvVariable("SONAR_HOME", "/path/to/sonar"); - runner.setStdOut(mock(StreamConsumer.class)); - runner.setStdErr(mock(StreamConsumer.class)); - - assertThat(runner.jvmArguments()).contains("-Xmx512m"); - runner.execute(); - - verify(commandExecutor).execute(argThat(new ArgumentMatcher<Command>() { - public boolean matches(Object o) { - Command command = (Command) o; - assertThat(command.toStrings()).hasSize(6); - assertThat(command.toStrings()[0]).isEqualTo("java"); - assertThat(command.toStrings()[1]).isEqualTo("-Xmx512m"); - assertThat(command.toStrings()[2]).isEqualTo("-cp"); - assertThat(command.toStrings()[3]).isEqualTo(jar.getAbsolutePath()); - assertThat(command.toStrings()[4]).isEqualTo("org.sonar.runner.impl.BatchLauncherMain"); - assertThat(command.toStrings()[5]).endsWith(".properties"); - - // env variables - assertThat(command.envVariables().size()).isGreaterThan(1); - assertThat(command.envVariables().get("SONAR_HOME")).isEqualTo("/path/to/sonar"); - return true; - } - }), any(PrintStreamConsumer.class), any(PrintStreamConsumer.class), anyLong(), any(ProcessMonitor.class)); - - } - - @Test - public void test_failure_of_java_command() throws IOException { - JarExtractor jarExtractor = createMockExtractor(); - CommandExecutor commandExecutor = createMockRunnerWithExecutionStatus(3); - - ForkedRunner runner = new ForkedRunner(jarExtractor, commandExecutor, processMonitor); - runner.setStdOut(out); - runner.setStdErr(err); - - try { - runner.execute(); - fail(); - } catch (IllegalStateException e) { - assertThat(e.getMessage()).matches("Error status \\[command: .*java.*\\]: 3"); - } - } - - private CommandExecutor createMockRunnerWithExecutionStatus(int executionStatus) { - CommandExecutor commandExecutor = mock(CommandExecutor.class); - when(commandExecutor.execute(any(Command.class), eq(out), eq(err), anyLong(), eq(processMonitor))).thenReturn(executionStatus); - return commandExecutor; - } - - private JarExtractor createMockExtractor() throws IOException { - JarExtractor jarExtractor = mock(JarExtractor.class); - final File jar = temp.newFile(); - when(jarExtractor.extractToTemp("sonar-runner-impl")).thenReturn(jar); - return jarExtractor; - } - - @Test - public void test_runner_was_requested_to_stop() throws Exception { - - when(processMonitor.stop()).thenReturn(true); - ForkedRunner runner = new ForkedRunner(createMockExtractor(), createMockRunnerWithExecutionStatus(143), processMonitor); - runner.setStdOut(out); - runner.setStdErr(err); - runner.execute(); - verify(out).consumeLine("SonarQube Runner was stopped [status=143]"); - } -} diff --git a/sonar-runner-api/src/test/java/org/sonar/runner/api/OsTest.java b/sonar-runner-api/src/test/java/org/sonar/runner/api/OsTest.java deleted file mode 100644 index 79550e0..0000000 --- a/sonar-runner-api/src/test/java/org/sonar/runner/api/OsTest.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * SonarQube Runner - API - * Copyright (C) 2011 SonarSource - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.runner.api; - -import org.apache.commons.lang.SystemUtils; -import org.junit.Test; - -import java.io.File; - -import static org.fest.assertions.Assertions.assertThat; - -public class OsTest { - @Test - public void testIsWindows() throws Exception { - assertThat(new Os().isWindows()).isEqualTo(SystemUtils.IS_OS_WINDOWS); - } - - @Test - public void testUsedJavaHome() throws Exception { - File javaHome = new Os().thisJavaHome(); - assertThat(javaHome).isNotNull().exists().isDirectory(); - } - - @Test - public void testUsedJavaExe() throws Exception { - File javaExe = new Os().thisJavaExe(); - assertThat(javaExe).isNotNull().isFile().exists(); - assertThat(javaExe.getName()).contains("java"); - } -} diff --git a/sonar-runner-api/src/test/java/org/sonar/runner/api/PrintStreamConsumerTest.java b/sonar-runner-api/src/test/java/org/sonar/runner/api/PrintStreamConsumerTest.java deleted file mode 100644 index 990b266..0000000 --- a/sonar-runner-api/src/test/java/org/sonar/runner/api/PrintStreamConsumerTest.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * SonarQube Runner - API - * Copyright (C) 2011 SonarSource - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.runner.api; - -import org.junit.Test; - -import java.io.PrintStream; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; - -public class PrintStreamConsumerTest { - @Test - public void consumeLine() { - PrintStream stream = mock(PrintStream.class); - PrintStreamConsumer consumer = new PrintStreamConsumer(stream); - consumer.consumeLine("foo"); - consumer.consumeLine("bar"); - - verify(stream).println("foo"); - verify(stream).println("bar"); - verifyNoMoreInteractions(stream); - } -} diff --git a/sonar-runner-api/src/test/java/org/sonar/runner/api/SourceEncodingTest.java b/sonar-runner-api/src/test/java/org/sonar/runner/api/SourceEncodingTest.java deleted file mode 100644 index 027a87f..0000000 --- a/sonar-runner-api/src/test/java/org/sonar/runner/api/SourceEncodingTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * SonarQube Runner - API - * Copyright (C) 2011 SonarSource - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.runner.api; - -import org.junit.Test; - -import java.nio.charset.Charset; -import java.util.Properties; - -import static org.fest.assertions.Assertions.assertThat; - -public class SourceEncodingTest { - - Properties p = new Properties(); - - @Test - public void should_set_default_platform_encoding() throws Exception { - p.setProperty("sonar.task", "scan"); - SourceEncoding.init(p); - assertThat(p.getProperty("sonar.sourceEncoding", null)).isEqualTo(Charset.defaultCharset().name()); - } - - @Test - public void should_use_parameterized_encoding() throws Exception { - p.setProperty("sonar.task", "scan"); - p.setProperty("sonar.sourceEncoding", "THE_ISO_1234"); - SourceEncoding.init(p); - assertThat(p.getProperty("sonar.sourceEncoding", null)).isEqualTo("THE_ISO_1234"); - } - - @Test - public void should_not_init_encoding_if_not_project_task() throws Exception { - p.setProperty("sonar.task", "views"); - SourceEncoding.init(p); - assertThat(p.getProperty("sonar.sourceEncoding", null)).isNull(); - } -} diff --git a/sonar-runner-impl/src/test/java/org/sonar/runner/impl/IsolatedClassloaderTest.java b/sonar-runner-api/src/test/java/org/sonar/runner/impl/IsolatedClassloaderTest.java index 222a2f5..c1cb9a5 100644 --- a/sonar-runner-impl/src/test/java/org/sonar/runner/impl/IsolatedClassloaderTest.java +++ b/sonar-runner-api/src/test/java/org/sonar/runner/impl/IsolatedClassloaderTest.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - Implementation + * SonarQube Runner - API * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * @@ -20,7 +20,6 @@ package org.sonar.runner.impl; import java.io.IOException; - import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -32,38 +31,15 @@ public class IsolatedClassloaderTest { public ExpectedException thrown = ExpectedException.none(); @Test - public void should_restrict_loading_from_parent() throws IOException { - ClassLoader parentClassloader = getClass().getClassLoader(); - IsolatedClassloader classLoader = new IsolatedClassloader(parentClassloader, new String[][] {new String[] {"UNMASK", "org.apache.ant."}}); - - assertThat(classLoader.canLoadFromParent("org.sonar.runner.Foo")).isFalse(); - assertThat(classLoader.canLoadFromParent("org.objectweb.asm.ClassVisitor")).isFalse(); - - assertThat(classLoader.canLoadFromParent("org.apache.ant.Foo")).isTrue(); - assertThat(classLoader.canLoadFromParent("org.apache.ant.project.Project")).isTrue(); - classLoader.close(); - } - - @Test public void should_use_isolated_system_classloader_when_parent_is_excluded() throws ClassNotFoundException, IOException { thrown.expect(ClassNotFoundException.class); thrown.expectMessage("org.junit.Test"); ClassLoader parent = getClass().getClassLoader(); - IsolatedClassloader classLoader = new IsolatedClassloader(parent, new String[0][]); + IsolatedClassloader classLoader = new IsolatedClassloader(parent); // JUnit is available in the parent classloader (classpath used to execute this test) but not in the core JVM assertThat(classLoader.loadClass("java.lang.String", false)).isNotNull(); classLoader.loadClass("org.junit.Test", false); classLoader.close(); } - - @Test - public void should_find_in_parent_when_matches_unmasked_packages() throws ClassNotFoundException, IOException { - ClassLoader parent = getClass().getClassLoader(); - IsolatedClassloader classLoader = new IsolatedClassloader(parent, new String[][] {new String[] {"UNMASK", "org.junit."}}); - - // JUnit is available in the parent classloader (classpath used to execute this test) but not in the core JVM - assertThat(classLoader.loadClass("org.junit.Test", false)).isNotNull(); - classLoader.close(); - } } diff --git a/sonar-runner-impl/src/test/java/org/sonar/runner/impl/IsolatedLauncherFactoryTest.java b/sonar-runner-api/src/test/java/org/sonar/runner/impl/IsolatedLauncherFactoryTest.java index 98154b2..d9eb613 100644 --- a/sonar-runner-impl/src/test/java/org/sonar/runner/impl/IsolatedLauncherFactoryTest.java +++ b/sonar-runner-api/src/test/java/org/sonar/runner/impl/IsolatedLauncherFactoryTest.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - Implementation + * SonarQube Runner - API * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * @@ -19,18 +19,15 @@ */ package org.sonar.runner.impl; -import org.sonar.home.log.LogListener; +import java.util.Properties; import org.junit.Before; +import org.junit.Test; +import org.sonar.home.cache.Logger; import org.sonar.runner.batch.IsolatedLauncher; +import org.sonar.runner.batch.LogOutput; -import java.util.List; -import java.util.Properties; - -import org.junit.Test; -import static org.fest.assertions.Assertions.assertThat; import static org.fest.assertions.Fail.fail; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; public class IsolatedLauncherFactoryTest { IsolatedLauncherFactory factory; @@ -41,47 +38,15 @@ public class IsolatedLauncherFactoryTest { @Before public void setUp() { tempCleaning = mock(TempCleaning.class); - factory = new IsolatedLauncherFactory(FakeIsolatedLauncher.class.getName(), tempCleaning); + factory = new IsolatedLauncherFactory(FakeIsolatedLauncher.class.getName(), tempCleaning, mock(Logger.class)); props = new Properties(); jarDownloader = mock(JarDownloader.class); } @Test - public void should_process_mask_rules() { - Properties p = new Properties(); - p.put(InternalProperties.RUNNER_MASK_RULES, "UNMASK|org.sonar.runner.impl."); - p.put("a", "b"); - - String[][] maskRules = IsolatedLauncherFactory.getMaskRules(p); - - assertThat(maskRules).hasSize(1); - assertThat(maskRules[0]).hasSize(2); - assertThat(maskRules[0][0]).isEqualTo("UNMASK"); - assertThat(maskRules[0][1]).isEqualTo("org.sonar.runner.impl."); - } - - @Test - public void should_download_jars_and_execute_batch() { - props.put("foo", "bar"); - - // Unmask the current classloader in order to access FakeIsolatedLauncher - props.put(InternalProperties.RUNNER_MASK_RULES, "UNMASK|org.sonar.runner.impl."); - - IsolatedLauncher isolatedLauncher = factory.createLauncher(jarDownloader, props); - isolatedLauncher.execute(props); - - verify(jarDownloader).download(); - verify(tempCleaning).clean(); - assertThat(FakeIsolatedLauncher.props.get("foo")).isEqualTo("bar"); - assertThat(isolatedLauncher.getClass().getClassLoader().getClass().getSimpleName()).isEqualTo("IsolatedClassloader"); - } - - @Test public void should_use_isolated_classloader() { - // The current classloader in not available -> fail to load FakeIsolatedLauncher - props.put(InternalProperties.RUNNER_MASK_RULES, ""); try { - factory.createLauncher(jarDownloader, props); + factory.createLauncher(jarDownloader); fail(); } catch (RunnerException e) { // success @@ -92,7 +57,7 @@ public class IsolatedLauncherFactoryTest { public static Properties props = null; @Override - public void start(Properties properties, List<Object> extensions) { + public void start(Properties properties, LogOutput logger) { } @Override @@ -105,11 +70,7 @@ public class IsolatedLauncherFactoryTest { } @Override - public void start(Properties properties, List<Object> extensions, LogListener logListener) { - } - - @Override - public void executeOldVersion(Properties properties, List<Object> extensions) { + public void executeOldVersion(Properties properties) { } @Override diff --git a/sonar-runner-impl/src/test/java/org/sonar/runner/impl/IsolatedLauncherProxyTest.java b/sonar-runner-api/src/test/java/org/sonar/runner/impl/IsolatedLauncherProxyTest.java index 8a2bb01..a75bb54 100644 --- a/sonar-runner-impl/src/test/java/org/sonar/runner/impl/IsolatedLauncherProxyTest.java +++ b/sonar-runner-api/src/test/java/org/sonar/runner/impl/IsolatedLauncherProxyTest.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - Implementation + * SonarQube Runner - API * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * @@ -22,11 +22,13 @@ package org.sonar.runner.impl; import java.net.URL; import java.net.URLClassLoader; import java.util.concurrent.Callable; +import org.junit.Before; +import org.junit.Test; +import org.sonar.home.cache.Logger; +import org.sonar.runner.batch.BatchIsolatedLauncher; import static org.assertj.core.api.Assertions.assertThat; -import org.sonar.runner.batch.BatchIsolatedLauncher; -import org.junit.Test; -import org.junit.Before; +import static org.mockito.Mockito.mock; public class IsolatedLauncherProxyTest { BatchIsolatedLauncher laucherProxy = null; @@ -40,19 +42,19 @@ public class IsolatedLauncherProxyTest { @Test public void delegate_proxied() throws ClassNotFoundException, InstantiationException, IllegalAccessException { String str = "test"; - CharSequence s = IsolatedLauncherProxy.create(cl, str, CharSequence.class); + CharSequence s = IsolatedLauncherProxy.create(cl, str, CharSequence.class, mock(Logger.class)); assertThat(s).isEqualTo(str); } @Test(expected = IllegalStateException.class) public void exceptions_unwrapped() throws ReflectiveOperationException { - Runnable r = IsolatedLauncherProxy.create(cl, Runnable.class, ExceptionThrower.class.getName()); + Runnable r = IsolatedLauncherProxy.create(cl, Runnable.class, ExceptionThrower.class.getName(), mock(Logger.class)); r.run(); } @Test public void create_proxied() throws Exception { - Callable<?> c = IsolatedLauncherProxy.create(cl, Callable.class, SimpleClass.class.getName()); + Callable<?> c = IsolatedLauncherProxy.create(cl, Callable.class, SimpleClass.class.getName(), mock(Logger.class)); assertThat(c.getClass().getClassLoader()).isEqualTo(cl); assertThat(c.getClass().getClassLoader()).isNotEqualTo(Thread.currentThread().getContextClassLoader()); assertThat(c.call()).isEqualTo(URLClassLoader.class.getSimpleName()); diff --git a/sonar-runner-impl/src/test/java/org/sonar/runner/impl/JarDownloaderTest.java b/sonar-runner-api/src/test/java/org/sonar/runner/impl/JarDownloaderTest.java index aff8805..35e02df 100644 --- a/sonar-runner-impl/src/test/java/org/sonar/runner/impl/JarDownloaderTest.java +++ b/sonar-runner-api/src/test/java/org/sonar/runner/impl/JarDownloaderTest.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - Implementation + * SonarQube Runner - API * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * @@ -24,6 +24,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Properties; import org.junit.Test; +import org.sonar.home.cache.Logger; import static org.fest.assertions.Assertions.assertThat; import static org.mockito.Mockito.doReturn; @@ -34,7 +35,7 @@ public class JarDownloaderTest { ServerConnection serverConnection = mock(ServerConnection.class); Properties props = new Properties(); - JarDownloader downloader = spy(new JarDownloader(serverConnection)); + JarDownloader downloader = spy(new JarDownloader(serverConnection, mock(Logger.class))); @Test public void should_download_jar_files() { diff --git a/sonar-runner-impl/src/test/java/org/sonar/runner/impl/JarExtractorTest.java b/sonar-runner-api/src/test/java/org/sonar/runner/impl/JarExtractorTest.java index 018ac07..8d2c0d7 100644 --- a/sonar-runner-impl/src/test/java/org/sonar/runner/impl/JarExtractorTest.java +++ b/sonar-runner-api/src/test/java/org/sonar/runner/impl/JarExtractorTest.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - Implementation + * SonarQube Runner - API * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * diff --git a/sonar-runner-impl/src/test/java/org/sonar/runner/impl/JarsTest.java b/sonar-runner-api/src/test/java/org/sonar/runner/impl/JarsTest.java index b6fead1..047d4e7 100644 --- a/sonar-runner-impl/src/test/java/org/sonar/runner/impl/JarsTest.java +++ b/sonar-runner-api/src/test/java/org/sonar/runner/impl/JarsTest.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - Implementation + * SonarQube Runner - API * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * @@ -19,13 +19,13 @@ */ package org.sonar.runner.impl; +import java.io.File; +import java.util.List; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.sonar.home.cache.FileCache; - -import java.io.File; -import java.util.List; +import org.sonar.home.cache.Logger; import static org.fest.assertions.Assertions.assertThat; import static org.fest.assertions.Fail.fail; @@ -52,11 +52,10 @@ public class JarsTest { when(jarExtractor.extractToTemp("sonar-runner-batch")).thenReturn(batchJar); // index of the files to download when(connection.downloadStringCache("/batch_bootstrap/index")).thenReturn( - "cpd.jar|CA124VADFSDS\n" + - "squid.jar|34535FSFSDF\n" - ); + "cpd.jar|CA124VADFSDS\n" + + "squid.jar|34535FSFSDF\n"); - Jars jars35 = new Jars(fileCache, connection, jarExtractor); + Jars jars35 = new Jars(fileCache, connection, jarExtractor, mock(Logger.class)); List<File> files = jars35.download(); assertThat(files).isNotNull(); @@ -74,7 +73,7 @@ public class JarsTest { // index of the files to download when(connection.downloadStringCache("/batch_bootstrap/index")).thenThrow(new IllegalStateException()); - Jars jars35 = new Jars(fileCache, connection, jarExtractor); + Jars jars35 = new Jars(fileCache, connection, jarExtractor, mock(Logger.class)); try { jars35.download(); fail(); diff --git a/sonar-runner-impl/src/test/java/org/sonar/runner/impl/MockHttpServer.java b/sonar-runner-api/src/test/java/org/sonar/runner/impl/MockHttpServer.java index 77982f3..36e5d08 100644 --- a/sonar-runner-impl/src/test/java/org/sonar/runner/impl/MockHttpServer.java +++ b/sonar-runner-api/src/test/java/org/sonar/runner/impl/MockHttpServer.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - Implementation + * SonarQube Runner - API * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * diff --git a/sonar-runner-impl/src/test/java/org/sonar/runner/impl/MockHttpServerInterceptor.java b/sonar-runner-api/src/test/java/org/sonar/runner/impl/MockHttpServerInterceptor.java index 7e23fbe..2cbfc7e 100644 --- a/sonar-runner-impl/src/test/java/org/sonar/runner/impl/MockHttpServerInterceptor.java +++ b/sonar-runner-api/src/test/java/org/sonar/runner/impl/MockHttpServerInterceptor.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - Implementation + * SonarQube Runner - API * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * diff --git a/sonar-runner-impl/src/test/java/org/sonar/runner/impl/NetworkUtil.java b/sonar-runner-api/src/test/java/org/sonar/runner/impl/NetworkUtil.java index cb63c1e..f9bfd83 100644 --- a/sonar-runner-impl/src/test/java/org/sonar/runner/impl/NetworkUtil.java +++ b/sonar-runner-api/src/test/java/org/sonar/runner/impl/NetworkUtil.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - Implementation + * SonarQube Runner - API * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * diff --git a/sonar-runner-impl/src/test/java/org/sonar/runner/impl/ServerConnectionTest.java b/sonar-runner-api/src/test/java/org/sonar/runner/impl/ServerConnectionTest.java index b1a94c7..d926203 100644 --- a/sonar-runner-impl/src/test/java/org/sonar/runner/impl/ServerConnectionTest.java +++ b/sonar-runner-api/src/test/java/org/sonar/runner/impl/ServerConnectionTest.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - Implementation + * SonarQube Runner - API * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * @@ -19,19 +19,20 @@ */ package org.sonar.runner.impl; -import org.junit.Before; -import org.sonar.home.cache.PersistentCacheBuilder; -import org.sonar.home.cache.PersistentCache; +import java.io.File; +import java.util.Properties; import org.apache.commons.io.FileUtils; +import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; - -import java.io.File; -import java.util.Properties; +import org.sonar.home.cache.Logger; +import org.sonar.home.cache.PersistentCache; +import org.sonar.home.cache.PersistentCacheBuilder; import static org.fest.assertions.Assertions.assertThat; import static org.fest.assertions.Fail.fail; +import static org.mockito.Mockito.mock; public class ServerConnectionTest { @@ -45,7 +46,7 @@ public class ServerConnectionTest { @Before public void setUp() { - cache = new PersistentCacheBuilder().setSonarHome(temp.getRoot().toPath()).build(); + cache = new PersistentCacheBuilder(mock(Logger.class)).setSonarHome(temp.getRoot().toPath()).build(); } @Test @@ -54,7 +55,7 @@ public class ServerConnectionTest { Properties props = new Properties(); props.setProperty("sonar.host.url", httpServer.url()); - ServerConnection connection = ServerConnection.create(props, cache); + ServerConnection connection = ServerConnection.create(props, cache, mock(Logger.class)); String response = connection.downloadStringCache("/batch/index.txt"); assertThat(response).isEqualTo("abcde"); @@ -66,13 +67,13 @@ public class ServerConnectionTest { Properties props = new Properties(); props.setProperty("sonar.host.url", httpServer.url()); - ServerConnection connection = ServerConnection.create(props, cache); + ServerConnection connection = ServerConnection.create(props, cache, mock(Logger.class)); File toFile = temp.newFile(); connection.download("/batch/index.txt", toFile); assertThat(FileUtils.readFileToString(toFile)).isEqualTo("abcde"); } - + @Test public void should_cache_jar_list() throws Exception { File cacheDir = new File(temp.getRoot(), "ws_cache"); @@ -80,33 +81,33 @@ public class ServerConnectionTest { Properties props = new Properties(); props.setProperty("sonar.host.url", httpServer.url() + "/"); props.setProperty("sonar.analysis.mode", "preview"); - + assertThat(cacheDir.list().length).isEqualTo(0); - ServerConnection connection = ServerConnection.create(props, cache); + ServerConnection connection = ServerConnection.create(props, cache, mock(Logger.class)); String str = connection.downloadStringCache("/batch/index.txt"); - + assertThat(str).isEqualTo("abcde"); assertThat(cacheDir.list().length).isEqualTo(2); - + httpServer.setMockResponseData("never requested"); str = connection.downloadStringCache("/batch/index.txt"); assertThat(str).isEqualTo("abcde"); } - + @Test public void should_not_cache_not_preview() throws Exception { File cacheDir = new File(temp.getRoot(), "ws_cache"); httpServer.setMockResponseData("abcde"); Properties props = new Properties(); props.setProperty("sonar.host.url", httpServer.url() + "/"); - + assertThat(cacheDir.list().length).isEqualTo(0); - ServerConnection connection = ServerConnection.create(props, cache); + ServerConnection connection = ServerConnection.create(props, cache, mock(Logger.class)); String str = connection.downloadStringCache("/batch/index.txt"); - + assertThat(str).isEqualTo("abcde"); assertThat(cacheDir.list().length).isEqualTo(0); - + httpServer.setMockResponseData("request2"); str = connection.downloadStringCache("/batch/index.txt"); assertThat(str).isEqualTo("request2"); @@ -119,7 +120,7 @@ public class ServerConnectionTest { Properties props = new Properties(); props.setProperty("sonar.host.url", httpServer.url() + "/"); - ServerConnection connection = ServerConnection.create(props, cache); + ServerConnection connection = ServerConnection.create(props, cache, mock(Logger.class)); File toFile = temp.newFile(); connection.download("/batch/index.txt", toFile); @@ -131,7 +132,7 @@ public class ServerConnectionTest { Properties props = new Properties(); props.setProperty("sonar.host.url", "http://localhost:" + NetworkUtil.getNextAvailablePort()); - ServerConnection connection = ServerConnection.create(props, cache); + ServerConnection connection = ServerConnection.create(props, cache, mock(Logger.class)); File toFile = temp.newFile(); try { connection.download("/batch/index.txt", toFile); @@ -146,7 +147,7 @@ public class ServerConnectionTest { Properties props = new Properties(); props.setProperty("sonar.host.url", "http://localhost:" + NetworkUtil.getNextAvailablePort()); - ServerConnection connection = ServerConnection.create(props, cache); + ServerConnection connection = ServerConnection.create(props, cache, mock(Logger.class)); try { connection.downloadStringCache("/batch/index.txt"); fail(); diff --git a/sonar-runner-impl/src/test/java/org/sonar/runner/impl/TempCleaningTest.java b/sonar-runner-api/src/test/java/org/sonar/runner/impl/TempCleaningTest.java index 8ca07b9..2037a62 100644 --- a/sonar-runner-impl/src/test/java/org/sonar/runner/impl/TempCleaningTest.java +++ b/sonar-runner-api/src/test/java/org/sonar/runner/impl/TempCleaningTest.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - Implementation + * SonarQube Runner - API * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * @@ -19,14 +19,15 @@ */ package org.sonar.runner.impl; +import java.io.File; import org.apache.commons.io.FileUtils; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; - -import java.io.File; +import org.sonar.home.cache.Logger; import static org.fest.assertions.Assertions.assertThat; +import static org.mockito.Mockito.mock; public class TempCleaningTest { @@ -34,8 +35,8 @@ public class TempCleaningTest { public TemporaryFolder temp = new TemporaryFolder(); @Test - public void should_clean_jvm_tmp_dir( ){ - TempCleaning cleaning = new TempCleaning(); + public void should_clean_jvm_tmp_dir() { + TempCleaning cleaning = new TempCleaning(mock(Logger.class)); assertThat(cleaning.tempDir).isDirectory().exists(); } @@ -55,7 +56,7 @@ public class TempCleaningTest { assertThat(oldBatch).exists(); assertThat(youngBatch).exists(); assertThat(doNotDelete).exists(); - new TempCleaning(dir).clean(); + new TempCleaning(dir, mock(Logger.class)).clean(); assertThat(oldBatch).doesNotExist(); assertThat(youngBatch).exists(); diff --git a/sonar-runner-impl/src/test/resources/fake.jar b/sonar-runner-api/src/test/resources/fake.jar index 4c83c13..4c83c13 100644 --- a/sonar-runner-impl/src/test/resources/fake.jar +++ b/sonar-runner-api/src/test/resources/fake.jar diff --git a/sonar-runner-impl/src/test/resources/org/sonar/runner/impl/BatchLauncherMainTest/props.properties b/sonar-runner-api/src/test/resources/org/sonar/runner/impl/BatchLauncherMainTest/props.properties index 82640ae..82640ae 100644 --- a/sonar-runner-impl/src/test/resources/org/sonar/runner/impl/BatchLauncherMainTest/props.properties +++ b/sonar-runner-api/src/test/resources/org/sonar/runner/impl/BatchLauncherMainTest/props.properties diff --git a/sonar-runner-batch-interface/src/main/java/org/sonar/runner/batch/IsolatedLauncher.java b/sonar-runner-batch-interface/src/main/java/org/sonar/runner/batch/IsolatedLauncher.java index 22fa54d..21b0d73 100644 --- a/sonar-runner-batch-interface/src/main/java/org/sonar/runner/batch/IsolatedLauncher.java +++ b/sonar-runner-batch-interface/src/main/java/org/sonar/runner/batch/IsolatedLauncher.java @@ -19,21 +19,17 @@ */ package org.sonar.runner.batch; -import org.sonar.home.log.LogListener; - -import java.util.List; import java.util.Properties; public interface IsolatedLauncher { - void start(Properties properties, List<Object> extensions); - void start(Properties properties, List<Object> extensions, LogListener logListener); + void start(Properties properties, LogOutput logOutput); void stop(); void execute(Properties properties); - void executeOldVersion(Properties properties, List<Object> extensions); + void executeOldVersion(Properties properties); String getVersion(); } diff --git a/sonar-runner-api/src/main/java/org/sonar/runner/api/CommandException.java b/sonar-runner-batch-interface/src/main/java/org/sonar/runner/batch/LogOutput.java index 6c371a5..f17eb55 100644 --- a/sonar-runner-api/src/main/java/org/sonar/runner/api/CommandException.java +++ b/sonar-runner-batch-interface/src/main/java/org/sonar/runner/batch/LogOutput.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - API + * SonarQube Runner - Batch Interface * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * @@ -17,14 +17,17 @@ * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ -package org.sonar.runner.api; +package org.sonar.runner.batch; -import javax.annotation.Nullable; +/** + * Allow to redirect batch logs to a custom output. By defaults logs are written to System.out + * @since 5.2 + */ +public interface LogOutput { -class CommandException extends RuntimeException { + void log(String formattedMessage, Level level); - CommandException(String message, Command command, @Nullable Throwable throwable) { - super(message + " [command: " + command + "]", throwable); + enum Level { + ERROR, WARN, INFO, DEBUG, TRACE; } - } diff --git a/sonar-runner-batch/pom.xml b/sonar-runner-batch/pom.xml index 4fe84da..dc57821 100644 --- a/sonar-runner-batch/pom.xml +++ b/sonar-runner-batch/pom.xml @@ -21,12 +21,6 @@ <scope>provided</scope> </dependency> <dependency> - <groupId>ch.qos.logback</groupId> - <artifactId>logback-classic</artifactId> - <version>0.9.15</version> - <scope>provided</scope> - </dependency> - <dependency> <groupId>org.codehaus.sonar</groupId> <artifactId>sonar-batch</artifactId> <version>${sonarBatchVersion}</version> diff --git a/sonar-runner-batch/src/main/java/org/sonar/runner/batch/BatchIsolatedLauncher.java b/sonar-runner-batch/src/main/java/org/sonar/runner/batch/BatchIsolatedLauncher.java index b88ba6e..8723ed8 100644 --- a/sonar-runner-batch/src/main/java/org/sonar/runner/batch/BatchIsolatedLauncher.java +++ b/sonar-runner-batch/src/main/java/org/sonar/runner/batch/BatchIsolatedLauncher.java @@ -19,22 +19,17 @@ */ package org.sonar.runner.batch; -import org.sonar.home.log.LogListener; -import org.picocontainer.annotations.Nullable; -import com.google.common.annotations.VisibleForTesting; - import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; -import java.util.List; import java.util.Map; import java.util.Properties; - -import org.sonar.api.utils.SonarException; +import org.picocontainer.annotations.Nullable; import org.sonar.batch.bootstrapper.Batch; import org.sonar.batch.bootstrapper.EnvironmentInformation; +import org.sonar.batch.bootstrapper.LogOutput; /** * This class is executed within the classloader provided by the server. It contains the installed plugins and @@ -42,20 +37,11 @@ import org.sonar.batch.bootstrapper.EnvironmentInformation; */ public class BatchIsolatedLauncher implements IsolatedLauncher { - private static final String WARN = "WARN"; - private static final String DEBUG = "DEBUG"; - private static final String FALSE = "false"; - private Batch batch = null; @Override - public void start(Properties globalProperties, List<Object> extensions) { - start(globalProperties, extensions, null); - } - - @Override - public void start(Properties globalProperties, List<Object> extensions, @Nullable LogListener logListener) { - batch = createBatch(globalProperties, extensions, logListener); + public void start(Properties globalProperties, org.sonar.runner.batch.LogOutput logOutput) { + batch = createBatch(globalProperties, logOutput); batch.start(); } @@ -69,15 +55,21 @@ public class BatchIsolatedLauncher implements IsolatedLauncher { batch.executeTask((Map) properties); } - Batch createBatch(Properties properties, List<Object> extensions, @Nullable LogListener logListener) { + Batch createBatch(Properties properties, @Nullable final org.sonar.runner.batch.LogOutput logOutput) { EnvironmentInformation env = new EnvironmentInformation(properties.getProperty("sonarRunner.app"), properties.getProperty("sonarRunner.appVersion")); Batch.Builder builder = Batch.builder() .setEnvironment(env) - .addComponents(extensions) .setBootstrapProperties((Map) properties); - if (logListener != null) { - builder.setLogListener(logListener); + if (logOutput != null) { + builder.setLogOutput(new LogOutput() { + + @Override + public void log(String formattedMessage, Level level) { + logOutput.log(formattedMessage, org.sonar.runner.batch.LogOutput.Level.valueOf(level.name())); + } + + }); } return builder.build(); @@ -87,8 +79,8 @@ public class BatchIsolatedLauncher implements IsolatedLauncher { * This method exists for backward compatibility with SonarQube < 5.2. */ @Override - public void executeOldVersion(Properties properties, List<Object> extensions) { - createBatch(properties, extensions, null).execute(); + public void executeOldVersion(Properties properties) { + createBatch(properties, null).execute(); } @Override diff --git a/sonar-runner-batch/src/test/java/org/sonar/runner/batch/IsolatedLauncherTest.java b/sonar-runner-batch/src/test/java/org/sonar/runner/batch/IsolatedLauncherTest.java index 2108751..610ff75 100644 --- a/sonar-runner-batch/src/test/java/org/sonar/runner/batch/IsolatedLauncherTest.java +++ b/sonar-runner-batch/src/test/java/org/sonar/runner/batch/IsolatedLauncherTest.java @@ -19,7 +19,6 @@ */ package org.sonar.runner.batch; -import java.util.Collections; import java.util.Properties; import org.junit.Test; import org.sonar.batch.bootstrapper.Batch; @@ -38,7 +37,7 @@ public class IsolatedLauncherTest { props.setProperty("sonar.projectName", "Sample"); props.setProperty("sonar.projectVersion", "1.0"); props.setProperty("sonar.sources", "src"); - Batch batch = launcher.createBatch(props, Collections.emptyList(), null); + Batch batch = launcher.createBatch(props, null); assertThat(batch).isNotNull(); } diff --git a/sonar-runner-dist/assembly.xml b/sonar-runner-cli/assembly.xml index 70a9969..70a9969 100644 --- a/sonar-runner-dist/assembly.xml +++ b/sonar-runner-cli/assembly.xml diff --git a/sonar-runner-dist/pom.xml b/sonar-runner-cli/pom.xml index 229643b..54f9eb6 100644 --- a/sonar-runner-dist/pom.xml +++ b/sonar-runner-cli/pom.xml @@ -6,9 +6,9 @@ <version>2.5-SNAPSHOT</version> </parent> - <artifactId>sonar-runner-dist</artifactId> + <artifactId>sonar-runner-cli</artifactId> <packaging>jar</packaging> - <name>SonarQube Runner - Distribution</name> + <name>SonarQube Runner - CLI - Distribution</name> <dependencies> <dependency> @@ -17,12 +17,6 @@ <version>${project.version}</version> </dependency> <dependency> - <groupId>${project.groupId}</groupId> - <artifactId>sonar-runner-impl</artifactId> - <version>${project.version}</version> - <scope>provided</scope> - </dependency> - <dependency> <groupId>com.google.code.findbugs</groupId> <artifactId>jsr305</artifactId> <scope>provided</scope> @@ -58,7 +52,7 @@ <archive> <manifest> <addClasspath>false</addClasspath> - <mainClass>org.sonar.runner.Main</mainClass> + <mainClass>org.sonar.runner.cli.Main</mainClass> </manifest> </archive> </configuration> @@ -115,8 +109,8 @@ <configuration> <rules> <requireFilesSize> - <minsize>279000</minsize> - <maxsize>350000</maxsize> + <minsize>160000</minsize> + <maxsize>180000</maxsize> <files> <file>${project.build.directory}/sonar-runner-${project.version}.zip</file> </files> diff --git a/sonar-runner-dist/src/main/assembly/bin/sonar-runner b/sonar-runner-cli/src/main/assembly/bin/sonar-runner index a3c2218..6ebfa40 100755 --- a/sonar-runner-dist/src/main/assembly/bin/sonar-runner +++ b/sonar-runner-cli/src/main/assembly/bin/sonar-runner @@ -80,13 +80,13 @@ if [ -z "$SONAR_RUNNER_HOME" ] ; then fi # check that the SONAR_RUNNER_HOME has been correctly set -if [ ! -f "$SONAR_RUNNER_HOME/lib/sonar-runner-dist-${project.version}.jar" ] ; then +if [ ! -f "$SONAR_RUNNER_HOME/lib/sonar-runner-cli-${project.version}.jar" ] ; then echo '$SONAR_RUNNER_HOME' does not point to a valid installation directory: $SONAR_RUNNER_HOME exit 1 fi JAVA_CMD="`which java`" -JAR_FILE="${SONAR_RUNNER_HOME}"/lib/sonar-runner-dist-${project.version}.jar +JAR_FILE="${SONAR_RUNNER_HOME}"/lib/sonar-runner-cli-${project.version}.jar PROJECT_HOME=`pwd` #echo "Info: Using sonar-runner at $SONAR_RUNNER_HOME" @@ -99,5 +99,5 @@ exec "$JAVA_CMD" \ -classpath $JAR_FILE \ "-Drunner.home=\${SONAR_RUNNER_HOME}" \ "-Dproject.home=\${PROJECT_HOME}" \ - org.sonar.runner.Main "$@" + org.sonar.runner.cli.Main "$@" diff --git a/sonar-runner-dist/src/main/assembly/bin/sonar-runner.bat b/sonar-runner-cli/src/main/assembly/bin/sonar-runner.bat index e3e603e..bf5eb80 100644 --- a/sonar-runner-dist/src/main/assembly/bin/sonar-runner.bat +++ b/sonar-runner-cli/src/main/assembly/bin/sonar-runner.bat @@ -58,7 +58,7 @@ goto run if "%SONAR_RUNNER_HOME:~-1%"=="\" set SONAR_RUNNER_HOME=%SONAR_RUNNER_HOME:~0,-1% @REM Check if the provided SONAR_RUNNER_HOME is a valid install dir -IF EXIST "%SONAR_RUNNER_HOME%\lib\sonar-runner-dist-${project.version}.jar" goto run +IF EXIST "%SONAR_RUNNER_HOME%\lib\sonar-runner-cli-${project.version}.jar" goto run echo. echo ERROR: SONAR_RUNNER_HOME exists but does not point to a valid install @@ -74,7 +74,7 @@ echo %SONAR_RUNNER_HOME% set PROJECT_HOME=%CD% -%JAVA_EXEC% %SONAR_RUNNER_OPTS% -cp "%SONAR_RUNNER_HOME%\lib\sonar-runner-dist-${project.version}.jar" "-Drunner.home=%SONAR_RUNNER_HOME%" "-Dproject.home=%PROJECT_HOME%" org.sonar.runner.Main %* +%JAVA_EXEC% %SONAR_RUNNER_OPTS% -cp "%SONAR_RUNNER_HOME%\lib\sonar-runner-cli-${project.version}.jar" "-Drunner.home=%SONAR_RUNNER_HOME%" "-Dproject.home=%PROJECT_HOME%" org.sonar.runner.cli.Main %* if ERRORLEVEL 1 goto error goto end diff --git a/sonar-runner-dist/src/main/assembly/conf/sonar-runner.properties b/sonar-runner-cli/src/main/assembly/conf/sonar-runner.properties index 213cc00..213cc00 100644 --- a/sonar-runner-dist/src/main/assembly/conf/sonar-runner.properties +++ b/sonar-runner-cli/src/main/assembly/conf/sonar-runner.properties diff --git a/sonar-runner-dist/src/main/java/org/sonar/runner/Cli.java b/sonar-runner-cli/src/main/java/org/sonar/runner/cli/Cli.java index 3a796e8..46489d8 100644 --- a/sonar-runner-dist/src/main/java/org/sonar/runner/Cli.java +++ b/sonar-runner-cli/src/main/java/org/sonar/runner/cli/Cli.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - Distribution + * SonarQube Runner - CLI - Distribution * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * @@ -17,12 +17,10 @@ * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ -package org.sonar.runner; - -import org.sonar.runner.api.RunnerProperties; -import org.sonar.runner.impl.Logs; +package org.sonar.runner.cli; import java.util.Properties; +import org.sonar.runner.api.RunnerProperties; class Cli { @@ -73,12 +71,14 @@ class Cli { } else if ("-e".equals(arg) || "--errors".equals(arg)) { displayStackTrace = true; + Logs.setDisplayStackTrace(true); } else if ("-X".equals(arg) || "--debug".equals(arg)) { props.setProperty("sonar.verbose", "true"); displayStackTrace = true; debugMode = true; Logs.setDebugEnabled(true); + Logs.setDisplayStackTrace(true); } else if ("-D".equals(arg) || "--define".equals(arg)) { i++; diff --git a/sonar-runner-dist/src/main/java/org/sonar/runner/Conf.java b/sonar-runner-cli/src/main/java/org/sonar/runner/cli/Conf.java index 4885a04..e32a06c 100644 --- a/sonar-runner-dist/src/main/java/org/sonar/runner/Conf.java +++ b/sonar-runner-cli/src/main/java/org/sonar/runner/cli/Conf.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - Distribution + * SonarQube Runner - CLI - Distribution * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * @@ -17,9 +17,7 @@ * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ -package org.sonar.runner; - -import org.sonar.runner.impl.Logs; +package org.sonar.runner.cli; import java.io.File; import java.io.FileInputStream; diff --git a/sonar-runner-dist/src/main/java/org/sonar/runner/Exit.java b/sonar-runner-cli/src/main/java/org/sonar/runner/cli/Exit.java index b893e54..7c2ed3c 100644 --- a/sonar-runner-dist/src/main/java/org/sonar/runner/Exit.java +++ b/sonar-runner-cli/src/main/java/org/sonar/runner/cli/Exit.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - Distribution + * SonarQube Runner - CLI - Distribution * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * @@ -17,7 +17,7 @@ * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ -package org.sonar.runner; +package org.sonar.runner.cli; class Exit { static final int SUCCESS = 0; diff --git a/sonar-runner-cli/src/main/java/org/sonar/runner/cli/Logs.java b/sonar-runner-cli/src/main/java/org/sonar/runner/cli/Logs.java new file mode 100644 index 0000000..a68e282 --- /dev/null +++ b/sonar-runner-cli/src/main/java/org/sonar/runner/cli/Logs.java @@ -0,0 +1,66 @@ +/* + * SonarQube Runner - CLI - Distribution + * Copyright (C) 2011 SonarSource + * dev@sonar.codehaus.org + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 + */ +package org.sonar.runner.cli; + +public class Logs { + + private Logs() { + } + + private static boolean debugEnabled = false; + private static boolean displayStackTrace = false; + + public static void setDebugEnabled(boolean debugEnabled) { + Logs.debugEnabled = debugEnabled; + } + + public static void setDisplayStackTrace(boolean displayStackTrace) { + Logs.displayStackTrace = displayStackTrace; + } + + public static boolean isDebugEnabled() { + return debugEnabled; + } + + public static void debug(String message) { + if (isDebugEnabled()) { + System.out.println("DEBUG: " + message); + } + } + + public static void info(String message) { + System.out.println("INFO: " + message); + } + + public static void warn(String message) { + System.out.println("WARN: " + message); + } + + public static void error(String message) { + System.err.println("ERROR: " + message); + } + + public static void error(String message, Throwable t) { + System.err.println("ERROR: " + message); + if (t != null && displayStackTrace) { + t.printStackTrace(System.err); + } + } +} diff --git a/sonar-runner-dist/src/main/java/org/sonar/runner/Main.java b/sonar-runner-cli/src/main/java/org/sonar/runner/cli/Main.java index ea472d1..3552fbc 100644 --- a/sonar-runner-dist/src/main/java/org/sonar/runner/Main.java +++ b/sonar-runner-cli/src/main/java/org/sonar/runner/cli/Main.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - Distribution + * SonarQube Runner - CLI - Distribution * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * @@ -17,17 +17,14 @@ * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ -package org.sonar.runner; - -import org.sonar.runner.api.Runner; +package org.sonar.runner.cli; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.Properties; - -import org.sonar.runner.impl.Logs; +import org.sonar.runner.api.EmbeddedRunner; /** * Arguments : @@ -46,9 +43,9 @@ public class Main { private final Shutdown shutdown; private final Cli cli; private final Conf conf; - private final RunnerFactory runnerFactory; - private Runner<?> runner; + private EmbeddedRunner runner; private BufferedReader inputReader; + private RunnerFactory runnerFactory; Main(Shutdown shutdown, Cli cli, Conf conf, RunnerFactory runnerFactory) { this.shutdown = shutdown; @@ -76,11 +73,11 @@ public class Main { runAnalysis(stats, p); - if(cli.isInteractive()) { + if (cli.isInteractive()) { while (waitForUser()) { stats = new Stats().start(); runAnalysis(stats, p); - } + } } } catch (Exception e) { displayExecutionResult(stats, "FAILURE"); @@ -114,17 +111,17 @@ public class Main { if (inputReader == null) { inputReader = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8)); } - + shutdown.signalReady(true); - if(shutdown.shouldExit()) { - //exit before displaying message + if (shutdown.shouldExit()) { + // exit before displaying message return false; } - + Logs.info("<Press enter to restart analysis>"); - String line = inputReader.readLine(); + String line = inputReader.readLine(); shutdown.signalReady(false); - + return line != null; } diff --git a/sonar-runner-dist/src/main/java/org/sonar/runner/RunnerFactory.java b/sonar-runner-cli/src/main/java/org/sonar/runner/cli/RunnerFactory.java index 8b68140..60f6f31 100644 --- a/sonar-runner-dist/src/main/java/org/sonar/runner/RunnerFactory.java +++ b/sonar-runner-cli/src/main/java/org/sonar/runner/cli/RunnerFactory.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - Distribution + * SonarQube Runner - CLI - Distribution * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * @@ -17,29 +17,34 @@ * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ -package org.sonar.runner; - -import org.sonar.runner.api.EmbeddedRunner; -import org.sonar.runner.api.ForkedRunner; -import org.sonar.runner.api.Runner; +package org.sonar.runner.cli; import java.util.Properties; +import org.sonar.runner.api.EmbeddedRunner; +import org.sonar.runner.api.LogOutput; class RunnerFactory { - Runner create(Properties props) { - Runner<?> runner; - if ("fork".equals(props.getProperty("sonarRunner.mode"))) { - runner = ForkedRunner.create(); - String jvmArgs = props.getProperty("sonarRunner.fork.jvmArgs", ""); - if (!"".equals(jvmArgs)) { - ((ForkedRunner) runner).addJvmArguments(jvmArgs.split(" ")); - } + EmbeddedRunner create(Properties props) { + return EmbeddedRunner.create(new LogOutput() { - } else { - runner = EmbeddedRunner.create(); - } - runner.addGlobalProperties(props); - return runner; + @Override + public void log(String formattedMessage, Level level) { + switch (level) { + case TRACE: + case DEBUG: + Logs.debug(formattedMessage); + break; + case ERROR: + Logs.error(formattedMessage); + break; + case INFO: + case WARN: + default: + Logs.info(formattedMessage); + } + } + }).addGlobalProperties(props); } + } diff --git a/sonar-runner-dist/src/main/java/org/sonar/runner/Shutdown.java b/sonar-runner-cli/src/main/java/org/sonar/runner/cli/Shutdown.java index 70ec898..857faac 100644 --- a/sonar-runner-dist/src/main/java/org/sonar/runner/Shutdown.java +++ b/sonar-runner-cli/src/main/java/org/sonar/runner/cli/Shutdown.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - Distribution + * SonarQube Runner - CLI - Distribution * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * @@ -17,7 +17,7 @@ * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ -package org.sonar.runner; +package org.sonar.runner.cli; class Shutdown { static final int SUCCESS = 0; diff --git a/sonar-runner-dist/src/main/java/org/sonar/runner/Stats.java b/sonar-runner-cli/src/main/java/org/sonar/runner/cli/Stats.java index 12c8e6f..5089c12 100644 --- a/sonar-runner-dist/src/main/java/org/sonar/runner/Stats.java +++ b/sonar-runner-cli/src/main/java/org/sonar/runner/cli/Stats.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - Distribution + * SonarQube Runner - CLI - Distribution * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * @@ -17,9 +17,7 @@ * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ -package org.sonar.runner; - -import org.sonar.runner.impl.Logs; +package org.sonar.runner.cli; class Stats { private long startTime; diff --git a/sonar-runner-dist/src/main/java/org/sonar/runner/SystemInfo.java b/sonar-runner-cli/src/main/java/org/sonar/runner/cli/SystemInfo.java index c9575ba..090eafd 100644 --- a/sonar-runner-dist/src/main/java/org/sonar/runner/SystemInfo.java +++ b/sonar-runner-cli/src/main/java/org/sonar/runner/cli/SystemInfo.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - Distribution + * SonarQube Runner - CLI - Distribution * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * @@ -17,9 +17,7 @@ * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ -package org.sonar.runner; - -import org.sonar.runner.impl.Logs; +package org.sonar.runner.cli; import org.sonar.runner.api.RunnerVersion; diff --git a/sonar-runner-dist/src/main/java/org/sonar/runner/package-info.java b/sonar-runner-cli/src/main/java/org/sonar/runner/cli/package-info.java index 9dbe260..f92c312 100644 --- a/sonar-runner-dist/src/main/java/org/sonar/runner/package-info.java +++ b/sonar-runner-cli/src/main/java/org/sonar/runner/cli/package-info.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - Distribution + * SonarQube Runner - CLI - Distribution * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * @@ -18,7 +18,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ @ParametersAreNonnullByDefault -package org.sonar.runner; +package org.sonar.runner.cli; import javax.annotation.ParametersAreNonnullByDefault; diff --git a/sonar-runner-dist/src/test/java/org/sonar/runner/CliTest.java b/sonar-runner-cli/src/test/java/org/sonar/runner/cli/CliTest.java index 81091ea..9eda2b9 100644 --- a/sonar-runner-dist/src/test/java/org/sonar/runner/CliTest.java +++ b/sonar-runner-cli/src/test/java/org/sonar/runner/cli/CliTest.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - Distribution + * SonarQube Runner - CLI - Distribution * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * @@ -17,13 +17,16 @@ * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ -package org.sonar.runner; +package org.sonar.runner.cli; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import org.junit.Test; +import org.sonar.runner.cli.Cli; +import org.sonar.runner.cli.Exit; + import static org.fest.assertions.Assertions.assertThat; public class CliTest { diff --git a/sonar-runner-dist/src/test/java/org/sonar/runner/ConfTest.java b/sonar-runner-cli/src/test/java/org/sonar/runner/cli/ConfTest.java index 04292e2..bfeb23d 100644 --- a/sonar-runner-dist/src/test/java/org/sonar/runner/ConfTest.java +++ b/sonar-runner-cli/src/test/java/org/sonar/runner/cli/ConfTest.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - Distribution + * SonarQube Runner - CLI - Distribution * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * @@ -17,13 +17,14 @@ * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ -package org.sonar.runner; +package org.sonar.runner.cli; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; - +import org.sonar.runner.cli.Cli; +import org.sonar.runner.cli.Conf; import java.io.File; import java.util.Properties; diff --git a/sonar-runner-dist/src/test/java/org/sonar/runner/MainTest.java b/sonar-runner-cli/src/test/java/org/sonar/runner/cli/MainTest.java index 7b7e019..4ae594d 100644 --- a/sonar-runner-dist/src/test/java/org/sonar/runner/MainTest.java +++ b/sonar-runner-cli/src/test/java/org/sonar/runner/cli/MainTest.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - Distribution + * SonarQube Runner - CLI - Distribution * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * @@ -17,26 +17,25 @@ * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ -package org.sonar.runner; - -import org.mockito.MockitoAnnotations; -import org.mockito.Mock; -import org.junit.Before; -import org.mockito.Mockito; -import org.mockito.InOrder; -import org.junit.Test; -import org.sonar.runner.api.Runner; +package org.sonar.runner.cli; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.Properties; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.sonar.runner.api.EmbeddedRunner; -import static org.mockito.Mockito.times; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -53,7 +52,7 @@ public class MainTest { @Mock private RunnerFactory runnerFactory; @Mock - private Runner<?> runner; + private EmbeddedRunner runner; @Before public void setUp() throws IOException { @@ -78,7 +77,7 @@ public class MainTest { @Test public void should_fail_on_error() { - Runner<?> runner = mock(Runner.class); + EmbeddedRunner runner = mock(EmbeddedRunner.class); doThrow(new IllegalStateException("Error")).when(runner).runAnalysis(any(Properties.class)); when(runnerFactory.create(any(Properties.class))).thenReturn(runner); @@ -105,7 +104,7 @@ public class MainTest { inOrder.verify(exit, times(1)).exit(Exit.SUCCESS); } - @Test(timeout=30000) + @Test(timeout = 30000) public void test_interactive_mode() throws IOException { String inputStr = "qwe" + System.lineSeparator() + "qwe" + System.lineSeparator(); InputStream input = new ByteArrayInputStream(inputStr.getBytes(StandardCharsets.UTF_8)); diff --git a/sonar-runner-api/src/test/java/org/sonar/runner/api/SimpleRunner.java b/sonar-runner-cli/src/test/java/org/sonar/runner/cli/RunnerFactoryTest.java index 6c356fe..29955d3 100644 --- a/sonar-runner-api/src/test/java/org/sonar/runner/api/SimpleRunner.java +++ b/sonar-runner-cli/src/test/java/org/sonar/runner/cli/RunnerFactoryTest.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - API + * SonarQube Runner - CLI - Distribution * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * @@ -17,22 +17,25 @@ * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ -package org.sonar.runner.api; +package org.sonar.runner.cli; import java.util.Properties; +import org.junit.Test; +import org.sonar.runner.api.EmbeddedRunner; -class SimpleRunner extends Runner<SimpleRunner> { - @Override - protected void doExecute(Properties props) { - } +import static org.fest.assertions.Assertions.assertThat; - @Override - protected void doStart() { - - } +public class RunnerFactoryTest { + + Properties props = new Properties(); - @Override - protected void doStop() { - + @Test + public void should_create_embedded_runner() { + props.setProperty("foo", "bar"); + EmbeddedRunner runner = new RunnerFactory().create(props); + + assertThat(runner).isInstanceOf(EmbeddedRunner.class); + assertThat(runner.globalProperties().get("foo")).isEqualTo("bar"); } + } diff --git a/sonar-runner-dist/src/test/java/org/sonar/runner/ShutdownTest.java b/sonar-runner-cli/src/test/java/org/sonar/runner/cli/ShutdownTest.java index 9de7f4c..7e570b1 100644 --- a/sonar-runner-dist/src/test/java/org/sonar/runner/ShutdownTest.java +++ b/sonar-runner-cli/src/test/java/org/sonar/runner/cli/ShutdownTest.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - Distribution + * SonarQube Runner - CLI - Distribution * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * @@ -17,11 +17,13 @@ * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ -package org.sonar.runner; +package org.sonar.runner.cli; import static org.mockito.Mockito.verify; import static org.fest.assertions.Assertions.assertThat; import org.mockito.MockitoAnnotations; +import org.sonar.runner.cli.Exit; +import org.sonar.runner.cli.Shutdown; import org.mockito.Mock; import org.junit.Test; import org.junit.Before; diff --git a/sonar-runner-dist/src/test/java/org/sonar/runner/StatsTest.java b/sonar-runner-cli/src/test/java/org/sonar/runner/cli/StatsTest.java index edf61ba..6093b41 100644 --- a/sonar-runner-dist/src/test/java/org/sonar/runner/StatsTest.java +++ b/sonar-runner-cli/src/test/java/org/sonar/runner/cli/StatsTest.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - Distribution + * SonarQube Runner - CLI - Distribution * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * @@ -17,38 +17,37 @@ * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ -package org.sonar.runner; - -import org.sonar.home.log.LogListener; - -import org.sonar.runner.impl.Logs; +package org.sonar.runner.cli; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; import java.io.UnsupportedEncodingException; - import org.junit.Test; -import static org.fest.assertions.Assertions.assertThat; +import static org.fest.assertions.Assertions.assertThat; public class StatsTest { @Test public void shouldPrintStats() throws UnsupportedEncodingException { - final StringBuffer sb = new StringBuffer(); - Logs.setListener(new LogListener() { - @Override - public void log(String msg, Level level) { - sb.append(msg + System.lineSeparator()); - } - }); - new Stats().start().stop(); - - String out = sb.toString(); - String[] lines = out.split(System.lineSeparator()); - - assertThat(lines).hasSize(2); - - assertThat(lines[0]).contains("Total time: "); - assertThat(lines[1]).contains("Final Memory: "); + + PrintStream backupOut = System.out; + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try { + System.setOut(new PrintStream(baos)); + + new Stats().start().stop(); + + String out = baos.toString(); + String[] lines = out.split(System.lineSeparator()); + + assertThat(lines).hasSize(2); + + assertThat(lines[0]).contains("Total time: "); + assertThat(lines[1]).contains("Final Memory: "); + } finally { + System.setOut(backupOut); + } } @Test diff --git a/sonar-runner-dist/src/test/java/org/sonar/runner/SystemInfoTest.java b/sonar-runner-cli/src/test/java/org/sonar/runner/cli/SystemInfoTest.java index ced4e1e..edeffff 100644 --- a/sonar-runner-dist/src/test/java/org/sonar/runner/SystemInfoTest.java +++ b/sonar-runner-cli/src/test/java/org/sonar/runner/cli/SystemInfoTest.java @@ -1,5 +1,5 @@ /* - * SonarQube Runner - Distribution + * SonarQube Runner - CLI - Distribution * Copyright (C) 2011 SonarSource * dev@sonar.codehaus.org * @@ -17,9 +17,10 @@ * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ -package org.sonar.runner; +package org.sonar.runner.cli; import org.junit.Test; +import org.sonar.runner.cli.SystemInfo; import static org.fest.assertions.Assertions.assertThat; diff --git a/sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldLoadCompleteConfiguration/project/sonar-project.properties b/sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldLoadCompleteConfiguration/project/sonar-project.properties index 0d1e025..0d1e025 100644 --- a/sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldLoadCompleteConfiguration/project/sonar-project.properties +++ b/sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldLoadCompleteConfiguration/project/sonar-project.properties diff --git a/sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldLoadCompleteConfiguration/runner/conf/sonar-runner.properties b/sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldLoadCompleteConfiguration/runner/conf/sonar-runner.properties index 7edfb99..7edfb99 100644 --- a/sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldLoadCompleteConfiguration/runner/conf/sonar-runner.properties +++ b/sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldLoadCompleteConfiguration/runner/conf/sonar-runner.properties diff --git a/sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfiguration/project/module1/sonar-project.properties b/sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfiguration/project/module1/sonar-project.properties index 6803263..6803263 100644 --- a/sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfiguration/project/module1/sonar-project.properties +++ b/sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfiguration/project/module1/sonar-project.properties diff --git a/sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfiguration/project/module2/sonar-project.properties b/sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfiguration/project/module2/sonar-project.properties index c12fad8..c12fad8 100644 --- a/sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfiguration/project/module2/sonar-project.properties +++ b/sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfiguration/project/module2/sonar-project.properties diff --git a/sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfiguration/project/sonar-project.properties b/sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfiguration/project/sonar-project.properties index 835124c..835124c 100644 --- a/sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfiguration/project/sonar-project.properties +++ b/sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfiguration/project/sonar-project.properties diff --git a/sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfigurationOverrideBasedir/project/module2.properties b/sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfigurationOverrideBasedir/project/module2.properties index 4df820c..4df820c 100644 --- a/sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfigurationOverrideBasedir/project/module2.properties +++ b/sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfigurationOverrideBasedir/project/module2.properties diff --git a/sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfigurationOverrideBasedir/project/module_1/sonar-project.properties b/sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfigurationOverrideBasedir/project/module_1/sonar-project.properties index 6803263..6803263 100644 --- a/sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfigurationOverrideBasedir/project/module_1/sonar-project.properties +++ b/sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfigurationOverrideBasedir/project/module_1/sonar-project.properties diff --git a/sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfigurationOverrideBasedir/project/module_2/Sample.js b/sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfigurationOverrideBasedir/project/module_2/Sample.js index e69de29..e69de29 100644 --- a/sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfigurationOverrideBasedir/project/module_2/Sample.js +++ b/sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfigurationOverrideBasedir/project/module_2/Sample.js diff --git a/sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfigurationOverrideBasedir/project/module_3/sonar-project.properties b/sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfigurationOverrideBasedir/project/module_3/sonar-project.properties index c074231..c074231 100644 --- a/sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfigurationOverrideBasedir/project/module_3/sonar-project.properties +++ b/sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfigurationOverrideBasedir/project/module_3/sonar-project.properties diff --git a/sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfigurationOverrideBasedir/project/sonar-project.properties b/sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfigurationOverrideBasedir/project/sonar-project.properties index 999b04c..999b04c 100644 --- a/sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfigurationOverrideBasedir/project/sonar-project.properties +++ b/sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldLoadModuleConfigurationOverrideBasedir/project/sonar-project.properties diff --git a/sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldLoadRunnerSettingsByDirectPath/other-conf.properties b/sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldLoadRunnerSettingsByDirectPath/other-conf.properties index 33dc79b..33dc79b 100644 --- a/sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldLoadRunnerSettingsByDirectPath/other-conf.properties +++ b/sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldLoadRunnerSettingsByDirectPath/other-conf.properties diff --git a/sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldLoadRunnerSettingsByHome/conf/sonar-runner.properties b/sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldLoadRunnerSettingsByHome/conf/sonar-runner.properties index 1e03622..1e03622 100644 --- a/sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldLoadRunnerSettingsByHome/conf/sonar-runner.properties +++ b/sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldLoadRunnerSettingsByHome/conf/sonar-runner.properties diff --git a/sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldSupportDeepModuleConfigurationInRoot/project/module1/module11/module111/placeholder.txt b/sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldSupportDeepModuleConfigurationInRoot/project/module1/module11/module111/placeholder.txt index e69de29..e69de29 100644 --- a/sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldSupportDeepModuleConfigurationInRoot/project/module1/module11/module111/placeholder.txt +++ b/sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldSupportDeepModuleConfigurationInRoot/project/module1/module11/module111/placeholder.txt diff --git a/sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldSupportDeepModuleConfigurationInRoot/project/module1/module11/module112/placeholder.txt b/sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldSupportDeepModuleConfigurationInRoot/project/module1/module11/module112/placeholder.txt index e69de29..e69de29 100644 --- a/sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldSupportDeepModuleConfigurationInRoot/project/module1/module11/module112/placeholder.txt +++ b/sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldSupportDeepModuleConfigurationInRoot/project/module1/module11/module112/placeholder.txt diff --git a/sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldSupportDeepModuleConfigurationInRoot/project/module1/module12/placeholder.txt b/sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldSupportDeepModuleConfigurationInRoot/project/module1/module12/placeholder.txt index e69de29..e69de29 100644 --- a/sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldSupportDeepModuleConfigurationInRoot/project/module1/module12/placeholder.txt +++ b/sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldSupportDeepModuleConfigurationInRoot/project/module1/module12/placeholder.txt diff --git a/sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldSupportDeepModuleConfigurationInRoot/project/module2/module21/placeholder.txt b/sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldSupportDeepModuleConfigurationInRoot/project/module2/module21/placeholder.txt index e69de29..e69de29 100644 --- a/sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldSupportDeepModuleConfigurationInRoot/project/module2/module21/placeholder.txt +++ b/sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldSupportDeepModuleConfigurationInRoot/project/module2/module21/placeholder.txt diff --git a/sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldSupportDeepModuleConfigurationInRoot/project/module2/module22/placeholder.txt b/sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldSupportDeepModuleConfigurationInRoot/project/module2/module22/placeholder.txt index e69de29..e69de29 100644 --- a/sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldSupportDeepModuleConfigurationInRoot/project/module2/module22/placeholder.txt +++ b/sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldSupportDeepModuleConfigurationInRoot/project/module2/module22/placeholder.txt diff --git a/sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldSupportDeepModuleConfigurationInRoot/project/sonar-project.properties b/sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldSupportDeepModuleConfigurationInRoot/project/sonar-project.properties index 56eb032..56eb032 100644 --- a/sonar-runner-dist/src/test/resources/org/sonar/runner/ConfTest/shouldSupportDeepModuleConfigurationInRoot/project/sonar-project.properties +++ b/sonar-runner-cli/src/test/resources/org/sonar/runner/ConfTest/shouldSupportDeepModuleConfigurationInRoot/project/sonar-project.properties diff --git a/sonar-runner-dist/src/test/resources/org/sonar/runner/RunnerTest/shouldInitDirs/fake.txt b/sonar-runner-cli/src/test/resources/org/sonar/runner/RunnerTest/shouldInitDirs/fake.txt index f0f877c..f0f877c 100644 --- a/sonar-runner-dist/src/test/resources/org/sonar/runner/RunnerTest/shouldInitDirs/fake.txt +++ b/sonar-runner-cli/src/test/resources/org/sonar/runner/RunnerTest/shouldInitDirs/fake.txt diff --git a/sonar-runner-dist/src/test/java/org/sonar/runner/RunnerFactoryTest.java b/sonar-runner-dist/src/test/java/org/sonar/runner/RunnerFactoryTest.java deleted file mode 100644 index 4ecd89f..0000000 --- a/sonar-runner-dist/src/test/java/org/sonar/runner/RunnerFactoryTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * SonarQube Runner - Distribution - * Copyright (C) 2011 SonarSource - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.runner; - -import org.junit.Test; -import org.sonar.runner.api.EmbeddedRunner; -import org.sonar.runner.api.ForkedRunner; -import org.sonar.runner.api.Runner; - -import java.util.Properties; - -import static org.fest.assertions.Assertions.assertThat; - -public class RunnerFactoryTest { - - Properties props = new Properties(); - - @Test - public void should_create_embedded_runner_by_default() { - props.setProperty("foo", "bar"); - Runner<?> runner = new RunnerFactory().create(props); - - assertThat(runner).isInstanceOf(EmbeddedRunner.class); - assertThat(runner.globalProperties().get("foo")).isEqualTo("bar"); - } - - @Test - public void should_create_forked_runner() { - props.setProperty("foo", "bar"); - props.setProperty("sonarRunner.mode", "fork"); - props.setProperty("sonarRunner.fork.jvmArgs", "-Xms128m -Xmx512m"); - Runner<?> runner = new RunnerFactory().create(props); - - assertThat(runner).isInstanceOf(ForkedRunner.class); - assertThat(runner.globalProperties().get("foo")).isEqualTo("bar"); - assertThat(((ForkedRunner) runner).jvmArguments()).contains("-Xms128m", "-Xmx512m"); - } - - @Test - public void should_create_forked_runner_with_jvm_arguments() { - props.setProperty("foo", "bar"); - props.setProperty("sonarRunner.mode", "fork"); - Runner<?> runner = new RunnerFactory().create(props); - - assertThat(runner).isInstanceOf(ForkedRunner.class); - assertThat(runner.globalProperties().get("foo")).isEqualTo("bar"); - - assertThat(runner).isInstanceOf(ForkedRunner.class); - assertThat(runner.globalProperties().get("foo")).isEqualTo("bar"); - assertThat(((ForkedRunner) runner).jvmArguments()).isEmpty(); - } -} diff --git a/sonar-runner-impl/pom.xml b/sonar-runner-impl/pom.xml deleted file mode 100644 index 56dcdb2..0000000 --- a/sonar-runner-impl/pom.xml +++ /dev/null @@ -1,140 +0,0 @@ -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> - <modelVersion>4.0.0</modelVersion> - <parent> - <groupId>org.codehaus.sonar.runner</groupId> - <artifactId>sonar-runner</artifactId> - <version>2.5-SNAPSHOT</version> - </parent> - - <artifactId>sonar-runner-impl</artifactId> - <name>SonarQube Runner - Implementation</name> - - <dependencies> - <dependency> - <groupId>com.github.kevinsawicki</groupId> - <artifactId>http-request</artifactId> - </dependency> - <dependency> - <groupId>com.google.code.findbugs</groupId> - <artifactId>jsr305</artifactId> - <scope>provided</scope> - </dependency> - <dependency> - <groupId>org.codehaus.sonar</groupId> - <artifactId>sonar-home</artifactId> - </dependency> - <dependency> - <groupId>commons-io</groupId> - <artifactId>commons-io</artifactId> - </dependency> - <dependency> - <groupId>${project.groupId}</groupId> - <artifactId>sonar-runner-batch</artifactId> - <version>${project.version}</version> - <scope>provided</scope> - </dependency> - <dependency> - <groupId>${project.groupId}</groupId> - <artifactId>sonar-runner-batch-interface</artifactId> - <version>${project.version}</version> - </dependency> - - <!-- unit tests --> - <dependency> - <groupId>junit</groupId> - <artifactId>junit</artifactId> - <scope>test</scope> - </dependency> - <dependency> - <groupId>org.easytesting</groupId> - <artifactId>fest-assert</artifactId> - <scope>test</scope> - </dependency> - <dependency> - <groupId>org.mockito</groupId> - <artifactId>mockito-all</artifactId> - <scope>test</scope> - </dependency> - <dependency> - <groupId>org.assertj</groupId> - <artifactId>assertj-core</artifactId> - <version>1.7.1</version> - <scope>test</scope> - </dependency> - <dependency> - <groupId>org.mortbay.jetty</groupId> - <artifactId>jetty</artifactId> - <version>6.1.25</version> - <scope>test</scope> - </dependency> - </dependencies> - - <build> - <plugins> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-dependency-plugin</artifactId> - <executions> - <execution> - <id>copy</id> - <phase>process-resources</phase> - <goals> - <goal>copy</goal> - </goals> - <configuration> - <artifactItems> - <artifactItem> - <groupId>${project.groupId}</groupId> - <artifactId>sonar-runner-batch</artifactId> - <version>${project.version}</version> - <type>jar</type> - <overWrite>false</overWrite> - <outputDirectory>${project.build.outputDirectory}</outputDirectory> - <destFileName>sonar-runner-batch.jar</destFileName> - </artifactItem> - </artifactItems> - <overWriteReleases>true</overWriteReleases> - <overWriteSnapshots>true</overWriteSnapshots> - </configuration> - </execution> - </executions> - </plugin> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-shade-plugin</artifactId> - <executions> - <execution> - <phase>package</phase> - <goals> - <goal>shade</goal> - </goals> - <configuration> - <createDependencyReducedPom>true</createDependencyReducedPom> - <minimizeJar>true</minimizeJar> - <relocations> - <relocation> - <pattern>com.github.kevinsawicki.http</pattern> - <shadedPattern>org.sonar.runner.kevinsawicki</shadedPattern> - </relocation> - <relocation> - <pattern>org.apache.commons.io</pattern> - <shadedPattern>org.sonar.runner.commonsio</shadedPattern> - </relocation> - <relocation> - <pattern>org.sonar.home</pattern> - <shadedPattern>org.sonar.runner.home</shadedPattern> - <!-- shared between sonar-runner-api, sonar-runner-impl and sonar-batch --> - <excludes> - <exclude>org.sonar.home.log.LogListener</exclude> - <exclude>org.sonar.home.log.LogListener$Level</exclude> - </excludes> - </relocation> - </relocations> - </configuration> - </execution> - </executions> - </plugin> - - </plugins> - </build> -</project> diff --git a/sonar-runner-impl/src/main/java/org/sonar/runner/impl/BatchLauncherMain.java b/sonar-runner-impl/src/main/java/org/sonar/runner/impl/BatchLauncherMain.java deleted file mode 100644 index 14a57b4..0000000 --- a/sonar-runner-impl/src/main/java/org/sonar/runner/impl/BatchLauncherMain.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * SonarQube Runner - Implementation - * Copyright (C) 2011 SonarSource - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.runner.impl; - -import org.sonar.runner.batch.IsolatedLauncher; - -import java.io.FileInputStream; -import java.io.IOException; -import java.util.Collections; -import java.util.Properties; - -public class BatchLauncherMain { - private final IsolatedLauncherFactory launcherFactory; - - BatchLauncherMain(IsolatedLauncherFactory factory) { - this.launcherFactory = factory; - } - - void execute(String[] args) throws IOException { - if (args.length == 0) { - throw new IllegalArgumentException("Missing path to properties file"); - } - Properties props = loadProperties(args[0]); - IsolatedLauncher launcher = launcherFactory.createLauncher(props); - launcher.start(props, Collections.emptyList()); - try { - launcher.execute(props); - } finally { - // try to still exit cleanly - launcher.stop(); - } - } - - private static Properties loadProperties(String arg) throws IOException { - Properties props = new Properties(); - try (FileInputStream input = new FileInputStream(arg)) { - props.load(input); - // just to be clean, do not forward properties that do not make sense in fork mode - props.remove(InternalProperties.RUNNER_MASK_RULES); - } - - return props; - } - - public static void main(String[] args) { - try { - new BatchLauncherMain(new IsolatedLauncherFactory()).execute(args); - } catch (Exception e) { - Logs.error(e.getMessage(), e); - // make sure non-daemon threads don't hang app - System.exit(1); - } - } -} diff --git a/sonar-runner-impl/src/main/java/org/sonar/runner/impl/Logs.java b/sonar-runner-impl/src/main/java/org/sonar/runner/impl/Logs.java deleted file mode 100644 index 7ef9c63..0000000 --- a/sonar-runner-impl/src/main/java/org/sonar/runner/impl/Logs.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * SonarQube Runner - Implementation - * Copyright (C) 2011 SonarSource - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.runner.impl; - -import org.sonar.home.log.LogListener.Level; -import org.sonar.home.log.LogListener; - -import javax.annotation.Nullable; - -import java.io.PrintStream; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.Collections; -import java.util.EnumMap; -import java.util.Map; - -public class Logs { - private static LogListener listener = new PrintStreamLogListener(getDefaultFwdMap()); - private static boolean debugEnabled = false; - - private Logs() { - } - - public static void setListener(@Nullable LogListener listener) { - if (listener == null) { - Logs.listener = new PrintStreamLogListener(getDefaultFwdMap()); - } else { - Logs.listener = listener; - } - } - - public static LogListener getListener() { - return Logs.listener; - } - - public static void setDebugEnabled(boolean debugEnabled) { - Logs.debugEnabled = debugEnabled; - } - - public static boolean isDebugEnabled() { - return debugEnabled; - } - - public static void debug(String message) { - if (isDebugEnabled()) { - log(message, Level.DEBUG); - } - } - - public static void info(String message) { - log(message, Level.INFO); - } - - public static void warn(String message) { - log(message, Level.WARN); - } - - public static void error(String message) { - log(message, Level.ERROR); - } - - public static void error(String message, Throwable t) { - log(message, Level.ERROR); - if (t != null) { - StringWriter sw = new StringWriter(); - - t.printStackTrace(new PrintWriter(sw)); - String[] lines = sw.toString().split(System.getProperty("line.separator")); - for (String l : lines) { - log(l, Level.ERROR); - } - } - } - - private static void log(String msg, Level level) { - listener.log(msg, level); - } - - /** - * This is recreated every time to be sure we use the current {@link System#err} and {@link System#out}. - */ - private static Map<Level, PrintStream> getDefaultFwdMap() { - Map<Level, PrintStream> map = new EnumMap<>(Level.class); - - map.put(Level.ERROR, System.err); - map.put(Level.WARN, System.out); - map.put(Level.INFO, System.out); - map.put(Level.DEBUG, System.out); - map.put(Level.TRACE, System.out); - return Collections.unmodifiableMap(map); - } - - private static class PrintStreamLogListener implements LogListener { - Map<Level, PrintStream> forwardMap; - - PrintStreamLogListener(Map<Level, PrintStream> forwardMap) { - this.forwardMap = new EnumMap<>(forwardMap); - } - - @Override - public void log(String msg, Level level) { - PrintStream ps = forwardMap.get(level); - if (ps != null) { - ps.append(level.toString() + ": " + msg + System.lineSeparator()); - } - } - } -} diff --git a/sonar-runner-impl/src/test/java/org/sonar/runner/impl/BatchLauncherMainTest.java b/sonar-runner-impl/src/test/java/org/sonar/runner/impl/BatchLauncherMainTest.java deleted file mode 100644 index 0f4a2fa..0000000 --- a/sonar-runner-impl/src/test/java/org/sonar/runner/impl/BatchLauncherMainTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * SonarQube Runner - Implementation - * Copyright (C) 2011 SonarSource - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.runner.impl; - -import org.sonar.runner.batch.IsolatedLauncher; - -import org.junit.Test; -import org.mockito.ArgumentMatcher; - -import java.io.File; -import java.net.URL; -import java.util.Properties; - -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.when; -import static org.fest.assertions.Fail.fail; -import static org.mockito.Matchers.argThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -public class BatchLauncherMainTest { - - IsolatedLauncherFactory launcherFactory = mock(IsolatedLauncherFactory.class); - - @Test - public void should_load_properties_and_execute() throws Exception { - URL url = getClass().getResource("/org/sonar/runner/impl/BatchLauncherMainTest/props.properties"); - when(launcherFactory.createLauncher(any(Properties.class))).thenReturn(mock(IsolatedLauncher.class)); - - BatchLauncherMain main = new BatchLauncherMain(launcherFactory); - new File(url.toURI()).getAbsolutePath(); - main.execute(new String[] {new File(url.toURI()).getAbsolutePath()}); - - verify(launcherFactory).createLauncher(argThat(new ArgumentMatcher<Properties>() { - @Override - public boolean matches(Object o) { - return ((Properties) o).get("sonar.login").equals("foo"); - } - })); - } - - @Test - public void should_fail_if_missing_path_to_properties_file() { - try { - BatchLauncherMain main = new BatchLauncherMain(launcherFactory); - main.execute(new String[0]); - fail(); - } catch (Exception e) { - // success - } - } - - @Test - public void should_fail_if_properties_file_does_not_exist() { - try { - BatchLauncherMain main = new BatchLauncherMain(launcherFactory); - main.execute(new String[] {"unknown/file.properties"}); - fail(); - } catch (Exception e) { - // success - } - - } -} diff --git a/sonar-runner-impl/src/test/java/org/sonar/runner/impl/LogsTest.java b/sonar-runner-impl/src/test/java/org/sonar/runner/impl/LogsTest.java deleted file mode 100644 index 467bb85..0000000 --- a/sonar-runner-impl/src/test/java/org/sonar/runner/impl/LogsTest.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * SonarQube Runner - Implementation - * Copyright (C) 2011 SonarSource - * dev@sonar.codehaus.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 - */ -package org.sonar.runner.impl; - -import org.sonar.home.log.LogListener; - -import org.junit.Test; - -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; -import java.io.UnsupportedEncodingException; -import java.nio.charset.StandardCharsets; - -import static org.assertj.core.api.Assertions.assertThat; -import org.junit.Before; - -public class LogsTest { - private static final String EXPECTED_DEBUG = "DEBUG: debug" + System.lineSeparator(); - private static final String EXPECTED_INFO = "INFO: info" + System.lineSeparator(); - private static final String EXPECTED_ERROR = "ERROR: error" + System.lineSeparator(); - - private ByteArrayOutputStream recordedSystemOut; - private ByteArrayOutputStream recordedSystemErr; - - @Before - public void restoreDefault() { - recordedSystemOut = new ByteArrayOutputStream(); - recordedSystemErr = new ByteArrayOutputStream(); - - System.setOut(new PrintStream(recordedSystemOut)); - System.setErr(new PrintStream(recordedSystemErr)); - - Logs.setDebugEnabled(false); - Logs.setListener(null); - } - - @Test - public void testNull() throws UnsupportedEncodingException { - Logs.setListener(null); - testDefault(); - } - - @Test - public void testDefault() throws UnsupportedEncodingException { - writeTest(); - - assertThat(recordedSystemOut.toString(StandardCharsets.UTF_8.name())).isEqualTo(EXPECTED_INFO); - assertThat(recordedSystemErr.toString(StandardCharsets.UTF_8.name())).isEqualTo(EXPECTED_ERROR); - } - - @Test - public void testDebug() throws UnsupportedEncodingException { - Logs.setDebugEnabled(true); - writeTest(); - - assertThat(recordedSystemOut.toString(StandardCharsets.UTF_8.name())).isEqualTo(EXPECTED_DEBUG + EXPECTED_INFO); - assertThat(recordedSystemErr.toString(StandardCharsets.UTF_8.name())).isEqualTo(EXPECTED_ERROR); - } - - @Test - public void testCustomListener() { - TestLogListener listener = new TestLogListener(); - - Logs.setListener(listener); - Logs.setDebugEnabled(true); - - Logs.debug("debug"); - - assertThat(listener.msg).isEqualTo("debug"); - assertThat(listener.level).isEqualTo(LogListener.Level.DEBUG); - } - - private class TestLogListener implements LogListener { - String msg; - Level level; - - @Override - public void log(String msg, Level level) { - this.msg = msg; - this.level = level; - } - } - - private static void writeTest() { - Logs.debug("debug"); - Logs.info("info"); - Logs.error("error"); - } -} |