Response
stringlengths
8
2k
Instruction
stringlengths
18
2k
Prompt
stringlengths
14
160
You don't need extra code, you just have make sure you calltest(true)andtest(false)and the test should show 100% branch coverage for that function
Considering the following code:function test(val){ flag = val; if (!flag) { doThis(); } createSomething(); }So, considering the unit test coverage, even the function statement is covered, the branches are not covered as else block doesn't exist. So the branches covered will be 50% and due to sonar issues, we will not be able to merge this to develop. So to get rid off this, useless code we write likereturn false;in the else block and make the script grow.Is it efficient way of writing the code? Is there a way to avoid writing useless un-necessary codes just to make sure the coverage is 100%. This is a bad practise, need suggestions to get rid off this. Do we have any setting, so that we can update ignoreelseblock statements and increase the coverage if not defined.Sonar forces to write else block:I have 100% code coverage, but the branch coverage is 50% just because of ignoring the else block. There are sonar rules defined if not more than 80%, we could not merge the code :(
How to avoid useless else block statements to increase branch coverage in unit test cases?
There is no hard limit, either within a single project or across the instance. However, depending on your infrastructure (e.g. disk space available for the DB) you may run into practical limits.
I'm about to use SonarQube on big projects and have been searching for info about LOC limit for analysis and there is no related information on their website. Is there? if it is, what's the limit?
SonarQube LOC analysis limit
With SonarQube 5.6.1, making it possible for users to run preview analyses but not push results to the server require the 2 following things:Those users don't have the global "Execute Analysis" permissionThose users have the "Browse" permission on their projectsThat's all they need.Note that if your developers are using IntelliJ, Eclipse or Visual Studio, you should encourage them to useSonarLint(connected to your SonarQube server) instead of running "preview" analyses manually. This will be far more efficient. And even if they don't have such IDE, they'd better useSonarLint for CLI.
SonarQube 5.6.1I need to allow users to run SonarQube analysis locally in preview mode, but I do not want them to be able to push anything to the server.I see that there is this assignable ability:EXECUTE ANALYSIS Ability to get all settings required to perform an analysis (including the secured settings like passwords) and to push analysis results to the SonarQube server.I need users to be able to do the first half of this:...get all settings required to perform an analysis...But not this part:...push analysis results to the SonarQube server.
How to run preview analysis locally, but disallow uploading to server?
According to thereference linkyou provided, the rule states:In a ternary expression avoid negation in the test. For example, rephrase: "(x != y) ? diff : same" as: "(x == y) ? same : diff". Consistent use of this rule makes the code easier to read. Also, this resolves trivial ordering problems, such as "does the error case go first?" or "does the common case go first?".It might be a bit confusing that the rule is named "confusing ternary rule" because what you have is a regular if-else construct, not a ternary expression. However, since?:can be thought of as shorthand for an if-else statement, you can also apply the rule here.Does it makes sense? Personally, I think absolutely. But if it doesn't apply to your (or your company's) coding style and, therefore, you get many violations, I'd rather remove—or adapt—the rule. As the reference says: consistency is important.
I write my java codeif(x !=null){ // Do something } else { // Do something }Then sonar Qube gives violation. Is the rule really needed for Confusing ternary?
Is Confusing ternary Rule in Sonar Qube really needed?
Theweb service docsshow that 100 is the default value of thepsparameter. You can set the value higher, but it will still max out.You might have noticed a"paging"element in the JSON response. You can use it to calculate how many pages of results there are and loop through them using thepparameter to specify page number.
Utilizing SonarQube 5.1, I have been attempting to utilize the API search feature to gather all of the issues pertaining to my current project to display on a radiator. On the Web interface, SonarQube indicates there are 71 major issues and 161 minor issues.Using this search stringhttps://sonarqube.url.com/api/issues/search?projectKeys=myproject'skeyI get back a response with exactly 100 results. When I process those results for only OPEN items, I get back a total of 55 issues. 36 major, 19 minor.This is being achieved through a Powershell script that authenticates to the SonarQube server and passes in the query, then deserializes the response into an array I can process. (Counting major/minor issues)With the background out of the way, the meat of my question is: Does anyone know why the responses I am receiving are locked at 100? In my research I saw others indicating a response to an issue search would be capped at 500 due to an outstanding bug. However the expected number of issues I am looking for is far below that number. The API's instructions indicate that it would return the first 10,000 issues. Is there a server side setting that restricts the output it will return to a search query?Thanks in advance,
SonarQube API Issue search is only returning 100 results
No, UTF8 character set is required since SonarQube 5.5. Seehttps://jira.sonarsource.com/browse/SONAR-6171.
I am using SonarQube for code analysis. I am trying to have Sonar connect to Oracle DB. I am getting this error -Exception sending context initialized event to listener instance of class org.sonar.server.platform.PlatformServletContextListener org.sonar.api.utils.MessageException: Oracle must be have UTF8 charset and BINARY sort. NLS_CHARACTERSET is WE8MSWIN1252 and NLS_SORT is BINARY.Is there any way to have Sonar use Oracle charset other than UTF8?
SonarQube - Connect to oracle using different charset
SonarSource provides acommercial plugin for Visual Basic 6. It may work for VBA if the syntax is the same.
We've have codebase with VBA/EXCEL. Which SonarQube plugin can analyze VBA inside excel or outside as text file. We can copy VBA to .vba text file if this is possible.If not is there any other tool which can help us perform Code Quality on these languages.
How to Code Quality on EXCEL VBA Code in SonarQube or Alternatives?
In SonarQube 4.5 if you start from the dashboard and click the Issues link you will see all the issues for every module. In the left box below the lists of Severities and Rules is a list of all the modules and sub-modules in your project. If you select from that list it will narrow down the centre and right boxes to just the packages and files within that module. Unfortunately it doesn't filter the rules or severities in the top boxes.In SonarQube 5.3 if you go to the issues tab you can select the module checkbox on the left side and select from your high runners. Near the top of the page is a hierarchy for the module you selected which you can click on to see the dashboard for that module or sub-module and then click issues for just that part. Then if you want a sub-module that isn't in high runners note that the URL is editable if you are careful and know your target hierarchy.I haven't found a better way than that yet in 5.3, but after only a few days playing with a recent 5.3 upgrade I am generally liking the UI changes.
I want to investigate how certain rules and issues have been violated in a certain package, however, from what I have seen in the Components-interface in SonarQube, it is only possible to view leaf node-directories and I am interested in viewing the entire folder, including sub-folders and files in that folder.E.g.Project src package1 subdirectoryone done code-a.java dtwo code-x.java dthree code-i.java code-1.java code-2.java subdirectorytwo package2 subdirone subdirtwoIn this example I would like to investigate the issues and rule violations insubdirectoryoneincluding the code files at all levels in the directory.Is there a way I can do this?
How can SonarQube be used to view results for specific directories (packages) of a project?
From your log it seems you're using default java aka gnu.gcj.You should installopenjdk7oropenjdk8You could select proper JVM in $SONAR_HOME/conf/wrapper.conf by editing wrapper.java.command property ie# To use Java 7 wrapper.java.command=/usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java # To use Java 8 wrapper.java.command=/usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java
I have a fresh install of Debian 8 on a VM with 4GB RAM. I installed SonarQube (using the native package). When I try to start with the supplied script, the log says the following:--> Wrapper Started as Daemon Launching a JVM... JVM exited while loading the application. GC Warning: Out of Memory! Returning NIL! Exception in thread "main" GC Warning: Out of Memory! Returning NIL! java.lang.OutOfMemoryError *** Got java.lang.NoClassDefFoundError: gnu.gcj.runtime.NameFinder while trying to print stack trace. JVM Restarts disabled. Shutting down. <-- Wrapper StoppedI tried increasing the -Xmx and -Xms values in the start script to no effect.
"Out of Memory!"-error on Debian 8 when starting SonarQube installed from native package
Those properties are not meant to be configured on the server side, they are passed on the scanner side, and are valid only for analysis in preview mode (by the way no need forsonar.issuesReport.json.enable). That's whatSonarLint for Command Lineis about.Why preview mode ? Because the goal is to analyse a diff (to comment the code review in your case). You don't want a full analysis to be submitted to SonarQube if the code is not yet pushed to the repo.Example:$ sonar-runner -Dsonar.analysis.mode=preview -Dsonar.issuesReport.html.enable=true -Dsonar.report.export.path=report.json -Dsonar.host.url=http://localhost:9000 [...] $ ls .sonar/ issues-report report.json(careful with the JSON report, looks like it will ultimately be removed, seeSONAR-7247)P.S.: I guess you might be using thesonar-gerritJenkins plugin, which is essentially saying the same thing:This plugin is intended to work with report provided by SonarQube running on your project in preview mode
I am runnig Sonarqube 5.3 and has integrated it with Jenkins. I want to post Sonareqube issues as Gerrit comments.Then I need to specify the path to and name of the data generated from sonarqube, e.g. build/sonar/sonar-report.jsonThe file sonar-report.json is not generated and I have found some setting for Sonarqube that shouold make sonareqube create the file.sonar.report.export.path=sonar-report.json sonar.issuesReport.html.enable=true sonar.issuesReport.json.enable=true sonar.issuesReport.console.enable=trueI have tried to set these in the file<sonar-installation-directory>/conf/sonar.propertiesI have restarted the Sonare service and restarted the computer but the sonar-report.json file is still not created.
How to get the sonar-report.json file created with sonarqube?
Here is a link to failing the build on quality gate violations with 5.3 or later, it uses the SonarQube for MSBuild - Begin Analysis taskhttps://blogs.msdn.microsoft.com/visualstudioalm/2016/02/11/use-sonarqube-quality-gates-to-control-your-visual-studio-team-services-builds/This updated task is not available with TFS 2015 Update 1 but is available in Update 2 RC1 and VSTS (VSO).Regards, Wes
We useVSTSbuild with standardSonarQubebuild steps:SonarQube for MsBuild - Begin Analysis... buildSonarQube for MsBuild - End AnalysisSome time after build I can see Analysis results in SonarQube - whether it Passed or Failed quality gate. But the VSTS build is successful even if quality gate is Failed.Is there a way to fail a VSTS build if quaility gate is failed?Following this:http://docs.sonarqube.org/display/SONAR/Breaking+the+CI+BuildI've tried looking forreport-task.txtfile, but I can't see it anywhere.I can probably just runMSBuild.SonarQube.Runner.exeas command-line build step, as described here:http://docs.sonarqube.org/display/SONAR/Analyzing+with+SonarQube+Scanner+for+MSBuild#AnalyzingwithSonarQubeScannerforMSBuild-AnalyzingfromtheCommandLineBut I thought I should first try standard Build Steps for SonarQube
Fail VSTS build if SonarQube fails quality gate
TheanalysisIdis the ID of a snapshot. Normally, you never see this in the Web interface. The main place where you will find it is in the<work_dir>/report-task.txtfile that is generated at the end of an analysis in your file system.In fact, the main (at least original) purpose of thisapi/qualitygates/project_statusWS introduced in SQ 5.3 is to be used when you want to break the build after the report of an analysis has been submitted to the server. You can find the comprehensive explanation on the"Breaking the CI Build" documentation page.
GET api/qualitygates/project_status call to sonar requires analysisId. I am not able to figure out that how to get the same.http://nemo.sonarqube.org/api_documentation/api/qualitygates/project_statusIn report-task.txt i have only this information createdprojectKey=org.cidemo.multispring:parent serverUrl=http://localhost:9000 dashboardUrl=http://localhost:9000/dashboard/index/org.cidemo.multispring:parent ceTaskId=AVI5GTgLuMgLdhRswoyi ceTaskUrl=http://localhost:9000/api/ce/task?id=AVI5GTgLuMgLdhRswoyiAnd no analysisid. There is nothing mentioned in the doc shared by you as how to get this id. In my env i want to check if code passed the quality-gate, and fail the build if it dont passes.I do not want to use this using Jenkins.I have created a pre-commit hook in which i am calling a sonar run when developer tries to commit and if code do not pass the quality gate ,commit must be aborted.Let me know if there is a better way to do this.
How to get analysisID in sonar
SonarQube is right, you should not directly callfutureTask.run(). Use an ExecutorService instead:ExecutorService executor = Executors.newFixedThreadPool(1); executor.execute(futureTask1);Thisis a short and good tutorial on the topic.
I have the below code for which Sonar Qube is raising a critical error.public void onMessageReceived(Message message) { if((message.getTargetInstanceId() != Message.ANY_TARGET) && (message.getTargetInstanceId() != this.instanceId)) { //Invalid message ignore return; } else { int randTime = ran.nextInt(2000); FutureTask<Message> workerTask = new FutureTask<>(new DummyCommandHandler(randTime, message,messageBus,instanceId)); workerTask.run(); } }Below is the issue I am getting.Description Assignee Resource New issue Thread.run() and Runnable.run() should not be called directly : Call the method Thread.start() to execute the content of the run() method in a dedicated thread.To call a start method in FutureTask, it doesn't have a start method in the first place. It only has a run method. How can I overcome this issue? Are there any Java solutions or Sonarqube solutions? Please advice.
How can I eliminate sonar qube issue when calling the run method of FutureTask?
You are encoutering the following issue :https://jira.sonarsource.com/browse/SONARJAVA-1369It happens when you have a parameter with%<during the printf check (rule squid:S2275).Issue has been fixed (few minutes ago for the record ;) ) and should be part of next release bound to happen within the next few days.
Using SonarQube 5.2 - just the "click and go" distribution downloaded yesterday and running under Windows. Nothing fancy.After upgrading the "Java" rules package from the bundled 3.6 version to 3.7.1, the sonar runner then fails during analysis.There's a long stacktrace that is revealed when running with '-e' option however there is no detail on where in the file it failed (line-number, method) or which rule failed.I have pared down the stack-trace to what I believe are the useful bits:ERROR: Error during Sonar runner execution org.sonar.runner.impl.RunnerException: Unable to execute Sonar ... Caused by: org.sonar.squidbridge.api.AnalysisException: SonarQube is unable to analyze file : 'C:\Users\robert.rusk\Documents\cvs\ip_probe\src\com\robert\splat\MyClass.java' ... Caused by: java.lang.IndexOutOfBoundsException: index (1) must be less than size (1) ... at org.sonar.java.checks.PrintfCheck.verifyParameters(PrintfCheck.java:173) at org.sonar.java.checks.PrintfCheck.onMethodInvocationFound(PrintfCheck.java:112) ...
SonarQube analysis fails after upgrade to 3.7.1 rules
Hi this seems to be a bug in deprecation link as the rule is numbered S864 (without the zeros) see :http://nemo.sonarqube.org/coding_rules#rule_key=squid%3AS864This one is already fixed (seehttps://github.com/SonarSource/sonar-findbugs/blob/master/src/main/resources/org/sonar/l10n/findbugs/rules/findbugs/IM_MULTIPLYING_RESULT_OF_IREM.html) but not yet released.And for the other one, the repository is not correct, it is not in squid repository but in common-java : seehttp://nemo.sonarqube.org/coding_rules#rule_key=common-java%3AInsufficientCommentDensityCan you reprecise which rule exactly generate this 2nd broken link ? so we can fix it.
On SonarQube 5.2 (after successive upgrade, not test on fresh now install) I managed my quatlity profile by removing all deprecated rules and replace them by suggested one.But for ruleCorrectness - Integer multiply of result of integer remainder, findbugs:IM_MULTIPLYING_RESULT_OF_IREM, the suggested one isS00864. But the link does not give me the rule accessible throw the link /coding_rules#rule_key=squid:S00864Same thing for ruleNcss Type Count, findbugs:AIM_MULTIPLYING_RESULT_OF_IREM, suggested one isInsufficientCommentDensityaccessible throw the link /coding_rules#rule_key=squid:InsufficientCommentDensityMay be suggested are were previously deleted ? Does someone have those rules in SonarQube instance ?
SonarQube deprecated rule suggestions missing
This has no right answer as this is a convention. Moreover it is subject to debate about what should be considered as constant (is it enough to have static final or should it be also immutable ?).As you cannot configure this rule from sonarLint, I think it should not be a rule activated by default hence this jira ticket :https://jira.sonarsource.com/browse/SONARJAVA-1385
I am trying to check the code quality withsonarlint.Above problem synopsis, I can't understand why should it says to make it to uppercase.Butthis discussionis against the above suggestion.Which one should be considered as correct one?
Rename the "log" logger to comply with the format "LOG(?:GER)?"
I do confirm that this is a known limitation, seehttps://jira.sonarsource.com/browse/SONAR-3321
After I renamed a Java package the SonarQube Preview shows me about +174 issues. About 150 of which already have been flagged as false-positives, but have been in another package back then.(How) can I inform SonarQube about that package rename so that already flagged issues are recognized and do not pop-up again?P.S.: I'm using SonarQube 5.1
How inform SonarQube about a package rename?
The latest version (4.0) of C# plugin won't work on linux servers like your RedHat, due to the fact that it requires the analyzer machines to run on Windows, and the .NET Framework 4.5 to be installed. You can find more info onofficial C# plugin page for Sonar. Team responsible for plugin starting from version 3.4 droped Java based parser and they've written new version in C#.
I'm trying to analyze a .Net in sonar using Jenkins, but everything I build the project I get the error below:Caused by: org.sonar.api.utils.command.CommandException: java.io.IOException: Cannot run program "/var/lib/jenkins/jobs/Ing1345-BalancedScoreCard/workspace/.sonar/SonarQube.CSharp.CodeAnalysis.Runner/SonarQube.CSharp.CodeAnalysis.Runner.exe": error=13, dennied permissionI've read some post about the error and they say I should give execution permission to that folder, but it doesn't work.Any idea of how I can solve this issue.Jenkins Version:1.609.1 Sonar Version: 5.1.1 Maven version:3.3.3 SonarQue Runner version:2.4 OS: RedhatThanks in advance for your help
Trying to analyze .NET project with Sonar using Jenkins
The sonar-maven-plugin is an independent project that does not follow SonarQube versioning. Correct command-line ismvn org.codehaus.mojo:sonar-maven-plugin:2.6:sonarThe groupId mvn.codehaus.sonar is for internal use.
I've just installed the latest version of SonarQube (5.1.1) and when I try to run the sonar:sonar target, I get an error:Embedded error: Unable to build project for plugin 'org.codehaus.sonar:sonar-maven-plugin': POM 'org.codehaus.sonar:sonar-maven-plugin' not found in repository: Unable to download the artifact from any repository org.codehaus.sonar:sonar-maven-plugin:pom:5.1.1I've checked here:http://mvnrepository.com/artifact/org.codehaus.sonar/sonar-maven-pluginAnd it seems that version 5.1.1 of the sonar-maven-plugin has not been pushed to the public repo(s).Is that so or am I looking in the wrong location?
sonar-maven-plugin 5.1.1 not found
The first entry point into the development of SonarQube analyzer is theplugin development documentation. You might also want to have a look at the structure and architecture of existing language plugins, such asJavaScript,Groovy,PHPorJava.
I need to extend SonarQube, so that I can add new analyzers into it. I have tried adding a new rule for java files using xpath. I want to know how to add code analyzers in SonarQube for a new language, e.g. for.metafiles. How can I go about this?
Extending Sonarqube analyzers
Like for every language plugin that offers rules in SonarQube, you shouldcustomize those rules(severity, parameters) your quality profile in SonarQube itself - not in a file that belongs to your project.So in your case, you have to go on the quality profile used for your project, find the rule that creates issues for missing translations, and change its severity to minor.
I analyzed my Android project with SonarQube (Android Lint profile).By default, Lint shows missing translations as Critical, but I consider them a minor problem.So I wrote thislint.xmlfile in the project's home (same folder assonar-properties.xml):<?xml version="1.0" encoding="UTF-8"?> <lint> <issue id="MissingTranslation"> <ignore path="res/values/constants.xml" /> </issue> </lint>Unfortunately, SonarQube does not seem to take this file into account.How to make SonarQube use mylint.xml?
Make SonarQube (Android Lint profile) use the project's lint.xml
If you want to be able to link issues to JIRA, then you must specify all your properties in Sonar Web UI, not in your Ant build script.Indeed, properties set on project files (may they be POM / sonar-project.properties / build.xml files) are not stored in the DB, so the UI can't retrieve this information and therefore won't display the link.
After installing theSonar JIRA pluginand restarting the Sonar server, I have run an analysis with the following properties configured in the Sonar Ant task:sonar.jira.url (no HTTPS used)sonar.jira.login.securedsonar.jira.password.securedsonar.jira.url.param (a JIRA filter)sonar.jira.project.key (the project key that is also used as prefix in JIRA issue keys)The JIRA widget shows results for the configured JIRA filter, but the item "Link to JIRA" is missing from the "More actions" pop-up menu. I have tried this with Sonar 3.0, 3.4.1 and 3.5.What could be wrong?
Sonar JIRA Plugin: "Link to JIRA" is missing
This rule is brought by PMD into Sonar, and it is quite basic: it just checks if there's a "myResource.close()" call in the finally block. Full stop. If you're extensively using your "small function", then you should probably consider deactivating this rule as it will generate too many false positives.You could also try to activate Findbugs rules that may be more intelligent. See those rules onour Sonar demo instance - Nemo.
In my Dao classes, for closing db resources I have written a small function which takes in ResultSet, Connection and Statement objects and closes it.I call this from finally block of each DB access method that I have. But Sonar is showing these as violations like:Ensure that resources like this Statement object are closed after useIs there any way to let Sonar know that these are handled?Profile used is 'Sonar Way'
Close Resource violation in Sonar
These are warnings issued by Findbugs, which requires access to source, compile binaries and 3rd party libraries.To resolve these warnings you need to include an additionalsonar.librariesproperty, populated with the 3rd party jars your code depends upon (SeeAnalaysis Parameters documentation)
Im trying to run a sonar analysis on a Jenkins Job. Im using ant so im using Sonar Runner and sonar.properties in the projects. Im configuring the the binaries tosonar.binaries=build/ant/classesAfter a successfull build Sonar starts and is running a while. But i get a lot of warnings during bytecode analysis.Im getting WARN XX - Class 'XX' is not accessible through the ClassLoader.for every class...I dont really know why classes are all there?
Sonar using Sonar Runner on Jenkins Job fails to access classes
The H2 database is not listed in theSonar pre-requisites. This is a pity because, like you, I consider it superior to Apache Derby.The Sonar team strongly discourage the use of Derby for production environments. I read in the release notes that Derby upgrades are now disabled. Do you have a good use case for using H2 apart from dis-liking Derby? :-)It can be tempting to setup Sonar initially with an embedded database. Problem is Sonar adoption within your organisation can go viral, eventually the day will come when someone starts to ask about backup and DR.... This is where having a proper database in place will make this transition easier.UpdateSONAR-3622: Reports the H2 database as supported. This support is coming in Sonar 3.2:David Gageot added a comment - 04/Jul/12 5:06 AMLatest version is more intelligent. h2 is the default for sonar>=3.2 and derby is the default for sonar<3.2
I wonder is it possible to run sonar 3.1.1 with h2 database? I tried to deploy sonar configured with h2 database and got following exception:21-Jul-2012 23:32:45 org.apache.catalina.core.StandardContext listenerStart SEVERE: Exception sending context initialized event to listener instance of class org.sonar.server.platform.PlatformLifecycleListener org.sonar.api.utils.SonarException: Unable to determine database dialect to use within sonar with dialect null jdbc url jdbc:h2:tcp://localhost:9092/~/sonarI searched a bit and the most probable cause is that 3.1.1 does not support h2. Are there any workaround to run 3.1.1 with h2?
sonar on h2 database
This probably doesn't help much, but I'm pretty sure that this is not supported.Sonar will only allow you to view the results by tested class, not by test class.One way to work around this would be to run Sonar multiple times, once for each test class, but that's probably not easy to do and probably not what you're looking for.
I know I can drill down in the coverage widget on the dashboard and see the code and branch coverage. However, I would like to see what source files and lines of code are covered by each individual test. It's looking like Sonar doesn't support this the other way around. If it's not supported, is there a way I can configure Sonar to do such? FYI, we are using JaCoCo for test coverage right now. Any info greatly appreciated!
In Sonar, how do I view test coverage by tests?
Each of those tools has a specific focus. Veracode is used for finding security vulnerabilities. SonarQube is used for determining general code quality. SonarQube has some static rules that address some vulnerabilities, but those are limited, and Veracode does much more thorough analysis of security vulnerabilities.
Is sonar and veracode serves the same purpose or we can use both tools to scan our applications?Metrics like, coverage, duplications, bugs and code smells are avilable in sonar but they are not available in veracode. so we need to use both tools or we can scan above mentioned metrics in veracode as well?Thanks
Sonar and Veracode
As Sonarsource saying:Double Brace Initialization (DBI) is so obscure...Double Brace Initialization should not be usedYou could do something likeMap<String, String> propertiesValueMap = createMap(); private static Map<String, String> createMap() { Map<String, String> myMap = new HashMap<String, String>(); myMap.put(SOME_STRING, SOME_STRING) return myMap; }Or, if you are creating an immutable Map and using Java 9 :import static java.util.Map.entry; Map<String, String> propertiesValueMap = Map.ofEntries( entry("SOME_STRING", "SOME_STRING"), entry("SOME_STRING2", "SOME_STRING2") );
I have this code where I am initializing thisHashMaplike:final HashMap<String, String> propertiesValueMap = new HashMap<String, String>(){{ put(SOME_STRING, SOME_STRING); put(SOME_STRING, SOME_STRING); put(SOME_STRING, SOME_STRING); }};The above code is giving non complaint code issue in SonarQube. is there any other way by which i can initialize?I know one way likeStream.of(new String[][]{ { SOME_STRING, SOME_STRING},{SOME_STRING, SOME_STRING} }).collect(Collectors.toMap(data->data[0],data->data[1] ));But this will return meMap<String,String>and I wantHashMap<String,String>.
Sonarqube is giving HashMap initalization code compliant issue
Your pipeline seems to contain the right steps, so there can be two issues:1. Code coverage file is not generated (correctly)The easiest way to validate if the code coverage file is generated correctly, is by publishing it as an artifact. Now check what format the output file is. If there is no output file, please check if you did include/p:CollectCoverage=true --logger trxto the test command. If you are running the build pipeline on Linux, you should also add/p:CoverletOutputFormat=opencoverand install the coverlet.collector NuGet package in the .NET Test Project.2. Code coverage file is not sent to SonarqubeIf you configured step 1 correctly, it is still possible that the generated files are not sent to Sonarqube. The best way to see what is going wrong, is by checking the build logs of the Run Code Analysis and Publish Quality Gate Results steps.The most common issue, is that Sonarscanner is checking the wrong directory. In the prepare step, please specify where the files are located, like:sonar.cs.opencover.reportsPaths=$(Build.SourcesDirectory)/**/coverage.opencover.xml sonar.cs.vstest.reportsPaths=$(Agent.TempDirectory)/*.trx
I have an .Net Core application along with unit test cases. For that I have configured the Build pipeline in Azure DevOps. In that pipeline I have integrated SonarQube tasks (prepare analysis, run code analysis, and publish quality gate results).I can see the report in SonarQube server after successful run. But in that report, I didn’t see the Code Coverage Results and Unit test results. Even though I used Cobertura for unit tests.
How to see the Code Coverage results in Sonar Qube using Azure DevOps pipelines
TheReplace <insert_your_build_command> by the actual oneshould mean you should replace it with the steps you do to build your project. In your case, since it seems to be a dotnet project, following can be inserted:dotnet buildPlease update if it works.
I’ve been trying to scan a project written in C# in Sonarcloud and when I write the .github/workflows/build.yml file, I should “Replace <insert_your_build_command> by the actual one”. Maybe I’m a bit stupid but I have no clue what I should use as the build command.Maybe someone here has an answer to this :)Thanks!
Sonarcloud: YML file - what to use as clean build command
There are two workarounds.Install LTS version instead withbrew install sonarqube-lts, it seems to support M1 architecture with no issues.ORInstall sonar through x86_64 brew:Install x86_64 brew under /usr/local/bin/brewarch -x86_64 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"Create an alias for the x86_64 brewAdd to .zshrc:# brew hack for x86 alias ibrew='arch -x86_64 /usr/local/bin/brew'Install sonaribrew install sonar
I'm trying tobrew install sonarqubeon a Apple M1 but I'm getting this errorsonarqube: The x86_64 architecture is required for this software.is there a workaround ?
sonarqube: The x86_64 architecture is required for this software
This error happened when you launch the command with a Maven version prior to the needed version (3.1+).In my case, it was Maven 3.0.5.
I try to use the Apache Maven plugin for Sonatype OSS Index (https://sonatype.github.io/ossindex-maven/maven-plugin/) to audit my project dependencies using Sonatype OSS Index.When I launch the command :mvn org.sonatype.ossindex.maven:ossindex-maven-plugin:audit-aggregate -f pom.xmlI have the following console error :[ERROR] 1) No implementation for org.sonatype.ossindex.maven.common.ComponentReportAssistant was bound. [ERROR] while locating org.sonatype.ossindex.maven.plugin.AuditAggregateMojo [ERROR] at ClassRealm[plugin>org.sonatype.ossindex.maven:ossindex-maven-plugin:3.1.0, parent: sun.misc.Launcher$AppClassLoader@6d9bf996] [ERROR] while locating org.apache.maven.plugin.Mojo annotated with @com.google.inject.name.Named(value=org.sonatype.ossindex.maven:ossindex-maven-plugin:3.1.0:audit-aggregate)
"No implementation for org.sonatype.ossindex.maven.common.ComponentReportAssistant was bound" error when using Maven plugin for Sonatype OSS Index
The sonar warning is caused because thecalendarobject could be updated from multiple threads. Either, as you said you could declare thecalendaras local to the method.OR 1) Make a synchronized block in your code. (using localcalendaris better)Date effValueDate ; synchronized(calendar) { calendar.setTime(some_date); calendar.add(Calendar.DATE, value); effValueDate = calendar.getTime(); }RECOMMENDED:Use the new java API classes for date and time (java.time).// or use DateTimeFormatter.ISO_LOCAL_DATE DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd"); LocalDateTime date = LocalDate.parse(reqDate, pattern).plusDays(value).atStartOfDay(); Duration duration= Duration.between(date, LocalDateTime.now()); long seconds = duration.getSeconds();Read moreabout the new API
I have the following variable declared :private static Calendar calendar = Calendar.getInstance();I am using that variable 'calendar' in a static method like below :myStaticMethod(String reqDate){ DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); Date some_date; long seconds = 0; int value = 10; try { some_date = df.parse(reqDate); calendar.setTime(some_date); calendar.add(Calendar.DATE, value); Date effValueDate = calendar.getTime(); seconds = (effValueDate .getTime() - System.currentTimeMillis()) / 1000; } catch (ParseException e) { //---Do---something---- } }I am getting the following sonar error :Make "calendar" an instance variable. Not all classes in the standard Java library were written to be thread-safe. Using them in a multi-threaded manner is highly likely to cause data problems or exceptions at runtime. This rule raises an issue when an instance of Calendar, DateFormat, javax.xml.xpath.XPath, or javax.xml.validation.SchemaFactory is marked static.This is my solution, but I am not sure if the solution quality is good enough.myStaticMethod(String reqDate) { Calendar calendar = Calendar.getInstance(); // the do the next processing }So how can I fix the error... can I use a localCalendarvariable in this case instead of class variable or is there any other smart way to address this.
sonarqube error on static Calendar variable
Make your code a bit more DRY and simplified by collecting your common cases that return the same values. I don't think SonarQube validates readability, but proper use of whitespace can go a long way in readability of unfamiliar code. It's opinionated, but I like a line between case returns.const getEmailTo = (subject) => { switch (subject) { case 'POWERUP_REWARDS': case 'GAME_INFORMER': case 'APP_REVIEW': case 'SOMETHING_ELSE': return COMMON_EMAIL; case 'ONLINE_ORDER': case 'STORE_EXPERIENCE': return '[email protected]'; default: return ''; } };
On Sonarqube I'm getting this as critical issue, can somebody help me in this to sort out this issue. Here is the code details, please let me know how can I refactor this code with switch case :const getEmailTo = (subject) => { switch (subject) { case 'POWERUP_REWARDS': return COMMON_EMAIL; case 'GAME_INFORMER': return COMMON_EMAIL; case 'ONLINE_ORDER': return '[email protected]'; case 'STORE_EXPERIENCE': return '[email protected]'; case 'APP_REVIEW': return COMMON_EMAIL; case 'SOMETHING_ELSE': return COMMON_EMAIL; default: return ''; } };
Refactor this function to reduce its Cognitive Complexity from 18 to the 15 allowed
That exception isn’t handled globally, it’s thrown away. You should use a pattern of:try{ //code } finally { //close connection }This removes the warning from Sonar and makes your apparent intentions true (that the global handler will deal with the exception) otherwise you’re just going to silently lose every error this code throws which will cause your help desk team no end of joyI’ve declined to answer the question as stated for this reason, but the answer you seek is in Sonar’s fine manual if you desperately want to go that route; itwillbite you
I am getting a message on Sonar:Handle the exception or explain in a comment why it can be ignored.How do I get rid off this warning by providing a comment explaining to ignore this?I am using C# for coding and my catch block iscatch {}catch { // handled globally } finally { connection.Close() }Catch code and on finally block I have added some code to close connection.
How to comment why a catch can be ignored
With every plugin, we can add section<configuration> ... <skip>...</skip> ... </configuration>in an<execution>-block to control when the execution should be skipped. In the given case, we can bind the skip logic to the propertyskipTests:<plugin> <groupId>org.sonarsource.scanner.maven</groupId> <artifactId>sonar-maven-plugin</artifactId> <version>${sonar.maven.plugin.version}</version> <executions> <execution> <id>sonar</id> <phase>test</phase> <goals> <goal>sonar</goal> </goals> <configuration> <skip>${skipTests}</skip> </configuration> </execution> </executions> </plugin>
I have set up Sonar as maven plugin in my pom, and would like the plugin to run only if tests are run. Use case is I want the sonar plugin to run on my CI server, but not when packaging the jar. Somvn testshould execute the sonar plugin, butmvn -DskipTests clean packageshould not.Today the sonar plugin are running also when I skip the tests.My setup today:<sonar.host.url>https://sonar.myserver.no</sonar.host.url> <sonar.login>my token</sonar.login> <sonar.projectName>My app</sonar.projectName> ..... <plugin> <groupId>org.sonarsource.scanner.maven</groupId> <artifactId>sonar-maven-plugin</artifactId> <version>${sonar.maven.plugin.version}</version> <executions> <execution> <id>sonar</id> <phase>test</phase> <goals> <goal>sonar</goal> </goals> </execution> </executions> </plugin>
Skip sonar plugin execution if maven tests are skipped
I found the solution in thesonar doc, it say:There's no point in having a JUnit TestCase without any test methods. Similarly, you shouldn't have a file in the tests directory with"Test"in the name, but no tests in the file. Doing either of these things may lead someone to think that uncovered classes have been tested.This rule raises an issue when files in the test directory have "Test" in the name or implement TestCase but don't contain any tests.Supported frameworks:JUnit3JUnit4JUnit5TestNGZohhakArchUnitAll you should to do is to use a class name withoutTestin my case I usedFakeData, else it will considered as a unit test.
I have an util class where I create Fake date for my unit test, I put it in test part of my Object:public class FakeDataToTest { //.. fake objects }But Sonar give a Blocker, because this class doesn't contain unit test, in another word not have a method annotated@Test, the message of sonar is:Add some tests to this class.What is the clean way to avoid this ?
Sonar: Add some tests to this class
No idea about this system, but it seems to complain about T not appearing in the Parameter list. I am unsure that is a legitimate warning. The onlyList<T>functions that use T as arguments are the Add ones. Everything else works perfectly fine with T being only used for the return type - or even nowhere at all.If the existing generic classes written by people with decades of experience violate the rules, it is propably a stupid rule. If you really need to follow this rule, you could use a ref or out parameter instead of creating your own instance and returning, I guess?
SonarQube rule S4018 requires generic methods to provide the generic type as a parameter.For example, this would be illegal because T is not passed in as a method parameter:public T DoStuff<T>(string json) { return someResult.ToObject<T>(); } // call the method var result = myClass.DoStuff<SomeObject>("some json");This is the violation text: "Refactor this method to have parameters matching all the type parameters"This is a link to the rule documentation:https://next.sonarqube.com/sonarqube/coding_rules?open=csharpsquid%3AS4018&rule_key=csharpsquid%3AS4018Is there a straight-forward way to make this valid that I'm just not aware of? Is this rule even valid? The examples in the documentation only use void-type methods whereas I want a generic return type.
What is the best way to refactor this generic method to satisfy SonarQube S4018
IMHO, you can mark it as a false positive. Thestated reasonsfor the issue areIt can significantly impair the readability of the code.It introduces additional side effects into a statement, with the potential for undefined behavior.It is safer to use these operators in isolation from any other arithmetic operators.Given the circumstances of your current code, I'd say they are invalid. The code is perfectly readable as it is and there's no undefined behavior possible and I don't see any safety concern there.
I am using Apache POI to create a excel form a Java POJO class.The POJO has 65 fields which needs to be populated while creating a POJO.One way I figured out was -int i = 0; hssfRow.createCell(i++).setCellValue(POJO.getField1()); hssfRow.createCell(i++).setCellValue(POJO.getField2()); hssfRow.createCell(i++).setCellValue(POJO.getField3()); ..... hssfRow.createCell(i++).setCellValue(POJO.getField65());The drawback of the above approach is SonarQube says it is non compliant with the following reasonExtract this increment or decrement operator into a dedicated statementThe first question is why is it not advised to usei++here?Also, is it advisable to declare constant from 1 to 65 in a separate Constant class and use it instead ofi++(i.e.hssfRow.createCell(Constant.ONE))?And is there any alternative to this solution which is compliant and is a better approach?
SonarQube-compliant solution, increment cell value
This is from the ruleThe purpose of checked exceptions is to ensure that errors will be dealt with, either by propagating them or by handling them,but some believethat checked exceptions negatively impact the readability of source code, by spreading this error handling/propagation logic everywhere.This rule verifies that no method throws a new checked exception.It's not an absolute rule. It's just up to you if you want to prevent people from throwing checked exceptions in your code.Remember that Sonar rules are just rules, if you don't agree with some, simply disable them. This one in particular looks very opinion-based.If you can't disable it, resolve the issue aswon't fixand add a comment to explain that you need to throw this exception because the architecture requires so.Personally I think that checked exception are a bit annoying but I wouldn't enable this rule, I don't find it relevant.
There is a SonarQube rule that states that "...no method throws a new checked exception."And it gives the following code example:public void myMethod1() throws CheckedException { ... throw new CheckedException(message); // Noncompliant ... throw new IllegalArgumentException(message); // Compliant; IllegalArgumentException is unchecked } public void myMethod2() throws CheckedException { // Compliant; propagation allowed myMethod1(); }How then can you actually throw a custom checked exception?Let's say I catch a IOException and do a getMessage() to get the detail message string of the IOException.Then have a condition checks the content of the string to throw a more specific custom checked exception (extends Exception).How do I actually accomplish this without violating SonarQubes rule that I notthrow new CheckedException(message);?Does this rule mean that SonarQube never wants the developer to throw a new custom checked exception?
How can you throw a checked exception without violating SonarQube?
There is nothing out of the box in SonarQube for your case, but you could apply some workaround for this.Create new project in SonarQube for each team and pass what sub-projects they are not interested in, for example:/k:"ApplicationName_Team1" /n:"ApplicationName :: Team1" /v:"12345" /d:sonar.coverage.exclusions=**\PathsToRemove\** /d:sonar.cpd.exclusions=**\PathsToRemove\** /d:sonar.exclusions=**\PathsToRemove\**This way you can analyze only subset of your code. Create similar configurations for other teams.
We have a monolithic application in development. Development is done by several backend teams. Our application is not tightly coupled and in general you can say, that each team is responsible for it's own set of Symfony bundles (say, top-level directories insidesrcfolder).We are now trying to use SonarQube for static analysis and overall code quality control, but I can't find a good way for each development team in GUI to see statistics for it's own application part only.There is a project view (Projects -> [project] -> Code) but it's just an unusable plain list of files and problems. There are about 2000 lines in total and this is really unmanageable.Documentation for SonarQube says, that subprojects are removed from it and apart from them I just can't find a way to make it usable for us.Is there a way for each of our teams to see it's own set of cases and monitor quality of it's own application part only?
SonarQube use case in a multi-teamed monolithic application development
You can pass the number of seconds as a parameter and multiply it with an interval of 1 secondselect * from table where modified_on < now() - (? * INTERVAL '1 second')
How do i change the following query to comply withSQL Injectionruleselect * from table where modified_on < now()- INTERVAL '" + interval + " seconds'I could't change the query for preparing Prepared Statement in Javaselect * from table where modified_on < now()- INTERVAL ? seconds
How to comply with Sonar's rule "SQL binding mechanisms should be used"
Here thewhileappears helpless :boolean wait = true; while (wait) { wait = false; monitor.wait(config.getWaitTime()); }Thewhilestatement around thewait()statement is designed to check that thewait()be re-invoked if the logical/function condition in thewhileistruebut in your case it is never as you assign wait tofalseas first statement of the while body.Thewhileis so helpless.Here is theObject.wait(long)javadocassociated to :A thread can also wake up without being notified, interrupted, or timing out, a so-called spurious wakeup. While this will rarely occur in practice, applications must guard against it by testing for the condition that should have caused the thread to be awakened, and continuing to wait if the condition is not satisfied.As often I am not convinced at all of Sonar advises....You could use a timer to check that the required time was elapsed in the while. But ugg.I advise you to keep the Thread way that suits to your requirement.Or if you want to make the tool API add helpless code. Of course I am joking : don't do that !
I am received a request to fix sonar issues in a legacy project, there is a code segment like this, every call to this function will be paused for 50ms:synchronized(monitor) { [...] try { [...] Thread.sleep(config.getWaitTime()); // return 50 } catch (SomeException e) { log.error(e.getMessage(), e); } [...] }First, sonar asked me to changeThread.sleep()towait()so I change the try block to to:try { [..] monitor.wait(config.getWaitTime()); } catch (SomeException e) { log.error(e.getMessage(), e); }Then, another issue appear :Remove this call to "wait" or move it into a "while" loop, I do not have much experience with multithreading, so I'm not sure my fix is correct:boolean wait = true; while (wait) { wait = false; monitor.wait(config.getWaitTime()); }Is the above solution correct? If not, what should I do?
How to fix Sonar issue "Remove this call to "wait" or move it into a "while" loop"?
Have you tried?ExcludeFromCodeCoverageAttributethis attribute could be used at class level tooIf not work, could be a problem in your Sonar Analyzer
I am using sonarqube for code coverage in visual studio c# project I want to exclude some methods for the sonar sonarqube code coverage. I have tried the ExcludeFromCodeCoverage attribute but this is not working.
How to exclude method in c# for sonarqube code coverage
Anybody landing on this page in search of a solution: OP has posted it on sonarqube forum as well and the solution is to disable css analysis. For larger projects sonarqube when installed as a server (instead of using cloud) is unable to handle the code analysis for css files resulting the error while it works fine on smaller projects.You can disable css analysis either in the script; by telling Sonar that the css files have a different extension like .foo, or from the AdministrationFrom script when SonarScanner.MSBuild.exe is run, add the following; /d:sonar.css.file.suffixes=.foo, like:"C:\sonar-scanner-msbuild-4.3.1.1372-net46\SonarScanner.MSBuild.exe" begin /k:"MyApp" /d:sonar.css.file.suffixes=.foo /d:sonar.host.url="http://localhost:9000" /d:sonar.login="200dc9294n6bg4d4cc9bed30mj76fcb10d25ee17"From SonarQube Adminstration, remove the .css suffix from the list:The problem is still investigated by the Sonar team;https://community.sonarsource.com/t/sonarqube-post-processing-fails-with-unknown-reason/1798/6
SonarQube is failing without any meaningful error message for a .NET C# project.I tried running the end command with the -X option but the -X format is unrecognized.SonarScanner.MSBuild.exe end -X /d:sonar.login="87195"Any ideas on what could be wrong ? I ran a simpler project with 2 - 3 cs files and that succeeds.: : INFO: Sensor Python Squid Sensor [python] (done) | time=1880ms INFO: Sensor PythonXUnitSensor [python] INFO: Sensor PythonXUnitSensor [python] (done) | time=529ms INFO: Sensor SonarCSS Metrics [cssfamily] INFO: Sensor SonarCSS Metrics [cssfamily] (done) | time=9835ms INFO: Sensor SonarCSS Rules [cssfamily] INFO: ------------------------------------------------------------------------ INFO: EXECUTION FAILURE INFO: ------------------------------------------------------------------------ INFO: Total time: 9:31.651s ERROR: Error during SonarQube Scanner execution ERROR: null ERROR: INFO: Final Memory: 26M/1008M INFO: ------------------------------------------------------------------------ The SonarQube Scanner did not complete successfully 14:53:45.844 Creating a summary markdown file... 14:53:45.847 Post-processing failed. Exit code: 1
SonarQube post processing fails with unknown reason
In SonarQube 7.x you can find the public/private setting when you browse to Administration - Projects - Management. This only works for new projects. For existing projects you can use the "Edit the permissions" option on the same page and switch between public and private.You can also use the web_api to achieve the same results. You can find the documentation when you add "/web_api/api/projects" after the sonarqube URL:Example of the POST request body: project=MyProject&visibility=private
I have my SQ server running in Kubernetes (via Tectonic) and all is going well. We need to tighten the security of our SQ installation, so we have LDAP up and working. We are trying to get all of the projects to be Private by default (which we can do Via the GUI for each project).However, trying to flip the switch in the GUI to make all new projects Private works, until you refresh the page, then it reverts back to Public.I have been searching for a way to set this up via the sonar.properties file or sonar-project.properties file (first if the preferred). The server.properties file we use is encrypted as a secret (because the LDAP settings exposes a service account password) and I would like to keep settings there.I have combed through documentation, posts, discussions and all that, but have not been able to find out what thevalue=keycombination is.Has anyone seen what this is or if we can even accomplish that? Is it a setting stored in the database? I'm kind of at a loss on this one.Thanks!
Setting Projects to Private by Default
SonarQube is telling you that you have a bug in your code. Contract forequalsif well-defined injava spec:For any non-null reference valuex,x.equals(null)should return false.If you are doing it differently in your override - you are doing it wrong.
SonarQube is throwing me a major bug in my quality code reports:Remove this call to "equals"; comparisons against null always return false; consider using '== null' to check for nullity.However, thisequalscall is a overrid one, which means I would like to test what happens if my object is actually null inside theequals()method.Is there any workaround to this issue ? Should I not test the nullability of my object, or have I no other choice but to ignore this case ?EDITThe code as asked in the comments:The object itself:@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MyTestedObject other = (MyTestedObject) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (type != other.type) return false; return true; }Inside the test:@Test public void test() { MyTestedObject testedObject = new MyTestedObject(); boolean nullValue = testedObject.equals(null); Assert.assertFalse(nullValue); }
Resolving "null comparison" bug in SonarQube while testing equals()
You don't have to install SonarQube on your build server, but it is necessary to execute analysis (results will be pushed to it). It means that you have a working server somewhere and next you have to set required parameters:sonar.host.url(http://localhost:9000is a default value)sonar.loginandsonar.password(if your SonarQube server is secured)See allAnalysis Parameters.
I'm getting started with SonarQube usage for JSF page static analysis[1] in Maven. I'm only really interested in using it in Maven since I don't like the idea to introduce another build command.After going throughAnalyzing the source codeandthe specific Maven guideI gained the impression that the plugin can only be used after downloading, installing/unpacking and starting a SonarQube instance atlocalhostand specifying the connection information in the plugin declaration in the POM. The plugin configuration parameter confirm that.While this workflow might have advantages it is painful to use on CI services and the necessity to start a service manually in order to be able to build seems not very user friedly (given the fact that other development tools like Selenium or Arquillian pull entire browser, driver and servers in the background without one single line of configuration). Am I missing something about a separate plugin or configuration which manages an embedded or otherwise temporary instance to perform the analysis with a single plugin declaration?[1] I'm aware that there're other tools based on XML validation which could do the job, but setting up a much more powerful tools like SonarQube seems to be a more flexible approach which will probably pay off.
How to use SonarQube Maven plugins without running a(n explicit) server?
You cannotupdatean existing analysis by any mechanism.What you should look at is theGeneric Test Data format. Set up a translation into this format and then feed your generic report into your analysis (/d:sonar.coverageReportPaths=[path to report]) and you should be good to go.
I have managed to produce a coverage report for a.NETcore project on a debian container where sonar-scanner resides usingminicover.It seems however there is no easy way of importing this into SonarQube (minicover is not in the list ofsupported coverage toolsand the ones listed do not seem to run on linux platforms).My question goes to SonarQube and is the following: assuming I have a coverage folder in the form of:- | \ coverage-folder/ | index.html | src/is there a way for manual upload (e.g.apicall) to sonarqube server so that it is streamlined in the project's analysis?...or is it at least possible at some project settings to hard-code the expected form of coverage report? (couldn't find anything related to the latter on the server's UI)UsingSonarQube 6.7.
SonarQube: Manual Upload of coverage report
For me, this was that the SonarQube server had a full HDD
I can not seem to find any answers regarding this issue5:04:56.635 INFO: ------------------------------------------------------------------------ 05:04:56.635 INFO: EXECUTION FAILURE 05:04:56.635 INFO: ------------------------------------------------------------------------ 05:04:56.635 INFO: Total time: 28.403s 05:04:56.849 INFO: Final Memory: 63M/1435M 05:04:56.849 INFO: ------------------------------------------------------------------------ 05:04:56.849 ERROR: Error during SonarQube Scanner execution The 'report' parameter is missing 05:04:56.850 DEBUG: Execution getVersion 05:04:56.850 DEBUG: Execution stop
Snoarqube- I keep getting the error "The 'report' parameter is missing"
Support for executing FxCop was dropped in v4.0 of the Scanner for MSBuild - seeSONARMSBRU-338for more information.However, this change should not cause the analysis to fail with the latest version of thesonar-fxcopplugin. Check the version of thesonar-fxcopthat you have installed. I can reproduce the error using v1.0 of the plugin, but not with v1.1 or v1.2.
After upgrading to SonarQube 6.7 LTS, many of our projects started failing during "complete SonarQube analysis" task with below error:[error]java.lang.IllegalArgumentException: No FxCop analysis has been performed on this project, whereas it contains cs files: Verify that you are using the latest version of the SonarQube Scanner for MSBuild, and if you do, please report a bug. In the short term, you can disable all FxCop rules from your quality profile to get rid of this error.These projects have codeanalysis enabled and produce proper fxcop results.SonarQube version: 6.7 LTS SonarC# plugin version: 6.6 SonarQube MSBuild Runner: 4.0Can someone let me know if this is known or any way to find the actual cause of the issue.
Analysis failing with error "No FxCop analysis has been performed on this project, whereas it contains cs files"
I was doing:mvn clover:setup verify clover:aggregate clover:clover sonar:sonar -sonar.host.url=...I broke this into 2 separate commands:mvn clover:setup verify clover:aggregate clover:cloverthenmvn sonar:sonar -sonar.host.url=...And it works now.Matched files in report : 100%
I'm having difficulties setting upopenclover 4.2.0to work with SonarQube 6.0.Here's what I have in logs:[INFO] [08:42:14.706] Sensor org.sonar.plugins.clover.CloverSensor [INFO] [08:42:14.707] 2/2 source files have been analyzed [INFO] [08:42:14.707] Parsing /workspace/topparent/biz/target/site/clover/clover.xml [WARN] [08:42:14.709] Resource /workspace/topparent/biz/src/main/java/biz/BizClass.java was not found. [WARN] [08:42:14.710] Resource /workspace/topparent/biz/src/main/java/integration/FirstClass.java was not found. [INFO] [08:42:14.711] Matched files in report : 0% [WARN] [08:42:14.711] 2 files in clover report did not match any file in SonarQube Index : /workspace/topparent/biz/src/main/java/biz/BizClass.java, /workspace/topparent/biz/src/main/java/integration/FirstClass.java, [INFO] [08:42:14.711] Sensor org.sonar.plugins.clover.CloverSensor (done) | time=5msI don't know why the .java files aren't found, the path is correct. I guess I don't see the coverage report because of this:Matched files in report : 0%But why?
SonarQube isn't showing openclover coverage report
The issue is that an older version of sonarqube had connected to database. Somehow the database was registered as older version. I delete and recreate the database and the problem was solved.
This question already has an answer here:SonarQube :: Current version is too old. Please upgrade to Long Term Support version firstly(1 answer)Closed6 years ago.I am new to SonarQube. I installed it to analyze my code on jenkins. When I edited properties file and run start command, the process stopped shortly after I started it. I went to web.log file and got this message:[o.s.s.p.Platform] Web server startup failed: Current version is too old. Please upgrade to Long Term Support version firstly.I have java-8, mysql 14.14 and SonarQube 6.5.What is it actually complaining? What is too old?
SonarQube Stopped with Error [duplicate]
Currently We are running sonar-scanner from GoCD pipeline and checking SonarQube Quality Gates correctly.What we do was the following: I created a bash script that launch the sonar-scanner. This script (and other ones used by our GoCD configuation) is inside a second Git Material (the first one is the Project source code). We have installed the 'SonarQube Quality Gates Task Plugin' to evaluate our SonarQube quality gates.So we have a Job in our Pipeline with the following tasks:Type:Custom Command ---Run if:Passed ---Command:/bin/bash ---Arguments:path_to_sonar_scanner_bash_script_launcher.sh ---Working Directory:your_working_dirType:SonarQube - Quality Gate ---Run if:Passed ---Key of the SonarQube project:sonar_qube_project_id ---Fail Quality Gate result:error Sonar ---Api Url:http://your_sonar:9000/apiWe have GoCD agent and sonarqube installed in the same machine.I expect this help you.
I am creating a GoCD pipeline to run sonar analysis for my project. Up to now, I have successfully configured sonar properties on my local file and it successfully pushes the metrics to the sonar server.The problem occurs when creating a GoCD pipeline to run the analysis. I am unable to successfully install sonar scanner on GoCD agents. The error that I get when executing command sonar scanner from the pipeline is "SONAR_RUNNER_HOME does not point to a valid installation directory".
How to add sonar scanner in GoCD?
There are so calledquality gatesin Sonarqube which can be configured to fail the build if necessary.You will have to configure awebhookbetween Sonarqube and Jenkins so that you pipeline can ask for the quality gate status. Further information can be found here:https://jenkins.io/doc/pipeline/steps/sonar/Note: Especially have a look at the methodwaitForQualityGate()which does exactly what you intend to do!
I'm trying to write a pipeline as a code and in this pipeline I want to return the result of sonarqube analyze and do a filter if the general note is >=97 continue if it is less return a Notif in slack. but how can I return a result a of sonarqube
return the results of sonarqube
Method references don't have to be references to static methods, they can also be references to a method on a particular object. In this case you can use:support.getValidationResult().getErrors().forEach( support.getValidationDecorator()::applyValidationDecoration);which is doing exactly the same thing as your original - callingapplyValidationDecorationwith the error parameter on the result of callingsupport.getValidationDecorator().
I've just started using SonarQube for improving my code quality and when I analyzed a JavaFx project that uses ControlsFX for validation I got this "code smell" error.Replace this lambda with a method reference:support.getValidationResult().getErrors().forEach(error -> support.getValidationDecorator().applyValidationDecoration(error));I'm unsure on how to refactor this since the ValidationSupport class does not have any static methods and my IDE is giving me this warning for most of what I'm tying to do:The type ValidationSupport does not define getValidationDecorator(ValidationMessage) that is applicable hereFor the time being I've just marked it down as a false positive in Sonar but that's not a good solution in the long run since it just hides it.
Converting ValidationSupport lambda call to method reference
You get this blame error because you are trying to analyze a set of files on which you have uncommitted changes.To fix this:Either you make sure that you a running an analysis on source code that has been freshly checked out from your version control system (and not changed since then-Or you tell SonarQube to not try to get SCM informationYou will find this in the "Administration > Configuration > SCM" settings page: it is called "Disable the SCM Sensor"
I have set up SonarQube server on my local system and run sonar runner. it will run good with .html file but when i am trying to run with php file, it failed and showing error like:java illegal language exception blame sample.php file.I installed all plugin as below.gitjavajavascriptwebphpc#but it is not working.
Sonarqube analysis not working
Version 5.6 can't be upgraded from a version previous to 4.5.x. It seems to be your case, so you should first upgrade to 4.5.x (the latest 4.5.7 is recommended) then upgrade to 5.6.
I downloadedsonarqube-5.6and configured thesonar.properties. My mysql version is 5.6 and java version is 1.8. when I start sonar getting error current version is too old , while my sonar is 5.6. Here is error log and sonar.properties2016.08.03 18:30:13 INFO web[o.s.s.p.ServerImpl] SonarQube Server / 5.6 / 074f3d1169f9688d15af4aff67e7e672cbeed782 2016.08.03 18:30:13 INFO web[o.sonar.db.Database] Create JDBC data source for jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance 2016.08.03 18:30:13 ERROR web[o.a.c.c.C.[.[.[/sonar]] Exception sending context initialized event to listener instance of class org.sonar.server.platform.PlatformServletContextListener org.sonar.api.utils.MessageException: Current version is too old. Please upgrade to Long Term Support version firstly.Sonar.propertiessonar.jdbc.username=sonar sonar.jdbc.password=sonar sonar.jdbc.url=jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEn coding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformanceEdit ::Please note I am using 5.6 version which is latest as perhttp://docs.sonarqube.orgLinksays "you must first upgrade to 4.5.x - I'd recommend 4.5.7 - and then upgrade to 5.3." . I am not getting this , should I install lower version fist and upgrade it 5.6 or what
SonarQube :: Current version is too old. Please upgrade to Long Term Support version firstly
Answer is no.The purpose of SonarQube is solely to analysesourcecode. All main features rely on the availability of the source - because in the end you end up on files to track issues or see the test coverage (for instance).
I am using Sonarqube tool for analyzing jar files.My jar files only contains classes file and not source code. I want to know that if it is possible to scan jar files that only contains classes through Sonarqube.
Analyzing jar files with sonar
it's been a while since you posted this but maybe I can help at least with my understanding.In SonarQube 5.6 (don't know when this changed) the build analysis is been analysed in a background task in SonarQube. So the Jenkins Build is finished after it posted the analysis to the server and the build is finished long before the background task on the SonarQube server is finished.During or on the end of the background task in SonarQube it checks the QualityGate.So the Jenkins plugin get's always "outdated" QualityGate status at least with SonarQube versions higher than 5.6.It's possible to extend the Jenkins plugin and add a "wait for background task" option. Of course this would lead longer build times in Jenkins. This is already done inthisfork of the "Quality Gates Plugin".Hope this all right :-)see the also the doku here
I m trying to fail a build in my Jenkins server using the Quality Gate plugin (v2.5). In my jenkins i have installed SonarQube plugin (v2.4.4) and SonarQube Scanner v2.6.1. I have configured a SonarQube server as well v5.6 I have defined a quality gate (for eg bugs > 10) in my server for the project which i m building using my Jenkins server. I have created a freestyle job for the same in Jenkins. What i want to achieve is the build in Jenkins should fail whenever the Quality Gate requirement is not met. I use the "Execute SonarQube Scanner" option in my build step in Jenkins and the Quality Gate option in the post build action (with my project key). I have defined the parameters for sonar analysis in the Analysis Properties section.Currently, when the quality gate threshold is not met the status changes to failed on the SonarQube server but the build is passed in Jenkins. During the next execution of the same job in Jenkins the build is failed by the Quality Gate. That is the build status is not changed in synchronization with the SonarQube server but in the following execution,Can you pls let me know what m i missing here ?
Failing a build in Jenkins using the Quality Gate plugin
Asdescribed here, SonarQube would integrate itself more with the successor of ClearCase:IBM RTCand its Jazz Source Control module.That being said, theSonarQube Plugin Librarypage does mention aClearCase plugin, for you to try.
I am looking for a confirmation regarding a code quality control tool (sonarqube) which can be integrated/used along with my version control tool clearcase.I heard about sonarQube but not sure whether we can use it along with Clearcase. I would like to know if it is possible to use sonarqube along with Clearcase.
clearcase and sonar qube integration for source code quality
It seems that there are some inconsistencies between the issues table and the issues index in elastic search.The only way to fix it is to :Stop SonarQubeDelete /data/es folderStart SonarQube
I have sonarqube 5.3 running and one of the projects is showing incorrect report. Other projects are fine.On the dashboard of the problem project it shows there are 9 Blocker issues. Clicking on this takes me to the issues page where it shows total 21 issues. The list of issues includes items that has been marked as "Closed(fixed)", which are the extra items. In the issues page, I only have "Blocker" under the Severity and "Unresolved" under the Resolution field checked.Can you please help to identify why this project's issues page is not showing issues properly based on the filters? Thanks,
sonarqube issues shows closed items when unresolved resolution is selected
Based on @CSchulz's answer I found the solution usingSonarQube moduleI configured SonarQube to use two submodule corresponding to myAandBgit projects. Each project get the name of git module as the importantprojectBaseDirparametre.sonar.projectKey=P sonar.projectName=P sonar.projectVersion=4.0.0 sonar.binaries=. sonar.cxx.includeDirectories=Common/Path sonar.cxx.cppcheck.reportPath=cppCheckReport.xml # Reports are present in A and B forlder # 2 modules definition sonar.modules=A,B # Module A IHM.sonar.projectBaseDir=A IHM.sonar.projectName=A IHM.sonar.sources=. IHM.sonar.cxx.includeDirectories=XXX # Module B Shares.sonar.projectBaseDir=B Shares.sonar.projectName=B Shares.sonar.sources=. Shares.sonar.cxx.includeDirectories=XXXI needed to figure out some configurations but it works and it is fine for me.
I configured a Jenkins Main ProjectPto manage two git repositoryAandB. This main projectPonly updates git sources and calls sonar analysis on sources from his workspace.Here's my tree folder.{Jenkins Install Path} \ workspace \ P |-- A |-- .git/ |-- all projects A files |-- B |-- .git/ |-- all projects B filesWhen Jenkins runs sonar analysis forP, I got the following errorSCM provider for this project is: git 2664 files to be analyzed 0/2664 files analyzed Missing blame information for the following files: (all files)The error is logical because SonarQube is looking for a.gitfolder under{Jenkins Install Path} \ workspace \ P. It doesn't exist.I looked around the internet to find a solution but I didn't find an answer. I am using SonarQube 5.5 installed on windows.Do you have some idea to make SonarQube working with my configuration ?This case is different thanSonarqube: Missing blame information for the following filesbecause the root cause is I am using two git folder fetch by a single SonarQube analysis.Sources I visited and read several timesSonarQube Git PluginSeems similar but different issueGlobal SCM error in SonarQube
SonarQube fails to get git blame information from Jenkins project
Sorry, no. This is a core feature.The closest you could come is with the commercial Governance plugin (to be released with 5.6) which would allow you to set the remediation cost for each rule to 0min.
This question already has an answer here:Is it possible to hide the Technical Debt metric from SonarQube dashboard, entirely?(1 answer)Closed7 years ago.SonarQube displays estimates for the amount of effort required to fix issues in various locations.Certain types of manager instantly home in on these figures as they appear to give an easy answer to the difficult and nuanced questions.It would be easier to have constructive conversations if SonarQube did not attempt to put a figure on the debt.Is it possible to somehow stop SonarQube from displaying these figures?
Is it possible to stop SonarQube displaying effort figures for debt and remediation effort? [duplicate]
There isn't one. The project home is the new, immutable front page for the project view.
Today I upgraded our sonar instance from 4.5 to 5.5.On 4.5 when you opened a project it opened adashboard view, top three entries in the left menu being dashboards.On 5.5 when you open the project you get to theproject home, a page that didn't exist in 4.5.If you want to see the dashboard you have to open the dashboard dropdown in the top menu and select the dashboard you're looking for.I couldn't find any configurable setting to change the default project page, so the default page would be the first dashboard entry named "Dashboard".
How to set default project page to dashboard in SonarQube 5.5?
It is planned that the SonarQube JavaScript plugin supports JSX files. By supporting, this means being able to correctly parse JSX files in the first place.You can watch and vote forSONARJS-521.
Closed.This question is seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. You can edit the question so it can be answered with facts and citations.Closed7 years ago.Improve this questionIs there a plugin for SonarQube that can analyze react/jsx/es6 code?
Is SonarQube able to analyze react/jsx/es6 code? [closed]
The status that you are describing is weird: if you have deleted "someModule" from project A and managed to analyze successfully this project in SonarQube, then it should not show up in the UI any longer and you should be able to analyze it within project B.But as you can see this module in 'Project Configuration > Update Key', then you might have a workaround:Update the key of that module in project A (just append "-off" to the key for instance)Run an analysis of project B with "someModule": this should work
I use SonarQube to analyze two Maven projects A and B with several modules each (only one displayed here):projectA `- someModule projectBSince I moved someModule from project A into project B, I get an error like this during the analysis:Module "myGroupId:someModule" is already part of project "myGroupId:projectA"Project A clearly does not contain 'someModule' anymore. It doesn't even show up as a component in the Sonar GUI after a new analysis, however it's still listed under 'Project Configuration > Update Key'.How is it possible to delete such an obsolete component without deleting the entire project?As a work-around I now renamed the key 'projectA:someModule' to 'projectA:someModuleThatShouldNotExist', but I hope someone can suggest a better solution...
Why are deleted Maven modules not disappearing from SonarQube?
What you're constructing is dynamic sql, which is generally considered inherently dangerous. For example, you appear to have no limits on what table you'll be updating. Instead, you should be doing something likeString update = "update MY_TABLE set SENT_STATUS=?, SENT_DATE=? where CI_ID=?"; try { conn = getConnection(); pstmt = conn.prepareStatement(update); pstmt.setString(1, CaaConstants.STATUS_CI_SENT); pstmt.setString(2, today.toString()); pstmt.setString(3, containerItemIds[i]); //...This does 2 thingsmakes sure you're really updating rows in the table you intend to updateprotects you from malicious input by escaping the values being passed into the queryNote that if you've made the table name dynamic because you have several different tables with the same columns,you should examine your DB structure for refactoring opportunitiesyou should write separate code for each one. Saving a few lines of codeis not worththe risk of updating something you didn't intend.
I am using below piece of code in a method:final StringBuffer queryBuffer = new StringBuffer(100); queryBuffer.append("update ").append(tblContainerItem).append(" "); queryBuffer.append("set SENT_STATUS=").append(CaaConstants.STATUS_CI_SENT); queryBuffer.append(", SENT_DATE='").append(today.toString()).append("' "); final int len = containerItemIds.length; for (int i = 0; i < len; i++) { if (i == 0) { queryBuffer.append("where CI_ID="); } else { queryBuffer.append(" or CI_ID="); } queryBuffer.append(containerItemIds[i]); } try { conn = getConnection(); pstmt = conn.prepareStatement(queryBuffer.toString()); ...and it shows a warning at the this line:pstmt = conn.prepareStatement(queryBuffer.toString());How can I avoid this warning? I know by using@SuppressWarningsbut that is not the correct way of eliminating this error.
SonarQube Report warning: 'A prepared statement is generated from a non constant string'
So if a File operation can throw exceptions of 8 types, How can I catch a specific exception? Does it mean I have to write multiple catch blocks?Yes, you'll need to write specificcatchclauses for each exception you want to catch, going from the specific ones to the general ones.The documentation ontry-catchis pretty clear:It is possible to use more than one specific catch clause in the same try-catch statement. In this case, the order of the catch clauses is important because the catch clauses are examined in order. Catch the more specific exceptions before the less specific ones. The compiler produces an error if you order your catch blocks so that a later block can never be reached.try { foreach (var str in strlist) { var jsonData = str; File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory)+ "test\"+".json", jsonData.ToString()); savedFiles++; } } catch (PathTooLongException pe) { // Do Stuff } catch (Exception exception) { _log.ErrorFormat("Exception occurred in Saving JsonDocs , exception Message {0}", exception.Message); return savedFiles; }Means that if anPathTooLongExceptionis thrown, it will be caught by that catch clause. If you mistakenly switched the order of the catch clause and hadExceptionfirst, it would take priority over any other exception handling clause.
I have this piece of code where I am trying to save some information to a filetry { foreach (var str in strlist) { var jsonData = str; File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory)+"test\"+".json",jsonData.ToString()); savedFiles++; } } catch (Exception exception) { _log.ErrorFormat("Exception occurred in Saving JsonDocs , exception Message {0}", exception.Message); return savedFiles; }When I checked in this code, My SONAR started complaining that I should catchspecific exceptions.But the only logic which I have here is aFileSaving which can have all the below possible exceptionsSo if a File operation can throw exceptions of 8 types, How can I catch a specific exception? Does it mean I have to write multiple catch blocks?
How to catch a specific exception if the possible list of exceptions are too many?
The rule will skip annotated private unused methods, it will be fixed in version sonar-java-plugin version 3.6.https://jira.sonarsource.com/browse/SONARJAVA-1179
We use the@PostConstructAnnotation for setup Methods (Spring Dependency Injection (@Autowired)) and get a false positive:"Unused private method should be removed"@PostConstruct private void setupAbc() { ... }any hints?
MAJOR: Unused private method should be removed - postConstruct Annotation - false positive
in sonar -> administration -> General Settings -> Analysis Scope set "Source File exclusions" like that: file:**/ProjectName/* * (without spaces between * *)
I have a solution which has three projects (X,Y,Z). Z referenced in Y , Y in X . When I start Analysis with MSBuild SonarQube Runner on project X, it is analyzing Y and Z as well. Do we have any solution for ignoring recursive analysis ?Note: I can not breakup solution file into multiple solution files & refer dll's rather than projects.
How to exclude/ignore referenced project(s) analysis from SonarQube
Why do you want to go through each file to compute the projects' lines of code ? Why not use theapi/resourcesWS ?documentationexampleHTH
Sonar reports the lines of code iformation for each language on each project's dashboard.In order to create a report from 70+ projects, we use THE Sonar's REST API. Currently we iterate over all files of a project to retrieve each file's lines of code. Here we run into the limits issue (the result is cut off at 500 entries, there is no paging on the REST API). SeeSonarQube API result limit, andhttps://jira.sonarsource.com/browse/SONAR-2920.Hence the pulled numbers are wrong, and we need to manually fix the report.Now my question: Is there a way to pull the numbers shown on the project's dashboard through the REST API? Or going to the database? (Sure, not ideal, but I need to solve my problem ;-)Thanks in advance.
How can I pull the right loc information from Sonar?
Use thesonar.branchanalysis property to distinguish the branches from head and from each other. Note that there are limitations. E.G. Issues marked "False Positive" in one version of the projectwill notshow up as FP's in the other versions.More analysis params in the docs
I recently configured our build server using bamboo and Sonar. In our case we have a multiple developer environment and chose to not only analyse our trunk but also the branch. The nightly builds of trunk and branch are analysed by sonar. And there lies our problem. The last build will be the build saved in Sonar, which is plausible from a Sonar point-of-view, ie the projects have the same name so are probably the same.In Branch we have fixes for our major release all projects name and code are same just in branch we have bug fixes. so we would love to see the analysis of branch and trunk separately in sonar dashboard.The question is there is a way to make multiple version of the same project in Sonar? Or is there any other best practice in this situations?Looking forward to you replies :)
Project analysis (Sonar Report )for branches
The Jenkins SonarQube plugin only allows to easily launch some SonarQube analysis with help of SonarRunner or Maven. If you want to launch a SonarQube analysis with help of the Gradle SonarQube plugin (seethe docs) you must manually configure your Jenkins job to execute 'gradle sonarqube'. Simple example for SonarQube with Gradle is providedhere.
I have installed Sonarqube plugin in Jenkins and configurations are done for SonarQube and sonar-runner in Manage Jenkins->configure System. I want to trigger analysis for Gradle project. I would like to know the steps to be followed.
How to launch a Grade SonarQube analysis with help of the Jenkins SonarQube plugin
The naming convention is org/sonar/l10n/{plugin key}_{language}/rules/{repository key}/{rule key}.html.It was documented inhttp://docs.sonarqube.org/display/DEV/Internationalizationat the time rule descriptions supported localization. That's not the case anymore since version 4.2, but these HTML bundles are still supported.The correct way since version 4.3 is to use the low-level API org.sonar.api.server.rule.RulesDefinition. It allows you to implement any kind over layer over it (xml, json, annotations, ...).
I have my custom rule, let's say withAEM-1key. So, as it is donehere, I make myAEM-1.htmlresource file with some simple html content and it does not get's picked up by SonarQube 5.1. It refuses to start, because no description is provided for the rule.I tried different packages names, tried to look for convention in source code etc. What's missing? Is there any documentation on that?
How to specify SonarQube rule description as a markdown/html resource file instead of using annotation?
I do confirm that this is not possible to bulk change the severity of a set of rules activated in a Quality Profile (whereas this is possible to bulk change the severity of a set of issues). Even if this might be useful from time to time, there is no plan to implement such feature at short term.
I want to change the severity of mulitple rules in a quality profile in bulk. At the moment there are ca. 20 rules with "Blocker" severity and I want to set them all to "Critical". Because we created a new quality gate for blocker rule violations and this rules should not be included.I could do this manually one by one. But I wonder if it's possible to do it in bulk. With 20 rules it's just annoying, with 100 rules changing the severity manually one by one would be a major headache.There's an issue about this,SONAR-3421 "Enhance Bulk Change possibilities for Profile Rule Filter". The issues is closed now. But as far as I can tell, this functionalty has not been implemented.
SonarQube - How to change severity of mulitple rules in bulk
You will not be able to add arbitrary rules directly from the UI.What is possible from the Rules page is:Change activation parameters of en existing rule on a given profileCreate a custom rule usingan existing rule template; this is the easiest way to customize behavior of rules, but this feature is limited to a restricted subsetCreate a manual rule; these rules will not raise issues at analysis, but can be used to create manual issues on source codeIf you need to develop completely custom rules (e.g non existing ones), you will need to develop a plugin and provide an implementation (using Java code) for your custom rules.
How can I add rules to SonarQube (V4.5.2) via the web interface? The most easy and logical way would be to copy/duplicate an existing rule and then customize it, but I can not find this copy-functionality.It is possible to add a new rule, but there is no way to add semantics to it here or to set the severity.
How to add Rules to SonarQube?
How can I configure the findbugs rules?Use the SonarQube web GUI. Click on "Quality Profiles" in the black area at the top, then choose "Java". The Maven plugin will download your definitions from there and use them.Do I have to configure the rules in maven as suggested in Import FindBugs configuration from Sonar to Maven?Nope. Configure them only in SonarQube, and you're all set.Where can I find a documenentation how to write the configuration file?That would be theFindBugs docs. But you don't need to do that if you're using SonarQube.Is the configuration in sonar still relevant? Thedocumentationdoesn't help.Yes it is relevant. The SonarQube documentation is generally not very helpful, but configuring rules is quite straightforward using the GUI. You should have a good chance even without documentation.
I'm calling sonar from maven:mvn clean install sonar:sonarHow can I configure the findbugs rules?Do I have to configure the rules in maven as suggested inImport FindBugs configuration from Sonar to Maven?Where can I find a documenentation how to write the configuration file?Is the configuration in sonar still relevant? Thedocumentationdoesn't help.
How to configure findbugs when using sonar with maven
SonarQuebe 5.0.X add the lombok patch, whick works for lombok's Getter.For SonarQuebe 4.5.X, which use sonar-java-2.4, you can find the patch here:https://github.com/SonarSource/sonar-java/compare/2.4...liudongmiao:patch-lombok-2.4You can download the binary from here too:https://github.com/liudongmiao/sonar-java/releases/tag/2.4-lombok
I am working with sonar and lombok and it seems that those two aren't friends with each other.@Getter public class MyAwesomeClass { private String string1; private String string2; private String string3; ... }The example above generates a getter-method for every field in the class, thanks to the @Getter annotation, but sonar warns me that those fields are "Singular Fields", which are only used in one method, which isn't the case because of the generated getter-methods.It is obvious that sonar doesn't take lombok into account. My question is if there is a possibility to make those warnings disappear, for example with a@SuppressWarningsannotation?
Sonar "Singular Field" rule contradicts lombok-getter
You can setupSettings Encryptionto encrypt settings if they are meant to be distributed. Note that most of the times, the RDBM login and password are only known on the machine responsible for analysis, which is often a continuous integration system.
Attempted to ask this to[email protected]but my email address appears to not be allowed to send to that list despite being subscribed.I'm trying to figure out how to put together a centralised, managed SonarQube service which would allow any developer to submit results to the service.All of the documentation for setting up SonarQube appears to state that users wanting to submit results should populate their configuration with something like the following:<properties> <!-- ... snipped ... --> <sonar.jdbc.username>sonar</sonar.jdbc.username> <sonar.jdbc.password>sonar</sonar.jdbc.password> <sonar.host.url>http://sonar-host:9000</sonar.host.url> <!-- ... snipped ... --> </properties>For example:http://docs.codehaus.org/display/SONAR/Installing+and+Configuring+Mavenhttp://docs.codehaus.org/display/SONAR/Installing+and+Configuring+SonarQube+RunnerThis would mean that any user wanting to update statistics would have access to a username/password for the main SonarQube database with full permission to query/update that database.Is the intention that SonarQube should be run as a centralised service which build administrators take code bases and build these on behalf of development teams or is there a way in which this function could be delegated to the teams directly?Cheers,David.
How do I hide Sonar database credentials from end users
The route DSL configures the Camel framework to run integrations.You need to know why you need code coverage reports out of your Camel apps and exactly what they should tell you.Camel routes can be written in a wide variety of ways. XML DSL, Groovy DSL, Java DSL etc.. Then even writing Java DSL, you may have the heavy logic inside expressions and scripts, such as simple/groovy/xslt.There is no way for any single tool to figure out that you have written perfect Java and XML and Groovy and Scala and XSLT and ... in a Camel/integration perspective.Define test cases and write decent integration/unit tests for your routes and use sonar for coverage of java processors/beans. That is straight forward.
Is there a code coverage/quality tool (like Sonar) that works well with Camel routes? I've been doing some analysis with sample builds of camel routes to find nothing registers inside of Sonar after running my junits through Jenkins.
Camel and code coverage
In the above example the following line sets what quality profile to be used during the analysis:property "sonar.profile", "test"You have to change "test" to your quality profile name that you want to use. If you want to use the default, then remove (or comment out) this line from your gradle build file.
how to include quaility profile in gradle? when i try to include sonar plugin like thisapply plugin: "sonar-runner" sonarRunner { sonarProperties { property "sonar.host.url", "" property "sonar.login", "r" property "sonar.password", "" property "sonar.jdbc.url", "" property "sonar.jdbc.driverClassName", "com.mysql.jdbc.Driver" property "sonar.jdbc.username", "r" property "sonar.jdbc.password", "" property "sonar.profile", "test" property "sonar.projectName", "liki" property "sonar.language", "java" property "sonar.sources", "src/main/java" property "sonar.binaries", "build"; } }i have got in sonar new project, but my quiluty profile not included
quality profile in gradle
Constants (static final) variables are generally in upper case in Java. So you can either:ignore the comment in this particular case (it is not unusual to use small caps for the logger)renameloggerinto something else, for exampleLOG
What is the correct way to initialize Slf4j LoggerFactory.getLogger? I have in my codestatic final Logger logger = LoggerFactory.getLogger(MyClass.class);But sonarqube code analysis marks this code as major error: "Rename this constant name to match the regular expression '^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$'"What is wrong?
Slf4j LoggerFactory.getLogger and sonarqube
When running a SonarQube analysis with the SonarQube Runner, you should be aware that tests are not executed: this is why you get no result.This means that you must make sure that they have been executed prior to the analysis, and the the results have been exported.Just for information, you can have a look at the sample projects here:https://github.com/SonarSource/sonar-examples/tree/master/projects/languages/groovy
Hi I have set up a groovy project analyzing with sonar-runner, it works for complexity, lines of code etc but the code coverage shows "-" and unit testing is 0%. This is the sonar-runner properties file I am using Groovy plug in 0.6 Sonar runner 2.3 Sonar Qube 3.7 Jacocsonar.projectKey=Groovy sonar.projectName= Groovy SonarQube Runner sonar.projectVersion=1.0 sonar.sources=src sonar.language=grvy sonar.binaries=target/classes sonar.libraries=lib sonar.junit.reportsPath=test/unit sonar.core.codeCoveragePlugin=jacoco sonar.jacoco.reportPath=test/coverage/jacoco.exec sonar.sourceEncoding=UTF-8I was wondering if somebody could point me in the right direction
Groovy Gradle Sonar-runner Unit Testing and Code Coverage
I do confirm that this is not possible to track the evolution of the number of violations on a given rule over time. I've created a JIRA ticket to cover this use case :http://jira.codehaus.org/browse/SONAR-4389
I have created a regex checkstyle rule. I would like to track the violations for this rule separately in time machine. While I can see options to track 'info violations' and so on, I couldn't find a widget where I can just enter the rule key and track its violations over time. Is it possible to do this with Sonar?
Is there a way to track a single rule violation in Sonar time machine?
It's because they have conditions in them which increasethe number of tests needed to ensure that the code is correct.Also probablyifs have less complexity than loops (while,for). Also read up oncyclomatic complexityrelated to this.Read this blog post, it describes the actual reality of not being able to test everything and the sheer number of tests you require to test everything.
FromSonar Metrics complexity pagethe following method has a complexity of 5.public void process(Car myCar){ <- +1 if(myCar.isNotMine()){ <- +1 return; <- +1 } car.paint("red"); car.changeWheel(); while(car.hasGazol() && car.getDriver().isNotStressed()){ <- +2 car.drive(); } return; }This is how the tool calculate complexity:Keywords incrementing the complexity: if, for, while, case, catch, throw, return (that is not the last statement of a method), &&, ||, ?Why docasestatements,ifblocks andwhileblocks increase the complexity of the method? What is the intuition behind this metric calculation of complexity of methods?
What is the principle behind calculating the complexity of methods?
For PHPMD (just as for PHP CodeSniffer, for example) you will have to specify a separate exclude pattern. You can use PHPMD's--excludeparameter for that.Took me a while to figure it out, but you can set PHPMD's command line parameters with the following setting in yoursonar-project.propertiesfile:sonar.phpPmd.argumentLine=--exclude libraries/externals
I'm trying Sonar and i've got some issues with it for a php project.I have to do it multi-module to get at least php and js analysis.this is my sonar-project.properties:sonar.projectKey=xxxx sonar.projectName=xxxx sonar.projectVersion=1.0sonar.sourceEncoding=UTF-8 sonar.sources= sonar.language=php sonar.exclusions=htdocs/libraries/externals/** sonar.phpCodesniffer.skip=true sonar.modules=php-module,js-module # PHP module php-module.sonar.projectName=PHP Module php-module.sonar.language=php php-module.sonar.sources= php-module.sonar.projectBaseDir=htdocs php-module.sonar.exclusions=libraries/externals/** # JavaScript module js-module.sonar.projectName=JavaScript Module js-module.sonar.language=js js-module.sonar.sources=js js-module.sonar.projectBaseDir=htdocsBut when i run sonar-runner, i get this error:Exception in thread "main" org.sonar.runner.RunnerException: org.sonar.api.utils.SonarException: PHPMD execution failed with returned code '1'. Please check the documentation of PHPMD to know more about this failureand the PHPMD error isThe parser has reached an invalid state near line "32" in file "/var/www/vhosts/dev3.xxxx.local/htdocs/libraries/externals/AvaTax4PHP/classes/ATConfig.class.php". Please check the following conditions: The keyword "parent" was used as type hint but the class "ATConfig" does not declare a parent.But why is that happening if i've excluded the dir libraries in the project and the module?Do i have to specify to PHPMD another list of exclusions?
Sonar and PHPMD: how to exclude directories
This behavior can be configured globally or on each Jenkins job in the Sonar configuration section. Here are the available options :Skip if triggered by SCM ChangesSkip if triggered by the build of a dependencySkip if environment variable is defined and set to true
I don't know why post build actions are not launched by jenkins when the build is triggered by the internal timer (typically a nighltly build or a SCM poll) For the context, our SONAR analysis is configured as a maven post build action but if the job is not launched directly by the user from jenkins web application, sonar is not updated and there is no trace of sonar analysis in the console log. If the job is launched manually all is working well.
Jenkins don't launch "post build" actions when trigger by the timer
The Sonar ANT task executes as part of ANT so you need to set the JVM heap using the standard ANT environment parameter. For example:export ANT_OPTS=-Xmx256m
I am analyzing quite a large project with Sonar. The first few runs went OK but now I get error. Something to do with timemachine and violation analyzer:java.lang.OutOfMemoryError: GC overhead limit exceeded at org.sonar.plugins.core.timemachine.ViolationTrackingDecorator.mapViolations(ViolationTrackingDecorator.java:131) at org.sonar.plugins.core.timemachine.ViolationTrackingDecorator.decorate(ViolationTrackingDecorator.java:70)I execute Sonar using ANT. Can I increase the java heap size somehow?
How to increase Sonar java heap size?
You can trigger Sonar Analysis as a build step and not a post-build step. Take a look atthis. But my question is, why you should want to run a quality analysis for a project failing its build?
I have a jenkins job to build my project run tests and then run sonar with sonar jenkins-plugin. but when tests failed sonar analysis skipped.
How to run sonar analysis even if build failed on Jenkins
I'm in a slightly different setup than you are, using Ant and Sonar 3.01, but... there was one property that did the trick for me, that seemed to be almost entirely undocumented when I looked. I notice the wiki pages have had updates in the last couple of days, which may have changed the doc situation.<property name="sonar.core.codeCoveragePlugin" value="jacoco" /> <property name="sonar.jacoco.reportPath" value="${test.log.dir}/jacoco.exec"/>Settingsonar.jacoco.reportPathexplicitly to the file, not a directory, was what finally worked for me.
Using :JaCoCo 0.5.3, Maven2, Sonar 2.14, sonar-maven-plugin 1.8, SùartGWT 3.0Currently trying to :Get code coverage on Sonar of my Selenium unit tests.Problem :Code coverage doesn't move from 0% although the sensor is launched properly, analyse the jacoco.exec which is correctly generated.Ressources :https://gist.github.com/2888912The pom.xmlIt's been about 2 weeks I'm trying to get code coverage. I upgraded the Sonar from 2.10 to 2.14, changed every single sonar property, tried the plugin jacoco (for maven) and I still DON'T get any results. So if someone had the same problems and found the solution, could you please tell me how you amde it work ?I'm quite sure my tests must generate at least 0.5% of code coverage. My Selenium tests are actually executed in SeleniumTestLoginEntry.java, does it have any incidence ? Must I call it TestLoginEntry.java ? (The tested class is LoginEntry.java) I'm using surefire to start the javaagent of JaCoCo (see the tag) and it actually GENERATES the jacoco.exec.Please give me some help, I'm totally lost I have only one week left to make it work... :(Thanks in advance.
Jacoco and Sonar code coverage?
As already noted, first consider whether you really need the duplication. Maybe they should be in a common object that gets passed around. Maybe they aren't needed.Now lets assume they really are needed. Which can be the case of course. PMD's copy paste detector lets you set the minimum number of lines before it counts as a duplicate. Since a getter/setter is only three lines each (or 6 for both), you could set the threshold just above there.
Let's say we have 3 classes: A, B and C. Each class has the others in parameter. Like this: EDIT:+-----+ +-----+ +-----+ | A | | B | | C | ------- ------- ------- | X x | | X x | | Z z | | Z z | | Y Y | | Y y | ------- ------- -------Getters and setters will be duplicated. So, is it a bad practice and should we avoid this ? Or does this should not be took as duplication code by code analyzers (eg. PMB) ?I have thought about "strategy pattern", but I think it's maybe too much, just for getters and setters ...EDIT : My first question is maybe not really clear. The question is if we have two classes (not linked) with a common attribut and exactly the same getter/setter. Sonar or PMD should consider these methods as duplicated code or not ? And if not, will it be fixed ?
Avoid duplicate code in POJO Class
Just removeuseMemo. It takes more CPU time than calculations inside of it.const link = !card || card.targetUrl === "/test" ? "/account" : card.targetUrlWithuseMemo, each render you have to create a function, get previously stored dependencies, loop through it, and even if there were no changes you already spent ten times more CPU time that simple string compare. And if card was changed, then... uhh. execute the function, store return value somewhere, replace dependencies.. ohh.. and store hook into hook execution chain... I believe even more overhead is here.
when I add this check: card.targetUrl !== "/test"I get this error and I cannot commit, how do I reduce this complexity?const link = useMemo(() => { if (!card?.targetUrl || card.targetUrl === "/test") { return "/account"; } else { return card.targetUrl; } }, [card]);this error is not present when the code looks like this:const link = useMemo(() => { if (card?.targetUrl) { return card.targetUrl; } else { return "/account"; } }, [card]);
How to refactor this function to reduce its Cognitive Complexity from 16 to the 15 allowed?
Let me highlight the location of a possible exception:Proxy proxy = new Proxy(Proxy.Type.HTTP, proxnet); HttpsURLConnection conn; conn = (HttpsURLConnection)urlStr.openConnection(proxy) /* EXCEPTION! variable is not assigned */; con.set...(); finally{ conn.disconnect(); }connremains set to its initial value (null). The safe route is to add a null check in the finally block:finally { if (conn != null) conn.disconnect(); }
I have created the connection from HttpsURLConnection to set all the parameters to it. In the end finally block i am disconnecting it as showin below. But the SonarQube build is not passing. Showing as bug while disconnecting the connection.Proxy proxy = new Proxy(Proxy.Type.HTTP, proxnet); HttpsURLConnection conn = (HttpsURLConnection)urlStr.openConnection(proxy); con.set...(); finally{ conn.disconnect(); }SonarQube addressing the Bug inside finally block with NullPointerException.keeping a NotNull check enough to the conn object? Or is anything to be done here apart from a not-null check? I am trying in different ways.A "NullPointerException" could be thrown; "conn" is nullable here.
SonarQube A NullPointerException could be thrown; Conn is nullable here
I guess that Sonar doesn't know about Stream.toList() (introduced in Java 16), and thinks it is a non-terminal operation. This seems to be bugSONAR-3746(see alsoStream#toList (JDK 16) is not recognized as terminal operator). This problem should be solved in SonarLint 7.2.I guess, that means you need SonarQube 9 or higher, as SonarQube 9.0 is the first version that announced Java 16 support, and SonarQube 9.1 mentions adding new rules for Java 16. However, I'm not to familiar with how SonarLint and SonarQube updates interact in this way.As a workaround, you can replacetoList()withcollect(Collectors.toList()).
I'm working on a project (Java 17) where I have a list of object with two properties,actionId(String) andright(boolean). I'm trying to get the actionId for object with right = true and store the result as List of String.This is my code:List<String> usserValidActionsArray = userActionGatewayDTO.stream().filter(UserActionGatewayDTO::getRight) .map(UserActionGatewayDTO::getActionId).toList();My code works fine, but Sonar is blocking me by saying:Refactor the code so this stream pipeline is usedCan anyone suggest to me how I can improve my code to be compliant?
How to remove Sonar issue on Java stream "Refactor the code so this stream pipeline is used"
I would move thereturn falsestatement to outside and after the catch (where return true is now). And move thereturn trueto immediately follow the Fileutils call in the try block, like this:try { FileUtils.moveFile(dcomExportFile, destination); return true; } catch(IOException e) { Logger.error(this, "Could not move file {} to {}, future job runs might fail as well", dcomExportFile.getAbsolutePath(), destination.getAbsolutePath()); } return false;It's confusing and arguably bad style to return from within a catch block anyway.I'm not sure that in this case not letting the exception be thrown is a great idea because this seems like the sort of error I would want to bubble up, where having a return value lets it get lost too easily. Maybe it's not so bad if logging the error is the only thing the code does to handle this.
I'm using latest SonarQube server 9.4 and it constantly reports "Refactor this method to not always return the same value." - java:S3516 in piece of code like this:try { FileUtils.moveFile(dcomExportFile, destination); } catch(IOException e) { Logger.error(this, "Could not move file {} to {}, future job runs might fail as well", dcomExportFile.getAbsolutePath(), destination.getAbsolutePath()); return false; } return true;Which is very strange because method FileUtils.moveFile can throw IOException and in this case method returns false.Any idea?Thx!
SonarQube rule "Methods returns should not be invariant" with catch block
I've changed the method name by removing_character and it worked perfectly with SonarQube and JpaRepository:findByCpoWorkflowStepWorkflowStepIdAndFinishDateIsNull
How everybody solve code smells related to method name on interfaces that extends JpaRepository? In my case I have anCpoWorkflowStepExecutionentity and I want to find by id and date.CpoWorkflowStepExecution:@Entity @Table(name = "cpo_workflow_step_execution", catalog = "cup_orchestrator") public class CpoWorkflowStepExecution implements java.io.Serializable { private Integer workflowStepExecutionId; private CpoWorkflowExecution cpoWorkflowExecution; private CpoWorkflowStep cpoWorkflowStep; private LocalDateTime startDate; private LocalDateTime finishDate; private String outcome; ...WorkflowStepExecRep:@Repository public interface WorkflowStepExecRep extends JpaRepository<CpoWorkflowStepExecution, Integer>{ Optional<CpoWorkflowStepExecution> findByCpoWorkflowStep_WorkflowStepIdAndFinishDateIsNull(String workflowStepId);SonarQube: Rename this method name to match the regular expression '^[a-z][a-zA-Z0-9]*$'.
SonarQube complains about JpaRepository method name
Typically classes annotated with spring‘s@Componentannotation are singletons unless a different scope (like request) is specified. That is the very sameinstanceof this class will be injected by spring in each and every place this class is autowired. By providing a setter for internal fields of the singleton separate threads could set the value in an unsynchronized way, messing up the internal logic of your class.Typically SonarQube should provide additional information and hints on how to solve warnings like this.The most simple fix for the warning would be to add thesynchronizedkeyword to the setter methods. To make your code at least potentially correct this synchronization would need to be added to all read and write usages of the respective members. And this will most likely result in other issues - not talking about performance…The question should beWhy do you need state in an @Component class and are there ways to avoid this state?To answer this it would be needed to know how this class and it’s members are actually used.If you’re only usingUrlItemsin the context of the @ConfigurationProperties class you don’t need to auto wire it and don’t need an @Component class but a simple Java bean. Spring will create instances of this class as needed.
In the SonarQube scan, it shows a major bug at the below-mentioned lines. The issue says,Singleton class writes to a field in an unsynchronized manner. I am not able to figure out, why this is an issue?@Configuration @ConfigurationProperties(prefix = "app") public class UrlConfigs() { @Autowired private List<UrlItems> item; //Getter & Setter } @Component public class UrlItems { private String url; private String location; // Getter public void setUrl(String url){ this.url = url; // ISSUE: Singleton class writes to a field in an unsynchronized manner } public void setLocation(String location) { this.location = location; // ISSUE: Singleton class writes to a field in an unsynchronized manner } }
SonarQube bug: Singleton class writes to a field in an Unsynchronized manner
The minimum version of Gradle that supports Java 11 is5.0.You would need to upgrade to version7.0or above forAndroid.Source:https://docs.gradle.org/current/userguide/compatibility.html
I have an Android project with Gradle 4 that I’m trying to analyze with Sonar. The sonar tasks must run with Java 11 so I configure the java version on 11 in my CI of Azure Devops but I receive this error:Could not determine java version from '11.0.12'.I saw that Gradle 4 is not compatible with Java 11 and that version 9 of sonar is not compatible with Java 8.How to Perform Sonar Analysis on a Gradle 4 Project
Gradle 4 Java 11
If you have everything working as expected after you configured SonarQube on Azure VM (Windows). You should see the sonar home screen via open a browser and openhttp://localhost:9000/.Make sure you add a rule to the Windows firewall. You could open a command prompt as an administrator on Azure VM and run the following command.netsh advfirewall firewall add rule name=Sonar dir=in action=allow protocol=TCP localport=9000Add Inbound security rules in NSG.Then you should be able to access it viahttp://<public IP address of VM>:9000.You could get more detailshereand let me know if you have any questions.
I configured SonarQube on Azure VM (Windows). Everything working as expected. Only thing is I can not access SonarQube portal outside my Azure VM. I whitelisted port in firewall as well as subnet NSG but didn't work. I tried accessing it through VM Public IP as well as DNS but none worked.Port: 9000Is there any specific configuration required?
Access SonarQube Port 9000 outside (publicly) the Azure VM