Response
stringlengths
8
2k
Instruction
stringlengths
18
2k
Prompt
stringlengths
14
160
This limitation will be fixed in 5.2. Thanks for the feedback and sorry for the inconvenience. Seehttp://jira.sonarsource.com/browse/SONAR-6700
I'm finding SonarQube is using alotof disk space in it's temp directory. Is there some sort of clean-up routine that runs regularly to purge this?--- /opt/codehaus/releases`/sonarqube/sonarqube-5.1/temp ------------------------------------------------------------------------------------------- /.. 29.7GiB [######### ] /tmp 92.0KiB [ ] jffi6092968669040435416.tmp 60.0KiB [ ] liblz4-java2192651176366163015.so 20.0KiB [ ] /tc e 4.0KiB [ ] /ror 4.0KiB [ ] sharedmemoryIf not, does anyone have any advice on how to manage this? Restarting the service seems to clear it all, but I don't really want to have to write something that restarts it on a timer.Using v5.1
SonarQube Temp Disk Space
No, it is not possible to change the prefix from "PMD." to "pmd:" in eclipse-pmd (I know because I created eclipse-pmd).It is however possible to use only one of the formats. The reason the two formats exists is that Sonar and eclipse-pmd use different rule engines to analyse the code. eclipse-pmd uses the original PMD engine. Sonar used to use the same engine in the past but a couple of years ago they decided to write their own engine and rewrite most PMD rules for their engine instead. The rules are mostly the same but unfortunately not 100% compatible. The SuppressWarnings format is one of those incompatibilities.You have to decide which engine you want to use. If you want to use the Sonar engine, then use theSonarQube Eclipse Pluginand of course Sonar. If you want to use the original PMD engine then useeclipse-pmdand thePMD plugin for Sonar(which uses the PMD engine instead of the Sonar engine for the PMD rules).Both ways have their advantages and disadvantages. If you use the Sonar engine the analysis should be faster, especially if you also use the Checkstyle and Findbugs rules. SonarSource is however still in the process of rewriting the rules so you currently will not have all the rules that are available in PMD (or Checkstyle and Findbugs).
I am using PMD Plugin for Sonar on Jenkins for the static analysis of my code. I am also running the PMD Plugin for Eclipse (eclipse-pmd 1.5 to be exact (http://marketplace.eclipse.org/content/eclipse-pmd)).My problem is the following : I wanto to suppress a certain PMD warning. Lets say that I want to suppress the warning ShortClassName (http://pmd.sourceforge.net/pmd-5.1.1/rules/java/naming.html) on my class named Rule. Look at the following example :@SuppressWarnings("pmd:ShortClassName") public class Role { //The class fields, constructors, methods ... }That works fine to suppress the warning on Sonar. However, it does not suppress the warning on eclipse-pmd. To do a such thing, I must do the following :@SuppressWarnings({ "pmd:ShortClassName" , "PMD.ShortClassName" }) public class Role { //The class fields, constructors, methods ... }That works, of course, but it bloats the code. Basically, to be consistent with my two plugins, I have to write (almost) the same suppress warning twice.So my question is the following : is there a way to change the warning name prefix from eclipse-pmd plugin from PMD. to pmd: , so the same @SuppressWarnings will suppress both warnings from Sonar and eclipse-pmd ?
Can we use the same suppress warning for both sonar's PMD plug-in and Eclipse's PMD plug-in?
Go to thehttp://<< yourserver >>:9000/setuppage and start the migration process. After that the Sonar Instance will return to working state.
I'm trying to update SonarQube from 4.3.2 to 4.5LTS.The last two lines for log are as below:2015.06.09 16:19:24 INFO app[o.s.p.m.Monitor] Process[web] is up2015.06.09 16:19:46 INFO http-bio-0.0.0.0-9000-exec-1 web[sql] 0ms Executed SQL: SELECT version FROM schema_migrationsAnd the web page shows "SonarQube is under maintenance. Please check back later."And then there is no response for over 6 hours without any error message. Is there anything I can do for this?(Should I upgrade to 4.4 first and then go 4.5?)thanks!
Upgrade from SonarQube 4.3.2 to 4.5LTS (No Response)
The code generation of GWT requires that the@UiFieldsare not private. The UIBinder code generator, that is run during compilation, will create a lot of Java code for you that is added dynamically to your project.This code will directly access the fields and bind the widgets to your variables. This generated code is not using any accessors and there is no option to allow this. (and actually, that makes perfect sense, as it disguises the fact, that these variables are actually set and makes the semantics of the annotation clear).That is the rationale behind the requirement, that these fields are not allowed to be private. Thus, there is no way around this but to disable the sonar warning for the class.
Sonar complains about the following line:@UiField Button saveBtn;Variable 'saveBtn' must be private and have accessor methods.Howerver when I set the visibility modifier toprivate, IntelliJ IDEA complains:@UiField 'saveBtn' should not be' private'What is the best solution about this conflict (besides disabling this sonar warning)?
How to make @UiField fields private
I had to go through my files and change their encoding from utf-8 without bom using Notepad++. The "Encoding" menu in the menubar at the top will give the ability to do this.
I have sonarqube 4.5.4 with installed C# plugin and it cant parse files in UTF-8 BOM encoding.[15:08:01][Step 1/8] 16:07:06.847 ERROR - Unable to parse file: E:\BuildAgent\work\daac5e6d39eee3cb\Source\GraphVizGraph.cs [15:08:01][Step 1/8] 16:07:06.847 ERROR - Parse error at line 1 column 0: [15:08:01][Step 1/8] [15:08:01][Step 1/8] --> п»їusing System;Does anyone had this issue?
Sonar C# plugin. Unable to parse files UTF-8 with BOM
The right solution is :sonar.exclusions=target/**(or justtarget/**is you set it through the UI)
I build my code and invoke SONAR analysis through Jenkins. I want to ignore all the folder/files from SONAR code analysis that fall under the 'target' folder of my code. I have already tried the following things:added '/target/' under the SONAR's Settings > Exclusions, restarted the SONAR server. But i am getting following error[ERROR] Failed to execute goal org.codehaus.mojo:sonar-maven-plugin:2.5:sonar (default-cli) on project : Dangling meta character '*' near index 0 [ERROR]/target/[ERROR] ^added '\\*\\*/target/\\*\\*' under the SONAR's Settings > Exclusions, to avoid the previos error.added 'sonar.exclusions=/target/' in sonar.properties file.But SONAR is still analyzing the code under the "target" folder and under all its sub-folders.
SonarQube 4.3.3 file exclusion not working
SONAR_RUNNER_OPTS is used to customized parameters passed to the JVMwhen you launch a SonarQube analysis on your projectwith thesonar-runnercommand line executable.For instance, you might have a big project for which a lot of RAM is required by the JVM to be able to run the full analysis without getting anOutOfMemoryError: you can increase the max size of the JVM heap using this environment variable.This means that those parameters do not impact other programs but only SonarQube Runner.
Can any one tell me what is meant by sonar-runner-opts and its use?SONAR_RUNNER_OPTS:-Xmx512m -XX:MaxPermSize=10240mWhat is the difference between java-opts and sonar-opts?
Why do we need to set SONAR_RUNNER_OPTS?
With latest versions of the SQ Java plugin, tests are no longer automatically executed. They must be executed prior to the SonarQube analysis and configured so that they produce reports that can be read by the SQ Java plugin.Everything is explained on theCode Coverage by Unit Tests for Java Projectdocumentation page.
I upgraded my sonarqube from 4.1 to 4.4. as in the latest java plugin 2.4 you don't need to have a JaCoCo plugin. I have deleted the jacoco plugin, but now i can not see Tes coverage on sonar dashboard - it's blank. We use bamboo for CI tool and run sonar build from Bamboo. we run below maven command from bamboo build .clean verify -Psonar sonar:sonar -U -fae -Dsonar.forceAnalysis=true
SonarQube 4.4 upgrade can not show test coverage on dashboard
Try to create a squid:XPath custom rule with the following xpathQuery ://assertStatementIt should detect all assert statements.You can achieve the same result with PMD by creating a pmd:XPathRule custom rule. However the xpath is slightly different ://AssertStatement
Over time, I have found that the usage of the "assert" keyword in java has caused more problems than what the developer was hoping to fix. Because of their "off by default" nature in production code, but "on" in test code that is run in Junit or Testng code, tracking down issues in their usage can be made more difficult.Anyway, we started using SonarQube recently. I was hoping to find a rule that would point out the usage of the "assert" keyword, but I have not found one.I was wondering if anyone else had a similar desire in this rule and possibly created a plugin for it?Thanks!
Adding a Sonar rule for the "assert" keyword in Java code
I suspect one of 2 things are happening here:1 - There is a bug in the checkstyle plugin2 - The code sonar analysed is not quite the code you posted hereI believe that violation should apply in the following case:/** * @param lastAccessTime the lastAccessTime to set */ public void setLastAccessTime(Date lastAccessTime) { lastAccessTime = lastAccessTime == null ? null : new Date(lastAccessTime.getTime()); }So when you are reassigning the method parameter it would be expected, but in your example you are not, you are assigning it to a class field so it should be ok.Try changing the method parameter tofinaland see if you still see the violation.
I have the following code and I got an sonar violation error:disallowed assignment of parametersWhat is the best way to fix this?/** * @param lastAccessTime the lastAccessTime to set */ public void setLastAccessTime(Date lastAccessTime) { this.lastAccessTime = lastAccessTime == null ? null : new Date(lastAccessTime.getTime()); }
Sonar violation on "disallowed assignment of parameters"
In order to import cobertura report into SonarQube you need the cobertura-sonar plugin. You can refer to this pagehttp://docs.codehaus.org/display/SONAR/Plugin+version+matrixto know which version of the plugin to use with your version of the platform.For version of cobertura plugin prior to 1.6 you would need to usesonar.dynamicAnalysis=reuseReportsand set the coverage tool to cobertura :sonar.java.coveragePlugin=coberturaas statedin sonarqube coverage documentationHowever I would really recommend you to upgrade to, at least, a LTS version of the platform.
I am trying to get Cobertura code coverage to work for a multi-package project. I had to update from 2.5.2 to 2.6 to work correctly with JDK 1.7 and now I am able to run and create cobertura code coverage reports. The files for the project are stored on a repo and are being built using Jenkins.I have been able to get Cobertura to run correctly through Jenkins as well, and the reports can be seen through Jenkins; however I have hit a speed bump because I want them to show in Sonar.My sonar is a out of the box build and is a much older version. From researching however it looks as though the most current cobertura-sonar plugin (1.6.1) does not work with JDK 1.7 so it would not function with Cobertura 2.0.3.So I am wondering if it is possible to get Sonar to publish the metrics. Is there a way to just ignore the cobertura plugin all together and just have sonar grab the reports? or for sonar to talk to jenkins to get them?I have seen information to get this to work, however I do not believe they are ever Cobertura 2.0.3; I would hate to update sonar and the cobertura plugin to the latest version just to see it not work; considering that updating sonar would most likely mess with other metrics I am passing it.Sonar - 3.2Cobertura-maven-plugin - 2.6 --> cobertura 2.0.3https://jira.codehaus.org/browse/SONARPLUGINS-3170link to the bug report of sonar not supporting cobertura maven 2.6 because of Java 7 syntax
Cobertura 2.0.3 and Sonar not showing code coverage
Yes, you can use PMD, FindBugs and Checkstyle together for a Java development project. There will be overlap, so you will have to select the rules that you activate accordingly. You could start with the default rulesets and then see which findings are being reported by more than one tool.Using SonarQube (formerly Sonar) will also work. SonarQube uses all three tools (and more) under the hood. Using the SonarQube plugin for your IDE, you can also see the SonarQube findings in your code directly. However, you may still run into some overlap depending on your configuration. Chances are smaller though. SonarQube has recently begun providing their own detectors for much of the Checkstyle, PMD, and FindBugs functionality. Those SonarQube provided detectors have little to no overlap among themselves. Also, the "Sonar Way" default ruleset is configured so that there is no overlap.However, if you want to utilize static code analysis professionally, you must be prepared to spend a significant amount of time configuring and fine-tuning the toolchain. After a while, the question of overlap becomes less present, and you will develop opinions on which detector implementation is best for your situation.
Can PMD, FindBugs, and Checkstyle be used together for a Java development project? Does it lead to wide overlapping of functions? Or else, can the same results be achieved using Sonar instead?
Can PMD, FindBugs, and Checkstyle be used together for a Java development project? Does it lead to wide overlapping of functions?
Manual measure won't answer your need: they are only used to push "simple" data at project level.What you need to do is to write your own SonarQube plugin to compute your own metrics. Here's the material that will be useful to you:Coding a PlugindocumentationSample Pluginthat you can use to bootstrap your plugin. Most notably, check theSensor and Decorator classes.
I'm on a project working with SonarQube and the given analysis. Can anyone tell me if I can add an own metric which SonarQube uses to analyse my code? For example (I know this one already exists "Comments Balance"):Tharmar's Metric 00 = "Commented Lines of Code" / "Lines of Code" - OR -Tharmar's Metric 01 = Count the word "Tharmar" used in "Lines of Code"I tried to find something usefull in the documentation. But the only thing I found was aboutManual Measures. I was able to create a new column within the analysis. (proved with the csv-plugin) Understandably, it contains no data.Is there a way how I can tell SonarQube how to find that data? Or how to calculate that Metric with the given data.Thanks for any help :)
Manual Measures / Metrics in SonarQube
Seems like you are looking to use JUnit Categories -https://weblogs.java.net/blog/johnsmart/archive/2010/04/25/grouping-tests-using-junit-categories-0You can then configure your build server to run specific categories at different timesMore info here -https://github.com/junit-team/junit/wiki/Categories
I have a Java project which has layered structure. And each time when commit is madeHudsonbuild is running with all test cases to make sure that code is not broken by new changes. But this may take considerable amount of time due to running test cases for persistence (Hibernate) layer. Also there is aSonarbuild which runs each night.Now I am looking for a way of optimizing test running. I want to remove persistence layers tests from Hudson build and only run it in Sonar. Now it should have two different test suites (profiles).Any suggestion very much appreciated.
How to configure JUnit test suite?
There is currently no way to tie an sonar analysis to a save action.However, you do not need to run the maven based analysis. Assuming you use a recent version of SonarQube and SonarQube ide (4+ and 3.3), you can simply run the analysis using the shortcut (ALT-Ctrl-Q, by default).Using incremental mode with SonarQube 4+, this is actually really fast, because it analyzes only the changed files as compared to the last successful SonarQube run.Of course, you need make sure that your buildserver regularily runs your full SonarQube builds as well.
Actually in our project, we are planning to start developing code (with SONAR to analyze from beginning only) , So we are making use of sonar plugin in eclipse. We know how to analyze code by configuring project to SONARQUEBE and making use of maven build tool as well as using sonarrunner. Instead of building maven for every code changes and analysing , is there any way that prompts (as well as show error lines ) sonar to immediately analyze just after saving the java file ?Help will be appreciated..... Thanks in advance
Prompt SONAR to analyse code
I am representing the NDepend team. Having a NDepend plugin for SonarQube is certainly a good idea and something we'd like to offer out-of-the-box in future features for NDepend vNext. It is also an idea ranked on theNDepend User Voice.Please come back to us by email atsupport at ndepend dot com. We'd like to hear the details of your needs concerningimport NDepend results into SonarQube.For now writing your own plugin using NDepend.API is the way to go if you cannot wait. 100% of data collected by NDepend (structure, metrics, diff, trend...) are reachable through the API. The NDepend PowerTools source code is the right place to get started with NDepend API and see how main API usage scenarios can be implemented.
How can I runNDependfromSonarQube, or import NDepend results into SonarQube?The SonarQubeC# Ecosystem Pluginsupports several other C# tools, but NDepend is not one of them. Commercial and free solutions are both welcome.If no solution is available yet, can theNDepend APIbe used to write a custom plugin SonarQube with reasonable effort?Update 2014-12-11:There was anannouncementby the NDepend team today that a SonarQube integration is being developed. It is expected for Q2 2015. They also mention that there is a new third-partySonarQube pluginfor importing NDepend results now.
Importing NDepend results into SonarQube?
The problem was that I was using 3.7.3 on the server and not 4.0 or above. I upgraded the server install to 4.1 and all is well now.BTW - The Sonar console output clearly stated :SonarQube version 4.0 is required to perform local analysis.
I'm using the Sonar Eclipse plugin v3.3.After I've fixed a rule violation, not a new issue, but one that exists on the sonar server, I re-run the analysis on my project in Eclipse. I expected that the fixed issues would no longer be flagged by the analysis, but they appear to be still flagged even though they have been fixed.In my Eclipse SonarQube preferences I have the severity marked as warning and Force full preview... unchecked.In the view options I have Show->All Issues on Selection checked.How do I set up the plugin so that once I've fixed the issue locally, the issue is no longer flagged when I re-run the analysis on my project?Edit:Full analysis is run nightly by a conditional build step in Jenkins using SonarQube Runner.When I run the analysis via Eclipse, the first thing it does is wipe out the existing issue annotations, but then as soon as it contacts the server it immediately adds them back in. The issues stay flagged regardless of whether they were fixed locally or not.If I intentionally put in the wrong projectKey in the org.sonar.ide.eclipse.core.prefs file, then the local analysis runs similar to what I would expect. It flags all existing issues as new, which is expected, since it can't reach the server to ask if they were preexisting. It doesn't flag any fixed issues.
Sonar Eclipse plugin : local analysis is still tagging fixed issues
It's all in how the sonar.modules properties are set.Following my example, the properties might look like this:sonar.modules=ProjectA,ProjectB ProjectA.sonar.modules=SubprojectA,SubprojectBThe remaining properties for setting basedir, source dirs, etc. are just like any other sonar properties file.
There are plenty of examples of how to do multi-project Sonar projects with Ant. However, what if the projects are nested multiple layers deep? For example:root Project A Subproject A1 Subproject A2 Project BI want to generate a Sonar project that reflects the same structure as the projects, with Project A having showing the summarized view of A1 and A2. However, I can't figure out what the resulting properties should look like to generate this project structure.
How to do a multi-level multi-module Sonar project with the Ant task?
For your information, SonarSource is currently working on a brand new plugin for IntelliJ:https://github.com/SonarSource/sonar-intellij
I have installed the SonarQube plugin in Intellij Enterprise 13. When I follow the configuration instructions at:https://github.com/sonar-intellij-plugin/sonar-intellij-plugin, no inspection errors or warnings are found, even though the code explicitly violates rules that have been returned by the Sonar server to the Intellij plugin and which are visible in the 'inspections' profile.I have a multi-module SpringMVC project thats being built with Gradle. I am not sure if this is relevant.Does anyone have the SonarQube plugin working in an Intellij 13 Java project? Could you share any details of your configuration process or tweaks you needed to make that are not covered in the plugin documentation at the link above?Thanks!
Intellij 13 SonarQube plugin
If you read carefully thedoc page "Analyzing with SonarQube Runner", you can read:Run the following command from the project base directory to launch the analysis:The most important part is"from the project base directory". This should answer your question.
Anyone knows how to figure this out?C:\sonar-runner\bin\.. SonarQube Runner 2.3 Java 1.7.0_45 Oracle Corporation (64-bit) Windows Server 2012 6.2 amd64 INFO: Error stacktraces are turned on. INFO: Runner configuration file: C:\sonar-runner\bin\..\conf\sonar-runner.properties INFO: Project configuration file: NONE INFO: Default locale: "pt_BR", source code encoding: "windows-1252" (analysis is platform dependent) INFO: Work directory: C:\sonar-runner\bin\.sonar INFO: SonarQube Server 4.0 INFO: ------------------------------------------------------------------------ INFO: EXECUTION FAILURE INFO: ------------------------------------------------------------------------ Total time: 7.425s Final Memory: 6M/31M INFO: ----- ERROR: Error during Sonar runner execution ERROR: Unable to execute Sonar ERROR: Caused by: You must define the following mandatory properties for 'Unknow n': sonar.projectKey, sonar.projectName, sonar.projectVersion, sonar.sourcesFor some reason the SonarQube can't find the configuration project path its return NONE from the INFO. I already have the file in the conf path of the sonar-runner.
SonarQube can't find the project configuration path
I'm just facing the same issue and it seems that you can run:sonarqube -x testto avoid having tests run before.
I'm looking at using Sonar to reduced the number of plugins I've had to install in Jenkins to get some decent code analysis (and sonar seems to do more and present it better). However when I kick of the sonar job the JUnit / Concordion tests are executed. I don't want these tests run as Jenkins is already executing the tests.How do I stop the tests executing and just perform code analysis?I've installed sonar 3.7.3 and executing using the Gradle sonar-runner plugin and specifying the :sonarRunner task.
How do I stop sonar running tests?
For non-Maven Java projects, you have to use the dedicated Sonar analysis build step, which relies on the standalone SonarQube Runner.
I am trying to build and run an analyses on anon-maven java projectby building it on Hudson and then running a Sonar analyses via the Hudson-Sonar-plugin.The trouble is, Sonar assumes that the project is a maven project, and fails the build when it doesn't find a pom file.How can I fix this?Here's the relevant parts from the stack trace from Hudson:[workspace] $ mvn.bat -f D:\Hudson\jobs\BirdApp\workspace\pom.xml -e -B sonar:sonar -Dsonar.jdbc.url=jdbc:mysql://localhost:3306/sonar -Dsonar.host.url=http://orbuild01:9000 ******** ******** [INFO] Error stacktraces are turned on. [INFO] Scanning for projects... [ERROR] The build could not read 1 project -> [Help 1] org.apache.maven.project.ProjectBuildingException: Some problems were encountered while processing the POMs: [FATAL] Non-readable POM D:\Hudson\jobs\BirdApp\workspace\pom.xml: D:\Hudson\jobs\BirdApp\workspace\pom.xml (The system cannot find the file specified) @ ......... Sonar analysis completed: FAILURE [DEBUG] Skipping watched dependency update for build: BirdApp #8 due to result: FAILURE Finished: FAILUREI am not sure what other information you might need in my question, but let me know in a comment and I'll add it.
Trouble getting SonarQube to analyze non-maven java project
I don't know if there's an equivalent of SonarQube for .NET projects, but if you really want such reporting (which I can understand, obviously!), you should rather ask questions on how to resolve your installation issue for SonarQube instead of searching for something else. There are plenty of organizations where big .NET solutions are successfully analyzed with SonarQube and the C# plugins, so there's no reason why it can't work for you!You can find useful material on the net to help you on this. For instance, a blog post written by John M Wright about"setting up SonarQube for C# projects". John periodically updates his post, so the information should still be very relevant.
I have a Visual studio solution, which is designed using c# 4.0 .I want to check the code quality for my solution and generate report out of it.I tried the FxCop and i also got the report but i need the report something like this(from the image).The rules compliance is 85% but in FxCop it only showed me the critical, error, etc.I was not able to even deploy my project into SONAR because I had some timeout issuecoming for one of my project in the solution.please someone help me.Thanks in advance.Regards,Roopini
Is there any tool replacement for SONAR for .net code quality and generate report from it?
You have to make sure to use the correct Sonar properties. Fromhttp://docs.codehaus.org/display/SONAR/Code+Coverage+by+Unit+Tests+for+Java+Project:sonarRunner { ... sonarProperty "sonar.java.coveragePlugin", "cobertura" sonarProperty "sonar.cobertura.reportPath", file(...) }
I'm trying to convert my configuration from the old gradle 'sonar' plugin to the new gradle 'sonar-runner' plugin for gradle 1.5.Since I switched to the sonar-runner plugin, sonar is no longer reusing my cobertura coverage.xml to calculate unit test coverage. I can't find any examples in thesonar-runner user guideshowing how to configure this. Previously I was using the sonar.project.coberturaReportPath to specify the location of my coverage.xml.My sonar instance is v.3.4. I'm using a gradle cobertura plugin to generate my coverage.xml.Here's my sonar-runner configuration:sonarRunner { sonarProperties{ property "sonar.host.url", "http://sonar" property "sonar.jdbc.url", "jdbc:mysql://sonar:3306/sonar" property "sonar.jdbc.driverClassName", "com.mysql.jdbc.Driver" property "sonar.username", "username" property "sonar.password", "password" property "sonar.language", "grvy" property "sonar.coberturaReportPath", file("$buildDir/reports/cobertura/coverage.xml") //not sure if this is right! } }Here's my old sonar configuration (which worked!):sonar { server { url = "http://sonar" } database { url = "jdbc:mysql://sonar:3306/sonar" driverClassName = "com.mysql.jdbc.Driver" username = "username" password = "password" } project { language = "grvy" coberturaReportPath = file("$buildDir/reports/cobertura/coverage.xml") } }
How can I specify cobertura report path for gradle sonar-runner plugin?
Sonar Eclipse has nothing to do with Ant, it's really independendent.You should follow the different steps listed in thedocumentation page. Most notably, you need to have a Sonar server up and running somewhere (on your local computer or elsewhere) and you must make sure that you already launched an analysis of your project, which you can browse on Sonar Web application. If not, you'll never be able to associate your project in Eclipse.Once you have a first analysis of your project on the Sonar server, then you need to configure the URL of your server in the Eclipse settings. Only after this, you'll be able to associate your project with Sonar.
Am working on sonar integrated with eclipse using antBut when i go "right click project-->configure-->associate with sonar" nothing happens!!My ant version is 1.7.1Eclipse is Helios(3.6)sonar version is 3.4.1Welcome all your favours..........
SONAR Integrated with Eclipse
Sonar is not just a tool to integrate other tools in a unified environment. First with Sonar you can analyze not just Java source code but code developed in more than 20 languages.http://www.sonarsource.com/products/plugins/languages/Then the star feature of Sonar is the differential views where you can see how the quality of your code is evolving over time. To be honest this can't be done by using these tools in separately.http://docs.codehaus.org/display/SONAR/Differential+ViewsFurthermore you can create code reviews and integrate it with Jira (if you use it) and benefit from over 40 open source and commercial plugins that add more features into your Sonar installation.So IMHO the two tools you mention can't be even compared! And I'd definitely suggest Sonar
I'm looking at adding static code analysis to our Jenkins builds of a Java project (~500K lines of code).Two possibilities areAnalysis CollectororSONAR.One advantage of SONAR looks to be it can showdead code and deprecated methods.Recommendations?
"Analysis collector" or "SONAR" for Jenkins?
Because anyone can modify the external array.With a list, you have the choice of passing in an un-modifiable list to get around that problem while still having the ease of external access if you -want-.So the problem does exist with the second case, but it's much less common, and can more easily be avoided.There are other problems with using a raw array. If the array needs to grow, and you also want external access, you don't have that anymore - they're pointing to the old array, not your new expanded array. With a list, that's all encapsulated.
I have 4 classesClass A { public void setMyArray(String[] myArray) { this.myArray = myArray; } } Class B { public void setMyArrayList(ArrayList myArray) { this.myArray = myArray; } } Class C { public void setX(int x) { this.myX = x; }} Class D { public void setX(Integer x) { this.x = x; }}Sonar reports an issue on the first class Only "Array is stored directly"but sonar did not report the same issue on the second class . I wonder Why ?
Sonar Security - Array is stored directly :: why issue in array only in ArrayList?
"sonar.libraries" references only dependencies of your application, not dependencies of Sonar execution context.If you want to develop custom PMD tasks that will be used by Sonar, please have a look at this example plugin:https://github.com/SonarSource/sonar-examples/tree/master/plugins/sonar-pmd-extension-pluginYou just have to build the JAR of the pluginPut it in your "/extensions/plugins" folderAnd restart Sonar
I'm trying to integrate custom PMD tasks in Sonar, which I currently managed to work along with Sonar PMD plugin.My current issue is to run sonar ant task with the command line.In my eclipse workspace, I add additional classpath entries in Eclipse for Ant to run and it works just fine. But when i run it in the command line, no matter how I pass the jars for ant, it just doesn't seem to be using it in the ClassLoader.This is a big issue for my project, once I can't put the task to run in my continuous integration server.I'm currently passing the jar's that contains all the classes need using the property sonar.libraries.The error I'm getting is:build.xml:121: java.lang.NoClassDefFoundError: net/sourceforge/pmd/AbstractJavaRule at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631) at java.lang.ClassLoader.defineClass(ClassLoader.java:615) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141) at java.net.URLClassLoader.defineClass(URLClassLoader.java:283) at java.net.URLClassLoader.access$000(URLClassLoader.java:58) at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
Run sonar ant task using the command line - ClassDefNotFoundError
Yes.You have to call sonar:sonar everytime you want to execute an analysis that you want to update on the server.If you have to sonar eclipse plugin (Sonar IDE), you can also trigger local analysis, which will not be send to the server.
I have set up a sonar server, and build my project with sonar:sonar. After I linked it in eclipse. So it is analysed the first time. Everything works and shows up in sonar.BUT: how can I retrigger an new analysis? Do I have to execute a new sonar:sonar?ty
Sonar trigger a new analysis?
You canset the Suppression(Comment)Filters manually: Go to Configuration -> General Settings -> Java -> CheckStyle. There's an input box. Paste the<module>definition from your checkstyle.xml file into the input box. Relative paths are interpreted from the .sonar folder. This feature is present in your 2.9, I think it was added on 2.3.For all my purposes, this feature was sufficient. To my knowledge, it is not possible to actuallyimportthe filter module definitions. Might be a newer version of Sonar can do it though.
I am trying to create new rules profile in Sonar 2.9 with my checkstyle rules xml. When I try to import a checkstyle rules file with suppression filter configured, sonar gives me following messages:Profile 'test2' created. Set it as default or link it to a project to use it for next measures. [hide] Checkstyle filters are not imported: SuppressionCommentFilter Checkstyle filters are not imported: SuppressionFilter [hide]I am not bothered about SuppressionCommentFilter for now, but how to enable SuppressionFilter? If it is not possible, is there any other way to have a similar functionality of excluding specific files from specific checks in Sonar?
Sonar 2.9 does not import SuppressionFilter
I wasn't able to solve this via the sqljdbc drivers so I took some advise from another post and fell back to the jTDS driverhttp://jtds.sourceforge.net/index.htmlThe post I used wasSonar MsSql Database IssueMy Setup:Sonar 2.11 unzipped to C:\Sonar\sonar-2.11The steps I made (paraphrased)Download jTDS drivers fromjTDS DriversUnzip it somewhere, I suggest C:\jDSTAdd the DLL to the system path. (C:\jDST\jtds-1.2.5-dist\x64\SSO)Copy the jar file (C:\jDST\jtds-1.2.5-dist\jtds-1.2.5.jar) to the extensions folder (C:\Sonar\sonar-2.11\extensions\jdbc-driver\mssql)Update the sonar.propertiessonar.jdbc.url: jdbc:jtds:sqlserver://localhost:1433/SONARsonar.jdbc.driverClassName: net.sourceforge.jtds.jdbc.Driversonar.jdbc.validationQuery: select 1sonar.jdbc.dialect: mssqlNote: in case you connect to the named instance, this must be specified explicitly in the connection URL:jdbc:jtds:sqlserver://localhost/SONAR;instance=SQLEXPRESSRun the bat file StartSonar.bat (C:\Sonar\sonar-2.11\bin\windows-x86-64\StartSonar.bat)Check your logs and go to the site http:// localhost:9000
When I start Sonar (StartSonar.bat), I get the following error in the log file.Wrong column type in SONAR.dbo.rules for column description.Found: ntext, expected: nvarchar(max)Looking at the column in SQL Server Management Studio it isnvarchar(max)I'm running:DB: SQL Server 2005OS: Windows 7 64 bitSonar: 2.11Tried these drivers:sqljdbc-1.2.2828.100.jarsqljdbc4.jar (Microsoft SQL Server JDBC Driver 2.0)sqljdbc4.jar (Microsoft SQL Server JDBC Driver 3.0)sqljdbc4.jar (Microsoft SQL Server JDBC Driver 4.0)My MSSQL Properties:sonar.jdbc.url: jdbc:sqlserver://localhost;databaseName=SONAR;sonar.jdbc.driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriversonar.jdbc.validationQuery: select 1sonar.jdbc.dialect: mssqlI'm using a user name and password (SQL Authentication) to connect the DBNote to self: When trying to connect to MSSQL remember to Enable TCP/IP. This is found in the SQL Sever Configuration Manager;SQL Server 2005 Network Configuration;Protocols for MSSQLSERVER;TCP/IPI thought it might be a driver issue, but I'm not sureAnyone else seen this?
Error Running Sonar connected to SQL Server 2005. SONAR.dbo.rules for column description
+50There is a build breaker plug-in that will fail the build if you breach a Warning or Error threshold setup in the quality profile.Plug-in details are here:http://docs.sonarqube.org/display/PLUG/Build+Breaker+PluginNot aware of any functionality that enables you to a metric trend.We use Sonar as the second last step in our release process. The build breaker ensures that releases do not breach predetermined quality criteria.
Does Sonar offer any way to raise alerts and fail a build when the trend for certain metrics is bad?Background: In our legacy project using a static threshold for example for code coverage ("red alert when coverage is below 80%") does not make much sense. But we would like to make sure that the coverage does not go down any further.Please do not give any advice on lowering the bar by using a less restrictive rule set. This is no option in our case.
Fail build when trend in Sonar is bad
I'm agree with @bmargulies, it's a valid UTF-8 char (actually it's thereplacement character) but after all, a PMD rule could help. Here is a proof of concept rule with a hard-coded unallowed character list:import net.sourceforge.pmd.AbstractJavaRule; import net.sourceforge.pmd.ast.ASTLiteral; import org.apache.commons.lang3.StringUtils; public class EncodingRule extends AbstractJavaRule { private static final String badChars = "\uFFFD"; public EncodingRule() { } @Override public Object visit(final ASTLiteral node, final Object data) { if (node.isStringLiteral()) { final String image = node.getImage(); if (StringUtils.containsAny(image, badChars)) { addViolationWithMessage(data, node, "Disallowed char in '" + image + "'"); } } return super.visit(node, data); } }Maybe it would be useful to invert the condition and make anallowedCharswhitelist with ASCII characters and your local chars as well. (There is some more detail ofcustom PMD rules in this answer.)
I'm currently working on a Java project where it's part of my job to watch over the quality. As tools I use Jenkins in combination with Sonar. These tools are great and the helped me to track issues fast and continuously.One issue I don't get under control is that some people commit using other encoding than UTF-8.When code like this:if (someString == "something") { resultString = "string with encoding problem: �"; }... gets committed, Sonar will help me finding the "String Literal Equality" issue. But as you see in the second line there is an issue with the encoding: "�" should usually be an "ü".Is there any possibility to find these kinds of problems with Sonar/Findbugs/PMD...Please advice! Thank you.Ps: Of course I've tried to explain the issue to my co-developers in person as well as via email. I even changed their project/workspace encoding myself... But somehow the still succeed in committing code like this.
Finding encoding issues in Java Project/Source
I finally found the problem (thanks the code browsing ;) ).I set the URL for my build tohttp://localhost:8080/jenkins, but the correct URL isHudson:http://localhost:8080/jenkins/job/MyJobName.But unfortunately, this plugin does not meet my requirements, but this is another problem!
I want to monitor the build stability of my continuous integration builds. To do that, I am using theBuild Stability Pluginfor Sonar, but unfortunately, I was not able to make it work correctly.At the end of the build (basically amvn clean install sonar:sonar), the logs display the following information:[INFO] Sensor org.sonar.plugins.buildstability.BuildStabilitySensor@13fc816... [INFO] CI URL: http://localhost:8080/jenkins [WARN] Unknown CiManagement system or incorrect URL: http://localhost:8080/jenkins [INFO] Sensor org.sonar.plugins.buildstability.BuildStabilitySensor@13fc816 done: 47 msOn Sonar, the widget does not display any data...Of course, the URL is correct, and both Jenkins and Sonar are running correctly, and on the same machine. Did I miss something?I am currently working with Jenkins 1.410, Sonar 2.7 and plugin 1.1.2, but I also tried with an older installation (Hudson 1.347 and Sonar 2.1.2).
Build Stability Plugin for Sonar does not gather data from Jenkins / Hudson CI server
If your projects are built with maven then all you need to do is runmvn sonar:sonaron your project root folder (where yourpom.xmlis located) and the report will get pushed to your sonar instance.And also you need to have the sonar profile set up in your settings.xml. Example below:<settings> <profiles> <profile> <id>sonar</id> <activation> <activeByDefault>true</activeByDefault> </activation> <properties> <!-- EXAMPLE FOR MYSQL --> <sonar.jdbc.url> jdbc:mysql://localhost:9000/sonar?useUnicode=true&amp;characterEncoding=utf8 </sonar.jdbc.url> <sonar.jdbc.driverClassName>com.mysql.jdbc.Driver</sonar.jdbc.driverClassName> <sonar.jdbc.username>sonar</sonar.jdbc.username> <sonar.jdbc.password>sonar</sonar.jdbc.password> <!-- SERVER ON A REMOTE HOST --> <sonar.host.url>http://localhost:9000</sonar.host.url> </properties> </profile> </profile>Read morehere.
I installed Sonar Plugin on my eclipse, (i ran the server .../StartSonar.bat) and when I do test connection on LocalHost:9000 its okay (Connection Sucessfull). Now What should I do to associate my projects with sonar? I'm kind lost. I'm rookie.
Sonar Configure
I'd suggest to define a filter in Sonar which only includes files. If you define a dashboard which contains this filter you can simply order the files by afferent couplings if you've added this column.
I want to find in a given Java project, the classes with the highestafferent coupling.I know that the metric is available in SONAR when youdrill down to a class from the dashboard, orwhen you drill down package by package in the components view.What's the quickest way to find this information within SONAR?
Afferent coupling in SONAR
JDependmaybe?BTW, I'm curious why do you need dependency analysis on tests? Maybea code coverage reportis what you're looking for instead?
I have a multi module maven project. I set up Sonar. The most interesting part for me right now is the dependency analysis on package level including the (JUnit) tests.Unfortunatly Sonar seems to ignore the tests at least for the dependency analysis. Is there a way to change that?If this is not possible, is there a way to get the dependency matrix for my tests (or tests + main src) using another free tool?
Do a dependency analysis of tests using Sonar (or other)
The SONAR_JAVA_PATH should end with java.exe. Try C:\Program Files\Java\jdk-20\bin\java.exehttps://docs.sonarqube.org/latest/setup-and-upgrade/install-the-server/This page has two examples, one for Windows and one for Linux.
I'm installing SonarQube version 10.I have already installed JDK 20 and setenvvariable path toC:\Program Files\Java\jdk-20\binandSONAR_JAVA_PATHtoC:\Program Files\Java\jdk-20. I have also setJAVA_HOMEpath to jdk-20. Now when I runStartSonarin cmd, it gives me error. I'm stuck at this problem for too long. I have tried with JDK 11 as well but still the same error. Any help would be appreciated.Thanks.Error message:Java --version:
Java path is not recognized in SonarQube installation
The code says:// if there are any entries in numlist if (numlist.Any()) { // find the first entry whose Number matches the request, // or if not found, return the default for the numlist's // type, which is null according to the warning numlist.FirstOrDefault(c => c.Number == request.Number) // set the ValCount property of the result to request.Count .ValCount = request.Count; }The problem is thatFirstOrDefault(predicate)returns a default value if none of the elements in the source collection matched the predicate.In other words: it's not guaranteed that there's any entry innumlistthat hasNumber == request.Number, in which caseFirstOrDefault()will returnnull.You can't assignValCountonnull, that will throw a NullReferenceException.Furthermore, combiningAny()andFirstOrDefault()is superfluous in this case. You can refactor the code like this:var requestedItem = numlist.FirstOrDefault(c => c.Number == request.Number); if (requestedItem == null) { throw new ArgumentException($"Cannot find item with number '{request.Number}'"); } requestedItem.ValCount = request.Count;Guarding execution (and at the same time pleasing the static analysis), guaranteeing that a situation which you think might never happen, will never happen.
c# codeif (numlist.Any()) { numlist.FirstOrDefault(c => c.Number == request.Number).ValCount = request.Count; }Sonar Cube throws bug message saying as 'numlist.FirstOrDefault(c => c.Number == request.Number)' is null on at least one execution path.I have tried to put nullable ? like this -> numlist? but it doesn't works.Can you please assist how to resolve this issue
Sonar Cube throws bug saying as "is null on at least one execution path."
Add the following system environment, Ex:SONAR_JAVA_PATH : C:\Program Files\Java\jdk-11.0.17\bin\java.exe
I've set the environmental variable SONAR_JAVA_PATH.It's taken in the SonarServiceWrapper.xml<!-- Path to the Java executable. To be replaced by SonarService.bat script --> <executable>D:\Programmes\Java\jdk-13.0.2\bin\java.exe</executable> <!-- DO NOT EDIT THE FOLLOWING SECTIONS --> <arguments> -Xms8m -Xmx32m -Djava.awt.headless=true --add-exports=java.base/jdk.internal.ref=ALL-UNNAMED --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.nio=ALL-UNNAMED --add-opens=java.base/sun.nio.ch=ALL-UNNAMED --add-opens=java.management/sun.management=ALL-UNNAMED --add-opens=jdk.management/com.sun.management.internal=ALL-UNNAMED -cp "..\..\..\lib\sonar-application-9.6.1.59531.jar" "org.sonar.application.App" </arguments> <id>SonarQube</id> <name>SonarQube</name> <description>SonarQube</description> <logpath>../../../logs</logpath> <log mode="none"/> </service>No error in the command line.Only one log file SonarServiceWrapper.wrapper.log with this line :2022-10-11 12:26:01,286 DEBUG - Starting WinSW in console modeI've tried with jdk-11.0.2, jdk-13.0.2 and jdk-19 : same thing
Sonarqube 9.6.1 not starting - Windows10 cmd
Unfortunately, the only real resolution is to set a duplications exclusion for those two classes (assuming this is 1 class/file).Go to Project Settings -> General Settings -> Analysis Scope -> C. Duplication Exclusions
Sonarqube block my build due to Duplicated blocks for this two classes :@Entity @Table(name = "my_table") public class Employee { @Id @Column(name = "ID") Integer id; @Column(name = "NAME") String name; @Column(name = "AGE") Integer age; public void setName(String name) { this.name = name; } public String getName() { return name; } public void setAge(int age) { this.age= age; } public int getAge() { return age; } public void setId(int id) { this.id= id; } public int getId() { return id; } }@ApiModel(value = "Employee") public class EmployeeDTO { @ApiModelProperty(required = false, example = "1") Integer id; @ApiModelProperty(required = false, example = "Jhon") String name; @ApiModelProperty(required = false, example = "25") Integer age; public void setName(String name) { this.name = name; } public String getName() { return name; } public void setAge(int age) { this.age= age; } public int getAge() { return age; } public void setId(int id) { this.id= id; } public int getId() { return id; } }any idea how i can resolve this issue since i don't want to create an abstract class then inherit from it because i will lose the swagger and JPA annotations and i want to keep the visibility for each class and layer.thanks.
SonarQube Major Issue: Duplicated blocks of code must be removed same class with different annotations
Okey, I've got an answer!Proper settings are:'sonar.sources': 'src', 'sonar.tests': 'src', 'sonar.exclusions': '**/__tests__/**', 'sonar.test.inclusions': '**/__tests__/**',It's notsonar.TESTS.inclusions, it'ssonar.TEST.inclusions, 1 letter difference.
Answers to questions like 'how to grab tests from multile folders' and to questions 'how to avoid file can't be indexed twice' are just opposite each other. So this question is not a duplicate of one of them.I have a structure like that:src |_component1 | |__tests__ | |_units.tsx | |_component2 |__tests__ |_units.tsxIf I try customizesonarlike this:'sonar.sources': 'src', 'sonar.tests': 'src', 'sonar.exclusions': 'src/**/__tests__/**/*', 'sonar.tests.inclusions': 'src/**/__tests__/**/*.{js,jsx,ts,tsx}',It fails with errorfile can't be indexed twice. Please check that inclusion/exclusion patterns produce disjoint sets for main and test files.If I providesonar.sourcesandsonar.testswith different paths, it can't see my multiple__tests__directories.How could I combine both grab multiple test directories and avoid this error?
Sonarqube: grab tests from multiple directories AND avoid an 'file can't be indexed twice'
You have to configure the server public URL:Log in to the SonarQube dashboard and click on theAdministrationtabBrowse to theConfiguration → General settings → GeneralmenuUnder theGeneralsection, change theServer base URLto the public URLSave the changesCopy-pasted from:https://docs.bitnami.com/aws/apps/sonarqube/administration/configure-domain/
Hello I have set up CI/CD on my project using SonarQube, my SonarQube is hosted on a server and GitLab connects to it, but for some reason after the analysis is finished it posts a summary of the analysis as a comment on merge request but the link is directed to localhost:9000 not my server link where the analysis can actually be accessed.how could I make it point to my server link?
SonarQube report points to localhost on GitLab
How about usingifPresent:customer.getFirstName().ifPresent(name1-> customer.getLastName().ifPresent(name2-> final String firstName = name1; final String lastName = name2; ); );
I receive a Customer object which contains lastName and firstName. In the conversion I check if both values are not empty and then pass them into the DTO:if (customer.getFirstName().isPresent() && customer.getLastName().isPresent()) { final String firstName = customer.getFirstName().get(); final String lastName = customer.getLastName().get(); // do assignment }But I still get the Sonar messageOptional value should only be accessed after calling isPresent().Am I missing something here or is this a false positive?
"Optional value should only be accessed after calling isPresent()" although checked in if for multiple values
There is a typo in your-Dsonar.tests.inclusions=**/*.spec.tsline.It must be-Dsonar.test.inclusions=**/*.spec.ts. sonar.test.inclusions, not sonar.tests.inclusionsHad the same situation, found this after 20 minutes of seeing that frustrating error.It is very strange that SonarQube allows this parameter to pass without any error or warning and most misleading thing is that there is more logic in-Dsonar.tests.inclusionsthen in-Dsonar.test.inclusionsbecause of-Dsonar.tests.
I have an angular project that is being scanned by Sonarqube through Jenkins. I get the code coverage but sonarqube won't show the number of unit tests (*.spec.ts files) we have written.From sonarqube test script:sonar-scanner \ -Dsonar.sources=. \ -Dsonar.tests=. \ -Dsonar.exclusions=**/*.spec.ts \ -Dsonar.tests.inclusions=**/*.spec.ts \ ...I have no access to the sonarqube ui since this is enterprise. Everything is being configured through scripts/config files in angular. Is there a way to see the number of angular unit tests on the sonarqube website after the scan is done?P.S.: Originally I had -Dsonar.exclusions=node_modules, **/.spec.ts \ but this will throw an error on Jenkins saying **/.spec.ts is an unrecognized command.
Please check that inclusion/exclusion patterns produce disjoint sets from main and test files. Sonarqube with Angular
On official documentation, there is a page aboutNarrowing the FocusSonarQube gives you several options for configuring exactly what will be analyzed. You cancompletely ignore some files or directoriesexclude files/directories from Coverage calculations but analyze all other aspectsexclude files/directories from Duplications detection but analyze all other aspectsexclude files/directories from Issues detection (specific rules or all of them) but analyze all other aspectsThere you can findIgnore Duplicationssection:Ignore DuplicationsYou can prevent some files from being checked for duplications.To do so, go to Project Settings > General Settings > Analysis Scope > Duplications and set the Duplication Exclusions property. See the Patterns section for more details on the syntax.
Let say I have a class like this.public class ApplicationInfoDTO implements IdInc { private String applicationName; private String description; private String version; private String releaseDate; private List<String> registeredServicesList; ... and soome other fieldsAll the fields are marked by Sonar as duplicated Code Block, actually it make no sense to rename fields or solve this with inheritance.At this point I want to ignore this warning. I put a // NOSONAR like this.public class ApplicationInfoDTO implements IdInc { // NOSONARalso I try it with // NOSONAR after a package declaration. Both not worked.How I can add an ignore flag?
How to ignore Sonars Duplicate Code Block Warning
Sometimes doing the right thingrequiresthat you "make a ton of changes". SonarQube is correct, losing the history (mostly - the stacktrace) is a real problem of your code.You are free to ignore the warning or disable it somehow, but you cannot make it "a SonarQube bug" just because it's inconvenient.The usual way to fix it would be to create another (or change existing) constructor of theCustomExceptionclass; or add the cause in each place it gets thrown. It might be a lot of work, but it can also be a life saver when you have a rare bug on production - and you can actually see where it originated.
In SonarQube scan it catches some bugs and it says method catches an exception, and throws a different exception, without incorporating the original Exception.Look at the below code,try { // something // can include nested exceptions... } catch (CustomException ex) { throw ex; } catch (Exception ex) { // Issue is here throw new CustomException(HttpStatus.INTERNAL_SERVER_ERROR, "exception message: "+ ex); }Below is the Custom Exception DTOclass CustomException { HttpStatus status; String message; // Getter & Setter.... }I couldsolve this issueby doing,catch (Exception ex) { CustomException exception = new CustomException(HttpStatus.INTERNAL_SERVER_ERROR, "message" + ex); exception.initCause(ex); throw exception; }The above solution is fine, but it's not ideal for the current situation, because I have to make a ton of changes then.My question is, why is the below code not working. Is it because I am passing theORIGINAL CAUSE as a STRING?throw new CustomException(HttpStatus.INTERNAL_SERVER_ERROR, "exception message: "+ ex);If "ex" passed as a String is the issue, then is there a way to resolve it because My CustomException can take only "String" fields and I cannot change the type of any of the fields? Any suggestion?
SonarQube Bug: Method throws alternative exception from catch block without history
setStringmay throw anSQLException. If the statement is successfully prepared and thensetStringthrows an exception, it will do sooutsideof thetryblock and the statement will never be closed. Moving theprepareStatementinto a nestedtryshould be OK, as long as you have theclsoein the rightfinallyblock (and without seeing what you did it's hard to say why SonarQube is complaining about it), but honestly, using the try-with-resource syntax would just be so much neater. Note, by the way, that theResultSetshould also be closed:public String getUserEmail(String id) throws SQLException { String emailAddress = null; String sql = "select email from my_table where id=?"; try (PreparedStatement preparedStatement = this.connection.prepareStatement(sql) { preparedStatement.setString(1, id); try (ResultSet rs = preparedStatement.executeQuery()) { while (rs.next()) { emailAddress = rs.getString("email"); } } catch(SQLException e) { throw new TuringClientException("Failed to getUserEmail. ", e); } } return emailAddress; }
I'm trying to get an email from a table based on the user's id. However, SonarQube keeps complaining aboutUse try-with-resources or close this "PreparedStatement" in a "finally" clausewhich I already have. I've looked at the answerhereand other places but the solutions don't work for me. Here's the code:public String getUserEmail(String id) throws SQLException { String emailAddress = null; String sql = "select email from my_table where id=?"; PreparedStatement preparedStatement = this.connection.prepareStatement(sql); preparedStatement.setString(1, id); try { ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { emailAddress = rs.getString("email"); } } catch(SQLException e) { throw new TuringClientException("Failed to getUserEmail. ", e); } finally { preparedStatement.close(); } return emailAddress; }I've also try wrappingPreparedStatement preparedStatement = this.connection.prepareStatement(sql)in another try catch or do nested try-catch but none of the attempts works.
SonarQube keeps complaining about Use try-with-resources or close this "PreparedStatement" in a "finally" clause
You can for example extract the complexifblocks to separate methods.I mean theseifblocks:Extract to method 1 (eghandleCategories):if (window.PageContext.categories) { for (let category of window.PageContext.categories) { if (Utils.categoryMap[category.slug]) { t = Utils.categoryMap[category.slug]; break; } } }Extract to method 2 (eghandleBreadcrumbs):if (window.PageContext.post && window.PageContext.post.breadcrumbs) { for (let category of window.PageContext.post.breadcrumbs.reverse()) { if (Utils.categoryMap[category.slug]) { t = Utils.categoryMap[category.slug]; break; } } }This will move around 3 complexity levels (if+for+if) from the original method to each of the extracted methods.
How can I reduce the complexity of the bellow piece of code? I am getting this error in SonarQube:Refactor this method to reduce its Cognitive Complexity from 16 to the 15 allowed.(function () { window.dm = window.dm || { AjaxData: [] }; window.dm.AjaxEvent = function (et, d, ssid, ad) { dm.AjaxData.push({ et, d, ssid, ad, }); window.DotMetricsObj && DotMetricsObj.onAjaxDataUpdate(); }; const d = document; const h = d.getElementsByTagName('head')[0]; const s = d.createElement('script'); let t = 'inews'; s.type = 'text/javascript'; s.async = true; if (window.PageContext.categories) { for (let category of window.PageContext.categories) { if (Utils.categoryMap[category.slug]) { t = Utils.categoryMap[category.slug]; break; } } } if (window.PageContext.post && window.PageContext.post.breadcrumbs) { for (let category of window.PageContext.post.breadcrumbs.reverse()) { if (Utils.categoryMap[category.slug]) { t = Utils.categoryMap[category.slug]; break; } } } }()); export default () => { };
Refactor this method to reduce its Cognitive Complexity from 16 to the 15 allowed. How to refactor and reduce the complexity?
Since SonarQube 9.0 analysis must be done using JDK11. This is one of the breaking changes in 9.0, see officialdocumentation.
We have upgraded from 7.6>7.9>8.9>9.0.And now we are facing the same issue,plugin:3.9.0.2155:sonar failed: An API incompatibility was encountered while executing org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.0.2155:sonar: java.lang.UnsupportedClassVersionError: org/sonar/batch/bootstrapper/EnvironmentInformation has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0I have gone through the documentationhttps://docs.sonarqube.org/latest/analysis/languages/java/#header-3, but how can we user sonar.java.jdkHome and where? And this jdk should be on jenkins slave or sonarqube server? We dont use the sonarqube properties file, we have jenkins build where we have maven config and only sonar:sonar for scans. How can we manage this scenario.Thanks in advance.
An API incompatibility was encountered while executing org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.0.2155:sonar
If you're using the "sonar:sonar" goal, it will use the Maven pom.xml. You should ensure your properties are set properly in the pom.xml. It is not useful to try to set these properties in an external file if you are using the Maven plugin.
I have a Spring Boot application that is using a local instance of SonarQube to analyse the code. I need configure some file exclusions. If a set the exclusion on pom.xml it works fine, example:<sonar.exclusions> **/services/MyClass.java </sonar.exclusions>But if a try using sonar-project.properties it not works, example:sonar.exclusions=**/services/MyClass.javaShould I need some extra configuration in order to use the sonar-project.properties file ?I did this test usingsonarqube-scanner-mavenproject.
SonarQube is using pom.xml and ignoring sonar-project.properties file
As you have mentioned java 8 is been deprecated so You can force the analysis with Java 8 temporarily by setting the property'sonar.scanner.force-deprecated-java-version' to 'true'.in POM file like below<properties> <java.version>1.8</java.version> <sonar.scanner.force-deprecated-java-version>true</sonar.scanner.force-deprecated-java-version> </properties>hope this will work.You can find more information here:sonar up-comings.cheers.
I have build maven project using java 8 and doing all the pipeline and authentication configuration with Bit-bucket n Maven, but still getting this issue.Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.7.0.1746:sonar (default-cli) on projectProject namealso getting this error message next line of error:The version of Java (1.8.0_121) you have used to run this analysis is deprecated and we will stop accepting it soon.As Java 8 has been deprecated we are unable to get/view Sonar overview widget for our services.
Failed to execute sonar-maven-plugin:3.7.0.1746 on project Project_Name
You can annotate it with@SuppressWarnings("unused").Either the method:@SuppressWarnings("unused") public int getIterableSize(Iterable<User> users){ int size = 0; for(User user : users){ size++; } return size; }Or the variable:public int getIterableSize(Iterable<User> users){ int size = 0; for(@SuppressWarnings("unused") User user : users){ size++; } return size; }Various IDEs can automatically offer both of these fixes.
This question already has answers here:Get size of an Iterable in Java(10 answers)Closed3 years ago.In my project I have a simple function that calculates the length of an iterable (as I don't think there is an easy way to get it? No.size()or.length()is accepted?) Here is the code:public int getIterableSize(Iterable<User> users){ int size = 0; for(User user : users){ size++; } return size; }I also use Sonarqube to keep my code quality and I get the following code smell about this function:Remove this unused "user" local variable.There must be an easy way to get rid of this right? Maybe an alternative for the for loop, maybe a different function provided by iterable?
Sonarqube complaining about unused variable in for loop [duplicate]
The code that's causing this issue is this:new RootElement(element, NewControlsNotifier);You are creating aRootElementwith new operator but ignored its result. You should either remove object creation completely or use the object you created.Try this if you want to return your object:private RootElement GetParentAsRoot(Element element, string method) { if (element.Parent == null) { return new RootElement(element, NewControlsNotifier); } var root = element.Parent as RootElement; if (root == null) { throw new ArgumentException(method + " method is applicable only on top-most element"); } return root; }
I'm trying to fix this bug that I get from SonarQube but their solution suggestion is not quite helpful for my case. The suggestion that I'm getting from them is: "There is no good reason to create a new object to not do anything with it. Most of the time, this is due to a missing piece of code and so could lead to unexpected behavior in production."Any suggestions on how this to be handled will be appreciated.private RootElement GetParentAsRoot(Element element, string method) { if (element.Parent == null) { new RootElement(element, NewControlsNotifier); //Either remove this useless object instantiation of class 'RootElement' or use it. } var root = element.Parent as RootElement; if (root == null) { throw new ArgumentException(method + " method is applicable only on top-most element"); } return root; }
SonarQube Complaint Either remove this useless object instantiation of class or use it
I did write an earlier comment that it is perhaps sonarqube but I've had another look:) I think your comments about the possible values is flawed because these are standard C++ strings (not C ones) so effectively can't be NULL as such. However there is a possible OOM exception on the add - you are probably right that the non-followed branch is this exception.I did some experiments comparing the gcovr output using the --exclude-throw-branches and --exclude-unreachable-branches. Basically it made no difference on the gcovr report for this line, although it did make some difference on other lines.I am not sure I mentioned that we are using clang rather than (say) gcc.I guess that might make a difference. Not sure. Whatever the reflection does seem to be that this is a gcov/gcovr issue and not sonarqube.I had originally assumed that made no difference. Seems it does. From what I can work out, "llvm-com gcov" (the subcommand of llvm-cov that simulates gcov) does not generate the tags to show that some branches reflect throws. I've looked at the output locally - I probably need to compare with gcc and gcov. However that seems to be the real problem.
We are running gcovr on our codebase which is (FTR) then fed into SonarQube (cxx-plugin). There are many places where there is a report of less than 100% coverage, even though there are no obvious branches so it should be surely 0 or 100%. Take for example the following:std::string quote(const std::string& str, const std::string& quote_str) { return quote_str + str + quote_str; }On SonarQube, the first line is reported as "Fully covered". The second line is reported as "Partially covered by tests (1 of 2 conditions)". The third line is not mentioned - as expected. Question is as to what are the conditions that (I guess) gcovr is seeing on the return line that I can't.I have tried a suggestion fromWhy gcc 4.1 + gcov reports 100% branch coverage and newer (4.4, 4.6, 4.8) reports 50% for "p = new class;" line?(adding --exclude-throw-branches) and have even tried adding --exclude-unreachable-branches. Seems to make no difference.Looking at the generated xml output, I notice that both the first few lines are showing 57 hits with branch="false". I am wondering where the "1 of 2 conditions" comes from and perhaps it is SonarQube?Has anybody else seen this or have a solution?UpdateI didn't mention this to start with, because it did not seem relevent, but we are using clang v11 (not gcc), and thus "llvm-cov gcov" (not gcov itself) below gcovr. As reflected below, seems this is important.
gcovr/SonarQube saying simple C++ function is only half covered
Add to your class:private static final Logger logger = LoggerFactory.getLogger(YourClassName.class);and try this:logger.error("Error in x file {}", e.getMessage());Logging this way, you avoid performance overhead for strings concatenation.More about spring-boot logging configurationZero Configuration Logging
I am writing code the below codeLogger.error("Error in x file :",+ e.getMessage());But for the above line of code I am getting the error to use format specifiers instead of string concatenation. How should I fix it?
Format specifiers should be used instead of string concatenation in java
in order to use arrow functions inside a class you need to enable this plugin in your babel configuration.{ "plugins": [ "transform-class-properties" ] }or you can do it like thisclass BackButton extends React.Component { constructor() { super(); this.handleClick = (val) => { ... }; … } }
I am facing this error while using sonar-scanner. It is unable to parse all those files in which i have used arrow functions.import React from "react"; import { Button } from "antd"; import history from "src/components/history"; class BackButton extends React.Component { handleClick = () => { history.goBack(); if (this.props.onBack) { this.props.onBack(); } }; render() { return <Button icon="arrow-left" onClick={this.handleClick} />; } } export default BackButton;The error at line 6. Need a solution to fix this.
Unexpected token = (with espree parser in module mode) in my react project using sonar-scanner
I think there is a misunderstanding, between SonarQube Server and SonarQube Scanner, this is already well explained inhttps://stackoverflow.com/a/49588950/3708208So to do an analysis, you actually need to run a SonarQube scanner with some specificaitons, which is pretty welldocumented. When you have successfully set up the scanner, you can easily retrieve reports, status, quality gate via REST API.
I am working on a online-school where student projects are decentralized on git repositories. When a student wishes to correct a project:The student must specify his git-repo-url + private key in order to pull it on the correction-serverThen several tasks are applied on the project (compilation check, output checks).I'd like to check the code quality and return a feedback for each user. I guess sonarqube would be a good choice since it supports 28+ languages.I am familiar with sonarqube used with a continous integration, but I can't find in their documentation how to call sonarqube for my use case. I'd need something like a rest api for requesting a code analysis by giving the git url & its key and get a response with the code quality output.Would it be possible?
Can I use my sonarqube server for any git repository?
No it can not. The scanner relies on the SonarQube Server to fetch a ruleset to execute this. Additionally it will check if you violate your quality gate or not. The server is your Rule Managament and Decision maker, where as the scanner, is just checking your code based on the rules provided.The question is, what is your usecase. Do you just want to verify during development, that everything is working accordingly, you could use SonarLint which has a built-in default set, but can be also configured to connect to sonarqube/sonarcloud server to fetch data.If you do not have the possibility to host your own sonarqube server, you can also take a look at sonarcloud.io - which is a cloud offering from SonarSource and a similar product to sonarqube (similar but not the same). It is free for open source, but also provide paid plans.
Sonar Scanner analysis work without pushing the results to the SonarQube server?sonar scanner is givingERROR: SonarQube server [http://127.0.0.1:9000] can not be reached [14:15:57] [Step 2/4] ERROR: Error during SonarQube Scanner execution [14:15:57] [Step 2/4] org.sonarsource.scanner.api.internal.ScannerException: Unable to execute SonarQube
can sonar scanner work without sonarqube server to be up and running
Depending on the nature (confidential or public) of your project, you could use aGitHub ActionslikeSonarSource/sonarcloud-github-actionThat way, on each push, you would scan your code withSonarCloud.io.But if you have a local SonarQube instance running, then you need theDeveloper edition, and check if your GitHub credentials are correct.
I have a repository in my github account and i want to analyse it with sonarqube after each commit I put the repository url in my sonar scanner properties : sonar.sources=https://github.com/rahma/JavaTestbut does not work . any idea about this please ?
sonarqube github project analysis
Although it is possible to use the agents to publish a website on an internal server (only accessible by VPN), Sonarqube isn't prepared to work in a similar fashion (uploading the necessary files from Azure DevOps).There are only 2 solutions to this problem:Create an exception on your VPN, authorizing the access to the Sonarqube port. This solution has security constraints.Use SonarCloud (SonarQube cloud version) instead of SonarQube. This solution might have an associated cost, as the SonarCloud free version forces us to share our code with the public. Only the paid version ensures your code remains private.
I cannot contact my internal on-premises SonarQube from Azure DevOps (cloud).Here's the error I get on the Azure Build Pipeline:##[debug][SQ] API GET '/api/server/version' failed, error was: {"code":"ETIMEDOUT","errno":"ETIMEDOUT","syscall":"connect","address":"172.16.8.3","port":9002}My on-premises SonarQube is internal (accessible only through VPN) but as I installed an Azure agent on this machine (where Azure is already capable of automatically publishing my websites) I thought I didn't need anything else for it to become accessible from Azure DevOps.What am I missing?
Can't access internal SonarQube (on-premises) from Azure DevOps (cloud - PaaS) despite having installed the agent
I found the resolution for this we need to go intoAdministration > General > Server base URLupdate the 'Server base URL'. on sonarqube portal.
The Quality gate status url in a PR is always pointing to localhost and not to the actual sonarqube server. The detailed analysis report link in the build pipeline is working fine. SonarQube 8.2 Enterprise Edition, Scanner Latest from Azure Devops Marketplace. Create a PR request and trigger a Build with Sonar Analysis. Add a Build policy to validate Sonar Quality Gate Click on the link. It routes to localhost and not the actual server.When I click on “Quality Gate failed” hyperlink, it takes me tohttp://localhost/dashboard?id=***&pullRequest=952. Ideally it should point to the server where I have my sonarqube hosted.
Sonarqube Quality Gate status link in Azure devops Pull Request always points to localhost
You should avoid the magic strings and usenameofinsteadpublic int Property2 { get => (int)Properties[nameof(Property2)]; set => Properties[nameof(Property2)] = value; }
Sample code:public class Foo: Bar { protected static readonly string Property1Name = "Property1"; protected static readonly string Property2Name = "Property2"; public string Property1 { get => (string)Properties[Property1Name]; set => Properties[Property1Name] = value; } public int Property2 { get => (int)Properties[Property2Name]; set => Properties[Property2Name] = value; } }Propertiescollection defined in base class and used inPropertyGrid. Real code much more complex - there are other classes derived fromBarand useProperties(hundreds properties).SonarQube found bugs in getters and setter ofProperty1andProperty2:Getters and setters should access the expected fieldsI could suppress or disable SonarQube's rule, but the code above is error-prone - if a developer copy/paste code it could be end up with something like:public double Property3 { get => (double)Properties[Property3Name]; set => Properties[Property2Name] = value; }Hunting for the above bug is not an easy task.Any ideas how to redesign code to fix SonarQube's warnings and make the code less error-prone?
How to redesign code to reslove SonarQube "Getters and setters should access the expected fields" bug?
So you want to take only the last created code coverage file, you can filter theGet-ChiledItemresults to get the last one:Get-ChildItem -Recurse -Filter "*.coverage" | sort LastWriteTime | select -last 1
I am using .Net Core Test--collect "Code coverage"to generate a coverage file, I need to convert this for sonarqube, the issue is I do not nave the name of the file thats generated as its placed in a folder with a guid name and the file name itself is a GUID all under theTestResultsfolderThe following script works to convert.coveragefiles intocoveragexml, but its for the whole working directoryGet-ChildItem -Recurse -Filter "*.coverage" | % { $outfile = "$([System.IO.Path]::GetFileNameWithoutExtension($_.FullName)).coveragexml" $output = [System.IO.Path]::Combine([System.IO.Path]::GetDirectoryName($_.FullName), $outfile) "Analyse '$($_.Name)' with output '$outfile'..." . "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\Team Tools\Dynamic Code Coverage Tools\codecoverage.exe" analyze /output:$output $_.FullName }But this converts the whole directory and after several days there are many builds, all I want to do it convert the.coveragefile generated by the current build, so I need to be able to isolate the.coveragefiles generated by the current build.
Convert the last generated .Coverage into coveragexml for SonarQubee in TFS 2017
At the same level as your compose file, create aDockerfileNote1: For example simplicity, I'm building against thelatesttag by default which is a bad practice for production. You should pick theversion that suits your needs(e.g.lts,9.2.4-developer....)Note2: For sonarqube versions prior to 8, the official image was based on an ubuntu image. Since version 8, the base image has been switch to alpine. I kept the previous exampleDockerfilebelowDockerfilefor sonar >= 8FROM sonarqube USER root RUN apk --no-cache add nodejs USER sonarqubeDockerfilefor sonar < 8 (for memory)FROM sonarqube USER root RUN apt-get update \ && apt-get install -y --no-install-recommends nodejs \ && apt-get clean USER sonarqubeModify your compose file to build and use this new image (note that the image namemustchange).sonarqube: image: my_local_sonarqube build: . ports: - "9000:9000" networks: - sonarnet environment: - sonar.jdbc.url=jdbc:postgresql://db:5432/sonar volumes: - sonarqube_conf:/opt/sonarqube/conf - sonarqube_data:/opt/sonarqube/data - sonarqube_extensions:/opt/sonarqube/extensionsLaunch your app. The image will be built automatically since it does not exists. If you need to rebuild the image later (e.g. after a change to theDockerfile), you need to either do it manually withdocker-compose buildor to use the--buildoption todocker-compose up.
I've installed a local SonarQube server in Docker on my machine, usingthis docker-compose.ymlbased onthis recipe. It spins up a Postgres database backend as well as SonarQube itself.When I run analysis of a Java project through Maven, it analyzes everything except my project's JS and CSS. I get these warnings:CSS files were not analyzed. Error when running: 'node -v'. Is Node.js available during analysis? Some JavaScript rules were not executed. Error when running: 'node -v'. Is Node.js available during analysis?SonarQube'sdocumentationexplains: "In order to analyze CSS code, you need to have Node.js >= 8 installed on the machine running the scan. Set propertysonar.nodejs.executableto an absolute path to Node.js executable, if standard node is not available."My question for you Docker-Compose experts is:How can I incorporate Node.js into the docker-compose configuration?(So I can get the benefits of these analyses without having to install and configure Node.js on the host machine outside of Docker...)
How to add node.js to this docker-compose file that spins up SonarQube?
Have you considered using a Struct to contain your different Params and then passing this structure to your constructorpublic struct CustomerParams { A a; B b; ... } public CustomerCommandService(CustomerParams cp) { }
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed4 years ago.Improve this questionI used 9 parameters in the constructor in a command service class, but sonarqube shows an error for too many parameters. Can anyone suggest a solution or design pattern solve this issue?public CustomerCommandService(A a, B b, C c, D d, E e, F f, G g, H h, I i){ //some code here }
How to reduce too many parameters from constructor [closed]
Injava propertiesfiles\characters need to be escaped with\\, e.g.:sonar.projectBaseDir=C:\\Django\\webapplication sonar.sources=.Note:/does not need to be escaped:sonar.projectBaseDir=C:/Django/webapplication sonar.sources=.
I've installed both sonarqube server as well as scanner and changed the properties file also. But still it's giving the below issue.ERROR: Error during SonarQube Scanner execution java.lang.IllegalStateException: Project home must be an existing directory: C:\Django\webapplication\webapplication\DjangowebapplicationI've my project in the C:\Django\webapplication directory.Below is my configuration file for sonar-project.properties filesonar.projectKey=devsonarqube sonar.projectName=webapplication sonar.projectVersion=1.0 sonar.projectBaseDir=C:\Django\webapplication sonar.sources=C:\Django\webapplication
I'm not able to run SonarQube on my project
Config installation fromMaveninGlobal Tool ConfigurationinSonarQube Scanner installationsin Jenkins.Example how to use, whereSonarQubeServeris name ofSonarQube serversconfiguration in JenkinsConfigure System.SonarQubeScannername ofSonarQube Scanner installations:withSonarQubeEnv('SonarQubeServer') { def sonarRunner = tool name: 'SonarQubeScanner', type: 'hudson.plugins.sonar.SonarRunnerInstallation' sh """ ${sonarRunner}/bin/sonar-scanner \ -Dsonar.projectKey=your_project_key \ -Dsonar.sources=. """ }
I'm trying to set up Sonarqube to run with Jenkins. I have both Jenkins and Sonarqube installed on an Ubuntu virtual machine that's running on a Windows 10 Hyper-V host. I downloaded Sonarqube to/opt/sonarqubeand then followed the installation instructions at docs.sonarqube.org. I am able to get to Sonarqube at myserver:9000 from my host machine and localhost:9000 from my guest machine, so Sonarqube is installed correctly and running as far as I can tell.I installed the Sonarqube Scanner plugin in Jenkins, but I'm having trouble with the configuration of SONAR_RUNNER_HOME in the Global Tool Configuration. I've tried setting it to both/opt/sonarqubeand/opt/sonarqube/bin/linux-x86-64, but in both cases building my Jenkins projects results in the errorFATAL: SonarQube Scanner executable was not found for LocalWhat do I set SONAR_RUNNER_HOME to in Jenkins Global Tool Configuration?
What do I set SONAR_RUNNER_HOME to in the Jenkins Global Tool Configuration for Sonarqube?
I just looked up the error description in sonar, and below is the description of error as per sonar.Controlling permissions is security-sensitive. It has led in the past to the following vulnerabilities:CVE-2018-12999CVE-2018-10285CVE-2017-7455Attackers can only damage what they have access to. Thus limiting their access is a good way to prevent them from wreaking havoc, but it has to be done properly.This rule flags code that controls the access to resources and actions. The goal is to guide security code reviews.Below is the code which is causing sonar issue.authorizeRequests() // Sonar complain this line here .antMatchers("/v1/").permitAll() .antMatchers("/**").authenticated()As I mentioned in comments of your question, don't blindly authorize the requests, access should be restrictive something like belowhttp.authorizeRequests() .antMatchers("/", "/home").access("hasRole('USER')") .antMatchers("/admin/**").hasRole("ADMIN") .and() // some more method callsIf this is your test/non-production code just add //NOSONAR at line it's complaining issue, sonar will bypass this but **Don't use //NOSONAR in the production environment.
I have a spring boot application that I am getting the following Sonar Critical defect on my configuration function at the line calling authorizeRequests(). How should I fix it? Thanks.Make sure that Permissions are controlled safely here. Controlling permissions is security-sensitive. It has led in the past to the following vulnerabilities: CVE-2018-12999 CVE-2018-10285 CVE-2017-7455My Configuration class:@Configuration @EnableWebSecurity public class MyConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() // Sonar complain this line here .antMatchers("/v1/").permitAll() .antMatchers("/**").authenticated() .and().httpBasic() .and().cors(); } }
Getting Sonar Critical defect on HTTP Security Configuration authorizeRequests()
The issue message “The main branch has no lines of code.” caused by C#/.net core require adedicated scanner. See this doc which announced by SonarCloud:SonarScanner for MSBuild.The SonarScanner for MSBuild is the recommended way to launch a SonarQube or SonarCloud analysis for projects/solutions using MSBuild or dotnet command as build tool.Since the extension has embeds the SonarScanner for MSBuild, just ensure the way of analysis should be chosen as the shown below.And also, since I could not get clearly know what's your csproj and sln files look like. I share my completed code in Github, you can refer to it:Sonar-Sample-Test.
The scan seems to run fine but in Sonarcloud we can browse the code files under the Code tab but there are no scan results. In another project containing both c# and typescript code, the typescript (and css etc) is analyzed but not the c# code.We are building **/*.sln and not *.csproj and are using the "normal" build steps.
Sonarcloud analysis of Dotnet core project with Azure DevOps says "The main branch has no lines of code."
It's becausegetClassLoader().getResourceAsStream("hello.txt")can returnnulland you're using it just after to create theBufferedReader, without checking for null value.
Please see the code snippettry (InputStream inputStream = this.getClass().getClassLoader()                 .getResourceAsStream("hello.txt"); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {ButsonarQubecomplaints below error in the above lineCorrectness - Nullcheck of value previously dereferenced(line starting with BufferedReader ) .Please help to resolve this issue
Try with multiple resource causes a sonar qube issue
However your field is declared asfinal, map itself is not immutable and you can stillput()some items to it (unless you are using someCollections.unmodifiableMap()- but anyway you don't know this by interface) and that's why Sonar is complainingTry to wrap theMapin some immutable class implementation and change the type of the field to this class. This has this additional advantage, that if in the future you will decide that you need to add some additional meta-data about file (like creation time) instead of sculpting in theMapstructure you can easily add a field to your own mapper class
I have this assignment to a static variable that reads data off a file:public static final Map<String, Integer> MY_DATA_RESOURCE; static { MY_DATA_RESOURCE = parseAndTransformFile(); }I want this variable to be publicly accessible to all classes and I want to initialize it with this method call. Doing this triggers a Sonar complaint "Mutable fields should not be "public static" though.I have that parseAndTransform method which I do not want to call directly multiple times and trigger a read each time and I also want to avoid adding a getter method which is basically adding a third layer to data access.Do I have any other options here?
Sonar complaining about static assignment
There are two types of code there are statements and there are expressions. In general, statements do not return anything but expressions do.Statements are things such asif,for,whileetc that do not return anything when they are finishedExpressions would be things like3,True,1 + 7,"a" * 3because they return values when they are executedIn python it is completely valid to have a line of code which is simply something like1 + 2this would execute, and return 3. This would be a problem for python because then there would be a 3 left on the stack. So an expression statement is basically just a wrapper for an expression which allows you to write expressions as a line of code on its own. All this means is that unlike a plain expression an expression statement pops its return value off the stack when it is finishedHope this makes sense, if not just leave me a comment
I am really struggling to understand how theEXPRESSION_STMTis seen in Python (see here to go to Python's grammar and to the correct linehttps://github.com/python/cpython/blob/v3.6.4/Grammar/Grammar#L41).What does it represent in Python ? If you have an example that would really help me :)PS: I've been told that an analyzer using this grammar would recognize the print function through theEXPRESSION_STMTbut I don't understand why
How does EXPRESSION_STMT work in Python grammar?
What you've hit ishttps://rules.sonarsource.com/java/tag/convention/RSPEC-120.This rule states that the name of the package should conform to a regular expression, which does not allow capital letters.To fix the SQ warning, you should correct your package name tocom.sample.loading.routebuilderorcom.sample.loading.route_builder.Note that the current default expression now allows underscores. Earlier it had not, which has been discussed herePackage names should comply with a naming convention (squid:S00120) and underscore.
when I run my jar in sonarqube for code coverage I m getting as rename this package name to match the regular expression the package name which is gave is routeBuilder.Can some one please let me know how to change this ?tried changing it to route builder everything in lower case.package com.sample.loading.routeBuilder
package naming issue in sonarqube
If anyone else is having this issue, I found the solution after some research.Solution: To be able to select 'SonarQube/quality gate' on the branch policy, you need to run at least once the pipeline that checks your code through a PR.In other words, add the check pipeline as part of the build validation to your PR policy, create a random PR and let it run. After that you will be able to select it in status check.Credits to Mickaël Caro on this thread:https://community.sonarsource.com/t/azure-devops-pull-request-quality-gate-status-check/33957/14
According to the tutorial written on the sonarcloud blog (https://blog.sonarsource.com/integrate-sonarcloud-with-vsts-to-boost-code-quality) and the Azure DevOps lab (https://www.azuredevopslabs.com/labs/vstsextend/sonarcloud/) I should be able to use the outcome of the analysis as a qualitygate for my pullrequest. Unfortunatly this option does not appear when adding a new status policy.The code has been analysed in the build and in the buildsummary you can see the outcome from sonarcloud.The last thing I need to do is add it as an approval pull-request requirement.
Unable to select "SonarCloud/Quality Gate" in "Require approval from additional services" in branch policies
I think you canot disable existing rule from default java plugin within your custom plugin. You could disable the rule in your profile and replace the default rule with custom one. (Actually there may be way with creating custom issue filter in your plugin )The rule is implemented like this.@Rule(key = "S1948") public class SerializableFieldInSerializableClassCheck extends IssuableSubscriptionVisitorpublic List<Tree.Kind> nodesToVisit() { return ImmutableList.of(Tree.Kind.CLASS); } public void visitNode(Tree tree) { if(!hasSemantic()) { return; } ... rule logic }just copy (and change the rule key and etc.) the existing rule into your custom plugin and add a check for class supertypeif(!classTree.symbol().type().isSubtypeOf("your.supertype.C")) || !hasSemantic()) { return; }
Please help me to solve these problems. SimplyI want to apply an existing sonarqube rule for only certain type of classes. As far as I know, we can use class tree to get the classes and identify the target class. The thing I want t know ishow can I enable or disable existing sonar rule within a custom rule?.The next question is toidentify the base class which is child class is extended. As an example class A extend class B, B extend class C and now I want to identify all the classes that is extended from the class C(The base class).Even a small guide, link, tip will be really appreciate.
How to apply an existing sonarQube rule for only given class type
I'm not so sure what you may want to match, but maybethis regexmight help you to do so or design your desired expression:^(logging:|\s+file:)(.+)This expression has a left boundary on start^.Your two words connected with an OR (|)Then, matches everything after that using.+You can also add additional boundaries to it, however if you could add some real samples to your question, it would be easier to answer.
I have a yaml which looks like this..! Sonar by default providing sonar-yaml-plugin with some templates which accepts regex as input to verify particular key is present or not in.ymlfile.I want regex to match entire keylogging:fileserver: port: 8989 logging: file: ./sample1.txt path: ./logI have tried using(logging)(?s:.*?)(file)but its not validating when I use it in sonar-plugin.
How to write regex to match a key in yaml file?
Your code is valid c# code, but sonar is not about that the compiler is. Sonar validates if you code does not have confusing constructions and this one is confusing. You do not want to iterate the collection you want the first item only. So your code should express your intention of it. So you should dovar OlifeExt = acordPolicy.OLifEExtension.FirstOrDefault(); if(OlifeExt != null) // ...
i am analyzing my code using sonarqube and am running into a bug for the following methodpublic static AllocationRuleList AsAllocationRuleList(this SIGACORD.Policy acordPolicy) { foreach (var OlifeExt in acordPolicy.OLifEExtension) { var elements = new List<XmlElement>(); foreach (var ele in OlifeExt.Any) { if (ele.Name == "AllocationRestrictions") { var allocationRestrictionElement = acordPolicy.OLifEExtension[0]["AllocationRestrictions"]; return allocationRestrictionElement.AsAllocationRuleList(); } } break; } return null; }sonarqube is saying mybreakshould be removed or made conditional. but, isn't it logically correct?
break statement issue - sonarqube
Thanks to the answers here, I could address my issue this way:BoundedInputStream boundedInputStream = new BoundedInputStream(zipInputStream, MAX_LINE_SIZE_BYTES); boundedInputStream.setPropagateClose(false); try(BufferedReader reader = new BufferedReader(new InputStreamReader(boundedInputStream))) { ...WithboundedInputStream.setPropagateClose(false);I can close theBufferedReaderwithout closing the zipInputStream.
I have the following code to open a zip file that contains several files, and extracts information from each file:public static void unzipFile(InputStream zippedFile) throws IOException { try (ZipInputStream zipInputStream = new ZipInputStream(zippedFile)) { for (ZipEntry zipEntry = zipInputStream.getNextEntry(); zipEntry != null; zipEntry = zipInputStream.getNextEntry()) { BufferedReader reader = new BufferedReader(new InputStreamReader(new BoundedInputStream(zipInputStream, 1024))); //Extract info procedure... } } }In summary, I pick each file from the zip, and open it with aBufferedReaderto read the information from it. I'm also usingBoundedInputStream(org.apache.commons.io.input.BoundedInputStream) to limit buffer size and avoid unwanted huge lines on the files.It works as expected, however I'm getting this warning on Sonar:Use try-with-resources or close this "BufferedReader" in a "finally" clause.I just can't close (or usetry-with-resources, like I did on the beginning of the method) the BufferedReaders I create - if I call the close method, theZipInputStreamwill close. And theZipInputStreamis already undertry-with-resources...This sonar notification is marked as critical, but I believe it is a false positive. I wonder if you could clarify to me - am I correct, or should I handle this in a different way? I don't want to leave resource leaks in the code, since this method will be called several times and a leak could cause a serious damage.
InputStream closes and sonar issues
You can create a shell/batch script according to your OS and while running sonar-scanner command just pass the arguments as shown below:-sonar-scanner -Dsonar.projectName=Project-Name -Dsonar.projectKey=Project-key -Dsonar.projectVersion=PV -Dsonar.projectDescription=PD -Dsonar.projectBaseDir=PBD -Dsonar.sources=sourcesFor more details please clicksonarlink
In Jenkins Freestyle JOB we have execute SonarQube Scanner section, In that we have option to include the sonar-project analysis properties, Similarly is there any way available to define/declare the sonar-project.properties in scripted pipeline itself? As I want to maintain the below properties values in my CI-System itself.sonar.projectName= sonar.projectKey= sonar.projectVersion= sonar.projectDescription= sonar.projectBaseDir= sonar.sources=
Sonar Scanner option to include the project properties values in scripted pipeline itself
Actually, for SonarQube 7.6, this is the status:All PR follow same rules of Short-Lived Branch and there is currently no possibility to set up an ad-hoc Quality Gate (or at least the same as the project), but this is planned for Q12019. More detailed, PRs and SLBs are recognized as 2 different things, but their presentation within SonarQube is the same.There is no way to identify PRs as Long-Lived branches (even with * in the long lived branches pattern regex).The only way to go for the quality gate would be to avoid the PR and launch the merge on the mainline so as to check if the quality gate passes.Here there is a reply from SonarQube community managerhttps://community.sonarsource.com/t/pull-request-analysis-and-quality-gate/6306/2
I have installed SonarQube 7.6 Developer Edition, and starting using it on my development environment pipeline. My coding approch isTrunk Based Development. We have only one mainline (master or trunk or develop as you prefer to define, but only one mainline)Actually all changes on code pass through a Pull Request, that as I have understood, into SonarQube is recognized as aShort Lived Branchand only thishard coded rulesare appliedError conditions:new open bugs > 0new open vulnerabilities > 0new open code smells > 0That is a subset of my Quality Gates conditions. It means that PullRequest could pass quality gate (becouse is recognised like Short-Lived Branch) and when it is merged into mainline (master/trunk) is applied my Quality Gates rules and could fail on merge.How could I know if it break quality gate before PR approvement, or more easy, how to identify a Pull Request as a Long Lived Branch?I have tried to define * as long lived branches pattern, but it does not work. attached a screenshot.
Pull Request analysis and Quality Gate on SonarQube
Upgrade to a newer version of SonarQube and use theSonarQube Community Branch Plugin. This plugin aims to support the same metric gathering and reporting across short and long lived branches as SonarQube developer edition, but without the limitations on cost or lines of code.Full Disclosure: I am the author of this plugin
I'm using the free sonar plugin:https://github.com/msanez/sonar-branch-communityI'm using Sonar 7.0. I can get the coverage in my master branch. Not in the short-living-branches (which is expected. It's only available since sonar 7.4 and probably the free plugin needs an update for it). But I can also not get the coverage in my long-living branches while they contains the same configuration as the master branch (which shows coverage). What am I doing wrong?
SonarQube branch plugin: no coverage in long living branch
You can use// NOSONARon the reported line (and probably explain why you ignored this issue).That's not the best solution but it works (at least, when used in Eclipse).You can also use@SuppressWarningswith the issue type (eg: likesquid:02020).
Question: why does sonar give me warning ("Change this issue so that it does not always evaluate to "false."). I've been able to prove thatif (info == null)evaluates totruewhen therequestEntitydoesn't contain a payload that's found in the db. So how can I get rid of this false positive? Does it have something to do with the@Nullable,@Checkfornull, or@Nonnullannotations? I know the postForObject method uses [email protected] info = restTemplate.postForObject(connectionString, requestEntity, Info.class); if (info == null) { throw new ApplicationException(Constants.NO_RESULT_ERROR_CODE); }Here is thepostForObjectmethod:@Override @Nullable public <T> T postForObject(URI url, @Nullable Object request, Class<T> responseType) throws RestClientException { RequestCallback requestCallback = httpEntityCallback(request, responseType); HttpMessageConverterExtractor<T> responseExtractor = new HttpMessageConverterExtractor<>(responseType, getMessageConverters()); return execute(url, HttpMethod.POST, requestCallback, responseExtractor); }
False-positive Sonar issue
Issue was with network side. Below command resolved the issue.sudo firewall-cmd --zone=public --add-port=30056/tcp --permanent
I have setup my sonarqube server in centos 7. I am using sonarqube 7.4. I have installed httpd and trying to access sonarqube dashboard. This will load for ever as I attached in image.Loading....I tried deleting data/es5 but no use. My sonar.properties file is as below.sonar.jdbc.username=sonar sonar.jdbc.password=mypassword sonar.jdbc.url=jdbc:postgresql://localhost/sonar sonar.path.data=/opt/sonarqube/data sonar.path.temp=/opt/sonarqube/temp sonar.web.port=30056 sonar.web.context=/sonarqubeNo errors in web.log. Please suggest me what wrong am I doing why sonarqube is not loading.
Sonarqube Loading for ever
I guess you're using a Java runtime < 1.8 for Eclipse ?Sonarlint requires a Java runtime >= 1.8.x
I installed SonarLint using thisapproachon my ECLIPSE MARS 2 - 4.5.0I couldn't do it with MarketPlace because of this error:Can not read the repository at https://eclipse-uc.sonarlint.org/compositeContent.xml. Received fatal alert: protocol_versionThe installation was successful, I had no erreor but I can't find SonarLint's view in the window's settings (Window>Setting).This is a screenshot of the installed plugins:The same result in marcketPlace :In Settings :Do you have any idea how to solve this problem ?
How to show SonarLint in Eclipse?
You may specify locale as in the following example.public static String getEndDate() { Calendar date = Calendar.getInstance(); date.setTime(new Date()); Format f = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH); // Locale date.add(Calendar.YEAR,1); return f.format(date.getTime()); }It is noteworthy that if you omit the locale, it will useLocale.getDefault()which is based on the host JVM. It could be a desirable feature.
Below is my method to set the date in yyyy-MM-dd format code is working as expected but I am getting sonar error - When instantiating a SimpleDateFormat object, specify a Locale. Any Suggestion experts how to resolve this issue ?public String getEndDate() throws ParseException { Calendar date = Calendar.getInstance(); date.setTime(new Date()); Format f = new SimpleDateFormat("yyyy-MM-dd"); date.add(Calendar.YEAR,1); return f.format(date.getTime()); }
Sonar - When instantiating a SimpleDateFormat object, specify a Locale
You execute goals in a wrong order:mvn sonar:sonar pmd:pmdSonarScanner is executed as first, and PMD as second. It means that PMD reports are unavailable when SonarScanner is doing its job. You have to change the order:mvn pmd:pmd sonar:sonar
I run a Maven command as "mvn sonar:sonar pmd:pmd", I can see the generated pmd.xml file under target folder in each module. But in command output I can see[INFO] Sensor Import of PMD issues [java][INFO] Importing D:\Temp\workshop\111\mat\mat-publish\mat-publish-core\target\pmd.xml[ERROR] Can't find PMD XML report: D:\Temp\workshop\111\mat\mat-publish\mat-publish-core\target\pmd.xml[INFO] Sensor Import of PMD issues [java] (done) | time=16msI can open the pmd.xml directly with the path, I am not sure why it report cannot find the file.
Can't find PMD XML report
Tips and clues:Ensure you have runSonarScanner.MsBuild beginbefore executingMsBuildRunMsBuildwith/v:diagnosticswitch to get detailed troubleshooting log. In the log lookupSonarQubeTargetsPathandSonarQubeTargetFilePathvalues.In case of this or another configuration difficulty see my tutorial on how to setup SonarQube in .NET ecosystem:https://blog.pragmasoft.pl/software/2018-10-10-sonarqube-2-setup-environment/
I am new to .Net and new to SonarScanner with MS Build. I am looking forward for your help on resolving the error I get when I build the project after sonarscanner-msbuild begin process .C:\Windows\system32\config\systemprofile\AppData\Local\Microsoft\MSBuild\14.0\Microsoft.Common.targets\ImportBefore\SonarQube.Integration.ImportBefore.targets(62,5): error : The build is configured to run SonarQube analysis but the SonarQube analysis targets could not be located. Project: XYZ.csproj [E:\jenkins\workspace\XYZ\XYZ.csproj]
The build is configured to run SonarQube analysis but the SonarQube analysis targets could not be located
I believe you are right, this is false-positive, issue should not be raised on this field same way as it is not raised on fields annotated with @Inject, @Resource or @EJB.I create an issue to fix this behaviorhttps://jira.sonarsource.com/browse/SONARJAVA-2895
I have a Servlet that have Spring auto-wiring capabilities using:WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext()) .getAutowireCapableBeanFactory().autowireBean(this);When I'm autowiring my beans SonarQube warns with `Servlets should not have mutable instance fields(squid:S2226)@Autowired MyBean myBean;Is it SonarQube bug which ignores Spring autowiring? Can I add different annotation to prevent this warning? am I missing something?By contract, a servlet container creates one instance of each servlet and then a dedicated thread is attached to each new incoming HTTP request to process the request. So all threads share the servlet instances and by extension their instance fields. To prevent any misunderstanding and unexpected behavior at runtime, all servlet fields should then be either static and/or final, or simply removed.EDITI found similarissuethat was fixed about Java's@Injectthat should not raise this warningIn practice when a field is annotated with @Inject it won't be mutated. So fields annotated with this annotation should not raise issue RSPEC-2226.EDIT 2Open a potential false positive issue inSonarSource Community
Servlets should not have mutable instance fields false positive with Spring autowire (squid:S2226)
+100Why not to check for theKindof the parent ? For the instance variables it should be aCLASS.Working Rule which bann's theBLABLAstring in the instance variables will look something like this.@Rule(key = "Banned Keyword Rule") public class BannedKeywordRule extends IssuableSubscriptionVisitor { // Define the word to ban private static final String BANNED_KEYWORD = "BLABLA"; @Override public List<Tree.Kind> nodesToVisit() { // visit only the variables return ImmutableList.of(Tree.Kind.VARIABLE); } @Override public void visitNode(Tree tree) { VariableTree variableTree = (VariableTree) tree; // check if parent is CLASS aka variable is instance if(variableTree.parent().is(Tree.Kind.CLASS) && variableTree.simpleName().name().contains(BANNED_KEYWORD)) { reportIssue(variableTree, "String " + BANNED_KEYWORD + " can not be used as a instance variable."); } } }
I am creating a custom SonarQube rule to warn about instance variables names that contain a particular string. It appears thatKind.VARIABLEdetects all variables, including local variables. Is there a way to detect and handle instance variables only?
Custom SonarQube Rule to identify instance variables
You can simply use thesonar.sources=.which will analyze all the files and directory in project root directory
I am having a Xcode Project for which I am running SonarQube Analyzer. It is getting analyzed successfully for main Project but my problem is Sonar Qube is unable to analyzed dependency projects like Pods or Frameworks. So is there is anyway to include Pods or Frameworks too.Here is the data of my sonar properties file for which I am using for running Sonar.sonar.projectKey=PROJECT_IDENTIFIERsonar.projectName=PROJECT_NAMEsonar.projectVersion=VERSION   sonar.sources=./PRODUCT_NAMEsonar.inclusions=**/*.m, **/*.h, **/*.swiftThanks in advance...
How to include dependency projects like Pods or Frameworks for SonarQube Analyzer in iOS
I resolved this problem. I did the following: Services > Jenkins > Right Click - Properties > Log On tab > Changing it from 'Local System Account' to 'This Account'.
I want to integrate SonarQube with a Jenkins project (ASP.NET project). I am trying to build a Jenkins job containing a build step for "SonarScanner for MSBuild " begin/end analysis. But I get the following error:"Running the Scanner for MSBuild under Local System or Network Service account is not supported. Please, use a local or domain user account instead."I even tried removing the "SonarScanner for MSBuild " begin/end analysis steps and manually executing Windows batch commands (which is working fine outside of Jenkins). But through Jenkins, I am getting the same error for the batch commands as well.Any help would be appreciated!
Jenkins: Running Scanner for MSBuild under Local System or Network Service account is not supported
In order to display your coverage in SonarQube, you should configure your sonarqube.properties file. In sonar properties, there is a parameter calledsonar.jacoco.reportPaths. You should add this parameter by giving the path of yourjacoco.execfile. For example:sonar.jacoco.reportPaths=yourpath/jacoco.exec
I'm using Jenkins+Jacoco+Sonarqube to test my code. In Jenkins, my mvn command is:clean org.jacoco:jacoco-maven-plugin:prepare-agent install -Dmaven.test.skip=false -Dmaven.test.failure.ignore=true sonar:sonarAnd I add action 'record jacoco coverage report' after build.But the result is, jenkins works as below:It shows coverage report and other information. But I cannot get coverage percentage in sonarQube therefore the quality gate in Sonarqube cannot be passed.I guess that sonar cannot find the coverage report because it's not exist in the 'code' tab in SonarQube.Please help me, I need the solution desperately.
Coverage report works in Jenkins using Jacoco but I cannot get coverage report in SonarQube
Thecontinuestatement as the last statement in a loop is redundant. You could do this:DirectoryInfo d = new DirectoryInfo(somePath); FileInfo[] Files = d.GetFiles(); foreach (FileInfo file in Files) { try { DoSomething(file.Name); } catch (Exception ex) { // do nothing } }This code works exactly the same as yours.
I have a method in which there is a for loop. The loop looks something similar as below.DirectoryInfo d = new DirectoryInfo(somePath); FileInfo[] Files = d.GetFiles(); foreach (FileInfo file in Files) { try { DoSomething(file.Name); } catch (Exception ex) { continue; } }What I'm doing is , getting all files from a directory, run the loop all the files, get the file Name and do something. Now what I want is even ifDoSomethingmethod raises an exception, I want the loop to continue and do not break in between. So for that I have writtencontinuein catch block.I'm running Sonarqube to check the code quality. It is showing the message "Remove this redundant jump." . I want to know how can I remove this Code smell and still achieve what I want.
Remove this redundant jump in Sonarqube
TheFile not foundwarnings are written by theAbstractAnalyzer.javaclass of the SonarGroovy plugin. As far as I understand, the plugin successfully found your jacoco.exec results (which contains those file paths likeutils/Rule.groovythat it fails to find).Probably you did not set yoursonar.sourcescorrectly, it should include a path to your groovy source code and also include thevarsfolder if you have Groovy source code there. By default,sonar.sourcesis set tosrconly and the code yourvarsfolder may therefore not be found. You could try adding the missing folders to the sources like this:sonar.sources=src,varsThe propertysonar.groovy.binariesis also needed for Groovy code coverage (it should point to the compiled groovy class files), if you don't set it explicitly thensonar.binarieswill be used to find the Groovy binaries. The following quote from theSonarGroovy pluginwebsite may also be helpful:The groovy plugin requires access to source binaries when analyzing JaCoCo reports. Consequently, propertysonar.groovy.binarieshas to be configured for the analysis (comma-separated paths to binary folders). For Maven and gradle projects, the property is automatically set.
I would like to solve the warnings in my Sonar log:INFO: Sensor Groovy JaCoCo [groovy] INFO: Checking binary directory: /home/project/target/classes INFO: Analysing /home/project/target/jacoco.exec INFO: Analysing /home/project/target/jacoco.exec WARN: File not found: utils/Rule.groovy WARN: File not found: com/acme/manager/Command.groovy WARN: File not found: com/acme/manager/util/YamlReader.groovy WARN: File not found: steps/DeployTest.groovy WARN: File not found: /deploy.groovyMy settings are:x.sonar.projectBaseDir=. x.sonar.sources=src,vars x.sonar.tests=test/groovy x.sonar.test.exclusions=test/groovy/com/acme/managerSome of the warnings are due to exclusions files (these files are evaluated in another Sonar module). But others should be no issue. Any idea whats going wrong here?In the Sonar I get coverage for files undersrc/com/acme/anythingbut not from thevarsfolder (defaultpackage). In the JaCoCo html report however, I have thedefaultpackage and coverage for thevarsfolder.
fix file not found in Sonar JaCoCo reporting
You can download jars from:https://sonarsource.bintray.com/Distribution/sonar-ldap-plugin/https://repo.maven.apache.org/maven2/org/sonarsource/ldap/sonar-ldap-plugin/You can also install the plugin by usingMarketplace:
Other plugins have download links on their web pages but this one for some reason is only available on dodgy websites with an out of date version.I could probably build it from source but ideally I'd like to have an "official" binary rather than rely on my patchy maven skills.Update: The server is not connected to the internet, that's why I can't use the Marketplace.
How can I get the LDAP SonarQube plugin jar file?
You can exclude an entire C# project by setting the MSBuild propertySonarQubeExcludetotruein the project file. See this post:How to exclude/ignore referenced project(s) analysis from SoanrQube
I am trying to exclude some folders from Sonar scan through VSTS build. We have used Sonar plugin for MSBuild.If I use the exclusion pattern as**/*.csthen it is excluding all the .cs files. My goal is to exclude whole folder from scan. I have tried the following patterns but none of them seems to work**/folder/* **/folder/*.cs **/folder/** **/folder/**/* **/folder/**/*.cs folder/*.cs folder/**/*.cs folder/**/* folder/** folder/*Please help in getting the correct pattern.I want to exclude This Issue project from the scan.
SonarQube - Excluding files and folders [Entire .Net Project (csproj)]
The problem could be caused by untrusted SSL certificate. SonarLint does not permit the configuration of certificates, but you can add certificate to JRE or JDK. Read more here:How to add certificates to SonarLint in Eclipse
The current configuration:latest IntelliJ Idea Community Edition (2018.1.4)latest SonarLint addon for Idea (3.4.2.2586)SonarQube v6.7 (build 33306)When I try to add the SonarQube server address (authentication with usr/psw) I got this message:Failed to connect to the server. Please check the configuration. Error: Fail to requesthttps://<sonarqube_server_url>/sonar/api/system/statusBut when I try to open this URL (https://<sonarqube_server_url>/sonar/api/system/status) from Chrome I got this:{ "id": "oTvPjWRbAMXWalmApGYG", "version": "6.7.0.33306", "status": "UP" }So it seems to be running well, and of course I can log in and use well the webUI.How should I connect to it from Idea?
With IntelliJ Idea and SonarLint I getting error while connecting to SonarQube server
PrerequisitesI have a SonarQube server setup in Azure on a Linux WebAppI have installed the following Azure DevOps [extension](https://marketplace.visualstudio.com/items?itemName=SonarSource.sonarqubeI have setup a SonarQube service connection ("SonarQube Service Connection") to my SonarQube server in Azure. You will find this option in Project Settings > Pipelines > Server ConnectionsPrepare analysis on SonarQube in Yaml:- task: SonarSource.sonarqube.15B84CA1-B62F-4A2A-A403-89B77A063157.SonarQubePrepare@4 displayName: 'Prepare analysis on SonarQube' inputs: SonarQube: 'SonarQube Service Connection' projectKey: ProjectKey projectName: ProjectNameRun Code Analysis in Yaml:- task: SonarSource.sonarqube.6D01813A-9589-4B15-8491-8164AEB38055.SonarQubeAnalyze@4 displayName: 'Run Code Analysis'Publish Quality Gate Result in Yaml:- task: SonarSource.sonarqube.291ed61f-1ee4-45d3-b1b0-bf822d9095ef.SonarQubePublish@4 displayName: 'Publish Quality Gate Result'
Phase LibraryBuildGated: Step input SonarQube references endpoint 17xxxxc3-4xx0-4xx4-9xx2-617fxxxxxxxx which could not be found. The service endpoint does not exist or has not been authorized for useThanks -Edited Question
Trying to add SonarQube - SonarAnalysis task in YAML build template for VSTS as a build task
Gb of disk sounds way too big for 3.5M lines of code. For comparison the internal PostgreSQL schema at SonarSource is 2.1Gb for 1M lines of code.I recommend to clean-up db in order to refresh statistics and reclaim dead storage. Command isVACUUM FULLon PostgreSQL. There are probably similar command on other databases. If it's not better then please provide the list of biggest tables.EDITThe unexpected size of tablece_scanner_contextis due tohttps://jira.sonarsource.com/browse/SONAR-10658. This bug is going to be fixed in 6.7.4 and 7.2.
I've found this post about the usual size of a Sonarqube Database:How big is a sonar database?In our case, we have 3,584,947 LOC to analyze. If every 1,000 LOC stores 350 Ko of data space it should use about 1.2Gb But we've found that our SonarQube database actually stores more than 20Gb...The official documentation (https://docs.sonarqube.org/display/SONAR/Requirements) says that for 30 millions LOC with 4 years of history, they use less than 20Gb...In our General Settings > Database Cleaner we have all default value except for "Delete all analyses after" which is set to 360 instead of 260What can create so much data in our case?We use sonarqube 6.7.1 versionEDITAs @simonbrandhof asked, here are our biggest tables| Table Name | # Records | Data (KB) | |`dbo.project_measures` | 12'334'168 | 6'038'384 | |`dbo.ce_scanner_context`| 116'401 | 12'258'560 | |`dbo.issues` | 2'175'244 | 2'168'496 |
Sonarqube - Very big database