Response
stringlengths
8
2k
Instruction
stringlengths
18
2k
Prompt
stringlengths
14
160
found it I don't know why URL Rewrite module was adding URL ashttp://http://localhost:9000/{R:1}I manually changed it tohttp://localhost:9000/{R:1}and it worked
I am trying to setup SonarQube with SSL on Windows Server 2019. I can access the SonarQube server locally on the server usinghttp://localhost:9000.I followed the exact steps asoutlined hereto setup reverse proxy in IIS using URL Rewrite module. I see the Re-Write URL set tohttp://http://localhost:9000/{R:1}However when I browsehttps://sonarqube.mydomain.comI get the error below502 - Web server received an invalid response while acting as a gateway or proxy server.Is there anything i need to enable in SonarQube to enable Reverse Proxy?I could not find anything in website's logs%SystemDrive%\inetpub\logs\LogFiles
Setting SonarQube for SSL using IIS and Reverse Proxy throws 502 error
Generally speaking you do have multiple options: (i assume you are using java, but there are equivalent solutions for other languages)ignoring the whole classThere is a property calledsonar.exclusionwhich you can set to ignore that specific class. This needs to be set either yoursonar-project.propertiesor based on the scanner you are using. For details take a lookhereignoring just some lines with issuesIn the java world you can use line comments with//NOSONAR <reason>to exclude lines from detection. There are equivalents in other languages too.ignoring just some issues on the class/methodIn Java you can use the@SuppressWarnings("<rule id>")to exclude issues from classes and methods for detection. seehttps://stackoverflow.com/a/30383335/3708208Define multiple ignore criteria for wildcard and rulesyou can also define special settings in sonarqube, to ignore special files and folders via wildcard input, and which rules should be ignored. seehttps://stackoverflow.com/a/53639382/3708208
am having a class, which is giving me sonar issues. That is just a temporary class and I would ignore it in future sprints. How can I mark that particular class to be ignored from sonar analysis, as we have guidelines to commit code only if no sonar issues found.
annotation to skip sonar analysis on a class
Wrap it in a try-with-resources so it will be closed at the end of the block. The error message is complaining that the file might be open a long time.try (InputStream in = new FileInputStream(TRUSTSTORE_FILE)) { KeyStore truststore = KeyStore.getInstance("JKS"); truststore.load(in, TRUSTSTORE_PASSWORD.toCharArray()); } // Automatically closes in.This frees system resources (a file handle) and allows others to overwrite the truststore file.
Here is my code :KeyStore truststore = KeyStore.getInstance("JKS"); truststore.load(new FileInputStream(TRUSTSTORE_FILE), TRUSTSTORE_PASSWORD.toCharArray()); //sonarqube issueWhich is the most suitable InputStream for getting this done?Here is the full error :This method creates and uses a java.io.FileInputStream or java.io.FileOutputStream object. Unfortunately both of these classes implement a finalize method, which means that objects created will likely hang around until a full garbage collection occurs, which will leave excessive garbage on the heap for longer, and potentially much longer than expected.Do I really need to switch to :InputStream is = java.nio.file.Files.newInputStream(myfile.toPath());I am not comfortable with this one.
Sonarqube - performance issue as Method uses a FileInputStream constructor, what are the better alternatives?
In the project panel, right click on the root directory, then navigate through Sonar Lint>Analyze with Sonar Lint.
In Pycharm, you can view the SonarLint issues in a single file by opening the file and clicking on the SonarLint tab on the bottom of the IDE.However, this only shows the issues for a single file.How can you view all the SonarLint issues across all files within a single project?
PyCharm SonarLint How to view all issues across all files?
Without knowing what is hidden under the// TODOit is impossible to propose something useful. The following code:public static boolean initialize() { if (!initialized) { // TODO initialized = true; return initialized; } // TODO return initialized; }is equivalent to:public static boolean initialize() { if (!initialized) { initialized = true; return initialized; } return initialized; }which is also equivalent to:public static boolean initialize() { if (!initialized) { initialized = true; } return true; }The returned boolean value is always the same, so there is no sense to return it. The final code:public static void initialize() { if (!initialized) { initialized = true; } }
I'm using this code to initialize an action handler and I'm getting a Sonar Alert with a severity blocker:Refactor this method to not always return the same valuefor the following code:private static boolean initialized = false; public static boolean initialize() { if (!initialized) { //TODO initialized = true ; return initialized ; } // TODO return initialized; }How can I improve this code ?
Sonar Alert : Refactor this method to not always return the same value
UseGET api/issues/searchwithseveritiesparameter.Search for issues.At most one of the following parameters can be provided at the same time: componentKeys and componentUuids. Requires the 'Browse' permission on the specified project(s).severitiesoptionalComma-separated list of severitiesPossible valuesINFOMINORMAJORCRITICALBLOCKERExample value:BLOCKER,CRITICALUPDATEIn order to retrieve only the newer issues, you could use:sinceLeakPeriodTo retrieve issues created since the leak period. If this parameter is set to a truthy value, createdAfter must not be set and one component id or key must be provided.Possible valuestruefalseyesnoDefault value:falseorcreatedAfterTo retrieve issues created after the given date (inclusive). Either a date (server timezone) or datetime can be provided. If this parameter is set, createdSince must not be setExample value:2017-10-19or2017-10-19T13:00:00+0200or evencreatedInLastTo retrieve issues created during a time span before the current time (exclusive). Accepted units are 'y' for year, 'm' for month, 'w' for week and 'd' for day. If this parameter is set, createdAfter must not be setExample value:1m2w(1 month 2 weeks)Just be aware that these parameters are mutually exclusive, andsinceLeakPeriodforces you to specify one component. See theAPI documentationfor more details and examples.
Is there a SonarQube API available that will give me the security vulnerabilities and bugs of specific criticality (Ex: Blocker).
SonarQube API for getting critical security vulnerabilities
This looks like an XY problem.You are entangled in a non-trivial transitivity issue associated with overridingequals()due to your business rule ("if the Doubles are close with respect to some epsilon..."), as pointed out in a comment to the OP.In fact it is impossible for you to meaningfully implement anequals()method for that rule, because transitivity ("if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true") cannot be guaranteed. You might have threeDataobjects, d1, d2 and d3, where d2 was equal (i.e. close enough) to both d1 and d3, but d1 was not equal (i.e. not close enough) to d3.There is nothing wrong with the rules Java imposes when testing for equality, and there is nothing wrong with your specific condition for determining the equality of yourDatainstances either. It's just that they are incompatible.But whilethere are a bunch of rules you should definitely followifyou go down theequals()path, I don't see anything in your question that indicates you have to override anything. So don't go there.Why not just create a new methodpublic boolean sameAs(Object other)in theDataclass? It can check for equality based on your rule(s), and your unit tests can call that method. Then you have no need or obligation to implementequals()andhashCode()at all.(Updated on 9/12/19 to clarify whyequals()cannot be implemented.)
I have a class as follows:public class Data{ int x; ArrayList<Double> list; }Now, I want to write unit tests and compare this class with another one merely to check equality. However, I want to allow some room for error so that even if the Doubles areclose with respect to some epsilonthey're considered equal. Now, if I override the equals() method NetBeans and Sonar prompt me to override the hashCode() method as well which doesn't make any sense. The reason is that it's not feasible to simply implement a hashCode() method that outputs the same hash code value for CLOSE lists.My question is this:Should I continue with overriding the equals() method and just override hashCode() for the sake of passing Sonar check? (A dummy implementation for hashCode())ORShould I just implement this method to check closeness in my unit tests and not in the actual source code?
Problem with overriding equals() and hashCode() for a List of Double
It solved for me when I add in .csproject file.Add following code snippet in existing<PropertyGroup>section.<DebugType>Full</DebugType>
I have Azure Devops Build pipeline for Xmarin project - which is .NET core project. I have unit test cases defined in that which get executed successfully.Steps:Build projectRun unit testsRun sonar Analysis.Now - Run sonar Analysis - give error as The Code Coverage report doesn't contain any coverage data for the included files.But the Azure DevOps displays the Code Coverage tab and display the coverage percentage as well.Tried to Covert the .coverage file to .coveragexml file.Tried to change the VsTest version from 2 to 1Tried to add runConfigSetting file in the project which defines the code Coverage tool settings.Added extra properties in Sonar Init stepsteps: task: SonarQubePrepare@4 displayName: 'Prepare analysis on SonarQube' inputs: SonarQube: SonarAPI projectKey: XXX projectName: XXX extraProperties: '/d:sonar.cs.vscoveragexml.reportsPaths="**/*.coveragexml"'`
How to fix sonarqube error "The Code Coverage report doesn't contain any coverage data for the included files"
I had the same problem and it turned out that I was passing-Xflag to thesonar-scannercommand. It seems that this flag overrides thesonar.log.levelsetting and always sets it toDEBUG. Here is the documentation of thesonar-scannercommand:https://docs.sonarqube.org/latest/analysis/scan/sonarscanner/
I'm trying to set sonar log level to INFO.I tried to usesonar-project.propertiesand set thesonar.log.level = INFObut its not working.Any help on this please?sonar.log.level = INFO
Trying to set sonar log level to INFO
You can simplify your following statement,if (backtoyear != undefined || backtoyear.length > 0) {toif (backtoyear) {This is more readable, efficient and understandable.Refer to this specificationToBoolean
i'm analyzing my code using sonarqube and am running into an issue with the following code:var backtoyear = $('#backtoyear').val(); if (backtoyear != undefined || backtoyear.length > 0) { var currentyear = (new Date()).getFullYear(); var numberofyears = currentyear - backtoyear; }thebacktoyear.lengthvariable is causing an "TypeError can be thrown as "backtoyear" might be null or undefined here." because it could potential be null/undefined and therefore won't have any properties.should i just remove the second have of the OR from the if condition?
accessing property of potential null/undefined variable - javascript
Just followed this documentation is the good path to use sonarcloud.io with github.comhttps://sonarcloud.io/documentation/integrations/github/Configure sonar to add your deposit and Install sonar GitHub app our your repository.Then add few options to your sonar build. Sample from doc:sonar.pullrequest.base=master sonar.pullrequest.branch=feature/my-new-feature sonar.pullrequest.key=5 sonar.pullrequest.provider=GitHub sonar.pullrequest.github.repository=my-company/my-repo
I would like to setup Sonarcloud to decorate pull requests on github following this documentationhttps://docs.sonarqube.org/latest/instance-administration/github-application/But I can't find the "Administration > Pull Requests > GitHub > GitHub App private key." option.Any clue ?
Configure sonarcloud.io with Github Pull Request Decorations
The issue turned out to be with the Pylint integrated into the Pytest call. The parent Pytest call generated a unit testing report, which had empty classnames for additional "empty" tests that Pylint came up with. SonarQube warned about those empty classnames. I ended up removing Pylint Pytest integration and just running Pylint as a separate step from Pytest.
My abridgedsonar-project.propertiesfiles is as follows:# Sources sonar.sources=felix sonar.sources.inclusions=**/**.py sonar.exclusions=**/test_*.py,**/**.pyc,felix/utils/*,**/*.iml # Linter sonar.python.pylint=/usr/local/bin/pylint sonar.python.pylint_config=.pylintrc sonar.python.pylint.reportPath=pylint-report.txt # Coverage / Unit Tests sonar.tests=./tests sonar.test.inclusions=**/test_**.py sonar.python.xunit.skipDetails=false #DEFAULT VALUES: sonar.python.xunit.reportPath=xunit-reports/xunit-result-*.xml #DEFAULT VALUES: sonar.python.coverage.reportPath=coverage-reports/*coverage-*.xmlThe abridged source code tree is like so:β”œβ”€β”€ felix β”‚ β”œβ”€β”€ __init__.py β”‚ β”œβ”€β”€ __pycache__ β”‚ β”‚ β”œβ”€β”€ __init__.cpython-35.pyc β”‚ β”‚ β”œβ”€β”€ process.cpython-35.pyc β”‚ β”‚ └── spark.cpython-35.pyc β”‚ β”œβ”€β”€ felix.iml β”‚ β”œβ”€β”€ process.py β”‚ β”œβ”€β”€ spark.py β”‚ └── utils β”‚ └── utils.py β”œβ”€β”€ requirements.txt β”œβ”€β”€ setup.py β”œβ”€β”€ sonar-project.properties β”œβ”€β”€ tests β”‚ β”œβ”€β”€ __init__.py β”‚ β”œβ”€β”€ __pycache__ β”‚ β”‚ β”œβ”€β”€ __init__.cpython-35.pyc β”‚ β”‚ └── test_process.cpython-35-PYTEST.pyc β”‚ β”œβ”€β”€ cia-spark.iml β”‚ β”œβ”€β”€ data β”‚ └── test_process.py └── tox.iniI'm getting the following warning, though, when I run thesonar-scanner:WARN: The resource for '' is not found, drilling down to the details of this test won't be possibleCould someone, please, let me know why I'm getting this warning and how can I get rid of / fix it? Thanks.
How to fix the following warning: `WARN: The resource for '' is not found, drilling down to the details of this test won't be possible.`
Kirk,We added a few more preconfigured environment variables for webhook builds in AWS CodeBuild.CODEBUILD_WEBHOOK_EVENT: The webhook event that triggered the current build.CODEBUILD_WEBHOOK_HEAD_REF: The head reference name of the webhook event that triggered the build. It could be a branch reference or a tag reference.CODEBUILD_WEBHOOK_BASE_REF: The base reference name of the webhook event that triggered the build. It is the branch reference for pull requests.CODEBUILD_WEBHOOK_ACTOR_ACCOUNT_ID: The account id of the user who triggered the webhook eventThese are the ones in addition to what was already documented inhttps://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-env-vars.html.Let us know if this doesn't suffice.
In order to add pull request checks from external tools (e.g. SonarCloud) during a CodeBuild job, I need to provide PR details - e.g. the numeric PR key, the base branch, and the compare branch.I know these are present in the GitHub PR web hook, but I can't access that within CodeBuild.However CodeBuild is able to post back its own build check, i.e. block the merge if the build fails, so I know that these details must available.How can I access them from within a CodeBuild 'build context'?
Accessing GitHub pull request details within AWS CodeBuild
SonarLint won't support analysis last modifications according tomailing group answer:We don't plan to introduce those kind of analysis properties in SonarLint. The goal of SonarLint is to simplify configuration and to work out of the box, because it has the advantage of being able to take a lot of configuration data directly from the IDE.Question was similar:We want to restrict sonarlint alaysis only for the latest modified/added code.
Is there a way to analyse the last modification on specific Java class without analsing the whole class in SonarLintCurrently when open file or I save my modifications the whole class is analysed and this is not intresting when it comes to large class.My goal is to analys last modification that are about to be commited.I am using SonarLint with SonarQube Server and this one contains configured the Quality Barriers which analyzes just the difference of the code committed.
How to analyze on SonarLint just the code that has been modified and not the whole class?
Problem is withreturn new ByteArrayResource(content);statement outside oftry/catchblock. As your method is throwingIOException, you shouldn't be catching it. Below should resolve it:public ByteArrayResource readFile() throws IOException { try (S3Object object = amazonS3.getObject(new GetObjectRequest(bucketName, key))) { byte[] content = IOUtils.toByteArray(object.getObjectContent()); return new ByteArrayResource(content); } }
SonarQube error for below method, any suggestion experts on how to resolve the issue -This method call passes a null value for a nonnull method parameter. Either the parameter is annotated as a parameter that should always be nonnull, or analysis has shown that it will always be dereferenced.public ByteArrayResource readFile() throws IOException { byte[] content = null; try (S3Object object = amazonS3.getObject(new GetObjectRequest(bucketName, key))) { content = IOUtils.toByteArray(object.getObjectContent()); return new ByteArrayResource(content); } catch (IOException e) { LOG.error("IOException caught while reading file", e); } return new ByteArrayResource(content); }
This method call passes a null value for a nonnull method parameter. Either the parameter is annotated as a parameter that should always be nonnull
I have created similar setup in my project, as we needed to set the exclusions from the maven command (same as you), and not via the sonar gui (Sonar documentation only refers to exclusions via sonar's gui) Here's what we did in our project:"-Dcommon.sonar.issue.ignore.multicriteria=e1,e2 " + "-Dcommon.sonar.issue.ignore.multicriteria.e1.ruleKey=squid:S1845 " + "-Dcommon.sonar.issue.ignore.multicriteria.e1.resourceKey=**/input/**/*.java " + "-Dcommon.sonar.issue.ignore.multicriteria.e2.ruleKey=squid:S1845 " + "-Dcommon.sonar.issue.ignore.multicriteria.e2.resourceKey=**/datatypes/**/*.java"We also had these additional exclusions, i thought would be of assistance to the public:"-Dsonar.issue.ignore.allfile=r1,r2 " + "-Dsonar.issue.ignore.allfile.r1.fileRegexp=@Input\\(.*\\) " + "-Dsonar.issue.ignore.allfile.r2.fileRegexp=@Output\\(.*\\)"
Is it supported by sonar-maven-plugin to set the "Ignore Issues on Multiple Criteria" toNarrow the focusas-Dsonar.issue.ignore.multicriteriafor the sonar-maven-plugin run command?Any working example is welcomed.
SonarQube define "Ignore Issues on Multiple Criteria" in maven build
You are not missing anything and indeed some configuration like Quality Gate and Quality Profile can be configured only via server UI. Mostly because usually, you would like to share this configuration across the organization and different projects, so it is easier to centralize it on the server itself.Project specific settings can be set by creatingsonar-project.propertiesfile or setting the properties in maven or gradle build files. You can configure exclusions, coverage, test reports this way.You can use web api to configure server programmatically, but doing so for every project is not the intended usage pattern and you might encounter some difficulties.
It seems to me it is a good practice to have all build-related configuration or quality-related rules of a project defined inside the project itself (as human-readable configuration files). This has several advantages: any developer coming to the project can readily see what configuration it uses; human-readable configuration files are auto-documented ways of reproducing the configuration (e.g. in case a new server needs to be installed or switching to a different service); the configuration history gets stored in the same place as the rest of the history of the project.But AFAIU the documentation of SonarQube is rather oriented towards using the SonarQube UI to change settings on a project. For example, I couldn’t find how to configure a different quality gate than default using a property file, rather it is suggested to configure it using the UI or usingcurl. This would make it non obvious to a foreign developer that a different quality gate is used on that project, it seems to me.Did I miss something and does the documentation in fact explain somewhere how to configure the SonarQube settings of a project in a configuration file?If not, is it indeed the view of the SonarQube developers that what I describe as a good practice is not in fact a good practice, and why?Is there some (possibly undocumented) feature that permits to do what I want to do?
Self-contained sonar configuration through property file
Syntaxexport default fromisstage 1 proposal. SonarQube supports out of the box only ES 2018 syntax. Effectively this means that no issues will be detected in this file.
While running sonar-scanner on a node project, I get a Failed to parse file error, which looks like thisERROR: Failed to parse file [file:///home/node-app/somedir/index.js] at line 1: Unexpected token './AddCat' (with espree parser in module mode)And myindex.jsfile looks like this:export default from './AddCat';And myAddCat.jsfile looks like this:import React from 'react'; import { Image } from '@cat-ui/core'; import { translate } from 'client/helpers/language'; import Page from 'client/components/Page'; import { StyledText, StyledButton, StyledImagePlaceholder } from './AddCat.styled'; import AdditionalApplicant from './images/additional_applicant.png'; const AddCat = () => ( <Page> <StyledImagePlaceholder> <Image width="67px" height="60px" src={AdditionalApplicant} /> </StyledImagePlaceholder> <StyledText color="grey">{translate('AddCatText')}</StyledText> <StyledButton tag="a" color="secondary" href="/morecats/morecats.html?route=V1&sharedCat=true" label={translate('AddCatButton')} /> </Page> ); export default AddCat;The problem is only withindex.jsand not AddCat.js while running sonar-scanner. I think it's some kind of formatting issue and any help in figuring out the problem is highly appreciated.Regards, Ashutosh
sonar-scanner - ERROR: Failed to parse file with espree parser in module mode
Why do you need to return true unconditionally? If that's the vulnerability detected by Sonar, you should either not do it, or document why it is actually safe in this case.In terms of implementing "some" fix,look at the test casesfor the class. It seems that the implementation it wants you to use is:@Override public boolean verify(String a, SSLSession b) { return a.equalsIgnoreCase(b.getPeerHost()); }
Below is my code snippet for SSL Hostname verifier. But As I am returning unconditionaltruefrom this method. This is countered as a vulnerability by sonar. How I will resolve this one?SslClient sslClient = SslClient.localhost(); SSLSocketFactory socketFactory = sslClient.socketFactory; HostnameVerifier hostnameVerifier = new HostnameVerifier() { @Override public boolean verify(String s, SSLSession session) { return true; } };I want to know the best way.
Sonar java vulnerability method return true
For getting the code coverage details into jacoco.exec, we can use the following steps 1. Create a new xml file(jacoco.xml) which will be used as the build file by ant.(new file created since, we do not want to tamper the build.xml of the hybris platform) 2. Add the below components to the newly created jacoco.xml<project name="jacoco_rpt_pim" xmlns:jacoco="antlib:org.jacoco.ant"> <taskdef uri="antlib:org.jacoco.ant" resource="org/jacoco/ant/antlib.xml"> <classpath path="<path>/jacocoant.jar"/> </taskdef> <target name="jacocoalltests" description="runs allstests with jacoco attached"> <jacoco:agent property="agentvmparam" append="true" output="file" destfile="jacoco.exec" /> <property name="testclasses.extensions" value="agcobackoffice"/> <ant dir="<PLATFORM_HOME>" target="unittests" inheritrefs="false"> <property name="standalone.javaoptions" value="${agentvmparam}"/> </ant> </target> </project>Now invoke the jacocoalltests target which will invoke the unittests to get the code coverage report.Additionally, providing the path of the report to sonar, would help get the codecoverage in sonarqube.
How can the unit test results of a hybris project be captured to jacoco.exec and published to sonarqube
How to get the code coverage for unit tests in hybris to sonarqube using jacoco
Sonar Sanner always scans the entire code base. If somebody has decided that some code structures are wrong or dangerous (the ruleset have been changed) then SonarQube has to notify about all occurrences of that code. Why? Let's think about the following example:After a plugin upgrade, SonarQube provides a new very important security rule which forbids the use of a dangerous cipher algorithm. Now is the question:is it only dangerous in new code?is it always dangerous?Of course, it is always dangerous. SonarQube doesn't force you to fix everything (usage of the quality gates is optional). Its main goal is to let you know how many problems (code smells/bugs/vulnerabilities) exist in the whole code base.
We are using Sonar Qube 6.7.3 and sonar-java-plugin 5.3We have made below changes to our sonar configuration recentlyEnabled new rulesChanged configuration to include byte code(changed from 'clean sonar:sonar' to 'clean package sonar:sonar')We are using sonar svn plugin and provide valid credentials to it.I understand providing byte code to sonar will help it identify more issues but, Iexpect Sonar to flag new issues based on svn code commit date and last analysis date, but it is not.Please let me know why it is flagging issues in old code as new?
Sonar is showing new violations in old code
You should use.filter(aIDetailsDto.getResult().getIdNo()::equals).
When I checked it in sonar, the result is:Replace this lambda with a method reference.It actually refers to this one:.filter(s -> aIDetailsDto.getResult().getIdNo().equals(s))My code below goes like this:AIDetailsDto aIDetailsDto = aaaService .getDetailsByUserId(userId) if (!ObjectUtils.isEmpty(aIDetailsDto)) { List<String> kvpValues = callService.getKVPCodes(NewConstants.REMOVED) .stream() .filter(s -> aIDetailsDto.getResult().getIdNo().equals(s))I tried to change it however I get an error. Does anyone has an idea how to change it?
SONAR: Replace this lambda with a method reference.
I resolved the problem.Background info: Our sonar server work behind httpS and the apache redirects all reuqest fromhttptohttps.So, the good maven call is:$ mvn sonar:sonar -Dsonar.host.url=https://sonar.corp.tld -Dsonar.login=5846e53_LOGIN_HASH_d7e04e819 -Dsonar.projectKey=out.projectkey -Dsonar.branch.name=applethe difference is-Dsonar.host.url=https://sonar.corp.tld
I tried a branch build on an empty pom.$ mvn sonar:sonar -Dsonar.host.url=http://sonar.corp.tld -Dsonar.login=5846e53_LOGIN_HASH_d7e04e819 -Dsonar.projectKey=out.projectkey -Dsonar.branch.name=appleAnd I got this error:Parameter 'characteristic' must be a key-value pair with the format 'key=value'.From maven DEBUG logs, I see:[DEBUG] 21:45:02.528 Upload report [DEBUG] 21:45:03.459 POST 400 https://sonar.copr.tld/api/ce/submit?projectKey=our.projectkey&projectName=projName&characteristic=branch%253Dapple&characteristic=branchType%253DSHORT | time=928msOn the SonarQube server side, in log we can see:172.16.0.14 - - [06/Jul/2018:19:03:42 +0200] "POST /api/ce/submit?projectKey=our.projectkey&projectName=projName&characteristic=branch%253Dapple&characteristic=branchType%253DSHORT HTTP/1.1" 400 103 "-" "ScannerMaven/3.4.1.1168/3.5.0" "SERVER_ID"Sonar server: 7.1Maven version 3.5.4And i also tried the newst sonar maven plugin.We discovered, the problem seems, the double encodedbranchandbranchTypeofcharacteristicsURL param.Is there anybody who met same like that?Thanks, zsolt
sonar-scanner-maven fails on branch build
You can do analysis for free withSonarOpenCommunity/sonar-cxx. However, you need an external tool such as cppcheck in your dev machine to produce its results in XML format in a file.Here is how I was able to do it:Installsonar-c-plugin. For my version of sonarqube 5.6.1 I got this fromhttps://github.com/SonarOpenCommunity/sonar-cxx/releases/download/cxx-0.9.8/sonar-c-plugin-0.9.8.jarConfigure the sonar.c.cppcheck.reportPath property in sonarqube server at Administration / General Settings / C(Community) / Cppcheck report(s). I set it tobuild/cppcheck.xmlInstallcppcheckin dev machineRun cppcheck on your project and save results to build/cppcheck.xmlCreate a sonar-project.properties file at root of your project see below for my sampleInstall and runsonar-scannerHere is my sonar-project.properties file:sonar.host.url=http://mycompany.com:9000 sonar.projectKey=myprojectShortName sonar.projectName=myprojectLongname sonar.projectVersion=0.1 # Your relative path to source folder may be different sonar.sources=src/main/c sonar.language=c # The build-wrapper output dir sonar.cfamily.build-wrapper-output=bw-outputs # Encoding of the source files sonar.sourceEncoding=UTF-8
I am using sonar qube for analysing C files. I am not able to see the complete smells listed for C/C++ after analysis. For example Divide by Zero error is not listed in the code smell.My sonar scanner settings is reconfigured for C language using the optionsonar.language=cand used C language specific tags like,sonar.c.include directories. I am getting Lexer errors for the C files.Can anyone help me to solve this.
sonarqube scanner properties file for C project
.sahuses the standard JS syntax. You should be able to analyse sah files with the JavaScript plugin.Add the following line in your sonar-project.properties:sonar.javascript.file.suffixes=.js,.sah
I need to analyse my project using sonar qube. It contains files with .sah extension but basically those .sah files contains javascript code. I can analyse those files if i change files extensions from .sah to .js but its not a good way . Is there a way with which I can analyse my code without changing extension from *.sah to *.jsThanks..
Can SonarQube analyse my project if it has files with .sah extension
Your comments indicate that the two classes are in separate files. That's why the issue is not suppressed; cross-file analysis just isn't available in SonarJava.Your best course is to mark this a False Positive and move on.
Here is an example:public class A{ public boolean equals(Object a){ if(a == null) return false; // Some Implementation } } public class B extends A { public boolean equals(Object obj){ if(this == obj) return true; if(!super.equals(obj)) // null check for obj is already there in super.equals return false; if(getClass() != obj.getClass()) return false; // Some Implementation } }The rule for the issue observed isA "NullPointerException" could be thrown; "obj" is nullable here.My question is, what's the best way to handle such scenarios? Wouldn't the analysis not be able to always to identify the null check insuper.equals(obj)?
Sonarqube not analyzing super class equals and potentially throwing a false positive for NPE
In 6.7 the 'Update Center' was renamed to 'Marketplace' and moved into the top level of the admin menu:
I recently downloaded and setup SonarQube using these instructions:https://docs.sonarqube.org/display/SONAR/Get+Started+in+Two+MinutesI now want to open the Update Centre to install the C++ community plugin. However, I cannot find the Update Centre in the web interface. Can anyone please guide me on how to proceed with this?There is the screenshot from my administration (Administration>System tab)Thank you in advance.
Finding Update Centre in SonarQube
You are looking foranalysis parametersonar.projectDate, you could use this parameter to assign a date to the analysis.Note: This parameter is applicable to a few, special use cases, rather than being an "every day" parameter:When analyzing a new project, you may want to retroactively create some history for the project in order to get some information onquality trends over the last few versions.When moving from one database engine to another, it is highly recommended (even mandatory) to start from a fresh new databaseschema. In doing so, you will lose the entire history for all yourprojects. Which is why you may want to feed the new SonarQubedatabase with some historical data.To answer those use cases, you can use the sonar.projectDate property. The format is yyyy-MM-dd, for example: 2010-12-01.The process is the following:Retrieve the oldest version of your application's source that you wish to populate into the history (from a specific tag, whatever).Run a SonarQube analysis on this project by setting the sonar.projectDate property. Example: sonar-scanner-Dsonar.projectDate=2010-12-01Retrieve the next version of the source code of your application, update the sonar.projectDate property, and run another analysis. Andso on for all the versions of your application you're interested in.Since you cannot perform an analysis dated prior to the most recent one in the database, you must analyze your versions in chronological order, oldest first.
I use Git integrated with Team Foundation Server. The idea is to put Sonar as a step in TFS to stop the build according to the established rule. I need to know if it is possible for Sonar to apply the tests only for changes made as of a certain date. Example: I have a 1-year history of system changes. I'm going to put the Sonar step today. I want it to only check the changes made as of today. To reduce the initial impact, the idea would be to make a validation framework, and then validate what was left behind. It's possible?
Sonar: Validate changes from a date
There's a reasonthe Upgrade docsadvise you to read the release notes for each intervening version. Dashboards were dropped in SonarQube 6.2.You'll find that in 6.7.* you have the ability to visualize your measure values in each project's Measures page, and to see measure history graphs on the project Activity page. There are also some cross-project visualizations in the Projects page. If you nonetheless still need additional features, then you have the option to write a plugin toadd a page to the interface.
we upgraded Sonarqube to 6.7.2 version and this new version does not have the Dashboards and also configure widgets option with in the project custom dashboard is not available, is there a way to achieve the missing dashborads and custom widgets?
Sonarqube upgrade from 5.6.3 to 6.7.2 but Dashboards are missing
I got this working, the difference is that I have Jenkins for CI/CD and I am not using the GitLab CI/CD. Here is what I had to do:While executing the sonar scan I had to pass the below properties:sonar.analysis.mode=previewsonar.branch=$GIT_BRANCHsonar.gitlab.project_id={project_ID_from_GitLab}sonar.gitlab.commit_sha=$GIT_COMMITsonar.gitlab.ref_name=$GIT_BRANCHSonarQube needs to be run in the preview mode for it to publish the results in GitLab.Setup the GitLab URL and user access token on the SonarQube server.Make sure the GitLab certificate is trusted on the JRE/CACerts on the Sonar Server and the scanner server.Step 1: Browse to your GitLab URL in FirefoxStep 2: Click on the lock button next to the URLStep 3: Click on secure connection -> more informationStep 4: Click on view certificate -> Details -> ExportStep 5: Save the crt fileStep 6: On the Sonar server/scanner - open an Admin command promptStep 7: Browse to the Go to yourjava_home\jre\lib\securityfolderStep 8: run the following command, this will add the GitLab certificate to your Java trusted certificate list.keytool -import -alias example -keystore "C:\Program Files\Java\jre_version\lib\security\cacerts" -file pathtothefile.cerLet me know if this works for you.Edit- adding Jenkins configuration screenshot.
I currently have a jenkins job that is triggered when push or commit is maded within a gitlab project with use of a configurated webhooks. Everything works fine and projects are analysed when they're supposed to with SonarQube scanner for maven method, the problem is I want to then push SonarQube analyze results to a given project in form of global or inline comments. So I have installed on my sonarQube serverSonar Gitlab plugin. Problem is it's not making those comments with results.I have used default templates for global and inline comments as are stated in plugin documentation. My gitlab configuration on my SonarQube server looks like this:SonarQubeConfig1- The gitlab name is direct https link directly to a repositorySonarQubeConfig2- FreeMarker syntax configuration in global and inline comments is directly from the default template which you can find in Sonar Gitlab PluginSonarQubeConfig3I haven't added any other configuration in connection with this except from the ones I have staed in my post, thanks.
Why is Sonar GitLab Plugin not sending analyze results to gitlab as a comments while using default templates?
Using exceptions for control flow is generally not considered good coding practice. Reasons for this can be foundhere.If you still want this to work, you may be able to do this:while(true) { try { //code... } catch (Exception e) { //code... break; } }Thebreakwithin the loop should make it work.
I have a Java code as followstry { while (true) { // do something without break but will throw an expected // exception in some random iteration of the loop } } catch (Exception e) { // handled properly }This is reported by Sonar to be aBlocker Bug, description as mentionedhere. How can I get rid of this as I am actually expecting my loop to be ended by an exception and hence no break is required.
How to tell sonar about a managed infinite loop
As replied by Jeroen Heier in comments, removing users from Administration > Security > Users will allow you to reuse the login of the removed user with an LDAP account.If it's not the case, please describe what you're doing.
In our SonarQube instance we have recently enabled LDAP authentication. Prior to LDAP integration the users were manually created. It so happened some of the users were created using the same LDAP user ID and custom password.Now when LDAP is integrated we want all users use the LDAP ID/pass instead of previously manually created ID/password. SonarQube login works with manually created password rather than LDAP password. So how do remove the manually created users and only activate the LDAP users?PS: I dont see the option to delete but only to de-activate
How to delete a user from SonarQube and re-activate?
This method is called once when creating the application, I would ignore this warning.Essentially, that call is going to get compiled down to something like this (in Java):Arrays.copyOf(args, args.length));If you were to do this in a loop, or very frequently under load the warning would make sense. But for app-startup and only once at that, I'd just ignore it.
Is there any alternative to using a spread operator in such case? Or should I ignore the warning?
Kotlin - spread operator in SpringApplicationBuilder
The clone operation does a shallow copy, meaning that most of the Date's instance variables are shared between both instances. To fully solve the error you need to make an entirely new object in the regular sense.Maybe:return new Date(this.datime.getTime());
SonarQube keeps reporting an issue for rule "may expose internal representation by returning reference to mutable object".I fixed it based on aguide of the Carnegie Mellon University, but SonarQube still raises this issue:public Date getDatime(){ return (Date)this.datime.clone();//IJTI-316 // .getDatime() may expose internal representation by returning *.datime }How can I resolve / avoid this issue?
Can not resolve "May expose internal representation by returning reference to mutable object"
The particular rules you're looking for are "common" rules applied at the server. You're not going to see them in SonarLint. But in general:Out of the box, SonarLint runs with the Sonar way (default) profile. If you want additional rules applied in the IDE, you'll need to:set up a SonarQube instance (assuming you don't already have one)configure a Quality Profile to your likingapply it to your projectconnectyour project in the IDE to the project on the serverAt this point you will see (almost) all the same issues in both places.
I'm trying to create method without add comment or documentation it, I expected SonarLint would show errors based on rules, but I don't see any errors or warnings. Why?
SonarLint plugin in Eclipse not display Error Javadoc
It sounds like your project is not inConnected Mode. That would explain S3725 being raised - it is part of the Sonar way profile, which is used by default on un-connected projects. It would also explain why you don't see the same issues in SonarLint that you see in SonarQube.Your missing duplications issue is from one of theCommon rules. Those rules areonlyprocessed server-side. You won't see issues from them in pull request analysis, SonarLint, or any other context in which an analysis report isnotsubmitted to the server.
I'm using Eclipse Java EE IDE (Version: Oxygen Release (4.7.0)) with SonarLint (3.2.0) in connected mode (Sonarqube 6.5.0).Time by time I have the problem that the issues shown in SonarLint views (SonarLint On-The-Fly and SonarLint Report) are not the same than showing in Sonarqube.Interesting thing is that it is not reproducible using complete empty project only creating this single issueThe quality profile I'm using only contains the basic rules coming with Sonarqube (no additonal rules from PMD, Checkstyle or FindBugs)Rule not part of used quality profile ("Sonar way rules not included") but still shown in SonarLint (i.e. "Java 8's 'Files.exists' should not be used (squid:S3725)Issue shown in Sonarqube not available in SonarLint (i.e. "Source files should not have any duplicated blocks")Issue shown in SonarLint not active in quality profile (i.e "'Preconditions' and logging arguments should not require evaluation (squid:S2629)")Can someone tell me if it is a known issue that there are sometimes deviations between SonarLint and Sonarqube? Because the issue is not reproducible as single problem in sample project, I'm not able to localize the problem.Updated 21.09.2017 09:28As you can see in attached screenshots (as example for the deviations) there are differences even project is bind to Sonarqube server
Sonarlint issues shown in eclipse not synchronous to Sonarqube project
No, SonarQube does not provide sample data.However it is not difficult to get some data analyzed.Either create minimal contents like this:cd /tmp cd $(mktemp -d) pwd echo "public class MyClass1 {}" > MyClass1.java ~/SonarSource/sonar-scanner-2.8/bin/sonar-scanner -Dsonar.projectKey=my_project -Dsonar.sources=. -Dsonar.login=admin -Dsonar.password=admin -Dsonar.version=1Or check-out any pre-configured maven project (like for example"SonarSource/sonarqube"from github) and runmvn sonar:sonar.Another solution might be to analyse your plugin's own source code. You will probably have it already configured. This might have the additional benefit, that you know your own code well, which will make it easier for you to understand and verify SonarQube's findings and statistics.
I'd like to generate a dummy data for SonarQube to develop furtherQualinsight SVN Badges.Does SonarQube have the capability of generating "sandbox data" for developers? Or are there already features available for this kind of use-case?The things I need to generate for are data for LOCs, Coverage, New Coverage, and Vulnerabilities with their respective periods.
Generating dummy data for SonarQube
This is a known missing feature ofSonarLint For Eclipse.If you'd like the feature, vote for this JIRA issue:Add filtering capabilities on the On-The-Fly and Report views based on issue classificationshttps://jira.sonarsource.com/browse/SLE-195which has the description:We could offer:filter / group by issue severityfilter / group by issue typefilter issue tag (no group by since tags are not limited to a fixed list of values)Note that the SonarLint for IntellJ also lacks this feature according to this StackOverflow item:How to group Sonar results by severity (MAJOR, MINOR,CRITICAL) in intellij community edition
How can I group or sort theSonarLint for Eclipseanalysis results by severity?I have installedSonarLint For Eclipseplugin version 3.2.0 inEclipse Java EE IDE for Web Developersversion Neon.2 4.6.2. I right-click on an Eclipse project and selectSonarLint->Analyze. Eclipse populates theSonarLint Reportview with a "flat" list of all issues found. Sadly, there appears to be no way to group or sort the items by severity major, minor and critical.
How to group SonarLint for Eclipse 3.2.0 results by severity (MAJOR, MINOR, CRITICAL)?
By default a Maven analysis is not going to include resources files into the analysis. You need to do that manually by overridingsonar.sourceseither as a property in your pom or by defining (-D) it on the command line. I would guess that has been done in a property in the pom of the project that's being scanned like you want.
We have two Java web application projects being analyzed by the same instance of SonarQube (version 6.4). Both of these projects have Java, JavaScript, and CSS components and we would like to run analysis for those profiles.Project A is successfully being analyzed for all three languages while Project B is only being analyzed for Java.The global settings are pretty much out-of-the-box and neither project has any project-specific settings.We don't think it should have any impact, but Project A is a Spring MVC application that uses JSPs. Project B is a Spring Boot application that uses Thymeleaf.Project A does not have a sonar.properties or sonar-project.properties file. On Project B we have tried it without any properties and with properties trying to name it both sonar.properties and sonar-project.properties that set the sonar.language either js alone or java,js,css, but there appears to be no difference in behavior.SonarQube is getting kicked off by Jenkins (version 2.61) with the SonarQube Scanner for Jenkins (version 2.6.1) plugin.Both Jenkins projects are similarly configured and start the Sonar analysis as a Post Build Step:$SONAR_MAVEN_GOAL -Dsonar.host.url=$SONAR_HOST_URL -Dsonar.login=$SQ_LOGIN -Dsonar.password=$SQ_PASSWORDWe have even tried dropping the Sonar database and having Sonar rebuild it, but Project B is still only being analyzed for Java.EDIT:We would like project B to be analyzed by Java, JavaScript, and CSS just like Project A is.
SonarQube Project Does Not Get Analyzed by JavaScript Profile
This is a SonarQube 6.2+ feature. Make sure to use an appropriate SonarQube version.In additionsonar.testExecutionReportPathsdoes not allow matchers (like*).Please provide relative or absolute paths, comma separated.See also:The official documentationof the Generic Test Data featureThe source code, that looks up the generic execution files
The whole morning I have been trying to setup e2e tests reporting via SonarQube's Generic Execution, by using the Generic Test Data -> Generic Execution feature.I created a custom xml report that gets added to the scan properties like this:sonar.testExecutionReportPaths=**/e2e-report.xmlSo far, SonarQube seems to completely ignore this property and I no attempt to parse the file in the logs. Has anyone made it work?These are links by Sonar about the Generic Execution feature:https://docs.sonarqube.org/display/SONAR/Generic+Test+Datahttps://github.com/SonarSource/sonarqube/blob/master/sonar-scanner-engine/src/main/java/org/sonar/scanner/genericcoverage/GenericTestExecutionSensor.java
SonarQube Generic Execution Report is ignored
Problem is coming from the plugin binary not being executable by default (at least on my Ubuntu 16.04 / VSCode 1.14). I just needed to make it executable:cd ~/.vscode/extensions/silverbulleters.sonarqube-inject-1.3.0/tools/sonarlint-cli/bin/ chmod u+x sonarlintThen, restart VSCode and run the commandSonarQube Inject: Create global config with credentials to serversagain and setup servers.
I was having some problem running SonarQube plugin and SonarLint on Visual Studio Code. After installing the former or both plugins, I tried to run (following the tutorial...) the commandSonarQube Inject: Create global config with credentials to serverswhich ended up with the following messagecommand 'sonarqube-inject.analyzeProject' not found.
Run SonarQube plugin on Visual Studio Code on GNU/Linux
api/issues/searchdoes not allow to combine filters. It will "AND" all conditions together.I assumed that you are asking about how to query for these issues:CODE_SMELL | BUG | VULNERABILITY BLOCKER | YES | YES | YES CRITICAL | no | no | YES MAJOR | no | no | YES MINOR | no | no | YES INFO | no | no | YESSo I suggest:api/issues/search?severities=BLOCKER&types=CODE_SMELL,BUG(for to get all BLOCKER issues of CODE_SMELL and BUG)CODE_SMELL | BUG | VULNERABILITY BLOCKER | YES | YES | no CRITICAL | no | no | no MAJOR | no | no | no MINOR | no | no | no INFO | no | no | noapi/issues/search?types=VULNERABILITY(for to get all issues of VULNERABILITY)CODE_SMELL | BUG | VULNERABILITY BLOCKER | no | no | YES CRITICAL | no | no | YES MAJOR | no | no | YES MINOR | no | no | YES INFO | no | no | YESSo you will not have duplicated issues, but have to do two requests.
I would like to select from all the issues I have all the blocking issues and all the vulnerability issues, which are Blocker, Critical or Major. How can I do that in one request for SonarQube 6.4? If I dohttp://localhost:9000/api/issues/search severities=BLOCKER,CRITICAL,MAJOR&type=vulnerability&additionalFields=commentsI will have the vulnerability issues only.And if I do two requests, one for blocker issues and one for the vulnerabilities, I will have blocking vulnerabilities which are redundant.
How to use a union operator in SonarQube web services?
this is my solution:sonar.modules=A,B A.sonar.modules=a1,a2 B.sonar.modules=b1,b2 sonar.projectBaseDir=. sonar.sources=srcthe key point is projectBaseDir ,I hope this can help someone meet the similar problem.
My project structure looks like this:services A a1 a2 pom.xml B b1 b2 pom.xml pom.xmlI would like to scan the inner-most projects (a1,a2,b1,b2). In jenkins Post Steps, I added "Analysis properties" in Execute SonarQube Scanner without property files, mainly:sonar.modules=A,B sonar.sources=srcI would like to build from services directory, but it failed with this ERROR:The folder 'src' does not exist for 'A:a1'I understand, that SonarQube tries to findsrcinside the directoryA, but I have a few nested projects likea1(I also triedA.modules=a1,a2without success)How can I make the scanner analyze these projects?
How to nest multi-module maven projects in jenkins?
The error is due to some deactivations of rules in your Quality profile, for example see "restrict should not be used" in the changelog:https://sonarcloud.io/organizations/inilabs-github/quality_profiles/changelog?language=c&name=inilabs.This bug is tracked inhttps://jira.sonarsource.com/browse/SONAR-9489and will be fixed as soon as possible.A workaround is to copy the profile to another one. Corrupted rules won't be copied.Sorry for the inconvenience.
I've setup a build job in Travis with the Sonarcloud plugin so that it analyzes one of our C/C++ projects, links:GitHub source -https://github.com/inilabs/libcaerTravis job -https://travis-ci.org/inilabs/libcaer/jobs/247488797Sonarcloud -https://sonarcloud.io/dashboard?id=com.inilabs.libcaerNow if I run this with the default C quality profile "Sonar way" it works fine. Then I created a test profile where I added a one rule and deleted another, and this also worked, so basic custom quality profiles seem to work fine. Then I created our main quality profile "inilabs" that I want to use, where many more rules are enabled (~50) and several (~10) are disabled. Surprisingly this build fails during the 'sonar-scanner' step, with the following exception:java.lang.IllegalStateException: Unable to load component class org.sonar.scanner.report.ActiveRulesPublisher(see the above linked build for full error, run with 'sonar-scanner -X) It seems to get the files with the custom quality profiles fine, so the only thing I can think of is that there must be a specific rule in one of the ~60 changes that makes this fail, but I have no clue how to debug this to understand which one it is. I hope you can help me in pinpointing the problem, thanks!
Sonarcloud + Travis fails for custom C quality profile
From your question tags, I see that a Checkstyle based solution would also be helpful to you. TheImportControlcheck should be just what you need. Checkstyle also features aSonarQube pluginshould you require that.
When the application needs to query a remote system, we often create a β€œremote” package, with an β€œentity” sub-package containing classes that will be easier to process the info we retrieve. These classes shouldn’t leak out of the remote package.Is there any rule available (or under study) to check for importing x.y.remote.entities outside of x.y.remote package?
checking for illegal imports of remote.entities outside remote package
It is likely that your problem is caused bySONAR-8995, which is addressed in 6.3.1 (out soon), and 6.4.In brief, this is a bad interaction between issue exclusions and some updates to the way files are indexed for analysis in 6.3.
I have a project where SonarQube crashes during completion of the analysis for no reason (as far as I can see). We have many other projects which work fine with the same build steps.The completion complains about:ERROR: Error during SonarQube Scanner execution java.lang.IllegalStateException: Unable to read the source file : 'C:/TfsAgents/AgentB/_work/61/s/MyProject/Content/DataTables-1.9.4/docs/media/images/arrow.jpg' with the charset : 'UTF-8'. at org.sonar.scanner.issue.ignore.scanner.IssueExclusionsLoader.execute(IssueExclusionsLoader.java:69)I have tried excluding the wholeContentfolder and excluding all*.jpgfiles, and opening and resaving the jpg file to check it's ok (which it is).I'm at a loss of what else to check to get this working except perhaps deleting the file.Has anyone else seen this problem / got any possible causes? I can post more of the stack trace from SonarQube if it helps.We're on SonarQubeVersion 6.3 (build 19869)EDIT: This issue looks similar (SonarQube: Unable to read and import the source file '.../somefile.js' with the charset : 'UTF-8'), but has no solution and the link in the comments doesn't shed much light on things either.
SonarQube - java.lang.IllegalStateException: Unable to read the source file - x.jpg with the charset : 'UTF-8'
What you are trying to achieve is not possible with the SonarQube GitHub plugin. If you want PR analysis back, you have 2 ways:Either you gather those projects under the same umbrella, making them modules of a top projectOr you extract them in different repositoriesThe best solution depends on how your "new" projects are coupled to each other. If they have the same lifecycle (~ the same versioning scheme), then it's best to gather them under a top project. If not (i.e. they can be released independently with different versions), then moving them to dedicated repositories would be the best approach.
We used to have a big project that had SonarQube analysis run on it for every pull-request on GitHub. Everything worked fine.Then we did some refactoring, and split the code into separate projects. Since the code is related, the repo is still the same. But, instead of running just one build+analysis we run multiple ones per pull-request.Everything else works fine, except that the SonarQube GitHub plugin writes the problems found in the first build, then removes them in the second build and so on. So I get an email about problems in the first build, but when I go and look at the PR in GitHub, it's all green and no messages anywhere.Optimally I would like to specify to SonarQube GH plugin that these builds should be handled as separate in the PR, but I haven't found a way to do that yet.
Multiple SonarQube analysis on one pull-request
You have two solutions :Either you force users to be authenticated in order to access to SonarQube => Activate the "Force user authentication" settingOr you change permission of projects to remove the "Anyone" group => more details in thedoc
I am able to see project details on Sonarqube UI screen in spite of my login credentials. Is there any settings I need to change so that I can see all this details only after I login.[![enter image description here][1]][1]
Sonar-qube project details disclosed dispite of Login credentials
I found a work-around. I looked at thesource codeof Jenkins SonarQube Plugin (because I couldn't find the documentation) and found a list of exposed environment variables:Inject environment variables related to the chosen SonarQube installation.The following variables may be set depending on the configuration:SONAR_HOST_URLSONAR_AUTH_TOKENSONAR_LOGINSONAR_PASSWORDSONAR_JDBC_URLSONAR_JDBC_USERNAMESONAR_JDBC_PASSWORDSONAR_EXTRA_PROPSSONAR_MAVEN_GOAL - supplies the correct Maven goal based on the "Version of sonar-maven-plugin" specified for the SonarQube instance.These variables are useful when configuring a SonarQube analysis using standard build steps such as Maven, Gradle, Ant, and command line scripts.This feature is not needed if you're using "SonarQube Scanner" or "SonarQube Scanner for MSBuild" build steps.After adding-Dsonar.jdbc.url=$SONAR_JDBC_URLto my build step:it works fine.
I try to migrate my build jobs from Hudson to Jenkins (version 2.32.1). The Maven build works fine, but the Maven build step for SonarQube doesn't work. I use Jenkins SonarQube Plugin version 2.5.My SonarQube configuration (followingAdding SonarQube Scanner):My build environment (followingConfiguring a SonarQube Scanner using environment variables):My Maven build step (followingAnalyzing with SonarQube Scanner for Maven):Jenkins console log:[INFO] SonarQube version: 4.3 INFO: Default locale: "en_US", source code encoding: "cp1252" INFO: Work directory: /home/jenkins/.jenkins/jobs/test/workspace/target/sonar INFO: SonarQube Server 4.3 [INFO] [15:34:56.104] Load batch settings [INFO] [15:34:56.248] User cache: /home/jenkins/.sonar/cache [INFO] [15:34:56.254] Install plugins [INFO] [15:34:56.320] Install JDBC driver [WARN] [15:34:56.329] H2 database should be used for evaluation purpose only [INFO] [15:34:56.329] Create JDBC datasource for jdbc:h2:tcp://localhost/sonar [ERROR] Fail to connect to databaseLogs show, that Jenkins used the wrong database URL (H2 instead of PostgreSQL).What did I wrong?
How to connect Jenkins with SonarQube 4.3?
PerSonarQube's Duplications documentation:A piece of code is considered duplicated as soon as there are at least 100 successive and duplicated tokens (can be overridden with property sonar.cpd.${language}.minimumTokens) spread on at least 10 lines of code (can be overridden with property sonar.cpd.${language}.minimumLines).For Java projects, the duplication detection mechanism behaves slightly differently. A piece of code is considered as duplicated as soon as there is the same sequence of 10 successive statements whatever the number of tokens and lines. This threshold cannot be overridden.
I have followed below link which is for Java ScriptSonarqube: Is it possible to adapt duplication metric for javascript code?Similarly I have done for my Java project. And as per this if we wish to change the duplication criteria, i.e. by default 10 lines, we have to add one line in sonar.properties file which is stored in project.sonar.projectKey=Test sonar.projectName=Test sonar.projectVersion=1.0 sonar.sources=src sonar.language=java sonar.sourceEncoding=UTF-8 sonar.cpd.java.minimumLines=5But its not working for Java, is there anything else I need to configure?
Duplication Criteria in Sonar
There is not a matrix.The version you're on is compatible with Java 7. That means you can still compile with Java 6 (or 5 or heaven forfend 4), but the analysis must be run with Java 7.For SonarQube 5.6+ the requirement is Java 8. So again, compile with what you want, but analyze with Java 8.
We are working on a existing project which should be compiled only in Java 6 version.We have sonar 4.5.7 to analyze the code quality.Now my question is the sonar-maven-plugin compatibility version which should work with Java 6. I have tried sonar-maven-plugin ver 2.4 and this is not working with Java6. So can someone tell me what is the comparability matrix of sonar-maven-plugin wrt. to java version. I must tell you that i have maven 3 in my system.I have tried older version of sonar-maven-plugin 2.0 and they are not generating jacaco reports which i need to prepare the sonar dashboard for condition coverage.
what version of java is compatible sonar-maven-plugin
First of all, is this behaviour correct? Seems a bit weird that you are trying to callconvertStringtoDateon the exception message as well.Secondly, I had the same problem with Sonar recently. Seems like you need to pass the whole exception as a parameter to the logger, instead ofe.getMessage()for Sonar to realize you are logging the exception.Try this instead:public static Date convertStringtoDate(String stringDate){ stringDate = StringUtils.trimToNull(stringDate); SimpleDateFormat dfm = new SimpleDateFormat("dd-MMM-yyyy"); Date date = null; if(stringDate!=null){ try { date = dfm.parse(stringDate); } catch (Exception e) { logger.info("Cannot convert String to Date: ", e); } } return date; }
I am running SonarQube 5 for code quality check after integrating the code with Maven.Sonar is complaining that I should:Either log or rethrow this exception.in following piece of code:public static Date convertStringtoDate(String stringDate) { stringDate = StringUtils.trimToNull(stringDate); SimpleDateFormat dfm = new SimpleDateFormat("dd-MMM-yyyy"); Date date = null; if (stringDate != null) { try { date = dfm.parse(stringDate); } catch (Exception e) { logger.info("Cannot convert String to Date: ",convertStringtoDate(e.getMessage())); } } return date; }What am I missing here?
SonarQube complains: Either log or rethrow this exception
Motion Chart Plugin 1.7 is not compatible with SonarQube 6.0. For the time being, there's no plan to make it compatible.Edit:Nevertheless, I think that 2 new core features may help you manage your team on a day to day basis:the Leak Periodthe new Quality ModelThis features are central in the way we use our software everyday.
Since I updated sonarqube to version 6.0, I can't get motionchart plugin to work ... All I get is a blank widget and a red top band with a [hide] button. Besides, I have found errors like this in the server log:2016.08.26 14:23:19 ERROR web[rails] undefined method `snapshot' for #MeasureFilter::Row:0x641ff8d3Has someone got the motion chart plugin 1.7 to work with sonarqube version 6.0?
sonarqube 6.0 and motion chart plugin
For FxCop it's pretty straightforward: in SonarQube, use theTemplate for custom FxCop rules(self-documented).For StyleCop there wasa pluginbut it's now deprecated.
How to add the custom rules created in stylecop or fxcop to sonarqube for c# and trigger the same.? where i need to put the custom rule-set dll and xml file.??Little help would be great..
How to add the custom rules in sonarqube for c# and trigger the same
No it's not possible to feed sonarlint-cli with sonar-project.properties. You must use a dedicated sonarlint.json configuration file. Seehttp://www.sonarlint.org/commandline/index.html
My objective is to run sonar scan and provide early feed back on defects without uploading scan result to sonar server.I am planning to use sonarlint-cli to scan code as soon as Git merge request is crated. This will help me to report issues early without running full sonar scan.I already have multiple module sonar-project.properties at the root folder of source code.Can I use same sonar-project.properties with sonarlint-cli?
Is it possible to provide sonar-project.properties to sonarlint-cli?
The closest you can come with out-of-the-box features is setting a custom Metric to indicate whether mutation testing is needed, implemented, or not-needed.Then you can do a Measures search to find the relevant projects, and use a Measure Filter Widget to display the search results on your dashboard.
I am working on adding plug-ins to my company's SonarQube dashboard. They wanted me to put 2 labels on the dash board,The Total number of projects that have mutation testingandThe projects that need Mutation testing.I am usingSonarQube Java APIalong which AngularJS for UI.I am looking for help on how to do this. Thank you in advance.
How to know if a project implemented mutation testing in SonarQube, programatically?
Bogdan, the same happened to me. You need to upgrade your C# plug-in to be at least version 5.3.1Indeed, Visual Studio 2015 Update 3 introduced a breaking change in the Static Analysis Result Interchange Format (SARIF) generated by the C#/VB compiler. As a result the C# plug-in could not find any issue any longer. SonarSource reacted quickly by providing a bug fix version (5.3.1) Note that this should not happen again as now SARIF has moved to version 1.0 (that happened in VS 2015 Update 3, and its versioning will be fully supported moving forward)
I upgraded my build agent to Visual Studio 2015 Update 3 and I noticed that C# code analysis issues are no longer reported.I am using SonarQube 5.6
SonarQube no longer detects C# issues
You can't modify an existing rule. A workaround is towrite a custom rule.However, you should first seriously consider whether the behavior you want to achieve is really specific to your own environment. If that's not the case, you can suggest a change to the existing rule by joining theSonarQube google group.
I wonder how to modify an existing rule in SonarQube. For example this rule:( Remove this commented out code ) /* ..... commented code ..... /*I want to modify this rule, to ignore the commented code containing@any_thinglike this://@anything /* ..... commented code ..... /*Or like this:/* @anything ..... commented code ..... /*How can I fix this?
How to modify an existing rule in SonarQube?
There is not a way you can apply two different rule profiles to the same project at the same time. You can choose one or the other but to have the rules from both you'll either need to edit one of them or create a 3rd profile.Note that this is not hard too do.create a new profile (it's empty at this point)go to theRulespageUse the Quality Profile facet to search for the rules active in the first source profile - click on the profile, and 'active'UseBulk Changeto activate them in your new profilerepeat steps 3 & 4 for each source profile.There's no need to worry about overlaps - rules active in multiple source profiles will be activated once and only once in your target profile.
I wanted to have an extensive static analysis of our code so chose FindBugs as the Sonar profile. However I also want to have a good security analysis too for which I can see there's a profile called Findbugs security Audit in SonarQube. Is there a way where I can use both of them to analyse our code without having to create a custom profile?Thanks
Findbugs and FindSecBugs in Sonar
As the warning in the footer states quite clearly, youcannotmigrate the H2 database. That'swhythere's a big red warning in the footer when you're using the embedded database. It's for initial evaluation purposes only.
I've been using the embedded H2 database with SonarQube 5.1 for a while but am now looking to migrate to a PostgreSQl db, can you advise me on how to do this?My only worry is that the 'ignore issue' feature will not be ported when moving to the new db, is there any way I can avoid this from happening?Thanks
Migrating from H2 embedded database to PostgreSQL
There's no replacement for this property. Instead, make your project-profile associations via the UI.
I am using sonarqube 4.5.4,and hence thesonar.profileis deprecated for the sonar version of 4.5.4,Please suggest what alternative tag can be used for the same.Regards, Namratha
sonar.profile is deprecated for 4.5.4 Sonarqube
I figured out what was going wrong. I noticed in the logs when I ran Sonar with log level set to debug I was getting the following message.- parsing <directory>/target/test-reports - Reports path contains no files matching TEST-.*.xml : <directory>/target/test-reportsI had set my "sonar.junit.reportsPath" correctly, but Sonar was expecting the xml files in my directory to start with "TEST-". When I renamed the xml files to start with TEST- the results then displayed on the dashboard.
I can't figure out how to get the "Unit Test SUccess" section to appear on my SonarQube dashboard. I've tried setting every sonar and sonar.java I can think of but they just don't appear. I am using the "sbt-sonarrunner-plugin", version 1.0.4, and Jacoco for calculating coverage. Any help would be greatly appreciated, as everything I have found says that settings the sonar.junit.reportsPath property should make it work. For reference I have also tried setting the sonar.test property and it didn't work either.This is what the unit test widget looks like.Here are my properties, the project name and directory are passed in.val commonSonarProperties = Map( "sonar.projectName" -> s"$projectName", "sonar.junit.reportsPath" -> s"$projectDir/target/test-reports", s"$projectName.sonar.sources" -> s"$projectDir/src/main/java", "sonar.java.binaries" -> s"$projectDir/target/classes", "sonar.java.test" -> s"$projectDir/src/test/java", "sonar.java.test.binaries" -> s"$projectDir/target/test-classes", "sonar.java.coveragePlugin" -> "jacoco", "sonar.jacoco.reportPath" -> s"$projectDir/target/jacoco/jacoco.exec", "sonar.jacoco.itReportPath" -> s"$projectDir/target/it-jacoco/jacoco.exec" )
Can't get Unit Test Success in SonarQube
Since SonarQube 5.4 the only Differential Period available for Quality Gate conditions is the Leak Period (see5.4 Upgrade Notes).The Leak Period can be customized at a project level (seeDifferential Views Settings). It currently defaults tosince_previous_versionbut you are free to set it toprevious_analysis(amongst other options) if you wish.
We want to upgrade our SonarQube Server from the 5.0 version to the current 5.4. We imported our Quality Profiles, and had to set the Quality Gates manually (we found no way to do that automatically).Now I have the problem, that i cant use the Value Ξ” since previous analysis , only "Value" and "Leak". We have to use this property, because our company have large projects with legacy Code.Does anyone know, what happened with this Property?
Quality Gate periods (SonarQube 5.4)
SonarLint does not yet support rules from custom plugins, seeMMF-248.
I have created a sonarqube custom rule for Java. It seems to be working when I check it in the sonarqube server UI.I have configured sonarlint with my eclipse but sonarlint is not reporting any error for my custom rule. How shall I add that, so that the sonarlint displays the error for my custom rule after analysis.I am using:javaFileScannerContext.addIssue(importTree, this, "Avoid imports (3rd party imports)");to add the issue. How can this issue be reported on eclipse side?
sonarlint(eclipse) not reporting error for my Java custom rule
FindBugs Plugincalls externalFindBugs analyzer- it means that they are the same rules.Read more onhttps://github.com/SonarQubeCommunity/sonar-findbugs#compatibility
Are the findbugs rules that come with sonarqube find-bugs plugin and the actual findbugs rules that come when findbugs is installed in eclipse one and the same.If not , is there any way to use the actual findbugs ruleset in sonarqube instead of using the ruleset that comes with findbugs sonarqube plugin?Thanks
Are the findbugs rules that come with sonarqube findbugs plugin same as the actual findbugs rules
See if this helps:2008 (MSSQL Server 10.0) with bundled Microsoft JDBC driver. Express Edition is supported. (tick) 2012 (MSSQL Server 11.0) with bundled Microsoft JDBC driver. Express Edition is supported. (tick) 2014 (MSSQL Server 12.0) with bundled Microsoft JDBC driver. Express Edition is supported. (warning) Collation must be case-sensitive (CS) and accent-sensitive (AS) (info) Both Windows authentication (β€œIntegrated Security”) and SQL Server authentication are supported. See the Microsoft SQL Server section in Installing page for instructions on configuring authentication.Duplicate key error with SonarQube 5.2
I keep getting this error when analyzing .net project using msbuild runner - ### Error updating database. Cause: com.microsoft.sqlserver.jdbc.SQLServerException: Cannot insert duplicate key row in object 'dbo.projects' with unique index 'projects_uuid'. The duplicate key value is (AVDyMY-5YwVQNVOkEEHa).
SonarQube - Cannot insert duplicate key row in object 'dbo.projects'
You must execute sonar-runnerfromthe project base directory. Socd my/project/base/dir sonar-runnerEDITThe base assumption withsonar-runneris that you're invoking itinthe directory where you want it to do its work. The only arguments* it ever took were "tasks" to be performed, but those are no longer supported.*Note that youcandefine (-D) parameters to be used during analysis on the command line.
I install SonarQube 5.2 and Sonar-runner 2.4 (latest versions). I managed to start SonarQube but I get the following error when trying to run Sonar-runner:ERROR: Unable to execute Sonar ERROR: Caused by: Tasks are no more supported on batch side since SonarQube 5.2 ERROR:EDIT: The following exception is thrown when I run the command with --debugERROR: Error during Sonar runner execution org.sonar.runner.impl.RunnerException: Unable to execute Sonar at org.sonar.runner.impl.BatchLauncher$1.delegateExecution(BatchLauncher.java:91) at org.sonar.runner.impl.BatchLauncher$1.run(BatchLauncher.java:75) at java.security.AccessController.doPrivileged(Native Method) at org.sonar.runner.impl.BatchLauncher.doExecute(BatchLauncher.java:69) at org.sonar.runner.impl.BatchLauncher.execute(BatchLauncher.java:50) at org.sonar.runner.api.EmbeddedRunner.doExecute(EmbeddedRunner.java:102) at org.sonar.runner.api.Runner.execute(Runner.java:100) at org.sonar.runner.Main.executeTask(Main.java:70) at org.sonar.runner.Main.execute(Main.java:59) at org.sonar.runner.Main.main(Main.java:53) Caused by: Tasks are no more supported on batch side since SonarQube 5.2It is there any configuration that should be changed to be able to analyze a project?Thank you
Tasks are no more supported on batch side since SonarQube 5.2
You don't specify your version of the platform, so I'll assume the latest & recommend the resource API.http://nemo.sonarqube.org/api/resources/indexgives you a list of projects - with id'sYou can setdepthto -1 to see all children, and add the list ofmetricsyou want included, to get complexity and whatever else you need. E.G.http://nemo.sonarqube.org/api/resources/index?resource=808785&depth=1&metrics=complexityEDITHere's what the docs say aboutdepth:Used only when resource is set:0: only selected resource-1: all children, including selected resource>0: depth toward the selected resourceDefault value: 0 Example value: -1Essentially, in your project tree,depthdetermines how many levels of children to retrieve from the specifiedresource.
I have checked in some files under svn and run a nightly build to publish the report for those files on Sonar dashboard. Now I have some custom reporting which use cyclomatic complexity of those files from sonar using api.As I checked there is a rest api to get the CC from resource ID but I don't have that also because info which is available that is only file name with absolute path. So if I go for current rest api then first how may I get resource id for that particular file then I can get CC for that file using another api.Someone can help me to get the CC using resources or file name by using rest api.
What's way to get the cyclomatic complexity of a file using sonar rest api?
You need to analyze the project after configuring Quality Gates.
I'm using sonar 5.1.2. I created a simple quality gate and associated it to my project. Then I went on the main dashboard and added the Quality Gate widget, configured it for my project, and then saved.Note, on the dashboard edition page (where you select widgets), under my new quality gate widget, it says : "No data".When I return to the dashboard I cannot see the widget. I can successfully add other widgets, but this one just won't show itself.Note that my project is a maven multi-module project (a big one). Tried it on a smaller project and had the same problem.Is there something to know about this widget that could explain why I don't see it ?
Sonarqube : Can not see quality gate widget on dashboards
Unless you are using that code in a loop, there no bad in your first way (String concatination). For a single attempt you can use that.As someone commented I assume by writingsign.append("-");, you meansign +="-"If you are using in a loop I suggest to useStringBuilderinstead ofStringBuffersince there is another overhead withStringBufferis it is synchronized. Unless you need Thread safety, better to change it toStringBuilder.I'm not sure why SonarQube suggest you to useStringBuffer.
This question already has answers here:StringBuilder vs String concatenation in toString() in Java(20 answers)Closed8 years ago.I would like to know if this use of StringBuffer does the same thing as my previous code, because SonarQube asks me not to use+=for appending strings.My previous code :String sign = ""; if (value < 0) { sign.append("-"); }My new code with StringBuffer :StringBuffer sign = new StringBuffer(); sign.append(""); if (value < 0) { sign.append("-"); }Is this better this way ?Thanks for your advices.
Using String Buffer For String Appends in Java [duplicate]
You can analyze as many language as you want.You want Multi-language Project.When you download the plugin for a particular language, you will see profile for every language. You can view those profiles under "Quality profiles" link like "Java profile" , "Xml profile", "c profiles" etc.Every profile will have a same name called "sonar way". In sonar.properties file while analyzing your source code, do not specify sonar.language rather specify sonar.profile=sonar way. In this manner it picks all the languages which is under sonar way profile. However sonar.profile has been deprecated but we still use it :-).However you should read thispagefor Multi-language Project . You can alsoprovisionthe project to support Multi-language Project.They are many ways to do.You can opt whichever you like.
Sonar newbie here. I am setting SonarQube up on my project. I have files in about 10 languages, but i'm interested in C# and C++ analyzis only. I know that you can analyze files in one language or every language, but is there a way to do it for exactly two languages? Any help or example would be appreciated as I really hope that excluding files is not the only option here.
Sonar analyze for two languages
You simply need to assign the project to those non-default profiles. Someone with admin rights on the project can do that, and of course global admins can too.
Maybe this is already a feature of Sonarqube, but I can’t find evidence of it anywhere. We have projects that contain java, javascript, and groovy code. I can analyze each language separately, or I can do a multi-language analysis if I use the default quality profiles for each language. But I can’t figure out how to use three custom profiles (java, javascript, and groovy) for the same project. Is it possible?I’m currently running Sonarqube 4.3.3, and using the maven to build and analyze the projects.
Sonarqube: use multiple custom quality profiles for a single multilanguage project...?
You might be interested in profile inheritance:http://docs.sonarqube.org/display/SONAR/Non-rule+Profile+Edits+and+Information#Non-ruleProfileEditsandInformation-ProfileInheritance
I would like to use the default rule set provided by sonarqube (5.1.2) which is collected in the default profile "sonar way". Now I need to add/remove some rules. What is the bets practice here? So far I have created a copy of the default profile and applied my changes there. Then after installing a new plugin I noticed that the default profile has been extend by some rules (obviously the useful ones) of that new plugin. So I need to add them manually to my custom profile. I reckon the same happens with updates of the java plugin.My questions:Should I work with a copy of the original profile to not pollute it and retain the opportunity to restore it to the factory defaults? (conclusion: manual work every time an update or new plugin comes in)Should work with the original profile? (will it then still be updated without conflicts on new plugins/updates?)Is there a way to work with a profile that is linked to the original profile? (like an overlay filesystem over a read only filesystem => OverlayFS)
Sonarqube profiles best practices
As you can read inBug 474406it is a bug of Hudson 3.3.x. It has nothing to do withSonar Plugin2.0.1, which worked fine with Hudson 3.1.2.It happens with Hudson post build action in:Free-style projectLegacy Maven project typeA work-around is to add abuild parameterto a job, seeBug 474406:
I configured a post build sonarqube analysis with the hudson SonarPlugin. I configured the MAVEN_OPTS for the SonarPlugin to be like this: "-Xmx1024m -Dmaven.javadoc.failOnError=false"If I run the job there is an error when hudson tries to execute the post build action:[workspace] $ mvn -f /home/hudson-3.3.0/jobs/myJob/workspace/pom.xml -e -B sonar:sonar -Dsonar.jdbc.driver=oracle.jdbc.OracleDriver -Dsonar.jdbc.url=jdbc:oracle:thin:@xxxxx:1521/xxxx ******** ******** -Dsonar.host.url=http://xxxx:9000/sonarError:Could not find or load main class MAVEN_OPTSSonar analysis completed: FAILUREI use the following setup:Tomcat 8.0.24Hudson 3.3.0Sonar-Plugin 2.0.1Maven 3.0.5 / 3.2.5JDK 1.7.0_45On a older hudson version with Sonar-Plugin 1.8.1 the build worked.As workaround I configured my MAVEN_OPTS path variable to contain the expected settings but since I have to configure different jobs with different settings this is only a workaround.Anybody got an idea how to fix this issue?
Hudson SonarPlugin fails if MAVEN_OPTS are set in build job
About methods, fields and inner classes:Havingmethods(or fields or inner classes) being public in a package-private class implies thatif extended with a public class, the public members from the package-private class will be visible from the outside! Consequently, they have to be considered as being public, and therefore documented.Example:package-privateclassA:package org.foo; class A { public int field; public void method() {} public class Inner {} }publicclassB:package org.foo; public class B extends A { }other package, classC:package org.bar; public class C { void test() { B b = new B(); int f = b.field; // visible B.Inner = b.new Inner(); // visible b.method(); // visible } }About constructors:As constructors of the package-private class are only visible from the same package, and these constructors won't be callable from another package, even through public child class, it's indeed wrong to raise an issue on them and it should be corrected in the SQ rule from the java plugin (seeSONARJAVA-1557).I would however recommend to lower the visibility of that constructor, as having it public is somehow senseless...
I have some classes, which are visible only in package. After analysis I received issues related with missing documentation on public constructors/methods/types etc.Is this a bug (false positive)? It seems to me that change from public to not public constructors/methods/types is senseless.I useSonarQube5.1.1 andJava Plugin3.4.
How to solve squid:UndocumentedApi on public method in package classes
I had to explicitly have sonar.sources property in each of the module.sonarqube { properties { properties["sonar.sources"] += "src" }}
I have a multi-module gradle project created in android studio and want to run an analysis using sonarqube. The project structure is as below root (no source files) Module 1 com.myapp.module1 package1 package2Module 2 (structure similar to that of Module 1)I added the sonarqube plugin in the build.gradle file in root along with the following sonarqube properties: a) Host URL b) jdbc url c) Username for jdbc d) password for jdbcI use gradlew for the build. When I run gradlew sonarqube from my root directory, sonarqube runs but indicates that 0 files are indexed for all the modules.What am I missing here? It should be something fairly obvious but I have not been able to find an answer in the existing stackoverflow archives.
Not able to get sonarqube to index files in my multi module gradle project
Maybe you can use the toolNDepend.It isintegrated with SonarQube.It comes with both build-in code metrics:Cyclomatic Complexity computed from source codeCyclomatic Complexity computed from IL code.It is integrated in Visual Studio and it makes it easy to write custom code rule. Such arule is actually a C# LINQ query.For example if you want to write a code rule to match methods that are both complex and poorly covered by tests, just write:// <Name>Complex methods poorly covered by tests</Name> warnif count > 0 from m in Application.Methods where m.CyclomaticComplexity > 10 && m.PercentageCoverage < 20 select new { m, m.CyclomaticComplexity, m.PercentageCoverage, m.NbLinesOfCode }Disclaimer: I work for NDepend
I need to calculate the cyclomatic complexity of C# methods and need to define the rule according to the CC value, in the FXcop 12.0.I've found that the tools likeCode Metricsprovide functionality to calculate the CC values, but I don't know how to use it in my code. Basically my requirement is the value of CC to reported via Sonar.If anybody has written a custom rule for this or any idea how to do this, Please help
C# :Cyclomatic Complexity of a method with FxCop sdk
Since it was a multi module project, I had to include the propertiessonar.sourcesandsonar.testsin the parent module'spom.xmlfile.<properties> <sonar.sources>pom.xml,src/main,src/test</sonar.sources> <sonar.tests></sonar.tests> </properties>sonar.testsparameter is empty since it is incompatible with Maven.
I am trying to run a sonar maven analysis on my multilanguage project which contains many languages like *.java, *.groovy, *.js etc. I have installed all the languages plugin in my sonar and configured my pomsonar.sourcesparameter assrc/main,src/testbut still it picks up only java files. In the console output. I get the following lines in the console indicating that it only scans the folders with patternsrc/main/javaandsrc/test/java[INFO] [05:13:57.140] ------------- Scan myapp [INFO] [05:13:57.140] Load module settings [INFO] [05:13:57.187] Initializer FindbugsMavenInitializer [INFO] [05:13:57.187] Initializer FindbugsMavenInitializer (done) | time=0ms [INFO] [05:13:57.187] Base dir: C:\myapp [INFO] [05:13:57.187] Working dir: C:\myapp\target\sonar [INFO] [05:13:57.187] Source paths: pom.xml, src/main/java [INFO] [05:13:57.187] Test paths: src/test/javaI am currently using SonarQube 5.1, Java 7u80Note: If analysis is done using Sonar Runner, It scans all the files.
sonar maven analysis only picks .java file
As of 6/12/15 it's been resolved that the Maven Sonar plugin does not support Maven 3's parallel build feature:http://jira.sonarsource.com/browse/MSONAR-7
Since maven supports multithread builds, would it be possible to also run sonar multithreaded? (e.g.mvn sonar:sonar -T 4)I ran it and while the module reported success, it reports back as the overall build failing withjava.util.concurrent.ExcutionException: java.lang.NullPointerExceptionThoughts?
Maven Sonarqube Plugin: Multithreading
I discovered that I could useproject.getExtensions().sonarRunner.sonarProperties{ ... }to set the sonar properties. See example below.class MySonarPlugin implements Plugin<Project> { @Override void apply(Project project) { project.apply plugin:'sonar-runner' project.getExtensions().sonarRunner.sonarProperties { property 'sonar.host.url', 'http://mySonar.company.com' property 'sonar.jdbc.url', 'jdbc:mysql://127.0.0.1:1234/sonar' } } }
I am creating a gradle plugin to apply the sonar-runner plugin and default many of the values such as the sonar host URL and the sonar JDBC URL. I cannot figure out how to set the properties though.When I set this up in build.gradle I use:apply plugin: 'sonar-runner' sonarRunner { sonarProperties { property 'sonar.host.url', 'http://mySonar.company.com' property 'sonar.jdbc.url', 'jdbc:mysql://127.0.0.1:1234/sonar' } }My gradle plugin looks like:class MySonarPlugin implements Plugin<Project> { @Override void apply(Project project) { project.apply plugin: 'sonar-runner' project.configurations { sonarRunner { sonarProperties { property 'sonar.host.url', 'http://mySonar.company.com' property 'sonar.jdbc.url', 'jdbc:mysql://127.0.0.1:1234/sonar' } } } } }With this setup I get aNo signature of methodexception. How should I be setting these properties?
How do I set task properties in a Gradle Plugin
Your server does not have enough available disk space to feed its internal Elasticsearch indices. Note that an external volume can be used by setting the property sonar.path.data (see conf/sonar.properties).
I have recently migrated from SonarQube 3.7.2 to SonarQube 5.1. Update was successfull and I was able to run analysis.However now I cannot reach the server and from log it seems ElasticSearch is slowly eating away my disk space.I tried to restart the server and to delete the data/es directory, but nothing helped.sonar.logis full of these lines:... 2015.05.18 00:00:13 WARN es[o.e.c.r.a.decider] [sonar-1431686361188] high disk watermark [10%] exceeded on [Jbz_O0pFRKecav4NT3DWzQ][sonar-1431686361188] free: 5.6gb[3.8%], shards will be relocated away from this node 2015.05.18 00:00:13 INFO es[o.e.c.r.a.decider] [sonar-1431686361188] high disk watermark exceeded on one or more nodes, rerouting shards ...There are just a few Java projects, but two of them are around a couple million lines of code (LOC).
SonarQube 5.1 too busy due to ElasticSearch
For the moment, this is not possible to fully synchronize rules and quality profiles between 2 servers because ofSONAR-5366. You can watch and vote for this ticket.Concerning the cache that you seem to have, this is probably the E/S indexes which are located in<install_dir>/data/esfolder. What you can do is:stop you serverfully delete the<install_dir>/datafolderrestart the server: your rules should be in sync with the DB
We currently have two SonarQube servers (v4.5.1) running on two separate Windows 2012 servers each with its own MS SQL database server. One is our Development server and the other is our production server. The idea being that we test out all rule changes on the development server first, once we are happy that they are correct we port them to the Production server.When we first setup the two servers we simply took a backup of the Development server database and restored it on the Production server. At this point both systems were in sync.We have recently made some modifications to the Development rules set, however when we tried the same approach to move these to the production server it did not work.The production box seemed to remember the previous rule set. There seems to be a cache of the previous rules that we can't work out how to clear.Before restarting SonarQube with the new DB in place we deleted the temp folder as that appears to keep a cached H2 database, but that did not solve the issue. We also tried starting it up and using the /setup url but this did not appear to work either.Is there a way to completely reset the SonarQube server prior to restoring the database so that it has no knowledge of the previous rule set?Alternatively is there a better way to export and re-import the entire rule set between two servers?We looked at exporting the rule profile, but this did not appear to contain the full detail of the rules.Thanks Pete
How do you replicate rules between SonarQube servers?
If you want to add a project to your instance of SonarQube, just analyze it and it should appear on the dashboards right after analysis (this requires that you have the global "Execute Analysis" permission).If you wish to have an Open Source project appear onthe SonarQube public instance on Nemo, please send an email to theSonarQube Users mailing list.
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed9 years ago.Improve this questionDoes anyone know how to add a project? I faced with problem. I don't know exactly how to add project to sonarqube. I will be very appreciated.
How to add another project to Sonarqube? [closed]
The newly added key for NUnit test reports can be found on the project c# settings page - under UNit Tests tab, and its value is:sonar.cs.nunit.reportsPathsProvided value should be the .xml output from the NUnit console runner.
I see that sonarcube re-added nunit test results support since Nov 7 2014:http://docs.sonarqube.org/display/SONAR/C%23+PluginHowever, I did not find anything that showed how to do this in the sonar-project.properties file.For example, see the one they provide on git hub here:https://github.com/SonarSource/sonar-examples/blob/master/projects/languages/csharp/sonar-project.propertiesWhat nunit specific line should be put in this file to replace the "sonar.cs.vstest.reportsPaths=TestResults/*.trx" mstest line?Thanks!
How to include nunit test results in sonarcube 4.5.1 c# plugin 3.3 sonar-project.properties file?
Those Checkstyle rules (like "ConstantNameCheck") are defined with a multiple cardinality in the SonarQube Checkstyle plugin. This means that it should be possible to activate several "instances" of those rules with different values for its parameters.In SonarQube 4.4+, it is no more possible to have multiple activations of those rules. They are considered as "rule templates", which means that you must create custom rules (with explicit parameters) out of them in order to be able to activate them on quality profiles.Everything is explained on theRules documentation page.
I'm trying to create a new quality profile with existing checkstyle ruleset but get the error message:Rule template can't be activated on a Quality profile: checkstyle:com.puppycrawl.tools.checkstyle.checks.naming.ConstantNameCheckI use the simplest ruleset example from thecheckstyle officail site:<module name="Checker"> <module name="JavadocPackage"/> <module name="TreeWalker"> <module name="AvoidStarImport"/> <module name="ConstantName"/> <module name="EmptyBlock"/> </module> </module>Versions: Sonar 4.5.1 with Checkstyle plugin 2.1.1What is wrong?
Sonar Checkstyle import: Rule template can't be activated on a Quality profile
If these are open source libraries that you don't want analyzed at all, you can exclude them from analysis altogether usingsonar.exclusions. Else, you can add an exclusion pattern to avoid the creation of issues on those files, so that their technical debt will effectively be 0, while other metrics will be computed (lines of code, duplications etc.) - seesonar.issue.ignore.multicriteria.
I have a project that I am using SonarQube 4.4 to track code quality on. The Technical Debt section (no longer a plug-in as they have merged it into the main project I believe) picks up several open source libraries in my project that I would like to ignore. Other sections in SonarQube allow for exclusions (i.e. Jacoco and/or Cobertura honor the exclusions in the exclusions tab) but the Technical Debt calculator does not seem to honor them.Is it possible to exclude files from Technical Debt analysis? If so, how?
How do I ignore files/folders in SonarQube 4.4's Technical Debt calulation?
This log indicates that the batch is updating a semaphore in the DB to make sure that it is still alive. This allows tthe backend to know when a batch has been killed without letting it end properly - which could result in inconsistencies in the DB.In upcoming versions, we're going to decouple the batch analysis from the DB to prevent any direct access to it. When this is done, this mechanism will be useless and therefore dropped.
I ran Maven debugger and when during "Load Module Settings" phase of Sonar analysis, Maven outputted "Updating Semaphore Batch". What does this statement mean? Does Sonar interact with either the database or the Sonar server during this point?Thanks
SonarQube - What is "Updating Semaphore Batch?
The two issues you raise are indeed false positive raised by the rule. Bug tickets have been created:https://jira.codehaus.org/browse/SONARJAVA-553andhttps://jira.codehaus.org/browse/SONARJAVA-591To detail a little bit : When there is athisreference an issue should not be raised (2nd case) because it is actually not fixable and I think this rule should only be applied Single Abstract Method interfaces and not for every anonymous class to fix the issue of the first case.
These code examples:public abstract class Main { public abstract void myMethod(); public static void main(String[] args) { Main main = new Main() { @Override public void myMethod() { // TODO Auto-generated method stub } }; main.myMethod(); } }import java.util.Observable; import java.util.Observer; public abstract class Main { public static void main(String[] args) { Observable observable = new Observable(); observable.addObserver(new Observer() { @Override public void update(Observable o, Object arg) { o.deleteObserver(this); } }); } }are noncompliant with thissonarqube rule:Anonymous inner classes containing only one method should become lambdas : Make this anonymous inner class a lambdahow can i fix it ?
Sonar : Anonymous inner classes containing only one method should become lambdas
It is the correct way to implement a custom rule. You can see your rule if you filter on inactive rules.
We have implemented a custom rule based on the BaseTreeVisitor inhttps://github.com/SonarSource/sonar-java/tree/master/java-checks/src/main/java/org/sonar/java/checksas described inhttp://docs.sonarqube.org/display/SONAR/Extending+Coding+Rules. We are able to deploy it and it appears as a new plugin in Sonar, but we couldn't find a way to add it to any of the quality profiles.Is this the correct way to implement a custom rule? If yes, how to deploy & use it in a profile properly?
SonarQube Java plugin custom rule
You want to create an XPath-based rule for the C# language, so here's how to proceed:Log in as Administrator in your SonarQube instance.Go in your quality profile and look for the "XPath" rule.Seethis rule on NemoClick on "Copy" link on this rule.Fill all the required information to create your new XPath-based rule.Once you save it, you'll be redirected to this new rule in your quality profile: just activate it by checking the box.
I am new to SONAR. Planning to create a new rule//ifStatement/statement[not(block)] ->rulethis is the test rule I want to create but when i navigate to quality profile as administrator I get this screen shot and there is no new rule link. Can any one help me in getting started on how to create a new rule. Thanks for your help.
How to create a new rule in sonar
ID is "squid" and repository name is "Sonar"
When browsing a quality profile, I can't seem to filter out rules covered by the squid plugin specifically. Under the repository filter, squid doesn't show up as an option (just PMD, Checkstyle, etc).The reason I'm concerned about this is that the 'avoid use of deprecated method' rule was inactive by default, and I had to try and dig it out by searching in the inactive rules. Now I'm wondering what other squid rules I'm missing out on.Does this sound right?
SonarQube 3.7 squid rules repository
You should be throwing MyException(e) and MyException(e1), respectively.
In my code I got a rule violation called 'preserve stack trace' while I have analysed the code on sonar.try { doSomething(); } catch(IllegalStateException e) { try { doAnotherThing(); } catch(IOException e1) { throw new MyException(e1.getCause()); } throw new MyException(e.getCause()); }So how to preserve the stack trace in this case?
How to preserve stack trace in this case?
You can also remotely debug part of your Sonar plugin running on batch side if you executesonar-runnerwith the following java options-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000but indeed there is no way to do hot deployment.
General question that I cannot seem to get an answer for from the SonarQube confluence page.I am looking to write a plugin for Sonar, but am unable to effectively setup my environment in an effective manner. I am able to connect a debugger to a Sonar server instance (by enabling the debug line in the wrapper config file) and I am able to hit breakpoints as the plugin is accessed from the Sonar UI, but....I can't seem to hook up a debugger during the analysis portion of the plugin. That is, when running sonar-runner on a project.I can't seem to figure out how to hot deploy the plugin. We should not have to build a deployable jar and move it over to sonar/plugins every time.Seems I would need to ideally run Sonar out of Eclipse and emulate the sonar-runner.If anyone has resources that talk about configuring this, that would be great. The official website is a bit sparse.Thanks
Writing/Debugging Sonar plugin with hot deploy
Apparently, your Gradle project group or name contains a whitespace. This value becomes part of the default value for the Sonar project key, which must not contain whitespace. To fix the problem, you can either reconfigure the Gradle project group or name (it's safer not to have a whitespace in there anyway), or reconfigure the Sonar project key for the project that applies thesonar-runnerplugin. The latter could look like this:sonarProperties { property "sonar.projectKey", "foo:shared" }If the offender is the Gradle project name (rather than the group), you may have to reconfigure"sonar.projectName"as well.
I am trying to set up SonarQube with a gradle project.I have started a local Sonar process:C:\Dev\Sonar\sonar-3.7\bin\windows-x86-64>StartSonar.bat wrapper | --> Wrapper Started as Console wrapper | Launching a JVM... jvm 1 | Wrapper (Version 3.2.3) http://wrapper.tanukisoftware.org jvm 1 | Copyright 1999-2006 Tanuki Software, Inc. All Rights Reserved. jvm 1 | jvm 1 | 2013-08-15 15:44:56.847:INFO:oejs.Server:jetty-7.6.11.v20130520 jvm 1 | JRuby limited openssl loaded. http://jruby.org/openssl jvm 1 | gem install jruby-openssl for full support. jvm 1 | 2013-08-15 15:45:27.198:INFO:oejsh.ContextHandler:started o.e.j.w.Web AppContext{/,file:/C:/Dev/Sonar/sonar-3.7/war/sonar-server/},file:/C:/Dev/Sonar/ sonar-3.7/war/sonar-server jvm 1 | 2013-08-15 15:45:27.261:INFO:oejs.AbstractConnector:Started SelectCha[emailΒ protected]:9000I have applied the Sonar Plugin:apply plugin: "sonar-runner"When I execute the Gradle Sonar task, I seeing this error:gradle sonarRunner...* What went wrong: Execution failed for task ':shared:sonarRunner'. > org.sonar.api.utils.SonarException: Validation of project reactor failed: o root[mod_EricFrancis2]:shared is not a valid project or module keyDoes anyone have any ideas on how to fix this error? Could it be a memory issue?
org.sonar.api.utils.SonarException: Validation of project reactor failed
To remove a rule, you just need to edit the quality profile that you're using on your project and remove the rule from this profile.More details here:http://docs.codehaus.org/display/SONAR/Quality+Profiles#QualityProfiles-EditingProfileIf you just want to disable the rule on a specific part of the code, then you can use the SwitchOffViolation plugin.More detais here:http://docs.codehaus.org/display/SONAR/Switch+Off+Violations+Plugin
We're using Sonar to perform code analysis. A design decision was made regarding the location of interfaces vs implementation classes that leads to sonar (correctly) finding a package cycle.Since this is known and accepted on the current project, how can I disable the check, preferably in code?I've tried putting//NOSONARon the import line causing the cycle as well as@SuppressWarnings("CycleBetweenPackages")just above the class declaration, but neither have made sonar ignore this error for the class in question.
How to disable "avoid cycle between java packages" in Sonar?
You can get measures of a developer for a specific project with the following API call:http://nemo.sonarsource.org/api/resources?resource=DEV:Fabrice%20Bellingard:org.codehaus.sonar:sonar&metrics=ncloc,coverageThe resource key is composite and consists of:"DEV:"the user name":"the project keyNote that not all the metrics are computed on developers. For instance, you won't be able to have the complexity for the moment. You can see which metrics are computed when you go on a developer dashboard: for instance, the API call above gives metrics aboutme on Sonar.
I've been trying Sonar'sWeb Service APIand so far it seems to offer a lot of information. However, looks like working on a per developer level is not easy - or supported.For instance, there are two things I'd like to fetch:A list of the developers of a project. I know that usingqualifiers=DEVI can get a list of all the developers in the system (sample request), but can't filter by project.Filter metrics by developer and project. For instance,get the cyclomatic complexity of the code of developer D1 in project P1. How'd I do that? Is it even possible?
Sonar Web Service API, filter data by developer
Ok, looks like I was using some deprecated properties. Once I enabled debug on the plugin I was able to get useful infoHere is what worked for me with LDAP plugin 1.2.1 and sonar 3.4sonar.security.realm: LDAP #sonar.authenticator.class: org.sonar.plugins.ldap.LdapAuthenticator -- use above sonar.authenticator.createUsers: true ldap.url: ldap://server:389 ldap.user.baseDn: DC=mycompany,DC=com ldap.bindDn: CN=myuser,OU=serviceaccounts,OU=MyGroup,DC=mycompany,DC=com ldap.bindPassword: password #ldap.user.objectClass: user -- use the ones below #ldap.group.objectClass: group -- use the ones below #ldap.group.memberAttribute: member --use the ones below #ldap.user.loginAttribute: sAMAccountName -- use the ones below ldap.group.request: (&(objectClass=group)(member={dn})) ldap.user.request: (&(objectClass=user)(sAMAccountName={login}))
I am trying to get Sonar to use LDAP authentication against Active DirectoryI have the following settings# LDAP Authentication sonar.security.realm: LDAP sonar.authenticator.class: org.sonar.plugins.ldap.LdapAuthenticator sonar.authenticator.createUsers: true ldap.url: ldap://172.20.16.15:389 ldap.baseDn: DC=mycompany,DC=com ldap.bindDn: CN=myuser,OU=serviceaccounts,OU=My Group,DC=mycompany,DC=com ldap.bindPassword: password ldap.loginAttribute: sAMAccountName ldap.userObjectClass: user # ldap.user.request: sAMAccountName={0}However, I keep gettingERROR rails Error from external users provider: java.lang.NullPointerException: nullI tried changing ldap.loginAttribute/ ldap.userObjectClass with ldap.user.request but that still does not work.The sonar ldap plugin I have is 1.2.1. Please help me identify what is wrong with the configI have used the same entries with ADExplorer to ensure that I can browse the AD and the same/similar settings work with Artifactory
Sonar 3.4 LDAP authentication with Active Directory - NullPointer exception
Indeed, by definition Jacoco instruments all java bytecode but you can tune this behavior with help of the 'excludes'/'includes' Jacoco parameters, seehttp://www.eclemma.org/jacoco/trunk/doc/agent.html.
Cobertura works by first 1) instrumenting the source files to be traced, and 2) executing the unit tests and comparing those to the instrumented classes. This way we can calculate the code coverage.However with JaCoCo for integration tests (Selenium) I have not seen this "instrumentation" phase in documentation. The JaCoCo Agent is just set to dynamically trace the source code covered "on the fly" when executing tests. How does JaCoCo know what source code to compare against, since the code has not been priorly instrumented as with Cobertura? Also, what if I want to exclude some source code?
How does JaCoCo for integration tests in Sonar actually work, compared to Cobertura?
I would suggest that you do not analyse the Sonar database schema too much (unless you plan to be a Sonar developer).The best (and recommended way) to interact with Sonar is via the publishedREST API
In sonar by which algorithm the folders and files are stored in the "projects" table.which are the files using to store these datas to "projects" table.Thanks
Sonar database
You should not try to extend Sonar DB when developing a plugin, otherwise this will cost you a lot when doing the successive migrations to future versions of Sonar.Instead, you should use Sonar API to achieve what you want. And if you miss some features, then you can come and discuss it on Sonar DEV mailing-list.But I advise you not to try to do some fancy stuff with the DB, that will cost you a lot of effort to maintain in the future.
I have to create a new table in sonar database to develop my plugin.Is it possible to create a new table in sonar database using java.
Creating a new table in sonar database