Response
stringlengths
8
2k
Instruction
stringlengths
18
2k
Prompt
stringlengths
14
160
As far as I know Sonar uses JaCoCo. I personally reconciled with the fact that tests take a lot of time under sonar, so we run sonar as a part of nightly build only while regular tests are running after each SVN commit.I am sorry if my answer does not satisfy you...
I am investigating the unit test time execution in Sonar, and there are very big differences between the tests run from maven and the tests run from Sonar.For example, for a single Java test class I get:just maven: 1.5 secmaven with cobertura: 5.7 secsonar: 16 secWhy is the difference between maven and Sonar so big? What other instrumentation does Sonar make that adds 10 sec to the execution time?
Very large unit test execution time in Sonar
If you have a clean database with no tables, then Sonar will create all the required tables the first time you start it.To know more about the tables, you can have a look at this DDL file that we are using for our tests:https://github.com/SonarSource/sonarqube/tree/master/server/sonar-db-core/src/main/resources/org/sonar/db/version/schema-h2.ddlThe project split, but the 4.5.5 version of the DDL orginally linked in the answer can be found here:https://github.com/SonarSource/sonarqube/blob/4.5.5/sonar-core/src/main/resources/org/sonar/core/persistence/schema-h2.ddl
This question already has answers here:Closed11 years ago.Possible Duplicate:What is the sonar database structure?Just want to ask which tables will be created after sonar get connected to the database? And also tables used to store the information like "Lines of code" "Classes" "Comments" etc. Could any one give me some documentation about these? Thanks
Tables created by sonar in the database [duplicate]
You could also use the REST-API to get the violations (something like 'http://sonar-host/api/violations?resource=1&depth=-1&priorities=BLOCKER,CRITICAL,MAJOR') to get the interesting violations and then use 'svn annotate' to get the relevant annotions and therefore the user. That is what I did, and in the meantime it works well.
Does anyone know if there is SONAR extension for filtering violations by user/author who introduced them ?Idea is to pick a user, and SONAR would list all violations made in the code by that specific user.Maybe some ideas could be provided if it is possible to achieve such functionality ?Thanks.
SONAR code violation filtering by user
Have you set thesonar.sourceEncodingparameter to UTF-8? If not, try setting it to Cp1252.Cp1252 is the default encoding on windows machines. Unfortunately it's not completely compatible with UTF-8 (the default for most Java installations). Some windows based editors will write incompatible characters that trigger this kind of Java read error.One common offender is the "£" symbol, which is part of the extended ascii character set. It therefore should be written as a two byte character under UTF-8 :-(
I'm trying to run Sonar 2.12 with Ant runner. Not using maven,But sonar target fails with an exceptionUnable to read and import the source file : 'D:\JUnitDocletPoC\iLog_Client\src\ ava\com\junitTest\NameFinder.java' with the charset : 'UTF-8'. at at org.sonar.plugins.squid.JavaSourceImporter.importSource(JavaSourceImporter,java.) at at org.sonar.plugins.squid.JavaSourceImporter.parseDirs(JavaSourceImporter,java) at org.sonar.plugins.squid.JavaSourceImporter.analyse(JavaSourceImporter.java) at org.sonar.plugins.squid.JavaSourceImporter.analyse(JavaSourceImporter.java)This fails at all the java source files and charsets and not specific to any file/charset.Can someone help ?
Sonar 2.12 unable to read and import source file
No it's not possible with Java runner. Only Maven plugin and Ant task support project structures with modules.Note that the modules of C# projects are automatically created from the VisualStudio solution file, even if the Java runner is used.
I have a Java project which consists of a couple of modules. I am using Sonar to statically analyse my code. Currently I am using sonar-runner to analyse each of the modules, and they appear as different Projects in the main page of Sonar. I would like to see the main project name on the main page, and, once I will click on it, and than on "Components" - to see all of it's modules as sub-projects - just like it appears here:http://nemo.sonarsource.org/components/index/308832
Sonar - how to create sub projects with sonnar-runner
For theSonar Eclipse Plugin, make sure there is no side effect with the Eclipse proxy setting.As illustrated inthis bug report:Connection via proxy works fine - tested in real life, but looks like "Test connection" button doesn't work.So the connection might work fine, but I don't see that correction in thatlatest release notes.The OPRayoumareports:Eclipse - > Window-> Preferences-> Network Connections.PutActive Providerto "Manual".For theschema "HTTP"makeEditand put inhost: "127.0.0.1" and inport9000.Re-test the creation of the server Sonar under Eclipse and that works!
I use Sonar 2.4.1, Maven 2, Eclipse SDK 3.5. Sonar is up and running athttp://127.0.0.1:9000.I've installedSonar Eclipse Pluginand when i try to add a sonar server and i click "Test connetion" button (http://localhost:9000with or without user and password) i don't get "Connected successfully".Waiting for your answers.
Sonar Eclipse Plugin - "Test connection"
A change in one line of code could generate a bug elsewhere, similarly for code smells, security hotsposts and so on; so, generally speaking, Sonarqube always evaluates all the code base. What changed in this case is the number of code patterns, or "rules", used in the evaluation: if you examine theSonar Rules catalog for Javayou can see that some rules are labeled with the Java version (from "java7" to "java17"), this means that the upgrade to Java 17 has triggered new rules that were not used before.The "New Code" tab does not refer strictly to "new lines of code" but to issues that were not present X days ago, as explained by the last phrase in the description of the config parameter in your snapshot.
This one is a bit specific.We use SonarCloud, and the "New Code" settings for the relevant project is as following:I.e, on the main branch, only code newer than 2 days is considered.We had a merge request that made some changes, including switching from Java 11 to Java 17. It had a passing pipeline, so we merged, and bam! the analysis fails on the main branch:As you can see, the new code is correctly detected (it says "New code: Since 2 days ago", and only 9 lines are considered as new. However, I get 10 code smells, and they are raised on totally different and much older code. Those smells are typically related to Java 17 (Replace this usage of 'Stream.collect(Collectors.toList())' with 'Stream.toList()').So my question is: Does SonarQube ignore the new code definition when it's detecting a java version change? Is it because those issues are on old code but are considered new? And why was it not raised in the passing merge request analysis?
SonarQube raises error on old code after merging upgrade to java 17
If you don't want to implement any permission for the component, just declare empty string like this- android:permission=""
I got warning from sonarqube that saysImplement permissions on this exported component.Meanwhile the android documentation clearly state that any activity with<intent-filters>should be marked asexported="true".https://developer.android.com/guide/topics/manifest/activity-element#exportedIf an activity in your app includes intent filters, set this element to "true" to allow other apps to start it.For example, if the activity is the main activity of the app and includes the category "android.intent.category.LAUNCHER".If this element is set to "false" and an app tries to start the activity, the system throws an ActivityNotFoundException.This is some piece of code from the warning inAndroidManifest.xml<activity android:name=".example.WebViewActivity" android:exported="true" android:launchMode="singleTop"> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:host="example.com" /> <data android:scheme="http" /> <data android:scheme="https" /> <data android:pathPrefix="/app/Webview" /> </intent-filter> </activity>So, is there any suggestions for this issue ? thank you
Android exported rules with intent-filters
+50Assuming the latest SonarQube version, note that, as mentionedin this threadVersion 5.12 of our SonarJava analyzer deprecated use JaCoCo’s binary format (.exec files) to import coverage.As a replacement, we developed thesonar-jacocoplugin, which imports JaCoCo’s XML coverage report, and this is the preferred option now. IThat page illustrates how to include those reports for a maven or a gradle project. Again, it depends on the nature of your projects.
We had recently implemented SonarQube in our team and we have a dashboard configuredWe've been able to see some of the details but the line coverage and code coverage is 0 alwaysCan you advise what we're missing ? I've checked the configuration and all of it seems to be in place
SonarQube Configuration
For SonarQube to be of any significant value, it should be run as part of a build, after the code is compiled and unit tests are run. I frankly don't know if it's possible to run a scan without class files, but I don't suggest you try to pursue that.If you really only want to look at static analysis issues, I believe there is a "Sonar Lint" tool that runs in Eclipse or possibly other desktop tools.
I'm trying to check if there are any difference between an analysis with only source code and with source code and the .jar generated after compiling. If I delete the '-Dsonar.java.binaries' property I get this error:ERROR: Error during SonarQube Scanner execution ERROR: Your project contains .java files, please provide compiled classes with sonar.java.binaries property, or exclude them from the analysis with sonar.exclusions property. ERROR: ERROR: Re-run SonarQube Scanner using the -X switch to enable full debug logging.The command I'm using:sonar-scanner '-Dsonar.host.url=http://192.168.1.25' '-Dsonar.projectKey=org.javaProject:myProject' '-Dsonar.projectName=myProject' '-Dsonar.sourceEncoding=UTF-8' '-Dsonar.sources=src' '-Djavax.net.ssl.trustStore=/certs'Do you know if it is possible only to analyze source code without any binary file?
Why are Java binaries necessary in Sonar?
Your regex is a character class,[...]. It matches\W(chars other than letters, digits or connector punctuation (underscore in ASCII mode),\s(a whitespace) and a+char. The error you get is related to the fact that both+and whitespace chars can already be matched with\W.So your pattern is basically\W. Note it does not match underscores that are punctuation chars. If you want to remove all chars other than alphanumeric chars use[\W_]or\P{Alnum}pattern.More, you usually do not need to check for a match before replacing, the following should be enough:c=c.replaceAll("\\W+", "").toLowerCase(); // or c=c.replaceAll("[\\W_]+", "").toLowerCase(); // or c=c.replaceAll("\\P{Alnum}+", "").toLowerCase();Notethis warning will appear in cases where you specified a case insensitive flag/iand use character classes to match letters in either case like[zZ](/[zZ]/i). This is clear you need to replace the character class with a single letter,zorZhere.
I have implemented the regex expression to remove all the special characters with empty strings and remove space(if any), which is working fine in my code but sonarQUbe is complaining as this is non-compliant solution, Can anyone tell me how to fix this issueString c = "test10101010test%79%% %%% $$$ \t \n $$$#$@^$%~`***c 33"; Pattern pt = Pattern.compile("[\\W\\s+]"); Matcher match= pt.matcher(c); while(match.find()) { c=c.replaceAll("\\"+match.group(), "").toLowerCase(); } System.out.println(c);I am getting error at"[\\W\\s+]". Getting below error Remove duplicates in this character class.Can anyone suggest how to fix this issue?
SonarQube issue: Remove duplicates in this character class
Fromhttps://docs.sonarqube.org/latest/analysis/scan/sonarscanner-for-msbuild/:BuildBetween the begin and end steps, you need to build your project, execute tests and generate code coverage data. This part is specific to your needs and it is not detailed here.So,dotnet sonarscanner end /d:sonar.login="<TOKEN>"is not enough, we have to:dotnet sonarscanner begin /k:"project-key" /d:sonar.login="<token>" dotnet build <path to solution.sln> dotnet sonarscanner end /d:sonar.login="<TOKEN>".
I've created a .NET Core app with just 1 file - Program.csIt simply prints from1-100for (var i = 1; i <= 100; i++) { try { Console.WriteLine(i); } catch (Exception) { throw new Exception("This is a sample exception"); } }I've also setup SonarQube localy and ran my first scan using the commanddotnet sonarscanner end /d:sonar.login="<TOKEN>"It was success and I've got a report with CodeSmells (I'm conciously putting those to test SonarCube)But once I corrected the code and re ran the command, I'm getting weard errors from sonar scanner. What can be the reason?ERROR: Error during SonarScanner execution java.lang.IllegalArgumentException: Line 5 is out of range for file Program.cs. File has 4 lines.
SonarQube Not Updating Report - "Line 5 is out of range for file Program.cs. File has 4 lines"
After merging branch to master it is commit and in that case ${{ github.event.number }} it's evaluating to null and it occures error so i suggest you to use in this case ${{github.sha}} even you can have condition"-Dsonar.pullrequest.key=`if [ -z "${{github.event.number}}" ]; then echo ${{github.sha}}; else echo ${{github.event.number}}; fi`"
I am running sonar-scanner with help of sonarqube.yml this code code snippet from there- name: Run sonarqube run: sonar-scanner -Dsonar.scm.provider=git -Dsonar.login=${{ secrets.SONARQUBE_TOKEN }} -Dsonar.pullrequest.key=${{ github.event.number }} -Dsonar.pullrequest.branch=${GITHUB_HEAD_REF#refs/heads/} -Dsonar.pullrequest.base=${GITHUB_BASE_REF#refs/heads/} -Dsonar.pullrequest.github.repository=${GITHUB_REPOSITORY} -Dsonar.pullrequest.github.endpoint=${GITHUB_API_URL}Error after creating merge requestSonarQube Scanner version 4.2.0.1873SonarQube server version 9.0.1i see in executing log that is remaining -Dsonar.pullrequest.key= to be equal to undefinedRun sonar-scanner -Dsonar.scm.provider=git -Dsonar.login=*** -Dsonar.pullrequest.key= -Dsonar.pullrequest.branch=${GITHUB_HEAD_REF#refs/heads/} -Dsonar.pullrequest.base=${GITHUB_BASE_REF#refs/heads/} -Dsonar.pullrequest.github.repository=${GITHUB_REPOSITORY} -Dsonar.pullrequest.github.endpoint=${GITHUB_API_URL}
SonarQube: ERROR a branch analysis cannot have the pull request analysis parameter 'sonar.pullrequest.key'
FollowingDavid M. Karr'sadvice I looked through thecustom rules documentationand found this template;Track uses of disallowed classesOpening this template for configuration, there appears a note explaining that the rule parameters (in this case the class name) allows for regex - and explicitly advises to use regex when targeting packages.The custom rule withorg.apache.commons.lang.StringUtilspassed to the ClassName parameter achieved the desired results stated in the question. Additionally the entire package can be targeted withorg.apache.commons.lang.*TL;DRIn SonarQube DashboardClick "Rules" in main nav barSearch for "Track uses of disallowed classes"Select rule marked as "Template"At the bottom of the screen click "Create"Fill out Custom Rule configuration form, most importantly the ClassName field with either the fully qualified class e.g.org.apache.commons.lang.StringUtilsor use regex to target an entire package e.g.org.apache.commons.lang.*Create/SaveAdd and then Activate this new custom rule to a profile associated with the target project. (I'm sure there are other ways to do this part, this is what worked for my small project, by extending the Java SonarWay profile)
UsingSonarQube(version 3.0) I am trying to implement a blacklist of java libraries. For example I'd like for SonarQube to generate a code smell for any java file that contains an import fororg.apache.lang.StringUtilsI did find this rule:"Track uses of disallowed dependencies"however as previously stated I want to focus on the java file import statements themselves. e.g.import org.apache.lang.StringUtils; // SonarQube should generate smell for this line import java.awt.Component;Ideally I'd like to maintain a centralized list of deprecated/bug causing imports that would cover the following use cases:Alert developer their code changes include prohibited importsScan legacy code base for prohibited, potentially bug causing imports
Using SonarQube how would one implement a java import blacklist?
The Idea is same as mentioned @Sonarqube Security Docsunder the title "Reinstating Admin Access".My Solution:I had to spin up fresh Docker container in order to get the default crypted_password value. If you already know/have the crypted password value then no need to spin up fresh containers, just follow the below steps by replacing the crypted_password accordingly.Below crypted_password value belongs to admin.exec to postgres docker container :docker exec -it POSTGRES-CONTAINER-NAME bashInside Postgres Container, login with the Credentials and follow on screen instructions:psql -U sonar -WConfirm the Database and Users :select * from users;Output must show a Sonarqube Users Table.Then Update the password to default i.e. admin :update users set crypted_password = '$2a$12$2NA1PhmvfPVwdwq5WeQj.Opb0z4OGYP8s2yPMRRum18bGV5nJK86W', salt=null where login = 'admin';try login to Sonarqube server with default credentials,ID : adminPassword : adminTo learn more about @Sonarqube Security Docs.
I have lost the Sonarqube Server admin password, want to recover that, any support will be appreciated.Environment docker images:sonarqube:7.9.5-communitypostgres:12.5-alpineI have gone through the previously answered block but unfortunately nothing worked out.Best
SonarQube Admin Password on Docker Container with Postgress DB Engine
it turned out that i need to add the following line:sonar.typescript.tsconfigPath = tsconfig.app.jsoni hope the comment will help someone
I am new to Sonar Qube, and i am trying to check the code smells in an angular (typescript) app, but dont seem to detect the rule breaches.SonarQube version is the latest: sonarqube-7.9.3in my angular component i added this rule breach explicitly:var a = NaN; if (a === NaN) { // Noncompliant; always false console.log("a is not a number"); // this is dead code }When i run: npm run sonar, it displays no issues under http://localhost:9000/projects.my sonar-project.properties file has:sonar.host.url=http://localhost:9000 sonar.login=admin sonar.password=admin sonar.projectKey=test-app sonar.projectName=test-app sonar.projectVersion=1.0 sonar.sourceEncoding=UTF-8 sonar.sources=src sonar.exclusions=**/node_modules/** sonar.tests=src sonar.test.inclusions=**/*.spec.ts sonar.typescript.lcov.reportPaths=coverage/lcov.infoQuality Profile typescript is set to “Sonar way recommended)”I have noticed the following in the output:ERROR: Failed to find a source file matching path D:\temp\angularHelloWorld\hello-world-angular\src\app\app.component.ts in program created with D:\temp\angularHelloWorld\hello-world-angular\tsconfig.jsoni dont see anything weird in the tsconfig, Can you please help me what am i missing?Thanks
SonarQube not detecting Angular-TypeScript rule breach
ernest_k is right: (Thank you!)Strictly speaking, when you call component.getId() for the second time, you can't assume that it will give the same Optional instance you called isPresent() on.So I changed the code to:Optional<String> optionalId = component.getId(); if (optionalId.isPresent()) { String id = optionalId.get(); // ... }
I get the error message: "Call "Optional#isPresent()" before accessing the value"But as you can see in the image there is a isPresent() check right before that line.Is this a bug of SonarQube?-
SonarQube 8.1.0 is complaining about Call "Optional#isPresent()" before accessing the value
I fixed the problem by using run-sonar-swift.sh and updating my properties file like this:sonar.host.url=http://localhost:9000 sonar.login=admin sonar.password=admin sonar.projectKey=testSonar sonar.projectName=testSonar sonar.language=swift sonar.sources=. sonar.test.inclusions=*.swift sonar.exclusions=**/*.xml,Pods/**/*,Reports/**/* # Scheme to build your application sonar.swift.appScheme=TestSonar sonar.swift.appConfiguration=Debugyou need also to download this run-sonar-swift sh filerun-sonar-swift
I had a very strange problem when using sonar with my swift project. Although, I get usually 0 bugs and 0 vulnerabilities every statics have 0 values which really very strange. this my report:I had installed SwiftLint, OcLint and Xcpretty recording to the documentation below:Link sonar swiftThis sonar-project.properties structure:sonar.projectKey=testSonar sonar.projectName=testSonar sonar.project=TestSonar.xcodeproj sonar.projectVersion=1.0 sonar.host.url=http://localhost:9000 sonar.login=admin sonar.password=admin sonar.language=swift sonar.exclusions=**/*.xml,Pods/**/*,Reports/**/* sonar.swift.simulator=platform=iOS Simulator,name=iPhone X,OS=latest sonar.sourceEncoding=UTF-8 sonar.junit.reportsPath=sonar-reports/ sonar.swift.lizard.report=sonar-reports/lizard-report.xml sonar.swift.coverage.reportPattern=sonar-reports/coverage-swift*.xml sonar.swift.swiftlint.report=sonar-reports/*swiftlint.txtI also added the plugin for the swift version like so :To scan I installed using brew the sonarScanner. Finally, I run this commandsonar-scannerso It launch the scan and It work fine but no errors despite I made error like this: class ViewController: UIViewController {let var x = 3 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. }Any help please ??
sonar report with 0 bugs and vulnerabilities
when you install sonarqube via homebrew, it is installed at following location/usr/local/Cellar/sonarqubeThus sonar.properties file can be found at/usr/local/Cellar/sonarqube/8.0/libexec/conffolderIn order to change port of SonarQube, editsonar.propertiesfile by changing the value ofsonar.web.portto desired port number from9000
Where to find sonar.properties file in the sonarqube installed via homebrew to change the value ofsonar.web.port
Change port of SonarQube installed via homebrew
You should uncomment & modify the sonar.web.context property inside sonarConfig file :/opt/sonarqube/conf/sonar.propertiesExample :sonar.web.context=/sonar
I had installed the SonarQube 7.9.x LTS on a Linux virtual machine. When I start the Sonar it stop on loading page with spin load forever. Using "F12" on console tab, I got the error message:GET http://172.29.200.143:9000/js/vendors-main.m.d184ed05.chunk.js net::ERR_ABORTED 404Please, what should I do?
SonarQube stoped on loading page
Adding<SonarQubeTestProject>false</SonarQubeTestProject>in a propertygroup in .csproj in my project has worked for me
I'm running SonarQube 7.9.1 on Windows 10 64-bit via the StartSonar.bat script. My backing database is SQL Server 2017, and my startup config is all default except the JDBC connection string and credentials for SQL Auth.I started SonarQube and created a new project for my Selenium test harness solution, which contains some middleware assemblies targeting .NET Framework 4.5, a framework assembly targeting .NET Standard 2.0 that takes a dependency on the middleware, and some test assemblies targeting .NET Core 2.2 that take dependency on the Selenium framework and in some cases on a few of the .NET Framework 4.5 middleware assemblies as well.When I run an analysis of my solution like so:dotnet sonarscanner begin /k:"MyCompany.Selenium"; dotnet build; dotnet sonarscanner endThe middleware assemblies are all scanned so I can see the lines of code, bugs, vulnerabilities, code smells, etc as I'd expect but the actual framework code isn't analyzed at all:My guess is that somewhere SonarQube is deciding on my behalf that the framework project is a "test" project and doesn't need code analysis, but the info I found athttps://docs.sonarqube.org/latest/analysis/scan/sonarscanner-for-msbuild/for Detection of Test Projects indicates that project names ending in Test/Tests and MSTest projects are the only ones automatically flagged as such, and neither apply to my framework. Is there anything else I should be looking for?
SonarQube Not Analyzing .cs Files In .NET Standard 2.0 Project
Issue in integrating sonarqube analysis with Ci buildAccording to the error messageAPI GET ‘/api/server/version’ failed, it seems your Azure DevOps agent fails to connect to the SonarQube URL.If you are using Hosted agent, it could not access to your localhost SonarQube server. So, you have to use private agent.If you are using private but still have this issue, you should confirm your private agent could connect to SonarQube server.Check thesimilar threadfor some more details.Hope this helps.
I am trying to run sonarqube analysis with Ci build. I have added the tasks ‘Prepare analysis on Sonarqube’ and ‘Run Code Analysis’ in my vsts build definition . I am getting the below error upon queuing the build:[SQ] API GET ‘/api/server/version’ failed, error was: {“code”:“ENOTFOUND”,“errno”:“ENOTFOUND”,“syscall”:“getaddrinfo”,“hostname”:“sonarqube.sssss.com”,“host”:“sonarqube.ssss.com”,“port”:443}Sonarqube version I’m using is 6.1. Can anyone help me in finding why this issue is occurring .
Issue in integrating sonarqube analysis with Ci build
It turns out, request body format which SonarQube sends to Discord is not acceptable. It leads to bad request error. Below is logged response from Discord,{ "message": "Cannot send an empty message", "code": 50006 }To successfully post the message it must be in the specific format documentedhttps://discordapp.com/developers/docs/resources/webhook#execute-webhookThe solution to this could be a mediatory URL which parses the request body and hits Discord Webhook with excepted body params.
I want notification on my discord app after completing every scan in sonarqube. I have tried to configured my discord webhook URL in sonarqube webhook option but it getting 400 error code after scanning the code and not sending notification.Steps i tried :Created webhook URL from my discord chennel.Configured that webhook URL insonarqube > Administration > Configuration > Webhooks.Run code scan So that it send notification to configured webhook.But i am getting below error.Error:Last delivery of Spidey Bot Response: 400 Duration: 186ms Payload: .....Discord webohook screenshot attachedSonarQube Error screenshot attached
SonarQube doesn't send notification to Discord webhook
When adding new task which required agent capabilities you need to add it to the agent.The capabilities must be installed on the build servers where the agents are located.UPDATE:I just installed sonar qube on my test environment. I got the same exception as you did, fixed it by installing java and msbuild . Check,if those capabilities exists under your agent :
I've succeeded build with TFS 2015 Using MSbuild task. Now I've added Sonar qube tasks (SonarQube for MSBuild - Begin Analysis & End Analysis), find the Sonarqube settings below:1. What is the Project key & how do we get it? I just gave Project Name as key.Immediately on build trigger threw error/warning:There are issues with the request or definition that may prevent the build from running:No agent could be found with the following capabilities: msbuild, java, msbuild, java. Queue the build anyway?On Trigger Build further, Build failed with following errorNo agent found in pool which satisfies the specified demands: msbuild java msbuild msbuild java Agent.Version -gtVersion 1.94.0On cross-checking, i see that under General section in Build definition : Demand for MSBuild & java exists.2. Am i correct or missing anything/settings?I've configured Service Endpoint for SonarQube also. Find the screen shot below:Please suggest on my error & queries highlighted.
TFS 2015 No agent can be found with following capabilities: msbuild, java, sonar qube
You have to delete one or more projecs to get below the threshold of 250'000 lines of code so that the suspending of analysis is lifted. (Or, if the project you are analysing is the only one, delete this project) That is a kind of deadlock situation, your changes (skipping the .js-file) cannot be honored by the server, because he declined taking the analysis results due to being over the threshold.
I am running sonar-scanner msbuild on my vb.net project . Since i didn't provide sonar.language properties during analysis it has analysed the .js files too. And now I am getting the error "Analyses suspended. You reached your 250000 lines of code limit allowed by your current license.Go to License page." on the sonarqube dashboard .Now ,when i am running analysis by skipping the .js files though the analysis is successful the results are not getting reflected .What can I do to view new results of analysis on sonarqube dashboard ? Does deleting the project free-up that much lines of code , so that i can run analysis again ?Also, can we use sonar.language property in command line while running analysis using scanner for msbuild ?Thanks in Advance !!
How to resolve line of code limit issue in sonarqube?
The WS api/ce is for internal use (as marked). It is not an API and the report it expect may change its format anytime.To submit issues based on a third party linter, I advice you look at thegeneric issue import feature. You simply have to convert your JSON file to the format we expect.
I want to upload a json report made in R using lintr package to my SonarQube server. I'm making a POST taking advantage of the api/ce/submit command (You can find it inhttps://next.sonarqube.com/sonarqube/web_api/api/ce?internal=true). To do this i'm using Postman with this params:projectKey: XXprojectName: XXnamereport: lintr_out.jsonprojectBranch: testing-1.0This command create the Project in Sonar but it's not able to show the information of the report.Anybody knows how can i see the results of the report in Sonar properly? Thanks for all!
How to upload a report to SonarQube properly using SonarQube API
you can do this :curl "http://sq_instance:port/api/measures/component?metricKeys=coverage&componentKey=the_project_key"then you see :{ "component":{ "id":"AWmbujtw_he9c8fQXlqh", "key":"blablabla", "name":"Sample Application", "qualifier":"TRK", "measures":[ { "metric":"coverage", "value":"55.2", "bestValue":false } ] } }anyway you'll find all metrics keys here :https://docs.sonarqube.org/7.4/user-guide/metric-definitions/
Could someone help me to get the code coverage from sonar dashboard through curl REST API call? We are using the Sonar version as 6.7 and I am not able to find the REST call to fetch the same.
How to get the code coverage from sonar dashboard
years ago I did something like you request via a lot of scripting. But we had special formats for the statements.We had three different kinds of files:One SQL file to setup the latest version of the complete database schemaOne file for all the changes to apply to older database schema's (custom format like version;SQL)One file for SQL statements the code uses on the database (custom format like statementnumber;statement)It was required that every statement was on one line so that it could be extracted with awk!1) At first I set up the latest version of the database by executing from statement after the other and logging the errors to a file.2) Secondly I did the same for all changes to have a second schema3) I compared the two database schemas to find any differences4) I filled in some dummy test values in the complete latest schema for testing5) Last but not least I executed every SQL statement against the latest schema with test data and logged every error again.At the end the whole thing runs every night and there was no morning without new errors that one of 20 developers had put into the version control. But it saved us a lot of time during the next install at a new customer.
For below script written in.sqlfiles:if not exists (select * from sys.tables where name='abc_form') CREATE TABLE abc_forms ( x BIGINT IDENTITY, y VARCHAR(60), PRIMARY KEY (x) )Above script has a bug in table name.For programming languages like Java/C, compiler help resolve most of the name resolutionsFor any SQL script, How should one approach unit testing it? static analysis...
Unit testing SQL scripts
Assumingfindhere isFiles.find, what should work for you isfinal Path startPath = Paths.get(nasProps.getUpstreamOutputDirectory() + File.separator + inputSource.concat("_").concat(contentGroup).concat("_").concat(parentId)); BiPredicate<Path, BasicFileAttributes> matcher = (filePath, fileAttr) -> fileAttr.isRegularFile() && filePath.getFileName().toString().matches(".*\\." + extTxt); try (Stream<Path> pathStream = Files.find(startPath, Integer.MAX_VALUE, matcher)) { pathStream.forEach(path -> textFileQueue.add(path)); } catch (IOException e) { e.printStackTrace(); // handle or add to method calling this block }The reason why sonarqube is warning here is mentioned in theAPI noteof linked document as well:This method must be used within a try-with-resources statement or similar control structure to ensure that the stream's open directories are closed promptly after the stream's operations have completed.
Sonar qube is giving me the following errorUse try-with-resources or close this "Stream" in a "finally" clauseList<Path> paths = find(Paths.get(nasProps.getUpstreamOutputDirectory() + File.separator + inputSource.concat("_").concat(contentGroup).concat("_").concat(parentId)), MAX_VALUE, (filePath, fileAttr) -> fileAttr.isRegularFile() && filePath.getFileName().toString().matches(".*\\." + extTxt)) .collect(toList()); paths.stream().forEach(path -> textFileQueue.add(path));I dont have much understanding of java8. could you please help me to close the stream
Sonar-Use try-with-resources or close this "Stream" in a "finally" clause java8 stream
I was not able to get the HTML Report plugin to work, either. I found another way to create a report using theSonarQube Web APIto extract data in JSON format, which can then be converted to a csv file using Java and a JSON Conversion library (I useJackson). You can then open the *.csv with Excel and save.For example, with SonarQube server running locally, I use this URL to extract all unresolved issues with the tag "leak":http://localhost:9000/api/issues/search?resolved=false&tags=leak
I have installed Sonarqube 6.7.6 and sonar-scanner (sonar-scanner-3.3.0.1492-windows). I have analyzed my code and the results are at dashboard.Now, I need to export the report in XML or Excel or PDF format (Anything among these are fine).I have googled and found some answers like,To get an HTML report, set the sonar.issuesReport.html.enable property to true. To define its location, set the sonar.issuesReport.html.location property to an absolute or relative path to the destination folder for the HTML report. The default value is .sonar/issues-report/ for the SonarQube Runner and Ant, and target/sonar/issues-report/ for Maven. By default 2 html reports are generated: The full report (default name is issues-report.html) The light report (default name is issues-report-light.html) that will only contains new issues.But I have included these in my project property file, yet the report is not found.Can anyone please help me out of this ?
Export report from SonarQube_6.7.6
You can use//NOSONARon any offending line to ignore a wide range of sonar issues.Source:Sonar FAQ.
Sometimes, I don't what exception will catch, so I use Exception rather than dedicate exception. When I use sonarQube to check the code quality of my project, and sonarQube always reports generic exception should be avoided, use the dedicate one instead.So how to make SonarQube ignore generic Exception check?
How can I make SonarQube ignore generic exception?
Fixed my issue by adding in SonarQube, not only the squid:S00119 but also the what file pattern to search for. I only added squid:S00119 and that is why it wasn't enough. You need also to specify what file.
I keep receiving this issue (Build failure) when I add a random exclude in SonarQube.I don't know why this occurs and it still throws a build failure irrespective of what what I exclude.This used to work before I upgraded SonarQube from 7.4 to 7.5.[ERROR] Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.5.0.1254:sonar (default-cli) on project root: Unable to load component class org.sonar.scanner.phases.AbstractPhaseExecutor: Unable to load component class org.sonar.scanner.issue.ignore.scanner.IssueExclusionsLoader: Unable to load component class org.sonar.scanner.issue.ignore.pattern.IssueExclusionPatternInitializer: Exclusions > Issues : Invalid format. The first field does not define a resource pattern: ,squid:S00119,* -> [Help 1]
SonarQube - Unable to load component class
In order to use the SonarQube steps you have to define a token for an user who hasexecute analysisrights. You use this token as login; this is the preferred way (the password should be empty). See also theUser Tokendocumentation page.
I tried to integrate Sonar Scanner for Ms Build with Teamcity. But there is problem in finish analysis step. I configured SonarQube.Analysis.xml file with sonar.login, sonar.password and sonar.host.url as it is showed on sonarqube website. But it gives error.SonarQube Begin Analysis StepSonarQube Finish Analysis StepError logsI tried to restart server, clean caches, running msbuild on command line. And when I try to post a request to SonarQube url via postman, it was able to create project on SonarQube without codes and my credential worked well.However, when I try to run SonarQube on Teamcity, it gives "Insufficient Privilege" error.Do you have any suggestions?Thanks in advance.
Teamcity - Sonar Scanner for Msbuild "Insufficient Privilege" Error
sonar properties has these keys missing :sonar.tests=. sonar.test.inclusions=**/**_test.go
Problem Statement - SonarQube's dashboard does not show the Unit test matrix which should be available next to the Coverage matrixJenkins Plugin SonarQube Scanner -sonar.projectBaseDir=/home/jenkin/workspace/github.com/company/project/src sonar.projectKey=sonar_projectname sonar.projectName=sonar_projectname sonar.projectVersion=${BUILD_NUMBER} sonar.go.coverage.reportPaths=cover-all.out sonar.go.gometalinter.reportPaths=static-analysis.out sonar.go.tests.reportPaths=test-report.json sonar.sources=. sonar.sources.inclusions=**/**.go sonar.exclusions=**/vendor**, **/*.xmlNote: Offical Documenthttps://docs.sonarqube.org/display/PLUG/Go+Coverage+Results+ImportHere is a screenshot of the dashboard missing the unit test matrix:SonarQube Dashboard
Golang Unit test matrix not visible on SonarQube dashboard
That's a serious bug indeed. I just logged anissueso that it get fixed in the next version. Thanks for reporting it!As a workaround, you may use anolder version of the SSLR Toolkitwhich seems to work. It's based on an older version of the parser, so it could give different results in some cases.
I am trying to add a new rule for my Python project, so according to this source (Adding Coding Rules using XPath), I was trying to run sslr-python-toolkit-1.9.1.2080.jar from command line to view AST of a given piece of code but it exited with the following error:Error: A JNI error has occurred, please check your installation and try again Exception in thread "main" java.lang.NoClassDefFoundError: org/sonar/sslr/toolkit/ConfigurationModel at java.lang.Class.getDeclaredMethods0(Native Method) at java.lang.Class.privateGetDeclaredMethods(Class.java:2701) at java.lang.Class.privateGetMethodRecursive(Class.java:3048) at java.lang.Class.getMethod0(Class.java:3018) at java.lang.Class.getMethod(Class.java:1784) at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544) at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526) Caused by: java.lang.ClassNotFoundException: org.sonar.sslr.toolkit.ConfigurationModel at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ... 7 moreAm I missing something? How could I make it work? I'm quite new in SonarQube arena, so please excuse my naivety and help me to solve the issue. Thanks!
Error running Sonar SSLR Toolkit
It turns out thatsonar.javascript.lcov.reportPathis deprecated and that the replacement issonar.javascript.lcov.reportPaths. With that little change everything is reporting as expected.
I have a project I'm working on for my senior project. This project was bootstrapped with create-react-app, and I added some config to ensure that coverage reports are generate. I integrated the project with Travis CI, SonarCloud, and Heroku.I can't figure out how to get SonarCloud to read the lcov file that is generated on the Travis CI build.Project is here:https://github.com/tanichols/rental-property-calculatorTravis CI build is here:https://travis-ci.org/tanichols/rental-property-calculatorSonarCloud project is here:https://sonarcloud.io/dashboard?id=rental-property-calculator%3AmasterAny and all help is greatly appreciated.
SonarCloud coverage report from create-react-app tests
See comment under the original post. Sorry for bothering...Ok, sorry for asking. I'm just stupid. I had two very similar variable names and checked the wrong one... Shouldn't work longer then 8 hours :P Sorry for bothering you!
I use theValidateclass from the packageorg.apache.commons.lang3in my project to do nonNull-validation of variables (https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/Validate.html).I also use SonarQube for static code analysis and it always complains, when I use those variables afterwards, bc theymight be null there.Is there is a way to mark some methods as null checks for sonar? I would really like to avoid marking all occurences as false positives (this would not be an option really, since the analysis is integrated in my builds, before I have the opportunity to do so).Thanks in advance!
SonarQube with Validate class from Apache Commons Lang3
The SonarQube 7.2 Developer Edition($) (E.T.A. early June 2018) will include a security rules to detect SQL injection vulnerabilities.
We are using sonarqube and we love the way it works. we are trying to extend sonarqube to enhance in security aspects also. I tried to find some security plugins for sonarqube 6.x to detect vulnerabilities for Java language. But I couldn't find any plugins. I wonder, if there is any plugins for finding vulnerabilities in sonarqube. So
Security plugins for Sonarqube 6.7x
You just need to add.mjsto the list of file extensions. You can do that in the project (or global) settings:You can also set this configuration via the "sonar.javascript.file.suffixes" key on the "sonar-project.properties" file. For example:sonar.javascript.file.suffixes=.js,.jsx,.vue,.mjs
I can't seem to find this answer anywhere.Does SonarQube currently support ES modules (.mjs) files?This is a Node.js (v9.11.1) project.As of now, I'm not sure if it's a configuration issue on my end, or if it's just lack of support, but it only recognizes and analyzes.jsfiles.
ES Modules (.mjs) support in SonarQube
This is not a supported use-case at the moment. You will have to split the analysis into 2 projects.
I'm trying to setup a Multilanguage project in SonarQube with Jenkinsfile consisting of a Java and a C# part. Every part works fine for itself in SonarQube.But when I run the SonarQubeScanner and afterwards the SonarScanner for MSBuild with the same ProjectKey and Name, the Project will be overwritten, so I just will see the C# part in SonarQube.Is there a way to get C# code and Java code into one single SonarQube-project?
SonarQube Multilanguage project for C# and Java
The quality profiles shown on Project homepages are those last used in analysis of the projects. Run a new analysis (with the new profiles) and this should clear itself up.
I just updated my SonarQube instance from 5.5 to 6.7.2 LTS, by taking care of migrating to 5.6.7 LTS before going to 6.7.2 LTS. Everything went smooth. Looking at the Quality Profiles, I see that the migration process imported/kept Quality Profiles from my old instance, and marked them as quality profile coming from the older version of SonarQube. Then I have marked the new Sonar way quality profiles (those with the built-in marker) as the Default Quality Profiles, and then cleared the old obsolety quality profiles.Now, when looking at a project dashboard, I get this:The specified qualityProfile 'xml-sonar-way-77200' does not exist The specified qualityProfile 'java-sonar-way-64367' does not exist The specified qualityProfile 'web-lsds-56954' does not existLooks like some kind of housekeeping was skipped when I changed the default quality profile to the new one.
Quality Profile: The specified qualityProfile 'java-sonar-way-64367' does not exist
If you simply want to remove "(outdated copy)" from the name of this quality profile, simply click on "Rename" and choose a unique name for your quality profile.If you want to get rid of this outdated copy, you have to change the default quality profile to be the "Sonar way" built-in one (or another one) before SonarQube allows you to delete the outdated copy.
I have installedsonarqubefor the version7.0. Previously in other directory I have installed the6.1version too. Thus exists two directories.I did do the upgrade without any problems, it was mandatory when I have started for first time the7.0:The situation is that appears the following:How I can fix or remove the(outdated copy)message?If I go toQuality Profilesoption available in the top of the page, I can see the following:and then if I select theblue gearI get the following:I can't find some option to do an update.From the same figure shown above, If I do click inSonar way (outdated copy)link I go to (see below thatblue gearis selected too)And again I can't find some option to do an update.If I go toMarketplaceand click inUpdates OnlyI can see just the followingThus How I can fix or remove the(outdated copy)message?AlphaOther questions:Why appears two profiles from the beginning? (It forJava)Is possible use both together profiles for a scan process? (Has sense?)How know if there are more profiles available to be installed? Where and How? (I thought all come fromMarketplace)According with the figure see that theoutdated copyprofile has312rules against the other that has295. Thus in a first glance seems the former is better than the latter because has more rules, my the purpose of my post is apply the approach (if is possible) if I do click in some place and the profile gets update (and not removed) and thus theoutdated copymessage disappears.
Sonarqube : How remove the (outdated copy) message from a Quality Profile?
According tohttps://community.sonarsource.com/t/number-of-unit-tests-is-zero/26104/6JUnit reports only support Java.For Swift, we need to convert the report to a generic typeFirstly, ForCoverage(https://gist.github.com/lucascorrea/80f3d57a7f97b2365ef39839eefe68a1)run test to generate test dataconvert to coverage data withxcrun llvm-cov showthat sonar can recognizeconfiguresonar.swift.coverage.reportPathto the report path generated byxcrunyou can runsonar-scannerto submit coverage datash("xcodebuild -workspace ../brewdog.xcworkspace -scheme brewdog -sdk iphonesimulator -enableCodeCoverage YES -destination 'platform=iOS Simulator,name=iPhone 7,OS=11.3' GCC_GENERATE_TEST_COVERAGE_FILES=YES build test -derivedDataPath ../DerivedData") sh("xcrun llvm-cov show -instr-profile=$(find ../DerivedData -iname 'Coverage.profdata') ../DerivedData/Build/Products/Debug-iphonesimulator/brewdog.app/brewdog > ../DerivedData/Coverage.report")Secondly, ForUnitTest(https://github.com/azohra/forsis) After you done this, you can check information like count of unit tests, success, fail, duration (There are some pictures in the above link)This one is the same, you need to convert the test execution report to generic type with this toolset up the convert**[IMPORTANT]**configuresonar.testsANDsonar.testExecutionReportPathsinsonar-project.propertiesrunsonar-scannerAfter done the two things You can check the coverage AND unit test in the column in sonarqube website!!
We are setting up a Swift iOS Project, build with fastlane, to be analysed by SonarQube with the SonarSwift Plugin. Everything works so far except for information about the Tests.We archived to add Code coverage by generating a report with slather (llvm-cov) and renaming itCoverage.reportand fillingsonar.swift.coverage.reportPathwith the path.We also generate *.junit files and feed them intosonar.junit.reportsPath. But those seem to never be included. We tried only the path./reportsand naming the files withTEST-prefix and.xmlending. We also tried a direct Path./reports/TEST-report.xml.Did anybody got this to work? If yes, How? Is this even supported by SonarQube?
Include iOS Swift Projects Test Data in SonarQube Analysis
If you want to store all modules as standalone projects, then you cannot specifysonar.modulesand use SonarQube Scanner for Maven. The Maven scanner is designed to create submodules (the same structure as defined inpom.xmlfiles).What you can to do:build all modules by Mavengenerate in every module's root directory asonar-project.propertiesfile with content:sonar.projectKey=<project.groupId>:<project.artifactId> sonar.projectName=<project.name> sonar.projectVersion=<project.version> sonar.sourceEncoding=<project.build.sourceEncoding> sonar.sources=pom.xml,src/main sonar.tests=src/test sonar.java.binaries=<project.build.directory>/classes sonar.java.libraries=<list of all compile and provided libraries> sonar.java.test.binaries=<project.build.directory>/classes sonar.java.test.libraries=<list of all compile, provided and test libraries>executeSonarQube Scanner:sonar-scannerThis is very not recommended because:makes your project less readable (modules are not "connected")executing an analysis is much harder (you have to generate all properties which in standard cases are generated by SonarQube Scanner for Maven)
For our code analysis I want for each maven module one sonar project. At the moment I got one sonar project with the modules from parent pom.For my Jenkins job configuration I use SonarQube Scanner for Maven (link) withsonar-project.properties.# Root project information sonar.projectKey=org.mycompany.myproject sonar.projectName=My Project sonar.projectVersion=1.0 # Some properties that will be inherited by the modules sonar.sources=src # List of the module identifiers sonar.modules=module1,module2So the expect result for my sonar would be a project one formodule1and a project two formodule2.module1andmodule2are both maven module with one parent pom.myproject | ->module1 | ->pom.xml (Sonar Project ONE) ->module2 | ->pom.xml (Sonar Project TWO) ->pom.xmlWhat is the best way to configure this behaviour inonejenkins job.
Sonar: Multi-module analysis sonar
Your users need theCreate Projectsglobal permission. You can grant this individually or by putting them in a group and giving the group the permission.They'll need the Execute Analysis global permission as well (another argument for using a group). Once these permissions are granted, they'll be able to analyze projects. Any project that doesn't already exist will be created in SonarQube on the first analysis.
I have just installed SonarQube 6.7 and I am creating users for my colleagues, who would like to create a project from their source code hosted on GitHub repositories.So far I did not find a way to let users create a project, without setting them as system administrator. Apparently a project is created indeed from theCreate Projectbutton on theAdministration > Projects > Managementpage as reported in the officialdocumentation.Unfortunately in this way, most users should be set as admin if they want to create projects: therefore they will be able to manage the users and the whole system. As you can imagine it is not ideal situation, when a lot of administrators on a system.How can users be able to create a project without having admin privileges over the whole system (configuration, security, users, etc.)?I thank you in advance for your help!
SonarQube 6.7: how do no-admin users create a project?
I had to eventually change the project name in the settings.xml file. This contained my sonar.projectname and sonar.projectkey. Then, I had to onboard the app on the sonar dashboard with the new details and run the analysis. However, i still feel that a simple renaming feature could have been easy. Since it is more of an enterprise version of sonar we are not allowed to upgrade the sonar version immediately.
I have a few projects which use pom.xmls to run the sonar analysis. Their names are:Myproject1 Myproject2 Myproject3 Myproject4I want to rename them on the sonar dashboard:MyprojectA MyprojectB MyprojectC MyprojectDwhats the simplest way to achieve this? I know that we can update the key, and then on-board the project with the desired name. Is it possible for me to use the same key and update the project display name?P.S: I use sonarqube version 6.1
How to rename projects in Sonar Qube
Please note the GitHub auth plugin requirements (from Configuration -> General Settings -> GitHub)SonarQube must be publicly accessible through HTTPS onlyThe property 'sonar.core.serverBaseURL' must be set to this public HTTPS URLIn your GitHub profile, you need to create a Developer Application for which the 'Authorization callback URL' must be set to '/oauth2/callback'.In my case, I wase experiencing the same error (No provider key found in URI), and setting sonar.core.serverBaseURL in my sonar.properties fixed the problem
I am trying to use SonarQube with Github as authentication.Here it shows the plugin iscompatibleI've followed theinstructionsto setup the pluginWhen I try to authenticate I get this error in the log[o.s.s.a.AuthenticationError] No provider key found in URIThen I am redirected to"GET /sessions/unauthorized HTTP/1.0" 200I found in the SonarQubecodewhere the error is thrown.This is the source for theGithub Sonar Auth ExtensionHow does one place a provider key in the URI?
SonarQube 6.7 using Sonar Auth Github 1.3 Plugin
As Julien H. indicated in his comment I found a parameter in the buildserver sonar start script which set the 'sonar.projectName' to a fixed value. After removing it, the correct names appeared within sonar.
In the "Code" section of the sonarqube web application all sub modules of a maven multi module project have the same name. Only when highlighted with the mouse a tooltip appears with the correct name of the module. Is there a way to show the correct sub module name? In every module pom.xml the correct<artifactID>and module<name>are set. We are using sonarqube 6.7
Sonarqube: Same name for all sub modules (of a multi module project) in Code section
The projects that have "Test" in their name are considered test projects (e.g. containing only tests) and their analysis results are not pushed to SonarQube. You could try adding/d:sonar.msbuild.testProjectPattern=<pattern>to the list of the arguments toSonarQube.Scanner.MSBuild.exe begin, or in your case toAdvanced / Additional Settings, where<pattern>is a .NET regex pattern that will match your test projects' names, but not your main project.We will change this behavior in the near future, because we would like to push analysis results of tests to SonarQube, but still, by default projects withTestin their name will most probably be considered as test projects and some rules will behave differently.
I have a project called TestCommander, it is not a test project but instead a product that helps people within the organization to write integration tests easier.Obviously I want to analyze this C# code. But as it is now it seem to be ignored by SonarQube since it is named Test*, correctly assessed?Structure is like this:CompanyName.TestCommander - Commands - HttpGetCommand.cs - ... - TestScanner.cs - TestRunner.cs - CompanyName.TestCommander.csprojWhat I have done:Tried Source Inclusion: **/*.csTried Test Inclusion: **/*.csBoth at the same time.More specific pointing out the exact files I wanted to includeNone of these have worked.My setup: Internal SonarQube 6.7 Automated build in TFS 2017.3 with the VSTS task versioned 3.0.2
SonarQube won't analyze C# project named Test*
In fact this method:@Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SemaMonitorProxy.applicationContext = applicationContext; }is an instance method writing to a static field:private static ApplicationContext applicationContextYou cannot make the above method static. So the only solution would be to remove the static keyword from theapplicationContextdeclaration.private ApplicationContext applicationContext
I am getting this prompt from Sonar:Instance methods should not write to "static" fieldsI'm not quite sure what I need to change to fix this issue.Does "SemaMonitorProxy.applicationContext" have to equal a static method?public class SemaMonitorProxy implements ApplicationContextAware { private static ApplicationContext applicationContext = null; public void registerFailedLoginAttempt(HttpServletRequest request, HttpServletResponse response) { final SemaMonitor semaMonitor = applicationContext.getBean(SemaMonitor.class); semaMonitor.registerFailedLoginAttempt(request, response); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SemaMonitorProxy.applicationContext = applicationContext; } }
Sonar: Instance methods should not write to "static" fields
For standard Java project is it probably the easiest to use JaCoCo to generate coverage data and then feed it to SonarJava (SonarQube's plugin to analyze Java code). You can find documentation herehttps://docs.sonarqube.org/display/PLUG/Code+Coverage+by+Unit+Tests+for+Java+ProjectYou might find mentions of separation between unit tests and integration tests, this has been deprecated and now there is only single kind of coverage.Don't hesitate to reach out to mailing list or ask question if something is not clear, we are in the process of improving this documentation.
I have pretty standard Maven multi-modules project (with JUnit, Arquillian and Selenium tests). I have Sonar 6.2 installed on a server. And on my project on Sonar the Code Coverage metric indicates 0.0%. But I know it's wrong as I do have some test coverage.I foundthis Generic Test Data documentation pagethat explains that since 6.2 Sonar is supporting code coverage out of the box and that I have topass a comma-delimited list of report pathsto a parametersonar.coverageReportPaths(I guess provided either in my pom or in command line).I'm fine with that. But I cannot find out an example onhow to setup this for a pretty classical Java project. What kind of file do I need to give in the list ? The relative paths to each of my Surefire/Failsafe reports ? Do I need to generate Jacoco reports in addition ? Can I give a "generic" path likereport.xmlif all of my reports have the same name ?
Configure Sonar 6.2 code coverage on a Maven project
A token you create has all your privileges. Neither is it possible to gain privileges by using a token instead of username/password, nor to restrict a tokens' privileges. In SonarQube tokens and username/password are much alike - both tell the server who you are and what you are allowed to do.A solution in your case might be:Create a new, technical user, that only has very limited privileges. Use a password, that only YOU knowLogin as that userCreate a bunch of tokens, one for each developer, with the developer's name as token nameGive each developer his/her own tokenWhenever a developer leaves the company, invalidate his/her token
My developers are making use of theIntelliJ SonarLint pluginto connect to our SonarQube server and perform local analysisTo connect to the server they need to provide a token, so I want to create a single token which can be shared across all developers. I want this token to have minimal privileges i.e. to only allow the download of rules to allow local analysis to work.If I generate a token as a SonarQube administrator, does this mean that the token has more privileges than a token generated by a non-admin user? TheSonarQube documentationimplies any token has the ability to execute the full list of SonarQube Web Services.
How to limit the permissions of a token?
You can enable preview mode and local HTML reports by passing these extra properties:-Dsonar.analysis.mode=preview -Dsonar.issuesReport.html.enable=trueHowever, this feature has been deprecated some time ago, and may not work at all with recent versions of SonarQube and the Gradle scanner.The old documentation is here, in any case:https://docs.sonarqube.org/display/SONARQUBE51/Getting+Issues+Report+in+Preview+Mode
In mybuild.gradle, I have asonarqubetask from'org.sonarqube'plugin. Whenever I rungradle sonarqube, I got the below error:You're only authorized to execute a local (preview) SonarQube analysis without pushing the results to the SonarQube server. Please contact your SonarQube administrator.I don't have admin access to SonarQube server in my organisation, please let me know how to run SonarQube analysys locally (preview analysis) without pushing result to server(I know there is aSonarLintplugin to IntelliJ to analyse code withn IDE, but the process to have it installed involves a lengthy approval-seeking process :) So I'll have to do without it)UpdateAdding my sonarqube task configsonarqube { def shortBranchName = versionDetails().branchName properties { property "sonar.host.url", 'http://dummy.net/' property "sonar.forceAnalysis", "true" property 'sonar.projectName', "[" + shortBranchName + "] " + rootProject.name property 'sonar.projectKey', "${sonarQubeProjectBaseKey}" property 'sonar.branch', shortBranchName property 'sonar.projectDescription', "[" + shortBranchName + "] " + rootProject.name property 'sonar.sourceEncoding', 'UTF-8' } }
Execute SonarQube analysis locally using Gradle without pushing
You must verify the user account trying to run the analysis has write permissions to the cited directory. Until that has been confirmed/corrected, no one can go any further with this.
I have following problem with SonarQube analysis through Bamboo build.[ERROR] Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.0.1:sonar (default-cli) on project grip: Unable to load component class org.sonar.core.platform.PluginLoader: Unable to load component class org.sonar.core.platform.PluginClassloaderFactory: Unable to load component interface org.sonar.api.utils.TempFolder: Failed to create working path: /home/users/jiradmin/.sonar -> [Help 1]Bamboo plan just fire maven task:sonar:sonar.Google suggest only to clear sonar temp folder and check bamboo agent permissions for directory create/save. (Currently I don't have possibility to check this).Do you have any idea how to fix it? (or maybe I should write to official SonarQube support)Bamboo uses maven 3.2.5 and jdk 1.8.0_45. Project is multi-module (uses reactor plugin).
SonarQube - Failed to create working path:
I realized what was the problem.Setting GRADLE_OPTS was correct solution, however I also used gradle daemon, so those options were ignored for daemon. I ended up disabling daemon by adding -Dorg.gradle.daemon=false to GRADLE_OPTS and it worked.
I have a project module with 30K classes. After migrating sonar analysis from ant script to gradle plugin I have OOM error with output like this:13:10:36 Out of memory13:10:36 Total memory: 954M13:10:36 free memory: 119M13:10:52 Caused by: java.util.concurrent.ExecutionException: java.lang.OutOfMemoryError: GC overhead limit exceeded13:10:52 at org.sonar.plugins.findbugs.FindbugsExecutor.execute(FindbugsExecutor.java:163)13:10:52 ... 109 more13:10:52 Caused by: java.lang.OutOfMemoryError: GC overhead limit exceeded13:10:52 atWe've run ant script with the following parameters "-Xmx3800m -XX:ReservedCodeCacheSize=128m"How can I set the same parameters for sonarqube gradle plugin?I've tried setting the following env variable before calling gradleGRADLE_OPTS=-Xmx3800m -XX:ReservedCodeCacheSize=128mIt's applied correctly, but findbugs still failing and prints "Total memory: 954M"Also I've tried adding the following properties to reduce memory consumption, but without any luckproperty 'sonar.skipPackageDesign', 'true' property 'sonar.skipDesign', 'true'Gradle version is 3.5Sonarqube plugin version is 2.5jdk version is 8u131
Gradle sonarqube plugin - how to set memory for findbugs?
+50According toCloudBees support, you can set build result by settingcurrentBuild.resultyourself, so, to get the yellow orb that indicates unstable status (failed unit tests), you can do this:currentBuild.result = 'UNSTABLE'Now, you want to do this when Sonar quality gate status is "WARN".Theydocument how to do it: first you wrap your sonar execution withwithSonarQubeEnv('Your Sonar server'), then you wait for server to call you back with the results withwaitForQualityGate():stage("Build & SonarQube analysis") { node { withSonarQubeEnv('My SonarQube Server') { sh 'mvn clean package sonar:sonar' } } } stage("Quality Gate Check"){ timeout(time: 20, unit: 'MINUTES') { def qg = waitForQualityGate() if (qg.status == 'WARN') { currentBuild.result = 'UNSTABLE' } } }I have not tested this, I have an outdated version that I plan to upgrade when I have time, using a manually scripted approach that's 10 times more complicated than the above, I want to get rid of it and replace it with this solution... Not done yet but I'm sharing notes I collected.
I am slowly diving in to the pipeline groovy dsl of Jenkins. And I am trying to figure out how I can create a step that does sonar and reflects the quality gate message in the Jenkins buildserver.At this moment I have the folowing step definded for sonar:stage ('sonar') { mvn "-Dsonar.lang.patterns.jsp=notverified -Dsonar.host.url=http://sonar.server.example:9494 org.sonarsource.scanner.maven:sonar-maven-plugin:3.3.0.603:sonar -Dsonar.login=key }Now I want that when Maven gets the :[INFO] Quality gate status: WARNthat it does not set it onOKorErrorbut makes that build step goWARNas well (so instead of the nice green or red a nice color of Yellow). I have been digging trough the documentation but as far as I can tell there is no real way to make a Step go to WARN state in any way its in essense binary. And there is noting in between any one a idea?
Jenkins SonarQube step go to Warn
On the page you have looked you can read it is compatable until version 5.4. The plugin will not be updated anymore: it is replaced by the SonarQube Quality Model. You can find more detailshere.
We are trying to upgrade from 4.5.6 to 5.6.6 LTS. Already have a commercial license for SQALE. The latest version of Sqale plugin 2.7 (http://www.sonarplugins.com/sqale) is not working on 5.6.6. Is there a version available for 5.6.6?
SQALE Plugin for Sonarqube 5.6.6 LTS
The SonarQube Scanner for MSBuild will automatically detect and include sources based on your solution file. Instead of trying to narrow analysis to a subset viasonar.sources, allow the SonarQube Scanner for MSBuild to do its normal discovery job andnarrow analysis scopeinstead using exclusions. Specifically, setsonar.exclusions(ProjectAdministration > Analysis Scope > Files) to omit the files/directories you want to skip.Alternately, you could usesonar.inclusions(found at roughly the same spot in the interface) to narrow analysis to only the files you want analyzed. That may be easier if "include" is a smaller subset than "exclude". However, you should only use one or the other of these two settings.
I have a broad source tree and I want to analyze only some directories in the tree. In SonarQube documentation I have found description ofsonar.sourcesoption which should help in this case.First I have tried to send it in as a command-line parameter/d:sonar.source=... TheSonarQube.Scanner.MSBuild.exe begincall accepts the parameter, but it doesn't make any difference. TheSonarQube.Scanner.MSBuild.exe endcall doesn't accept the parameter.I have also tried to specify it in the config fileSonarQube.Analysis.xmland it doesn't make any difference either (whilesonar.exclusionsworks very well through the config file).SonarQube'sAdministration > Analysis Scopeweb-page doesn't havesonar.sources.Is there any way to makesonar.sourceswork together withSonarQube.Scanner.MSBuild.exe?I usesonar-scanner-msbuild-3.0.0.629andSonarQube 6.4.
SonarQube.Scanner.MSBuild.exe: How to specify sonar.sources?
Problem is solved withsonar.findbugs.excludesFilterspropertysonarqube { properties { property 'sonar.findbugs.excludesFilters', 'findbugs-filter.xml' } }and findbugs-filter.xml is<FindBugsFilter> <Match> <Or> <Class name="~.*\.R\$.*"/> <Class name="~.*\.Manifest\$.*"/> </Or> </Match> </FindBugsFilter>
When I run sonar analysis of my android project, I always get lots of messages about .class files generated by Android resource compilation like followingRun sonar: The class 'foo.bar.R$string' could not be matched to its original source file. It might be a dynamically generated class.I guess these messages come from Findbugs.I have tried to exclude**/R.class**/R$*.classfrom sonar analysis, but no luck.Any ideas on how to get rid of such messages?
Run sonar on android project: The class 'foo.bar.R$string' could not be matched to its original source file
I received the exact same log message from the production environment. The configuration works in the test environment. The issue was credentials. I agree with your update, "The error message is kind of misleading..."In my case the SonarQube token was incorrect in the sonar-project.properties file. I corrected the token and reran the analysis successfully.
I follow the instruction atAnalyzing with SonarQube Scanner for Antto analyzing an ant project and got following error:Buildfile: C:\Projects\my-sonar\build.xml [echo] Build properties read from build.properties clean: sonar: [sonar:sonar] Apache Ant(TM) version 1.9.4 compiled on April 29 2014 [sonar:sonar] SonarQube Ant Task version: 2.5 [sonar:sonar] Loaded from: file:/C:/Projects/my-sonar/.ant/lib/sonarqube-ant-task-2.5.jar [sonar:sonar] User cache: C:\Users\test\.sonar\cache [sonar:sonar] Load global settings BUILD FAILED C:\Projects\my-sonar\build.xml:541: java.lang.IllegalStateException: Scanner engine is not started. Unable to execute task.I'm using JDK 1.8 and connecting to a remote SonarQube server.Do I have to start sonar-scanner as a service locally?Any helps are appreciated.UPDATE:This works after adding "sonar.login" & "sonar.password" in build.xml. The error message is kind of misleading...
Sonar Scanner engine is not started
Just because the method you are overridingthrows Exception, it doesn't mean you have to.You are free to not declare that you throw any exceptions at all, or to throw specific exceptions instead:public abstract class ParentClass { abstract void doSomething() throws Exception; }These are all valid (obviously, not all at once):public class ChildClass extends ParentClass { public void doSomething() { } public void doSomething() throws MyException { } public void doSomething() throws Exception { } }There's no reason for you to carry on their bad practices.
I am using SonarQube for my code quality analysis. I am coding in java with the use ofAbstractJavaSequencefrom AdroidLogic API.Many of my project classes extend this class and override execute method which by default declarethrows Exception. The SonarQube analysis raises an issue, stating that the class uses a generic exception instead of specific one.How can I resolve this SonarQube issue?
How to avoid SonarQube issue about abstract exceptions?
Sorry, rule type is not settable, although as @Simon pointed out, you can change the type of an issue.
Is there a way to change the type for rules existing in SonarQube 6.4 (not custom rules). For example, can I change an existing rule from a bug to a vulnerability or a code smell etc.. ?Thanks in advance
Change default rule type in SonarQube 6.4
Two things:proxy authentication between SonarQube Scanner and Server is only supported since SonarQube 6.1 (SONAR-8084)with the above,http.proxyUserandhttp.proxyPasswordare leveraged for basic proxy authentication (and you can leavesonar.host.urlto the actual HTTP URL)
Have a Sonar instance running behind basic auth (not Sonar auth).Using the Sonar Gradle plugin and specifying the Sonar host URL ingradle.propertiesvia:systemProp.sonar.host.url=https://admin:[email protected]However this does not seem to authenticate as in Gradle logs I see:SonarQube server [https://admin:[email protected]]can not be reachedIf I curl the same URL I get a 200 response as expected.Not sure why thesonar.host.urlisn't playing nicely?
Gradle + Sonar host URL and basic auth
Thanks for the input. The problem was caused by some totally different reason:We had the ReSharper plugin installed, which caused a warning in its settings tab like "path to inspectcode and resharper cannot be used simultaneously".After uninstallation of ReSharper all was fine again and the UI was behaving as expected and displaying all settings' values.
Using SQ 6.2 I observe a strange behaviour: Whe I modify and save no matter which setting in the administration UI and then reload the page, everything looks reset.Example: Set "General / Delete all snapshots after" to "5", press "Save" and then press "F5". The field is empty again.Does SQ store its settings in the database or on the filesystem? May I have wrong access rights then?We're using an external PostgreSQL database.
SonarQube is not saving settings
I resolved this issue by putting in-Duser.homein mvn command for sonar Which would somewhat look like:mvn sonar:sonar -Duser.home=__<new location to download sonar jars in which it will create .sonar/cache wherein the jars will be downloaded>__
I am trying to do a maven sonar analysis of my project, but the problem I face is, it downloads sonar jars in my users home/user/.sonar directory in Linux. The logs shows the path to be set in User cache as that of home/user/.sonar I want to change this patch since this users directory doesn't have enough space.What all do I need to change?
Sonarqube 5.6.3 .sonar /cache directory change
Use theapi/projects/createweb service to provision your projects. You can then callapi/permissions/add_groupto grant group access to your newly provisioned project.
We are using an in house gitlab setup and teams can use a centralized sonarqube server for their scans. However, we are faced with an issue where the users don't have access to their newly created projects. We need a project template in place beforehand to create the proper permissions. Is there any API in place for me to automate the creation of the project templates?Ex) when a new project group is created in gitlab sync that over to a permissions template in sonarqube
Sonarqube - Automating Permissions Templates
SONARAVA-71has been implemented in version 4.9 of the SonarJava Analyzer, so your version of SonarJava should ignore such annotated elements if configured correctly.Now, in order to have classes ans methods annotated with (and only with)@javax.annotation.Generatedbeing ignored by the analyzer, be sure toprovide the bytecode for your analysis.
I see thishttps://jira.sonarsource.com/browse/SONARJAVA-71improvement which the current status is closed. I was asked to raise my question here.I would like to know how to implement the fix because i tried to use latest SonarJava 4.10.0.10260, however it still reports issues on class/methods with @generated annotation. Please advise how to implement this fix. Which version of SonarJava release this fix is included. Thanks!
SonarJava-71 Exclude issues on generated code when annotated with javax.annotation.Generated
If your Jenkins server doesn't have access to the internet to download the update file, then it's not going to be able to auto-install the scanner either.For your case, you'll need to install a scanner manually, then configure the path to it in Jenkins.
I am following the instructions at the url below to configure jenkins/sonar.https://docs.sonarqube.org/display/SONARQUBE52/Installing+and+Configuring+SonarQube+Scanner+for+Jenkinsand I come to that stepScroll down to the SonarQube Runner configuration section and click on Add SonarQube Runner. [...]If you don't see a drop down listwith all available SonarQube Runner versions but instead see an empty text field thenthis is because Jenkins still don't have downloaded required update center file (default period is 1 day). You may force this refresh by clicking 'Check Now' button in Manage Plugins >> Advanced tab.The tutorial fails to mention how to fix this in the case the server isnot able to connect to the internet(this would be the case for many or most companies!). The explanation provided "required update center file" is to vague IMO.any help appreciated.
Installing and Configuring SonarQube Scanner for Jenkins - needs clarifications
Sonar lint is a plugin for live code analysis. Sonar lint can automatically connect to the configured remote server and fetch quality profiles required to analyse the code. This plugin scans the source code for only rules from SonarAnalyzer repository(As you said).I suggest you to use the below IntelliJ plugins:FindBugs Plugin download link -https://plugins.jetbrains.com/plugin/3847-findbugs-ideaPMD Plugin download link -https://plugins.jetbrains.com/plugin/1137-pmdpluginAs far as I know it is not possible to export an PMD or Findbugs config file from sonarqube server-this not trueIt is possible to export PMD or Findbugs config file but separatelyCreate a quality profile and activate all the rules of pmd and findbugs in that quality profile.After that if you click on the created qualityprofile like the one named "pmd" i created in the below screenshoti have only activated pmd rules in it so you can a filter named PMD on the left bottom side.click on that filter then rules that only belongs to pmd shows up as in the below screenshot.click ctrl-s and save it into an notepad.this is how you export the rules and findbugs have also been present on the left bottom if i have activated it.you can use this file to configure the above suggested jetbrains plugins install the plugins and you can configure them in the settings using the exported rule file.I did this in android-studio.
I've defined a quality profile containing rules from the sonar analyzer, PMD and Findbugs. However if I want to check those rules in the IDE (IntelliJ IDEA and Eclipse) only the sonar rules are applied (by design). I'd prefer sonarqube server to be the single source of truth and thererfore want to use PMD and Findbugs rules defined on the sonarqube server in my IDE. As far as I know it is not possible to export an PMD or Findbugs config file from sonarqube server.What is the best way, to use sonarqube server as the single source of truth regarding static coded analysis and using PMD and Findbugs rules defined on the sonarqube server inside an IDE?
How to use PMD and FinBugs rules defined on SonarQube server inside IDE?
The problem is solved so that my .Net project name was 'TestProject'. Because of it contains 'Test' keyword, sonar automatically detect it as a test project and doesn't transport bugs and issues to the dashboard.
I was installed Sonarqube server on my machine and I am running sonarscanner for msbuild described inhereThese are the commands:SonarQube.Scanner.MSBuild.exe begin /k:"org.sonarqube:sonarqube-scanner-msbuild" /n:"Project Name" /v:"1.0" MSBuild.exe /t:Rebuild SonarQube.Scanner.MSBuild.exe endAll steps succeeded and showing results on command prompt but the analysis results doesn't appear on dashboard. What's the problem?
Sonar scanner bug results does not appear on sonarqube dashboard
It appears you are victim ofthis Jenkins bug: when using a JRE installed at a path that includes parentheses, Jenkins (on Windows) tries to execute an invalid command.Workaround: install the JDK elsewhere, and use that one in your Job configuration (or Jenkins itself).
I followed the SonarQube Jenkins integration tutorial from SonarQube official website. I am getting an error after building my project.[RetailerWebsite_releaseTestCodeDx] $ "C:\Program Files (x86)\Jenkins2\tools\hudson.plugins.sonar.SonarRunnerInstallation\My_scanner\bin\sonar-scanner.bat" "SonarQube Scanner" -e -Dsonar.host.url=http://10.252.80.55:9000 -Dsonar.projectName=RetailerWebsite -Dsonar.projectVersion=1.0 -Dsonar.projectKey=Retailer-Website -Dsonar.sources=. -Dsonar.projectBaseDir=D:\Builds\RetailerWebsite_releaseTestCodeDx \Jenkins2\tools\hudson.plugins.sonar.SonarRunnerInstallation\My_scanner\bin\..\jre was unexpected at this time. ERROR: SonarQube scanner exited with non-zero code: 255Project ConfigurationGlobal Configuration
Getting an error while integrating SonarQube with Jenkins
In thesonar-scannerscript, there is this blockif [ -n "$JAVA_HOME" ] then java_cmd="$JAVA_HOME/bin/java" else java_cmd="$(which java)" fiAnd given that myJAVA_HOMEwas unset, the script calledwhichand the command is not installed inside my container.As a workaround, I set the env variableJAVA_HOME.
I'd like to run SonarQube Scanner from a Jenkins pipeline and I followed the documentation.Regarding the error, it seems that the scanner is present but some commands are not found. My jenkins instance runs in a docker.Jenkins version : 2.46.1SonarQube Scanner : 2.6.1+ /var/lib/jenkins/tools/hudson.plugins.sonar.SonarRunnerInstallation/SonarQube_Scanner/bin/sonar-scanner /var/lib/jenkins/tools/hudson.plugins.sonar.SonarRunnerInstallation/SonarQube_Scanner/bin/sonar-scanner: line 56: which: command not found /var/lib/jenkins/tools/hudson.plugins.sonar.SonarRunnerInstallation/SonarQube_Scanner/bin/sonar-scanner: line 66: exec: : not found
SonarQube Scanner fails in a Jenkins pipeline due to command not found
As stated in release notes for6.2:Customisable global dashboards and widgets are removed ( SONAR-8354 - Remove dashboards & widgets Closed ). As a consequence, custom plugins which were contributing widgets or dashboards won't be effective any more (but they won't fail SonarQube startup, they will just be ignored).
In current LTS version you can configure theHomedashboard andCustomdashboards for projects, but in 6.3.1 (latest) the menu option doesn't appear. Are these features removed?Is there any way to configure sonarqube home page, projects home page or add custom dashboards?Thanks in advance.
Dashboard has been removed in Sonarqube 6.X?
The problem is that:SonarQube Server supports external plugins like PMD, FindBug, and CheckStyle.SonarLint management has decidednotto support any external plugin, so you have only support of Sonar bug rules here.Solution:What we can do is that we canexportthe bug rules file from SonaQube Server andlinkit with the installed external plugins (PMD, FindBug, CheckStyle) so they can prompt you issues which Sonarlint is not able to show alone.
Sonar Lint 2.0, It's connected to my own Sonar Qube server with no issues reported by the plugin. The issue is that it is not in sync with my server rules. Found those mentioned in the doc for Java but they also seemed not to be all. I wonder if these java rule list are used only when it's not connected to any server only.Does it have a restriction of what rules to use or synchronize when using a remote server?What exactly we can do to make it synch if it is possible.Plateform: Java SonarQube Server: Version 5.6+ Sonar Lint: Version 2.0
Sonar Lint not in sync with server rules
Your problem is describe here:https://jira.sonarsource.com/browse/SONARJAVA-1810Check your sonar version.
How to Store a String array which needs to be serialized and must be stored in Session in java? I have a String Array in Session which is not serialized I am taking a particular value from array and I am updating it.this code works fine but When i runSonar Qubefor my project it suggests the value which i am storing in session should beserialized.can u plz suggest me how can i resolve this issue?****Make "String[]" serializable or don't store it in the session. ****String[] array=(String[])request.getSession().getAttribute("sortvalues") array[1]=""; request.getSession().setAttribute("sortvalues",array);
Serialize an String array and store it in Session
Generally speaking, theorg.sonarsource.*groups are indeed a direct continuation of theorg.codehaus.sonar*ones.This is true for almost any component you'll find out there:libraries - like the JaCoCo oneSonarQube pluginsSonarQube APISonarQube itself
I've been trying to get a legacy application to start working with code coverage tools and Sonarqube this week and I've been struggling. I noticed when comparing 2 sample 'apps' I've downloaded and modified to get the basics working that they are using different group Ids for similar components. Especially sonar-jacoco-listeners.so one is using<dependency> <groupId>org.codehaus.sonar-plugins.java</groupId> <artifactId>sonar-jacoco-listeners</artifactId> <version>2.9.1</version> <scope>test</scope> </dependency>and the other<dependency> <groupId>org.sonarsource.java</groupId> <artifactId>sonar-jacoco-listeners</artifactId> <version>3.8</version> <scope>test</scope> </dependency>If I look at this web articlehttp://www.javaworld.com/article/2892227/open-source-tools/codehaus-the-once-great-house-of-code-has-fallen.html& compare the versions (codehaus stops at it 3.2 and sonarsource picks up at 3.4) it looks obvious that the sonarsource group took over & continued the management of this component.I wondered if anyone could confirm that this is just a direct continuation with a different group ? And also if there is anything I should watch out for ? It seems clear that one leads into the other bit is there a place I should be looking to see this history clearly ?
codehaus sonarqube component moved to sonarsource
Yes, you can exclude those files from scan.From project settings you can exclude, you can choose to exclude only for issues or you can totally exclude the file (no metrics is generated - loc, complexity, duplication nothing is calculated)If first analysis has not happened use provisioning to achieve the same.Updating to cover peculiar case of excluding only old issues:By marking all old issues as false positives you'd exclude them from future analysis, though might sound like bonkers it will work as long as don't change directory structure.
I want sonar scanner to run on a legacy project but capture only new issues. Is there a way to mark and neglect all the existing legacy issues ?
Is there a way to instruct sonar scanner to exclude issues related with legacy code?
I believe you're misreading the docs. You cancompileyour project with whatever version of Java you like. 1.4 even. But you mustanalyzewith 8.
I want to configure SonarQube for my maven project which is on jdk 1.6. Can I use the latest SonarQube 5.6. It say code should be complied with jdk 1.8 only. Is it possible to analyse code with older version of JDK with SonarQube on latest vesrion of JDK?My project is compiled on jdk1.6. Do I need to use scanner which supports jdk1.6 because if I uses sonar-maven-plugin - 3.1.1 it gives error :Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.1.1:sonar (default-cli) on project StreamDiffCLI: Execution default-cli of goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.1.1:sonar failed: Unable to load the mojo 'sonar' in the plugin 'org.sonarsource.scanner.maven:sonar-maven-plugin:3.1.1' due to an API incompatibility: org.codehaus.plexus.component.repository.exception.ComponentLookupException: org/sonarsource/scanner/maven/SonarQubeMojo : Unsupported major.minor version 52.0
SonarQube 5.6 with Java Project (JDK 1.6)
Ticketcreated. Meanwhile, you can either:deactivate the rule completelymark the issues flagged as won't fixset an exclusionon test filesfor all issues
I have set SonarQube to manage code quality on my project, but I have this issue: On tests projects I don't want to run this rule:Source files should have a sufficient density of comment lines common-cs:InsufficientCommentDensityHow can I do this? I tried to add in Issues-> Ignore Issues in Blocks: Regular Expression for start of the block with the patternusing NUnit.Framework;But no success, the rule is still appearing on test files.
Sonarqube restriction of a rule
The LDAP plugin (supported by SonarSource) doesn't include anymore theactive-directory related code.This code is now contained in the community supported pluginActive Directory pluginHonestly, I haven't found any trace of this change in their official documentation. I have found it while browsing the code of the LDAP plugin (because when I finally completed its configuration to match my domain, I noticed that the users created by the LDAP plugin were not matching the existing users => loss of privileges)Enabling the Active Directory plugin (and disabling the LDAP one) allowed me to get the same feature level as in SonarQube 5.3, LDAP 1.5
After having migrated to SonarQube 5.6, LDAP 2.1 (from SonarQube 5.3, LDAP 1.5)When authenticating against an Active Directory domain I get the following error2016.12.16 15:56:31 ERROR web[rails] Error from external users provider: exception Java::JavaLang::NullPointerException:Please notice thatDuring the migration I have had to add the following parameters in order to get the LDAP plugin to recognize the working domainldap.realm=company.domain ldap.user.request=(&(objectClass=user)(sAMAccountName={login}))In the logs I findTest LDAP connection on ldap://servername.company.domain: OK
LDAP plugin: user authentication fails after upgrade
Make the plugins DSL not auto-apply the plugin and apply it manually likeplugins { id "org.sonarqube" version "2.2.1" } apply plugin: 'org.sonarqube'then you should be able to put the applying into a separate Gradle file, or only apply it depending on any condition you can formulate with Groovy.
I'm using Gradle 3 and Sonarqube on a Java7 project:https://github.com/cbeust/testng/blob/master/build.gradleAnd my ci is Travis with Java7 & Java8:https://travis-ci.org/cbeust/testng/Only recent versions of the Sonarqube plugin support Gradle 3 and they only run on a Java8 runtime. When I run the Gradle build with Java7 then it fails withjava.lang.UnsupportedClassVersionError: org/sonarqube/gradle/SonarQubePlugin : Unsupported major.minor version 52.0I tried to enable the SonarQube plugin with Java8 only but it fails too:https://github.com/cbeust/testng/blob/update-gradle-plugins/build.gradleI tried to define the SonarQube plugin in an external gradle file but Gradle allows the plugin definition in the main file only.I'd like to avoid the duplication of thebuild.gradle. Is it possible?
Disable a gradle plugin depending on the java target
The SonarQube C# plugin version 5.4.0.464 fixes this issue. Have a look at this ticket:https://jira.sonarsource.com/browse/SONARCS-613
I'm trying to use theSystem.Diagnostics.CodeAnalysis.SuppressMessageattribute to stop sonarqube raising this issue on a specific method in our codebase. I'm not sure exactly what form the suppress message attribute should take. I have tried a few variations on the following with no luck.[SuppressMessage("csharpsquid", "S1871:Two branches in the same conditional structure should not have exactly the same implementation")] public static string SomeMethod(string input)Here is the link to the documentation for the issue:http://dist.sonarsource.com/plugins/csharp/rulesdoc/0.9.0-RC/S1871.htmlUsing: sonar-csharp-plugin-5.3.2
SonarQube C# SuppressMessage, Category for S1871
In your Maven goals, append the following-Dsonar.erlang.eunit.reportsfolder=PATH-TO-YOUR-REPORT-FILESFor me following setting worked-Dsonar.erlang.eunit.reportsfolder=_build/test/cover
I am using Maven to run EUnit tests on my Erlang project and then making a static code analysis. I do not know how to configure the coverage report path so that SonarQube could also show my code coverage results.
SonarQube code coverage for Erlang EUnit tests
Specify where your sources are located. If you are using Maven, the easiest way is to specify it via -Dsonar.sources=src/main:mvn -Dsonar.sources=src/main sonar:sonar
We are using Sonar 5.5 and we have a number of js files in 'resource' folder in a maven structured application. This is not a web application so there is no 'webapp' folder. The js files are bundled in an executable jar file using Spring boot.I searched everywhere and based on the following link, Sonar already supports multi-language:Does Sonar support multiple language in same project?However, it doesn't work in our application. It doesn't seem any special configuration for that to happen.I made a comment on the above link a while ago but haven't got any answer. I suspect, js files are detected by Sonar only if they are located in 'webapp' folder. I can't find any documentation on this.We are using maven sonar plugin to analyze the project:mvn sonar:sonarPlugins and versions installed:Git 2.1 C# 5.0 Java 3.13.1 Javascript 2.11
SonarQube 5.5 doesn't pick javascript files in a Java application
You need to run thejacocoant target first :ant jacocoalltests
In Hybris, running"ant alltests"of platform/build.xml generates an HTML report of test cases execution.Running"ant sonar"of platform/build.xml results in analysis report, But Junit/testcase coverage is not being shown.For Sonar to check coverage, do we need any extra configuration?
Running SonarQube on Hybris Custom Extensions
You don't need to upgrade to 4.5.7.
Do we need to upgrade our Sonarqube 4.5.5 to latest LTS 4.5.7 before upgrading to 5.6? Or is it ok to upgrade directly to 5.6 as long as you are on the latest LTS branch 4.5.x?
sonarqube upgrade from 4.5.5 to 5.6
You're looking for "Coverage on New Code", which is calculated against the "Leak period", i.e. the first listing inAdministration > General > Differential Views.Your problem is that differential values are calculated during analysis, so you can't update the leak period value and retroactively get exactly what you described. But narrow the leak period value down from the default 30 days (maybeprevious_version?) and you'll get close going forward.
Is it possible in SonarQube to calculate code coverage for a delta only?For instance: a project had 1000 lines yesterday and its unit test coverage results are already in SonarQube. A new commit was pushed today with an extra 100 lines of code and additional test cases. These additional test cases cover 70 of the 100 new lines. Is there a way, possibly using TimeMachine, to retrieve/calculate the code coverage for the delta only? (in this case 70%)
SonarQube: calculate code coverage for delta only
I'm currently developing a SonarQube plugin for importing PVS-Studio static analysis results and I have faced the same problem. The message you have mentioned is produced by MSBuild.SonarQube.Runner and means that the source file under analysis is located higher in the directory tree than the .vcxproj file, for example:sourceFile.cpp projectDirectory | ---project.vcxprojAs far as I understand, MSBuild.SonarQube.Runner assumes that all source files should be located under the directory where the .vcxproj file exists, and ignores all the files that doesn't satisfy this condition.Since it's not possible to alter the way MSBuild.SonarQube.Runner determines project's base directory, and you still need to analyze those skipped files, I suggest you use the default SonarQube scanner, create the sonar-project.properties config file as described here:SonarQube Scanner, and use the sonar.sources property to specify paths to source files.
i've got a problem analysing a solution containing C# and Cpp Projects using Jenkins, SonarQube and cppcheck.. The analysis of the C# Code is working totaly fine, all results (issues, code coverage etc.) are shown in Sonar.The analyses of the C++-code with cppcheck is working fine - the results are shown in Jenkins via the the Cppcheck plugin but no output in sonar (not even the quality profile for cpp gets activated in the sonar project - that worked automaticaly in a test project i set up for test purposes).The console output in jenkins gives me the following warning for each .cpp, .h, .vcxproj file:WARNING: File is not under the project directory and cannot currently be analysed by SonarQube. File [filepath]The files are definitely located in the filepaths listed after these warnings and they are during the analysis (no copying/moving of files in the build jobs).I already read thispostand made sure that i've got no occurence of "Test" in my paths. I also made sure that the files i want to analyse are no shared files.I hope anybody has some ideas what is getting wrong here - i haven't got a clue why sonar does not want to show my cppcheck-results.My system:Jenkins v. 2.15Jenkins Cppcheck Plug-in v. 1.21SonarQube v. 5.6SonarQube C++ (Community) Plugin v. 0.9.6cppcheck v. 1.74 (cppcheck-results are written in XML version 2 format)Best regardsAkki
SonarQube not analysing C++ Code with warning File is not under the project directory
you can generate a html file if you run an analysis in the preview modehttp://docs.sonarqube.org/pages/viewpage.action?pageId=6947686
I want to create a custom report. Response format for sonarqube web service API /api/issues/search is JSON or XML. How can I use that response to create a html or CSV file using "unix shell without using command line tools" so that I can use it as a Report. Or is there any other better way to achieve this?
How can I use SonarQube web service API for reporting purpose
As @Simon told me, it was a space in path problem.
When sonarlint eclipse ask me to refresh my sonarqube data (Update all projects binding), I get the following error :Unable to update data from server 'cerbere' Unable to move C:\workspace neon\.sonarlint\work\cerbere\.sonartmp_1776998337301134698\4346381085123285128 to C:\workspace neon\.sonarlint\storage\cerbere\globalAs I also upgraded to latest version of sonarlint (2.1.0), I don't know if this caused my problem, that I hadn't had before.I have to manually move the data to fix it.Thank you.
Can't update data from sonarqube server
The C# plugin has been rewritten in version 3.4 to use Roslyn internally. So any later version will handle (parse) C# 6 features. Also, I recommend to update to the latest version as we are constantly adding new rules, and fixing known issues.You can check the version historyhere.
I am setting up our TeamCity build to run a SonarQube analysis of our C# solution. I have already been through one hurdle by using-Dsonar.sourceEncoding=UTF-8to allow Sonar to recognise the utf-8 BOM header in our files. My current problem has to do with C# 6.0 syntax, like string interpolation, which does not seem to be recognised by Sonar and is giving me "parse errors":[09:38:39][Step 4/6] 04:38:39.338 ERROR - Unable to parse file: C:\BuildAgent\work\.........\DataLayerTests.cs [09:38:39][Step 4/6] 04:38:39.338 ERROR - Parse error at line 44 column 46: [09:38:39][Step 4/6] [09:38:39][Step 4/6] 43: Assert.IsNotNull(results, "The method returned NULL instead of any results."); [09:38:39][Step 4/6] --> Assert.AreEqual(1, results.Count, $"The method returned {results.Count} results instead of 1.");Is there any additional command line parameter that I need to use with thesonar-runnerto ensure compatibility? Or does this have to do with the version of the C# plugin that we use?I found thisotherquestion, which is only tangentially related. That question is about enabling the issues that are spotted by the Roslyn analyser to flow back into SonarQube. My question is a lot more basic than that, as I am not yet even at a stage where Sonar would fully understand my syntax!
Configuring SonarQube to recognise C# 6.0 syntax
There's a Bamboo plugin for that:https://marketplace.atlassian.com/plugins/com.marvelution.bamboo.plugins.sonar.tasks/server/overviewI haven't used it, and I don't know whether it supports SonarQube Scanner for MSBuild (I'm skeptical on that count.)Perhaps your best bet is to treat Bamboo like a fancy CLI, and use follow theinstructions for analyzing from the command line. I.E.install an configure SonarQube Scanner for MSBuild on the Bamboo servervia Bamboo run commands:MSBuild.SonarQube.Runner.exe begin /k:"sonarqube_project_key" /n:"sonarqube_project_name" /v:"sonarqube_project_version"build the projectMSBuild.SonarQube.Runner.exe end
I have setup SonarQube in Azure Virtual Machine.sonarqube-5.4MSBuild.SonarQube.Runner-2.0SonarQube website at 9000 port is up and running.(http://something.regionname.cloudapp.azure.com:9000/)Now, how to execute sonarrunner from a local bamboo build server ?What are the configuration settings and other changes ?Earlier, I did setup sonarqube with bamboo locally successfully, because all are local paths.But now, I want to install sonarqube and bamboo on different servers. How to connect these two ?Please provide comments / settings in detail.ThanksBhanu.
How to execute SonarQube Runner from Bamboo?
Almost all of this is covered here exception for the unit test exclusion.http://docs.sonarqube.org/display/SCAN/From+the+Command+LineTo run for the whole solution you should be able to just run the following from your RootFolder:MSBuild.SonarQube.Runner.exe begin // Other args msbuild /t:Rebuild Project.sln MSBuild.SonarQube.Runner.exe endAs for your unit test questions. Most people choose not to include the test code in the project. This is done via the regex in the sonarqube UI: Administration->Scanner for MSBuild. Changing this regex to something that doesn't match for your test projects will cause them to be included.
I have setup SonarQube with the following:sonarqube-5.4,MSBuild.SonarQube.Runner-2.0, VS 2013 (target .NET Framework 4.5.1), SQL Server 2014 Express, Windows 7 Professional SP1 64-bit OS.I am able to execute sonarqube runner for one .NET project (.csproj) successfully and generate the results. Now I would like to executeMSBuild.SonarQube.Runner-2.0for a .NET solution (.sln) which has many .csproj entries.The folder structure is as below:RootFolder has a .sln file, and each project (.csproj) is created in a separate folder inside the root folder. Unit tests for each project are also created in a separate folder inside the root folder. For example:RootFolder -> Project.sln RootFolder -> ProjectABCFolder -> ProjectABC.csproj RootFolder -> ProjectABCTestsFolder -> ProjectABCTests.csproj RootFolder -> ProjectXYZFolder -> ProjectXYZ.csproj RootFolder -> ProjectXYZTestsFolder -> ProjectXYZTests.csprojCan you help me on the following ?How to execute the .sln file - what the required entries / settings to be made ?How to skip the unit test projects ?How to include the unit test projects ?How to execute the VS Code Analysis ?
How to execute MSBuild.SonarQube.Runner for a .net solution which has multiple projects?
This is pretty simple:Make sure that the "Execute Analysis" global permission is granted only to a "technical" user and configure your CI server to pass credentials of this user to the Maven command=> This will allow the CI to push analysis reports to the SonarQube server, but prevent any other user to do so.Make sure that every other user has the "Browse" permission on the projects=> This will allow any user to run an "issues" analysis and therefore generate an HTML report
I'd like to configure SonarQube so that developers can generate an HTML report locally (in 'issues' mode), but not be able to publish reports on the SonarQube server (in 'publish' mode).Instead, I'd like the CI server to be the only system with access to publish results (using a 'technical' user).TheRelease notes for SonarQube 5.4indicate that the "Execute Preview Analysis" permission has been removed.There is an "Execute Analysis" permission, but from what I've understood, this is required for both 'issues' mode and 'publish' mode.Right now, the Execute Analysis permission has been granted to 'Anyone'. This allows the Maven plugin to perform an analysis (issues or publish mode). However, sonar-runner (and sonar-scanner) both seem to need a login token configured before they can run even a preview analysis. This inconsistency seems confusing.How can SonarQube 5.4 be secured so that only the build server can update the results shown on the dashboard?
How to secure SonarQube 5.4?
The fact that you cannot see more than 1000 lines is a bug in SonarQube 5.3, reportedhere. It is fixed (bythis commitI guess) in SonarQube 5.4.The number of lines shown by default in the Component Viewer is not configurable.
How to configure themaximum number of lines of source codeshown in theComponent Viewerin SonarQube? I must be blind but I cannot find it either in SonarQube itself or on Internet.Component Vieweris the heart of SonarQube: it displays the source code of a file, and its high-level statistics. However, it displays maximum of 1000 lines of source code, then there is a spinning wheel under the last line and I cannot see the rest of the source code.N.B. I am using SonarQube 5.3.
SonarQube 5.3: Configure number of lines of source code displayed in Component Viewer
You're dealing with Quality Profiles, soapi/qualityprofilesto the rescue !api/qualityprofiles/add_project(documented here):Associate a project with a quality profileNote that your question mentions:default quality profile for projectThere is no such thing as adefaultQuality Profile for a project. A project has one and only one Quality Profile. However alanguagecan indeed have a default Quality Profile (can be set in the UI or viaapi/qualityprofiles/set_default).
I can not deal with changes in the project properties. I need to set default quality profile for project.I use query:curl -X POST -u 'admin:admin' -d 'resource=somedomain:aem' -d 'id=sonar.profile.java' -d 'value=java-sonar-way-aem-rules-22238' 'http://localhost:9000/sonar/api/properties'It does nothing and outputs:{"err_code":200,"err_msg":"property created"}P.S.somedomain:aem value I get from /api/resources > keyjava-sonar-way-aem-rules-22238 value I get from /api/profiles/list?format=json > key
Sonar 5.3 set quality profile for project via api
HA is not supported right now. Clustering is planned for end of this year.
This question already has answers here:Sonar: Replication/high availability or clustering solutions(2 answers)Closed6 years ago.I would like to know whether SonarQube will support HA/clustering? How to overcome the fail over situation of SonarQube instance when there is a hardware failure.?For example, I have two SonarQube instances are running on two different machines. Also I have a separate machine for storage/DB used by two Sonar instances. How to proceed to achieve HA for this situation.?
Clustering/High availability on SonarQube [duplicate]
You've run into this:https://jira.sonarsource.com/browse/SONARJAVA-1179As a workaround, you can enable or disable rules in Sonar via the rules administration UI. You can also set up company or project specific rule sets and assign them to your projects.
I am using SonarQube 4.5.4 and it works quite well for certain rules. However there are some rules that show a rule violation where there should not be one. namelyUnused private method should be removed. I have some private methods that are defined in a class. These methods are called from an .fxml file as FX object.Is there a way I can teach SonarQube to learn this exception?Further one of the method in question has an parameter which is marked as unused by SonarQube but the parameter is necessary for FX action events.I would be very glad if anybody could help.Here is a piece of the code:@FXML private void scanList(ActionEvent aEvent) { superObject.scanCurrentListAction(); }
How to handle certain SonarQube wrongly recognize rules?
To do so, you have to edit your quality profiles, seehttp://docs.sonarqube.org/display/SONAR/Quality+Profiles
I need to downgrade/upgrade some of the priority levels of default SQ rules.For Eg: The duplicated block of code rule , seems to be false positive in our scenario so we need to downgrade for Major to Info/Minor.The Hardcoded password rule needs to be a blocker for us.I couldn't find any documentation on the same. can the rule priorities be changed, if so how?Note:I'm using SQ 5.2
How to change Sonarqube rule priority for default JAVA rules?
There are two Bitbucket-related plugins to analyze pull requests. One forOn Demand/Cloudand one forServer. Each will add comments to your pull request, and the On Demand version will approve a PR with no new issues.Regarding your second question, the Issue Reports you're referring to contain only issues. In fact, it's not possible to calculate general Quality Gate compliance from a preview/incremental analysis since such analyses look only at issues, and Quality Gates can contain conditions on tests, duplications, &etc.
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question does not appear to be about programming within the scope defined in thehelp center.Closed1 year ago.Improve this questionWe're trying to set up a pull-request build pipeline that is triggered from Bitbucket, reports back failure when Sonarqube's code analysis reports some quality gate violation and ultimatively rejects the PR.As far as I have read, the build breaker plugin, that should enable such a thing,is no longer supportedin the most recent versions of Sonarqube, at least not in incremental / preview modes, since they now work database-less.What are my alternatives for creating such a functionality? Sticking with 5.0?Also, I figured that since quite some time Sonarqube can spit outText / HTML reportsfor CI analysis - does this output quality gate violations as well or only all individual inspection results? Should one retrieve the formervia API then? But I suspect this would require a full analysis, since it requires the results to be saved to the database, right?
Let quality gate violation fail incremental analysis [closed]