Response
stringlengths
8
2k
Instruction
stringlengths
18
2k
Prompt
stringlengths
14
160
There is a known issue with PowerMockito and sonar code coverage calculation, and I did a big research on this - as of today, there is no fix to it. How I personally deal with it - try to avoid the usage of PowerMockito - so use static and final sparsely, which is generally a good advice to have more object oriented code anyway. However, there will still be a few cases were you will need to use static and or final. For these, compare my answer here:cobertura-showing-proper-coverage-but-in-sonar-many-files-showing-0-coverageShareFolloweditedJun 20, 2020 at 9:12CommunityBot111 silver badgeansweredApr 29, 2015 at 14:42Marcus BielMarcus Biel44044 silver badges1515 bronze badgesAdd a comment|
I'm using PowerMockito and @PrepareForTest annotation for my test class. When I do this, Sonar says none of the branches have been covered. However, my other test classes that don't use PowerMockito works well. For example:@RunWith(PowerMockRunner.class) @PrepareForTest({ MyClass.class }) public class MyClassTest { //create some mocks and run some tests here }Is there anyone encountered with the same problem?Thanks in advance.
PowerMockito disables Sonar branch coverage
There are three ways you can do this:Write directly to the database (there is a simple table called users).Use the LDAP plugin, if you specifysonar.authenticator.createUsers: truein sonar.properties, it will create the users in the sonar database automatically the first time they authenticate.Write a java application that depends on the sonar plugin API, you can then use constructor injection to get a Sonar hibernate session and persist the user you want. SeeHere.ShareFollowansweredSep 2, 2010 at 22:58shipmastershipmaster3,99444 gold badges3030 silver badges3333 bronze badges2If it were me I would definitely go with the LDAP plugin.–Zac ThompsonSep 5, 2010 at 18:06The webservice API apparently didn't exist when this was originally asked, but should be the preferred way to do this now.–PolyTekPatrickNov 5, 2016 at 2:48Add a comment|
Is it possible to create a new user in sonar without using the web interface? I need to write a script that inserts the same users for some tools, including sonar.
Create new user in sonar
There is a separate SAST tool released by OWASP team named "OWASP SonarQube". This is developed using the sonarqube tool, but as a SAST tool.This tool can be integrated with your project build same as the SonarQube integration. So if you are familiar with SonarQube, it will be a straightforward move.ShareFollowansweredOct 8, 2019 at 9:51lkamallkamal3,83811 gold badge2222 silver badges3636 bronze badges2The associated github repo has been archived and is read-only. It looks to me like the OWASP SonarQube project has been retired.community.sonarsource.com/t/owasp-sonarqube-project/36920/2–Paul GFeb 1, 2021 at 21:182@PaulG - however, the sonarqube product still supports security tests as a SAST tool as per the websitesonarqube.org/features/security–lkamalFeb 2, 2021 at 10:32Add a comment|
I'm looking for a Static Application Security Testing (SAST) tool and I can't afford the commercial products (eg. Checkmarx).SonarQube is a great static code analysis tool but I notice that there is only a few rules of the "Vulnerabilities" type ("Vulnerabilities" equals "Security", am I right?).I plan to extend some custom plugins including a lot of vulnerabilities rules (maybe hundreds of rules for C/C++, Java, and other languages that SonarQube supports).Is that a practicable way to make SonarQube a "Checkmarx like" tool? Or is SonarQube suitable for static security testing? (I'm not sure if Sonar Scanner is suitable for scanning security problems)Thanks a lot!
Can SonarQube be used as a Static Application Security Testing (SAST) tool?
You can define a method as below, to do the job and then call the method whenever you need according to your need or on some event like git branch merged/removed, etc.def deleteSonarProject() { def sonarToken = "-your admin credential token generate it from sonarServer-" def url = "http://yourBaseURL:portNumber/api/projects/delete" sh "curl -u ${sonarToken}: ${url} -d 'project=projectKey'" }ShareFollowansweredJul 4, 2019 at 8:15GentleGentle53911 gold badge66 silver badges1313 bronze badges3interesting. I should launch this script when the branch has been deleted o merged. I will review that solution. Thanks a lot.–F.RosadoJul 23, 2019 at 13:301Did it help you?–GentleAug 7, 2019 at 6:22Yes, that is the best option i has found. Thanks–F.RosadoAug 14, 2019 at 15:45Add a comment|
We currently have a jenkins pipeline usingMultibranch Workflow plugin. Each git branch execute a sonarqube analysis creating a sonarqube project using thesonar.branchproperty. This is very useful because each branch is being analyzed before merge it, the problem appear when a branch is merged with master and disappear on GIT, the project continues on sonarqube and need to be deleted manually. Is There a way to do it automatically? or any other recomendation?
Automatically remove Sonarqube branch projects when git branch merged / removed
Probably the compiled code you trying to run was compiled using java 11, but in env installed only java 8.Try to installjava 11and make sure to update OS environment settings to point to the new JDK.Java Details:Java 8 uses major version 52Java 11 uses major version 55ShareFollowansweredJul 8, 2021 at 6:52Adir DayanAdir Dayan1,4381515 silver badges2323 bronze badgesAdd a comment|
How to avoid issue with sonar scanner plugin on Jenkins 2.289.2, plugin sonar 2.13.1 when compiling a project I got the error[ERROR] Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.0.2155:sonar (default-cli) on project maven-project: Execution default-cli of goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.0.2155:sonar failed: An API incompatibility was encountered while executing org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.0.2155:sonar: java.lang.UnsupportedClassVersionError: org/sonar/batch/bootstrapper/EnvironmentInformation has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0It looks like an issue with the version of java but I would like to avoid changing my java version
How to fix sonar plugin issue in jenkins
I have created the following ticket on the SonarQube .NET side to allow multiple coverage reports to be specified, and to aggregate them:http://jira.codehaus.org/browse/SONARPLUGINS-3666.In the meantime though, I cannot think of other options besides the 2 you already had.
I'm using OpenCover to generate functional test coverage for a web application. These tests are fairly long running (3+ hours), so we've chopped them up into multiple tests that run in parallel. So instead of a single coverage report, there are six.In order to import these coverage reports into SonarQube, I need to figure out a way to combine them into one uber report. ReportGenerator supports merging multiple reports into one, but creates HTML output, which is not something SonarQube can consume.At this point my options arehand-roll an OpenCover report merger (blech!)Run my functional tests serially, substantially increasing failure feedback timesAny other options I'm missing?
OpenCover: possible to merge multiple reports into one?
You're not able to deactivate that issue because none of the mechanisms you're trying to use have been implemented for Kotlin.Instead, you'll have to do this from the UI side.
I'm using SQ 7.3-alpha1 with sonar-kotlin-plugin-1.0.1.965.jar. However, I cannot deactivate a special warning inside my Kotlin code for repositories in Spring Data where I need an "_" in a method name. I tried both//NOSONARand@Suppress("kotlin:S100")and@SuppressWarnings("kotlin:S100"). Any hint is appreciated.
SonarQube: How to suppress a warning in Kotlin code
+50You should useBranch Pluginin order to analyse branches for only new issues. This plugin has a corresponding Quality Gate:For short-lived branches, there is a kind of hard-coded quality gate focusing only on new issues.It will create Issues only if there are new bugs or vulnerabilities.As per the plugin documentation all your feature branches should be identified asshort-lived branches.NOTE:Branch Plugin is licensed underSonarSourceand is available in nonfreeDeveloper Edition
I am currently introducing SonarQube into a large legacy project. This means that there are already hundreds of warnings, in the first step I would like to ensure that there areno new warningscoming from our feature branches.To achieve this, I want to have the Sonar analysis run on every feature branch, compare it to the main branch and alert the committer in case new warnings have been introduced.Assume the following situation:MyProject 1.0-SNAPSHOTis the name and version of the project on SonarQube. It has 100 warnings. It represents thedevelopbranch. Theleak periodis the analysis from 1 day ago. This works very well, I can see whichnew warningshave been introduced since yesterday.Developers are working onfeature/somefeaturebranches. When they open a pull request, I want a Sonar analysis to run on that branch. This works fine, but I can't set theleak versiontoMyProject 1.0-SNAPSHOTfrom yesterday, because this branch is seenas a completely separate projectby SonarQube, even though I set thesonar.projectKeyto the same name and I have also tried playing around with thesonar.branchproperty.The desired outcome is:develop -> 100 warningsfeature/somefeature -> 102 warningsOn the SonarQube dashboard offeature/somefaturedisplay "2 new warnings".Can it be done with sonar itself, or do I need to write my own program using the Sonar REST API?
SonarQube Leak Period between Branches or Projects
As described onhttps://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner, you have to follow these steps:Download the executable for your platformExtract it somewhereAdd thesonar-scannerexecutable (that was expanded in<install_directory>/binfolderAlternatively, because you are developing a JS project, you can also use theSonarQube Scanner for JSthanks to which you won't have to bother with the standard SonarQube Scanner and its properties file. For example, you can write the following script and add it to yourpackage.jsonfile:let sonarqubeScanner = require('sonarqube-scanner'); sonarqubeScanner({ serverUrl : "https://localhost:9000", token : "019d1e2e04eefdcd0caee1468f39a45e69d33d3f", options : {} }, callback);
I have installed sonarqube inside a virtual machine in my system.And is able to access it from anywhere inside my local network.I am trying to analyse the java-script files of my react-native project which is inside the app folder as shown in the above screenshot.so i set up a sonar-project.properties file inside the base directory of react-native project(as shown in the above screenshot) according to the sonarqube official doc in the below linkhttps://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scannerand from the base directory i am trying push the file using sonar-scanner command (i am doing this from outside the virtual machine from my system os).and it shows sonar-scanner command not found(as in the blow screenshot).How does this sonar-scanner command work ?,when accessing sonarserver from outside the virtualmachine do need something extra in my system os other than sonar-project.properties file in my projects root directory ? ,do i need to install something in my system os to use the command sonar-scanner.And what does the below property do// To import the LCOV reportsonar.javascript.lcov.reportPath=report/lcov.datAnd how do i properly configure it for my project ?
Analysing a React Native Project Using SonarQube?
I'm in version 4.0.1.I had the same error, found your question without answer and finally I found and tried this in settings.gradle and now it works.pluginManagement { repositories { gradlePluginPortal() } }
I am trying to get a simple Gradle project (the one that is created by eclipse automatically) with static code analysis made by Sonar to run on our continuous integration. Our CI server is behind a proxy and i have to access the Gradle plugin repository over an internal Nexus server.As described in theuserguidei have added the following to my settings.gradlepluginRepositories { maven { url 'http://link.to.my.nexus' } gradlePluginPortal() } rootProject.name = 'GradleTestProject'my build.gradle looks like this:plugins { id "org.sonarqube" version "2.0.1" } apply plugin: 'java' repositories { mavenLocal() mavenCentral() } dependencies { compile 'org.slf4j:slf4j-api:1.7.21' testCompile 'junit:junit:4.12' }When i run this on Jenkins, i get the following error message:FAILURE: Build failed with an exception. * Where: Settings file '/opt/hudson/jobs/GradleTestProject/workspace/settings.gradle' line: 1 * What went wrong: A problem occurred evaluating settings 'workspace'. > Could not find method pluginRepositories() for arguments [settings_20tc2o9xuj82hi1fvpe4wvcvt$_run_closure1@52b56c40] on settings 'workspace'.I have looked at other examples in the web. They all do it the same way as i described.BTW: I am using Gradle 2.12
Gradle Configuration of pluginRepository
You can have a look at our "Metric Definitions" Wiki page (and more specifically on the"Complexity" section) to know more about the meaning of metrics found in Sonar."Complexity" is the total complexity of a resource (for a file => sum of the complexities of every class defined in the file)"Complexity / method" is the "Complexity" divided by the number of methods found in the file... and so on for the other metrics.
In Sonar, for a particular Java class, I see :Complexity: 830 Complexity /method: 8,1How could you explain the difference between those two metrics ?Is "Complexity" the class complexity ?What is the maximum complexity a class should be under ? I know methods should be less than 10 for method complexity, but what is the maximum class complexity number a class should conform to be considered not complex ?Thanks.EDITI also look at Cyclomatic-Complexity rule violations in the file.For a number of methods, sonar says with different complexity numbers (in french) :"La complexité cyclomatique de la classe est de 28 alors que le maximum autorisé est de 10."in english :"The class cyclomatic complexity is 28 but the maximum allowed is 10".I don't understand why it says "class cyclomatic complexity" as it seems as a "method cyclomatic complexity".Also, the class in question does not appears on top of the most complex class sorted by average complexity/method, as sonar says it has only 8,1 average method complexity.
Difference between "complexity" metric and "complexity / method" metric
At this link someone says that Sonar 6.0 corrects this issue:https://groups.google.com/forum/#!topic/sonarqube/iXxKGIYRZ1g.I have just realised Sonar v6.0 is out, the problem is gone after I tested with the new version. Thank you Michael for your time.It seems like it is a bug on previous versions of Sonar. It's well known that all exception classes in Java are named by convention ending with "Exception" and that they can have multiple levels so your code seems to be correct as soon as your upper level exception is extending theExceptionclass.
I have created custom base exception that extendsExceptionclass. Later on I'm extendingMyBaseExceptionclass by another - this time specyfic exception class. And I now have problem with one of SonarQube - to be specyfic with "Classes named like "Exception" should extend "Exception" or a subclass" rule. Class declarations looks like that:import org.apache.log4j.Logger; import org.springframework.http.HttpStatus; public class MyBaseException extends Exception { public MyBaseException(int code, String message) { super(message); this.code = code; LOGGER.error("Exception with HttpStatus code: " + code + " Msg: " + message); } public MyBaseException(HttpStatus code, String message) { this(code.value(), message); } public int getCode() { return code; } } import org.springframework.http.HttpStatus; public class SpecException extends MyBaseException { public SpecException (HttpStatus code, String message) { super(code, message); } public SpecException (int code, String message) { super(code, message); } }Problem is only with thisSpecException. SonarQube don't see any issues with first inheritance. Hint given by SonarQube is: "Rename this class to remove "Exception" or correct its inheritance." but I think inheritance is correct since I'm inheriting by subclass ofException.
Custom exception wrong inheritance
+25Yes you can,Sonaris a code analysis tool and has plugins that can even estimate technical debt in man hours or dollars. Really easy to setup and run, you just download it, extract it and start (comes with an internal DB, so no extra dependencies of configurations required). Then if you use maven, you add this to your pom.xml:<plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>sonar-maven-plugin</artifactId> <version>2.0</version> </plugin>and run:maven sonar:sonarSonar will then show you all sorts of useful info about your code, include technical debt.------ Update 1 ------If you have multiple projects (assuming they are maven), you can make them all children of one parent project and runmvn sonar:sonaron the parent, it will analyze all the children for you.Here is an example of multiple projects.
I have a large number of individual, unrelated Java programs in a "Programs" folder, and I'd really like to be able to calculate a technical debt score automatically for each individual program. I understand that SonarQube can allow you to do this (kind of) withSonar-Runner, however I would really like a way to do this dynamically, so I can have a script analyze and write technical debt scores of all the programs within the "Programs" folder into a csv.I am perfectly willing and happy to try any other sort of technical debt software (or quality for that matter) if it can do this for me. I would just really appreciate any input, or thoughts about if this would even be possible?
Can I dynamically calculate technical debt?
I just had the same issue. I am using sonar-scanner and figured out that it needs to set Lombok jar file using command line argument.For example:sonar-scanner -D sonar.java.libraries=/home/gitlab-runner/.gradle/caches/modules-2/files-2.1/org.projectlombok/lombok/1.18.10/625fc0055674dff70dbc76efa36d0f2c89b04a24/lombok-1.18.10.jarNow SonarQube does not show any issues related with Lombok annotations.
I am getting a lot code smells from lombok generated code in Sonar. F.E.:Method Dto.hashCode() stores return result in local before immediately returning itDto.equals(Object) is excessively complex, with a cyclomatic complexity of 58How can I point out sonar that this should be skipped from analyze?UPDATEI've tried it already. Mylombok.configfile in root directory is:config.stopBubbling = true lombok.addLombokGeneratedAnnotation = true lombok.equalsAndHashCode.callSuper = callIt doesn't helpsI've tried it already:sonarqube + lombok = false positivesI've updated:sonar-project.propertiesin root directory to:sonar.sources=src/main sonar.tests=src/test sonar.language=java sonar.java.binaries=build/classes sonar.junit.reportPaths=build/test-results/test/ sonar.jacoco.reportPaths=build/jacoco/jacocoTest.exec sonar.java.libraries=.gradle/caches/**/lombok-*.jarIt doesn't work either.Please don't close it. It is not duplication.
Sonar + Lombok false positives on @Data annotation
What I had done in my situation.Installed SonarQube 4.4.Installed IntelliJ 13.1.4b (the same history was with 13.0.4).Configured SonarQube intelliJ plugin (not community provided one butplugin from SonarSource). All instructions are under the link on Wiki.Attached to Sonar project. Every step just as SonarSource recommends.This gave me mapping from Sonar onto source code. But it does not update when I simply fix the issue. But if I fix issues I then re-post project onto Sonar throughmvn sonar:sonarand this gives me updated picture next time I run inspection through sonarqube plugin.But this is not 100% what is wanted. But definitely better than nothing. Also I have imported Sonar rules throughQAPlug- this is far less useful. But notable faster.Overall this configuration allows me to make what is needed but I'd like to receive real incremental processing without publishing local changes onto Sonar server.
I’d like to ask for help. I installed thepluginand successfully added the SonarQube server. I upgraded to version 4.1.2. I use IntelliJ IDEA 13.0.2. I also successfully associated the project and inspection warnings appeared. But when I fix the issue the status is not updated.How to synchronize ?I also run inspection by name ‘SonarQube issues’. Nevertheless after running the inspection the warnings are also there, where the code was fixed. It seems to me the synchronization somehow fails. Any idea, what todo, please?
New Sonar IntelliJ plugin incremental analysis and detection not working
Check this out:This repository contains a SonarQube plugin implementing C++ support.https://github.com/SonarOpenCommunity/sonar-cxx
I'd like to use SonarQube to analyse C code for an open source project and integrate it into Jenkins. Unfortunately the commercial C/C++ plugin is at EUR 7.000, which rules it out for a free software. I also saw thecommunity C++ plugin. Does this also work well for C code? If not, how could I configure SonarQube with suitable open source tools to get a legal free C plugin?
C plugin for SonarQube
It is there a bit hidden under Project Information, Description it is possible to add the tags there... I was a bit lost for this myself... SQ is not great in terms of UI. You can type your tags and they will be possible to filter them.
Is there a way to set project tags similar to project key (sonar.projectKey) in the sonar-qube.properties for tags to be automatically added during project creation?I was looking through the docs:https://docs.sonarqube.org/display/SONAR/Analysis+Parametershttps://docs.sonarqube.org/display/SONAR/Project+Settingsand wasn't able to find info
Sonarqube project tagging via properties
each module need its own tests. Jacoco build each jacoco.exec module after module and cannot go back to a previous one. So you have to set a TestFoo in moduleA.
I have a multi-module project with Gradle(2.2) + JaCoCo + Sonar. I'm using thesonar-runnerplugin, and when I execute the tests, I can see in each module the test report underbuild/jacoco/jacoco.exec. So far so good.The problem is, I have some tests in module A that are testing classes from other module B, and so that JaCoCo is identifying that classes from module B with 0% code-coverage. I know this is not a good practice but it has to be done like that.Example of the structure:moduleA src java Foo test moduleB src java test TestFooThen JaCoCo will show the classFoowith 0% coverage. I have tried merging the results from all modules but I get the same result but in one single file, so this is not what I'm looking for. Is there any option to include sources from other module when executing the JaCoCo report?Thanks.
JaCoCo configuration when sources and tests classes are in different modules
You cannot pass env variable into sonar-project.property file.If you are creating sonar-project.property file from jenkins, you can use build with param.(or)Create a sonar-project.properties without sonar.source.Create build with param variable {path}, get the src path from user for each build,Map the variable with sonar.source=${path} in sh.Append sonar.source to sonar-project.properties for each build in sh using (>>) or cmd from jenkins.eg) sonar.source="path" >> sonar-project.propertiesfinally work space contains sonar-project.properties file with src path.
I am executing sonar through Jenkins build, there is use-case where 'src' location changes depending upon build so i want to use environment variable for specifying 'src' path.For example in sonar-project.properties i want to specify as shown below:src= c:/project/workspaceinstead i want to usesrc =${SONAR_RUN_WORKSPACE}
Is it possible to use environment variable in sonar-project.properties file
UPDATE: Perhttps://docs.sonarqube.org/latest/analysis/scan/sonarscanner-for-jenkins/the desired functionality is now available.What a nice way to waste an evening...According tothisSonar Runner is not meant for Maven projects. It turns out you're supposed to look under "Post-Build Actions" (not "Post-Build Steps") and you will find "Sonar". Seeherefor more information.
I am attempting to get Jenkins to run Sonar as a post-build step.Jenkins runs SonarRunner [1] but this fails with:ERROR: Error during Sonar runner execution ERROR: Unable to execute Sonar ERROR: Caused by: You must define the following mandatory properties for 'Unknown': sonar.projectKey, sonar.projectName, sonar.projectVersion, sonar.sourcesIf I runmvn sonar:sonar[2] instead it works fine. It almost sounds like SonarRunner is ignoring pom.xml.How do I get SonarRunner to pick up these properties from Maven?[1]/Users/builds/.jenkins/tools/hudson.plugins.sonar.SonarRunnerInstallation/Default_Sonar_Runner/bin/sonar-runner -Dsonar.jdbc.url=jdbc:h2:tcp://myServer:1009/sonar -Dsonar.host.url=http://myServer/sonar/ -Dsonar.projectBaseDir=/Users/builds/.jenkins/workspace/myProject[2]mvn sonar:sonar -Dsonar.jdbc.url=jdbc:h2:tcp://myServer:1009/sonar -Dsonar.host.url=http://myServer/sonar/ -Dsonar.projectBaseDir=/Users/builds/.jenkins/workspace/myProject
SonarRunner can't find sonar.projectKey, sonar.projectName, sonar.projectVersion, sonar.sources
I had the same issue with my Liferay project in Eclipse (liferay-plugins-sdk.6.2.0) and here is how I got it working:Install the eclipse plugin, and test server connectionInstall the Sonar server and start it (for example onyourhost:9000)Go toyourhost:9000and login (admin/admin unless you changed it)Go to Settings -> System -> ProvisioningCreate new project (+Createin the top right corner)I've used key=Liferay6.2 and name=liferay-plugins-sdk-6.2.0After the above steps I went back to my eclipse project and inConfigure > Associate with SonarI was able to search/find the liferay project.
I have Eclipse Indigo 3.7 base with MyEclipse 10 Java enterprise development plug-in:I have installed Sonar plug-in for eclipse.Installed Sonar server and running it locally from localhost (localhost:9000)Tested the Server connection in Eclipse fromWindows>Preferences>Sonar>Servers. Connection is successful.For my Project, ran the Maven goal for sonar (sonar:sonar). Build is successful. I am able to browse the results in localhost. (localhost:9000)My issue is with Associating the project to Sonar. When i right click on my project, Configure > Associate with Sonar, I get a screen where nothing happens.Basically the screen has 2 fields,Project and Sonar Project. The Project field contains the name of my Project and Sonar Project field lists this message - "click here to start searching for a remote Sonar project"I click on that field and enter my groupid:artifactid but nothing happens.I also tried entering the Project Name listed in Sonar dashboard but that also does not help.When i right click on my project, In the context menu i am unable to see 'Sonar' option.Help me associate my project to Sonar in eclipse. Please let me know what i am missing. Thanks in advance.
Associating a Project to Sonar in Eclipse
The property issonar.qualitygate.It was not documented because this is generally not a good idea to change the quality gate that should be used during a standard analysis - but it's true that it can be useful with the build breaker onpreviewanalyses.I updated the documentation.
I am using Jenkins to kick off Sonar-runner for analyzing projects.Now I use theBuild Breakerplugin. This breaks a build when a quality gate is reporting that the quality is below/above given values.I'd like to change the quality gate used by the Sonar-Runner, on a per-job basis in Jenkins. Looking up atAnalysis Parametersdocumentation:**sonar.profile** parameter is to change the language to analyseI would thought that for the gate:sonar.gatewould work (it doesn't)Question:What parameter for sonar-runner has to be used to change the "Quality Gate"?Used versions:Jenkins 1.598Sonar 4.5.1 (LTS)
Change: Quality Gate from Jenkins (sonar-runner)
You can't have multiple profiles for the same project. But if you want this, you just have to create your own custom profile which has all the rules defined in your profiles. For Example, let's say you have quality profile "Android Lint" and "Sonar Way", and if you wan't to check your project against both these profiles, just do the following:Go to Quality Profiles tab in SonarQubeClick on Back Up on the Profiles you want. It will download an .xml file for each profile.Just go through the .xml file and figure out how it is written and then Create a new .xml file which contains the rules of both the profiles and give it a cool name.Go back to Quality Profiles tab in SonarQubeClick on Restore Profile and upload your .xml file.That's it.You now have your own custom quality profile with all the rules that you want.UPDATE:In the latest version of SonarQube (I am using 6.2), you can use the concept of "Inheritance" to combine multiple quality profiles. You can now set a parent quality profile for any profile. Using this you can chain multiple quality profiles.See:SonarQube: How to apply multiple quality profiles to one project?
Is there a way to have several profiles for one project in Sonar ?For example we have a Java EE project with : EJB and WebApp (JSP and Back Bean). We have 3 quality profiles: Java, Web and XML. To "execute" these 3 profiles on our project we run three sonar analysis and create 3 result projects in Sonar.We use views to regroupe these three projects, is there a way to have one project that use 3 profiles and not use views?We want to use views to group different projects and not on the same project.
Several quality profiles for one project
See the documentation in the General Settings > Exclusions page. The patternfile:**/generated-sources/**will do the job if you're not using a too old version of SonarQube.
The generated code is present in a separate target folder path like:target/generated-sources/fod1/fod2/*.javaI have been trying several option but in vain please help.<properties> <sonar.exclusions>**/generatedsources/fod1/fod2/**/*.java</sonar.exclusions> </properties>I have tried the option from one of the posts also**/*generated*
To exclude the generated code from sonar analysis on Quality violation
I usually get that message when the database isn't correctly set (either the local has an issue, in which case I try a fresh installation).Or the mysql database you can associate has an issue (wrong 'sonar.jdbc.username' or 'sonar.jdbc.password' insonar.propertiesfile.).Or the default port for the embedded database (jdbc:derby://localhost:1527/sonar;create=true) isn't available on your server/workstation.If you are using a Mysql database (not your case), you need to create it first:mysql [localhost] {root} ((none)) > CREATE DATABASE IF NOT EXISTS sonar CHARACTER SET utf8 COLLATE utf8_general_ci; Query OK, 1 row affected (0.01 sec) mysql [localhost] {root} ((none)) > grant all privileges on sonar.* to 'sonar'@'localhost' identified by 'sonar'; Query OK, 0 rows affected (0.00 sec) mysql [localhost] {root} ((none)) > flush privileges; Query OK, 0 rows affected (0.00 sec)Q4 2023,Purval Patelmentions inthe commentsto his blog post:"SonarQube installation Ubuntu"
Information about InstallationUsing embedded database DerbisProblem :I runbin/windows-x86-32/StartSonar.batand then clickhttp://localhost:9000On clicking this, I get the following error:We're sorry, but something went wrong. Please try back in a few minutes and contact support if the problem persists. <%= link_to "Go back to the homepage", home_path %>Do you know what to do with that error message.
Sonar Installation problem
Smolderis a continuous integration framework that runs smoke tests and produces coverage reports, stats, and nice graphs. It acceptsTAPinput, so anything that can provide this can be plugged in. You can use the variousTAPmodules to provide integration on the Perl side.You can also adapt off-the-shelf build systems.Hudson,Cruise ControlandBuildBotcan all be configured for Perl projects, although feature support will vary (Hudson is a little Java-centric). You can plug them together in different ways. For example,TAP::Harness::JUnitproduces JUnit-like output, which can be fed to your tools.There's also theDevel::Covermodule which points out areas of untested code.Here's an interestingdiscussionof code coverage in Perl.
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a book, tool, software library, tutorial or other off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.Closed9 years ago.Improve this questionIs there something equivalent toSonarfor Perl ?
Is there something equivalent to Sonar for Perl? [closed]
Try to use wildcard :* Match zero or more characters ** Match zero or more directories ? Match a single characterLike this:sonar.sources=**/scriptUpdateAs of 2019, thesonar.sourcesparameter doesn't support such glob patterns. The common practice is to set this value to a list ofdirectoriesthat contain source code. The scanner will find traverse the directory trees and run applicable analyzers (JavaScript analyzers will consume.jsfiles, Python analyzers will consume.pyfiles, and so on.)
I am trying to use SonarQube to scan the UI modules I have. The UI modules are lot in number. They have a common structure. Each module has its own JS files.I need to specify thesonar.sourcesvalue to match all JS files in my project. Is it possible to do something like this?sonar.sources=\*/*/script sonar.language=jsI used these. But, I got an error saying something like"unable to resolve path". Can someone help?
How to specify wildcards in sonar-project.properties
I just had this problem as well. If you are running a newer version of Maven, you can exclude modules. This may or may not be a sufficient answer for you, but it was for me.When you run Sonar on project A, run it normally (no --projects switch). When you run Sonar on project B, supply an exclusion list (with the --projects switch).For Project A:mvn sonar:sonarthenmvn sonar:sonar --projects !moduleCThis method is mentioned briefly here:http://docs.sonarqube.org/display/SONAR/Analyzing+with+Maven#AnalyzingwithMaven-ExcludingamodulefromSonarQubeanalysis
I have two projects (A and B), which use the same reusable module (C). I upload A into sonarqube without problems, but when I upload B, the sonar-maven-plugin tells me that Module C is already part of project A. How can I fix it? I want both of my projects to be uploaded into sonarqube.
Sonar: "Module is already part of project" or How to upload projects with same dependencies?
The warning is because you did not give the field an initial value. This is how you should implement the code to ensure immutability usingjava.util.Collections.class ABC { private List<DEF> defList = Collections.emptyList(); public List<DEF> getDefList() { return defList; } public void setDefList(List<DEF> defList) { // defensively copy, then make immutable defList = new ArrayList<>(defList); this.defList = Collections.unmodifiableList(defList); }
I have a list which is a private member in my class. I have used getter and setter to get and set the values. SOnar throws an error - Mutable members should not be stored or returned directly.For example: ABC and DEF are two classes.class ABC{ private List<DEF> defList; public List<DEF> getDefList() { return defList; } public void setDefList(List<DEF> defList) { this.defList = defList; }After lot of googling and searching, I have understood that the getter can be changed as follows:public List<DEF> getDefList() { return new ArrayList<>(defList); }When i try to use setter similarly,public void setDefList(List<DEF> defList) { this.defList.addAll(defList); }then the variable starts showing'private field 'defList' is never assigned.May I know the correct way to do when it is a list, (a list of another class)Note: Both the answers from Prasad Karunagoda and Leo Aso works. I cant mark both as accepted answer. So having a note here
Sonar - Store a copy - Mutable members should not be stored or returned directly
Standalone ModeOut of the box, in the stadanlone mode, SonarLint uses a set of default rules. You can find the list of rules in theSonarLint webpage.Update: You can now configure the rules in the settings.Connected ModeIt is possible to bind projects to aSonarQube server, and use itsQuality Profiles, allowing to customize the rules being used and share the rule set within a team.On top of that,any known issue in SonarQube that is marked asfalse positiveorwon't fixwill not be displayed in SonarLint.Finally, even though we don't promote this feature, you can always add a//NOSONARas a comment to hide issues.Changing HighlightingBy default, issues created by SonarLint are highlighted as warnings in IntelliJ, but it can be changed in the following location:Settings > Editor > Colors & Fonts > SonarLint.It can be useful to make it more clear what SonarLint is contributing with.Giving FeedbackIt would be great if you could show concrete examples of false positives. The rules are constantly being improved, as you can see in thistracker, and feedback is always appreciated. You can open a topichereabout false positives.
I'm experimenting with SonarLint for IntelliJ, but I'm a bit wary of it. It doesn't seem to be offering anything more than IntelliJ already does, and there's no way to even look at what rules it is offering, let alone change them.Now, maybe it does add something, but, right now, I'm being spammed by false positives. Things like saying a variable is nullable when it was asserted not null in the very previous line. Is there any way to silence the false positives so I can concentrate on what's left?
How does one mark issues as false positives in SonarLint?
Try to use sonar-maven-plugin version 3.2 on your pom.xml<plugin> <groupId>org.sonarsource.scanner.maven</groupId> <artifactId>sonar-maven-plugin</artifactId> <version>3.2</version> </plugin>This works for me
I am trying to do code analysis for sonarqube. However, I got the error when runningmvm sonar:sonarThis is the error message:[ERROR] SonarQube server [http://localhost:9000] can not be reached [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 42.972 s [INFO] Finished at: 2017-06-06T08:51:52+08:00 [INFO] Final Memory: 8M/19M [INFO] ------------------------------------------------------------------------ [ERROR] Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin: 3.3.0.603:sonar (default-cli) on project example-java-maven: Unable to execute SonarQube: Fail to get bootstrap index from server: Status returned by url [http://localhost:9000/batch/index] is not valid: [504] -> [Help 1] [ERROR] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionExceptionBut when I accesshttp://localhost:9000via the browser, I can see the sonarqube homepage.So why could this be happening?Thank you.
Failed to get bootstrap index from server
It is actually a false-positive. TheSerialization of Enum Constants(which you've provided a link to) says that:Enum constants are serialized differently than ordinary serializable or externalizable objects. The serialized form of an enum constant consists solely of its name; field values of the constant are not present in the form.As I see it, it doesn't make sense to markEnum's field values astransientor make them implementSerializable, since they'll never get serialized, no matter if they're marked astransientor implementSerializable.If that analyzing tool forces you to do one of these two things, then you'll be writing useless code. If I were you, I'd try to disable that warning forenums.
I'm analyzing Java SE 7 project by SonarQube version 5.1.Then, I facedsquid:S1948on below code.Fields in a "Serializable" class should either be transient or serializableFields in a Serializable class must themselves be either Serializable or transient even if the class is never explicitly serialized or deserialized. That's because under load, most J2EE application frameworks flush objects to disk, and an allegedly Serializable object with non-transient, non-serializable data members could cause program crashes, and open the door to attackers.enum ShutterSpeed { private final Rational value; // Make "value" transient or serializable. ... }I think that any enum fields won't be serialized in J2SE 5.0 (Serialization of Enum Constants)Is this a false-positive?Whole code and issue arehere.
Does enum's field have to be Serializable?
+25If identity is what you need then it is what you need. The warning makes sense as it is often a bug but in this case it's not.As an example,IdentityHashMap(which works with identity vs. equality) has this in its javadoc:This class is not a general-purpose Map implementation! [...]This class is designed for use only in the rare cases wherein reference-equality semantics are required.So it is rarely useful but has its uses. You are in a similar position. And of course,its internal codedoes exactly what you expect, it uses==to get a key.Bottom line: I don't see why you would need to make the code more complex just because some static code analysis tool says it may be a problem - such a tool is supposed to help you, not to force you into some weird construct that will essentially do the same thing. I would explain why==is used in a comment for clarity, mark it as a false positive and move on.If you really want to remove the warning, the only option I can think of is to useequalsand change theequalsmethod to either:the defaultObject#equalswhich is based on identitysome implementation that uniquely identifies the cells, maybe based on some unique id or coordinates?
We are checking the quality of our code using Sonar, and Sonar found code which compares objects for identity like this:if (cellOfInterest == currentCell) { … }Sonar finds this kind of identity check peculiar enough to call it critical and proposes to replace the identity check (using==) with a check for equality (using.equals()instead). Identity checks, so the rationale behind this, are often not what is meant.In our case, however, we iterate through a list ofCells and check in each iteration (currentCell) whether we are handling a special cell we already have (cellOfInterest).I'd like to hear if there are other patterns than ours which are common and which avoid this issue simply by using a different design. Or what solutions do you propose to avoid using an identity check in the mentioned situation?We considered a replacement of the identity check with an equality check as described above but it does not seem applicable in our situation because other cells might be "equal" as well but not identical.All ideas are welcome!
Checking objects for identity and Sonar issues
On all your other machines, you need to install the Sonar Runner and configure it to point to your remote Sonar server. To do so: edit the "conf/sonar-runner.properties" file to reference the URL of your remote Sonar server and the JDBC connection to your remote database.All this is explained here:Installing and Configuring Sonar Scanner
I am using Java,Eclipse.I have installed & configured sonar-server,sonar-runner on my machine,it is working properly.I have tested the code quality of my project on my machine usinghttp://localhost:9000/. Everything is working fine.But now I want to test code quality of project which is on another machine using sonar server which is on my machine.(Means I have 5 machines then I don't want to install sonar-server,sonar-runner on all machines, I just installed it on one machine & want to use it for all other machines).How to connect sonar server to the project which is on another or different machine. Please guide me,how to do this?How to do setup?
how to use one sonar server on multiple machines
If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.You can safely ignore the returned value, if you don't need it.Sonarqubeis pretty invasive with certain rules, so just disable it and go on with your business.Imho, that specific rule is mostly set for common patterns on a project where code is written by multiple developers.
i've got a ConcurrentMap of ConcurrentMaps like this...ConcurrentMap<String, ConcurrentMap<K, V>> mapsMap = new ConcurrentHashMap<>();Now in some method, I would like to prevent NPE by making sure a map exists for a certain key like this...mapsMap.putIfAbsent(someKey, new ConcurrentHashMap<K, V>());...so I can safely call stuff like...mapsMap.get(someKey).put(...);...without worrying about null values here.Now, Sonarqube is telling me, that this violates the ruleRSPEC-2201...Return values from functions without side effects should not be ignored [..] and also on ConcurrentMap.putIfAbsent calls ignored return value.Is this just SonarQube not detecting that the side effect of the method is enough for me here (and the return value would not add any information) or am I missing an important point about the putIfAbsent contract?
The return value of "putIfAbsent" must be used - really?
Assuming your .sh files are bash scripts or some approximate equivalent then you can't currently configure your SonarQube server to analyze them because there's no plugin that handles such scripting.Sept 2018 UpdateThere's now a plugin in the Marketplace to read in i-Code CNES reports. i-Code CNES covers two flavors of FortranandShell.
Closed.This question is seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. You can edit the question so it can be answered with facts and citations.Closed5 years ago.Improve this questionI need to analyse the shell scripts using the Sonar server.The files that I have are of extension sh and would need to be analysed. But I don't see any plugin for the sh from the Sonar plugins.
How to analyse sh files in Sonar? [closed]
Use@SuppressWarnings("squid:UnusedProtectedMethod")See alsoSonarQube Java Plugin FAQ - SuprressWarningsThis has been implemented in the SonarQube Java plugin version 2.8.
I have a couple Hadoop map and reduce classes that override protected methods. Sonar flags these with:Unused protected method Plugin: squid Key: UnusedProtectedMethodI know there's a fix in Sonar that addresses this and that at some point my organization will use a version with that fix. In the meantime, I'd like to disable the warning. I've tried:@SuppressWarnings("UnusedProtectedMethod")and@SuppressWarnings("SQUID.UnusedProtectedMethod")to no avail.@SuppressWarnings works for PMD issues, @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "blah") works for findbugs issues. Is there another variant for squid issues, or is it just not supported yet?
How can I disable SQUID:UnusedProtectedMethod in Sonar for a class or method?
There's currently no way to do exclude specific methods from code coverage.For your second case, the problem is not on Sonar side but on the coverage tool that you use (Cobertura by default, but you may have changed it to Jacoco, Emma or Clover). You can try all those different tools to see which one gives you the best results. FYI, Jacoco will soon be the default coverage tool for Sonar.
I am using sonar for code analysis in my current project and my question is how can I specify certain methods, particularly getters and setters to be excluded when counting code coverage.Also I realized that for the @Component and @Value annotations the line coverage is 0, even when there is a unit test which uses the specific bean. Interestingly, the @Autowired is skipped as it should be.Where can I change this configuration/add some exceptions?
How to specify methods to be skipped by Sonar when counting coverage?
Here's some background info on the why:https://groups.google.com/forum/#!msg/sonarqube/Ir1sE6OVW40/64rLvZJFDAAJhttps://blog.sonarsource.com/sonarqube-6-x-series-focused-and-efficient/Hence my recommendation is basically to stay with your current 5.x version, or upgrade to 6.0 but not beyond, and then wait until mid 2017 and see what new cross project governance features are coming then.
I have SonarQube 6.1. When I click on a project entry from the main dashboards projects widget, I get to a project home page where it says "quality gate passed" and where some issues are listed ('Bugs', 'Vulnerabilities', 'Code smells' and 'Duplications').On the left side, close to the top, below the project name, there is a "home" icon and to the right it says 'Issuses', 'Measures', 'Code' and 'Administration'.When I tried to get to a project dashboard - similar to the main dashboard, but specific to the project - I found this pagehttp://docs.sonarqube.org/display/SONARQUBE56/Project+Dashboards. It shows in part a project home page that looks very different from my installations projects home pages. Instead of 'Issuses', 'Measures', 'Code' and 'Administration', like in my case, it has 'Technical Debt', 'Coverage' and so on and also 'Dashboards'. I guess thats where I should go looking for a project dashboard. But that menu item is just missing (along with others) from what my SonarQube shows me!What can I do?
sonarqube missing project dashboard
I found this jira, It's a Sonar's Bug.https://jira.sonarsource.com/browse/SONARJAVA-1138
I updated my Sonar to Version 5.1.2, and the issueMethods should not be emptyappears on this code:public User() {} public User (String login) { this.login = login; }It seems to be a bug. Am I right? Because this didn't happen before.
Sonar Methods should not be empty at the constructor
You should move the password to configuration.
In my application I have a ApplicationConstants.java class that serve for String Constants used in the application. I havepublic static final String PASSWORD = "password"as one of the constant. Sonar throws an error for that as below. Kindly let me know if there is a way to handle the same.Sonar error: Description Assignee Resource New issue Credentials should not be hard-coded : Remove this hard-coded password. EnrollmentConstant.java false
Sonar "Credentials should not be hard-coded" Error
You can read the following thread of discussion:http://sonarqube.15.x6.nabble.com/I-can-t-understand-the-meaning-of-quot-condition-coverage-quot-in-SonarQube-tt5029339.html
SonarQube describes the "Condition" coverage like this:On each line of code containing some boolean expressions, the condition coverage simply answers the following question: 'Has each boolean expression been evaluated both to true and false?'. This is the density of possible branches in flow control structures that have been followed during unit tests execution.http://docs.codehaus.org/display/SONAR/Metric+definitionsWell but I suspect they mean "branch coverage":if (A || B || C)Testing A=true and B=true yields 100%, without the need of checking the last expression (C). Also just two branches are tested - true and false for the whole expression, not individual expressions. Is that right?As far as I know, condition coverage should check all conditions in an expression.
SonarQube - is Condition coverage actually the branch coverage?
You should build a new separate class which represents your Entity ("Book" ) as Plain Old Java Object (POJO) or Data Transfer Object (DTO). If you use JSF or other stateful technology this rule is important. If your entity is stateful there might be open JPA sessions etc. which may modify your database (e.g. if you call a setter in JSF on a stateful bean).For my projects I ignore this Sonar rule because of two reasons:I alway you REST and REST will map my Java Class into JSON which can be seen as a DTO.REST is stateless (no server session) so no database transaction will be open after the transformation to JSON
I have a controller with a method like@PostMapping(value="/{reader}") public String addToReadingList(@PathVariable("reader") String reader, Book book) { book.setReader(reader); readingListRepository.save(book); return "redirect:/readingList/{reader}"; }When I run a static code analysis with Sonarqube I get a vulnerability report stating thatReplace this persistent entity with a simple POJO or DTO objectBut if I use a DTO (which has exactly the same fields as the entity class, then I get another error:1 duplicated blocks of code must be removedWhat should be the right solution?Thanks in advance. Enric
How to avoid the vulnerability created by using entities at a requestMapping method?
Apparently, this problem was caused by us usingsonar-scannerwithout specifyingsonar.java.libraries. Since it's multimodule maven project it wasn't clear to us how to specifysonar.java.librariescorrectly.Nicolas Peru, from SonarSource, suggested that we should use sonar maven plugin, instead ofsonar-scanner, as the plugin has access to build classpath of the project. Indeed that solved this problem for us.
Package has following package-info.java:@ParametersAreNonnullByDefault package foo; import javax.annotation.ParametersAreNonnullByDefault;Class has the following method:private static String toIsoString(@Nullable Instant dateTime) { return dateTime == null ? null : dateTime.toString(); }On which SonarQube (Version 6.2, SonarJava 4.14.0.11784) gives the following warning (squid:S2583):How can I convince SonarQube that the code is actually correct?Interestingly, SonarLint plugin (3.0.0.2041) in Idea doesn't generate the same warning.
@Nullable and SonarQube 'Conditionally executed blocks should be reachable' warning
This is what is stopping it:-Dsonar.analysis.mode=previewYou have to change it to:-Dsonar.analysis.mode=The assumption being you will have to upload bad builds and then trap them with a leak-period of 3 days instead of previous version.
I'm trying to get my build to break based on sonar results - so I've got a build-breaker running off the results inreport-task.txt.I'm running sonar in maven - with the following plugin config:<plugin> <groupId>org.sonarsource.scanner.maven</groupId> <artifactId>sonar-maven-plugin</artifactId> <version>3.0.1</version> </plugin>And the following command:mvn -Dsonar.analysis.mode=preview -Dsonar.scm.enabled=false -Dsonar.scm-stats.enabled=false -Dsonar.working.directory=/mypath/target/.sonarNow I expect thereport-task.txtto be created in/mypath/target/.sonarbut it is not.SonarQube version: Version 5.5My question is:Why doesn't my sonar scanner run create a report-task.txt file?
Why doesn't my sonar scanner run create a report-task.txt file?
According to this open githubrequest, it looks like it used to be there in v1, but was subsequently removed. For what it's worth you can do this to help (excerpt from the link):Expand AllClick somewhere in the window and start typing TypeMAJORif you want to find allMAJORissues
I would like to categorizeSonarQuberesults by severity 'major'. I have installedSonarQubeplugin in intellij community edition(version 14.1.4). When i try to run the sonarAnalyze -> Inspectcode, The inspection window shows all the issues by rule but does not categorize the issues by major, minor and critical. I would really appreciate if anyone has achieved this using IntelliJ IDEA Community edition.
How to group Sonar results by severity (MAJOR, MINOR,CRITICAL) in intellij community edition
Go to the project's Measures space and drill in on the metric of interest. You should find a history graph there.UPDATEThese history graphs moved intothe Activity page in 6.3
SonarQube used to have dashboards which were quite convenient to display how metrics changed over time. There was even a dashboard called "Time Machine".How can I see this sort of information in SonarQube 6.1? I appreciate the new focus on the "leak period" but this is not everything I care about.
SonarQube 6.1: How can I see the changes over time without the dashboards?
Geo j's approach of using a class selector instead of an element selector is good. Instead of editing every html source file to add the class, you can use@HostBindingto give every instance of the component the same class by default:@HostBinding('class.student-result') hasStudentResultClass = true;
We have used angular custom directive to generate a custom html tag called .The corresponding style sheet file for this tag is student.scss and its content isstudent-result {/* Sonarqube is reporting critical issue at this line saying "Remove the usage of the unknown "student-result" type selector" */ .student-result-top { position :absolute; height :300px; } }Can anybody suggest any way to resolve the issue or any plugin which will make sonarqube to recognize these custom HTML tags?
sonarqube giving false positive with the rule "Unknown type selectors should be removed" when trying to style a custom HTML tag
I bypass this issue:by adding a delete file task to pipeline before"Prepare analysis on SonarQube"task;delete".sonarqube\out\"folder. Source folder"$(Agent.BuildDirectory)\.sonarqube\out\";be sure to check"Remove files starting with a dot"in advance.
I need to run sonarqube for multiple projects in a nightly build definition. The problem I found is - after successfully run sonarqube for the first project, a.sonarqubefolder is created and a process seems keep using the folder. As a result, the folder cannot be deleted / used by subsequent projects. Is there a way to solve this?Error in the prepare step of 2nd project:2017-06-08T22:43:53.0910761Z ##[error]Failed to create an empty directory 'C:\VSTS-Agent-2.104.0\_work\3\.sonarqube'. Please check that there are no open or read-only files in the directory and that you have the necessary read/write permissions. 2017-06-08T22:43:53.0910761Z ##[error]Detailed error message: The process cannot access the file 'newSummaryReport.md' because it is being used by another process. 2017-06-08T22:43:53.0910761Z ##[error]Pre-processing failed. Exit code: 1 2017-06-08T22:43:53.0910761Z ##[error]System.Exception: Unexpected exit code received from batch file: 1 2017-06-08T22:43:53.0910761Z at Microsoft.TeamFoundation.DistributedTask.Task.Internal.InvokeBatchScriptCmdlet.ProcessRecord() 2017-06-08T22:43:53.0910761Z at System.Management.Automation.CommandProcessor.ProcessRecord() 2017-06-08T22:43:53.1066882Z ##[error]PowerShell script completed with 1 errors.
Sonarqube "Failed to create an empty directory" when scanning multiple projects in one VSTS build definition
Sonarqube provides the intelligence to execute a scan.SonarScanner is the scanner developed in-house by Sonar Source the organisation that developed SonarQube too.SonarScanner is one of many scanners available for our use. maven, gradle, ant, Jenkins are few others. Which means maven is not dependent on SonarScanner, and you can simply use maven instead of SonarScanner. Hope that helps. That said I don't understand what you mean by I analysed with Sonarqube! Because to my knowledge Sonarqube server does not perform analysis and it needs a tool to the job
I have a very big confusion that what is the use of sonar scanner when we have sonarqube server? when I analyzed a project with soarqube server it made an analysis and worked well. I am still in confusion why we need scanners too.Does it required when integrating with eclipse or maven or github? I did research on this but unable to get exact answer to satisfy myself.
Sonarqube vs sonarscanner
It's a false positive as you can seehereit's fixed in version 4.5.Answer to question 1:Yes, it is a bug, upgrade your Sonar version to 4.5 (or newer)Answer to question 2:Disable rule in sonarhereorHow to remove False-Positive issues?here
sonarqubeincorrectly reportson the following (simplified) sourcePreparedStatement has no parameters.(squid:S2695):public static final String UPDATE_QUERY = "UPDATE TABLE SET COL1=? WHERE PK=?"; private PreparedStatement preparedStatement = null; public void updateMethod(Date date, Long pk ) { if(preparedStatement == null) { //ConnectionService is not a Connection! preparedStatement = ConnectionService.prepareStatement(UPDATE_QUERY); } //sonarqube reports on the following two lines: 'This "PreparedStatement" has no parameters.' preparedStatement.setDate(1, date); preparedStatement.setLong(2, pk); ResultSet rs = preparedStatement .executeQuery(); //further code left out }Questions:Is this a bug or a limitation of the analyser?Is there something I can do to hide these "false positives"?
sonarqube incorrectly reports "PreparedStatement has no parameters."
I had the same problem migrating from sonarQube 3.7 to sonarQube 4.5. I changed the deprecated sonar.binaries for sonar.java.binaries... And suddenly my coverage didn't work anymore. . I had to revert:MyProject.sonar.java.binaries=classesfor:MyProject.sonar.binaries=classesand that work for me, even sonar tells me that I'm using deprecated entries.
After endless googling and reading tons of documentations, I am completely finsihed.I want to import already created unit tests reports like .xml and .exec-files (JUnit and Jacoco) into SonarQube. The Problem isSensor JaCoCoOverallSensor... 15:54:48 15:54:48.909 INFO - No JaCoCo analysis of project coverage can be done since there is no class files. 15:54:48 15:54:48.909 INFO - Sensor JaCoCoOverallSensor done: 374 ms 15:54:48 15:54:48.909 INFO - Sensor JaCoCoSensor... 15:54:48 15:54:48.910 INFO - No JaCoCo analysis of project coverage can be done since there is no class files. 15:54:48 15:54:48.910 INFO - Sensor JaCoCoSensor done: 1 msAs we have a rather large code, we do not have allways binaries of the src. So, the question is: "How can I import only the finished reports into SonarQube without having binaries?"SonarRunner Propertiessonar.dynamicAnalysis=reuseReports sonar.core.coveragePlugin=Jacoco sonar.junit.reportsPath=[...]/workspace/junit/xml-results sonar.jacoco.reportPath=[...]/workspace/junit/junit-test.execAny help is highly appreciated! Thanks in advance!
SonarQube unit tests w/o binaries
@PostMapping ResponseEntity<Object> addSomething(@RequestBody Some object) { // some code there return new ResponseEntity<>(HttpStatus.NO_CONTENT); }This will also remove the error. It is still very generic, but it is one of the solutions if you want to return different types based on the outcome. For instance:@PostMapping ResponseEntity<Object> addSomething(@RequestBody Some object) { //Will return ResponseEntity<> with errors ResponseEntity<Object> errors = mapValidationService(bindingResult); if (!ObjectUtils.isEmpty(errors)) return errors; // some code there return new ResponseEntity<>(HttpStatus.NO_CONTENT); }
I use SpringBoot for REST web services development and SonarQube for static analysis.I have a few endpoints in my application that look the following way:@PostMapping ResponseEntity<?> addSomething(@RequestBody Some object) { // some code there return new ResponseEntity<>(HttpStatus.NO_CONTENT); }SonarQube complains about using ResponseEntity with a wildcard, reporting me aCritical issue "Generic wildcard types should not be used in return parameters".I wonder if I should disable this verification in SonarQube or come up with something different for return type for these cases.What do you think about it?
SonarQube complains about using ResponseEntity with a wildcard
The issue is resolved. I used combination of Sonar 5.2, Eclipse Luna 4.4.2 (SR2) and Maven-eclipse-plugin 1.6 (download.eclipse.org/technology/m2e/releases/1.6). recent version of eclipse allowed me to install m2e 1.6 and recent sonar version allowed me to execute sonar plugin without proxy error.
Getting error while executingsonar:sonar goal on maven projectTried usingsonar-maven-pluginversion2.7.1and5.0Error :Failed to execute goal org.codehaus.mojo:sonar-maven-plugin:2.7.1:sonar (default-cli) on project XXX: Execution default-cli of goal org.codehaus.mojo:sonar-maven-plugin:2.7.1:sonar failed: Unable to load the mojo 'sonar' in the plugin 'org.codehaus.mojo:sonar-maven-plugin:2.7.1'. A required class is missing: Lorg/apache/maven/rtinfo/RuntimeInformation;
Maven: Failed to execute goal org.codehaus.mojo:sonar-maven-plugin:2.7.1:sonar
If you definecompareToyou should at least defineequalsboolean equals(it) { return compareTo(it) == 0; }otherwise you will get strange problems when you put your object inMaps andSets. It is generally good practice to also definehashCode.
Wondering what needs to be done for listed methodpublic final int compareTo(final FieldDTO o) { return o.available.compareTo(this.available);its throwing exception on line 2 stating Bad practice - Class defines compareTo(...) and uses Object.equals() 16 daysfield defines compareTo(FieldDTO) and uses Object.equals()Not sure how should i handle this. Thanks in advance.
Bad practice - Class defines compareTo(...) and uses Object.equals()
From the famous bookCode Complete:The comments have to be aligned so that they do not interfere with the visual structure of the code. If you don't align them neatly, they'll make your listing look like it's been through a washing machine.Endline comments tend to be hard to format. It takes time to align them. Such time is not spent learning more about the code; it's dedicated solely to the tedious task of pressing the spacebar or tab key.Endline comments are also hard to maintain. If the code on any line containing an endline comment grows, it bumps the comment farther out, and all the other endline comments will have to bumped out to match. Styles that are hard to maintain aren't maintained.Endline comments also tend to be cryptic. The right side of the line doesn't offer much room and the desire to keep the comment on one line means the comment must be short. Work then goes into making the line as short as possible instead of as clear as possible. The comment usually ends up as cryptic as possible.A systemic problem with endline comments is that it's hard to write a meaningful comment for one line of code. Most endline comments just repeat the line of code, which hurts more than it helps.Having said that, it's also about one's choice about coding style. I would personally avoid trailing comments as they don't helpthatmuch.
After running Sonar on one of my project I get a violation for 'trailing comments'. So I wonder, is this purely related to accepted/recommended code layout conventions for Java or is there 'more to it'? What's the reasoning behind it? When I'm looking over some C++ code ( recentDoom code review, there are tons (or binder full of) trailing comments.
sonar, java and 'trailing comment' violation
If you have no commited file, you can't run command mvn sonar:sonar. You need commit any change into your branch and after run mvn sonar:sonar. This fix me.
I couldnt run my maven project in sonarqube using command mvn sonar:sonar. It results with the error :Missing blame information for the following files. But a normal helloworld program run successfully and it got added in the projects tab of sonarqubes.Kindly help me to sort out this error.
Missing blame information for the following files SonarQube Error
Thejenkins-sonar-pluginusessonar-maven-pluginto run the Sonar analysis.Sonar-maven-plugin was updated to 2.7 on 2015-10-19 and the new version is not compatible with Java 6.Jenkins-sonar-plugin uses the latest version of sonar-maven-plugin per default, but you can override this.So to fix the error, open "Manage Jenkins"/"Configure System", find the Sonar section, click advanced and enter 2.6 in "Version of sonar-maven-plugin". This forces jenkins-sonar-plugin to use the previous version of sonar-maven-plugin, which works with Java 6.Alternatively, if you want to set 2.6 only for one specific Jenkins job then you can force maven to use 2.6 version using goalorg.codehaus.mojo:sonar-maven-plugin:2.6:sonarinstead of standardsonar:sonar.Also: begin planning to upgrade the build server to Java 7 or Java 8.
Our Jenkins builds started failing overnight with the error:[ERROR] Failed to execute goal org.codehaus.mojo:sonar-maven-plugin:2.7:sonar (default-cli) on project <project>: Execution default-cli of goal org.codehaus.mojo:sonar-maven-plugin:2.7:sonar failed: Unable to load the mojo 'sonar' in the plugin 'org.codehaus.mojo:sonar-maven-plugin:2.7' due to an API incompatibility: org.codehaus.plexus.component.repository.exception.ComponentLookupException: org/codehaus/mojo/sonar/SonarMojo : Unsupported major.minor version 51.0The Jenkins server is still running Java 6, but we did not change anything.What happened and how do we fix it?
Jenkins Sonar plugin suddenly stops working
sonar:sonarexecutes analysis and sends the results to the server - assuming you're running it with the token of an account that has the appropriate privileges.Developersshould notbe running this type of analysis locally to check their changes. Instead, they should be usingSonarLintand perhapspull request analysis(depending on your infrastructure).(EDIT:Pull request analysis has been deprecated and replaced by a fuller-featuredBranch analysis($).)To expand a little on why developers shouldn't be usingsonar:sonarlocally: it updates the central server in a last-saved-wins manner. So if you've edited A.java and analyzed it locally before commit, and I've renamed A.java to B.java and done a similar pre-commit local analysis... what's visible on the SonarQube server? Depends on who saved/analyzed last.Instead,sonar:sonarshould be run only from your CI tool on the checked-in code that's alreadyvisible to the whole team.
We want to use SonarQube with some CI tool in our project. Sonar Server url is configured in mainpom.xml.There are several team memebers in the project. So what happen when one team member executessonar:sonarlocally with his local changes, then another team member executessonar:sonarwith his local changes, and then someone executessonar:sonarfrom CI tool (it is configured to analyse source code in Git repository)?Will SonarQube display issues related team members local changes? What if there are differences between team members local source code and source code in Git repository?
How does sonar:sonar work?
The update instructions in the Administration view (System Upgrades) differ from the instructions here:UpgradingI would change the first instructions as follows (in cursive text the changed/added lines) and I'd try to keep theUpgradinginstructions in sync.Copy the list of installed plugins and stop your old SonarQube server.Download the new SonarQube version and start it on an empty DB (the bundled H2 DB for instance).Install (from the update center) the plugins you want.Install your custom plugins (if any).Update the conf/sonar.properties file to use the relevant configurations from your old instance, including the connection information for your production DB.Stop your new SonarQube server.Remove the following folders from the new SonarQube server:data, tempStart the new SonarQube instance: you're done!
We are currently running a production server at version 5.1.2 which we are planning to upgrade.Tests have shown that upgrading to 5.3 works as expected.However, upgrading from 5.1.2 -> 5.4 or 5.1.2 -> 5.3 -> 5.4 results in all quality profiles from the 5.1.2 instance becoming empty - no rules assigned at all.Worse, backing up the rules and attempting to restore them fails silently.Has anyone else experienced this? Is there a work-around?Thanks in advance.
All quality profiles have no rules when SonarQube is upgraded to 5.4
Yeah I have to write a custom script using exit status to break the build. I used API to analyse the status of QG.PROJECTKEY="%teamcity.project.id%" QGSTATUS=`curl -s -u SONAR_TOKEN: http://SONAR_URL:9000/api/qualitygates/project_status?projectKey=$PROJECTKEY | jq '.projectStatus.status' | tr -d '"'` if [ "$QGSTATUS" = "OK" ] then exit 0 elif [ "$QGSTATUS" = "ERROR" ] then exit 1 fi
I set up a Build project in TeamCity and integrated Sonarqube with it. The project is getting build and even publish the report successfully in SonarQube console. But when the quality gate fails, it's not breaking the build. I searched and read about the build breaker, but its already supported with Sonarqube plugin of TeamCity as this documenthttps://confluence.jetbrains.com/display/TW/SonarQube+IntegrationAm I missing something to configure/or any gotcha? I tried to search a lot but didn't find any sort of proper documentation or lead on that.
Quality Gate Failure in SonarQube does not fail the build in Teamcity
In yoursonar-project.properties, you have two ways to ignore files:sonar.exclusions=the/full/path/*.xmlwill ignore all.xmlfiles inpath.sonar.exclusions=**/*.xmlwill ignore all.xmlfiles in the folder and sub-folders where you are.Here are the different wildcards:* zero or more characters ** zero or more directories ? a single characterYou can find more information onSonar Documentation
I have confused on SonarQube's wildcards usage. Say I want to ignore all xml files. Should I just put*.xmlin the Global Source File Exclusions? But will it ignore xml files in different layers, for instance/foo/bar/file.xmland/foo/bar/folder/folder2/xml?
SonarQube - Using wildcards to ignore all xml files
After many tests, i found the correct syntax ofsonar.exclusionsclause:sonar.exclusions=src/Application/Sonata/**/*,src/Simuleo5BOBundle/Resources/public/js/lib/**/*,src/Simuleo5BOBundle/Resources/public/js/jquery.validate.js
I work on symfony project and I want to exclude some generated code fromsonar analytics.I want to exclude a folder named by this path:src/Application/Sonata.I tried many possibilities with sonar exclusions but in vain:sonar.exclusions=src/Application/Sonata/* sonar.exclusions=src/Application/Sonata/** sonar.exclusions=src/Application/Sonata/**/*this is my sonar-project.properties file# Required metadata sonar.projectKey=project sonar.projectName=project sonar.projectVersion=0.1.3 # Description sonar.projectDescription=project a base symphony 2 # Encoding of the source code sonar.sourceEncoding=UTF-8 sonar.exclusions=src/Application/Sonata/**/* ,src/project/Resources/public/js/lib/**/*, src/project/Resources/public/js/jquery.validate.js
SonarQube: sonar.exclusions parameter cannot exclude a folder
I agree you should use some common sense and go with the code which you believe is simplest.BTW You can simplify you code and have just one return if you use? :String foo() { return cond1 ? a : cond2 ? b : cond3 ? c : cond4 ? d : e; }
For the following piece of code, sonarqube computes the method cyclomatic complexity as 9String foo() { if (cond1) return a; if (cond2) return b; if (cond3) return c; if (cond4) return d; return e; }I understand as per the rules for computationhttp://docs.sonarqube.org/display/SONAR/Metrics+-+Complexitythe complexity of 9 is correct. So complexity of the method is = 4 (if) + 4 (return) + 1 (method) = 9This complexity can be reduced, if I have a single exit point.String foo() { String temp; if (cond1) { temp = a; } else if (cond2) { temp = b; } else if (cond3) { temp = c; } else if (cond4) { temp = d; } else { temp = e; } return temp; }I believe this code is more cluttered and unreadable than the previous version and I feel having methods with return on guard conditions is a better programming practice. So is there a good reason why return statement is considered for computation of cyclomatic complexity? Can the logic for computation be changed so that it doesn't promote single exit point.
Sonar cyclomatic complexity rule issue - discourages multiple return statements
The plugin the message is referring to is the Sonar Java Plugin. Log in to Sonar as admin, go to Administration/System/Update Center and you'll see that the current installed plugin version is 3.0. Update it to the newest version available and it should work.[Edit] - The upgrade is triggered by just clicking the button, but after it is downloaded and installed, you'll have to restart the Sonar server.
I have eclipse mars2 with sonarLint 2.1. I try to connect to a SonarQube Server 5.1.2When I try to connect via the eclipse GUI, the following error occurs:The following plugins do not meet the required minimum versions, please upgrade them: java (installed: 3.0, minimum: 3.8)Do you have any ideas? Thank you guys!
SonarLint cannot connect to SonarQube Server
You can use the Resources API :https://nemo.sonarqube.org/api/resources/index?metrics=date&format=jsonand look at the 'date' field to get the last analysis time.
How do I get a project's last analysis time (the one you can see in the dashboard) with the REST API of SonarQube?I am working with SonarQube 4.5.6, but if it's only available on later versions I'd still be interested in how it is done.
REST API for getting project last analysis date?
Currently code is not ready to handle exceptions - you're missing finally block to close open streams. And, sure, you're right - using try-with-resources solves this problem:public void archivingTheFile(String zipFile) { byte[] buffer = new byte[1024]; try (FileOutputStream fos = new FileOutputStream(zipFile); ZipOutputStream zos = new ZipOutputStream(fos)) { for(String file : this.fileList) { try (FileInputStream in = new FileInputStream(SOURCE_FOLDER + File.separator + file)) { ZipEntry ze = new ZipEntry(file); zos.putNextEntry(ze); int len; while ((len = in.read(buffer)) > 0) { zos.write(buffer, 0, len); } } } } catch(IOException ex) { LOGGER.error("Exception occurred while zipping file",ex); } }
Sonar is giving an error that thisFileOutputStreamshould be closed. I need to modify the following code to usetry-with-resources. How do I do this?public void archivingTheFile(String zipFile){ byte[] buffer = new byte[1024]; try{ FileOutputStream fos = new FileOutputStream(zipFile); ZipOutputStream zos = new ZipOutputStream(fos); for(String file : this.fileList){ ZipEntry ze= new ZipEntry(file); zos.putNextEntry(ze); FileInputStream in = new FileInputStream(SOURCE_FOLDER + File.separator + file); int len; while ((len = in.read(buffer)) > 0) { zos.write(buffer, 0, len); } in.close(); } zos.closeEntry(); zos.close(); }catch(IOException ex){ LOGGER.error("Exception occurred while zipping file",ex); } }
Sonar: How to use try-with-resources to close FileOutputStream
It's not a need, it's a finalizer writing idiom that should be followed.If, at any time in the future, you refactor your code and your class extends some other class that may have afinalizemethod, this practice will prevent strange bugs from popping up.The idiom istry { // Do whatever the finalization is } finally { super.finalize(); }This ensures that the superclass finalizer, if there is ever a non-trivial one, will be called even if some exception is thrown (because nothing catches exceptions in finalizers, their execution simply stops).And of course:Avoid finalizers. (Item 7 in Joshua Bloch's Effective Java, second edition).
I am getting SonarQube error that : "Calling thesuper.finalize()at the end of this method implementation is highly recommended in case parent implementations must also dispose some system resources."But I found thatObjectclass has no implementation forfinalizemethod.protected void finalize() throws Throwable { }So why need to callsuper.finalize()?
Why calling super.finalize() is preferred when overriding finalize() method?
After upgrading our sonar to v4.4 and changing Sonar's Quality profile from 'Sonar way' (Java) to 'Sonar way with Findbugs' I came accross this same exception complaining about the SAX2 driving:Can not execute SonarQube analysis: Can not execute Find bugs: SAX2 driver class org.apache.xerces.parsers.SAXParser not foundI got around it by adding the driver to my maven command:Dorg.xml.sax.driver=com.sun.org.apache.xerces.internal.parsers.SAXParserBellow was my actual maven command to clean, compile, run test, analyse code and upload stats to sonar (having the fix in the command line also meets you non machine specific preference fix and requires no change to your source code)$ mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent install -Dmaven.test.fai lure.ignore=true -Dorg.xml.sax.driver=com.sun.org.apache.xerces.internal.parsers. SAXParser sonar:sonar
I am trying to get sonar to work for a project with a quality profile that includes Findbugs rules.However when analyzing the project the sonar anttask chrashes with the following error:Caused by: java.io.IOException: SAX2 driver class org.apache.xerces.parsers.SAXParser not found at edu.umd.cs.findbugs.filter.Filter.<init>(Filter.java:134) at edu.umd.cs.findbugs.FindBugs.configureFilter(FindBugs.java:516) at edu.umd.cs.findbugs.FindBugs2.addFilter(FindBugs2.java:374) at org.sonar.plugins.findbugs.FindbugsExecutor.execute(FindbugsExecutor.java:136) ... 50 moreon this project the dependencies are resolved with ivy, and has no dependencies on libraries like xerces and xalan. Also i understood that xerces is included included in the JVM and is always a pleasure to deal with...i've tried to add all sorts of dependencies to use for the sonar.libraries property but with no effect adding the local JRE libs also doesnt seem to have much effect.How do i get this findbugs analysis to run (in a machine independent way)?(Sonar version: 4.4, findbugs3 plugin)Update: I just found out the source of the conflict is having a target earlier in the build, removing it fixes it. Ofcourse i very much like to keep my ivy report as well, so the question is still how do i get this to work...?
Sonar Xerces conflict Findbugs and ivy:report
If you don't configure the Maven Sonar plugin, it will attempt to connect to the default location for the embedded database that ships with Sonar. Starting with version 3.2 the default embedded database is H2 (replacing derby).The forum recommendations are correct, I suspect that your Maven instance is not loading the correct settings file. Try running Maven as follows:mvn -s /path/to/settings/file/setting.xml sonar:sonar
I just downloaded Sonar 3.2 and have configured the sonar.properties files to connect to my local MySql database. I have the following setting enabled:sonar.jdbc.url: jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true sonar.jdbc.driverClassName: com.mysql.jdbc.DriverI am able to start the server without any errors and am able to log into the Sonar interface however when I run 'mvn sonar:sonar' on my maven project I get the following error:[ERROR] Failed to execute goal org.codehaus.mojo:sonar-maven-plugin:2.0:sonar (default-cli) on project vrservices: Can not execute Sonar: Fail to connect to database: Cannot load JDBC driver class 'org.h2.Driver' -> [Help 1]I have read a few forums that saying to put the following code in the settings.xml file however this still didn't fix the issue.<profile> <id>sonar</id> <activation> <activeByDefault>true</activeByDefault> </activation> <properties> <!-- EXAMPLE FOR MYSQL --> <sonar.jdbc.url>jdbc:mysql://localhost:3306/sonar?useUnicode=true&amp;characterEncoding=utf8</sonar.jdbc.url> <sonar.jdbc.driver>com.mysql.jdbc.Driver</sonar.jdbc.driver> <sonar.jdbc.username>root</sonar.jdbc.username> <sonar.jdbc.password></sonar.jdbc.password> </properties> </profile>I was wondering if anyone has come across this issue as well and if so how did you fix it?Thanks in advance!
Sonar MySQL setup
The theory is that preview mode is what a end user should use for example when using issues report feature. The goal is to run an analysis without publishing results. The issues mode is a technical mode similar to preview but focusing only on issues. It can be used in combination with one of the pull request analysis plugin (like GitHub plugin).Now in practice, in SonarQube 5.6, they are doing exactly the same thing. It is a bit confusing I admit, so maybe we could try to simplify this.
Which are the key differences between thesepreviewandissuesmodes of SonarQube (greater than 5.2) analysis?Consideringhttp://docs.sonarqube.org/display/SONAR/Conceptsthe main differences betweenpublishandpreviewis thatpreviewreports only issues (no measures) and no report is pushed back to the SonarQube server; this idea is clear. But what aboutissues? It is written thatissuesis the same aspreview, but should be used only for tools development. I'm a little confused, what do they mean by tools?
SonarQube analysis mode: preview vs issues
If your build already takes 45 minutes, then I'm not surprised that the SonarQube analysis takes a lot of time as well. 500k LOC is a lot for a single project.Here are some various ways to reduce the time:First make sure that you run SonarQube server on a real DB, not on H2Then, the analysis should occur very close to the SonarQube DBIf possible on the same machineIf not possible, analysis and DB should be located on the same high-bandwidth & high-speed LANAlso, make sure that you activate only relevant rules, and not all the available rules (some are even redundant)
Even though it seems to point to the enormous number of lines of code (500,000), engineering is unconvinced why it takes 90 mins on a beefy Solaris box with 16GB RAM and dual-CPU to finish one Sonar analysis. Please tell me if 90 mins is too much time for a codebase this size.I am checking out code from Git using Jenkins git plugin, running a full ant build which takes 45 mins and then running 'ant sonar' which populates data to a SonarQube server running 4.1.2 and which has a 'Quality profile' as the default profile consisting of findbugs, checkstyle and PMD. Total time is 45 + 90 mins.When i use the incremental option, the analysis time goes down and it does "see" that only one file has to be analysed. However, as per the documentation, the diff analysis is not populated in the database, hence rendering that option useless for my purposes.How can I reduce the time taken for each SonarQube analysis?
SonarQube Analysis takes too much time
Or you could:echo NEW_VAR=${GIT_BRANCH#*/} > newfile
Large team with separate git branches per team and sonar as a code quality checker.The scm tool is set up to pick up every branch that corresponds to this name:'feature-branch-*'which works perfectly, for the maven build.I wanted to set up sonarqube so it would use a different branch for every actual git branch, but sonarqube does not allow wildcards. It does however allow variables so I tried${GIT_BRANCH}, but this variable holds:'origin/feature-branch-214', which sonarqube does not recognise as a valid branch name. Sonarqube expects'feature-branch-214'So I need something to put there (in sonarqube branch) that doesa substring of the${GIT_BRANCH}to exclude the'origin/'part.
Jenkins build using variable ${GIT_BRANCH} as sonarqube parameter without "origin/"
Instead of as a dependency, put thesonar-maven-pluginin the<build>section of the rootpom.xml, as follows:<build> <plugins> <plugin> <groupId>org.sonarsource.scanner.maven</groupId> <artifactId>sonar-maven-plugin</artifactId> <version>3.0.1</version> </plugin> </plugins> </build>And since it's a multi-module project, you shouldfirst perform an install from the root project and then run thesonar:sonargoal as a dedicated step, as follows:mvn clean install mvn sonar:sonarTo configure the sonarqube server URL,specify a project property ofsonar.host.urlin yoursettings.xmlorpom.xmlas follows:<properties> <!-- Optional URL to server. Default value is http://localhost:9000 --> <sonar.host.url>http://myserver:9000</sonar.host.url> </properties>
I have a project made up of several modules.I'm trying to analyse these with SonarQube.I've included the Sonar Maven plugin as a dependency in each module:<dependency> <groupId>org.codehaus.sonar</groupId> <artifactId>sonar-maven-plugin</artifactId> <version>5.1</version> </dependency>Then I'm running Maven using:mvn clean verify sonar:sonarMaven completes successfully and I can see the Sonar analysis happening however when I open the Sonar UI, the modules aren't visible in projects.However...If I run the Maven command from an individual module directory, it is visible in projects.Feel I'm missing something very simple, appreciate any help!
Maven SonarQube multi module
I do confirm that this property sonar.java.source is used only by the PMD tool. The SonarSource's Java analyser uses a superset grammar and so can analyse source files regardless of the Java version they comply to.
How can I know against which version of Java SonarQube validates the code? Is it the version of the JVM? What then if my project is based on a different version?
SonarQube Java version used to verify code
Check-out the SonarQube ruleRSPEC-4288: Spring components should use constructor injection. Although it doesn't explain why thefinalusage is triggered as non-compliant, there is a compliant code sample. Initialize the fields asnullto make it SonarQube compliant:private Environment env = null; private YYYAdaptor yyyAdaptor = null; private JAXBContext jaxbContext = null;However, what SonarQube says isnot sacredand is filled with lots offalse-positives. These static-analyzers hits the issues that areworththe further introspection, yet not definitive and based on the rules made by people with opinions.Personally, I'd mark this issue aswon't fixand declare the fields asfinalto make the object immutable:private final Environment env; private final YYYAdaptor yyyAdaptor; private final JAXBContext jaxbContext;
I have a piece of code with field injections I am trying to convert to use constructor injections instead. The initial code looks like this:@Autowired private Environment env; @Autowired private YYYAdaptor yyyAdaptor; @Autowired private JAXBContext jaxbContext;And this is how I rewrite it:private Environment env; private YYYAdaptor yyyAdaptor; private JAXBContext jaxbContext; @Autowired public YYYResource(Environment env, YYYAdaptor yyyAdaptor, @Qualifier("YYYYReq") JAXBContext jaxbContext) { this.env = env; this.yyyAdaptor = yyyAdaptor; this.jaxbContext = jaxbContext; }Doing this gives me a critical vulnerability on the sonar scan, with "this member" referring to each of the declared variables:Annotate this member with "@Autowired", "@Resource", "@Inject", or "@Value", or remove itWhat is the best way I can avoid using field injections while avoiding sonar throwing a fit?
Using Spring constructor injection with SonarQube
Thanks to SonarQube mailing list, the solution is to set the following properties:sonar.sources=client sonar.tests=client sonar.exclusions=**/*.spec.js sonar.test.inclusions=**/*.spec.js
I have a project to analyze which is only based on Angular framework. The main issue I have is that both source and test files are on the same directories, divided into features.Here is an example of my structure:+- client | +- features | | +- home | | | +- home.js [source code] | | +- home.spec.js [test code] | +- home.html | +- home.less +- admin | +- admin.js [source code] | +- admin.spec.js [test code] | +- admin.html | +- admin.less ...In mysonar-project.properties, it seems impossible to set a pattern instead of a path (for ex.sonar.tests=client/**/*.spec.js).Is there a way to run an analysis with this kind of structure?Thanks.
How to analyze with SonarQube a project where sources and tests are in the same directories
You will need the Java JDK (or the JVM if you prefer), version 11 or higher. You can download and install 11.0.11 from here:https://www.oracle.com/java/technologies/javase/jdk11-archive-downloads.html.
Trying to use SonarQube, Community edition, for my first experience with SonarQube. I have just now downloaded it, and am following instructions to start a local instance. I am running Java v10.0.2.When I run the D:\SonarQube\bin\windows-x86-64\StartSonar.bat file, I get an error launching a JVM. The exact output of StartSonar.bat is:wrapper | --> Wrapper Started as Console wrapper | Launching a JVM... jvm 1 | Unrecognized option: --add-exports=java.base/jdk.internal.ref=ALL-UNNAMED jvm 1 | Error: Could not create the Java Virtual Machine. jvm 1 | Error: A fatal exception has occurred. Program will exit. wrapper | JVM exited while loading the application. wrapper | JVM Restarts disabled. Shutting down. wrapper | <-- Wrapper Stopped
SonarQube Could not create the Java Virtual Machine Unrecognized option: --add-exports=java.base/jdk.internal.ref=ALL-UNNAMED
This is a question of which language "claims".hfiles. Only one language can claim any given file extension and currently you have two languages claiming.h, so the scanner can't figure out which analyzer to give those files to, and gives up.Specifically, from your error message:the file matches patterns of both sonar.lang.patterns.c++ : **/*.cxx,**/*.cpp,**/*.cc,**/*.c,**/*.hxx,**/*.hpp,**/*.hh,**/*.h and sonar.lang.patterns.objectivec : **/*.h,**/*.mYou have bothcxxandobjectivecclaiming.h. You must remove the extension from one of those two lists.Go to (Global)Administration > [Language] > [Language] file suffixesto edit the extensions claimed by each language, and remove.hfrom one or both languages.Make sure that you do not leave either of these fields blank. If left blank, the default value (which includes.h) will be used.
Our Sonar Build Environment details as follows:* SonarQube Server Version - 5.6.6 (64-Bit). * Sonar Client Build Operating System – Windows-7 (64-Bit). * Sonar-scanner- Version - 3.0.3.778. * sonar-cxx-plugin-0.9.7.jar * sonar-csharp-plugin Version -5.11.0.1761. * sonar-objective-c-plugin-0.5.0-SNAPSHOT.jar * Source Code Language: C# and C++Our SonarQube server is centralized server, So have installed (cxx-plugin, objective-c-plugin and csharp-plugin)Current Problem:When we scan the code, if fails with below error. Since we have multiple language (C# and C++) code, Both the language has to be scanned at a time.ERROR: Caused by: Language of file 'workspace/HS30/baseclasses/ametex.h' can not be decided as the file matches patterns of both sonar.lang.patterns.c++ : **/*.cxx,**/*.cpp,**/*.cc,**/*.c,**/*.hxx,**/*.hpp,**/*.hh,**/*.h and sonar.lang.patterns.objectivec : **/*.h,**/*.msonar.language=cs,c++ (Tried but didn't work)So kindly help us to resolve the same.
SonarQube Language sonar.lang.patterns error
This rule relies on the new "Cognitive Complexity" metric - for which you can read the definition in the following PDF:"Cognitive Complexity - A new way of measuring understandability".Note that it differs from the "Cyclomatic Complexity" (the original one that has always been available in SonarQube), which is a way of measuring testability of your code.
we noticed there is a new rule in SonarQube java plugin about cognitive complexity, "Cognitive Complexity of methods should not be too high", but we didn't understood which metric is used by this rule.Is there a new metric or an older one, with another name, is re-used ?thanksMassimo
SonarQube cognitive complexity metrics
The Sonar Server / Dashboard / GUI is just used to display data, not to collect data (this oldblog postexplains the sonar architecture).To collect data you can use maven, gradle, ant or sonar-runner for other projects. The documentation that guides you is in ... thesonar documentation:) - see the child pages, as they explain the details of how to configure the technologies I mentioned above.I suggest you to also have a read at theconfiguration parametersyou can pass, as the docs are not super clear about them.
Is there a way to run aSonar 5.1.1Analysis completely in the Dashboard GUI?If not what are the steps to run it otherwise? I can't seem to find a document that walks you through the steps.
Running a Sonar Analysis from the Dashboard
Here's one way to do it, if you are ok with triggering the build usingcronor some other scheduling tool:Make the buildparameterized, and use a parameter in your build file to decide if the Sonar build target should run or not.Trigger the build remotely by HTTP POST:ing the parameter values as a form tohttp://[jenkins-host]/jobs/[jobname]/buildWithParameters. Depending on your Jenkins version and configuration, you might need to add anAuthentication Tokenand include this in your url.Authenticate your POST using a username and password.wget --auth-no-challenge --http-user=USERNAME --http-password=PASSWORD "https://[jenkins-host]/job/[jobname]/buildWithParameters?token=<token defined in job configuration>&<param>=<value>&<param2>=<value2>"
The group that I work in has standardized on Jenkins for Continuous Integration builds. Code check-in triggers a standard build, Cobertura analysis and publish to an Artifactory SNAPSHOT repo. I've just finished adding a new target to the master build file that'll kick off a Sonar run but I don't want that running on every check-in.Is there a way to schedule a nightly build of a specific build target in Jenkins? Jenkins obviously facilitates scheduled builds but it'll run the project's regular build every time. I'd like to be able to schedule the Sonar build target to run nightly.I could, of course, create a separate Jenkins project just to run the Sonar target on a schedule but I'm trying to avoid that if I can. Our Jenkins server already has several hundred builds on it; doubling that for the sake of scheduling nightly builds isn't very desirable. I looked for a Jenkins plug-in that might facilitate this but I couldn't find anything. Any suggestions?
Schedule specific build target in Jenkins?
As far I know there is no public schedule available. You can find the latest versionshere. SonarQube 5.6 LTS was released in Jul 2016; SonarQube 6.7 LTS in Dec 2017 so it is likely that the 7.x LTS version will be released somewhere in the first half of 2019. The latest SonarQube news is postedhereand you can also follow thefeedbackchannels. On the Google forum (will be moved very soon) you can find messages about pre-releases for example. You can also have look at thecloud version; that will be updated first.Update May 2019In a blog SonarSource announced the end of support ofMySQL, starting from SonarQube v7.9. So there will be one more minor version update before a LTS version is made or they skip v7.8. Seethe roadmap pageregarding the new v7.9 LTS version.
We would like to upgrade our Sonar setup to 7.x but waiting for LTS release.Is there any update on when Sonarqube LTS (7.x) release is scheduled?Is there already some URL containing such information?(i hope it is ok to "impersonate"the question for the 6.x LTSwhich g.ann was so nice to answer)If such info would be made available on the interwebs somewhere we would not need to ask here.cheers and thank you in advance!
Sonar 7.x LTS release schedule
show columns from table_name;This will show you the data type of columns, primary key, initial values etc.
I have written java code to connect to H2 database(sonar's default database) and using metadata I can see all tables and columns for each table. But I want to see table structure(like Primary key, foreign key, number of records in table). How can I view table structure using metadata? or Is there any other approach for viewing table structure?Solution/help would be highly appreciated.
how to get table structure for h2 database using metadata
Remove the semicolon;from the end; right now it's being included in the constructed path.This variable is expected to be a single directory, not a list, and should not have a path separator.
Situation: I installed Sonarqube on a Win XP 32-bit system. I set all paths as instructed. The server opens up well at localhost://9090.My JAVA_HOME is: C:\Program Files\Java\jdk1.7.0_60;ProblemWhen I run, sonar-runner.bat, I get the following error:ERROR: Java_Home exists but does not point to a valid Java home folder. No "\bin\java.exe" file can be found here.What I tried:I added /bin to the path. I tried /jre, and then /jre/bin (Note: all of them contain the "/bin/java.exe" within them.Is this due to some permissions issue of the Java (or Jdk) folder ?
Sonar runner: JAVA_HOME exists but does not point to a valid Java home folder
This is a deficiency in a way how SonarJava (Java static code analyzer used in SonarQube platform) detects this issue. I created following ticket to improve the implementation to cover cases when field is returned usingthis.https://jira.sonarsource.com/browse/SONARJAVA-2424
Sonar rulesquid:S2384raises an issue on this code:public Date getCreatedOn() { return createdOn; }following the ruleMutable members should not be stored or returned directlyI understand that we should not return the original, instead we should return a copy of the object.On the other hand, Sonar does not raise an issue on this code:public Date getCreatedOn() { return this.createdOn; }What makes this code different?Are we not returning the original copy in the 2nd case?
Why is returning this.variable not a vulnerability?
You can achieve this with the excel web-query.Open an excel sheet and go toData-->selectFrom Webfrom Get External Data section.paste URL inAddresssection and click onGObutton, here you can see your sonar report on the wizard.click onImportthen you will get awizardto setproperties, set properties as you wish to set and hitOK.It brings all the data from the URL/Sonarto your excel sheet.Take one new sheet and prepare table what all the things you want to highlight ex: Skipped Test cases/major/minor/coverage issues etc..Finally with the excel formulaMATCH, INDEX, LEFT..you can achieve this.Hope it helps to prepare sonar statistics
Using SonarQube 4.3 version.I'm trying to export the issues listed in sonar analysis to MS-Excel. Please help. I don't want to export to .html using report plugin.
In sonarqube - How to export issues to MS-Excel
This is indeed a False Positive (FP) raised by version 4.13.0.11627 of the SonarJava plugin.After investigation, the FP is caused by a bug in handling of unary operators in our Symbolic Execution (SE) engine. The following ticket will fix the issue:SONARJAVA-2460(expected fix version: 4.14)For details about WHY the issue is occurring: Class fields, when accessed usingthis.xorsuper.x, are not handled as they should be. They are currently purely and simply ignored (will be fixed by the JIRA ticket). It has for side effect that update of the field occurring withthis.x--is not registered by the SE engine: the symbolic value associated to symbolxis not updated. Consequently, when testx == 0is done, the only thing that the engine knows at this time is the (wrong) constraint thatx > 0. In such state, the condition will always be false. Fixing the issue will allow the engine to know that thextested in the condition is not the same anymore as the one used for checkingx > 0.
This seems to be a new example of a false positive of the rule "Conditionally executed blocks should be reachable" (squid:S2583). Does anyone know why SonarQube claims thatif(this.x == 0)always evaluates tofalsein the following Java class?public class MyClass { private long x; void setX(long x) { this.x = x; } public void decrementX() { if(this.x > 0) { this.x--; if(this.x == 0) { // <-- Always false?! // apparently dead code } } } }Clearly the variablexcan be set to1and thendecrementX()will get into that exact condition:@Test public void testDecrement() { MyClass c = new MyClass(); c.setX(1); c.decrementX(); }(executed on SonarQube server 5.6.6 with SonarJava plugin 4.13.0.11627)Update: as noted by Absurd-Mind, SonarQube is happy whenthis.xis shortened tox. In my opinion, this is a false-positive.
SonarQube claims condition to always evaluate to false for fields accessed with "this."
Currently you cannot achieve that by configuring SonarQube itself. However, you can try our tool,SourceMeterwith itsSonarQube plug-in, which implements an AST based clone detection and therefore it presents syntactically coherent duplications inside SonarQube. For an example, you may take a look at theonline demo.
I’m using SonarQube on my Java projects, and want to eliminate code duplications from our code as far as possible.My problem is that SonarQube’s code duplication detection doesn’t take into account method boundaries. It lists identical parts of files as duplications, and it often happens that a duplication starts in the middle of a method and ends in the middle of another. These can hardly be refactored.Here is anexample. Click on file MavenArtifactRepository.java in the upper right list box, and take a look at the 4th duplication block in the lower part of the page.Is there any way to parameterize the code duplication detector plug-in to show duplications, which are syntactically coherent?
Can SonarQube code duplication detector be parameterized to stop on method boundaries?
+25Try to add @SuppressWarnings("squid:S00107")
In sonar rules, there is aS00107rule for "Methods should not have too many parameters". This rule has exceptions for some annotations:ExceptionsMethods annotated with Spring's @RequestMapping (and related shortcut annotations, like @GetRequest) or @JsonCreator may have a lot of parameters, encapsulation being possible. Such methods are therefore ignored.Is it possible to add another annotations to this exceptions?My case:I have constructors, annotated by the Lombok's@Builder, which contains a lot of parameters! So i want to ignore this rule on these constructors.public class MyClass extends MySupperClass { @Builder public MyClass(String a, int b, ..., String z) { } }
Add a custom exception to the "Methods should not have too many parameters" SonarQube rule
$paths = Get-ChildItem -include *.csproj -Recurse foreach($pathobject in $paths) { $path = $pathobject.fullname $doc = New-Object System.Xml.XmlDocument $doc.Load($path) $child = $doc.CreateElement("ProjectGuid") $child.InnerText = [guid]::NewGuid().ToString().ToUpper() $node = $doc.SelectSingleNode("//Project/PropertyGroup") $node.AppendChild($child) $doc.Save($path) }
I will preface this that my current solution to this is very easy but one I do not want to keep implementing.The ProblemBelow you will see an image outlining my current build steps. Each of these contain the default settings, with thePrepare analysis on SonarQubesetup to point to my endpoint.When I run this, again just default settings, I am presented with the following errorsWARNING: Duplicate ProjectGuid: "00000000-0000-0000-0000-000000000000". The project will not be analyzed by SonarQube. Project file: "D:\a\1\s\API.Tests.csproj" WARNING: Duplicate ProjectGuid: "00000000-0000-0000-0000-000000000000". The project will not be analyzed by SonarQube. Project file: "D:\a\1\s\API.csproj"This is because the build step for dotnet core, by default, looks for**/*.csprojusing the linked setting(Parameters.RestoreBuildProjects)- with the update to the csproj format the project guid is no longer stored in the csproj files. What I suspect is happening is that SonarQube just defaults the guids when it finds nothing defaults to000...and then throws this error.The FixUnlinking thePath to project(s)parameter and pointing to**/.*.slnfixed the issue, because now SonarQube can see the project guids (defined the.sln)The Question, finallyAfter that long winded explanation I am lead to ask if there is a better way to get SonarQube to recognise dotnet core projects.I do not want to change the default build task every time I create a project to satisfy SonarQube's requirements.
SonarQube dotnet core: how to avoid the duplicate guid error without altering the default build task
I'm afraid this isn't a problem spring-boot or spring-cloud can solve. You need to add exceptions to your sonar configuration.
I have this class to start up the spring-cloud config server. It is a spring-boot application.@SpringBootApplication @EnableConfigServer @EnableDiscoveryClient public class ConfigServerApplication { public static void main( String[] args ) { SpringApplication.run( ConfigServerApplication.class, args ); } }The application runs fine and all my unit tests are fine. However, in our bamboo pipeline, it will initial a sonar process to analyze the code. We keep getting these minor warnings indicating the following:Utility classes should not have a public constructorI know that this is a minor issue, but I have been tasked with removing these from our code.Ideally, you would mark the class final and provide a private constructor, or so all searches provide as a solution. However, a Spring Configuration class cannot be made final and cannot have a private constructor.Any ideas how to resolve this?
Sonar complains about Spring Boot configuration
+50SonarQube requires that the absolute paths of the source files found in the coverage HTML reports to be strictly equal to the absolute paths of the files being analyzed.This implies that youcannotrun your tests and collect code coverage on a machine A, transfer the report to machine B, and then run the SonarQube analysis from machine B. From within the same machine, you alsocannotcheckout the code once to run the tests & collect code coverage, and then check it out another time to run the SonarQube analysis.This is a common case of why code coverage doesn't get imported into SonarQube, but without the logs, it is hard to tell whether this is your case or not.
I have been struggling with this issue. I have been able to generate theHTMLreports with the help ofDotCover. Also, I have given the path of the reports in the Sonar Portal too underProject Settings--> C# --> CodeCoverage --> DotCoverReportPathand also in theSonar.Propertiesfile for the particular solution (Mine is aDotNetapplication).When I run theSonar-Runnerit seems to parse theHTMLfiles and also says that Execution success, but however my dashboard on theSonar Systemshows "No Data" for the coverage.Please help me out if any of you have faced a similar issue and have been able to figure out the error.
How to integrate the dotcover HTML reports with sonarqube 4.5?
To get rid of these errors, add android.jar location directly tosonar.libraries:sonar.libraries=libs/*.jar,/usr/local/opt/android-sdk/platforms/android-18/android.jarTwo obvious drawbacks with this:Directly pointing to local environment. SonarQube project configuration doesn't support environment variables yet (https://jira.codehaus.org/browse/SONARUNNER-76).Directly pointing to a version of android platform; this is probably OK but needs to be manually kept in sync with your targetSdk
I trying to set a sonar analysis on an android projectThe analysis is done with version 4.3 of sonarQube trough sonar-runner, android-plugin install, ANDROID_HOME env variable is set on /path/to/android/sdk, the build is done with ant without any problemsthe execution run well but i have tons of error messages :14:23:46.563 ERROR - Class not found: android.content.UriMatcher 14:23:46.563 ERROR - Class not found: android.net.Uri 14:23:46.563 ERROR - Class not found: android.database.sqlite.SQLiteDatabase 14:23:46.568 ERROR - Class not found: android.provider.BaseColumns 14:23:46.757 ERROR - Class not found: android.net.Uri 14:23:46.829 ERROR - Class not found: android.content.ContentProvider 14:23:46.829 ERROR - Class not found: android.net.Uri 14:23:46.830 ERROR - Class not found: android.database.sqlite.SQLiteDatabase 14:23:46.830 ERROR - Class not found: android.content.Context ...My sonar-project.propeties :sonar.projectKey=Client-Project sonar.projectName=Client-Project sonar.projectVersion=2.0 sonar.sources=src sonar.binaries=bin/classes sonar.librairies=bin/dexedLibs,usr/local/android-sdk-linux sonar.language=java sonar.sourceEncoding=UTF-8 sonar.profile=Android LintHow to set Sonar to find these android classes ?
Android classes not found during sonar analysis
From the webJava Ecosystem:It is no longer possible to let SonarQube drive the execution of the unit tests. You now have to generate the JUnit and code coverage (JaCoCo or Cobertura or Clover) reports prior to the SonarQube analysis and then feed SonarQube with those reports.So you need to include Jacoco in the pom.xml:<plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>0.7.0.201403182114</version> <configuration> <destFile>${basedir}/target/jacoco-unit.exec</destFile> <dataFile>${basedir}/target/jacoco-unit.exec</dataFile> </configuration> <executions> ... </executions> </plugin>And give this data file to SonarQube:sonar.jacoco.reportPath=target/jacoco-unit.exec
I'm running SonarQube in a jenkins job (using Post-build Actions). I'm getting the following problem with JaCoCo -[INFO] [16:57:43.157] Sensor JaCoCoSensor... [INFO] [16:57:43.157] Project coverage is set to 0% as no JaCoCo execution data has been dumped: /var/lib/jenkins/.../target/jacoco.exec [INFO] [16:57:43.426] Sensor JaCoCoSensor done: 269 msAs a result, I'm getting 0% code coverage for my project. Couldn't find why jacoco.exec is not being created.I don't have "JaCoCo" configured to run by maven (in my pom.xml). I know that in the past the jacoco.exec was created anyway (probably by Sonar itself).What am I doing wrong? Do I need to configure JaCoCo in my pom.xml for it to work? Thanks.
SonarQube - no JaCoCo execution data has been dumped
You should check following parameters:Project keygenerated during maven build and generated on SonarCloud (or make sure that you setsonar.projectKeyproperty that was generated on SonarCloud).Check if provided Token value matching the one on SonarCloud (you can provide your own value on project setup page.
Hi I am automating code coverage on SonarCloud using Travis CI for aMavenapplication.Now, running thesonar:sonarcommand locally submits the report on SoundCloud and I can see it as shown below with BranchmasterNow I have also configured.travis.ymlfile to auto push the report toSoundCloudon each build as belowBut when build is triggered by Travis CI it fails with following error[INFO] Load project branches [INFO] Load project branches (done) | time=114ms [INFO] Load project pull requests [INFO] Load project pull requests (done) | time=116ms [INFO] Load branch configuration [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 27.884 s [INFO] Finished at: 2019-05-19T16:47:23Z [INFO] Final Memory: 93M/496M [INFO] ------------------------------------------------------------------------ [ERROR] Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.6.0.1398:sonar (default-cli) on project safenest-java-server: Project was never analyzed. A regular analysis is required before a branch analysis`I am new toSonarCloudand couldn't find much documentation to get help with this. Can somebody explain what exactlyA regular analysis is requiredmean? And how to fix this?Thanks in advance.
Travis CI SonarCloud error "Project was never analyzed. A regular analysis is required before a branch analysis"
This rule will have been configured with the expected header when it was added to the profile being applied to your project. You should check not the "Compliant Solution" but that configuration to see what's expected.Note that the header can be configured as a regex. Typically this is used to deal with copyright year variations, but you should double check whether it's being used as a regex as well.
I have even tried "Compliant Solution" given :/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2013 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * SonarQube is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */but it's not fixing the code smell. Can you please give me the working SIMPLEST EXAMPLE which can solve this?
How to solve "Add or update the header of this file." code smell in SonarQube?
Latest release of the SonarLint common library (used by most SonarLint flavors)unlock support of SonarTS. This is not yet officially supported in SonarLint for IntelliJ, but it will come.SonarLint requires at least SonarTS 1.5, and it seems your have SonarTS 1.1.0 installed on your SonarQube server. So basically SonarLint is asking you to update it, and will ignore the plugin.The classloader error should come from something else, but we need a stacktrace to better understand (look at SonarLint logs).
I'm trying to configure the SonarLint plugin (Version - 3.2.0.2350) on Idea Intellij (Ultimate Edition. Version: 2017.3.4, Build: 173.4548.28) but I get an error when trying toUpdate binding-**Analyzers not loaded**. The following plugins do not meet the required minimum versions, please upgrade them. typescript (installed1.1.0, minimum 1.5).Although I am still able to go ahead and Update the Project list, find my project and save the settings, whenever I try to Analyze any file, it saysCannot create ClassLoader. I do not have any separate Typescript plugin installed apart from theJavascript Supportplugin. And the updated to the latest version 1.0.Can anyone help with this ?
Unable to configure SonarLint plugin on Idea IntelliJ
I'm not really sure, whether this will work for Gradle plugun, but you may try.Sonar has a property to specify the name of the integration tests JaCoCo report. This property is calledsonar.jacoco.itReportPath(sonar.jacoco.reportPathfor unit tests report).And as far as I know, gradle sonar plugin let you add custom properties to it. So you can change IT report name via properties as follows:sonarqube { properties { property "sonar.jacoco.itReportPath", "build/jacoco/ integrationTest.exec" } }
I'm trying to integrate the sonarqube gradle plugin with the jacoco plugin:classpath 'org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:2.1'apply plugin: 'org.sonarqube' apply plugin: 'jacoco'My build/jacoco folder contains: integrationTest.exec test.execHowever, the sonarqube plugin only recognises the 'test.exec' file:18:20:45.130 INFO - JaCoCoItSensor: JaCoCo IT report not found: C:\Users\abc3\Downloads\sme-letter\target\jacoco-it.exec : 18:05:55.609 INFO - Analysing C:\Users\abc3\Downloads\sme-letter\build\jacoco\test.execHow do I get the sonarqube plugin to recognise 'integrationTest.exec'ThanksMark
sonarqube gradle plugin excluding jacoco integration tests
Not easily, and not without using reflection.Using reflection you could loop through the list of values and call the appropriate method in the client object. That would get rid of the complexity and be cleaner/more robust. However it would also perform slower.Fundamentally though you have the case where you are doing nearly but not quite the same operation over and over, that's always tricky.
I have the following method:private void setClientAdditionalInfo(Map map, Client client, User user) { Map additionalInfo = (Map) map.get("additionalInfo"); if (checkMapProperty(additionalInfo, "gender")) { client.setGender(additionalInfo.get("gender").toString()); } if (checkMapProperty(additionalInfo, "race")) { client.setRace(additionalInfo.get("race").toString()); } if (checkMapProperty(additionalInfo, "ethnicity")) { client.setEthnicity(additionalInfo.get("ethnicity").toString()); } .....12 more if statements are used in the similar way. The only difference being a different setter method name and a different parameter. Now, as the same pattern is repeated again and again, is there a way to reduce the code complexity?
Reducing the cyclomatic complexity of a java method