Response
stringlengths
8
2k
Instruction
stringlengths
18
2k
Prompt
stringlengths
14
160
There could be many of reasons for this issue. One of the reason we face this issue is when we raise a PR in a new repository.Now, in a new repository, base/default branch would always be empty and hence there will be no sonar data for that. Now, to add the codebase the very first time, you would create a feature branch and raise a PR for that. Now, if you have enabled the sonar plugin for your repository, bitbucket will try to compare sonar reports of your feature as well as base branch. Now, since there is no sonar data for base branch, bitbucket will throw below error.Sonar data unvailableSolution:Disable the sonar plugin on your repository for the very first PR merge. Once PR is merged in base branch, enable the plugin back again and you will be back into business.
Below is the message shown when I create a pull request(which I configured the sonar for bitbucket plugin).Please advise. Thanks.Sonar data unavailableWas not able to fetch data for Sonar project "abc.com". Either your pull request has not been analyzed yet, a non-existing Sonar project is referenced or you use the new branching feature of SonarQube 6.7 but have not enabled this in the repository settings. You can configure the Sonar project in the repository settings.
Pull request analysis not working in Sonar Qube for bit bucket server(sonar for bitbucket plugin)
Looking at theOther Pluginssection of the documentation, looks like there is a plugin for this:https://github.com/mibexsoftware/sonar-bitbucket-pluginHowever, this plugin relies on a deprecated feature of SonarQube (the "preview/issues" mode) - which will be removed in future versions.Note that SonarSource is currently working on a built-in support of Bitbucket Cloud (pull request analysis included) for itscloud service called SonarCloud. This built-in support should be available by the end of Q2 2018.
Is there something similar tohttps://docs.sonarqube.org/display/PLUG/GitHub+Pluginbut for Bitbucket cloud?I would like to run it from Jenkins with gradle.
Sonarqube plugin for Bitbucket as for GitHub
The support for branches is part of the SonarQube Developer Edition, which is a commercial package. You will not be able to change the name of the default name if you haven't purchased a license for it.If you did purchase a license, then you can change the name of the default branch in the "Administration > Branches and Pull Requests" page. You can read more about support for branches on thedocumentation page.
I use sonar-runner (2.8) to launch analysis in Jenkins job. The Sonar Branch plugin is installed on SonarQube 6.7.1 server that I use.Regardless of what values I put in params:sonar.projectKeysonar.projectNamesonar.branch.name #from branch pluginsonar.branch.target #from branch pluginI cannot set up the Main branch name. It's always called the "master" which is the default name for Main branch. I also played with the regex responsible for detecting long-live branches.I can change the branch name of the Main branch by hand on the SonarQube server side (via UI). I'd like to set it up on the parameters side (before the analysis is launched) to avoid manual work.Is it possible at all?
Is it possible to set up the Main Branch name automatically?
The symbolic execution engine from the SonarJava analyzer (5.1.1) is raising an issue because it assumes that the only way to reach thecatchblock would be by at least havesearchRequestbeing non-null. This is a limitation of the engine, which is not covering these case for the moment. The following ticket tracks this limitation:SONARJAVA-2669Now, as you said it, nothing prevent you to call the method with the parameter beingnull. In such case, theNullPointerExceptionwill be thrown and, indeed, we will reach thecatch (Exception e)block withsearchRequestbeingnull.SonarJava is consequently raising aFalse Positive.Now, regarding your implementation choice, I believe that handling thenull-case like this (by relying on thrown exception) is not something that people usually expect. An explicitnull-check when entering the method are usually way clearer and should be preferred.Note that as a good practice, I think that it would be clearer to annotate thesearchRequestparameter of the method [email protected] some similarnullnessannotation (this one is fromJSR-305). This will help other developers (and the SonarJava engine) to understand in which state you can provide parameters, and make it crystal clear.
Sonar is raising "changes this condition so that it does not always evaluate to true" for below code. I have consulted multiple people they all agree it is a false positive are we missing something?public SearchResponse getSearchResponse(SearchRequest searchRequest) { try { searchRequest.validate(); } catch(VerifyException e) { ///some code to make errorResp return errorResp } catch(Exception e) { String key = searchRequest != null ? serchReqeust.getKey() : null; Logger.log("some text {}", key); //some code to make errorResp return errorResp; } }The error is raised in generic catch block atsearchRequest != null. However if searchRequest is null, first line in try block will throw NullPointerException and if I don't check for null in my catch block it will break again in my catch block. Making my method fail again which is what I don't want.Edit:As some people in comments asked for code to reproduce the error i have uploaded it to github athttps://github.com/shariqislam786/testthe issue is reproducible with sonar lint 3.4 in eclipse as well.
Sonar false positive, "change condition so that it does not always evaluate to true."
SonarQube Community Edition is licensed under the GNU Lesser GPL License v3, as you can read on theLicense page on sonarqube.org.If you want to know what you can legally do with this LGPL v3 license, you can chek the following page:https://tldrlegal.com/license/gnu-lesser-general-public-license-v3-(lgpl-3)
We want to build a commercial product using SonarSource Community Edition which we deployed on our own servers, I am not able to find relevant information regarding its licensing faqs, can we create the product using it and sell it?
Sonarsource Community Edition License
The patterns you cite aren'tinvalid; they're simply unrecognized. I.E. they're not expected in this context. What you want is a multi-module project structure. If you're using Maven (and presumably Gradle) this just works automatically. Outside of that, you'll need toset it up explicitly.
I'm trying to configure Sonarqube to run an analysis through TeamCity with multiple projects in a solution with a structure like this:Projectname.Core Projectname.Database Projectname.Services Projectname.Test.Common Projectname.Tests.Database Projectname.WebApi Projectname.WebUINow, as you can see, i'd effectively like the "sources location" to be something likeProjectname.*and the tests location to be something likeProjectname.Test*\bin\releaseand the binaries location to be something likeProjectname.*\binWhen I try to do this in the Sonarqube runner in TeamCity, it thinks*is an invalid character and fails the build.The information i've found online seems to suggest that*and**are accepted characters as perThis documentHas anyone had experience with including multiple projects to be analyzed, and if so, how do you include them all with some kind of syntax?
Sonarqube path locations and wildcards
Nope it's not possible. Which column do you need in this page ?
I am getting started with SonarQube and using 6.7.1 version. I need to modify SonarQube page, adding one more column to background task. Is it possible?
Modify SonarQube UI Page
You're looking for badges, which allow you to embed a little image in a page with a metric name andcurrentmetric value. This is a native feature on SonarCloud.io, and coming soon for SonarQube. In the meantime, there's acommunity pluginyou can use.
I would like to integrate my sonarqube instance with a confluence space, so all my team could have access to the project metrics. Does anyone know any plugin that does this or how to do it without a plugin? Thanks
Sonarqube Plugin for Confluence
TheS1166 Exception handlers should preserve the original exceptionsis disabled in quality profiles provided by SonarSource.Some time ago (I don't remember in which version exactly) SonarSource developers made those quality profiles as read-only. It probably means that you:modifiedSonar wayprofile → S1166 has been enabledanalyzed code → issues have been createdupgrade SonarQube → quality profiles have been restored and marked as read-onlyanalyzed code → issues have been closed, because the rule is disabledYou have to create your custom quality profile and enable that rule.
In SonarQube 6.1 I got 125 such issues on one project of mine. However in versions 7.0 and 6.7.1 I suddenly got exactly 0 on the same code with no changes.What happened?Here's a typical example of code that should get that issue, but didn't get it:try { ... } catch (Exception e) { log.error("Load balance test faild with exception: " + e.getMessage()); }
SonarQube no longer detects S1166 (Exception handlers should preserve the original exceptions)
Your resource management seems ok to me - maybe Sonarqube complains because it can't follow your logic?Anyhow - you'll probably be better off if you use a try-with-resources and forget about the close() nonsense :)protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try ( BufferedReader reader = new BufferedReader(new FileReader("foo.in")); GZIPOutputStream gzos = new GZIPOutputStream(response.getOutputStream()) ) { String line; while ((line = reader.readLine()) != null) { gzos.write(line.getBytes("UTF-8")); } gzos.flush(); } }Also, you usually don't want to flat-out ignore exceptions :) I'm talking about the two emptycatcharoundgzos.write- the ones inside thefinallyare actually ok (or at least, I would have written them too)
I have two resources which are properly closed in finally clause with separate try catch blocks. But an issue is raised by sonar scanner to close the second stream even if it is closed.Below is the sample snippet.protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { BufferedReader reader = new BufferedReader(new FileReader("foo.in")); GZIPOutputStream gzos = null; try { gzos = new GZIPOutputStream(response.getOutputStream()); String line = null; while ((line = reader.readLine()) != null) { gzos.write(line.getBytes("UTF-8")); } gzos.flush(); } catch (Exception exp) { } finally { try { if(reader != null) { reader.close(); } } catch (Exception exp) {} try { if(gzos != null) { gzos.close(); } } catch (Exception exp){} } } catch (Exception e){} }Is there any proper explanation for this rule?
Resources should be closed issue is raised by sonar java even if the resource is closed
Thanks to @agabrys for the tip.Running this Maven command:mvn clean verify help:evaluate -Dexpression="sonar.password" -Dsonar.login=438fd33be6d6e5c9146c674717fea4675f0ebReturned:adminIn order to accept the token, then password must be empty. It must be the Maven sonar plugin that is setting this default password!! Setting the default password to empty via this:mvn clean verify sonar:sonar -Dsonar.password= -Dsonar.login=438fd33be6d6e5c9146c674717fea4675f0ebWorked.
Just stood up a brand new SonarQube6.7.1server and configured it to authenticate users via the LDAP plugin (2.2 build 608). So far so good.However, when users trying to run a command line scan using maven with a token:mvn sonar:sonar -Dsonar.login=438fd33be6d6e5c9146c674717fea4675f0eb...they get the following error:Not authorized. Please check the properties sonar.login and sonar.password.The Sonar logs are showing:2018.01.19 18:20:14 DEBUG web[AWELLmgpg7dbJTF2AALW][o.s.p.l.LdapUsersProvider] User 438fd33be6d6e5c9146c674717fea4675f0eb not found in <default> 2018.01.19 18:20:14 DEBUG web[AWELLmgpg7dbJTF2AALW][auth.event] login failure [cause|No user details][method|BASIC][provider|REALM|LDAP]This makes it look like Sonar's LDAP plugin is attempting to look up a user on LDAP whose name would be the access token. Clearly this isn't going to work!We are using sonar maven plugin version3.4.0.905.Edit: The same token works from IntelliJ SonarLint. Which seems to point to the Maven plugin being at fault here.
SonarQube token access when LDAP is enabled
I'm the author of the plug-in. We've just released a bug fix version 1.7.1 which only sets the sonar.login parameter in the MSBuild end task, thus resolving this issue.Best regards, Michael
We updated our SonarQube for Bamboo plugin to the latest version, 1.17.0, and now our SQ integration is broken. No reports are sent to our Sonar Qube server. I get these errors in the Bamboo build output:This setting is not valid in the "end" phase in this version of the C# plugin: sonar.host.url Failing task since return code of [C:\sonar\bin\MSBuild.SonarQube.Runner.exe end /d:sonar.host.url=http://[ip-address]:9000/sonar /d:sonar.login=*** /d:sonar.password=*** was 1 while expected 0And:SONAR4BAMBOO: was not able to find a SonarQube result URLIt seems like somewhere in the process it's passing sonar.host.url as an argument to executing the runner, but in the latest SonarQube for Bamboo plugin this is, for some reason, not allowed anymore? Has anyone updated SonarQube for Bamboo and come up against similar problems?
sonar.host.url not valid in end phase of C# plugin in SonarQube for Bamboo 1.17
You can browse the code of your project by clicking on the "code" tab. See this example on SonarCloud :https://sonarcloud.io/code?id=com.cognifide.aemrules%3Aaemrules
I have a multi-module maven project with a structure likeparent - child1 - child2 - child3In the SonarQube dashboard I can only see the parent project. If I search for "child1" in the "Search for projects, sub-projects and files..." box I am able to find and view each child module.Is there any possibility to have these sub-projects displayed at the dashboard or at least be able to navigate to them without doing a search?
How do I configure SonarQube to display all modules of a multi-module maven project?
It's possible but not that easy but it's doable.You can find some details here :How to migrate SonarQube 6.7 from MySQL to postgresql
I have a question about the migration of versions in Sonar, to see if you can solve it.I have Sonar 5.2 with MySQL and I want to update to 6.1 and move to PostgreSQL. From what I've been reading, I think the best way is to perform the required update, create a Squema in the new Sonar and then import the database I had in the old Sonar ...is this correct?Greetings, Thank you very much
How to migrate from version in Sonar from MySQL to PostgreSQL
You can use theproject_tags api, to set project tags. An example:curl -XPOST http://your.sonarqube/api/project_tags/set?project=yourproject&tags=yourmodule_yourbranch
I am running the sonar-plugin in my Jenkinsfile. I'd like to pass some tags for the builds I am running. My projects consists of multiple modules (article, authentication) and I'd like to add<moduleName>_<branchName>as a SonarQube tag.My maven command line I run in the Jenkinsfile looks like this:sh "mvn -B -Dsonar.projectName=MyProject_${module}_${env.BRANCH_NAME} -Dsonar.projectKey=${Config.groupId}:${module}_${env.BRANCH_NAME} -Dsonar.host.url=${Config.sonarUrl}"Is there any way to pass tags to SonarQube or do I have to apply them in SonarQube manually?
Is there a way to pass tags to SonarQube via maven command line?
It's not possible to do a bulk change of more than 500 issues, but you can update more than 500 using web services :Get list of issues usingapi/issues/search?p=1&ps=500Do the bulk change usingapi/issues/bulk_change?issues=ISSUE1,ISSUE2,...on found issues.Repeat these 2 steps updating thepparameter of api/issues/search each time.
Some bulks needed have over 100K issues.Is there a way to bulk change more than the 500 issues in SonarQube 6.x?The UI certainly does not allow to customize this. Where can I find the parameter/code/table in the database needed to change the 500 value ?
How to bulk change more than 500 issues on SonarQube 6.x?
This question has already been answered in the SonarQube Google Group :https://groups.google.com/d/msg/sonarqube/JzgetifU9ik/VruCki39DAAJ. Answer is 5.6.x is no longer maintained starting 6.7 release date.
Since 6.7 LTS was released on Nov 8th 2017, when is the previous 5.6 LTS end-of-support date?(We have developed widgets for the old LTS and need to understand when can we stop supporting them in favor for new plugins)
SonarQube 5.6 LTS end-of-support date
As of Sonar 7.0 and Jacoco 6.5 it is now possible to use try with resources as a more elegant solution thanorg.apache.commons.io.IOUtils.closeQuietly(fileInputStream);
I have a null check on a FileInputStream object and SonarQube says that on the first line of this block:if (fileInputStream != null) { try { fileInputStream.close(); } catch (IOException ioe) {} }only (and I quote): "Covered by tests (3 of 4 conditions)"How in this world can there be 4 conditions? I can only see 2 conditions: either the object is null or not. Can anyone post those other 2 conditions? I use java 8. Is there a way to please Sonar? A workaround? Anything.Update: I removed the if statement and replaced the whole if block withorg.apache.commons.io.IOUtils.closeQuietly(fileInputStream);which checks for null and makes Sonar happy.
SonarQube says "Covered by tests (3 of 4 conditions)" on a null check
The Compute Engine needs to load all data included in the report sent by the scanner in memory to be able to process it.You can see in the log of the scanner the size of the report, to get a rough idea of how much data there is to process. It will of course be related to how many lines of source code is being analyzed.[INFO] Analysis report generated in 3282ms, dir size=53 MB [INFO] Analysis reports compressed in 5909ms, zip size=28 MB [INFO] Analysis report uploaded in 3252msThere is currently no way to have the scanner send fragments of the report. You can analyze for example different modules of the project separately, but this will result in different projects being created in SonarQube.Increasing the heap size is a good solution, and using 1GB seems perfectly reasonable.
I'm having a huge maven project on which the SonarQube analysis is been done, from maven everything is fine but the SonarQube background task fails because of OutOfMemoryError exception.I have increased the heap memory for compute engine and its working for now, but is there a way to handle this in SonarQube without increasing the memory, like split the background task in to smaller tasks and combine the results?
Better way to handle OutOfMemoryError: Java heap space in SonarQube Compute Engine
According to your kernel information (aarch64), you are trying to start SonarQube on a ARM64 architecture and the wrapper in linux directory is not compatible with this architecture (the wrapper binaries are for x86 or amd64 architecture).
I've install SonaQube on a ubuntu Xenial server with this tutorial:https://www.vultr.com/docs/how-to-install-sonarqube-on-ubuntu-16-04all installations (postgreSQL, java, sonarqube, apache2, etc.) work fine but I always get an syntax error when I try to start sonar with:/opt/sonarqube/bin/linux-x86-64/sonar.sh startI get:/opt/sonarqube/bin/linux-x86-64/./wrapper: 1: /opt/sonarqube/bin/linux-x86-64/./wrapper: Syntax error: "(" unexpectedAnd I get exactly the same error using :/opt/sonarqube/bin/linux-x86-32/sonar.sh startso it seems to be a different problem than that post :./sonar.sh start on ubuntu giving not starting sonar servermy uname -a :Linux scw-2a7881-sonarqube 4.4.95-mainline-rev1 #1 SMP Fri Oct 27 08:56:55 UTC 2017 aarch64 aarch64 aarch64 GNU/Linuxhas someone got the same problem ?thanks in advance
Sonarqube wrapper syntax error with 64 and 32 bits sh call
Starting SonarQube 5.6sonar.authenticator.createUseris indeed not working anymore (seehttps://jira.sonarsource.com/browse/SONAR-8208for details).Then you have 2 options :Upgrade to SonarQube 6.3 or later version, everything will work fine.Execute the following SQL request :update users set user_local=false where login = '<LOGIN_TO_LOG_WITH_AD>'
i am having some issue with sonarqube 5.6 LTS using LDAP authentication on a AD server.Before finally managing to configure SQ to work with AD for ldap authentication i had created an user with a login name equal to an AD account.Then i found out that i could set up in sonar.properties the property sonar.authenticator.createUser=true. So i clicked on the red cross (with a tooltip deactivate) on the user list to remove the the local user created by me so that the user could login via AD authentication.Unfortunately it seems that SQ does not perform at all any query for the deleted local user. What can i do? (renaming the user account on the AD side is not an option)thanks
Sonarqube deleted local user cannot login anymore with remote ldap authentication
The issue raised by SonarQube is a false positive in this example. Your best course of action is to mark it as such on SonarQube.If your DTO files follow a consistent naming pattern, then it could also be interesting to configure SonarQube to ignore this issue in those files by default.
I have this DTO class:class DTO{ private String a; public DTO(String a){ this.a = a; } }I am JSON serializing this class using Gson and sending it over to other application.I don't need getters for this class. For this class sonar is showing following issue:"Remove this unused "a" private field."Should I ignore this sonar issue or there is another ideal way to change my code to eliminate this sonar error?
Sonar showing issue for private fields of DTO class
This is a known issue:https://jira.sonarsource.com/browse/SONARGITUB-35with unfortunately no workaround.
We're getting an odd error on one of our new github projects when we attempt to run a sonar analysis. We get the following error message and it appears to be because org.kohsuke.github.GHCommitStatus["id"] gets a "Numeric value (4275691320) out of range of int" error.[ERROR] Failed to execute goal org.codehaus.mojo:sonar-maven-plugin:2.5:sonar (default-cli) on project audit-config: Unable to load component class org.sonar.batch.scan.ImmutableProjectReactorInterestingly enough, this is the only one of our projects having this issue. Any thoughts would be greatly appreciated!
sonar-maven-plugin getting "out of range of int" error
Unfortunately, those "Common" rules are available by default on all languages directly from SonarQube itself, and cannot currently (as of 6.6, at least) be removed.
I'm developing a new plugin for SonarQube supporting a new language, but when I included this plugin there were a couple of built-in rules such as:Branches should have sufficient coverage by testsFailed unit tests should be fixedLines should have sufficient coverage by testsSkipped unit tests should be either removed or fixed and etc.For my new language testing doesn't have any sense and I'd like to exclude them. Is there a way to do it?
How to exclude built-in rules in a custom plugin?
This seems to be a problem in how catch blocks are handled during data flow analysis in SonarJava. Catch block catching subtype of the exception declared in the throws declaration of called method is not being considered, hence the assignment to the variable is never seen by the engine.I created following ticket to fix this problemhttps://jira.sonarsource.com/browse/SONARJAVA-2483
Does anyone know why SonarQube detects a violation of the rule "Conditionally executed blocks should be reachable" (squid:S2583) in the following example? Is this a false positive?In this piece of Java code, a file is read and anEOFException(or multiple of them) can occur in the process of reading the input stream. Thus, the exception is caught and handled, and a flag is set to remember that it happened. However, Sonar does not consider the lineexHappened = true;in the first catch block and claims that variable is alwaysfalse:public static boolean doSomething() { boolean exHappened = false; try (DataInputStream s = new DataInputStream(new FileInputStream("test"))) { LOGGER.info("Doing something..."); } catch (EOFException eof) { // this Exception can definitely happen exHappened = true; } catch (IOException io) { LOGGER.error("sorry", io); } if (exHappened) { // Sonar thinks this condition is always false return false; } else { return true; } }To make it even more clear, add athrow new EOFException()into thetry { }, then the condition willalwaysbe true and Sonar still claims that it always false...(I'm using SonarQube 5.6.6 and SonarJava plugin 4.13.0.11627)
Sonar seems to ignore variables set in catch block
The release of 6.7 LTS is planned for this fall. But youcannotupgrade directly from 4.5.7 to 6.7; you must first go through the intervening (current) LTS: 5.6.6.For a summary of the differences between 4.5.7 and 5.6.6, seethis blog post. If you want more details, you should consult the release notes, as Simon noted in the comments.When you upgrade to 5.6.6 (why not go ahead & get that out of the way?), you'll find that your custom dashboards are still there, but have been set aside in favor of a hard-coded project homepage. When you get to 6.7, you'll find that custom dashboards have been eliminated entirely, and a new projects page has been provided, as well as a reworked Measures space and countless other improvements.Nov 2019 Update:The current LTS is now7.9. More information aboutthe SonarQube LTS model is available here.
We would like to upgrade our Sonar setup to 6.x but waiting for LTS release. Is there any update on when Sonarqube LTS (6.x) release is scheduled?Also, we would like to understand major differences between Sonarqube 4.5.7 & Sonarqube 6.x in terms of support for Java/maven/msbuild/fxcop versions and other major features that 4.x users should be aware of.
Sonar 6.x LTS release schedule
I think how to exclude with MSBuild depends on what you are trying to exclude. I was only able to exclude an entire project by using the property group in the csproj.<PropertyGroup> <!-- Exclude this project from analysis --> <SonarQubeExclude>true</SonarQubeExclude> </PropertyGroup>However I was able to successfully exclude files and groups of files with the sonar.exclusions settings through the SonarQube UI (project administration, analysis scope, files). The pattern that I could get to work was **/folder1/folder2/file where folder1 is the first folder inside your project root (not solution root). Adding what you are trying to exclude would help me be more specific on my answer.
Originally it seemed that after a SonarQube Scanner for MSBuild analysis the server-side configured sonar.exclusions settings where cleared.After some investigation it turned out that on page load of the Administration page an http 404.15 occured (in the SonarQube Web UI red alert is shown that a failed request occured which disappears quickly).In our case we could solve the problem with adapting the configuration of the used IIS reverse proxy, specifically the request filtering module (if installed) has to allow a query string a larger than default. In our case 4096 seems to work.
SonarQube settings appear to be empty on reload due to reverse proxy misconfiguration
There are a few rules implemented in SonarJava that check the proper use of SQL-related Java objects, specificallyS2695- "PreparedStatement" and "ResultSet" methods should be called with valid indiciesS2232- "ResultSet.isLast()" should not be usedS2077- SQL binding mechanisms should be usedBut there are no rules that check the correctness of SQL statements themselves, and I'm not aware of any other plugins that offer such rules for Java.If you really need this, then you'll have to go down the custom rule implementation route. There'sa tutorial to get you started, and if you have specific development questions you can ask them in theSonarQube Google Group, or here, obviously.UpdateThe Google Group has been replaced withhttps://community.sonarsource.com.
I have native queries in java files and i want to scan that queries for using sonarQube server.Is there any way to do that?
Scan Native query in JPA using SonarQube
Open the file conf/sonar.properties and edit the propertiessonar.jdbc.url,sonar.jdbc.usernameandsonar.jdbc.password.Example:sonar.jdbc.url=jdbc:sqlserver://windowsmachine;databaseName=sonar sonar.jdbc.username=yourLogin sonar.jdbc.password=yourPasswordReading thedocumentationcan also help.
I am trying to install a SonarQube server on my Linux machine. I want to use a SonarQube database on my windows machine - a Microsoft SQL server instance.How can I connect my SonarQube server to my SonarQube database?
How to install a SonarQube server with a remote database?
The list of users is by default not shown completely in newer versions of SonarQube. Start typing a user's name or email in thefilterinput box to find the users you are looking for.While a list of 40 users would be easy to display, some instances of SonarQube have thousands of users. The new behaviour of the user list improves the user experience on such systems.Side note: If an unexpected error occurred during startup you indeed might have toreindexthe database once. To do this stop SonarQube, make a backup of everything, remove thedata/esdirectory and start SonarQube again.
I have 40 users in my sonarqube instance. After updating to Sonarqube 6.5 in Administration/Security/Users there is only Administrator. Sonarqube connected to PostgreSQL database and tableuserscontains all 40 users. Also they can login. Creating missing users fails with message:An active user with login 'XXXX' already exists.I triedREINDEX DATABASE sonarqube;with no result.How can I solve this problem?
After update to 6.5 no users except Administrator in Administration/Security/Users
Python requests is really a good library. Files option in post is used to upload file and I don't thinkcom.eclipseoptions.viewserver:viewserver:feature_VS-313-add-an-instruction-event-and-viewis a file if so, you have to read the file in binary mode and then send it likefiles = {'key': open(filename, 'rb')}. so the code should be:import requests files = {'key': open(filename, 'rb')} headers = {'Authorization': 'Basic YWRtaW46YWRtaW4='} response=requests.post(url,files=files)check thisfor details on uploading files using requests library in python.If it is not a file you can send the payload directly as a dictionary like this:import requests headers = {'Authorization': 'Basic YWRtaW46YWRtaW4='} data = {'key': 'com.eclipseoptions.viewserver:viewserver:feature_VS-313-add-an-instruction-event-and-view'} response=requests.post(url,data=data,headers=headers)check thisfor details on sending payload.
I have a simple python 3 script that send a post request to delete a project in SonarQube. While I am keep getting in my python script, a simple curl commands works... any idea what is wrong with my python script?import requests headers = { 'Authorization': 'Basic YWRtaW46YWRtaW4=', } files = [ ('key', 'com.eclipseoptions.viewserver:viewserver:feature_VS-313-add-an-instruction-event-and-view'), ] r = requests.post('http://devsonar/api/projects/delete', headers=headers, files=files) print(r)The following curl command works fine:curl -X POST -H "Authorization: Basic YWRtaW46YWRtaW4=" -F "key=com.eclipseoptions.viewserver:viewserver:feature_VS-313-add-an-instruction-event-and-view" "http://devsonar/api/projects/delete"
Python Post - keep getting response 400, but curl works
Old analysises are automatically clean up after 5 years. Consider to lower that period inAdministration > General > Database Cleaner.
I am running SonarQube 6.4 on Windows with a SQL Express database. The database has now reached the 10Gb limit of SQL Express and I would like to make it smaller.I have remove some old projects and changed the 'Database Cleaner' settings but the database remains the same size (there isn't any free space in the files to shrink it).Is there a way to force SonarQube to clean-up old/deleted projects?
Shrink SonarQube database
I discovered that this feature is not supported in Sonarqube. A ticket opened for thisissuehas already been closed as "Won't Fix" by the Sonarqube Team.For a workaround you can checkthis
Im using SonarQube v6.4. I'm aware that all types of tests (Unit Tests, Integration Tests etc) have been merged together as overall coverage.However, on the interface I can see statistics for only Unit tests, Is there a way to get the statistics for other types of tests?Example of statistics available only for unit testUnit Test ErrorsUnit Test FailuresSkipped Unit TestsUnit Test Success (%)Unit Test Duration
How to show Integration Test Statistics?
Most (or even all?) UI interactions only trigger Web API calls.In your case,api/system/migrate_dbseems to serve your purpose.From the api documentation:Migrate the database to match the current version of SonarQube. Sending a POST request to this URL starts the DB migration. It is strongly advised to make a database backup before invoking this WS.To call it from the command line use:curl -s -u admin:admin -XPOST "localhost:9000/api/system/migrate_db"curlis a linux command line tool for to communicate via HTTP-stoggle "silent mode"-u admin:adminprovides authentication-XPOSTset's the HTTP method toPOST(instead of defaultGET)
https://docs.sonarqube.org/display/SONAR/UpgradingI am just going through this documentation to upgrade Sonarqube. One of the steps is to open the URL in browser and follow instructions.Is there any CLI command available for this step? So that I can automate this step in my upgrade automation?
CLI command for Sonarqube Upgrade browser step
SonarQube promotes the idea of a"leak paradigm". In short, the idea is to continously enrich your existing code base with clean, maintainable, secure increments - which will make your code base better over time.Fixingall existingissues is not advisable.So: define a leak period in SonarQube andchange your quality gateto only leak measures. SonarQube is made for exactly your use-case!
We have a lot of legacy code in our repositories, and now we implement SonarQube 6.4 but our legacy code causes a lot of errors and warnings, so we would like to analyze only new written/in the future modified code and exclude the old because we have no resources to amend all issues from legacy code written during last 10 years.How can I exclude already found issues e.g. by the date they when they were found? But we don't want to exclude all old files as such, because edit them from time to time. We just want to make sure not to add new issues.
How to exclude all legacy issues by date?
Use the mavensonar:sonargoal. If maven is already set up, than this is much more convenient then usingsonar-project.properties.
My Project structure belowApp XYX +- pom.xml +-SubfOlder +- Module 1 +- pom.xml +- Module 2 +- pom.xml +- Module3 +- pom.xml +- Module4 +- pom.xml ....... ....... +- Module10 +- pom.xmlI'm currently using the sonar scanner v2.5.1 as a Jenkins post build task. I'm not sure how to define sonar.sources for all my 10 modules.I went thru the documentation :https://docs.sonarqube.org/display/SCAN/Advanced+SonarQube+Scanner+Usagesbut I don't want to define all the 10 modules one by one. Also what if there are 50+ modules.Any suggestion how to approach this scenario.Thanks.
Setup Sonar Runner + cobertura for multi module projects
When I went tolocalhost:8080/job/TEST/10/injectedEnvVars(for example) I couldn't seeGIT_BRANCHas an environment variable. I realized I hadn't selected 'inject environment variables to the build process' in the build environment.Then inbuild.xml, I madevalue="$(branch)"and added-Dbranch=%GIT_BRANCH%to my command line.Thanks all for the help :)
I'm trying to use the git branch name as a variable so that I can include it in the SonarQube project key. Does anyone know of how I can do this? I'm on Windows if that helps. I've tried doing things like this:property name="sonar.projectKey" value="${GIT_BRANCH}"or setting environment variables in Jenkins and calling those but I can't seem to get it.Thanks in advance :)Additional info:I'm building the project from Jenkins and the part where it fails is when I callant sonar. Using${GIT_BRANCH}results in this:"C:\Program Files (x86)\Jenkins\jobs\PR Projects\jobs\PR_JmxMonitor_RPM\workspace\projects\JmxMonitor\build.xml:132: Validation of project reactor failed: o "${GIT_BRANCH}" is not a valid project or module key. Allowed characters are alphanumeric, '-', '_', '.' and ':', with at least one non-digit."
How to include git branch name as variable for ant build.xml
The current version of SonarQube is 6.4 and the current LTS is 5.6.6. Plugin versions only compatible with versions lower than those have been purged from the Update Center.There is, however, a version of the Perforce plugin that's compatible with 5.6.6.
I want to use perforce as SonarQube 5.3 scm provider, but it failed with this error message:ERROR: SCM provider was set to "perforce" but no SCM provider found for this key. Supported SCM providers are svn,gitI want to install perforce plugin in SonarQube update center, but it said:Error while downloading plugin 'scmperforce' with version '1.4'. No compatible plugin found.And I can't find any available scm perforce plugins on the SonarQube website.How to use perforce with SonarQube 5.3?
How to install the scm perforce provider for SonarQube 5.3?
This message indicates than there is not enough free disk space on your server, so the best fix is to free some space.Your curl request is not working because you need to start SonarQube with this property set :sonar.search.httpPort=10000and use this port (without any authentication-u admin:admin) in your curl request.And then remove this property and restart SonarQube.Please note that overriding this value is not supported.
I have a little problem with sonarqube 5.6 I got the error:high disk watermark [90%] exceeded on [dGbc0mfEQmOT5LXYQU45aQ][sonar-1498565081006] free: 931mb[5.1%], shards will be relocated away from this node high disk watermark [90%] exceeded on [dGbc0mfEQmOT5LXYQU45aQ][sonar-1498565081006] free: 931mb[5.1%], shards will be relocated away from this nodein the sonar.log which I would like to disable (or at least decrease the limit). And after a little search I found out that I have to run this commandcurl --noproxy '*' --u admin:admin -vvvv -XPUT http://localhost:9004/_cluster/settings -d '{"persistent" : {"cluster.routing.allocation.disk.threshold_enabled": False}}'but when I do this I got a 404-Error and I have no idea why this don't work. That's why I would very thanksful if someone can give me a little hint what I am doing wrong? The sonarqube-Installation is running on SuSE. best regards Dan
Disable high watermark-Log entries in sonarqube 5.6
Values that cause projects to fail the quality gate are no longer highlighted in red on the project homepage, and this is not configurable.
We have a strange bug/issue in Sonar Qube. There is a project X that has a Quality Gate with condition: Coverage on new code < 80 (error). In this project the value for this is ~50, so SQ should mark this as error with red color. On Project X details site it's ok:But on dashboard (it's SonarQube 5.6.6 LTS) the value is not colored:How to set change this behavior, so that SQ will color also the value in dashboard? Thanks for any help!
SonarQube qulity gate color on dashboard
Ok, I guess I've found the answer... See question #5 ofSonarLint's FAQ:We don't plan to support plugins running third-party analyzers (like PMD, Android Lint, JSLint...). Most of the time those analyzers already have dedicated IDE integration.Too bad though, because we wanted to share our SonarQube quality profiles all over the company...
I've configured a server binding between SonarQube and Intellij and it's working fine on "usual" rules. I tested it: I changed the severity of a JavaScript rule in the quality profile of the project in SonarQube, updated the binding in Intellij, and saw the new severity in Intellij on-the-fly report. Alright.The problem is I also need SonarQube rules that come from its plugins. For example, I have TypeScript and CSS rules that come from plugins. My SonarQube analysis report 1000+ bugs, but SonarLint within Intellij reports 0 bug.Is there a way of exporting this rules from SonarQube into Intellij?Thank you.
SonarLint doesn't use SonarQube server rules that come from a plugin
I figured it out. Instead of having *.ec for my reportPath, I changed it to be "coverage.ec". And then it showed up. Thanks for the help guys!
I have a coverage.ec file which gets generated and shows code coverage for my espresso UI tests. I also have sonar configured in gradle like so:sonarqube { properties { property "sonar.projectName", "Android 9" property "sonar.projectKey", "org.sonarqube:Android9" property "sonar.host.url", "http://localhost:9000" property "sonar.username", "admin" property "sonar.password", "password" property "sonar.projectVersion", "5" property "sonar.java.source", "7" property "sonar.android.lint.report", "build/outputs/lint-results.xml" property "sonar.sourceEncoding","UTF-8" property "sonar.sources","src/main/java" property "sonar.exclusions","build/**,**/*.png" property "sonar.test.exclusions", "" property "sonar.binaries", "build/classes" property "sonar.jacoco.reportPath","build/jacoco/testDevDebugUnitTest.exec" property "sonar.tests", "src/androidTest/java" //property "sonar.import_unknown_files", true //property "sonar.android.lint.report", "./build/outputs/lint-results.xml" property "sonar.jacoco.itReportPath", "build/outputs/code-coverage/connected/flavors/NORMAL/*.ec" }}problem? No code coverage at all is being displayed in sonar - nothing, 0% which is really odd and I haven't found anything online for the past week I've spent scavenging the internet. Does anyone have any idea what's going on?
Uploading coverage.ec file to sonar Android
.Select your project and in Eclipse'sQuick Access, selectAnalyze - Analyze with SonarLint. You can also assign a keyboard shortcut to this action by going toWindow -> Preferences -> General -> Keys.2.It seems as if you are not running in connected mode. Connecting a SonarQube server is not enough, you also have to bind individual projects. To do this, right click on your project in Eclipse, and selectSonarLint -> Bind to a SonarQube project...Search for the name of your project on the server by typing in the box under SonarQube project, as show in the following screenshot:Once connected, a SonarQube symbol should appear on your project's icon in Eclipse.3.Once connected, the quality profile of your SonarQube server project will be used.4.SonarLint only provides on the fly feedback, but does not trigger any analysis server side. Personally I have aclean verify sonar:sonarMaven run configuration for my projects, and run it every now and again within Eclipse.I recommend reading theSonarLint documentationfor more information.
I'm using Eclipse Neon and SonarQube 5.6.6(LTS). I've install sonarLint version 3.1.0. Following are my question.In SonarLint whether there is an option to analyze the entire project? I can't able to find such option.The issue showing in Eclipse reported by sonar lint is different from reported on server. When I'm wantedly creating the sonar issues(based on the rule) in eclipse but SonarLint is not recognizing . why?From Eclipse I've made the connection to the SonarQube server and the connection was success, Whether it is using the activated quality profile rule?After resolving the issues, how the issues will be reflected to the sonarQube server ? In case of Maven whether I need to add the sonar properties and sonar-maven plugin and trigger the build?
Sonar Lint Eclipse Issue
It is a JGit bug. Please refer tohttps://bugs.eclipse.org/bugs/show_bug.cgi?id=499543
I am suddenly having trouble running a SonarQube analyses on a project that previously ran fine (I'm running it through Jenkins). It's giving me an error, "Unable to blame file pom.xml". (We're using GIT).This makes no sense... since the last successful run I've only added two lines to the pom, and I'm the only one who has ever committed to the pom file. The project is in our company's BitBucket Server, and I'm able to see the blame information there... so what could be causing this error?I've included a snapshot of the stacktrace in the Jenkins log:
SonarQube Unable to blame file pom.xml
Since you're talking about a Maven build, then I know we're dealing with Java. In which case, youmustbuild before the analysis; much of the analysis relies on byte code for depth and accuracy. If byte code is not available to the SonarJava analyzer you end up with a lot of false negatives.Specifically, you'll get the same measurements of coverage, duplications, ... with or without byte code. But without byte code, SonarJava looses the ability to, for instance, look at the super class and understand which methods are missing [email protected]: From SonarJava version 4.12 binary files are required. (Seethe docsfor more details.)
Can some one help me how to configure a best CI pipeline for analyzing source code (JAVA) using Sonarqube? In my mind I have a Pipeline likeSCM-->Jenkins --->maven build-->sonarqube analysis.Is this is a best practice? or can we skip maven build and just do sonarqube analysisSCM-->Jenkins-->sonarqube analysis. Is there any other CI pipelines which is a best practice for an organization who are looking mainly for code analysis?
Different Ways to create an effective Ci pipeline for sonarqube analysis
Fixing the Water Leak(paradigm at the core of SonarQube features/UX) is about making sure that your software quality does not degrade from one product version to another, which is why the default value of the Leak Period issince_previous_version.By definition of asprint, your software should be releasable at the end of each sprint. If you do release an increment at each sprint then the defaultsince_previous_versionwill do.And actually even if you don't release every sprint,since_previous_versionstill is the best pick:quality since last released version is what you should focus on (if you didn't release after the previous sprint, then you shouldn't ignore bugs/vulnerabilities/code_smells potentially introduced back then)it will still ensure that quality does not degrade in the course of one sprint (since_previous_versionbeing a sort of superset of 'since last sprint')
I'm Using SonarQube 5.6.5 and trying to configure it so that the Leak Period is starting every x (=21) days.Our sprints are running 21 days so I want the differential view is showing the changes since last sprint start. I get this only if I manually change each sprint start the 'Leak Period' to the date of the sprint start. Is there a more convenient way to do so?
SonarQube: How to configure leak period start every X days
There arethreefour (thanks @Julian) possibilities here:~10k issues in your project have been "resolved" False Positive or Won't Fix. Okay, this volume of FP/WF issues is unlikely, so on toYou have set someexclusionswhich filter out some issues. This is possible, but 10k seems a bit high for that, so...The number you're looking at is the total number of SonarC# issues, plus compiler warnings, plus (insert some other checker run automatically during the build here), but only issues that correlate to Rules active in yourQuality Profilewill be reflected in SonarQube.csfiles outside the project base directory may be excluded automatically by the SonarQube Scanner for MSBuild
I see26,253warnings in MSbuild log with SonarScanner (Red marked). It includes 558 compiler warnings, rest are from the code analyzer.But, I see only16,396issues in SonarQube (blue marked)Why there is huge difference of around10,000issues, why are not those issues reported in SonarQube !!
Sonar scanner issue count doesn't match that shown in SonarQube
As mentioned in theofficial documentation of the SonarQube Travis Add-onabout analysing pull requests:For security reasons, this advanced feature[i.e. pull request analysis]works only for internal pull requests. In other words, pull requests built from forks won’t be inspected.
I'm trying to configure SonarQube analysis in a github project. I've followed the official travis ci documentation but SonarQube analysis is not performed.I'm getting the following message: "Skipping SonarQube Scan because it is not running in a secure environment"pull request link:https://github.com/zakshya/cronos/pull/4Full build log:https://s3.amazonaws.com/archive.travis-ci.org/jobs/216125526/log.txtDoes some one encountered this problem ? I'm i missing some config ?
Travis CI skipping SonarQube analysis
This doesn't seem to be a Jenkins issue; rather you should be able to set the varioussonar.*properties (e.g.sonar.projectNameorsonar.branch) when running the Maven plugin.The documentation seems to have a full list:https://docs.sonarqube.org/display/SONAR/Analysis+Parameters
When building a multibranch pipeline, I send each of my projects to SonarQube using the SonarQube plugin like so:pipeline { agent any options { buildDiscarder(logRotator(numToKeepStr:'20')) timeout(time: 30, unit: 'MINUTES') } tools { maven 'Maven 3.3.9' jdk 'JDK 1.8' } stages { stage('Checkout') { steps { echo 'Checking out..' checkout scm echo "My branch is: ${env.BRANCH_NAME}" } } stage('Build') { steps { echo 'Building..' bat 'mvn clean verify -P!local' } } stage('SonarQube analysis'){ steps{ echo 'Analysing...' withSonarQubeEnv('SonarQube') { bat 'mvn org.sonarsource.scanner.maven:sonar-maven-plugin:3.2:sonar' } } } } }It works fine, but one thing I need it to do is to change the name of the project in SonarQube to be projectName/builtBranch instead of just the project name. Is there a way I can do this using the pipeline?
Jenkins Pipeline SonarQube key name
SonarQube 5.6* will scale vertically; throw more hardware at it and it will use that hardware well.SonarQube 6.x will eventually scale horizontally as well; throw more nodes at it and it will use them well. But this feature won't be available in the Community Edition - it will be available only for customers.
I read that SonarQube is going to provide high availability and clustering from 6.x version. But I couldn't seen any document related to the procedure of it. Overall, how does the high availability and clustering work with SonarQube 5.6.6 version and latest 6.X versions?Is there any difference between these two in High availability and is there any high level modifications does between 5.5 and 6.X version of SonarQube?
High availability and clustering in SonarQube
Since SonarQube v6.3:api/components/search- Search for components - Parameterq:Limit search to component names orcomponent keysthat contain the supplied stringBefore SonarQube v6.3 (only for searching on projectnamethere):api/projects/index- Parametersearch:Substring of projectname, case insensitiveSource:SonarQube WebAPI(documentationembeddedin any SonarQube instance).
Is there an api in sonarqube (old and new versions) to get projects by passing a key with '*'.Example :http://localhost/api/resources?format=json&key=sonar*Or is there an alternative way to get this result?
Sonarqube API - search projects by passing a wild card
The "Complexity" metrics currently being calculated are Cyclomatic Complexity.It is worth noting that recent Code Analyzer versions compute the correct Cyclomatic Complexity value - versus the previous combination of Cyclomatic and Essential Complexities.Cognitive Complexity metrics aren't available at this writing, but should be available "soon".UPDATECognitive Complexity is currently available as a metric in SonarJava, SonarJS, SonarC#, SonarSwift, and SonarC-Family (C/C++, Objective-C)
In the past, Sonar used cyclomatic complexity. On their website, they mention Cognitive complexity..but in their documentation, there is just "Complexity" measure but with the same "shortcomings" of the cyclomatic one (e.g. increasing by 1 for each CASE in a switch). Which one is the one used now,then?
What kind of complexity does SonarQube use?
First, in docker means each tool is in its own container.They only need to see each other through the network, which is where aDocker Engine in Swarm modecomes in.Second "configure Jenkins to work with SonarQube"... that is what I have done in my shop, and there isn't much to it.Once theJenkins SonarQube pluginis installed, and theaddress for the SonarQube server entered, you canconfigure your joband call sonar (for instance with maven:$SONAR_MAVEN_GOAL -Dsonar.host.url=$SONAR_HOST_URL)The analysis done in the Jenkins workspace will then be published in the SonarQube server.A swarm server is the more modern version of this 2015docker-compose.yml filefrom themarcelbirkner/docker-ci-tool-stackproject.The idea remains the same though: each element is isolated in its own container.
Currently, I am working in a quality process so as to ensure that the code is acceptable. For that, I'm integrating Jenkins, SonarQube and GitLab, which are running in different servers (actually they are in different docker containers).The idea is to check with SonarQube everytime the code is pushed against GitLab and block commits, merges, and so on, whether SonarQube has not passed.I have already integrated Jenkins with SonarQube, but Jenkins checks the code inside his workspace, so imagine a situation where a developer in his laptop needs to push his changes.My conceptual question is simple: Is it possible to integrate these technologies in order to do this? And, if the question is yes, which steps are necessary?PD: I don't need to see code, configuration files,and so on. I just need something like:Configure SonarQube to work with JenkinsDo an script so as to copy that file in that folder,...
Is it possible to integrate SonarQube, Jenkins and GitLab (all in dockers)?
"Dashboards" per se were dropped in SonarQube 6.2. They were replaced with standard landing pages. Your first screenshot is of the Projects page, which is not configurable.
I have setup SonarQube 6.0 on our server and shown specific column on project dashboard using Configure Wizard(1st Image). Now I have migrated our SonarQube version to 6.2 I don't see configure wizard option (2nd Image) to add specific column to track what are the unresolved issue, bugs, vunnerabilities etc.Do you have any idea of customizing dashboard with columns for SonarQube 6.2.
SonarQube 6.2 - configure wizard option not there on dashboard?
You would need to implement the rules in a custom plugin. You don't list a language, so I'll assume Java and point you at the documentation for implementing custom Java rules:https://docs.sonarqube.org/display/PLUG/Custom+Rules+for+Java
I am working with sonarqube ,and i need to display some custom issues which reported by my SDK in sonarqube web console . Is there any API available to post custom issues or give me any suggestion to do the same.Thanks in advance
Custom issue posting to sonar sonarqube?
It's a permalink to that particular item: issue or rule.
What does the broken link icon signify in SonarQube? In my environment it does link to a lower level project or source file. but does the broken link icon signify that there is something broken in my configuration? Is there a "whole" link icon (I've never seen one)?Can't find any documentation on the iconography in general. Point me there if it exists please.
What does the broken link icon signify in SonarQube?
This is possible to ignore all rules on all files using the "Analysis Scope > Ignore Issues on Multiple Criteria" settings on your project.Please read"Narrowing the focus"on the official documentation.
I have some generated code (JavaScript from TypeScript) that I don't want analysing by sonar (for bugs etc), but I do want the test coverage including.Currently by using the Sonar inclusion/exclusion we have the coverage and the bugs.Sonar v6.2
SonarQube - Include files for test coverage, exclude for analysis
if you are able/permitted to modify the files ininstalldir\web\WEB-INF\app\controllersyou could change the filelanding_controller.rbdef index if logged_in? return redirect_to :controller => 'projects', :action => 'favorite' else return redirect_to :controller => 'projects' //here was 'about' end end
The SonarQube 6.2 product has dramatically changed its skin. I am still playing with it, and my first impression is that I like it, but one thing that is bugging me and will surely confuse my users is the default landing page for my host (e.g.http://sonar.example.com) is redirected tohttp://sonar.example.com/aboutinstead ofhttp://sonar.example.com/projectswhich is a pretty swift departure from where we used to be previously. I think it would be more useful to go to /projects by default. How can I get this as the default landing page instead of /about?I haven't found any likely sonar.conf variable, nor anything in the Administration panels... Please help, thanks!
SonarQube 6.2 - Change default landing page to /projects from /about
Starting with version 5.6, SonarQube helps you focus on the Leak Period, to keep new code clean. The other side of that coin is that access to the other differential periods has been dropped. You can consider the administrative settings vestigial: useless remnants left behind by evolution. They will be removed "soon".
A few days ago I've upgraded from SonarQube 5.3 to SonarQube 6.1.Now I'm missing the Dropdown to set the Leak Period I'm interested in. The configuration values are still there (Administration - General - Differential View - Leak Period / Period 2 / Period 3) but within every view there is only "... since last analysis" available.Is it not possible anymore to dynamically change the periods I'm interested in? Is there another way to compare Analysis? (e.g. last 30 days, last week etc.)
Comparison of Analysis within SonarQube 6.1
Translate your SoapUI reports to the Generic Coverage format. Support for the format is provided bya pluginin SonarQube v <=6.1 and in the core in SonarQube v 6.2+.The format changes slightly from the plugin to the core. The plugin's version of the format is still supported (tho deprecated) for now.
I am trying to get some coverage on SonarQube using the test cases I wrote on soapUI. I tested WCF services on soapUI. Is there any way to integrate the 2 reports?
Integrating SoapUI test cases with SonarQube
The Useless Code Tracker plugin tracked the number of duplicated lines that could be reduced/removed via consolidation. To findunusedcode, take a look at therelevant PHP rules.
Closed.This question is seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. You can edit the question so it can be answered with facts and citations.Closed7 years ago.Improve this questionI tried searching for a way to detect unused and dead PHP code through sonar. I found a plugin Useless Code Tracker Plugin at -http://docs.sonarqube.org/display/PLUG/Useless+Code+Tracker+PluginBut it has been discontinued.Has a new plugin or a rule-set been introduced for it?
SonarQube 6.0 plugin or rule-set to detect unused and dead PHP code [closed]
In the end, I found a workaround - not a particularly nice one, mind you. I opened up the Sonar database and had a look in the PROJECTS table:select * from projects where kee like 'au.com.foo:project-bar%'This revealed a couple of old entries from a previously (unsuccessful, I guess - there was no files indexed against these entries) attempt to analyse the project. Doing a delete from the table of these entries then enabled me to create the project in Sonar again.Why the entries didn't render on the UI in the first place is anyone's guess.
I'm having trouble creating a project in my sonarqube instance - it's like there are projects already created that I cannot see.I login as the admin user, go to the Administration -> Projects -> Projects Management page, and then click Create Project.I give it a name, and then when I type in my maven project name in the key field, e.g.au.com.foo:project-barand click create, I get the message that"Could not create Project, key already exists: au.com.foo:project-bar"Thing is, when I look at the list of all projects on that project management screen, there is no project with that key. There is also nothing under Provisioned and nothing listed under Ghosts either.What gives? I would have thought if there was a previous unsuccessful project with that key it would have been listed under the ghosts section anyhow. I'm also definitely logged in as admin here, so should see everything?
Can't create project in sonar
If you have to use theJava 7and above, I prefer you to usetry with resourceswhich was introduced inJava 7new features.Try-with-resourcesinJava 7is a newexceptionhandling mechanism that makes it easier to correctly close resources that are used within atry-catch block.As to your code:finally { try { if (null != fileIn) { fileIn.close(); } if (null != buffIn) { buffIn.close(); } if (null != inData) { inData.close(); } } catch (Exception exFinally) { // some stuff someArray= null; } }Do you notice that ugly double try?But, if you used thetry with resources,close()is automatically called, if itthrowsanExceptionor not, it will be supressed(as specified in the Java Language Specification 14.20.3). Same happens for your case. I hope it helps.So, your code will be looked like:public static byte[] readSomeFile(String filePath) { byte[] buffer = new byte[FILE_SIZE]; int size = 0; byte[] someArray= null; try (FileInputStream fileIn = new FileInputStream(filePath); BufferedInputStream buffIn = new BufferedInputStream(fileIn); DataInputStream inData = new DataInputStream(buffIn);) { size = inData.read(buffer, 0, FILE_SIZE); someArray= new byte[size]; System.arraycopy(buffer, 0, someArray, 0, size); } catch (IOException e) { //log(Log.ERROR,"IO ERROR: " + e.toString()); } return someArray; }
I have the following piece of code:public static byte[] readSomeFile(String filePath) { byte[] buffer = new byte[FILE_SIZE]; FileInputStream fileIn = null; BufferedInputStream buffIn = null; DataInputStream inData = null; int size = 0; byte[] someArray= null; try { fileIn = new FileInputStream(filePath); buffIn = new BufferedInputStream(fileIn); inData = new DataInputStream(buffIn); size = inData.read(buffer, 0, FILE_SIZE); someArray= new byte[size]; System.arraycopy(buffer, 0, someArray, 0, size); } catch (IOException e) { //log(Log.ERROR,"IO ERROR: " + e.toString()); } finally { try { if (null != fileIn) { fileIn.close(); } if (null != buffIn) { buffIn.close(); } if (null != inData) { inData.close(); } } catch (Exception exFinally) { // some stuff someArray= null; } } return someArray; }the problem is Sonar is still complaining aboutfileInnot being closed, although it's the first resource addressed in the finally block.How does Sonar work in this case ? and how to resolve theResources should be closedrule ?
Resources should be closed - Sonar
One can use theConfigureblock of Job DSL to define custom elements. A related question isUsing Jenkins Job-DSL Configure block to place custom steps in particular positions.The following script worked for me,configure { project -> project / publishers / 'quality.gates.jenkins.QGPublisher' (plugin:'[email protected]'){ jobConfigData{ projectKey('MY-PROJECT-ID') sonarInstanceName('SonarQube') } } }The script can be tested using "Job DSL playground" athttp://job-dsl.herokuapp.com/
Does someone know Jenkins' Job-DSL syntax to configure SonarQube's quality gate plugin section?
Configure SonarQube's Quality Gate section using Jenkins' Job-DSL
This is not supported currently (version 6.1). You can track this ticket to be informed of the progress:https://jira.sonarsource.com/browse/SONAR-6763
I am currently working with SonarQube v5.6 and have a need to generate comprehensive "preview" reports locally before pushing the results to my remote SonarQube server. Specifically, I need to be able to see technical debt, code coverage, and duplicated blocks in the local HTML and/or console reports which are created when running the analysis in "preview" mode.Currently, I am able to see issues -- new, existing, resolved, minor, major, etc. -- and nothing else. I would like to be able to see technical debt, code coverage, and duplicated blocks as well (at the very least, I need to see code coverage). Can SonarQube be configured to show these details in "preview" mode reports, via a command line argument or some other setting? I am using Maven and JaCoCo.
Can SonarQube be configured to show code coverage in "preview" mode reports?
Rule "Unused Protected Method" has been deprecated in version4.1, and dropped in version4.2of theSonarQube Java Analyzer plugin, due to its poor reliability (numerous false positives). We are consequently not maintaining this rule anymore.If these issues are wrong, like you said and as it probably is, simply mark them as "False Positive" (if you are using LTS5.6version of SonarQube), or "Won't Fix". There is nothing to fix and SonarQube is doing a mistake.Note that updating the Java Analyzer Plugin to version 4.2 will make the issue disappear, but only because the rule itself will disappear from available rules.
I have implemented some lines of codes as:if(condition){ Class a = new Class(); method(a.b(), a.c()); }else{ method(null, null); }Sonar fails onprotected bandprotected cas unused. Please suggest me any solution regarding the same.Thanks in advance
Sonar Violations of Unused methods in if statement
This is a known issue, and will be fixed by the next release. See:https://jira.sonarsource.com/browse/SONARMSBRU-262.We just announced the RC versions of the products that have this fix, you can give them a try. Seethis thread.
I am using Visual Studio Team Services to carry out an automated build, and using SonarQube to display Code Quality, Coverage, etc. I am also using a privately hosted build agent.The build steps all work successfully with data being processed and populated through to SonarQube which is great. However, no code coverage is being displayed in SonarQube. After looking through the logs in VSTS I found that SonarQube is looking for the .trx file (which contains code coverage) in a different directory to the one that VSTS publishes the .trx file to.So when VSTS builds the solution it creates the test results file here: C:\agent_work\3\s\TestResultsBut SonarQube is trying to use test results from here: C:\agent_work\3\TestResultsOn the build server, if I manually copy the .trx file into the correct location and then run the build again, the code coverage all works fine and processes through to SonarQube. So the issue is definitely the mismatch of the locations where the .trx is published and where it is to be picked up form.I can't find a way of changing the publish location, or the SonarQube source location.Please help!
VSTS SonarQube cannot find TRX file
SonarQube doesn't know the concept of "class". This is a logical element, whereas SonarQube manages only "physical" components like files or folders. The consequence is that the Web API allows you to query only components that are "physical".
I want to get the sonar result in the class wise classification or modularized format. I am using python and the sonar web API. Apart from the basic APIs are there any other APIs which give me the results per class
Is there a way to get the sonar result per class or per module
I have figured one way to handle the big if/switch statements. Based on the ideas, I got from everyone of you. I compiled into a simple solution that is easy to understand and modify, also handles the complexity part. Please find my solution below,// Dependency Injected private someService; public void processCapability(..., String capabilityId) { Boolean isCapabilityProcessed = processDispenseCapabilities(...) || processUpdateCapabilities(..); if(isCapabilityProcessed) { throw exception("Invalid Capability"); } } private Boolean processDispenseCapabilities(..,String capabilityId) { Boolean result = false; switch (capabilityId) { case ORDER_DISPENSED_WITH_SOURCE1: someService.doDispense1(); result = true; case ORDER_DISPENSED_WITH_SOURCE2: someService.doDispense2(); result = true; case ORDER_REJECTED: someService.doReject(); result = true; ... default: //do nothing } return result; } private Boolean processUpdateCapabilities(..,String capabilityId) { Boolean result = false; switch (capabilityId) { case ORDER_CANCEL: someService.doCancel(); result = true; case ORDER_PURGE: someService.doPurge(); result = true; ... default: //do nothing } return result; }
I have a method that takes an input called capability id. Based on the capability id, I execute the business implementations put forward in form of a switch case. I have my functionality working, But came across a problem where the sonar report is showing high cyclomatic complexity around 12-14. The company I work for, uses a standard of 10 as the max cyclomatic complexity. My considerations is that, If I happen to break the code into too many block, the code readability is getting affected.Note:-I don't have permissions to change sonar rules.Unfortunately, I can't share the code. The code would be in the following way though,// Dependency Injected private someService; public void processCapability(..., String capabilityId) { switch (capabilityId) { case ORDER_DISPENSED_WITH_SOURCE1: someService.doDispense1(); case ORDER_DISPENSED_WITH_SOURCE2: someService.doDispense2(); case ORDER_REJECTED: someService.doReject(); case ORDER_CANCEL: someService.doCancel(); case ORDER_PURGE: someService.doPurge(); ... default: throw exception } }Update:I was able to resolve my problem, with a solution I posted in below answers.
What is the best way to handle code with if/switch statements having high cyclomatic complexity?
Your use-case is at the core of theSonarQube Leak Concept. All you need to do is make sure that there is an analysis which corresponds to the start of the Leak Period and which will set the baseline in terms of issues already existing at that point. The right way to do this is to actually usesonar.projectDate(seeAnalysis Parameters) for that initial analysis. Bottom line:check out the commit which corresponds tointegrationin your caseanalyse it by settingsonar.projectDateas the date of that commit andsonar.projectVersiontobaselinefor exampleset your Leak Period tobaselinefor all further analysis, theLeakwill correspond to new Issues introduced since that initialbaseline. Legacy problems (before integration) will be considered as legacy and not accounted in theLeak Period, your Quality Gate can then do the job as you expect.FYI SCMblameinformation is used by SonarQube for auto-assignement of issues and for identification of Coverage onnew code, however it can't reliably determine which Issues are new or not: imagine a variable defined and used in your code, if a commit removes its usage then it would raise avariable unusedissue on the variable definition, whereas that precise line wasn't touched by any commit. That's why Issues are determined as New relative to the date when SonarQube first detected them (during a previous analysis), hence the workflow detailed above.
I had recently integratedsonarqubein our release process. I have set the leak period as the date of integration, and mandated it inquality gatedefinition that there should be zero new issues since the start of leak period.The problem is whenever there is a change in a file, sonarqube starts considering all previous issues as new issues. This is especially problematic for large files, as the person who is making any change in a file needs to make all the corrections retrospectively. What I want sonarqube to do is to honor the commit date from the blame information and to definenewby comparing commit date with the leak period.How to make this possible? I am usingsonarqube 6.0
Sonarqube not honoring git commit date while calculating new bugs/vulnerabilities/leaks
First, I raise your attention on one important point: you shouldnotrun a "standard" SonarQube analysis on PR - otherwise your project on SonarQube.com will be "polluted" by intermediate analyses that have nothing to do with each other. Standard analyses must be executed only on the main development branch - which is usually the "master" branch. Please read therunSonarQubeAnalysis.sh fileof our sample projects to see how to achieve that.Now, why your attempt does not work? Simply because the SONAR_TOKEN environment variable (that you've set as "secure" in your YML file) will not be decoded by Travis when the PR is coming "from the outside world" (i.e when it's not a PR of your own). This is a security constraint to prevent anybody to fork your repo, update the YML file with aecho $SONAR_TOKEN, submit a PR and genlty wait that Travis executes it to unveil the secured environment variable.Analyzing "external" PR is something that we'll soon be working on so that this is easy, straightforward and yet secured for OSS projects to benefit from this feature.
I'm setting up a project with Travis CI and SonarQube.com, everything goes smoothly when a pull request comes out of a branch from the repository but it is failing when Travis runs a build off a pull request from a forked repository.A build out of a PR from the repository:https://travis-ci.org/PistachoSoft/dummy-calculator/builds/162905730A build out of a PR from a forked repository:https://travis-ci.org/PistachoSoft/dummy-calculator/builds/162892678The repository:https://github.com/PistachoSoft/dummy-calculatorAs it can be seen in the build log this is the error:You're not authorized to execute any SonarQube analysis. Please contact your SonarQube administrator.Things I've tried out but didn't work out:Updating the sonar token.Using an encrypted token granted by another person from the organization.Granting 'sonar-users' and 'Anyone' the 'Execute Analysis' permission on the SonarQube project.What can I do to fix this?
Not authorized to execute any SonarQube analysis when building pull request from a forket repo on Travis CI
SonarQube analysis is not executed. You have to call it explicitly. Something like:gradle sonarqubePlease read the documentation for theSonarQube Scanner for Gradle.
I have a Java Gradle projet hosted on GitHub and connected to travis CI.On the root of this project, I have:.travis.ymllanguage: java addons: sonarqube: true env: global: - secure: <the token generated on sonarqube.com> script: gradle check.sonarsource.propertieswallboard.teamAtSonarSource=support sonar.host.url=http://sonarqube.combuild.gradle// Uses DSL plugins resolution introduced in Gradle 2.1 plugins { id "java" id "jacoco" id "org.sonarqube" version "1.2" } sonarqube { properties { property "sonar.projectName", "Java :: Simple Project :: SonarQube Scanner for Gradle" property "sonar.projectKey", "org.sonarqube:java-gradle-simple" property "sonar.jacoco.reportPath", "${project.buildDir}/jacoco/test.exec" } } allprojects { ext.baseVersion = "0.1" ext.snapshotVersion = true group = "org.sonarqube" version = "$baseVersion" + (snapshotVersion ? "-SNAPSHOT" : "") } test { ignoreFailures = true } dependencies { testCompile 'junit:junit:4.12' } repositories { repositories { maven { url "http://repo1.maven.org/maven2/" } maven { url "https://plugins.gradle.org/m2/" } } }I found this one onSonarSource example repoThe travis CI pass but the sonarqube.com analysis do not run. I am new to Travis, SonarQube and Gradle, so I don't know where exactly I am wrong.Edit: Here is theTravis logs.
Analysing a Java Gradle project on SonarQube.com with Travis CI
Issues are automatically assigned by SonarQube. This behaviour cannot be overridden/changed by a plugin.
What type of SQ plugin interface should I use for assignment of issues to an user? Sensor, MeasureComputer, other?What would be the main related classes and/or interfaces? Any source file to check?
Sonarqube 6.0: How can an issue be assiged to an user from a plugin?
Following Teryk's response I manage fine tune my investigation. It turns out that it is cased by the MSBUILD output which does not include a filename or line for certain CA warning is Microsoft.Design and Microsoft.Naming, e.g. CA1024, CA1040, CA1704, CA1716, thus:3>MSBUILD : warning CA1040: Microsoft.Design : Define a custom attribute to replace 'ITierRepository'.When this happens the issue is recorded against the solution but obviously cannot be assign to a specific file and the line not identified.Having found that I was quick able to find the article which discusses the same issue:https://groups.google.com/d/topic/sonarqube/UDIIjWbCGjsIt is caused by the fact that FxCop is not able find source for the issue as described here:https://blogs.msdn.microsoft.com/codeanalysis/2007/05/12/faq-why-is-file-and-line-information-available-for-some-warnings-in-fxcop-but-not-for-others/It apparently relates to changes to FxCop reporting that were introduced in v5.2 of the C# plugin which was also deployed at the same time as upgrading to SQ 6.0
We have an issue since our upgrade to SonarQube 6.0 that on the issues page the link icon or the right arrow icon no longer link to the code.In this case clicking either link takes you to another (smaller) list of issues.This is not the case for all issues, the only difference I can spot is that on the problem issues the filename and line number are not shown. checking in the database and in the issues table the 'line' column is also null.We are using SonarQube 6.0 with C# plugin 5.3.2 - Analysis is triggered by TFS2015 Update 3Many thanks in advance for any ideas/advice.
SonarQube 6.0 Link to code for issues not working
Let's start by using the good wording : the SonarQube Eclipse Plugin is dead and now there is SonarLint for Eclipse :http://www.sonarlint.org/eclipse/index.html. This Eclipse plugin supports two modes :The "Standalone mode": which is the default one and which doesn't require to have any SonarQube server running.The "Connected mode" : which can be activated on-demand to make SonarLint using locally the same rules and analyzers that are used remotely by the SonarQube server to analyse the same project.
As I understand Eclipse Plugin for SonarQube has two options: local and remote analysis.What is the difference between them?Should we install Sonar Server locally to run local analysis?Will we see results of remote analisis in remote Sonar Server?
What is the difference between local and remote SonarQube Eclipse Plugin analysis?
You're stuck.To make a plugin check a file type, typically you would configure it to "claim" that file extension (Administration > General Settings > [language] > General > File suffixes). But each file extension can be claimed/declared by one, and only one plugin. Presumably in your attempts to make this work, you've configured both plugins to claim the.xmlfile extension. Hence the error you're seeing.Short of some custom development on your part, you're not going to get this to work.On the topic of custom development, it's worth noting that the Java plugin does check some.xmlfiles without claiming/declaring that file extension. So if you go this route, you probably want to take a look at how the Java plugin gets this done.But because files with unclaimed extensions are by default not indexed (and therefore not checkable) these Java plugin rules only work when eitherthe XML plugin is installed to declare the.xmlfile extension and have those filed indexed and therefore available to the rulesAdministration > General > Analysis Scope > Files > Import unknown filesis set totrue. (It defaults tofalse.)UPDATEChanges to the way the scanner works means that even files with unclaimed extensions are now indexed if an analyzer raises an issue on them. So, e.g. you no longer need SonarXML installed before SonarJava can raise issues on pom.xml files.
I want to applysonar text pluginandsonar jproperties pluginto scan properties/txt/sh/xml files via regular expressions, but received such error[ERROR] Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.1.1:sonar (default-cli) on project test: Language of file 'src/main/java/test.properties' can not be decided as the file matches patterns of both sonar.lang.patterns.jproperties : **/*.properties and sonar.lang.patterns.text : **/*.properties,**/*.txt -> [Help 1]How to avoid this problem and fix limitation of sonar?
How to use two different plugins on one type of file in SonarQube
See:http://docs.sonarqube.org/display/DEV/Adding+Coding+RulesThe broken link on the PL/SQL plugin page has been fixed. Points to the very same page now. Thanks for reporting that.
I'd like to learn how to create custom rules for the SonarQube PL/SQL Plugin, however the link on the official Sonar website is "broken". Clicking on it opens a page with a "The page you are looking for does not exist" error. Does anyone know if it is possible to find documentation on this elsewhere?I know this might not be the place to ask these types of questions but I don't know where else to ask and maybe someone will know. Thank you.This is the link about the plugin in, clicking on "custom rules" from the Advanced Usage section leads to the non existent page error.http://docs.sonarqube.org/pages/viewpage.action?pageId=6389850
SonarQube: Create PL/SQL custom rules
Yup, the UI is very confusing in this area, I struggled for quite some time before realising what to do.What you need to do is first search for a string in the search box ("sonar" is a good query), and then the list will be populated with all users/groups matching that query. You can then assign them permissions as you see fit.
I am using SonarQube (SQ) 6.0 community version and trying to setup authorization using groups and project permissions. There doesn't appear to be a way to assign permissions to a created group, even though the defined SQ groups have permissions assigned to them. What I wanted to do was assign permissions to a created group via the Admininistration->Security->Global Permissions process. But this action only returns the Anyone and sonar-administrators defined groups based on the usage of the internal API api/permissions/groups, which only returns groups with permissions. This same API is used in the action Administration->Projects->Management->Actions->Edit Permissions. From this last action the goal was to remove permissions for this project from the Anyone group and allow permissions from a created group (which would apply to the users in that group). But that doesn't seem possible. I've looked at permission templates, but that doesn't seem to allow association to a group. What I'm really attempting to do is a common RBAC process, which SQ does not seem to support. Is there a solution in SQ for this capability?
SonarQube 6.0 authorization using groups
Design-related services weredropped in version 5.2.
I liked the package design (later renamed to file design) feature in SonarQube to detect cycles inside my application. See this old blog post:http://www.sonarqube.org/fight-back-design-erosion-by-breaking-cycles-with-sonar/In the recent 6.0 version of SonarQube I can't find this anymore, there is a design plugin but that only seems to be supported until version 4.5.6. Am I overlooking something or is the file design feature just gone?
Status of package / file design feature
Currently in SonarQube (6.0 and LTS 5.6 as of this writing), editing Quality Gates (or Quality Profiles) requires a global permission calledAdminister Quality Gates(orAdminister Quality Profiles). This permission is usually locked down to a few select admins (e.g. on sonarqube.com) as the impact spans across all projects (including those that you do not own).With respect to Quality Profiles: allowing some users to edit their own profiles is a frequently discussed topic, you should trackSONAR-1330for the full details on this.
I can't find the option to create custom QG on sonarqube.com instance used by my open source GitHub project. Is it non-customisable for open source projects at all?
Custom Quality Gate for open source project
This is a known bug, and will be fixed:https://jira.sonarsource.com/browse/SONARCS-601
I just upgraded my SonarQube instance to 5.6.1. I've got a single C# solution being analyzed currently. I re-analyzed my project and noticed on my dashboard that all of the widgets that were showing me complexity/class aren't working properly.For example:TreeMap: I had a treemap where the complexity/class was the size factor, and it now shows me the error message 'treemap.all_measures_undefined'.Hotspot: I had a hotspot measure that showed me the 10 biggest offenders for complexity/class and now it says "No Data" in design view and just doesn't appear in non-design view.Complexity: the complexity widget shows me total complexity and complexity per file, but doesn't show me average complexity per class.Why does complexity per class appear to have fallen off?SonarQube 5.6.1C# plugin 5.3.2MSBuild Scanner 1.1
SonarQube 5.6.1 complexity per class measure failing
After struggling with this issue for some weeks now, I identified the problem and found the solution. The problem was with redirects, which due to my Reverse proxy setup, didn't work. I had followed the instructions for setting up the proxy, however it still failed. The solution was found on MSDN,https://blogs.msdn.microsoft.com/visualstudioalmrangers/2016/06/04/running-sonarqube-behind-an-iis-reversed-proxy/, which included a small addition to the sonarqube instructions, as it beside from the inbound rewrite rule, also included an outbound rule.
In connection with setting up SonarQube, I have installed and configured GitHub Authentication plugin, to allow users to use their GitHub credentials. Now when trying to login with a GitHub account (Pressing the "Login with GitHub" button, SonarQube redirects to "https://servername/login/oauth/authorize?..." which results in an error page, stating "The page you were looking for doesn't exist.".It seems that the correct path should be "https://github.com/login/oauth/authorize?...", instead of pointing to my SonarQube server. Could it be that the plugin fails to resolve the URL for GitHub and using a blank url instead? Thereby creating a link to "/login/oauth/authorize?..."?I have checked both the properties table in the database and the configurationfile for the property "sonar.auth.github.webUrl" - both are set to "https//github.com"
Using SonarQube GitHub Authentication Plugin results in "The page you were looking for doesn't exist."
First you need to have the appropriate plugins installed in your SonarQube server, so C# if it's not there already.Then you'll install SonarQube Scanner for MSBuild on the Windows machine, and run the analysis there because full/proper analysis of .NET code requires MSBuild and that's not gonna work on Linux. Don't worry, there's no problem running the analysis on a different machine than the one that hosts your SonarQube server.Essentially, you set up a build step to eavesdrop on the MSBuild execution, then you run the analysis based on the data gathered during the build.Full detailsin the docs.
I need to perform static code analysis of .NET project using SonarQube.I have 2 machines:Linux with Sonar ServerWindows with .net code and its tools (Fxcop, ...)I need to perform analysis on Windows and push the results to Sonar Server on Linux machine.Can someone help me with this?
Analyse .NET code with SonarQube on Linux platform
The last time I setup Sonar, I am pretty sure the sonar.exclusion property worked as expected... Perhaps your naming pattern is a little off. For example, how about a ** at the end rather than *. Seethis answerfor examples and answers when using naming patterns.
I have a ASP.net project that i need to run SonarQube analysis on and i have configured it with Jenkins to run the analysis. The analysis is running fine but it is including the bower_components and node_modules i have in the project. The way the project is structured there are multiple node_modules and bower_component folders in the projects folder structure. So i need to exclude them all in a pattern. I have added aSonarQubeSettingsection to the .csproj file and i have the current values for exclusion.<Target Name="BeforeBuild"> <ItemGroup> <SonarQubeSetting Include="sonar.exclusions"> <Value>**\main-built.js,**\template-build.js,**\kendo*.js,**\bower_components\*,**\node_modules\*</Value> </SonarQubeSetting> </ItemGroup> </Target>Using**\bower_components\***\node_modules\*did not work and the libraries are still picked up and scanned. How can i exclude folder (in my case node_modules & bower_components) content regardless of its location in the directory structure in sonar?
Excluding contents of a folder anywhere in directory tree from analysis in Sonar
SonarQube does not allow to group several existing projects into a single one. So you won't be able to achieve your 2 goals.The only thing you can do is to update the key of each existing project on SonarQube (for instance, you can add "_OLD" suffix on their key). This will allow you to:Keep the history for those projects - but they won't evolve any longerMake it possible to analyze successfully the new multi-module projectTo know how to update project key, please readthe documentation.
We're in process of migration of a single Maven project that has been analyzed in SonarQube 4.5.4 into a multi-module Maven project.The SonarQube analyzing is going to be migrated to the Parent project so that the old and new modules would be analyzed all-in-one.During the analyzing we receive an error: 'The project '...' is already defined in SonarQube but not as a module of project '...:Parent''The obvious solution is to remove the old project from SonarQube, however it means removal of all historical information.How can we achieve both goals:migrate to multi-module projectkeep history of analyzing of the existing project (that should be a child of the new multi-module project) ?Thanks.
SonarQube and migration to multi-module project with preserving history
The error is telling you that SonarQube Scanner was unable to create the necessary temp files to run the analysis. You should check file existence and permissions.
I successfully run the demo project with SonarQube + SonarLint for Eclipse. Then I add to this project java classes to analyze and try to re-run but Solar keeps to throw the error - "Unable to create root temp directory. " The LocalHost is up. Once again, the first demo run was successful. For more information, please, take a look on print-screen.The successful demo run :https://gyazo.com/770ac87cd20cd2729c96ec5518244d47Error from Eclipse ( I also install sonarLint plug-in ) :https://gyazo.com/3002ef55d3e306fc7a73683156c69d66Error from CMD ( I'm using Windows 10 ) :https://gyazo.com/e56480776778d649d4ad029392d1e35d
Re-running SonarQube failed. "Unable to create root temp directory"
There is an openissueregarding this. sonarqube uses jacoco code coverage. It shows the number of branches covered or missed but it doesn't show which one. I think you have a similar situation
I have a java project whose coverage results are being pushed to SonarQube but I'm having a problem with a line in one of my classes. It says that only 1/6 branches are covered for the below line, however for the life of me I can't figure out what the 6 branches are, or why only one is being tested.I have a test where datacenters is a list, and where datacenters is a string, so surely that would be there are at least 2 branches covered. I can't figure out what the other branches might be besides it being an instance of neither, or why it says only 1 branch is being covered.If anyone has a suggestion as to what the other branches might be, or if this might just be a bug, please let me know.assert (datacenters instanceof List || datacenters instanceof String);
How to determine what the branches are that are listed in SonarQube
This has nothing to do with your scanning method. It's about the version of the Java plugin in use. I'm willing to bet that when you upgraded SonarQube you also - advertently or inadvertently - upgraded the Java plugin too.Each new version of a language plugin introduces new rules and, typically, improves the underlying detection methods. Or at least that's the intent. It does happen that in taking two steps forward, they sometimes take one step back.If you feel you're seeing false positives (as you note in your comment) you should raise them at theSonarQube Google Group.
I have this buildsystemGradle 2.14SonarQube 5.6.1sonarqube gradle plugin 2.0.1My sonarqube.properties look like this:property "sonar.host.url", "http://myserver" property "sonar.login", "mylogin" property "sonar.sourceEncoding", "UTF-8" property "sonar.projectVersion", project.ext.sonarVersion property "sonar.java.source", "1.7" property "sonar.java.target", "1.7" property "sonar.sources", "src/main/java" property "sonar.exclusions", "src/generated/**" if (file("$projectDir/src/test/java").exists()) { property "sonar.tests", "$projectDir/src/test/java" } if (file("$projectDir/build/intermediates/classes/debug/").exists()) { property "sonar.java.binaries", "$projectDir/build/intermediates/classes/debug/" property "sonar.binaries", "$projectDir/build/intermediates/classes/debug/" } if (file("$projectDir/build/test-results/debug/").exists()) { property "sonar.junit.reportsPath", "$projectDir/build/test-results/debug/" } def sonarLibraries = configurations.compile.join(",") property 'sonar.libraries', sonarLibraries property 'sonar.java.libraries', sonarLibraries property 'import_unknown_files', true./gradlew sonarqube -Dsonar.password=xxx runs.But I see issues that are not issues, like "unused private constructor". This has not been an issue before I upgraded to 5.6.1 and the sonarqube plugin. It appears as if the .class files won't be inspected. Does anybody has the same issues with Gradle/SonarQube and Android?
SonarQube 5.6 Android Gradle
The way complexity is computed should be changed by next plugin version (seehttps://jira.sonarsource.com/browse/SONARJS-729).
i have some problems with complexity in my javascript. It looks like:function mainFunction(scope, element) { var eventHandlerMap = { 'firstEvent': firstEventHandler, 'secondEvent': secondEventHandler, ..... }; function firstEventHandler(element) { if (element) { //some code } else { //some code } } function secondEventHandler(element) { //some code } //and other EventHandler functions }Now mainFunction has complexity of 41, but my sonar allows no more than 10. I dont good at javascript and dont have ideas how fix it.
How procced cyclomatic complexity in such javascript code?
Are these values being placed in a command line call? Depending on the situation spaces in path names can cause problems with tools. If you can, try installing Java to a folder that does not have spaces. As an alternative you could also use the Windows short name in JAVA_HOME for "Program Files". This is usually "PROGRA~1".
We have the following value for JAVA_HOME: C:\Program Files\Java\jre1.8.0_91We can navigate via Windows Explorer to that location, and you can get to "\bin\java.exe". We've also done a cd to %JAVA_HOME% to verify that resolves correctly.However, the scanner step in TeamCity is throwing "ERROR: JAVA_HOME exists but does not point to a valid Java home folder. No "\bin\java.exe" file can be found there."I've noticed that the SonarQube plug-in for TeamCity has a JDK override where you can pass the location of the java home. Does the manual process have the same? We cannot use the TeamCity plug-in because it is not correctly sending the unit tests results to the web app, hence our switch to the manual process.Any help you can provide would be greatly appreciated!
Scanner Says JAVA_HOME exists but isn't a valid Java Home
Build steps are calledbuildersin the XML configuration, so you need to replace'steps'by'builders':job('example') { configure { it / 'builders' << 'hudson.plugins.sonar.SonarRunnerBuilder' { properties '' javaOpts '' jdk '(Inherit From Job)' project '' task '' } } }
I would like to configure Jenkins job using JobDSL. I define a variablesonarProperties. ButInvoke standalone analysispart is missing. Here is my configuration:job('example') { def sonarProperties = '''\ sonar.projectName=example sonar.projectVersion=1.0 .. .... '''.stripIndent() configure { sonar -> sonar / 'steps' << 'hudson.plugins.sonar.SonarRunnerBuilder' { properties ("$sonarProperties") javaOpts '' jdk '(Inherit From Job)' project '' task '' } }
Configure Jenkin's SonarQube section using Job DSL (SONAR part missing)
I do this regularly as the servers I run on are only provisioned for 30 days. You don't specify the operating system, but for windows it's as simple as:Stop "old" serviceCopy folder from old machine to new machineInstall the windows service with the java wrapperStart the serviceIn my case I change the DNS alias after the service is running
Need to migrate my SonarQube to a new server (not the remote DB, just the application). Is there any special tool offered by Sonar to do so? is it just a matter of pointing this new installation (if possible) to the old DB?Sonar v5.2 MySQL 5.xThanks!
How to migrate SonarQube to new host
SonarQube C# docs says "Drilldown on Test Execution Results is not supported Tests execution results will be displayed on project level dashboards."There is an open ticket about this problem:https://jira.sonarsource.com/browse/SONARNTEST-17and this another one is also worth to look:https://jira.sonarsource.com/browse/SONARMSBRU-233So now I think it is a limitation of the C# plugin and not a bug or configuration issue.
I clonedhttps://github.com/SonarSource/sonar-examples.gitthen opened a command prompt under SonarSource/sonar-examples/tree/master/projects/languages/csharp and run the following commands (based on "Unit Test Execution Results Import (C#, VB.NET)" @ docs.sonarqube.org/pages/viewpage.action?pageId=6389772):MSBuild.SonarQube.Runner.exe begin /k:"org.sonarqube:csharp-simple-sq-scanner-msbuild" /n:"C# :: Simple Project :: SonarQube Scanner for MSBuild" /v:"1.0" /d:sonar.cs.xunit.reportsPaths="%CD%\XUnitResults.xml" MSBuild.exe /t:Rebuild packages\xunit.runner.console.2.1.0\tools\xunit.console.exe XUnitProject1\bin\Debug\XUnitProject1.dll -xml %CD%\XUnitResults.xml MSBuild.SonarQube.Runner.exe endUnder metric/tests/list I get "Unit Tests 1" and that is OK but beneath it the list is empty:Why?The relevant part from console:INFO: Sensor org.sonar.plugins.csharp.CSharpUnitTestResultsProvider$CSharpUnitTestResultsImportSensor INFO: Parsing the XUnit Test Results file C:\workspace\SonarSource-sonar-examples-92828b2\projects\languages\csharp\XUnitResults.xml INFO: Sensor org.sonar.plugins.csharp.CSharpUnitTestResultsProvider$CSharpUnitTestResultsImportSensor (done) | time=15msSonarQube 5.6 w embedded h2 (extra plugins: C# 5.3, StyleCop 1.1)
"Unit Tests 1" but beneath it the List is empty
It can be done if the SVN supports hooks or alike.For example, Git allows writing hooks for the commits/push/receive[server side] ;First downloadsonarscannerCreate a git pre-push hook on the developer's machine to run sonarscannerrun sonarscanner and you will see the result on the stdout.if sonar-scanner | grep '[ ]+[0-9]* blocker$' thenexit 1elseexit 0fiUsing this you can decide whether to accept or not the checkin (if there are blockers etc.)
I need to run Sonar analysis on Java file before committing code to svn. Is there any mechanism to ensure that code having sonar issues doesn't gets checked into svn unless all sonar issues get resolved.
Sonar analysis prior to code check in
You have to change theLeak Periodof your project.Default value isprevious_version, which means you get the delta between last analysis and last version (defined in sonar-project.properties for example).Based on your example, you want the delta between each analysis, so you need to set up the parameter toprevious_analysis.Solution 1 : Setting using web interfaceThe easiest way to change the parameter is to use the sonar web interface as described in the documentation :change the Leak PeriodSolution 2 : Setting using configuration fileIf youcan't or don't want to use web interfaceto set this parameter, use the configuration filesonar-project.properties.Create or editsonar-project.propertiesinto the root folder of your projectAdd the following line :sonar.timemachine.period1=previous_analysisSolution 3 : Set as a parameter of command lineThe last solution is to add an argument of the command line to take into account the parameter. You have to add the argument-Dsonar.timemachine.period1=previous_analysisto your command line.SonnarQube scanner options are defined in themanual page
is there a manner, using sonar runner, to see only the delta of the issues? For delta I mean only the issues introduced by recent changes? If yes how? Thanks and best regards
Sonar runner, seeonly newly introduced issues
This solution might help you. Basically, it exports information between databases and / or DBMS using simple scripts. BTW, it avoids duplication if projects already exist in the destination.https://github.com/awltech/sonar-data-migratorTo use, follow below steps.Download (or clone) git projectRun maven install on the project, it will create bineries zip under target/assemly folder.Extract zip on machine from where you have access to both sonar server DB.Do sonar analysis on both source and target sonar with same code.Configure source and target db details in database.properties fileRun init.sql on target sonar db, it will create temporary tables to store migrated data detailsSet proper java path in script.bat file (you can use script.sh for executing on linux) .UsageRun the bat/sh script passing users as argument for migration of usersRun the bat/sh script passing data as first argument and project key as per "Key" value in sonar report as second argument. If key is not passed, it will work for all projects in db.This script will migrate below things:Users (default sonar-users role is assigned to all migrated users)Action plans associated to the projectAll changes to issue like assignee,severity,status,action plan and resolutionAll reviews/comments added to issueAll false positive dataMy migration was similar to yours (two databases in PostGre), step by step worked! :)
Need to know how we can migrate data post change of database collation change. Basically, below is what I am planning.Get a new DB with new collation which is a requirement for Sonar (Latin1_General_CS_AS). Collation on our existing DB is - Latin1_General_CI_ASSetup the Sonar service and point to the new database with new collation. This will create new tables required for Sonar on the database.Migrate data from old database to new database without changing collation.I can import data using SELECT INSERT but I ran into issue where Sonar service didn't start post this.(SonarQube service not starting)We had to truncate and drop tables and re-create them. Can someone advise how we can migrate data?I am aware of Sonar DB copy tool but I believe this is only for Enterprise version. (http://docs.sonarqube.org/display/SONAR/Sonar+DB+Copy+Tool)
Sonar data migration post Database collation change
The root cause here is that FxCop uses information from the PDB file for providing location information. However, the PDB only contains information that would be useful for debugging scenarios, which means that FxCop rule violations that are associated with non-executable code (e.g.: field declarations or interface definitions) will not have location information available. (FWIW, there is an open SonarQubeissuefor addressing this, but it would be non-trivial to accomplish unless SonarQube were to directly examine the source files to attempt to locate the field declaration. I rather suspect they might not bother given that it simpler to address via a Roslyn analyzer.)Further problem is in SonarQube 5.4 the same rule is activated but web app does not show the error.That's because older versions of theC# pluginfor SonarQube completely ignored FxCop violations without location information. This was addressed inversion 5.2of the plugin, which only became in early May 2016 (and is presumably what you used when you installed SonarQube 5.5). It is compatible with version 5.4 of SonarQube, so you should be able to use it with your older installs if you like.
I'm tring to run analysis on SonarQube, using an FxCop custom Rule. In SonarQube 4.5.7 I add the rule to the set of rules, I activate it and then run the analysis. To run the analysis I use the sequence of following commands:1) MSBuild.SonarQube.Runner.exe begin /k:my.project.C-Sharp-ConsoleApp /n:C-Sharp-ConsoleApp /v:1.1 2) "C:\Program Files (x86)\MSBuild\14.0\Bin\MSBuild" /T:Rebuild 3) MSBuild.SonarQube.Runner.exe endI see that the rule is executed, because when I run the second command I read the following part of log:... (RunCodeAnalysis target) -> MSBUILD : warning CR1000: MyRules : Field 'CSharpSortNames.m_variabile' is not in Hungarian notation. Field name should be prefixed with 's'. [C:\Users\Alessandro\Documents\Visual Studio 2015\Projects\C-Sharp-ConsoleApp\C-Sharp-ConsoleApp\C-Sharp-ConsoleApp.csproj]My custom rule checkID is CR1000, and after the third command, I see that an error of this rule is founded, but the web app doesn't let me see where. For all other errors the web app let me see the precise line where is the error by a link to the .cs file. For my rule it doesn't.Anyone can help me about this? Further problem is in SonarQube 5.4 the same rule is activated but web app does not show the error.
FxCop Rule in SonarQube 4.5.7 on C# project
You're hitting a known bug in SonarQube 5.5:SONAR-7589. Until 5.5.1 or 5.6 getsreleased, you can temporarily use SonarQube 5.6-RC1 (availablehere).
I had an installation of SonarQube 5.4 running on Ubuntu (latest) against a SQL Azure database.Since the upgrade to 5.5 it's not working anymore.For the upgrade I deleted the data/es directory and updated the new conf file with my settings as advised.The collation was wrong at first so I decided to try with a new db of collation SQL_Latin1_General_CP1_CS_AS.Now it's looking for database_firewall_rules (table?) but cannot find it.Any idea how I can solve that? Any table I could create?Thanks!
SonarQube SQL Azure Database support broken with 5.5?
Values in the technical debt pyramid was the amont of technical debt for each characteristics. As characteristics have beenremovedin SonarQube 5.5, I would not recommend you to try to use theses values.If you need technical debt values per type for instance, you can use theapi/issues/search WSusing parameters 'facetMode=effort' and 'facets=types'.
Im trying to access to default technical debt pyramid values, the chart that appears on dashboard, using the web service api that sonarqube provide.I don't have SQALE plugin installed, i just need those default values.there is any way to access to these values using the web service api?.Thanks.
sonarqube how to access to default technical debt pyramid values from web service api?
The rules you name are all template rules, i.e. rule "cookie cutters" from which you can stamp many rule variations. Unfortunately, rules created from templates, a.k.a. "custom rules", aren't properly handled in profile backup and restore.This is currently scheduled for the 6.x series. The Jira ticket isSONAR-5366.
I tried to create an exact copy of of our default SonarQube quality profile by clicking on the "Copy" link in the "Quality Profiles" page, but some of the rules are not copied. We use SonarQube version 4.5.6 and the profile I tried to copy does not inherit from any other profiles.According to theSonarQube documentation,the new profile is an exact copy of the original profile, including inheritance (parent) relationships. However, my copied profile is missing the following 9 rules out of 487 and I don't see any reason why (they are all 'checkstyle' rules, but there's many more with the same label that got copied correctly):Boolean Expression Complexity (checkstyle)Comment pattern matcher (checkstyle)Constant Name (checkstyle)Hidden Field (checkstyle)Inner Assignment (checkstyle)Local Variable Name (checkstyle)Magic Number (checkstyle)Member name (checkstyle)Static Variable Name (checkstyle)
SonarQube: Copy of Quality Profile is Missing Rules