Response
stringlengths
8
2k
Instruction
stringlengths
18
2k
Prompt
stringlengths
14
160
The configuration file is, in my case, always in the application repository and then called from the jenkins job as $WORKSPACE/sonar-project.propertiesThe content of the file is (example):# Required metadata sonar.projectKey=<project-key> sonar.projectName=<project-name> sonar.projectVersion=<project-version> # Comma-separated paths to directories with sources (required) sonar.sources=src sonar.exclusions=src/vendor/**/* # Language sonar.language=php # Encoding of the source files sonar.sourceEncoding=UTF-8 sonar.php.coverage.reportPath=src/coverage-clover.xml #change path to location of your test report sonar.php.tests.reportPath=src/unitreport.xml #change path to location of your test reportIn Jenkins/Global tool configuration you must add a Sonarqube scanner, looks like this:And in the manage Jenkins/Configure system you must add your Sonarqube server "redacted Sonarqube" configured like this:In the job itself you have:def scannerHome = tool 'azure-tools-sonarqube' #This is the scanner you added withSonarQubeEnv('redacted Sonarqube') { #This is the server you added sh "${scannerHome}/bin/sonar-scanner" }
I am trying to build a Jenkins Pipeline job. I am trying to put sonarqube scanner configurations into Jenkins pipeline job's Groovy script.But when I build the above job I get the following error-Also when I refer to Sonarqube documentation for integrating with Jenkins Pipeline job I get no information about setting the sonarqube properties which otherwise we have to set by adding a step - "execute sonarqube scanner"Could anyone help in knowing how can we set the Sonarqube properties in jenkins pipeline job which otherwise we can specify in Maven or Freestyle Job Types in Jnekins (shown in above snapshot). Thanks.Now I have changes the Groovy script of Jenkins Pipeline Job configuration-Now I am getting the error -Could anyone please help me with the above issue.
Jenkins Pipeline Job Build
Go tohttp://yourserver:port/issuesand try to filter out exactly those issues, that you do not want to handle for the moment (probably using the "Language" or "Creation Date" filters are a good start).Then do a "Bulk Change" (link on top of the page) to get all of these issues out of your project's quality gate.Depending on your quality gate, this might mean to change the status of the issues from "open" to "confirmed", change their severity, or similar.Since this approach really depends on the quality gate configuration, it does not work in all cases.
I added two plugins to SonarQube version 6.3.0.19869 (css and web). Now all my projects fail on their quality gate.How can I get it to pass for the first time? I can't fix all old errors now. I want to fix only new issues.
How to make quality gate pass, although new plugins are added?
First thing:api/authentication/loginis of no help here. PerWeb API documentation, Web API authentication is made through HTTP basic authentication.So just pass the username/password in the header of each Web API request. And if you useUser Tokens, as persame documentation:This is the recommended way. Benefits are described in the pageUser Token.Token is sent via the login field of HTTP basic authentication, without any password.
I havemigratedmy Sonar version from5.4to6.3.1. In 5.4 version, there was no login API provided by Sonar. Hence we were adding an Authorization header in every call with value as Base64 encoded "username":"password".But post migration to 6.3.1, the authorization fails with current implementation.We tried passing token (generated from UI) as value of Authorization header but in vain.We also tried calling Sonar login API (api/authentication/login) but it is not giving back any response.Kindly help us resolve this issue.Thanks.EditFollowing is the code for calling REST Webservice:byte[] encodedUsernamePassword = Base64.getEncoder().encode("adminUserName:adminPassword".getBytes()); ResteasyClient client = new ResteasyClientBuilder().build(); String target = "http://IP:Port/api/issues/search/?statuses=" + "CLOSED" + "&assignees=" + username + "&resolutions=" + "FIXED" + "&createdBefore=" + end_date + "&createdAfter=" + start_date + "&facetMode=debt"; javax.ws.rs.core.Response response = client.target(target).request(MediaType.APPLICATION_JSON).header("Authorization", new String(encodedUsernamePassword)).get(); String strResponse = response.readEntity(String.class);
Authorization in Sonar REST/Web API
Perdocumentation of theSonarQube Scanner for MSBuild(which is the scanner to be used for analysing C#/.Net projects in SonarQube) :Analysis of ASP.NET vNext projects (i.e. project.json) is currently not supported, refer toSONARMSBRU-167[EDIT] .Net Core projects now supported sinceScanner for MSBuild v2.3(which itself is already old, so just grab the latest)
Anyone has any idea on whether ‘.Net Core’ (with .xproj extention) projects are supported by Sonarqube v4.x or v5.x (C# plugin version 5.2)?Though there is no error message in SonarQube Scanner log file, all our .xproj files are listed under “Skipped projects” in ProjectInfo.log file and dashboard is showing results only for .csproj files and not for any .xproj files.Thank you for the your response for this
Sonarqube support for ‘.Net Core’ (with .xproj extention) projects
Sensor itself describes when it should be executed - seehttps://github.com/SonarSource/sonar-java/blob/4.5.0.8398/java-jacoco/src/main/java/org/sonar/plugins/jacoco/JaCoCoSensor.java#L65andhttps://github.com/SonarSource/sonarqube/blob/6.2.1/sonar-plugin-api/src/main/java/org/sonar/api/batch/sensor/SensorDescriptor.java#L37-L42
I have following situation - in Teamcity I set up two builds for sonarFirst - by use ofmaven sonar:sonarSecond - with special teamcity step "SonarQube"In the second case I see in sonar logs that it run Jacoco sensors, but in the first case, when running from maven, Jacoco sensors did not start.So, I have a general question about this situation - who controls which sensors will be started for a build? Is it some environment variables that I should setup for maven, or is it somehow controled by SonarQube server?
How does SonarQube knows which sensors to run for build?
It has been marked as deprecated with no replacement.Quoting pagehttp://docs.sonarqube.org/display/SONARQUBE43/Analysis+Parameters:Note that only parameters set through the UI are stored in the database. For example, if you override the sonar.profile parameter via command line for a specific project, it will not be stored in the database. Local analyses in Eclipse, for example, would still be run against the default quality profile.And the latest version of the same pagehttp://docs.sonarqube.org/display/SONAR/Analysis+Parametershas link to ticket about deprecation that contains other details -https://jira.sonarsource.com/browse/SONAR-5370In other words - profile should be configured via UI or using web services.
I am looking for a Sonar Property to attach the quality profile during the build. In previous versions of Sonar there was a property -Dsonar.profile which is deprecated now. Can anyone please help me to get the property to attach the quality profile at runtime.I am using Sonar version 4.5.7. Any help is highly appreciated.Thanks, Sanjiv
Why property "sonar.profile" marked as deprecated?
Sonar is complaining that you shouldn't use mutable state, but you don't want to follow that advice. Your options thus are: ignore the warning or follow the advice even if you don't want to. Following the advice doesn't mean slapping 'final' in there (as it doesn't make sense in this context), but redesigning your code to be better.You canignore using suppresswarnings already explained. If you want to follow the advice, you need to redesign your piece of code in a different way.We don't know your code beyond what you've posted, so we cannot say how exactly you should redesign it. However, doing that is recommended. As to why, you can read up on it here:Why is Global State so Evil?
I have the following piece of code in my program and I am running SonarQube 5 for code quality check on it after integrating it with Maven. I am facing this errorMake this "public static processStatus" field final.Make this "public static processStatusId" field finalBut I don't want to make this as final. Is there any other solution?public abstract class ProcessStatusListPO_ { private ProcessStatusListPO_() { } public static volatile SingularAttribute<ProcessStatusListPO, String> processStatus ; public static volatile SingularAttribute<ProcessStatusListPO, Long> processStatusId ; }
Sonar asking to Make this field final
So this is a little old but I thought I would go ahead and answer for the future. the columns are12345For this I believe setting your indentation to 2 and reformatting should fix everything.
I am fixing all the sonar violation fix and I have nearly 6k issue likeMake this line start at column 9"issues. I tried adding the java formatter, but it did not resolve the issue instead increase my sonar violation to 9k. Can you please let me know which java formatter to use so it will complaint.<plugin> <groupId>net.revelc.code</groupId> <artifactId>formatter-maven-plugin</artifactId> <version>0.5.2</version> <executions> <execution> <goals> <goal>format</goal> </goals> </execution> </executions> </plugin> or <!--Plugin for formatting the code base --> <plugin> <groupId>com.coveo</groupId> <artifactId>fmt-maven-plugin</artifactId> <version>1.0.0</version> <executions> <execution> <goals> <goal>format</goal> </goals> </execution> </executions> </plugin>I have tried both of these formaters, both did not resolve the issue instead increased the issue. The rule for this says Source code should be indented consistently. The formatter is taking care of this already not sure why this violation is happening. The rules says the indent should be consistent and it is consistent.
Make this line start at column 9 sonar violation fix(Source code should be indented consistently)
TheJPAstatic metamodel ("_") classes are generated by yourJPAprovider, not by you. They follow exactly what the JPA spec says to include (and there is no "final" there). Not including "final" makes perfect sense because those variables need initialising, and are not initialised by included code.
I have a JPA static metamodel class which is as follows-@StaticMetamodel(Test.class) public class Test_{ public static volatile SingularAttribute<Test, String> id; public static volatile SingularAttribute<Test, String> name; public static volatile SingularAttribute<Test, String> description; public static volatile ListAttribute<Test, Property> property; }I am usingsonarqubeto improve my code quality and it suggested that I have to changepublic static id to field finalfor above member variables.Can anyone suggest that should I change these variables to final?
Can we declare member variable of JPA static metamodel class as a final?
You can't see previous analysis values. SonarQube 4.5.5 only stores the current measure value and its differentials.
We are using sonarqube 4.5.5, could someone please tell me how do I see my past reports from few days back like at the specific date. In the drop down I can only see delata from yesterday and 10 days back.
how do I see sonarqube time machine reports for a specific date in past
Answering my own question. Just add a //NOSONAR comment to the line.import com.sun.mail.smtp.SMTPMessage; //NOSONAR
I'm trying to suppress a rule on an importimport com.sun.mail.smtp.SMTPMessage;apparently doing the following on the class does not work@SuppressWarnings("squid:S1191")any suggestions? Using SonarQube 5.3
How to suppress SonarQube rule on import-statement?
Simply setSONAR_RUNNER_OPTSas an environment variable (documentation).
I am trying to use SonarQube to analyze a rather big project. I ran into an issue where it tells me I don't have enough memory so I set out to figure this out. I understand that I need to increase the amount of memory that Java can use, but I don't understand where it wants me to set the variable "SONAR_RUNNER_OPTS". It keeps telling me it's not set so it defaults to 1024. But that obviously wasn't enough.So I ask, where do I set this variable? The variable appears to exist in the sonar-runner.bat file in my...\.sonarqube\bin\sonar-runner\binfolder but changing it doesn't do anything as theMSBuild.SonarQube.Runner.exedeletes those files straight away to make them again, when I do theMSBuild.SonarQube.Runner.exe endcommand.What do I do?
Where do I set the SONAR_RUNNER_OPTS?
Technical Debt is a core feature of SonarQube, so there's no reason why it should be possible to remove it from the main "pages" of the SonarQube web application.If you want to hide this, you should first ask yourself why. Indeed, technical debt was not invented by SonarQube, this is a famous and widely spread concept that has been there formore than a decade. With this concept come good practices for software development. So again, trying to hide this in SonarQube is a bit weird.Also, I highly discourage you to fork the code of SonarQube and write your own version just for this. Think 2 seconds how difficult it will be for you to maintain your fork, and I'm sure you will forget this idea as fast as it came to your mind.
I understand that the Technical Debt metric became part of SonarQube after it was a plugin, but I would like to remove it from the dashboard completely, and only show other metrics. Is that possible from the dashboard settings? if not, I appreciate any directions on what parts of the source code have to be edited.
Is it possible to hide the Technical Debt metric from SonarQube dashboard, entirely?
There is a reason why these additional ruleset files are created. Well actually there are multiple:That is to allow you to set a baseline to which all projects must adhere, but the enable additional rules for projects with specific types of code. You may have a couple MSOCAF rules enabled that are specific to Sharepoint projects, which don't make sense for your Unittest or Windows Service projectsSay, when you are fixing technical debt in your projects, you can set a baseline for the whole solution and that slowly tighten the rulesets of the individual projects so that you can focus your cleanup effort on a specific project. Instead of having to clear up a specific rule or set of rules across all projects in the solution at the same time.One of the project ruleset files will be overwritten each time you sync with SonarQube. The other one will remain as you've left it. Allowing you to save your customizations and still allowing you to safely sync changes to the SonarQube baseline.If I'm remembering this correctly, the Solution ruleset is included in the project ruleset as is the ruleset in which you store your customizations. Currently I don't have a SonarQube server at hand to verify which ruleset file server which purpose, but this is the reasoning behind it.
We are currently in the process of evaluating the use of SonarQube/SonarLint for our .NET applications. We are pretty happy with what we've seen so far (and, btw, kudos for bringing SonarQube this far - I've used it a couple of years ago for my PhD project, and it has improved greatly since then!).However, one thing was a bit surprising: When I connected my SonarLint instance to our SonarQube server (which worked just fine) and started syncing the bound project, SonarLint started to download nuget packages (which was kind of expected) and then created one or even two .ruleset files for each project of our solution (in addition to a fileSonarQube/<solution name>CSharp.rulesetwhich I assume is the solution-wide ruleset).What I expected and would prefer is only the single ruleset valid for the complete solution (and possibly the option to override that ruleset for projects where this makes sense (e.g., test projects)).Is this behavior possible at all, i.e., did I miss anything? Documentation is the only area I've identified so far where SonarLint is lacking.
SonarQube/SonarLint/Visual Studio: Use one ruleset fo all projects in solution
You can safely mark this violation as afalse positiveand enter a descriptive comment. This kind of false positive should be rare enough to allow you to treat them individualy, and act accordingly - AoP API is a good example, legacy and/or badly written libraries is another. But do NOT add the files to exclusions, as you would loose other rules from the Sonar analysis
Sonarqube defines a rule sayingGeneric exceptions should never be thrown(i.e. throw a dedicated exception instead of using a generic one.) However AOPProceedingJoinPointalways throws genericThrowableand normally I am not interested in the exception at all and just throw it from the method like this:@Around(...) public void someMethod(ProceedingJoinPoint point) throws Throwable { // do something... point.proceed(); // do something else... }Obviously this is against the above-mentioned Sonarqube rule. Do I really have to wrapper it with try catch and log the throwable or something? What is the best practice on this?
Sonarqube treat AOP Throwable as an issue
Design information have been removed in version 5.2. Seehttp://www.sonarqube.org/sonarqube-5-2-in-screenshots/for more details.
We have SonarQube up and running, and it's producing a nice dashboard with a lot of general info.Sections like Duplications and Unit Tests Coverage have both dashboard info, and detail info you can drill down to.Drilling down from Package Tangle Index, Cycles, Between Packages, and Between Files just gives the number listed in the dashboard. So, something has done the analysis, but the details have not made their way into the database. I can see from this 2010 article that Sonar does have a facility for displaying details:http://www.sonarqube.org/fight-back-design-erosion-by-breaking-cycles-with-sonar/Does anyone know how to get the Package Tangle Info details to display?Thank you
SonarQube missing Package Tangle Index and Dependencies drilldown information
The answer is the solution stated in the relatedSonarQube 5.3 Background Task Fails with No Log in Dashboard. There were several SonarQube servers, which I was unaware of when I originally posted, accessing the same database. When those other instances were shut down there were no more failures in the background tasks.
It seems that over half of the time I try to execute analysis using Sonar Runner 2.4 on several different projects that the analysis completes successfully but the publish (via the background task) to SonarQube fails. There is no log that I can find with relevant information on the SonarQube server for the failed tasks - at least I can't find any. I am new to SonarQube. The SonarQube 5.2 server is on Windows Server 2012 R2 using SQL Server 2012(SP1) database.
sonarqube 5.2 background tasks sometimes fail with no log
By default, SonarQube comes with a predefined Quality Gate that is designed to achieve exactly what you want: progressively make you increase your code coverage.You can take a look at this"SonarQube way" quality gate on Nemo.The important line is the one which is highlighted on the screenshot. It means: "The code introduced since the beginning of developments on the current version must be covered at least at 80%". If you admit that you are constantly refactoring and rewriting parts of your code, then ultimately your code will be covered at least at 80%.
To motivate ourselves to increase code coverage of unit tests, we have defined this rules for coverage:overall code coverage must be > 80%overall code coverage must not be less than the last timecode coverage on new code must be > 90%To fulfill rules 1 and 2 I configured a Quality Gate with these conditions:"Coverage - value - is less than - 80""Coverage - delta since previous analysis - is less than - 0"For rule 3 I think that the following condition would meet it: "Coverage on new code - value - is less than - 90". But it is not possible to choose a value for this condition, only a delta. What is the meaning of a delta here? New code shouldn't have a delta, because it's new. How must i configure the condition to fulfil rule 3?
How to configure SonarQube to make us increase the coverage?
In trying to revert things I figured this one out.The very first time we ran the CI changes we had failed to update the project keys first. In all the attempts to fix via restores/retries all we did was reimport the database backup. The culprit was the Elasticsearch cache. The duplicates only existed in the context of the ES index due to the initial failure to update the keys first.In the end, I ended up deleting the<sonar>/data/es, restoring the database, updating the project keys, and the running the analysis via CI.
SituationI am running Sonarqube 5.2. Due to changes with how we run Sonarqube via CI, I needed to update my project keys. This is a Maven-based Java project (i.e., submodules). The key changed was to simply add the branch to the key for the parent and all sub-modules. After updating all the keys I ran the new CI job.ProblemAfter doing so our unresolved issue count went from 223 to 883. Strangely enough, the projects dashboard still displays 223. However, if click that 223 issue count link to drill into them the number jumps to 883.If I use the default "My Issues" filter it says I have 74. If I try to navigate/view each one of them I can't get past 11/74 (I click but the paging control just flashes yellow).What doesn't workSince I can't delete these mysteriously inaccessible issues I thought I'd mark them all as "Won't Fix". However, attempting this has no impact on the "Unresolved" issues/count. Viewing sonar.log the POST to make the change returns a 200.QuestionIs there anything I am missing within the web application that can address this. Or is there any SQL I can run?FWIWI subsequently did the same process for a Javascript project with any issue duplication
Sonarqube: How to get rid of duplicate issues?
This is indeed a bug in android lint sonar plugin 1.1, see the ticket associated with this issue :https://jira.sonarsource.com/browse/SONARANDRO-38This should be fixed in version 1.2 of the sonar android lint plugin.
I have an gradle android build using android build tools version 1.3.1 and run lint checks on my code. When running the sonar task (provided by the org.sonarqube gradle plugin) the sonar lint plugin (org.sonar.plugins.android.lint.AndroidLintSensor) fails when reading the lint-result file with the following error:2:35:44.278 [Daemon worker] ERROR o.s.p.a.lint.AndroidLintProcessor - Exception reading /Users/Rene/dev/gradleware/clients/bosch/trials/MyAndroidApplication/app/build/outputs/lint-results-freeRelease-fatal.xml org.simpleframework.xml.core.ValueRequiredException: Unable to satisfy @org.simpleframework.xml.ElementList(inline=true, entry=, name=, data=false, empty=true, required=true, type=void) on field 'issues' java.util.List org.sonar.plugins.android.lint.AndroidLintProcessor$LintIssues.issues for class org.sonar.plugins.android.lint.AndroidLintProcessor$LintIssues at line 2 at org.simpleframework.xml.core.Composite.validate(Composite.java:644) ~[simple-xml-2.7.1.jar:na] at org.simpleframework.xml.core.Composite.readElements(Composite.java:449) ~[simple-xml-2.7.1.jar:na] at org.simpleframework.xml.core.Composite.access$400(Composite.java:59) ~[simple-xml-2.7.1.jar:na]The lint xml itself looks like this:<?xml version="1.0" encoding="UTF-8"?> <issues format="4" by="lint 24.1.2"> </issues>I'm using sonarqube 5.2 with android sonar plugin 1.1 installed. Is this a known issue? or is there a workaround available?
sonar lint plugin fails reading lint-results.xml
You must use a single quality profile to analyze all projects within your solution. Indeed, only a single quality profile is used during a SonarQube analysis. In theory, you could create two quality profiles in SonarQube, and run two SonarQube analysis (one for example on all product code, and another one on all test code), but this requires some manual setup on your side.Regarding custom rules, they are supported: You need to create them in SonarQube web interface from the "Template for custom FxCop rules" rule template, and then enable the newly created custom rules in your quality profile.
I have a question regarding FXCop analysis using SonarQube with the MSBuild-Runner. I have realized that the MSBuild-Runner loads a rules file from the server which matches the quality profile in Sonar and uses that file for the FXCop run.In our project we have a solution with several projects. For each project a rules file is configured depending on its type e.g. product or test code. We also use custom rules in own FXCop assemblies.How can I configure MSBuild-Runner so that he uses the rules file which is configured in the project file? How can I add our custom rules into Sonar? Can I import our rules files somehow?Thanks for your help!
SonarQube MSBuild-Runner use custom FXCop rules from project file
From what I can see in your logs, you are running the analysis in "preview" mode:... -Dsonar.analysis.mode=preview ...As you can read on thedocumentationabout preview mode:The source code is analyzed but the measures and issues are not pushed to the SonarQube database. Therefore, they cannot be browsed through the web interface.So this is normal that you only get aANALYSIS SUCCESSFULmessage without the related SQ URL (because results are not pushed to the server in preview mode).
on the main page of a Jenkins job, I see the SonarQube icon, which should be a link, but it's just text:I use...Jenkins 1.596.2 (also tried 1.609.1)Jenkins SonarQube-Plugin 2.1 (also tried 2.2.1)Maven 3.3.1sonar-maven-plugin:2.6 (when configuring SonarQube post build action)sonar runner 2.4 (when configuring SonarQube analysis build step)After browsing the source code of the jenkins sonarqube-plugin, I found thatSonarUtils.extractSonarProjectURLFromLogs()seems to be broken. It parses the console output for the regexp "ANALYSIS SUCCESSFUL, you can browse (.*)". My console output never prints this line. It just prints "ANALYSIS SUCCESSFUL".Is this a known issue?
Link to SonarQube on Jenkins job not available
SonarQube does not officialy support ARM processors, that's why there's nosonar.shscript for ARM.What's more, I know some guys tried to make it work, but they failed.Thread 1Thread 2Still, you can try again and write a simple script so start SQ:#! /bin/sh java -jar lib/sonar-application-5.1.jarJust put this script in the SQ intallation root directory, run it, et voilà!(if SonarQube starts but has other errors, please open another question)
I'm trying to install sonarqube in a Synology Diskstation DS112j with an ARM Processor.Insonarqube-5.1/binfolder there's only batch files for linux-x86-32/64 bits so I can't start sonarqube due to this error/var/services/sonarqube-5.1/bin/linux-x86-32/./wrapper: line 1: syntax error: unexpected "(" Failed to start SonarQube.Is there any sonar.sh for ARM or any workaround to install sonarqube in an ARM diskstation?
Does sonarqube 5.1 support ARM?
The versions you specified are not compatible for running sonar analysis.Please upgrade SonarQube version (current is 5.1.1) which requiresJava 1.7-1.8 SonarQube 5.0 or 5.1.1 Sonar-runner 2.4
I am trying to run sonarsonar:sonarby integrating sonarqube and jenkins. While doing, am getting the below error.[ERROR] Failed to execute goal org.codehaus.mojo:sonar-maven-plugin:2.6:sonar (default-cli) on project iwm_common: Can not execute SonarQube analysis: org.slf4j.impl.SimpleLoggerFactory cannot be cast to ch.qos.logback.classic.LoggerContext -> [Help 1]Jenkins version - 1.612Sonarqube version - 3.6JDK-1.7.0_76Maven - 3.1.1Jenkins WAR is deployed in server A and sonarqube is deployed in server B. I have not installedsonar-jenkinsplugin in Jenkins.Can anyone let me know whethersonar-jenkinsplugin is mandatory to be installed in jenkins to integrate jenkins with any sonar server (eg:sonarqube).If the answer isYES, then after installation of the required plugin, will adding the sonar server (eg:sonarqube) information underManage Jenkins -> Configure system -> sonarresolve the above error ?The error is related tosonar-maven-pluginand this plugin is not used in any of the project's pom.xml. Can anyone please explain whether this plugin gets referred as a part ofsonar:sonargoal. Thanks.
Integrating sonarqube with Jenkins
It's not recommended, as Mithfindel already advised.Simply replace dots and semi-colons with underscore.Code sample:documentClient.deleteDatabase("dbs/" + DATABASE_ID, null);The resulting comment without the warning would be:// documentClient_deleteDatabase("dbs/" + DATABASE_ID, null)_
I was wondering if there is a way to trick sonar into neglecting commented out code while still keeping it inside. I would like to leave the snippet of code in there for modifications at a later date but would also like to increase compliance.I have this for example// bdgItems.setGpIncrease(zero);and this is where i get compliance issuses. on the other hand regular comments like// get data pointsis no cause for issue. I'd like to keep the commented code in there to pick up where I left off in the next cycle of development, but like i said, reduce the issues. Ive tried a few ways in tricking it like// [DELETE THIS] bdgItems.setGpIncrease(zero);or// bdgItems . setGpIncrease ( zero );with spaces in between words but it still knows! I was wondering if some of you vets knew any tricks [i'm fairly new to sonar].Thanks in advance!
Trick sonar into ignoring commented code
The control-flow graph of your example contains 5 edges (E), 5 nodes(N) and one connected components (P).According to the defintion of the complexity (M=E-N+2P) the correct complexity value is 2.
I use SonarQube for a Java project but the complexity calculation is not clear for me. The complexity value is 3 for the following example:public boolean even(int i) { if (i % 2 == 0) { return true; } return false; }According to theUser Guidethe complexity is calculated as follows: “It is the cyclomatic complexity, also known as McCabe metric. Whenever the control flow of a function splits, the complexity counter gets incremented by one. Each function has a minimum complexity of 1.” In the detailed description it is mentioned that the return statement increases the complexity value by one (if it is not the last statement in the method). I do not understand why the return statement splits the control flow. In my opinion, there is only one possible way after every return statement in the control flow.
Why does the return statement increase the complexity?
'Unused private fields should be removed' is the message generated by the internal SonarQube rulesquid:S1068, whereas your@SuppressWarningsannotation disables the matching (and deprecated) PMD check.You might want to check your quality profile, eventually disable this rule, or put some exclusions for the Lombok augmented classes.
After upgrading SonarQube from 4.0 to 4.2, I got a bunch of 'Unused private fields should be removed' errors from the classes with Lombok annotations.I have@SuppressWarnings("PMD.UnusedPrivateField")declared at the beginning of all those classes. It worked fine when I was using SonarQube 3.7 and 4.0.I usemvn sonar:sonarto generate the SonarQube report.And this shows how my class look like:@Data @SuppressWarnings("PMD.UnusedPrivateField") public class MyClass { private String field; }How can I get rid of those errors in version 4.2? Thanks.
sonarqube 4.2 and lombok
Unfortunately, there's no way to mute this INFO-level log.
I have a Maven 3.x build that uses Sonar 2.1.x for quality control. The maven-sonar plugin is used from inside Jenkins to run the Sonar checks. During the Jenkins build, when Sonar kicks in, it logs A LOT of not so useful information at INFO level:[INFO] [15:29:14.195] Java version: 1.6 [INFO] [15:29:20.853] Execute PMD 4.3 done: 6658 ms [INFO] [15:29:20.853] Sensor PmdSensor done: 6658 ms [INFO] [15:29:20.854] Sensor ProfileSensor... [INFO] [15:29:21.186] Sensor ProfileSensor done: 332 ms [INFO] [15:29:21.187] Sensor ProfileEventsSensor... [INFO] [15:29:21.190] Sensor ProfileEventsSensor done: 3 ms [INFO] [15:29:21.190] Sensor ProjectLinksSensor... [INFO] [15:29:21.192] Sensor ProjectLinksSensor done: 2 ms [INFO] [15:29:21.192] Sensor VersionEventsSensor... [INFO] [15:29:21.198] Sensor VersionEventsSensor done: 6 ms [INFO] [15:29:21.198] Sensor Maven dependencies... [INFO] [15:29:21.261] Sensor Maven dependencies done: 63 ms ...The log is quite big. I have been trying to find a way to set the log level to WARN with no luck. Any idea?Thanks!
Reduce log level in Sonar 2.1.x
Add the following to your machine.config located at C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config<runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="Microsoft.VisualStudio.QualityTools.CommandLine" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <bindingRedirect oldVersion="10.0.0.0" newVersion="11.0.0.0"/> </dependentAssembly> </assemblyBinding> </runtime>Then you will need to add a registry key called InstallDir with a value of "InstallDir => C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\" to the following location HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\10.0Then run the following command regsvr32 "C:\YourSonarInstalation\opencover\x86\OpenCover.Profiler.dllThe issue is being discussed here. The potential solution above was posted a few days ago.https://code.google.com/p/mb-unit/issues/detail?id=899
I've got an annoying issue with Gallio when I try to analyse my VS2012 C# solution with my sonar-runner. When Gallio try to launch my unit test I can find this issue in the logs :[error] Assembly XXXX Cannot run tests because MSTest executable was not foundI've already tried some propositions of solution exposedhereandhere(I have installed Agents for VS 2012 and I have added a registry key with the path of my VS2012 installation) but nothing seems to work.Thank you by advance for your help.EDIT :It seems that this issue come from an hard coded registry value in Gallio source code because when I try to add the InstallDir registry key for VS2010 to point to my VS2012 installation I can see a new error message.This new error is an I/O Exception relative to the following DLL : "Microsoft.VisualStudio.QualityTools.CommandLine.dll" version 10.0.0.0 which I'm able to find in my GAC_MSIL directory but in version 11. My conclusion is that Gallio isn't fully compatible with VS2012 and the corresponding version of MSTest.I'm going to investigate to find a way to manually generate Unit testing reports that Sonar will be able to store.EDIT 2 :There is finally no way to collect mstest reports in sonar for now. The only solution I found is to convert every unit test made with MSTest into an NUnit test to be able to run it with gallio and gather the results in my Sonar server.
Gallio error : MSTest executable was not found
As it turns out, three years after asking the question I find thatsquid:SwitchLastCaseIsDefaultChecknow checks for complete coverage of anenum. Probably has for some time now, at least for 4.4.0.8066 of the Java plugin from Sonarqube I can confirm that. And that’s a very satisfactory answer for me.
To me, the following Java code is perfectly valid, good style:enum Side { LEFT, RIGHT }; ... Side side = ...; switch (side) { case LEFT: // do something break; case RIGHT: // do something break; }For SonarQube’s ruleSwitchLastCaseIsDefaultCheck, this is not good enough, it wants a default case. Now here, a default case is superfluous, since the enumeration is covered completely.For enumerations, I would like to see a test that checks whether the enumeration is completely covered and complain if it is not coveredandhas no default case (Eclipse can do that). Either should be fine. In fact, completely covering an enumeration allows for a compile-time warning later when the enumeration is extended, while giving a default case will fail only at run-time.Optionally, both completely covering the enumeration and giving a default case could trigger a warning for unreachable code.
How to deeply analyze Java switches over enumerations with SonarQube
you can try this way: sonar_web.xml add following code<property key="sonar.sourceEncoding" value="utf-8" />refer to :https://stackoverflow.com/a/15537832/2193246
I use sonar to check jquery code, but it always throw an exception:C:\Documents and Settings\user\.jenkins\workspace\ksp2\ant\sonar_web.xml:31: com.sonar.sslr.impl.LexerException: Unable to lex url: file:/C:/Documents%20and%20Settings/user/.jenkins/workspace/ksp2/WebContent/js/post/viewEditRevisions.js Caused by: com.sonar.sslr.impl.LexerException: Unable to lex source code at line : 197 and column : 42 in file : file:/C:/Documents%20and%20Settings/user/.jenkins/workspace/ksp2/WebContent/js/post/viewEditRevisions.js Caused by: java.lang.IllegalStateException: None of the channel has been able to handle character '"' (decimal value 34) at line 197, column 42 at org.sonar.channel.ChannelDispatcher.consume(ChannelDispatcher.java:87) at com.sonar.sslr.impl.Lexer.lex(Lexer.java:126)I don't know why. my jquery file is too long, and it throw exception at this line:var postTemplate = '<h3><div class="title">'+data.postResult.title+'</div></h3><p>'+data.postResult.contentPreview+'</p>'+postTags;I was so confused, I have set encoding as UTF-8, but it still throw exception.
sonar check jquery code error
I was missing the/Cfrom the build args element, so I got this working with:<exec> <executable>c:\Windows\System32\cmd.exe</executable> <baseDirectory>BuildAssets</baseDirectory> <buildArgs>/C %SONAR_RUNNER_HOME%\bin\sonar-runner</buildArgs> <buildTimeoutSeconds>$(slowBuildTimeout)</buildTimeoutSeconds> </exec>
I have setup Sonar and want to run the code analysis as part of my nightly build.I've setup the nightly build but I'm having some issues with running the sonar runner.To run code analysis I want to navigate to a folder I've created called \BuildAssets, inside the main solution folder. To run the code analysis manually I would open up a command prompt within \BuildAssets and run:%SONAR_RUNNER_HOME%\Bin\sonar-runner.batHow would I set this up in CCNET?I've tried:<exec> <executable>%SONAR_RUNNER_HOME%\bin\sonar-runner.bat</executable> <baseDirectory>BuildAssets</baseDirectory> <buildTimeoutSeconds>$(slowBuildTimeout)</buildTimeoutSeconds> </exec>but this doesn't work because it tries to runc:\cc\myBuild\code\BuildAssets\%SONAR_RUNNER_HOME%\bin\sonar-runner.batI also tried:<exec> <executable>cmd</executable> <baseDirectory>BuildAssets</baseDirectory> <buildArgs>%SONAR_RUNNER_HOME%\bin\sonar-runner</buildArgs> <buildTimeoutSeconds>$(slowBuildTimeout)</buildTimeoutSeconds> </exec>but this doesn't seem to do anything either. I'm sure it's pretty easy but I'm not well versed in CCNET configuration.
Calling .bat file from specific location with CCNET
Like Oers suggested on my question comments if you are using ANT as a build script in your CI server (Jenkins in my case) you will have to use the SONAR-ANT-TASK to generate Sonar reports, do as follows:Download MySQL or any other Sonar supported RDBMS such as Postgres, Oracle, etc..'Download and Install sonar server.go to (sonar installation folder)/extras/database/mysql and run the create_database.sql script.I had to run an extra sql statement in my case using mysql, you can see hereUnable to access Sonar MySQL database Caused by: java.sql.SQLException: Access denied for user 'sonar'@'glassfishdev.ccs.local' (using password: YES)Start Sonar by typing ./sonar.sh startAdd the sonar ant task to your build script. You can follow this templatehttp://docs.codehaus.org/display/SONAR/Analyse+with+Ant+Task+1.0DO NOTcheck the sonar check box in your Configure screen if you have the Hudson Sonar plugin for installed, as this plugin only works with Maven projects.Click the "Build Now" button. If everything above has been done correctly you should be able to see the reports athttp://ipaddressofmachinesonarisinstalled:9000/Hope this helps, -Dario
ProblemI have just installed the Sonar Jenkins plugin. I went into my configured job (a free style job) that produces a WAR file artifact through an ANT build and did as follows:Check the Sonar checkbox. (No problems here)Configure the install dir of sonar (No problems here)Checked the checkbox that states:"Check if this project is NOT built with maven 2"(I am confused here)I have checked that box because I am not using maven for build, I am using ANT but it still asked me for required properties that resemble a lot MVN such as: Organization id, project id, project name, project version, source directories... etc..So I have filled those as well. When I click the play button "Build Now" the build seems to be running fine as it always had prior to sonar installation but it fails at the very end because its trying to execute MAVEN.See as follows:$ mvn -f /root/.jenkins/jobs/HRDA/workspace/pom.xml -e -B sonar:sonar FATAL: command execution failed java.io.IOException: Cannot run program "mvn" (in directory "/root/.jenkins/jobs/HRDA/workspace"): java.io.IOException: error=2, No such file or directoryQuestionsWhy is Sonar trying to execute Maven if I have checked the box that said check this box if you doNOTuse Maven 2?Can I make use of this Sonar plugin if my apps are built with ANT, GANT, GRADLE?Do I have to reconvert my apps to use MVN builds?Thanks, - Dario
Sonar plugin not working for projects that use ANT as a build script
Yes, you just need to write a maven or ant script to check out the latest from SVN first, then run the sonar:sonar command.It looks like Sonar forces you to create a pom.xml file and install maven2, even for a non-mavenized project:http://docs.sonarqube.org/display/SONAR/Analyzing+Source+Code(fyi - Sonar is dead easy with a mavenized project, but in any setup the key will be in getting in the habit of looking at and using the results of Sonar to improve development. That's the hard part.)
It is possible to take the source code directly from a svn repository and analyze it with sonar? Or configure sonar just to run a Checkstyle or pmd plugin for certain sources? I need to do this on non-maven projects.
Analyze source code with sonar
So i managed to do it. In the "Begin" command i was missing the directory where the file will live. And also on the "Test" command i was missing the output directory to match the fist one. After that i was able to upload the file as you can see in the image.I have just a problem since i have to point to the exact file and this is not dynamic at all, each time i have to edit the command to point to the correct file locationMy commands now are:dotnet sonarscanner begin /k:"myKey" /d:sonar.login="myToken" /o:"myOrg" /d:sonar.cs.vscoveragexml.reportsPaths="C:\TestResults\DotnetCoverage.coveragexml" dotnet build "pathToSLN" dotnet test --collect "Code Coverage" --results-directory "C:\TestResults" CodeCoverage.exe analyze /output:"C:\TestResults\DotnetCoverage.coveragexml" "C:\TestResults\c887677b-b89e-4222-93e4-09e563b48b7a\randomGeneratedFileName.coverage" dotnet sonarscanner end /d:sonar.login="myToken"so as you can see, when i run the code coverage command i have to match the new directory the file was created following ../guidId/randomGeneratedFileName.coverage
i'm new to sonar cloud and my company implmented it in AzureDevOps Pipeline. The problem we are facing is that, to know our code coverage we have to create a pull request and build the solution in devops for the code to get analysed.So i'm trying to do this locally, i installed SonarQube and SonarScanner and when i run the commands provided by sonarQube documentation it runs without problems, but when i check the sonarcloud page my project as 0% code coverage. I think i am missing one step in the commands i run but i am not able to find the solution.The commands i run are:dotnet sonarscanner begin /k:"project-key" /d:sonar.login="myToken" /o:"myOrg" dotnet build "myPathTo .sln" dotnet test --collect "Code Coverage" (this step creates the .coverage file in my UnitTest project) dotnet sonarscanner end /d:sonar.login="myToken"After the commands the page gets updated but not with code coverageCan you guys help me with the missing step?Thanks in advance
How to send .coverage file to SonarCloud
You were apparently requesting the use of installation "sonarqube", but the configured name is "SonarQubeScanner". Those don't match. I also note that calling it "SonarQubeScanner" is not quite right. That is an installation of SonarQube, not the scanner. It doesn't make sense to use the same name for SonarQube installations and SonarQube scanners. They are different things.
I installed Sonarqube plugin in Jenkins, already configured the sonarqube server and sonarqube scanner from the Jenkins configuration:but when I ran the pipeline I got this error:ERROR: SonarQube installation defined in this job (sonarqube) does not match any configured installation. Number of installations that can be configured: 1.Here is the configuration:What causing the error above?
Sonar-scanner in jenkins error does not match any configured installation
The problem that Sonar points as is that the non-transactional methodcleancalls transactionalexecute. Therefore the@Transactionalannotation onexecuteis ignored and the method will not get executed in the transactional mode.You have to annotate eithercleanmethod or the whole class [email protected] the class itself has to be registered as a Spring bean using for example@Serviceor@Copmonent, otherwise the proxy wrapper bean will not be created for such class.Read more at:Spring - @Transactional - What happens in background?
I'm struggling with sonar issue:squid:S2229 "Methods should not call same-class methods with incompatible "@Transactional" values"I'm not sure how am I supposed to resolve this. Should I add@Transactionalabove clean method or something? Or even delete@Transactionalannotation.@Override public void clean(BooleanSupplier isInterrupted) { // other code while (shouldContinue(isInterrupted) && partitionsIterator.hasNext()) { PartitionDeleteSql partition = partitionsIterator.next(); execute(partition); } } @Transactional public void execute(PartitionDeleteSql sql) { // other code getJdbcTemplate().execute(sql....()); getJdbcTemplate().execute(sql....()); getJdbcTemplate().execute(sql....()); }
Sonar issue - transactions
I had the same issue. I changed name of folders in file system to reduce the path to the project - it works for me.
Error while running test coverage using Jacoco.I am currently using operating system Windows 10 Professional, Java 8, Gradle.CLI to execute test coverage report I am using the command:gradlew sonarqube -Dsonar.projectKey=projectKey -Dsonar.host.url=http://localhost:9000 -Dsonar.login=c231ced071c19ae0ab12342dfgd3fa17e85fd6a5While I am running jacoco to publish report in local sonarqube, I am getting the following error:Error occurred during initialization of VM Error opening zip file or JAR manifest missing : build/tmp/expandedArchives/org.jacoco.agent-0.8.5.jar_6a2df60c47de373ea127d14406367999/jacocoagent.jar agent library failed to init: instrument Error occurred during initialization of VM Error opening zip file or JAR manifest missing : build/tmp/expandedArchives/org.jacoco.agent-0.8.5.jar_6a2df60c47de373ea127d14406367999/jacocoagent.jar agent library failed to init: instrument Process 'Gradle Test Executor 2' finished with non-zero exit value 1 org.gradle.process.internal.ExecException: Process 'Gradle Test Executor 2' finished with non-zero exit value 1 at org.gradle.process.internal.DefaultExecHandle$ExecResultImpl.assertNormalExitValue(DefaultExecHandle.java:417) at org.gradle.process.internal.worker.DefaultWorkerProcess.onProcessStop(DefaultWorkerProcess.java:141)Please need your input to resolve this issue. Thanks in advance.
Error opening zip file or JAR manifest missing : build/tmp/expandedArchives/org.jacoco.agent
I fixed this issue.while running sonar-scanner command, I added the xmlReportPaths as a define property like sonar-scanner -Dsonar.coverage.jacoco.xmlReportPaths=tests/target/site/jacoco-aggregate/jacoco.xml,../tests/target/site/jacoco-aggregate/jacoco.xml
SonarQube:8.2.0.32929sonar-scanner:3.0.3.778jacoco:0.8.4jdk:1.8mvn:3.6.3What are you trying to achieveI am trying to achieve code coverage by using sonar-scanner but I am getting code coverage 0 in sonarqube dashboard.What have you tried so far to achieve thisI configured the multi-module java project usinghttps://github.com/SonarSource/sonar-scanning-examples/tree/master/sonarqube-scanner-maven/maven-multimoduleand created sonar-project.properties file in base directory with below configurationsonar.projectKey=org.sonarqube.sonarscanner-maven-aggregate sonar.projectName=Sonar Scanner Maven Aggregate sonar.projectVersion=1.0 sonar.language=java sonar.java.binaries=.If I use mvn sonar:sonar it works. but with sonar-scanner it is not working.It works fine with sonarqube 7.8.Any insight would be appreciated.
SonarQube 8.2 Analysis shows 0 code coverage
FindbugsExternal Analysers Analyze Java code with SpotBugs 3.1.0-RC6. 3.6.0I cannot find version of theSonarQube Findbugsplugin which provides SpotBugs 3.1.0-RC6. It should be between:3.7.0(released: 15 Mar 2018) provides SpotBugs 3.1.2 (seecode)3.6.0(released: 21 Sep 2017) provides SpotBugs 3.1.0-RC5 (seecode)It seems to me that you use a custom version of the plugin.First version of the Findbugs plugin which promise to support JDK 11 is3.10.0(depends on SonarJava 5.10.1, where JDK 11 is supported since SonarJava 5.8 (SONARJAVA-2862), seecode).Second problem is that you try to use an not maintained (unsupported) version of server:SonarQube version: Version 6.7 (build 33306)with the latest version of SonarScanner:<artifactId>sonar-maven-plugin</artifactId> <version>3.7.0.1746</version>SonarQube6.7has been released on 8 Nov 2017 (tag has been created at 7 Nov 2017). It has been released before the first official JDK 11 LTS release (Google shows September 2018).I think the only correct solution is to upgrade SonarQube to at least7.9 LTSwith all plugins.
I migrated my application to OpenJDK11 and Jenkins build is failing because Findbug is no longer supported. The plugin :sonar-maven-plugin-Is internally calling Findbug in java 11 env and it's breaking the Jenkins buildHow do I migrate this plugin to use the latest Spotbug dependency, I still want to keep the sonar-maven-plugin to get the report to sonar.Current pom.xml relevant portion :<build> <pluginManagement> <plugins> <plugin> <groupId>org.sonarsource.scanner.maven</groupId> <artifactId>sonar-maven-plugin</artifactId> <version>3.7.0.1746</version> </plugin> </plugins> </pluginManagement> </build>Already went through many docs. Couldn't find a solution.SonarQube version:Version 6.7 (build 33306)Installed Plugins (Relevant ones) :FindbugsExternal AnalysersAnalyze Java code withSpotBugs3.1.0-RC6. 3.6.0SonarJavaLanguages Code Analyzerfor Java 5.13.1 (build 18282)SonarXML Code Analyzerfor XML 2.0.1 (build 2020)CheckstyleExternal AnalysersAnalyze Java code with Checkstyle 4.23
SonarQube FindBugs analyzer (with SpotBugs 3.1.0-RC6) does not suport JDK 11
I see two problems:you didn't add any installer toSonarQubeScannertool (only checkbox is checked)the code is incorrectSingle quotes are not evaluated (treat as is). It means that:def value = 'ABC' println '${value}/bin/sonar-scanner.bat'prints${value}/bin/sonar-scanner.bat. You have to use double quotes:def value = 'ABC' println "${value}/bin/sonar-scanner.bat"printsABC/bin/sonar-scanner.bat.The code should be equal to:withSonarQubeEnv('SonarQube') { bat "${scannerHome}/bin/sonar-scanner.bat" }
i'm tring to use SonarQube inside my Jenkinsfilepipeline{ agent any stages{ stage('build'){ steps{ // invoke command to build with maven bat 'mvn clean install' } } stage('SonarQube') { environment { scannerHome = tool 'SonarQubeScanner' } steps { withSonarQubeEnv('SonarQube') { bat '${scannerHome}/bin/sonar-scanner.bat' } } } } }this is my SonarQube serverand this is SonarScannerwhat is wrong withwithSonarQubeEnvstep:withSonarQubeEnv('SonarQube') { bat '${scannerHome}/bin/sonar-scanner.bat' }that I always got an error'${scannerHome}' is not recognized as an internal or external command,
SonarScanner is configured in Jenkins Tools, but '${scannerHome}' is not recognized as an internal or external command
YourPostmethod returns anint. On your test you are expecting to receive a nullable int (int?).My gues is the problem is that your are not really testing the result of your method when you use this assert:Assert.IsTrue(response != null);. The first problem is that kind of test will never fail.I imagine that yourdashboardrepos.SaveSearchHistoryByUsermethod should return the primary key of the entity you just persist on your db. Based on that assumption I suggest you to refactoring your test as I describe below, to improve and solve the problem with coverage.[TestMethod()] public void GlobalSeach_PutTest() { SearchHistory history = new SearchHistory { // redacted for ease of reading on SO } // _dashboardreposMock is an example of Mock<IDashboardRepository> _dashboardreposMock.Setup(_ => _.SaveSearchHistoryByUser(It.IsAny<SearchHistory>)).Returns(1); var controller = new GlobalSearchController(_config); int response = controller.Post(history); Assert.IsTrue(response == 1); }
Here's my API endpoint:[HttpPost] public int Post(SearchHistory searchHistory) { IDashboardRepository dashboardrepos = new DashboardRepository(); int historyId = dashboardrepos.SaveSearchHistoryByUser(searchHistory); return historyId; }And here is the SonarQube report:The two green bars on lines 37 & 38 indicate that they are covered by the unit test. But for some reason like 39 isn't?Here's the test:[TestMethod()] public void GlobalSeach_PutTest() { SearchHistory history = new SearchHistory { // redacted for ease of reading on SO } var controller = new GlobalSearchController(_config); int? response = controller.Post(history); Assert.IsTrue(response != null); }
Why does SonarQube claim the `return` line is not covered by a unit test?
I this area no tool is the same. So when you run all those tools on the same code you will get some similar findings, some new one's and some missing (maybe false positives), depending how they implement the tool. Given the fact that SonarQube is relatively new in this field I would suggest using some other tool for this specific area also. Be aware that achieving a 100% detection result is extremely difficult/impossible.
Can we replace the Static application security testing SAST Tool like (Fortify, Checkmarx and IBM Appscan) with SonarQube.As per the SonarQube Roadmap Docs 8.1 (https://docs.sonarqube.org/latest/) says it covered all the security rules originated from establish standard: CWE, SANS Top 25, and OWASP Top 10.
Can we replace the Static application security testing SAST Tool like (Fortify, Checkmarx and IBM Appscan) with SonarQube
I'm guessing, that you enabled SonarQube ruleRSPEC-1128 Unnecessary imports should be removedand now you want to have enabled UnusedImportsCheck in Checkstyle ruleset file. I don't think the exporter works in this way. It just takes all enabled rules of a specified tool and export them in a file. It means that if you enable UnusedImportsCheck Checktyle rule, I'm sure it will be in the exported file.Is it possible to export all rules defined in SonarQube Quality Profile to Checkstyle, PMD and SpotBugs rule files?It is possible to export:Checkstyle rules to Checktyle ruleset filePMD rules to PMD ruleset fileetcIt is impossible to export SonarQube rules as different tool rules, example:SQUID rules to Checktyle ruleset file
IssueI am usingSonarQube 7.9.1. I have Quality Profile containing ~450 active rules for Java code. There are exporters forFindBugs,PMDandCheckstylein SonarQube, but they are not exporting all available rules. After export ~20 rules are missing. What can be the cause of that?Example of missing rule:"Unnecessary imports should be removed". It seems strange, because both Checkstyle and PMD have such rule available.QuestionIs it possible to export all rules defined in SonarQube Quality Profile to Checkstyle, PMD and SpotBugs rule files?
How to export all rules from SonarQube Quality Profile to SpotBugs, Checkstyle and PMD rule files
About your try, Sonar gives indeed thevolatilefieldas workaroundbut it looks like that according to new issue when you use it, it contradicts itself.... Not obvious : )but we got an SonarLint error of Double-checked locking should not be used (squid:S2168) on double locking code.I would remove the double checked locking that is really error prone and verbose.Eager initialization is thread safe and is in most of case fine :public class Singleton { private static final Singleton singleton = new Singleton(); private Singleton() { } public static Singleton getInstance() { return singleton; } }The lazy way with the holder class is an alternative too (while I generally avoid because the laziness is often not a requirement) :public class Singleton { private static class SingletonHolder{ static final Singleton singleton = new Singleton(); } private Singleton() { } public static Singleton getInstance() { return SingletonHolder.singleton; } }
I have a already implemented Singleton class earlier which was using double locking mechanism for Singleton instance but we got an SonarLint error ofDouble-checked locking should not be used (squid:S2168)on double locking code.public class Singleton { private static Singleton singleton; private Singleton() { } public static Singleton getInstance() { if (singleton == null) { synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; }}As a fix of this issue, I thought of puttingvolatilekeyword before Singleton object reference like below.private static volatile Singleton singleton;But after making this field as volatile SonarLint is giving errorNon-primitive fields should not be "volatile" (squid:S3077)Does this mean now it is not good practice to make object reference as volatile as most of the example of singleton available are like mentioned code example?
Sonarlint is giving error on volatile object reference when using double locking for Singleton class in updated 4.1 version
Take a look at the description ofthe rule.Failing to explicitly declare the visibility of a member variable could result it in having a visibility you don't expect, and potentially leave it open to unexpected modification by other classes.If you have a property of a class package private then any class in the same package can modify this property.But Package private still has valid uses. For example you might want to declare a class as package private so that it can be used inside the package it is declared in but remains hidden from public use.
As well known in Java present default visibility modifier. As I understand this modifier can be used like other modifiers. But why SonarQube mark default modifier as vulnerability - Explicitly declare the visibility for "var"?
SonarQube vulnerability: Explicitly declare the visibility for variable
I still have no idea how to manually get a step context to manually execute a step, but in case anyone else finds this by trying to get information out of the Sonar plugin, this is how I got the task ID that I needed.def output = sh(script: "mvn sonar:sonar", returnStdout: true) echo output // The capture prevents printing to console def taskUri = output.find(~'/api/ce/task\\?id=[\\w-]*')
I have a step in a pipeline that pulls objects from the context and uses them. However, I need to access those objects outside of the steps to feed into different steps, and the second step doesn't expose it.stage() { steps { script { def status = waitForQualityGate() // Use the taskId } } } }ThewaitForQualityGate()call only returns a boolean, so I can't access it there.I could instead manually initialize the step, like so:script { def qualityGate = new WaitForQualityGateStep() def taskId = qualityGate.getTaskId() }but thetaskIdis null. If I try to run the start methods manually on the step:script { def qualityGate = new WaitForQualityGateStep() qualityGate.start().start() def taskId = qualityGate.getTaskId() }It fails with the message:java.lang.IllegalStateException: you must either pass in a StepContext to the StepExecution constructor, or have the StepExecution be created automaticallyTheWaitForQualityGateStephas the info I need, but I can't initialize it without having a StepContext (which is an Abstract class). How can I get one from the pipeline?
How to get the current Jenkins pipeline StepContext
Searching for this same issue, I came upon this unreplied question. Digging some more, I've found a workaround. I'm using Eclipse Simrel 06-19.Just check (or configure as you like) your hover preferences in Window->Preferences. Select in the tree Java->Editor->HoversThis is my current (also the default) configuration:On your specific case (as happened to me) you could just press Ctrl+Shift while hovering to display javadoc instead of the warning description (or just Shift to see the source).Samples with the above config:With no key held:With Ctrl + Shift:With Shift:Hope this helps (although a bit late!)
In Eclipse Neon, when adding@Deprecatedto method for example,The Sonar S1133 warning of removing the deprecated method is blocking seeing the java docs of the method (when hovering over)It prevents [email protected] there a way around it expect ignoring this specific warning? I just don't want it to block the java docs pop upI saw that you can useF2to open pop up, but it's also show sonar warning instead.Is it eclipse issue of pop up or sonar plugin issue that can be opened?EDITThe only solution I found is to deactivate this specific sonar warning
Eclipse - @Deprecated warning hides java docs pop up
You don'tusetheFileInputStream, but if you add the following line (or similar):fis.read();It will add the valid rule:Resources should be closed (squid:S2095)Connections, streams, files, and other classes that implement the Closeable interface or its super-interface, AutoCloseable, needs to be closedafter use.But you have a point that we need to release resource asFileInputStreamYes, you need to close the inputstream if you want your system resources released back.You can raise this question inSonarSource communityEDITResources should be closed not warns on new FileInputStreamadded as a possible sonarqube bug
public static String getMD5Checksum(String filePath) throws Exception { File file = new File(filePath); FileInputStream fis = new FileInputStream(file); return DigestUtils.md5Hex(fis); }In the above code fis is not closed but it is not thrown as error in SonarQube. The DigestUtils.md5Hex method does not close the stream too. Both SonarQube and Sonar Java plugins are in latest versions.
SonarQube not capturing FileInputStream which is not closed
Could not find method property() for arguments [sonar.jacoco.reportPaths,"ProjectATest1/gradleBuild/jacoco/Tests.exec", "ProjectATest2/gradleBuild/jacoco/Tests.exec", "ProjectATest3/gradleBuild/jacoco/Tests.exec"]It means that the methodpropertydisallow passing 4 arguments. You have to define paths in a one string (comma separated list):sonarqube{ properties { property "sonar.jacoco.reportPaths", "ProjectATest1/gradleBuild/jacoco/Tests.exec,ProjectATest2/gradleBuild/jacoco/Tests.exec,ProjectATest3/gradleBuild/jacoco/Tests.exec" } }
I have a multi-module gradle project. Tests for one of my module are in separate modules. For ex: ProjectA, ProjectATest1, ProjectATest2, ProjectATest3. Jacoco execution reports are getting created in the test projects. I want to do sonar analysis of my ProjectA and sonar fails to find the jacoco files.in ProjectA, sonarqube properties, I gavesonarqube{ properties { property "sonar.jacoco.reportPaths","ProjectATest1/gradleBuild/jacoco/Tests.exec", "ProjectATest2/gradleBuild/jacoco/Tests.exec", "ProjectATest3/gradleBuild/jacoco/Tests.exec" } }But I get this exceptionCould not find method property() for arguments [sonar.jacoco.reportPaths,"ProjectATest1/gradleBuild/jacoco/Tests.exec", "ProjectATest2/gradleBuild/jacoco/Tests.exec", "ProjectATest3/gradleBuild/jacoco/Tests.exec"]SonarQube: Coverage incomplete on multimodule gradle project with JaCoCothe answer says it should work. Is there a bug in sonar gradle plugin?
sonar.jacoco.reportPaths is not working with sonar gradle plugin
Finally figured this out and wanted to share with anyone else who stumbles across this problem. The issue here is that the SonarQube version being used by the OP is 6.7 (similar to me) and the documentation he linked to is for the latest version of SonarQube (7.3 as of this writing).The documentation for 6.7 is locatedhereand navigating to the equivalentConfiguring Portfolios and Applicationspage includes the following required command be run in order to execute the Portfolio Calculation task in previous versions of SonarQube:Calculation Calculation must be triggered manually each time a Portfolio structure is modified. Portfolios should also be recomputed on a regular basis to keep them up to date with the most recent project quality snapshots. Portfolio are computed with the SonarQube Scanner.To compute all your Portfolio, run the following command (credentials from a user with "Administer System" or "Execute Analysis" permission is required):sonar-scanner views -Dsonar.login=<token> or sonar-scanner views -Dsonar.login=<login> -Dsonar.password=<pwd>So when using SQ 6.7, without running thatsonar-scanner viewscommand in your build plan, only theProject Analysistask will run and your Portfolios will never be updated. Running thisviewscommand appears to run thePortfolio Calculationtask for all Portfolios on the SQ Server which in turn will update the UI for each entry.
We have created a portfolio and added few applications to portfolio but when i choose portfolio in the sonar dashboard it shows the below message even though i have added few projects to it and there were no background tasks or analysis related data after sonar analysis on one of the project. Message: This portfolio is empty. This portfolio has no projects, or none of associated projects has lines of code.We have followed the below link to configure a portfolio.https://docs.sonarqube.org/display/SONAR/Configuring+Portfolios+and+ApplicationsCreated a Portfolio and few projects the portfolio Project selection mode: Manual Sonar Version: 6.7.4 LTS Enterprise Edition Issue: i Could not see the projects which i have added to portfolio under Sonar portfolio sectionCan someone please point me to the right configuration steps or help me with the resolution.
Sonar Portfolio is not showing configured projects, message portfolio has no projects, or none of associated projects has lines of code
TheDOCTYPEandhtmltags are only mandatory when you author Facelets templates in a visual page designer. The Java EE tutorial's author had probably in mind that this kind of developers would become the largest group of JSF users. However, after all, this turned out to be untrue. In reality, these visual page designers generate terrible and non-semantic source code full of bad HTML/CSS practices, which one had to cleanup afterwards.When you're authoring Facelets templates in a plain text editor (with syntax highlighting, of course), then you don't necessarily need theseDOCTYPEandhtmltags in template compositions and composites. A root element of<ui:composition>and<ui:component>already suffices.So, in your specific case, just use:<ui:component xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://xmlns.jcp.org/jsf/facelets" xmlns:cc="http://xmlns.jcp.org/jsf/composite" > <cc:interface> ... </cc:interface> <cc:implementation> ... </cc:implementation> </ui:component>And then Sonar won't anymore incorrectly interpret it as a "plain" HTML page.See also:How to include another XHTML in XHTML using JSF 2.0 Facelets?Is there a way to run a JSF page without building the whole project?
Following Oracle (and others)documentation, I have all my JSF components looking like :<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:composite="http://xmlns.jcp.org/jsf/composite" > <composite:interface> ... </composite:interface> <composite:implementation> ... </composite:implementation> </html>Of course, it works properly, but SonarCube disagree with this (rule detailshere):"title" should be present in all pagesThere are a couple of solutions :Asking Sonar to ignore these issues,Adding<head>and<title>tags,But these looks like workarounds and I would like to set a permanent solution.
How not to specify a <title> on all my JSF custom components
Instead of the using the traditional properties file under solution/project folder, you could directly use it in Additional properties setting ofSonarQubetask with version 4.0One of the best improvements of this new preparation task, is that the single line “Additional properties” is replaced by a multi-line textbox which allows you to set all the properties as you would normally do in the “sonar-project.properties” file.More details take a look at this blog:Perform SonarCloud and SonarQube analysis with the new version 4 build tasks
i have multiple projects in one solution file. and need to build 3 projects in one pipeline and two projects in another pipeline of CI. So in order to have code analyzed using sonarqube, i found that using two project.properties file and by running sonar-scanner command in the directory of the solution file as well as the properties file serves the issue.this is working if i include 3 projects in one sonar-project.properties file. because im not passing any arguments along with sonar-scanner it is picking default properties file i.e., sonar-project.properties . if i rename it and create another properties file for the other pipeline, i need to pass the arguments assonar-scanner -Dproject.settings=../myproject.propertiesbut it is not recognizing the properties file. Please help.I followed this link:https://docs.sonarqube.org/display/SCAN/Advanced+SonarQube+Scanner+UsagesSonarqube version = 6.8 pipeline in TFS 2017. MSBuild version 15.Thanks in advance.
passing project.properties file to sonar-scanner
sonar.javascript.jstestdriver.reportsPathis deprecated since a long time. You should use generic report import:https://docs.sonarqube.org/display/SONAR/Generic+Test+DataTo convert to generic format use something like thishttps://www.npmjs.com/package/mocha-sonarqube-reporter
I am learning how to integratesonarqubewith aNodeJSproject, so far it has been working fine but the dashboard has theunit testsmeasure missing. The runner being used for testing the project ismochaand i've been usingnycto generate alcovfile so the coverage measures are displayed in sonar, however i am not able to make the unit test measure to display even when i've tried many mocha reporters, for now i am tryingmocha-junit-reporterin order to create aXMLfile.For the xml to be generated incoverage/this is the command i've run:MOCHA_FILE=./coverage/file.xml npx mocha test/**/*.js --reporter mocha-junit-reporterThe scanner is being used byJenkinsand it has these properties:sonar.projectKey=node-user-data sonar.projectName="User Data" sonar.projectVersion=1.0 sonar.baseProjectDir=${workspace} sonar.sources=${workspace}/classes sonar.tests=${workspace}/test sonar.language=js sonar.sourceEncoding=UTF-8 sonar.exclusions=node_modules/** sonar.javascript.lcov.reportPaths=coverage/lcov.info sonar.javascript.jstestdriver.reportsPath=${workspace}/coverage/file.xmlI have also tried removing thexmlfile inreportsPathparameter as i have readed it has to point to directory where thexmlfile is but still no avail.Any help on how i could display the unit tests number in dashboard is appreciated
SonarQube Javascript: how to show unit tests dashboard with mocha
SonarQube allows you toadd custom rules.Assuming there is no existing enum related rule warning on incomplete switch case coverage, you can simply add your own rule on SQ and have it enforced on all the SonarLint instances connected to your SQ server..
Using Java, SonarQube is complaining about switch statements on enum values not having adefault:case.The reasoning given is:"The requirement for a final default clause is defensive programming. The clause should either take appropriate action, or contain a suitable comment as to why no action is taken. When the switch covers all current values of an enum - and especially when it doesn't - a default case should still be used because there is no guarantee that the enum won't be extended."I do not agree with the above statements - I want the following behavior to generate a warning:Modifying an enum so that the switch no longer covers every case.By requiring a default case - we will not get a warning if the enum changes, and the switch will no longer handles all the cases.
Is there any way to get SonarQube to only warn about incomplete Switch statements?
You need to merge your JaCoCo .exec files into a single binary file.To achieve this use JaCoCo'smerge mojo.Cristian (fromcristian.io) has an excellent walkthrough of how to achieve thishere. The following is a slightly modified version of the code from that blog post.def allTestCoverageFile = "$buildDir/jacoco/allTestCoverage.exec" task jacocoMergeTest(type: JacocoMerge) { destinationFile = file(allTestCoverageFile) executionData = project.fileTree(dir: '.', include:'**/build/jacoco/test.exec') } sonarqube { properties { property "sonar.projectKey", "your.org:YourProject" property "sonar.projectName", "YourProject" property "sonar.jacoco.reportPath", allTestCoverageFile } }
I have a maven Jenkins job (Jenkins version 2.105) with Jacoco and Sonar (Version 6.0) configured. The project has multiple jacoco.exec created and I need to put the path for the same under sonar.jacoco.reportpath. The code coverage comes up in sonar if I add for only one exec. While adding the others are comma separted values, code coverage in not displayed in Sonar.As the version of SonarQube is prior to 6.2 I understand we are required to use sonar.jacoco.reportPath property and not sonar.jacoco.reportPaths. How do we configure multiple path here?
Multiple paths in sonar.jacoco.reportpath
sonar.php.coverage.reportPathandsonar.php.tests.reportPathshould provide xml file paths, not folder paths. For example, it could be:sonar.php.coverage.reportPath=reports/phpunit.coverage.xml sonar.php.tests.reportPath=reports/phpunit.xml
I am trying to publish in sonarqube the junit reports generated by phpunit. It does'nt matter the path that I put, It never finds the files. The log show this message:No PHPUnit test report provided (see 'sonar.php.tests.reportPath' property)My configs are the following:sonar.projectKey=MyProj sonar.projectName=MyProj sonar.language=php sonar.sources=Application sonar.tests=Tests sonar.php.tests.reportPath=build/logs/ sonar.php.coverage.reportPath=build/coverage
Sonarqube does not find junit reports
(assuming you're using jacoco for coverage reporting)If you're not using Lombok, you might try adding the @Generated annotation to your methods you want skipped. I'm not sure this will work - but worth a shot!If you're using Lombok [like I was], here's a solution from Rainer Hahnekamp that marks the code as @Generated, which makes jacoco ignore the methods, and in turn makes sonarqube display a higher coverage percentage.Luckily, beginning with version 0.8.0, Jacoco can detect, identify, and ignore Lombok-generated code. The only thing you as the developer have to do is to create a file named lombok.config in your directory’s root and set the following flag:lombok.addLombokGeneratedAnnotation = trueThis adds the annotation lombok.@Generated to the relevant methods, classes and fields. Jacoco is aware of this annotation and will ignore that annotated code.Please keep in mind that you require at least version 0.8.0 of Jacoco and v1.16.14 of Lombok.https://www.rainerhahnekamp.com/en/ignoring-lombok-code-in-jacoco/
I'm wondering if it is currently possible to ignore the equals and hashcode method for the sonar test coverage? I have heard about the block exclusion, but it didn't work.
How to make sonarqube ignore the equals and hashcode
As you can read in theTravis CI logs, at line 556:Skipping SonarCloud Scan because this branch is not master or it does not match declared branchesThis is because you haven't activated analysis on that "feature/sonarcloud" branch. As described in theofficial documentation, you can achieve that like this:addons: sonarcloud: organization: open62541 token: secure: "..." branches: - master - feature/sonarcloud
I am trying to add SonarQube analysis to our OSS Project with travis on Github.I performed the following steps:Create a organization and project on sonarcloud.ioAdd the sonarcloud definition in.travis.ymlCreate asonar-project.propertiesfilePush everything to a feature branch calledfeature/sonarcloudAdd this branch to travis.yml and properties file.The final result can be seen here:https://github.com/open62541/open62541/tree/feature/sonarcloudUnfortunately Travis does not submit the sonar analysis:INFO: Scanner configuration file: /home/travis/.sonarscanner/sonar-scanner-2.8/conf/sonar-scanner.properties INFO: Project root configuration file: NONE INFO: SonarQube Scanner analysis skipped(See alsohttps://travis-ci.org/open62541/open62541/jobs/287631673)I already tried to forcefully setexport SONARQUBE_SKIPPED=falsebut it is still skipped. How can I find out why the scanner analysis is skipped?Related questions:SonarQube Scanner analysis skipped in travis CITravis CI skipping SonarQube analysis
Travis - INFO: SonarQube Scanner analysis skipped
Yo can use SonarCube with a plugin for Typescript and integrate SonarCube with Jenkins. This plugins works fine with Angular 2/4:SonarTsPlugin
Is there any tool to integrate with Jenkins? I have the testing and coverage but I could't find any related with analysis code for Angular 2/4.Thanks
How to have code quality analysis for Angular in Jenkins?
You can useBUILD_LOG_REGEXtoken to extract required information from the log. The syntax is as follows:${BUILD_LOG_REGEX, regex, linesBefore, linesAfter, maxMatches, showTruncatedLines, substText}Exemplary email notification content with a Sonar result URL (in a case of successful scan):SonarQube result URL: ${BUILD_LOG_REGEX, regex=".*ANALYSIS SUCCESSFUL, you can browse (.*)", showTruncatedLines=false, substText="$1"}
I am using Jenkins for Orchestrate a build of a Java Project. I am scanning this project source with SonarQube Scanner in pre-build phase. I need to send a mail for both pass and fail case to a list of Recipient.Client want this SonarQube result link in the mail. I manage to configure Jenkins to shoot the mail but I cant find any document which specify how to add SonarQube result.Jenkins do print the link in logs. I am usingJenkins 2.25,SonarQube 5.6.4and mail pluginEmail Extension Plugin 2.58.Please help.
Send SonarQube link in mail from Jenkins
Notice when SonarQube is installed, some bundled plugins are automatically installed, see whcih plugins are installed automatically and maybe need to be upgraded.There's anupgradeinstructions,When upgrading you need to install the plugins you use seeplugin versionsSonarQube plugin tojenkinsdependencies:maven-plugin (version:2.14, optional)workflow-cps (version:2.25, optional)configurationslicing (version:1.40, optional)jquery (version:1.11.2-0)
I upgraded sonarqube from 6.0 to 6.4 on JenkinsSonar analysis was working fine with 6.0 but after the upgrade I got an error saying:No quality profiles have been found, you probably don't have any language plugin installedWhat's going wrong here?
Sonarqube No language plugin error when upgraded from 6.0 to 6.4
If you plan to handleException,UnexpectedInputException,ParseException,NonTransientResourceException, or if you want to let users of your custom class handle these exceptions, then the issue is acceptable and you can mark it False Positive or Won't Fix in your SonarQube.But it's unlikely that you, or users of your custom class will be interested in handling all those low-level exceptions separately. If that's the case, then it will make sense to define your custom exception, and throw that instead. Catch all of Spring's exceptions and preserve them in the custom exception in case somebody might want to see the original cause.
I am using SonarQube to improve coding quality but I got a bug here that I don't know the best solution.I call a Spring's method with the following signature:T read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException;As I just have to call this method and I have no intention to treat any error, I defined my method like this:ItemTransacaoEnvioVO read() throws UnexpectedInputException, ParseException, NonTransientResourceException, ExceptionBut I get this Sonar bug:Remove the declaration of thrown exception 'org.springframework.batch.item.ParseException' which is a subclass of 'java.lang.Exception' ... etcThen I changed like Sonar wants:ItemTransacaoEnvioVO read() throws ExceptionAnd I get this:Define and throw a dedicated exception instead of using a generic one.Thinking in the best practices and coding quality what would be the best solution for this problem?Java 8, Sonar
Best solution for a Sonar issue related to "throws"
There is a way to set the rule type using some special tags.Tag "bug" means type "bug"Tag "security" means type "vulnerability"So try for example:tags = {"suspicious", "bug"}NB: This is documented inAPI Javadoc(but hard to find I admit)
I am using sonarQube 6.3 and when adding new custom rules for Php or Javascript, they are by default declared as Code smell. I would like to declare them as Vulnerability or bug.Here is an example of a rule declaration@Rule(key = "Rule1", priority = Priority.MAJOR, name = "Rule 1 sould be used.", tags = {"suspicious" })Is there a way to do it?
Declare custom rule type as Vulnerability in SonarQube 6.3
[edit] I have confirmed that 5.10.1.1411 resolves this issue. Thanks Amaury and Sonar Team!https://sonarsource.bintray.com/Distribution/sonar-csharp-plugin/sonar-csharp-plugin-5.10.1.1411.jar[original]Rolling back to 5.9-RC1,https://github.com/SonarSource/sonar-csharp/releases/tag/5.9-RC1, manually seems to resolve the issue.It seems the 5.10.0.1334 generates malformed XML for /api/qualityprofiles/export?exporterKey=sonarlint-vs-cs&language=cs&name=Sonar%20wayI have opened an issue on sonar-csharp's github.https://github.com/SonarSource/sonar-csharp/issues/283
See more information in the output window (SonarLint).Note sure what the oupur window it is refering to. I get this issue in Visual Studio 2015 when binding a project to sonarqubeFailed to bind the solution to SonarQube project, try again. See more information in the output window (SonarLint). Server side is at version 5.6.3 and was recently upgraded.I've re-installed the plugin, tested on several workstations. No luck.-- update : found this log SonarQube request failed: Response status code does not indicate success: 500 (Internal Server Error). Failed to download quality profile. Name: 'Sonar way', Key: 'cs-sonar-way-15069', Language: 'C#'-- update #2 And I can confirm my quality profile is available - same IDhttp://mysonarserver/profiles/show?key=cs-sonar-way-15069here is my log on server side.Fail to process requesthttp://mysonarserver/api/qualityprofiles/export?name=Sonar+way&language=cs&exporterKey=roslyn-csjava.lang.NullPointerException: null value
Failed to bind the solution to SonarQube project, try again
You will certainly get additional advantage when using PVS-Studio together with SonarQube. We do not have a direct comparison between the analyzers, but you can look at this article: "Analysis of PascalABC.NET using SonarQube plugins: SonarC# and PVS-Studio". The thing is, SonarQube is a code quality assurance platform, and it is not primarily orientated at finding errors. In general, it looks for "code smells". For example, a file does not start with a comment block. This is not an error in itself. PVS-Studio is orientated toward finding the 'direct' errors.
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed6 years ago.Improve this questionI recently came across PVS Studio. I would like to know how PVS Studio is different from SonarQube. I see that, both tools perform static code analysis. I am trying to understand which is the best tool to opt for.Any insights are helpful.Best Regards Gowtham
PVS studio compare with sonarqube [closed]
This got worked out for me[root@sonarqube ~]# egrep "^local|^host" /var/lib/pgsql/9.5/data/pg_hba.conf uncomment below lines in pg_hba.conf local all all md5 host all all 127.0.0.1/32 md5 host all all ::1/128 md5
When I am installing sonarqube using postgresql, I got stuck with connecting it to jdbc of Postgresql. In/opt/sonarqube/conf, I uncommented JDBC assonar.jdbc.username=username sonar.jdbc.password=password. 2.sonar.jdbc.url=jdbc:postgresql://localhost/usernameAdditionally, below is my sonar scanner conf that I uncommented Default SonarQube serversonar.host.url=http://localhost:9000 PostgreSQL sonar.jdbc.url=jdbc:postgresql://localhost/usernameThis is what I followed for configuringPostgres DBThis is my log file shows2017.03.08 14:39:13 INFO web[o.sonar.db.Database] Create JDBC data source for jdbc:postgresql://localhost/username 2017.03.08 14:39:13 ERROR web[o.a.c.c.C.[.[.[/]] Exception sending context initialized event to listener instance of class org.sonar.server.platform.PlatformServletContextListener java.lang.IllegalStateException: Can not connect to database. Please check connectivity and settings (see the properties prefixed by 'sonar.jdbc.'). at org.sonar.db.DefaultDatabase.checkConnection(DefaultDatabase.java:104) ~[sonar-db-5.6.6.jar:na]Is there any other thing that I need to do for JDBC connection of Postgresql. is there is any document available for sonarqube for postgresql.
Unable to connect JDBC to sonarqube using Postgresql
Yes, theyshould. But they don't because when no coverage engine reportsanycoverage on a file, is that because the file is executable but there are no tests on it, or because the file is not executable?SonarQube v6.2 will begin to address this by automatically forcing to 0 the coverage metrics on files not covered in the unit test reports. However, this behavior will only be fully enabled when each of the language plugins reports the "executable lines" for each file.So in practice the new behavior enabled in 6.2 (not released at this writing, but "soon") won't be truly available until the language plugins start supporting it. Probably over the next few months.
Here's a screenshot so you better understand what I'm talking about:Shouldn't all directories have coverage?I have to say that those directories (without any number) are not covered by any tests but doesn't this mean that the coverage is 0%?
SonarQube coverage not showing up
This seems to be fixed inSonarLint 2.3.1.
In the following code I get a warning from thesquid:RedundantThrowsDeclarationCheckrule on theFoo1Exception(behind thethrowskeyword):Remove the redundant '!unknownSymbol!' thrown exception declaration(s).Foo.java:public class Foo { public static boolean bar(final String test) throws Foo1Exception, Foo2Exception { if (test.startsWith("a")) { throw new Foo1Exception(); } else if (test.startsWith("b")) { throw new Foo2Exception(); } else if (test.startsWith("c")) { return true; } return false; } }Both exceptions are decrlared in seperate files:Foo1Exception.java:class Foo1Exception extends Exception {}Foo2Exception.java:class Foo2Exception extends Exception {}I think this is a false positive, isn't it? Also interesting: I don't get this message directly in SonarQube (web interface) only in the SonarLint plugin in IntelliJ IDEA. Any Ideas?I'm using: IntelliJ IDEA 2016.2.2; SonarLint 2.3 (with working server binding); SonarQube 5.6; SonarQube Java Plugin 4.0; Java 8
SonarLint - RedundantThrowsDeclarationCheck - false positive?
You need the Governance commercial plugin to modify the rule time to fix (more precisely remediation cost/function in SonarQube terminology)You cannot change the classification of a rule. You can only change the classification of a rule violation, i.e. issues.
I have created a new quality profile in SonarQube 5.5 and added the rules I want to have with the severity (Info, Minor, Major, Critical, Blocker) I want to have - no problem so far.Now I want toedit the "time to fix" for each rule individuallyadd the classification for each rule (is it a bug, a violation or a code smell). This should be done on a "global level" for all projects. I know I can change the classification on a "per project" level.
SonarQube: Change rules "time to fix" estimation and issue type
There is no Matlab plugin for SonarQube.If you decide to develop the plugin yourself (which is not a small undertaking), then you will not need PMD. Have a look at the PHP or CSS plugins source code to know how to get started:https://github.com/SonarCommunity/sonar-phphttps://github.com/SonarCommunity/sonar-cssAlternatively, you can also add support of the Matlab language to PMD, and then develop a SonarQube "Matlab PMD" plugin. This doesnotmake sense, unless you really want to be integrated with PMD for some reason. There seems currently to bevery limitedMatlab support in PMDhttp://pmd.sourceforge.net/pmd-5.3.2/pmd-matlab/index.html- i.e. just a lexer, but no parser nor rules.
Does someone know, where I can find a plugin for parsing and integrating Matlabin Sonarqube ?If I have got or written this plugin, can I use the internal PMD runner of Sonarqube to check created Custom Rules (XPath) for Matlab ?Or do I have to write an extra "parser" for extending PMD with Matlab ?Thank you very much in advance!EDITOkay, I am still thinking about it. Like it seems, I have to write/extend a matlab grammar, if I want to use PMD (with JavaCC I can generate parser and lexer).But before I do this, can I also generate parser and lexer for Sonarqube with the created grammar and a generator (e.g. ANTLR) ?
Is there a plugin for parsing and integrating Matlab in Sonarqube?
This isn't supported yet.One solution would have to group your Git repos in a parent Git repo, declaring them assubmodules.ButSONARSCGIT-6shows that submodules are not yet supported in theSonarQube SCM Git plugin.
I am trying to make work the SCM support with git on my sonar project but I get an error because my workspace root is not a git repository.Indeed I have several git repositories for a single project so my workspace root is not a git repo but the subfolders are.I thought that thesonar.sourcesvariable would do the trick but no.
How to use Sonar SCM support with a workspace root that is not a Git repository
In order to make SonarQube analyse your tests as well, you should also set the "sonar.tests" property:<properties> <sonar.sources>src/main</sonar.sources> <sonar.tests>src/test</sonar.tests> </properties>
I'm trying to setup sonar to analyze both java and javascript sources. I have a standard structure maven project. FollowingTHISexample I've added the line<properties> <sonar.sources>src</sonar.sources> </properties>But when I runmvn clean install sonar:sonarI get the following error[ERROR] Failed to execute goal org.codehaus.mojo:sonar-maven-plugin:2.5:sonar (default-cli) on project myproject: File [moduleKey=myproject:myproject, relative=src/test/java/com/myproject/api/v1/ControllerTest.java, basedir=C:\sources\project] can't be indexed twice. Please check that inclusion/exclusion patterns produce disjoint sets for main and test files -> [Help 1]"ControllerTest.java" is the first file in the /src/test/java/../.. folderproject structure:Any hints? Thanks in advance for any help!UPDATE1# Tried Akash Rajbanshi suggestion: error disappeared but js code is not analyzed and also sonar doesn't analyze the test folder2# tried to put<sonar.language>js</sonar.language>and the js code is actually analyzed but java code is not (that was just a test)I'm kind of stuck
Sonar error in multi language project: File can't be indexed twice
Since version 5.1.0, they have had Java 8 support:See Changelists here.I am not an active Sonar user, but from what I could find, there has been some limitation of Sonar support for Java 8. It looks like you need a more recent version of SonarQube, and version 2.2.0 or higher of the PMD plugin:read here
I have upgraded to Java 8 and when I try to run the task sonarRunner in order to get the reports I get the following message.Execution failed for task ':sonarRunner'.org.sonar.api.utils.XmlParserException: org.sonar.api.utils.SonarException: Unsupported Java version for PMD: 1.8Is Java 8 supported in PMD? If yes how can I solve this problem?Many thanks
Java 8 for Sonar, PMD, Findbugs and Checkstyle in IntelliJ
I was having an issue similar to this. I found the log output in /usr/local/Cellar/sonar/4.5.1/libexec/logs/sonar.log.My first issue was that I had run "sudo sonar start" so I was getting this:Exception in thread "main" java.lang.IllegalStateException: Temp directory is not writable: /usr/local/Cellar/sonar/4.5.1/libexec/temp... Caused by: java.io.IOException: Permission DeniedI fixed that by running "sudo rm -rf /usr/local/Cellar/sonar/4.5.1/libexec/temp"Then I was running into the issue that my hostname was not resolvable:org.sonar.api.utils.SonarException: Unable to start database ... Caused by: org.h2.jdbc.JdbcSQLExecption: IO Exception: "java.net.UnknownHostException: mymac.mydomain.com: mymac.mydomain.com: nodename nor servname provided, or not known"I fixed that by adding "mymac.mydomain.com" to the /etc/hosts file:127.0.0.1 localhost mymac.mydomain.comHopefully this helps you. If not, maybe at least knowing where the logs are, you can troubleshoot.
After installing SonarQube 4.3.1 through Brew on Mac OS 10.9 Mavericks, when I navigate to localhost:9000, I could see the console but now after trying to install an Android plugin and restarting the server through terminal I can no longer view the localhost:9000 page? I even tried localhost:9000/setup but I only get page unavailable.Could someone give an idea as to why the plugin would cause this behavior and how to fix this?Thanksedit: I am using the latest version of the Android plugin that can only be installed via the SonarQube Dashboard. And as far as an error, as I mentioned when I navigate to the dashboard e.g. localhost:9000 it just gives me "Page unavailable" But if I uninstall from Home Brew and reinstall I can navigate there just fine.
SonarQube on mac doesn't start after plugin
You should get what you want with the /api/rules web service and with help of the "profile" parameter :http://docs.codehaus.org/pages/viewpage.action?pageId=229743284
How to download a sonar quality profile along with description./profiles/export?language=java&name=xyz_profileGives me xml dump with repositoryKey, key, priority elements of each rule. What shud i do to get description/rule descriptiin text?Pls help.
sonar quality profile rule export with descrption
According tohttp://jira.codehaus.org/browse/SONAR-188, you can try to update your connection settings in file:conf/sonar.propertieswith adding "autoreconnect".Example:sonar.jdbc.url=jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8?autoReconnect=true
from time to time I have the following error in my logs:Error querying database. Cause: org.apache.commons.dbcp.SQLNestedException: Cannot get a connection, pool error Timeout waiting for idle objectThe error may exist in org.sonar.core.issue.db.ActionPlanMapperThe error may involve org.sonar.core.issue.db.ActionPlanMapper.findByKeysThe error occurred while executing a queryHow should I adjust my connection pool settings so that this doesn't occur anymore?sonar.jdbc.maxActive=25 sonar.jdbc.maxIdle=5 sonar.jdbc.minIdle=2 sonar.jdbc.maxWait=15000 sonar.jdbc.minEvictableIdleTimeMillis=600000 sonar.jdbc.timeBetweenEvictionRunsMillis=30000
Connection Pool configuration / error in SonarQube
As an ugly workaround I was able to configure report path to:sonar.jacoco.reportPath=../build/jacoco/test.exec sonar.jacoco.itReportPath=../build/jacoco/integTest.execand for second level modules (a modulemod1which has its own submodulesmod1aandmod1b):mod1.sonar.jacoco.reportPath=../../build/jacoco/test.exec mod1.sonar.jacoco.itReportPath=../../build/jacoco/integTest.execNevertheless it is very error prone and I hope someone else will have a better idea.
I have a multi-module project and would like to visualize integration code coverage with SonarQube. I'm able to generate test.exec and integTest.exec (JaCoCo), but have problem to force sonar-runner (sonar-jacoco-plugin) to use them. sonar-runner reports:Project coverage is set to 0% since there is no directories with classes.which is true as for the root project (where integTest.exec is generated) doesn't have source files (but it should not be a problem for integration coverage). My configuration:(...) sonar.dynamicAnalysis=reuseReports sonar.jacoco.reportPath=build/jacoco/test.exec sonar.jacoco.itReportPath=build/jacoco/integTest.exec sonar.modules=mod1,mod2 sonar.sources=src/main/java,src/main/resources sonar.tests=src/test/java,src/test/groovy,src/test/resources sonar.binaries=build/classes/main,build/resources/mainThe project is built with Gradle, but due to a CI restrictions I need to usesonar-project.propertieswith sonar-runner configuration (not sonar-runner plugin from Gradle which worked for me in the past).Update. After the analyze of sonar-jacoco-plugin sources I tried to just create a directory defined as a binary directory, but unfortunately sonar-runner doesn't set sonar.binaries property for a root module at all.My question. Is there a workaround which would allow me to use file with the integration coverage data in a multi-module project with sonar-runner?
Unable to use integration coverage with sonar-runner in multi-module project
It turns out that the most recent gcovr version (3.1-prereleas) changes the way Cobertura reports are generated in that it the class tag's filename attribute contains the source code file's name only and not it's project root-relative path.The problem can be solved either by using an earlier gcovr version (I tried 2.4 and it worked) or by manually modifying the report to make it compatible with the C++ plugin's Cobertura parser again.
I am writing a tool that would generate Cobertura coverage reports for C++ projects. I have managed to generate the reports and now I would like to import these reports into Sonarqube.I noticed thatthe Sonar C++ Community Plugin supports the Cobertura XML formatso I downloaded asample C++ project for that pluginand executed sonar-runner and the execution is succeeding, however the Unit Tests Coverage section for the project in the the Sonar server's web front end contains no information (just a dash '-' symbol, indicating nothing).What am I doing wrong? Why can't I see any information from the imported Cobertura covreage report?Thanks in advance.
How to import C++ Cobertura coverage reports into Sonar?
There's currently no support for clustering with SonarQube.What you can do for the moment is only to have prepared virtual machines that you can start when there's a failure on the SonarQube instance. Obviously, there will be the startup time during which the service won't be available - but that's the best you can do for the moment.
Does SonarQube (Sonar) support replication/high availability solution? My goal is to have a failover SonarQube instance for if/when there's hardware failure on the machine the current instance is running on.
Sonar: Replication/high availability or clustering solutions
http://jira.codehaus.org/browse/SONAR-766is currently planned for version 4.1. Feel free to watch it.
We use Jenkins CI with Sonar for test coverage. We use Atlassian Clover as coverage tool. So the question: how to exclude getter/setter methods from test coverage in order to increase test coverage percent without writing useless test cases? I have tried to make some changes in Settings->General Settings->Clover and Settings->General Settings->Java sections but without any success. As I understand I need to apply something like (.* )?public .(get|set|is)[A-Z0-9].but I don't know where should I put this expression.
How to exclude getter/setter methods from test coverage in sonar clover plugin?
On sonar side this is pretty simple : each line containing a character which is neither a blank character or a character part of a comment is considered to be part of a line of code and there is no way to tune this behavior.
We're just switching our metrics gathering to sonar. We previously used sloccount to get the lines of code and are now using sonar but the counts are coming up as around 40% different. Does anyone know what the differences are and if there is any configuration that I should do in sonar to align the two?
Sonar lines of code vs. sloccount
TheJavadocMethodcheck does not offer an option to limit itself to certain files, so this cannot be done easily. But - you could:Write acustom filterwhich suppresses allJavadocMethodwarnings that occur in files which do not match a pattern. This is not difficult - the example on the linked page covers just that case. But it requires you to deploy the filter and that may be a bit of a hassle.I am not sure if this works in Sonar. I use custom Checkstyle checks in Sonar all the time, but I haven't tried custom filters yet.Write a subclass of Checkstyle'sJavadocMethodCheckwhich adds an option to apply itself only to certain files (Sonar Examples,Checkstyle tutorial). This is a sure bet if custom filters cannot be added to Sonar.If you are using Eclipse, you can configure it to use different rule sets based on filename. You would do that using the "advanced" configuration setting in the project properties. Your regexes would beController\.java$to match all controllers, and.{10}(?<!Controller)\.java$to match the other Java files. This approach could also be applied to a stand-alone or Ant-based Checkstyle run, but not to Sonar.I am sorry that there is nothing easier available to you - but that's how things are at the moment ...Good luck!
I have a pre-existing Java project, that Sonar Analysis was recently applied to. There are a large number of CheckStyle JavadocMethod rule violations.How would I restrict the JavadocMethod rule, to apply only to java filenames with the pattern "Controller.java" ?
How can I restrict the Sonar JavadocMethod rule to filenames including "Controller"?
AFAIK, the Delphi plugin, developed and maintained (?) by guys fromSabre, is not extensible: it does not have a rule extension mechanism, nor does it provide an XPath rule that could be used to achieve this purpose.
How to add custom rule in sonar for delphi language? Our problem is we are able to add custom rule for all other languages like c#,javascript,java in sonar, but are not able to add for delphi, We can't find new rule option like the one showed in thislink for adding custom rules in sonar. Someone please advise.
sonar delphi plugin custom rule
There is no such webservice API available. Could you please move to the user mailing-list to detail and discuss your needs? Seehttp://www.sonarsource.org/get-support/
There is a webpage that shows this information, but the webservice API docs do not mention any apis for listing libraries.
Is there a Sonar webservice API that lists all the libraries a project uses?
There are 2 things you can do from a Java program:launch a Sonar analysis: look into theSonar Ant Task(in method #launchAnalysis) to see how to do that very easily.retrieve results from the Sonar server: check theWeb APIfor that purpose
I have installed sonar server on my localhost. And I am able to run and analyse the java project. Even i have installed sonar plugin on eclipse.But I want to run sonar from my java project(like simple java class) and should retrieve the sonar results and able to save it in database. I searched for the tutorial but unable to find the answer for this. Please anyone can give sample code or resource where I can gain knowledge to overcome this task.import javax.annotation.Resource; import org.sonar.wsclient.Host; import org.sonar.wsclient.Sonar; import org.sonar.wsclient.connectors.HttpClient4Connector; import org.sonar.wsclient.services.*; public class SonarTask1{ public static void main(String[] args) { //public void Hi(){ String url = "http://localhost:9000"; String login = "admin"; String password = "admin"; Sonar sonar = new Sonar(new HttpClient4Connector(new Host(url, login, password))); String projectKey = "java-sonar-runner-simple"; String manualMetricKey = "burned_budget"; sonar.create(ManualMeasureCreateQuery.create(projectKey, manualMetricKey).setValue(50.0)); for (ManualMeasure manualMeasure : sonar.findAll(ManualMeasureQuery.create(projectKey))) { System.out.println("Manual measure on project: " + manualMeasure); } } }
Calling Sonar from my java program
Sonar provides it's own dashboard for analysis metrics and violations, separate to Jenkins. The time machine feature in Sonar allows you to look at the historical trend of your project's metrics.
This question already has answers here:how to publish sonar result in jenkins server, or do we have sonar-report jenkins plugin(2 answers)Closed10 years ago.TheSONAR plugin for Jenkinslooks to run SONAR analysis on a repo. How do we display some summary of the results in Jenkins? For example, a graph per build of critical and blocker violations.Analysis Collectorlooks to have a trend graph. However,this guyadvocates SONAR.
Show SONAR results in Jenkins? [duplicate]
You have to identify all the sniffs referenced by the Drupal standard and create a profile in Sonar (through the Web UI) that references them all. Then you activate this profile as the default one, and you're ready for an analysis.
I am trying to add the Drupal Coding standards in phpcs.I can run the Drupal Standards withphpcs --standard=DrupalNow I want to execute the same standards with Sonar.In Sonar I can add the keys of all the rulesets in therules.xmlextension, but how can Igetall the keys for these rules?I can identify some of the keys using the*sniff.phpfiles and the folder structure but I'm not sure I am getting all of them.Can anyone suggest an automated way to getallthe rules available in a particular standard?
How to get all the keys for of a PHP Codesniffer Ruleset to use with Sonar?
Gendarme expects you provide an ignore list,http://www.mono-project.com/Gendarme.FAQhttps://github.com/mono/mono-tools/blob/master/gendarme/self-test.ignoreThe ignore file format is bit of weird, but you can learn it by experiments.
I'm working with gendarme for .net called by Sonar (launched by Jenkins). I've a lot of AvoidVisibleFieldsRule violations. The main violations are found in the generated files. As I can't do anything on it, i would like to exclude *.designer.cs from the scan.I can't find a way to do that. There is a properties in Sonar to exclude generated files but it doesn't seem to be applied for gendarme.Is there a way to do such a thing ?Thanks for all
C#, Gendarme, Sonar and Jenkins : Exclude generated files from Gendarme
You can use theSwitch Off Violations Pluginto control precisely which violations should not be reported. Check the documentation for more information.And as @oers said, it would be best to group your JAXB classes in specific packages to exclude them all with the "sonar.excludes" property.
I am using Sonar to list the violations in code. While, a lot of the violations are legitimate, some of the violations that it shows are a bit too far-fetched.For example, I want Sonar to exclude violations in logger statements and also in annotated JAXB classes. Since, these classes are widely spread across multiple packages in the project, I am not able to exclude any specific package.Is there a suitable way to resolve this problem.Thanks
Modifying Rules in Sonar
Sonar analysis is performed through a maven plugin. So, whenever you start a sonar analysis, maven will run through all phases that come before the sonar phase, meaning that it will also run the compile and the test phase.This means, if you want to do a Sonar analysis, you can make a Free-Style Job in Jenkins, configure no Build Step, and only activate the Sonar button. That should work, and should only build your code project once.
I installed Jenkins on my build machine and in the Jenkins config checked the box to run sonar analysis on my maven based project. It works but if I look at the log my entire project is built twice. Once from maven and once for sonar (still using maven). Any idea what I am doing wrong here?
Why does the sonar plugin in jenkins build everything again?
Hudson/Jenkins has theWarnings plugin. There's no similar plugin for Sonar, but I'm wondering if the compiler checks are redundant with the many checks embedded in Sonar (Checkstyle, Sonar Squid, PMD, Findbugs, ...).
Is there a plugin to show compiler warnings in Hudson and / or Sonar?
Hudson / Sonar report about compiler warnings
I believe i know what's going on. I believe your code is being weaved by Clover, and the clover code is embellishing that code and the way it does it is in a not so clean way.44: sipush 14625 47: invokevirtual #10; //Method com_cenqua_clover/CoverageRecorder.iget:(I)I 50: ifeq 57 53: iconst_1 54: goto 58 57: iconst_0 58: iconst_1 59: ior 60: ifne 85That is what FindBugs is complaining about.
I have a Comparator that checks "null"s for the two objects before comparing their contents. The compare method looks like this:public int compare(MyClass left, MyClass right) { if (left == null) { return right == null ? 0 : 1; } if (right == null) { return -1; } // do some other comparing }When I run this through sonar code quality checking tool, it reports "incompatible bit masks" error at the if statements. (It reads something like: "Correctness - Incompatible bit masks: Incompatible bit masks in (e | 0x1 = 0x0) yields constant result in ....Compare (MyClass, MyClass) I cannot see how this can be the case. Can anybody shed some light on this? Is this a false positive case?By the way, The sonar version I am using is 2.6.
Findbugs reports an incompatible bit mask bug, but I don't see how
The sonardocumentationrecommends running the sonar plugin in 2 stages:-mvn clean install -Dtest=false -DfailIfNoTests=falsemvn sonar:sonarThe tests are bypassed in the first phase and run implicitly in the second stage.A one line alternative is to run the following command:-mvn clean install sonar:sonar -Dmaven.test.failure.ignore=truebut this will run the tests twice - as you have found.
I have a bunch of Maven projects building in Hudson with Sonar sitting in the side-lines. Sonar gives me Sonar stats, FindBugs stats, and code-coverage.I've noticed that regardless of if I use Sonar or if I use EMMA via Maven directly,the entire build cycle runs twice.This includes init (which in my case, reinitializes the database -- expensive) and unit tests (a few hundred -- also expensive).How can I prevent this? I did a lot of reading, and it seems like this is due to the design of code-coverage plugins -- to keep uninstrumented classes separated from instrumented ones.I've tried configurations like:Maven runs: deploy, EMMAMaven runs: deploy; deploy to Sonar on completion
Hudson + Maven + Emma/Sonar = Build Cycle Runs 2x
You have to add the requested parameters on the Prepare step in the Advanced section:Detailed explanation of the parameters you can find here:https://docs.sonarqube.org/latest/analysis/languages/java/
While running Sonar Scanner in simple hello word through Azure pipeline and SonarQube getting below error.Your project contains .java files, please provide compiled classes with sonar.java.binaries property, or exclude them from the analysis with sonar.exclusions property.
ERROR: Error during SonarScanner execution org.sonar.java.AnalysisException:
You need to create a temporaryAuthenticationinformation@Test public void getAllInformationAboutUserTest() { // If you use Mockito -> Mockito.mock(Authentication.class) SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("foo", "bar")); ResponseEntity<Utilisateur> responseEntity16 = userController.getAllInformationAboutUser(); SecurityContextHolder.clearContext(); ResponseEntity<Utilisateur> responseEntity15 = userController.getAllInformationAboutUser(); }Result:
can you help me how I can cover if statement by junit test in this method:This is my Method in the controller "User" :@GetMapping(value = "/informationUser") public ResponseEntity<Utilisateur> getAllInformationAboutUser() { Utilisateur user = null; // Fully covered By tests Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); // Fully covered By tests if (authentication != null) { // Partially covered by Tests user = userService.findUserByLogin(authentication.getName()); // Not covered by Tests } return new ResponseEntity<>(user, HttpStatus.OK); Fully covered By tests }My problem is with the 2 lines of the if statment, I don't know how i want to cover them.This is my test code for this method :Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); ResponseEntity<Utilisateur> responseEntity16 = userController.getAllInformationAboutUser(); SecurityContextHolder.clearContext(); ResponseEntity<Utilisateur> responseEntity15 = userController.getAllInformationAboutUser();Thank you in advance for your help
junit- sonarQube test coverage : if condition
For those looking for a solution, you unfortunately need to tell sonarqube to ignore this file explicitly. Not an ideal solution, but what I ended up with.docs:https://docs.sonarqube.org/latest/project-administration/narrowing-the-focus/I put my filename insonar.coverage.exclusions.
I have a JavaScript app where we generate a code coverage report using Istanbul and use SonarCloud for static analysis.There are two ways we exclude code from the Istanbul. The first is to set exclusion paths. Injest.config.jswe have this to exclude patterns:"coveragePathIgnorePatterns": [ "source/legacy" ]The second way is to use Istanbul ignore comments in source files like/* istanbul ignore file */. In either case the ignored file will not be part of the generated report file.In our Sonar configuration we set it to use the generatedlcov.inforeport file with thesonar.javascript.lcov.reportPathsproperty. However we then also need to setsonar.coverage.exclusionsto exclude patterns likesource/legacybecause it is not treating thelcov.inforeport as the source of truth. This is acceptable but duplicates configuration, which is unfortunate. The real problem is that I cannot find any way to get Sonar to handle the files excluded with/* istanbul ignore file */.Is there some way to make Sonar treat thelcov.infofile as its source of truth, such that any file that is not included in the file is excluded from coverage?Alternately, is there a way with Istanbul where I can make it list ignored files but say that they are ignored? Maybe that way Sonar will see that they are ignored.
SonarCloud requiring code coverage for files ignored with Istanbul
I just get rid of this error stopping importing dynamically inside components declarationscomponents: { BasicTab: () => import('./Tabs/BasicTab'),I moved all the imports to the beggining of the statementimport BasicTab from './Tabs/BasicTab'It may not be the solutions but at least this error is gone
I'm having some issues running a scan of Vue.js code with SonarQube. I'm running the scan using SonarQube scanner (installed with yarn)yarn sonar-scannerSonarQube ScannerThe scan appears to go well, the scan does complete and I do get a list of items to fix on the SonarQube dashboard - however at some point I receive a wall of errors like these in the middle of the scan:ERROR: Failed to parse file [FILENAME] at line 27: 'import' and 'export' may appear only with 'sourceType: module'This happens regardless of whether it's importing a component or just a module like Axios.import Axios from 'axios' import Component from '@/src/js/global/component';Things i've looked atMake sure sourceType is set to 'module' in .eslintrc.json => It is set to moduleChecking if there is a Vue.js specific configuration for SonarQube => Do not see any specific documentation regarding configuring SonarQube for Vue.jsSaw the following post, but not using TypeScript:SonarQube-Scanner fails to analyze Vue files - Failed to parse file [.vue]Anyone suggestions would be appreciated.
Error when running SonarQube scan: ERROR: Failed to parse file [FILENAME] at line 27: 'import' and 'export' may appear only with 'sourceType: module'
To touch on your first question:Do you have the prerequisites set up?https://docs.sonarqube.org/latest/analysis/languages/javascript/And have you configured reportPaths and a reporter? I think that SonarQube needs this to run concurrently with your testing framework's coverage tool to analyse the overall project coverage data.https://docs.sonarqube.org/latest/analysis/coverage/Your second issuemight be sorted by the first solution. (I'm actually here because of my own problem: SonarQube isn't analysing a React component / JSX correctly and is seeing it as a code duplication. It's not my project, so I might just have to ask higher up to upgrade SonarQube... hopefully that solves it for me.)
I'm trying to analyze ongoing ReactJS project using SonarQube (first time with that tool) version 6.7.5 but after second code scan I'm getting Quality Gate failed due to 0% Coverage on New Code and 5% Duplicated Lines on New Code.First problem - I have no clue why I'm getting it at all (no coverage on new code) when I see new code got picked up by SonarQube. It looks like most of functional components are not covered by tests.Second problem - duplicates. Most of them are false positive like import statements or declarations (ex. react-table and columns declaration). Is there any way to mark them as non-duplicate? Or is there any workaround to get those kind of code blocks as valid (not dups)?
SonarQube with ReactJS - false positive on duplicates and coverage on new code
You may need to run your build pipeline on your on-premise agent in order to integrate with your local sonarque server. For cloud hosted agent cannot access local your SQ server with address 127.0.0.1:9000.It is easy to install and configure self-hosted agents, please check the microsoft official detailed guidancehere.Please check theexercise 2herefor detailed steps to integrate build pipeline with SonarQube .However you can also follow the detailed steps inexercise 1hereto create a sonarque server hosted on azure. Azure hosted SQ server works with both on-premise agents and microsoft-hosted agents.
[error][SQ] API GET '/api/server/version' failed, error was:{ "code": "ECONNREFUSED", "errno": "ECONNREFUSED","syscall":"connect","address":"127.0.0.1","port":9000 }I have configured sonarqube and it's running fine on localhost.
I get the following error when i try to connect sonarqube with azure devops build pipeline