Response
stringlengths 8
2k
| Instruction
stringlengths 18
2k
| Prompt
stringlengths 14
160
|
---|---|---|
No bugs here, just some subtleties aboutLDAP Pluginconfiguration and behaviour. :)Case-insensitive loginSetsonar.authenticator.downcasetotruewhen delegating authentication to an LDAP/AD server which is case-insensitive.Group mapping behaviourWhen group mapping is configured (i.e. you manually configuredldap.group.*or you use thewindows authentication modewith lightweight AD config), membership in LDAP/AD will override any membership locally configured in SonarQube. LDAP/AD becomes the one and only place to manage group membership (and the info is fetched each time the user logs in).
|
I am checking SonarQube 5.4 and the latest LDAP plugin 1.5.1. There are however a couple of issues.First. My AD account is majcicam. If I log in with it, it is correctly shown in the users list. However if I login with MajcicaM (note capital letters) another additional user is added to the list:As you can see from the attached image. For every login that I do make, seems it is treated as case sensitive and thinks of it as a different user.Second thing. Once I assign a group to my user, on the next login those settings are gone. Seems that they are not persisted.Am I doing something wrong? Is this a bug? Are my settings messed up?ThanksMario
|
SonarQube and LDAP - Case sensitive logins
|
We have SonarQube 5.1.2. This is how I would try to fix this issue with our version. If this exact procedure doesn't work, maybe it will give you ideas for solving the problem and then we'll refine the answer.Log into SonarQubeView the multi-module projectIn the project menu, click Settings --> Update KeyFindmodule-bin the list of keys, and provide an alternative name - maybemodule-b-oldRun multi-module analysis to see if that still worksRunmodule-banalysis to see if that works now.There is also a Reset link; not sure what that does.
|
I have a project with an aggregator POM and several submodules:com.example:root
|- com.example:module-a
|- com.example:module-b
|- com.example:module-cIt was decided thatmodule-bneeds to be a separate project, so the directorymodule-bwas split off into a separate git repository.Now we have 2 projects:com.example:root
|- com.example:module-a
|- com.example:module-c
com.example:module-bcom.example:rootwas analyzed for a long time with SonarQube. I use the maven goalsonar:sonar.Now when I analyzecom.example:module-bwith SonarQube, I get this error:2016.02.16 13:03:24 ERROR [o.s.s.c.t.CeWorkerCallableImpl] Failed to execute task AVLqLZdJf9ZlZw0WwFfK
org.sonar.api.utils.MessageException: Validation of project failed:
o The project "com.example:project-b" is already defined in SonarQube but as a module of project "com.example:root". If you really want to stop directly analysing project "com.example:root", please first delete it from SonarQube and then relaunch the analysis of project "com.example:project-b".
2016.02.16 13:03:24 ERROR [o.s.s.c.t.CeWorkerCallableImpl] Executed task | project=com.example:project-b | id=AVLqLZdJf9ZlZw0WwFfK | time=302msThe thing is, yes, in the pastcom.example:project-bwas indeed a module ofcom.example:root, but it isn't any more now. I also don't want to stop analyzingcom.example:rootand I don't want to delete it and loose all history and all other modules.How do I solve this?
|
SonarQube: How to analyze project that used to be submodule of another project?
|
SonarQube 5.2 is expected late October 2015 / early November 2015.Update: SonarQube 5.2 was released on November 2th, 2015.
|
Apparently, SonarQube 5.2 won't need a connection string to push build data. (I discovered this by having a look at the sonar.runner vso-build-tasks earlier this morning).When will this version be available?
|
Is there a planned release date for sonarqube 5.2?
|
I think this is what you are after[hostname]/api/resources?resource=[com.test]:[module-name]:[fully qualified class]&metrics=coverage,branch_coverageI have added an example below.http://sonar-server/api/resources?resource=com.test:module:com.test.service.impl.CheckServiceImpl&metrics=coverage,branch_coverageI looked at the page you shared and used this also :http://docs.codehaus.org/pages/viewpage.action?pageId=229743280
|
I am trying to retrieve the unit test code coverage for individual classes through the SonarQube API (Sonar version 4.1.2). Everything is working fine, and I can see the metrics okay when I go directly to the sonar dashboard and go to the coverage tab for a class:93.9% by unit tests Line coverage: 97.9% (285/291) Branch coverage: 85.0% (113/133)Can anyone tell me the correct call to retrieve this same/similar information through the sonar API interface please? I've already had a look at the documentation athttp://docs.sonarqube.org/display/SONAR/Metric+definitionsand can get test coverage metrics back at project level but I can't see how to construct a query for individual classes.
|
Sonarqube API single class test coverage
|
Recent Sonar versions require Gradle 2.2. (2.1 might also work but I'm not sure.)
|
I have updatedSonarto the 4.5.1 LTS version, and now in my gradle task i have got the following error and can't fix it:Fail to download libraries from serverbuild.gradle with sonar runnersonarRunner {
sonarProperties {
property "sonar.host.url", "http://sonar:9000"
property "sonar.login", ""
property "sonar.password", ""
property "sonar.jdbc.url", "jdbc:mysql://sonar"
property "sonar.jdbc.driverClassName", "com.mysql.jdbc.Driver"
property "sonar.jdbc.username", "sonar"
property "sonar.jdbc.password", "sonar"
property "sonar.profile", "sonar"
property "sonar.projectName", "sonar"
property "sonar.language", "java"
property "sonar.sources", "src/main/java"
property "sonar.binaries", "build";
}
}i've tried to write this property, but nothing happend:toolVersion = '2.3' // default
|
SonarRunner with gradle: Fail to download libraries from server
|
We use ant rather than maven, and an older version of the Sonar ant task at that. But what works for us is setting a sonar.exclusions property in our build.xml, which accepts wildcards for filenames. For example:<property name="sonar.exclusions" value="**/com/ex/wsdl/asvc/*.java,**/com/ex/wsdl/bsvc/*.java"/>That skips analyzing all the code generated from a wsdl file for two services. You ought to be able to do something similar for maven.
|
The code base I am working with has a lot of generated code. In addition, there are also some deprecated files that I would want to exclude from SonarQube analysis. I've read up the documentation and looked at some answers on here about that, but it does not help in my case.I have a multi-module maven project. So I have multiple projects in my workspace that are all part of a large application. Say I want to exclude this file:/home/username/workspace/com.mst.rtra.importing.message/bin/com/mst/rtra/importing/message/idl/parse/idlparser.javaI don't really know how to write this in the exclusions settings on SonarQube because of how long the filepath is. Also, what if I want to exclude another file, but from a different module, say :/home/username/workspace/com.mst.rtra.interpreter.create/I am confused about I should write this in the exclusions box in project settings. Should I write the absolute file path due to the multi-module nature of this project? Or is there some other convention used?In addition, if I want to exclude generated files from analysis, I would need to putfile:/generated-sources/as I saw in another answer. However, after analysis, I can still view the analysis results of those files when I open up the project in SonarQube dashboard.
|
SonarQube excluding files, directories, and generated code?
|
Well, 3.0.0 RC1 is released today (25.06.2014) and we plan to release 3.0.0 final (if there will be no major regressions reported) in July.Update: 3.0.0 is releasedon 06.07.2014, seehttps://mailman.cs.umd.edu/pipermail/findbugs-discuss/2014-July/004029.html
|
My understanding is that Findbugs 3.0.0 will support analyzing Java 8 bytecode. I see that there is a beta version of it available here:http://sourceforge.net/projects/findbugs/files/findbugs/3.0.0/SonarQube is waiting until the final version of Findbugs 3.0.0 is released before upgrading their Java plugin to use it. This means SonarQube is unable to analyze our Java 8 projects.Is there a target date for Findbugs 3.0.0 release or a known workaround for using the beta version of it with SonarQube?
|
When will Findbugs 3.0.0 FINAL be released?
|
I decided to create a simple template file as a quick work around.
Just search/replace for a unique string in the template file and save to a new sonar-project.properties file for the project.Here's some sample code in case anyone's interested:$hg_version = hg identify -n
(get-content {C:\dev\myProj\sonar-project.template | foreach-object {$_ -replace "my_proj_version", $hg_version}) | set-content c:\dev\myProj\sonar-project.properties
sonar-runnerHope this is helpful for anyone else finding this.
|
Is there a way to use sonar-runner to dynamically update the project version for every build without having to manually update the sonar-project.properties file each time?
(note: this is for a non-mavenized .NET MVC app)Was trying to parameterize the properties file having it reference an environment var set automaticallyAdded in sonar-runner.batfor /f "delims=" %%i in ('hg identify -n') do set HG_LOCAL_REV=%%iModified sonar-project.properitessonar.projectVersion=%HG_LOCAL_REV% #don't want to have to manually update thisWould be great if we could just pass the projectVersion as a parameter for sonar-runner.bat
|
How to dynamically set ProjectVersion with Sonar-Runner.bat
|
This error can also happen if you have2 Sonar instances pointing at the same database. You can only have one Sonar instance per database.Sonar updates a row in thepropertiestable whereprop_key = 'sonar.core.id'every time it starts up, and then compares the cached value against the one in the database whenever an analysis is executed. If the two don't match then you get the error.To fix it, shut down both instances then only restart the instance you want to keep. Sonar will reset the sonar.core.id value and things should work again.You can get the server's cached id via REST:http://server:port/sonar/api/serverIt has to match the one in the database for Sonar to work.select * from properties where prop_key = 'sonar.core.id'
|
I have installed sonar and mysql database on server A and on server B. I'm trying to run sonar analysis using sonar-runner but every time I get the following error:Caused by: java.lang.RuntimeException: wrapper
at org.picocontainer.lifecycle.ReflectionLifecycleStrategy.monitorAndThrowReflectionLifecycleException(ReflectionLifecycleStrategy.java:130)
... 22 more
Caused by: org.sonar.core.persistence.BadDatabaseVersion: The current batch process and the configured remote server do not share the same DB configuration.
- Batch side: jdbc:mysql://xx.xx.xx.xx:3306/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true (sonar / *****)
- Server side: check the configuration at http://xx.xx.xx.xx:9000/systemServer B is accessing DB from server A. I have checked all configurations from batch and server side everything seems to be ok.I also googled and found thefollowing link,
but I cannot understand what to do for resolving this issue.Any pointers?
|
Sonar throwing error BadDatabaseVersion
|
I haven't used them but theSonar documentationdescribes the additional properties that would enable historical analysis. Specifically it's the "sonar.projectDate" property you need to set.You haven't specified which Java build technology you're using. I've included some examples below.Finally, have you considered setting up Jenkins to launch Sonar, instead of cron? Lots of good reasons for running Jenkins, but if you're using Maven as your build tool, theJenkins Sonar pluginmakes Sonar integration very easy.Maven examplemvn clean install -DskipTests=true
mvn -Dsonar.projectDate=2012-09-01 sonar:sonarANT exampleant -Dsonar.projectDate=2012-09-01 clean sonarNote:This assumes you have a target called "sonar" setup to compile, test and run sonar.
|
A while ago I setupSonarto scan a development project. The scans are invoked nightly using a cronjob. At one point I had an issue with the machine that run the cronjob and a few nightly scans were missed. I downloaded the source code from one of the days that was missed, and completed a new Sonar scan using Sonar Runner. As I expected the data shows up in Sonar as the most recent scan which is not what I want. I would like to inject that scan in to a specific date so I can fill the days when the scan was not run. I did not see an option to do this in the sonar-project.properties file.Is there a way I can run a Sonar scan, but have the data be entered on a date of my choice rather than the current date, so it shows up in the appropriate position in my Sonar timelines?
|
Injecting a Sonar analysis before an existing one
|
You need to set the following paramater to tell Sonar to use a pre-generated report:sonar.dynamicAnalysis=reuseReportsSecondly Sonar doesn't read the "cobertura.ser" file. It can be configured as follows to read the generated XML report (See cobertura docs):sonar.cobertura.reportPath=target/reports/coverage.xmlFinally, my reference for all this stuff comes from the from the Sonar wiki:http://docs.codehaus.org/display/SONAR/Advanced+Parametershttp://docs.codehaus.org/display/SONAR/Code+Coverage+by+Unit+Testshttp://docs.codehaus.org/display/SONAR/Code+Coverage+by+Integration+TestsThe Sonarsource tutorials are increasingly pushing JaCoCo. This appears to be an emerging standard (replacing the older defunct Emma project)
|
I have a cobertura.ser file, that got generated while integration-test and system test. Now I want to import my coverage this to sonar server.How can I achieve this, so while executing mvn sonar:sonar the coverage should consider external coberture.ser file?Can I do this using sonar, where i can see overall coverage obtain during all test run?
|
SONAR importing cobertura.ser coverage reports to sonar server using mvn sonar:sonar?
|
You can not associate your project in Eclipse if you haven't first analysed it with Sonar (by running "mvn sonar:sonar" on your project).Once your project has been succesfully analysed and that you can browse it in the Web UI (http://localhost:9000 by default), then you can try to associate your project within Eclipse and this will work.
|
I'm trying to use Sonar to analyse my projects in Eclipse. I am currently using Maven in eclipse. I installed the Sonar Eclipse plugin as described inthis link.But when I try and associate my project with Sonar, I get an error saying:
project with key not found on server.Am I missing some steps? I started the Sonar Server before connecting to eclipse. But nothing works.
I even tried following this article (Sonar plugin Eclipse) but to no avail.Please help..The Sonar documentation is not descriptive at all making it very hard for beginners like me to understand.
|
Using the sonar plugin with eclipse
|
The screenshot only shows code coverage for packagescom.gfs.transportation.transprointegration.filewatcher
com.gfs.transportation.transprointegration.filewatcher.implIf the Code coverage for the below components are 100%com.gfs.transportation.transprointegration
com.gfs.transportation
com.gfs
comThen total coverage will be (87.9 + 89.2 + 100 + 100 + 100 + 100) /600
which equals 96.183%I am thinking if a package has no classes under it then the coverage of the package is 100%
|
Maybe this is due to my own misunderstanding of what in Sonar is being analyzed, but at the Component level Sonar is reporting a much higher percentage of code coverage than what appears to be possible given the results at the package level.
May I point your attention to the attached screenshot...
See:https://i.stack.imgur.com/yCnms.pngAny ideas?
|
Sonar Code Coverage Analysis Doesn't Add Up
|
Do not use negated conditions in ternary operators.
Try replacing this:return breakStartTime != null ? new Date(breakStartTime.getTime()) : null;with this:return breakStartTime == null ? null : new Date(breakStartTime.getTime());The same applies to yourif-elselogic.
Replace this:if (breakStartTime != null) {
return new Date(breakStartTime.getTime());
} else {
return null;
}with this:if (breakStartTime == null) {
return null;
} else {
return new Date(breakStartTime.getTime());
}
|
Sonar reported Confusing Ternary violation against the below code:package com.example.dto;
import java.util.Date;
public class ShiftTemplateUserDTO {
private Date breakStartTime;
private Date breakEndTime;
public Date getBreakStartTime() {
return breakStartTime != null ? new Date(breakStartTime.getTime()) : null;
}
public void setBreakStartTime(Date breakStartTime) {
this.breakStartTime = breakStartTime != null ? new Date(breakStartTime.getTime()) : null;
}
public Date getBreakEndTime() {
return breakEndTime != null ? new Date(breakEndTime.getTime()) : null;
}
public void setBreakEndTime(Date breakEndTime) {
this.breakEndTime = breakEndTime != null ? new Date(breakEndTime.getTime()) : null;
}
}I tried updating the code to add if/else condition but still Sonar is complaining about the same rule, what am I doing wrong?public Date getBreakStartTime() {
if (breakStartTime != null) {
return new Date(breakStartTime.getTime());
} else {
return null;
}
}
public void setBreakStartTime(Date breakStartTime) {
if (breakStartTime != null) {
this.breakStartTime = new Date(breakStartTime.getTime());
} else {
this.breakStartTime = null;
}
}
|
Java Confusing Ternary Sonar Violation Issue
|
try to disable the "sonar.scm.exclusions" setting, it works for us.sonar.scm.exclusions.disabled=true
|
I can't change any settings on the SonarQube server, I can only change the parameters I feed the scanner.My 'sources' is actually pointing at a submodule's directory, but every file within it is ignored. It seems as though files in submodules are being ignored by SonarQube.Is there any way to override this behavior?
|
SonarQube is ignoring all files in submodules: 11:55:09.209 DEBUG: File 'C:/...' is excluded by the scm ignore settings
|
You can useOWASP Encoderto encode user input:<dependency>
<groupId>org.owasp.encoder</groupId>
<artifactId>encoder</artifactId>
<version>1.2.3</version>
</dependency>AddEncode.forJava(userInput)for user input which will:Encodes for a Java string. This method will use "\b", "\t", "\r",
"\f", "\n", """, "'", "\", octal and unicode escapes. Valid
surrogate pairing is not checked. The caller must provide the
enclosing quotation characters. This method is useful for when writing
code generators and outputting debug messages.So in your case it may be:Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = Encode.forJava(headerNames.nextElement());
if (headerName.equalsIgnoreCase("SampleHeader"){
headers.add(headerName, request.getHeader(headerName));
}
}
|
I'm trying to add custom header in my HTTPHeader like belowEnumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
if (headerName.equalsIgnoreCase("SampleHeader"){
headers.add(headerName, request.getHeader(headerName));
}
}but I'm getting below bug while running sonar."Refactor this code to not place tainted, user-controlled data in the header."I think adding a regex might solve my problem, but I had two problems.I'm need to write an regex that allow alphabets, number and . , ! - _ But I'm unable to create one.I'm not sure checking using some regex will debinately solve my problem.
|
Refactor this code to not place tainted, user-controlled data in the header
|
I had the same problem, it seem it was an issue of jacoco when generating the report, more info on this issue:https://github.com/jacoco/jacoco/issues/763The solution:upgrade to0.8.3that was release with that issue fixed.With the new version of jacoco now my classes that had zero coverage on sonar now have the real coverage.
|
I'm having some issues when trying to import Jacoco code coverage to sonar, this is happening to all Koin modules.Sonar version:7.5.0.20127Jacoco version:0.8.2Erro:ERROR: Cannot import coverage information for file 'mmaccount/src/main/java/br/com/project/mmaccount/di/AccountModule.kt', coverage data is invalid. Error: {}
java.lang.IllegalStateException: Line 84 is out of range in the file mmaccount/src/main/java/br/com/project/mmaccount/di/AccountModule.kt (lines: 83)
at org.sonar.api.internal.google.common.base.Preconditions.checkState(Preconditions.java:197)
at org.sonar.api.batch.sensor.coverage.internal.DefaultCoverage.validateLine(DefaultCoverage.java:93)
at org.sonar.api.batch.sensor.coverage.internal.DefaultCoverage.lineHits(DefaultCoverage.java:81)And because of this, my module class is with 0% of o coverage, but if I look the HTML report it seems to work fine:Jacoco HTML reportThis is happening only with my Koin modules, I'm not sure if the problem is how Koin works or some incompatibility between Jacoco and Kotlin
|
SonarQube + Jacoco - Unable to read Koin module test coverage
|
The only "default" SonarQube database is the embedded H2 database, which is providedsolely for initial testing. It is neither intended nor supported for production use. Youwill notbe able to upgrade with this database. As a large red banner should be telling you at the bottom of every single page in the SonarQube interface.But okay, to answer your question, you can use any generic client to make this update. I generally useSQuirreL SQLon the rare occasions I need to peer intothe black boxthat is the SonarQube database.
|
I'm trying to reset the admin password of my SonarQube and I have already found that is executing the following query:update users set crypted_password = '88c991e39bb88b94178123a849606905ebf440f5', salt='6522f3c5007ae910ad690bb1bdbf264a34884c6d' where login = 'admin'But the thing is that I don't know what is the database manager where I need to execute it and how to connect to it. When I installed my SonarQube and my SonarQube Scanner I didn't specified any database manager.
|
What is the default sonar database?
|
Jenkins was running as local system user. I change it to a normal Windows user and it did the trick. dotnet build was not using Sonarqube dedicated targets.
Thanks you @Valeri!
|
I'm trying to launch Sonarqube on a .NET Core 2.0 solution from Jenkins using SOnarQube MsBuild on Windows.It works fine when i execute the following script from Jenkins workspace:C:\SonarQube\bin\MSBuild.SonarQube.Runner.exe begin /k:XXXX.Campaigns /n:CI /v: /d:sonar.host.url=http://x.x.x.x:9000 /d:sonar.verbose=true /d:sonar.projectBaseDir="C:\Program Files (x86)\Jenkins\workspace\CI"
dotnet clean
dotnet build
C:\SonarQube\bin\MSBuild.SonarQube.Runner.exe endBut when i execute the same command from Jenkins, i got this message:The SonarQube MSBuild integration failed: SonarQube was
unable to collect the required information about your projects.
Possible causes:The project has not been built - the project must be built in
between the begin and end steps.An unsupported version of MSBuild
has been used to build the project. Currently MSBuild 14.0 upwardsThe begin, build or end steps have not all been
launched from the same folderI use Jenkins 2.46.2 - MSBuild 15 - Sonarqube 6.7 & Sonar MsBuild 4.0.2.892. I tried using Jenkins build steps, command step, command step with a script without success. On a classical .Net 4.5.2 project, it works.
|
Sonarqube with dotnet core works fine on command line but not from Jenkins
|
As you pointed out, there is a free and open source edition, namedCommunity Edition.Some plugins and features are not in theCommunity Edition(and they are not OSS), however the platform (SonarQube) is the same, but you will have to upgrade toDeveloper EditionorEnterprise Edition(and if you want high availability to theDataCenter Edition) to be able to use the features.When you have installed commercial edition, the licence options will appear in the Administration page.Disclosure : I'm working for SonarSource.
|
I'm confused about SonrQube usage. According to theSonarQube documentationSonarQube® software (previously called Sonar) is an open source quality management platformAt the same time SonarSource sells somesubscription plansand somecommercial plug-ins.My first question is: can we use commercial plugins with the open source SonarQube Community version?Another question is: when I installed the Community version 6.7 LTS I am not able to find any license option under administration? Am I missing something here?
|
Can I use SonarQube 6.7 LTS Community version with commercial plugins?
|
completing @JulienL.-SonarSourceTeam advice:changingsonar:sonartoorg.sonarsource.scanner.maven:sonar-maven-plugin:3.4.0.905:sonarsolved the problemso now it is:./mvnw -X clean org.jacoco:jacoco-maven-plugin:prepare-agent package org.sonarsource.scanner.maven:sonar-maven-plugin:3.4.0.905:sonar -Dsonar.host.url=https://sonarcloud.io -Dsonar.organization=xxxx-github -Dsonar.login=yyyy
|
I have an public project on github. i try to attach sonarcloud to it:./mvnw -X clean org.jacoco:jacoco-maven-plugin:prepare-agent package sonar:sonar -Dsonar.host.url=https://sonarcloud.io -Dsonar.organization=xxxx-github -Dsonar.login=yyyyproject is built, tests passes and thensonar-maven-plugin:3.0.1:sonarexecutes:[ERROR] Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.0.1:sonar (default-cli) on project xxx: Execution default-cli of goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.0.1:sonar failed: A required class was missing while executing org.sonarsource.scanner.maven:sonar-maven-plugin:3.0.1:sonar: org/sonar/batch/bootstrapper/IssueListenerand at the end of the stacktrace:Caused by: java.lang.ClassNotFoundException: org.sonar.batch.bootstrapper.IssueListenerwhat's missing? how to fix that?mvn wrapper with mvn version: apache-maven-3.5.2java 8ubuntu 14.04
|
sonar cloud plugin fails on missing class
|
This isn't configured insonar-project.propertiesbut through the GUI:Administration > General Settings > SonarJS > File Suffixes
|
In my project there is sonar scanner which is analyzing only *.js files (probably there is such configuration or so on). Also I have istanbul code coverage which generates a perfect lcov file with the results.This lcov file has references to *.ts files which are not analyzed by Sonar. So the question is how to tell Sonar to analyze *.ts files instead of *.js files?Now i'm getting somthing like this -Could not resolve 10 file paths in [coverage.lcov], first unresolved path:
[path]/test.ts .I would really appreciate any help and it will be super if someone can share their working configuration filesonar-project.properties.
|
How to tell Sonar to analyze *.ts files instead of *.js files
|
The tasksonarqubeexposes all of the defined properties:plugins {
id "org.sonarqube" version "2.0.1"
}
sonarqube {
properties {
property "sonar.working.directory", "..."
}
}
task printSonarqubeProperty {
doLast {
println "${project.tasks['sonarqube'].properties['sonar.working.directory']}"
}
}
|
I'm using Gradle 2.14.
I'd like to read the report-task.txt generated by the SonarQube Gradle plugin. For this purpose I need to get the location of this file which is stored insonarqube {
properties {
sonar.working.directory "..."
}
}I want to access this property from outside the sonarqube plugin, i.e. I'm writing a gradle task that runs after the sonar task. This tasks needs to process the report-task.txt located in sonar.working.directory.Is is possible to access the properties of a gradle plugin?
|
Read SonarQube properties of gradle plugin
|
This an issue on JaCoCo side due to the try-with-resource construction :
The bytecode generated have several branches in order to safely close the open resource and JaCoCo instrument bytecode and report some of those branches as uncovered.See this issue :https://github.com/jacoco/jacoco/issues/82and this onehttps://github.com/jacoco/jacoco/issues/15for more detailed explanation.
|
I have the java code liketry (FileInputStream fileInputStream = new FileInputStream(filePath);
PrintWriter out = response.getWriter()) {
while ((i = fileInputStream.read()) != -1) {
out.write(i);
}
} catch (IOException e) {
throw new IOException(e);
}For this I have all the test written and I am using Sonarqube as code coverage tool. But unfortunately conditional coverage result(2 conditions are covered by test) is coming in mycatchstatement. As far my knowledge, conditional coverage is apply only for condition check. Why it is showing incatchstatement. Can someone shed some light here.
|
SonarQube - Why condition Coverage metrics on catch statement
|
I'd like to complete answers from Seb and Jeroen.
Schema is indeed created programmatically by SonarQube during startup. This step can't be executed independently in a script. Just start server. Instead of parsing logs, I suggest to call the web service GET http:///api/system/status (see documentation athttp://nemo.sonarqube.org/api_documentation/api/system/status) to know when database is fully initialized.Database upgrade when installing a new release can also be triggered through the web service POST http:///api/system/migrate_db (seehttp://nemo.sonarqube.org/api_documentation/api/system/migrate_db).
|
I'm trying to automate sonarqube installation.
One (small) issue I'm running into is after installation during first access, as sonarqube is initializing the db schema, we run into timeouts.
I'd like to know if there's a script/command to initialize the db (create tables and all) from the bash?
I've been digging on the internet and couldn't find an answer to that.
Thanks!
|
Command line to initialize SonarQube database?
|
Apologies for answering with such a long delay!I've had a look at this and it seems that the SharePoint msbuild targets are calling the "Build" target twice - once part of the normal build and once part of the packaging process. In order for SonarQube analysis to track all the build artefacts, we've injected some logic that depends on the Build task and now this logic is being called twice and you get the "Duplicate project GUID" problem.Here's a workaround I tried on a simple SharePoint project - keep the actual build and the packaging as separate steps. So your build definition will be:SonarQube BeginMSBuild (without /p:IsPackaging=true)SonarQube EndMSBuild your_SP_project.csproj /t:PackageNote that the second call to msbuild needs to be done on your sharepoint project - calling /t:Package on the solution will not work because the SharePoint targets will have not been imported.Please let me know if this works!
|
I've a Visual Studio Team Services build definition containing a Visual Studio Build task surrounded by the Sonar Begin Analysis and End Analysis task. The Visual Studio Build packages a SharePoint provider hosted add-in using the /p:IsPackaging=True property. If this property is set I get the following error from the Sonar Build Runner:2015-11-27T13:23:05.9534586Z WARNING: Duplicate project GUID: "31ef7995-fdbc-4307-9024-a3d640fdf987".
Check that the project is only being built for a single platform/configuration and that that
the project guid is unique. The project will not be analyzed by SonarQube.Of course I could first build the solution without the /p:IsPackaging=True and running analysis on this and in a second step do the packaging, but this seems like a waste of resources to have to build the solutions twice.Any idea how I can package a SharePoint provider hosted Add-In and use the same task for code analysis with Sonar?Sonar version in use is 5.1.2. And MSBuild.SonarQube.Runner version used by the VSTS task is 1.0.1.
|
Using Sonar MSBuild Runner with /p:IsPackaging=True
|
You have a problem with execution ofCURL(not with SonarQube API).&is a special character in shell. You should use quotes (curl params "url"):curl -X GET -v -u admin:admin "http://localhost.com:9000/api/issues/search?severities=MAJOR,CRITICAL&assignees=nits&pageSize=-1"or escape special characters (\&):curl -X GET -v -u admin:admin http://localhost.com:9000/api/issues/search?severities=MAJOR,CRITICAL\&assignees=nits\&pageSize=-1
|
I am trying to fetch a list of all issues in my name and having severity asMAJOR,CRITICAL.I tried API and it is not accepting two parameters and complain that not supported. Please help how to read list of issues?I am using reference form below sitehttp://docs.sonarqube.org/pages/viewpage.action?pageId=2392181#WebService/api/issues-GetaListofIssuesC:\cURL\bin>curl.exe -X GET -v -u admin:admin http://localhost.com:9000/ap
i/issues/search?severities="MAJOR,CRITICAL"&assignees="nits"&pageSize="-1"SONARQUBE 4.4
|
SonarQube API search issues
|
It depends which version of SonarQube you are running on:prior to SQ 5.1, there's a bug that prevents to have the DEBUG logs of the LDAP plugin. There's a ticket for this and we should provide a fix in the upcoming month:LDAP-2starting with SQ 5.1, you just have to setsonar.log.level=DEBUGin theconf/sonar.propertiesfile and you're done.
|
What is the preferred way to display the debug log level information from the latest SonarQube LDAP 1.4 plugin. I did not find the logging conf file.
Thanks.
|
SonarQube LDAP 1.4 -> debug logging
|
File exclusions is case sensitive, so you should do the following to exclude your file:sonar.exclusions=**/BottomBar.csConcerning your initial problem which is related to SCM information, SonarQube will be less strict about such failures in the upcoming 5.1 version. Please see "SONAR-6172 - Do not fail when a file has no blame information".
|
Is it possible to exclude a file from Sonar's SCM blame data gathering?I have a file at this path:./projects/ichrg/ichrg.Web/bottombar.cssvn blame from a command line works fine on the file, but when I run it with sonar I get the following error:java.lang.IllegalStateException:The svn blame command:svn blame --xml --non-interactive -x -w --username ********
--password ******** --trust-server-cert BottomBar.csfailed:svn: warning: W155010:The node'D:\JenkinsBuilds\svntrunk\projects\ichrg\ichrg.Web\BottomBar.cs'was
not found.svn: E200009:Could not perform blame on all targets because some
targets don't existWhich sounds like it's probably an svn problem.For now, I just want to exclude the file in question from SCM analysis, I added the following pattern to the "Source File Exclusions" property in the web portal, under "File Exclusions":**/bottombar*But it continues to try to get blame data for the file.Is there someway else I can prevent sonar from trying to get blame data for my file?
|
Exclude a file from SonarQube SCM blame?
|
Thedocsshow themetricsparameter with a value ofncloc, notnloc. I think you've just got a typo.
|
I was able to get the list of projects(resources) from sonar REST API using the following java codeSonar sonar = Sonar.create("wwww.example.com/sonar/api/resources?metrics=nloc");
ResourceQuery query = new ResourceQuery();
List resourceList = sonar.findAll(query);
for(Resource resource : resourceList){
System.out.println(resource.getid()+":"+resource.getMetricIntValue("nloc"));
}But this resulted in1001:null
1002:null
1003:null
1004:nullWhy is the lines of code value returning null?
|
how to get all values of a patricular metrics in sonar REST api
|
If you use LDAP users in your Sonar installation, and a non-LDAP user to maven sonar plugin, this may explain the problem:http://sonarqube.15.x6.nabble.com/cannot-login-to-sonar-using-created-user-and-ldap-td5025428.htmlhttp://jira.codehaus.org/browse/SONAR-4543I fixed the problem editing the sonar.properties like this:# LDAP
sonar.security.realm=LDAP
sonar.security.localUsers=admin,jenkinsuser
ldap.url=....
|
When executing the sonar analysis using the Maven Sonar Plugin:Without any other change, except upgrading from SonarQube 3.7 to 4.2We receive the following error:[ERROR] Failed to execute goal org.codehaus.mojo:sonar-maven-plugin:2.2:sonar (default- cli) on project museum-mobile: Can not execute SonarQube analysis: Not authorized. Please check the properties sonar.login and sonar.password. -> [Help 1]Our account is still listed as "sonar-administrator", with full access to all Global Permissions: Administer Quality Profiles, Administer System, Execute Analysis, Execute Preview Analysis, Provision Projects, Share Dashboards And FiltersWhen we run with the default "admin" account we are able to execute the analysis.Environment:Windows 7 64-bitJava JDK 1.6.0_31 and 1.7.0_25Maven 3.0.5sonar-maven-plugin 2.0 and 2.3JIRA opened:MSONAR-66
|
Receiving "Not authorized" error after upgrading to SonarQube 4.2
|
SonarQube can ignore issues on certain components and against certain coding rules. You might want to read theIgnore Issues on Multiple Criteriasection inSonarQube Narrowing the Focus.As mentioned in the documentation:You can ignore issues on certain components and for certain coding rules.Examples:I want to ignore all issues on all files => *;**/*I want to ignore all issues on COBOL program bank/ZTR00021.cbl => *;bank/ZTR00021.cblI want to ignore all issues on classes located directly in the Java package com.foo, but not in its sub-packages =>;com/foo/I want to ignore all issues against coding rule cpp.Union on files in the directory object and its sub-directories => cpp.Union;object/**/*
|
I do not wand violations to be reported for Java test files in SonarQube, but I do want JUnit and Cobertura code coverage to be analyzed and displayed (JUnit and code coverage reports are reused, not executed by SonarQube).How do I exclude test files from violations analysis only? I tried adding to global exclusion these settings, but they are not working:**/test/**
**/Test*.*Thanks
|
Excluding Java test files from SonarQube 4.1.1 analysis
|
Error handling can be tricky in any environment, java included. I haven't used sonar, but I can comment on general good practices for java error handling.e.printStackTrace() is generally discouraged because it just prints out the stack trace to standard error. Because of this you can't really control where this output goes.The better thing to do is to use a logging framework (logback, slf4j, java.util.logging, log4j, etc) because then you can control where the errors are logged to and what the log retention policy is.And generally you'll want to catch the exception and if it's unexpected behavior, log it and either throw a new exception (probably specific to your application) or do whatever you have to do to continue operating gracefully.If you're using java.util.logging, you can do something like the following:class YourClass
{
Logger logger = Logger.getLogger(YourClass.class.getName());
...
public void someMethod() throws YourException
{
try
{
// your code here
} catch (NullPointerException e)
{
String message = "Unexpected NullPointerException in processing!";
logger.log(Level.ERROR, message, e);
throw new YourException(message, e);
}
}
}Hope this helps!
|
i recently started using sonar as code review tool.
When i analysed my code running sonar,
it reflected printing stack trace as violation of java coding standard.
As an alternative to stack trace, I tried:e.getcause()but this did not clear the exception as done by stack trace
|
why it is not recommended to use e.printstacktrace() by sonar?
|
public static int Compare(XXX lhs, XXX rhs);Return value:Less than zerolhsis less thanrhs.Zerolhsequalsrhs.Greater than zerolhsis greater thanrhs.Examples:DateTime.Compare MethodDecimal.Compare MethodUsage:// operator // named alternative
x < y Compare(x, y) < 0
x <= y Compare(x, y) <= 0
x > y Compare(x, y) > 0
x >= y Compare(x, y) >= 0ImplementingIComparable<T>is also a good idea.
|
As the operator overloading (operator> and operator<) violates the ruleOperator overloads have named alternates, the operator > and < require an alternative method Compare, however, since there can only be one Compare method, what should the signature of that method be?for example, I have:public static bool operator >(XXX lhs, XXX rhs)andpublic static bool operator <(XXX lhs, XXX rhs)How to provide a compare method to behave the same as both greater to and less than operators?Edit:Theint Compare()only returns positive (greater than), negative (less than) and 0 (equal), what about in my overloaded operator there is a >= operator, which means my Compare method should handle (greater to or equal to) sinario as wellWhat about there are >, < >= and <= four overloaded operators?
|
How to correct the rule 'Operator overloads have named alternates' in c#
|
You have to be running Sonar somewhere, localhost:9000 is fine. Then you have to do a build of this project using that Sonar. If you are using Maven, right click on the project -> Run As -> Maven build, and put in sonar:sonar as the Goal. This can also be done using Ant instead, but you will need a sonar target in your build.xml. Then when you do the "Associate with Sonar" dialog, if GroupId and ArtifactId are empty, type in the correct values in those columns.
|
Can I use Sonar plugin without others installations of Sonar ? I'm trying to use following the steps ofsonar docbut it don't work. When I try to associate my projects the message "IDgroup empty" appears, and I can't connect when I try 'test connection'. Someone knows some better tutorial , or more specific? Thanks
|
Sonar plugin Eclipse
|
I have an answer that feels more like a work-around, but seems to work. Within SonarQube, I canrename the main branch. This is more than just a cosmetic change. I set the value todevelop, and the next SonarQube analysis withsonar.branch.name=developwas accepted as the main branch. This works – for now – but does not seem to be the documented and preferred way.
|
SonarQube has the concept of amain branchirrespective of its actual name. According to the documentation, the key isnotto pass thesonar.branch.nameproperty to the analysis.So far, so good. However, when my Gradle build in Github does not set the property, then automatic branch detection kicks in and I get:Detected branch/PR in 'GitHub Action'Auto-configuring branch 'develop'Well, that’s unfortunate, because nowsonar.branch.nameis set todevelop, and SonarQube will not accept it as the main branch. Thisdevelopis set as the default branch in Github, but the scanner seems not able to detect this. Automatic detection will not happen when I set the property explicitly, but then of course it is still set to something.The question is now: Can I skip branch detection in the Sonarscanner without settingsonar.branch.name? Can I influence the branch detection so it will correctly detect it is on the default branch?We are using Github actions in a GitHub Enterprise Server 3.5.5, for reference.
|
Override SonarQube automatic branch detection
|
Finally I found the solution. build wrapper doesnot support Mac os Ventura 13.xSonarCommunity, Build wrapper is not working as expected, Objective C, XCodeInitially, I had used this command: xcodebuild clean build -workspace
PagaloTodo.xcworkspace -Scheme PagaloTodo and the build is successful.I had tried passing others configuration options as arch, sdk,
BUILD_LIBRARIES_FOR_DISTRIBUTION where also the build is successful
but the build wrapper generated file is uncomplete.There is a jira ticket created for same.
|
I'm running the build-wrapper like so:build-wrapper-macosx-x86 --out-dir build_wrapper_output xcodebuild -project MyProject.xcodeproj -scheme All -configuration Release clean buildHowever, when I look at the result output the json file is empty:# (C) SonarSource SA, 2014-2022,[email protected]# All SONARSOURCE programs and content are copyright protected.
# SONARSOURCE and SONARQUBE are trademarks of SonarSource SA. All rights are expressly reserved.
#
# This file is designed exclusively for use with the SONARSOURCE C / C++ / Objective-C Plugin.
# It may not be used in connection with any other software.
# Any other use is prohibited by law and may be grounds for immediate termination of your License.
{
"version":"6.35",
"captures":[
]}When I runxcodebuildnormally the build works. Is there something I'm missing here? I tried reading the following and followed the instructions:https://docs.sonarqube.org/latest/analysis/languages/cfamily/
|
SonarQube build-wrapper silently fails
|
Yes.Optional chaining returnsundefinedin case of an invalid reference. MDN docs state:The ?. operator is like the . chaining operator, except that instead
of causing an error if a reference is nullish (null or undefined), the
expression short-circuits with a return value of undefined. When used
with function calls, it returns undefined if the given function does
not exist.However, keep this in mind:Optional chaining cannot be used on a non-declared root object, but can be used with an undefined root object.Exampleconst dog = {'foo': 0};
console.log(dog?.foo === 0);
console.log(dog?.bar === 0);
|
I am trying to reduce the function cognitive complexity required by SonarQube, I am wondering, are these two if statements equivalent?The first statement:if (
currentRef &&
currentRef.current &&
currentRef.current.value.length === 0
)I want to replace it by :if (
currentRef?.current?.value.length === 0
)
|
Are these two if statements equivalent?
|
I'm going to guess that what you're really asking is how you can configure a SonarQube project so that it REQUIRES 80% code coverage to be determined as successful. This is determined by the "Quality Gate". If you edit the quality gate, or create a new one, you will see that you can set the various properties that are measured, and the numbers that have to be hit. The "code coverage" metric is just one of the several metrics it can measure and examine.
|
In SonarQube, by default, code coverage is set to 80%. How can I set it to some other value?
|
How do I set a code coverage value in SonarQube?
|
Sonar does not know that the two consecutive calls togetBody()will return the same value.So, it is really possible, from the point of view of a static analyzer, that the second call returnsnull.I'd recommend assigning the body to a local variable, and calling the getter only once.Hereis a reference from Sonar community, where someone reported this behavior as bug and received a similar response.A static analyzer actuallycannotprove that the two calls will return the same value, unlessresponseis of a final and immutable type. And no static analyzer I've tried yet goes to the length of trying to prove that.
|
if (response != null && response.getBody() != null && response.getStatusCode() == HttpStatus.OK) {
return new BigDecimal(response.getBody());
}I am getting possible null pointer dereference due to return value of called method on above code.Can someone please let me know the exact issue and why it's an issue?response.getBody() // returns a string valueThanks in advance! Please let me know if any other details are needed.
|
Sonar : Possible null pointer dereference due to return value of called method
|
The issue is found by theRSPEC-1213 The members of an interface or class declaration should appear in a pre-defined orderrule. The description says:According to the Java Code Conventions as defined by Oracle, the members of a class or interface declaration should appear in the following order in the source files:Class and instance variablesConstructorsMethodsYour code contains a constructor before the variables. Valid code:public final class AppConst {
public static final String READ_ERROR = "READ";
public static final String PROCESS_ERROR = "PROCESS";
public static final String WRITE_ERROR = "WRITE";
private AppConst() {}
}
|
I have the following class:public final class AppConst {
private AppConst() {}
public static final String READ_ERROR = "READ";
public static final String PROCESS_ERROR = "PROCESS";
public static final String WRITE_ERROR = "WRITE";
}SonarQube marks errors on all three lines with the variables:Move this variable to comply with Java Code Conventions.How to make the code compliant with SonarQube?I'm using SonarLint for Eclipse v2.6.0.
|
How to make the code compliant with: Move this variable to comply with Java Code Conventions
|
I solved this using jest-sonar npm package.
|
How to use jest-sonar-reporter? Inconfig.jsonwe were using"testResultsProcessor": "/config/jest/resultsProcessor":resultsProcessor.jsmodule.exports = (results) => {
process.env.TEST_REPORT_PATH = root('reports/unit')
process.env.JEST_SUITE_NAME = 'React Unit Tests'
process.env.JEST_JUNIT_OUTPUT = root('reports/unit/junit.xml')
require(root('node_modules/jest-sonar-reporter/index')).apply(this, [results])
require(root('node_modules/jest-junit/index')).apply(this, [results])
// add any other processor you need
return results
}this was working fine when we were using"jest": "^21.2.1",
but after updating Jest to"jest": "^26.1.0",as per documentation..."reporters": [ "default",[
"jest-junit", {
"outputDirectory":"reports/unit",
"suiteName": "ANZ-React-BoilerPlate Unit Tests",
"outputName": "junit.xml"
}]],jest-junitis working fine but how to supportjest-sonar-reporter?
|
How to use jest-sonar-reporter?
|
i know this is maybe late to answer, but i went through the same problem, and i could solve it this way, hope it can help someone.What helped me solve this, was adding the following properties to thesonar-project.propertiesfile:sonar.tests ={{project folder}}/__tests__
sonar.test.inclusions={{project folder}}/__tests__/*.test.tsHere you should replace those values with the name of the folder your project is in. Take into account, if your directory is already pointing to inside of your project folder. avoid those values. The key here is to include this properties pointing to the right path.Note that my tests are in thetestfolder. point the sonar.tests property to the folder where your tests are, and the sonar.test.inclusions to inside of it.
|
I was using the -D option since I don't have access to the sonar properties file itself./home/....../src/ contains both sum.js and sum.test.js files./home/.../reports/test-reporter.xml`<?xml version="1.0" encoding="UTF-8"?><testExecutions version="1"><file path="/home/....../src/sum.test.js"><testCase name="sum" duration="4"/></file></testExecutions>`
mvn sonar:sonar
-Dsonar.testExecutionReportPaths=/home/.../reports/test-reporter.xml
-Dsonar.host.url=https://xxx
-Dsonar.login=xxx
mvn sonar:sonar
-Dsonar.testExecutionReportPaths=/home/.../reports/test-reporter.xml
-Dsonar.host.url=https://xxx
-Dsonar.login=xxx
-Dsonar.tests=src
-Dsonar.test.inclusions=src/**/*.test.jsBoth of the above commands fails with same error
Error: Line 3 of report refers to a file which is not configured as a test file:
|
Sonar Report error: Report refers to a file which is not configured as a test file
|
+25The methodsetHttpOnlyof thejavax.servlet.http.Cookieclass was added in Servlet 3.0 specification.Tomcat 7 implements Servlet 3.0 spec but in order to compile your code, you need to add appropriate Maven dependencies.Make sure you have a dependency on Servlet 3.0 API with scopeprovided:<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>With this dependency codecookie.setHttpOnly(true);will compile.AppendingHttpOnlyflag to a cookie value manuallyresponse.addHeader("Set-Cookie","name=value; HttpOnly");most likely would not pass SonarQube check.The rulehttps://rules.sonarsource.com/java/RSPEC-3330checks the presence of thesetHttpOnly(true)method call.But this SonarQube check can be suppressed by adding//NOSONARcomment to the end of line causing the warning:Cookie c = new Cookie("code", code.trim()); //NOSONAR
|
Below is my Java code for creatingjavax.servlet.http.Cookiefrom Tomcat 7 APICookie c = new Cookie("code", code.trim());
c.setPath("/public");
response.addCookie(c);
response.setStatus(200);Am trying to addc.setHttpOnly(true);to make the above code sonar compliant but Eclipse is throwing a compiler error sayinghe method setHttpOnly(boolean) is undefined for the type Cookie, but from the Javadoc of Tomcat 7 APIhttps://tomcat.apache.org/tomcat-7.0-doc/servletapi/index.htmlI do see thatsetHttpOnly()exists inCookieclass, can someone please help me Understand why am I getting the compiler error for addingc.setHttpOnly(true);?
|
Tomcat 7: Sonar compliant setHttpOnly(true) for Cookie
|
Sonar isn't that smart. It sees quantified groups that include quantified patterns. Although it's the main reason for a ReDoS attack to take place, that's not enough.The suspicious regular expression in question has a boundary:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*
^That boundary makes a failure to happen earlier (see whathappens without it). If it wasn't there then we could say Sonar is a hundred percent right. Your reasoning is correct.
|
This is the regex pattern suggested for email validation by theW3C HTML spec:^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$SonarQube flags it as "vulnerable to a denial of service attack (ReDOS)".
I think it's a false positive, but I'm no expert on this field and I might be missing something.I believe Sonar thinks it might be susceptible to ReDoS attacks due to nesting repetitions -[a-zA-Z0-9-]{0,61}contained in the group followed by the asterisk. But still, I think that when regex engine backtracks this expression it can resolve it quickly as either dot or end of the line is expected afterward. Is my reasoning correct?
|
Is email regex pattern suggested by W3C spec prone to ReDoS attacks?
|
The language is determined by file extension. You don't need to set the language explicitly for the analysis
|
According to thedocumentationof SonarQube, thesonar.languageparameter that used to set the language on which to perform the analysis is now deprecated;Is there an alternative for this?
How SonarQube scanning process now sets the default language?
|
SonarQube: replacement for deprecated language analysis parameter
|
I think you can directly pass the SonarQube parameter on the command line:stage('Sonarscan') {
withSonarQubeEnv('SONAR') {
bat "gradlew sonarqube -Dsonar.branch.name=${BRANCH_NAME} --info"
}
}
|
A multibranch jenkins pipeline calls a gradle build.Need to pass theBRANCH_NAMEto the sonarqube task in build.gradle:sonarqube {
properties {
property "sonar.host.url", "https://sonar"
property "sonar.projectKey", "com.foo.bar:Foobar"
property "sonar.projectName", "com.foo.bar-Foobar"
property "sonar.binaries", "build"
property "sonar.branch.name", "${branchname}" <---------------
property "sonar.branch.target", "master"
}
}I tried:stage('Sonarscan') {
withSonarQubeEnv('SONAR') {
bat "gradlew -Pbranchname=${BRANCH_NAME} sonarqube --info"
}
}output:* What went wrong:
A problem occurred evaluating root project 'fooBar'.
> Cannot get property 'branchname' on extra properties extension as it does not existandstage('Sonarscan') {
withSonarQubeEnv('SONAR') {
bat "gradlew -Dbranchname=${BRANCH_NAME} sonarqube --info"
}
}output:* What went wrong:
A problem occurred evaluating root project 'fooBar'.
> Could not get unknown property 'branchname' for root project 'sfrToolbarContract' of type org.gradle.api.Project.and also:stage('Sonarscan') {
withSonarQubeEnv('SONAR') {
def branchname = "${BRANCH_NAME}"
bat "gradlew sonarqube --info"
}
}but the pipeline jobs just hangs.How to pass a property from Jenkinsfile to gradle build ?
|
Jenkins pipeline, pass branchname to gradle build
|
I tested the following solutions on SonarQube 7.1.project_analyses/searchYou have to add thebranchparameter. Example:https://website.com/sonar/api/project_analyses/search?project=PC_civil-affairs&branch=xyzsettings/valuesSettings are the same for all branches, so your URL is correct:https://website.com/sonar/api/settings/values?component=PC_civil-affairs&keys=sonar.leak.periodqualitygates/project_statusUnfortunately, I didn't find any way to get quality gate status.
|
I'm using SonarQube branch plugin (1.0 (build 507)) and want to retrieve information from branches. My SonarQube version is 6.7.The SonarQube project (PC_civil-affairs) has three branches, master (main), develop, feature_branch. These are all long-lived branches.The next calls retrieve information from the master branchhttps://website.com/sonar/api/project_analyses/search?project=PC_civil-affairshttps://website.com/sonar/api/settings/values?component=PC_civil-affairs&keys=sonar.leak.periodhttps://website.com/sonar/api/qualitygates/project_status?projectKey=PC_civil-affairsHow should I adjust the above calls to retrieve the same information from the develop and feature_branch?
|
How to retrieve branch information by the API from a SonarQube project?
|
At the time of writing, the behavior you are seeing is "by design", even though it is not very intuitive. In other words, you cannot chain Scanner for MSBuild and Scanner CLI.Scanner for MSBuild is able to scan JavaScript code (and all other languages too) only if it is referenced from a project in the currently analyzed solution. For example, if your WebApplication project contains JS (or TS, Java, COBOL, etc.) files they will be analyzed.When the non-.NET language files are not referenced in the currently analyzed solution, it is better to create a separate SonarQube project to store the analysis results from Scanner CLI.We are aware of this limitation and we are planning to fix it in the near future, but right now I cannot commit to a specific date.
|
I'm trying to implement SonarQube (SonarCloud) to our development pipeline. We are using TFS (on-premise) and our project has just one repository. In this repository, we have two different applications, one .NET application, and one javascript application.The folder structure is like this:|
|- NetProjectFolder
|- JSProjectFolderAnd our build definition (which is working with Pull Requests) steps are like this:SonarQube Scanner for MSBuild - Begin Analysis (for .NET project)Visual Studio Build (build .NET project solution)Visual Studio Test (tests of the .NET solution)SonarQube Scanner CLI (To scan JS project)SonarQuber Scanner for MSBuild - End AnalysisI was thinking that step 4 and step 5 will analyze our .NET and JS projects and at the end, I will see a full report of our all projects. But, when step 4 completed it's automatically uploading the report of JS project and when step 5 completed it's overwriting JS report, uploading the report of .NET project.In the end, there are only .NET project's report/warning / technical debt etc. Because step 5 overwriting step 4's result.How can I configure these steps so SOnarQube can analyze both our JS and .NET projects properly?
|
Scanning multi-language projects with SonarQube
|
Analysis will notexecuteyour tests. It will only readsomereports of your test execution. You must execute your tests independently and then convert the results into theGeneric Test Data formatfor inclusion in your analysis.
|
I'm working withSonarquberecently & we had a requirement to scanPL/SQLprojects, which we are able to do usingSonarPLSQL plugin.But there are some test cases written inProcedures(inside a PL/SQL package), which perform testing over the the source code (present in a different Pl/SQL package).I've a requirment in which I want sonar to perform code-coverage anaylsis.Is there any sonar plugin avaliable that can execute these test cases and provide me the code-coverage metrics?Also, if there is an alternate approach for my problem, please suggest.
|
Sonarqube plugin to execute PL/SQL test procedures
|
Return a copy of the array, so any changes made to it aren't reflected in the original array. This does incur a performance and memory penalty of course, so for large arrays this can be something you need to think about.return Arrays.copyOf(dataBytes, dataBytes.length);
|
This question already has answers here:Returning 'data' may exposed internal array?(2 answers)Closed5 years ago.I have a getter method in one of the class:public byte[] getBytes() {
return dataBytes;
}Sonar is giving me exception as. Ho do I fix this?Returning 'dataBytes' may expose an internal array
|
Returning 'dataBytes' may expose an internal array [duplicate]
|
You're likely impacted by the following issue:SONAR-10451-Incorrect filtering on "Leak Period" issues in the Issues pageNote that the filtering onLeak Perioddefinitely is toggled (left facet), however the above known issue impacts the output of that filtering.
|
I migrated my SonarQube from 5.6.6 (LTS) to 6.7.1 (LTS).In previous version I was able to list only the new issues created between the 2 last analysis from the Home of the project. In the leak period when I clicked on New code smells, the issues list displayed only these 2 issues.In new version, on overview page of the project we can still see the number of new issues created (in the leak period) but when I click on the number of new issues (i.e. 2 new code smell) the list of issues is not filtered on new ones and all issues are displayed. (i.e. Impossible to limit the list to the 2 new code smell issue).Did I do something wrong ?See below screenshot of a project with my SonarQube 5.6.6 env.url of link :http://sonar:9000/component_issues?id=my_project#resolved=false|types=CODE_SMELL|sinceLeakPeriod=trueSee below screenshot with SonarQube 6.7.1 env. of the same projecturl of link :http://sonardev:9000/project/issues?facetMode=effort&id=my_project&resolved=false&sinceLeakPeriod=true&types=CODE_SMELL
|
SonarQube 6.7 - New issue identification
|
If your class has a non-staticrunImport()method,
then you can write like this:Runnable task = this::runImport;If therunImport()method is static, then instead ofthis, write the name of the class, for example if the name of the class isMyClass, then:Runnable task = MyClass::runImport;
|
private void runAsyncImport() {
Runnable task = () -> runImport();
new Thread(task).start();
}I am getting sonar issue for the above code, Replace this lambda with a method reference. (sonar.java.source not set. Assuming 8 or greater.)How to fix it
|
Runnable Interface : Replace this lambda with a method reference. (sonar.java.source not set. Assuming 8 or greater.)
|
We changed the way we validate project layout, and it leads to this error. Aticket was createdto track this change, and we are currently discussing options (like updating the SonarQube Scanner for Maven). Feel free to follow it for updates, and sorry for the inconvenience.For your specific case, one workaround is to create a build profile, and exclude module../org.eclipse.dawnsciwhen running the SonarCloud analysis. Or move the module to be under the project basedir (and avoid using..in module location).As a side note, there is no point maintaining the filesonar-project.propertiesif you are using the Scanner for Maven (mvn sonar:sonar) since the Scanner for Maven will only read configuration from pom.xml.
|
Some time between the11th Septemberand the14th September, running sonar through our travis build started failing with anorg.eclipse.dawnsci.targetplatform should be relative to project baseDirerror:[ERROR] Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.3.0.603:sonar (default-cli) on project org.eclipse.scanning: Dir /home/travis/build/eclipse/org.eclipse.dawnsci/org.eclipse.dawnsci.targetplatform should be relative to project baseDir -> [Help 1]Looking through thepom.xmltheorg.eclipse.dawnscimodule does stand out as being different to all of the others:<modules>
<module>org.eclipse.scanning.target.platform</module>
<module>../org.eclipse.dawnsci</module>
<module>org.eclipse.scanning.api</module>
...
</modules>I have tried updatingsonar-project.propertiesfromsonar.exclusions=**/*.xml,**/*.classto each of the following:sonar.exclusions=**/*.xml,**/*.class,../org.eclipse.dawnsci
sonar.exclusions=**/*.xml,**/*.class,org.eclipse.dawnsci*
sonar.exclusions=**/*.xml,**/*.class,org.eclipse.dawnsci**but none of these changes helped.Afterprevious problemsI have added--fail-neverto themvn -q sonar:sonarcommand in.travis.ymlso this problem won't prevent pull requests being merged, but it would be nice to have sonar reports on our repo again.Any suggestions about how I can fix our travis build would be appreciated?
|
Sonar `should be relative to project baseDir` error in travis
|
There is no manual override for the Quality Gate. You'll have to either change the quality gate conditions (or temporarily? apply a less strict QG to the project) or fix the problem.
|
I'm using SQ 6.2 with quality profile "Sonar Way" and quality gate also "SonarWay".After some refactorings the QG fails with new issues and coverage on new code (which is not really new). I'd like the project to pass the QG (because no new code was added), so I marked the new issues as "Won't fix", but I found no way to accept the coverage failure.Is there a way to manually mark the QG green or set the leak period?
|
Make quality gate pass manually
|
SonarQube expects you to analyse all files every time. Depending on the analysed languages this is especially important for the "cross file analysis" (issues raised on one file, because of the changes in another file).Depending on your language and build environment, you could however consider to split your project into smaller independent projects. If you for example split one big java/maven project into smaller ones and let SonarQube have access to all those dependencies, you will have faster build and analysis times.
|
Issues for the entire project is reported whenever I run analysis for the entire project. But when I run analysis for only the changed files next day the issues of other files are getting deleted.Is there any way to preserve the issues of other files when I run with-Dsonar.inclusions?
|
Sonarqube run analysis without removing existing issues
|
The issue is raised because you're passing a concatenated string to your formatter. If you're going to use string formatting, thenusestring formatting:int paddingLength = seqLength - seqNoLength;
String fmt = String.format("%%0%dd", paddingLength);
String.format(fmt, seqNo);Or evenint paddingLength = seqLength - seqNoLength;
String.format(String.format("%%0%dd", paddingLength), seqNo);Although the first version is far more readable.
|
SonarQube is raising an issue on my string formatter use:Format specifiers should be used instead of string concatenation.I have used below java code to add padding 0 in the number.int paddingLength = seqLength - seqNoLength;
String.format("%0" + paddingLength + "d", seqNo);
|
SonarQube issue raised on use of string formatter
|
Unfortunately we do not support custom dictionaries yet. We did not have a ticket for that, so I created one:Custom Dictionaries for S100. It is not easy to implement, but I hope that we could squeeze it in our plans for the upcoming months.
|
As you know, the FxCop tool allows us to input custom dictionary in the .xml file for ignoring the casing exception. Does SonarLint also support us to do the same?Example: We have the names as below:SPVerionSPVersionTypeSPNameChangedSP...These names contain the string "SP" and violate the S100 rule of SonarLint. Can we input a custom dictionary "SP" so that SonarLint will ignore checking for these names?
|
Does SonarLint have the custom dictionary feature like the FxCop?
|
According to the error message ("Unsupported major.minor version 52.0"), you are using an old JDK. To fix this, you have to install the JDK 8 and configure wrapper.java.command to point to the installation of this JDK 8.
|
I am facing the following issue while running startSonar.bat:--> Wrapper Started as Console
Launching a JVM...
Wrapper (Version 3.2.3)http://wrapper.tanukisoftware.orgCopyright 1999-2006 Tanuki Software, Inc. All Rights Reserved.WrapperSimpleApp: Unable to locate the class org.sonar.application.App: java.lang.UnsupportedClassVersionError: org/sonar/application/App : Unsupported major.minor version 52.0WrapperSimpleApp Usage:
java org.tanukisoftware.wrapper.WrapperSimpleApp {app_class} [app_arguments]Where:
app_class: The fully qualified class name of the application to run.
app_arguments: The arguments that would normally be passed to the
application.
<-- Wrapper StoppedI am trying to run SonarQube on 64 bit Windows Server R2. It is an old server from 2009.I tried few things like appending the Java and SonarQube paths in PATH environment variable. Besides this I tried to provide an absolute path forwrapper.java.commandin wrapper.conf.
|
SonarQube 6.2 installation issue
|
Thank you for reporting these issues. We haven't tested Unity projects with SonarQube, but it's on our radar as the community and the Unity based code base is huge.At this point I can't suggest any other workaround for your first problem (convention based reflection) but to disable that rule. I created a JIRA ticket to investigate the options:https://jira.sonarsource.com/browse/SLVS-1104And here is the ticket for the readonly field problem. That's definitely something that can be easily fixed. It will be part of the next release:https://jira.sonarsource.com/browse/SLVS-1105
|
I'm trying to setup Sonar on our organization that we mostly make Unity projects.Our problem is that the rules provided to C# language are not always the same in Unity context.In Unity there is a MonoBehaviour class that if you declare some methods (Awake, Start) they are being called by reflection:https://docs.unity3d.com/ScriptReference/MonoBehaviour.htmlSo in this case I have tons of "Remove this unused private member".Is there a way to tell, don't apply that rule if my class derives from MonoBehaviour (or AssetPostprocessor, etc...) and my method name is for example "Awake"? I mean, is there a way to set a custom rule and invalidate other one?The same applies to Unity serialization system. You can have a private field with [SerializeField] attribute and it gets automatically initialized by Unity:https://docs.unity3d.com/ScriptReference/SerializeField.htmlIn this case I get tons of "Make "{FIELD}" "readonly"" if my field has a default value because it's Unity then who "fills" that value updated/changed from inspector but if I make it readonly it won't work in Unity's serialization system.Thanks.
|
SonarQube using it with Unity 3D tons of problems
|
For the record, SonarQube 6.0 doesn't have a SQALE rating, but a Maintainability RatingWhile you can't set a Quality Gate condition directly on the Maintainability rating, you can set a condition on the technical debt ratio (the Maintainability Rating is based directly on the tech. debt ratio).For the Security and Reliability ratings... "bug" is such an ugly word. Let's just say there's a lot to do. :-)
|
Reliability Rating, Security Rating and SQUALE Rating doesn't appear in quality gate definition form. Is this a bug or there's some hidden reason for this?
|
why sonarqube 6.0 doesn't allow to select metrics of type "Rating" in quality gate definitions?
|
The following should do the trick:When looking at the argument of the method invocation, check if its kind is aSTRING_LITERAL, then cast the argument into aLiteralTree. From there, you will be able to access its value, as aString(Note that it will contain the double quotation marks).To check if the invocation was done on a variable, get themethodSelect()expression tree from the method invocation. If its kind is aMEMBER_SELECT, cast it toMemberSelectExpressionTree. From there, check if the kind of theexpression()is anIDENTIFIER. If it's the case, then you will be able to get theIdentifierTreeand its associated symbol. You will then be able to say if the symbol calling the method is a variable or not, check its type, etc.
|
I'm writing a custom rule for SonarQube for java, I want to check if the value of an argument is qualified. For example, I want to know if the String fit the specific pattern. I can only test if the argument is a String, but I can not get the exact value. Does the API allows me to do so?For example, for the code belowlog.error("errorID:210134 It's an error");Can I get the argument and test if the string contains errorID?Besides, can I get what variable did the method invocation?For example, for the code belowlog.error("errorID:210134 It's an error");How can I know that log is an Object of the class Logger?
|
How to get the value of the arguments of the sonar tree
|
I just found the answer. Sadly the package design widget is not available anymore.Since sonarqube 5.2...All design-related features were droppedSeehttp://www.sonarqube.org/sonarqube-5-2-in-screenshots/sectionAlso worth notingAll design-related features were dropped in this version (seeSONAR-6553for details), including Package Tangle Index and related metrics.
|
After a while I installed sonarqube 5.6 today and wondered where the dependency matrix feature is.I foundthis SO question, but it is about sonarqube 4.5.I also searched the update center to see if I must install a additional plugin now, but I had no success.Does anyone know how to get the package design widget back?
|
Is the dependency matrix (package design widget) removed from sonarqube?
|
The subprojects do not have an own sonar runner task. Make the root projects sonar runner task depend on the subprojects jacocoTestReport tasks.In mybuild.gradlethis looks likeif (hasProperty('sonarAnalyseOnly') && sonarAnalyseOnly.toBoolean()) {
tasks.sonarRunner.dependsOn = []
} else {
tasks.sonarRunner.dependsOn {
project.subprojects.findAll { !it.sonarRunner.skipProject }.collect {
[
it.tasks.compileSharedJava,
it.tasks.compileServerJava,
it.tasks.compileGuiJava,
it.tasks.integTest,
it.tasks.jacocoMerge
]
}.flatten()
}
}
|
Why doesn't this work and how can I get the result I'm looking for? Specifically, I want jacoco to run before sonarqube.subprojects {
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'eclipse'
apply plugin: 'jacoco'
test {
jacoco {
excludes = [...,
"javolution.*"]
}
}
jacocoTestReport {
dependsOn tasks.withType(Test)//This makes integrationTests go.
}
//This is the part that I can't get to work:
project.tasks["sonarqube"].dependsOn jacocoTestReport
}Error is:* Where:
Build file '/dev/abc/build.gradle' line: 92
* What went wrong:
A problem occurred evaluating root project 'abc'.
> Task with name 'sonarqube' not found in project ':thingamajig'.Of coursethingamajigis an empty parent directory. Nobuild.gradlethere but it has many sub-directories that do have abuild.gradle. I've tried a number of things like checking the task graph and catching an swallowing the Exception when callingproject.tasks.getByName()Time to punt, I guess.
|
How do I get sonarqube to depend on jacocoTestReport?
|
In my case, the solution was to addsonar.tests=test/specto my sonar.properties. Now it is working like a charm@ElenaVilchik: many thx for your direction, helped a lot
|
I searched a lot for this specific error, but I had no chance in finding a suitable answer.I have SonarQube 5.4 and using newest Karma-version.Following error occurs when running sonar-runner:INFO: Analysing /Users/foo/repository/BarJS/test/reports/coverage/lcov.info
INFO: Could not resolve 6 file paths in lcov.info, first unresolved path: /Users/foo/repository/BarJS/test/spec/Classname.test.jsWhile foo is my username and BarJS is the name of the project.Other people getting those errors having mispelled or case-specific or relative paths. I checked half a dozen times.My paths are correct.I have absolute paths in my Karma lcov.info-file. All camelcase letters are equal to their path in Finder.Content of Karmas lcov.infoSF:/Users/foo/repository/BarJS/test/spec/Classname.test.jsAnybody out there having same issue? It is really annoying
|
SonarQube and Karma code coverage - unresolved file paths
|
SonarLint for Eclipse currently only supports Java, JavaScript and PHP. Support for other languages - including those backed by commercial plugins like C/C++, is in our backlog but I can't give an ETA for this yet.
|
With version 2.0 of theSonarLint plugin for Eclipseit's now possible to sync rules from a SonarQube 5.2+ server instance.By default there is no C language support in SonarLint but if the server instance has installed theC plugin,does this mean that SonarLint can analyze C projects?With version 2.0 you can now establish a connection to a SonarQube server (5.2+) and bind your Eclipse project to a SonarQube project....SonarLint is an Eclipse plugin that provides on-the-fly feedback to
developers on new bugs and quality issues injected into Java,
JavaScript and PHP code.Source:http://www.sonarlint.org/eclipse/(2016-04-19)
|
SonarLint for Eclipse supports the C/C++ plugin?
|
So it turned out my problem was that the JVM wasn't using the proxy settings of my machine, I had to add the following to the Sonar runner script.SONAR_RUNNER_OPTS="-Dhttp.proxyHost=myproxy -Dhttp.proxyPort=80 -Dhttp.nonProxyHosts=my.local.host"
|
I'm trying to use Sonar Runner but keep getting a socket timeout exception. The machine I'm running it on is behind a proxy so I think maybe that is the problem.I still get the problem when the Sonar Server and the Runner are on the same box so I also don't know if this is a problem with Java not properly picking up the proxy settings from the machine (which is OS X), in particular the address where the proxy should be bypassed.No matter what my configuration the browser andcurlcan get to the Sonar Server, its only the Sonar Runner Jar that has a problem.Can anyone offer any advice about getting Sonar Runner to work behind a proxy?UPDATEThis does seem to be OS X related as using a Windows VM to get to the same Sonar Server works, since this is Java I'm assuming this is some issue with my Java set-up or my OS X networking set-up?
|
Sonar Runner Behind a Proxy
|
That property has been removed.Tryconfiguring the project's visibility. The relevant permissions are:Browse- see 1) that the project exists, and 2) what its measures areSee Source Code- see the project's uploaded source code.This is stated explicitly in the docs, but bears repeating:Note that permissions are not cumulative. For instance, if you want to be able to administer the project, you also have to be granted theBrowsepermission to be able to access the project.The same holds true forSee Source Code. You'll first needBrowseon the project beforeSee Source Codedoes you any good.
|
We have some sensitive code that we don't want stored in Sonar's database. We do however want to record quality statistics for the code base and are happy for the file structure to be shown.I have seen some mentions of an 'importSources' configuration parameter in old forum posts but can't find this in either the documention or the source in GitHub. I've tried addingsonar.importSources=falseto a project properties file and it doesn't appear to have any effect.
|
Is it possible to stop SonarQube from saving source code
|
If I understand correctly you want to import the result of a tool in SonarQube to track certain metrics over time.The best course of action in my opinion would be to write a plugin not to compute the metrics but to import the report generated by your tool. That is probably the best reusable option and you don't have to reinvent the wheel and benefit from SonarQube features.
This is how the coverage plugins are usually written (for java). You can have a look at Cobertura or Clover plugin or even Generic Coverage plugin to see how at SonarSource we write those kind of plugins.
|
I want to start tracking code metrics over time in my team's codebase. We decided that the five metrics we were primarily going to be concerned with is Coupling Between Object, Halstead Effort, Lack of Cohesion of Methods, Weighted Method Complexity, and Response for Class. There are plenty of tools for just one time measuring these metrics over our code, but I want to track it. A coworker mentioned Sonar (now apparently called SonarQube).I got an instance set up and it looks like it has the timeline support I need, but it lacks any good code metrics beyond code complexity and code coverage. Plenty of search results tell me things like how Lack of Cohesion of Methods actually used to be in it but were deprecated and removed. I need these metrics, regardless of if they are officially supported or through a community plugin, but I haven't found a non-deprecated one that adds them.Manual metrics exist, but we have hundreds of classes and I don't want to have to make a manual measurement for each class every week. It would become a full time job. I'd rather avoid having to write my own plugin. If I went that route, I might as well just write a cron job that runs once a week to pull the latest, get the analysis I need with a local tool (currently using MetricsReloaded), and dump the local analysis into a local database where I can do whatever with it later. These approaches seem poor and a better one has to exist, right?How can I get these metrics to be tracked by SonarQube?
|
Is there a way to add additional code metrics in SonarQube without having to write my own plugin?
|
This is planned to be fixed in version 5.3 :https://jira.sonarsource.com/browse/SONAR-7036
|
I have a number of technical users on this system which was recently upgraded to SQ 5.2. The system uses LDAP authentication for normal users. When I try to change the password for a technical user, I get this:Password cannot be changed when external authentication is usedI've also tried deleting the user, then re-creating it with the new password. That attempt gives the same error message.I've made sure that the affected users are listed in sonar.properties, for sonar.security.localUsers.
|
Can't change passwords for technical users
|
I was able to solve these problems by adding<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<scope>provided</scope>
</dependency>
|
I've got following errors when running SonarQube 5.1.2 with nightly build job[ERROR] [01:39:46.669] Class not found: javax.el.ELContext
[ERROR] [01:39:46.672] Class not found: javax.el.ELResolver
[ERROR] [01:39:46.673] Class not found: javax.el.ValueExpression
[ERROR] [01:39:46.674] Class not found: javax.el.ExpressionFactory
[ERROR] [01:39:46.674] Class not found: javax.el.ELException
[ERROR] [01:39:46.674] Class not found: javax.el.ELContextListener
[ERROR] [01:40:23.297] Class not found: javax.servlet.ServletOutputStream
[ERROR] [01:40:23.778] Class not found: javax.json.JsonObjectCan you please advise what is the best way to handle such an errors?
|
SonarQube ClassNotFound
|
Because either way, if you end up incatch,connectionwill always be null. There are several places where you can have an exception, but all they are before you assignmentconnection = dbRriver.connect(PropertyLoader.get("URL"), props);So it will always be null incatch.
Yes, you need to put this code infinallyas @Stultuske suggests
|
Below is the code where i am getting the Sonar violationpublic static Connection getConnection(
String db)
throws SQLException {
Connection connection = null;
try {
Driver dbRriver = (Driver) Class.forName(driver).newInstance();
Properties props = new Properties();
props.put("user", PropertyLoader.get("user123"));
props.put("password", PropertyLoader.get("pass"));
connection = dbRriver
.connect(PropertyLoader.get("URL"), props);
} catch (Exception e) {
**if(connection!= null){
connection.close();**
}
LOGGER.error(IN_EXCEPTION, e);
}
return connection;
}the connection needs to be checked for null condition before closing it,but the sonar is giving the violation as "Dodgy - Redundant nullcheck of value known to be null". Please suggest me as how i can avoid this violation without removing the null check.
|
Dodgy - Redundant nullcheck of value known to be null
|
You need SonarQube installed and running on same/different machine.
also you require SonarQube plugin in Jenkins which will connect SonarQube for Storing results.Sonar-runner will be analyzer which will run analysis on your codebase.
You need to install sonar-runner on your local machine and have to specify its path in Jenkins system configuration.Please find below the screenshots for detail purpose.
|
I have installed SonarQube-4.3 and Jenkins in my machine. To integrate Sonar with Jenkins installed the SonarQube plugin.Do I need to install Sonar-runner in my machine in order to trigger a analysis through Jenkins?
|
SonarQube and Sonar runner installation in Jenkins
|
I would start with making sure you're naming the new file with the extension *.coveragexmlCodeCoverage.exe analyze /output:[name of xml file to be generated].coveragexml [name of the coverage binary file].coverage
|
In order to import a coverage file to SonarQube, I'm executing CodeCoverage.exe to convert a ".coverage" file to xml.
I execute a cmd line like:CodeCoverage.exe analyze /output:[name of xml file to be generated] [name of the coverage binary file].coveragebut I do not get any output xml and no errors.
I must say that I was able to generate such xml for tests of other solution files.
What can be the problem? How can I troubleshoot it?Thanks!
|
Codecoverage.exe does not generate output xml
|
You are doingfoo.getKey(). Iffoois null that will throw a NullPointerException but you aren't declaring thatfoomust not be null.Null checkfoobefore you use it.if (foo != null) {
return foo.getKey().equals(o);
} else {
return null;
}
|
I have written this predicate and sonar is complaining about it. I am not sure how to fix this violation. Please help:import com.google.common.base.Predicate;
import java.util.Map;
public final class FooPredicate {
private FooPredicate(){}
public static Predicate<Map.Entry<Long,Long>> isFirstElement(final Long o) {
return new Predicate<Map.Entry<Long,Long>>() {
@Override
public boolean apply(Map.Entry<Long,Long> foo) {
return foo.getKey().equals(o);
}
};
}
}It is complaining about the Foo parameter to the apply method.Dodgy - Parameter must be nonnull but is marked as nullable
foo must be nonnull but is marked as nullableThe apply method is defined as taking a nullable and I can't do anything about that. So isn't Sonar and Guava fighting here?> boolean apply(@Nullable
> T input)
>
> Returns the result of applying this predicate to input. This method is
> generally expected, but not absolutely required, to have the following
> properties:
>
> Its execution does not cause any observable side effects.
> The computation is consistent with equals; that is, Objects.equal(a, b) implies that predicate.apply(a) ==
> predicate.apply(b)).
>
> Throws:
> NullPointerException - if input is null and this predicate does not accept null arguments
|
Sonar issue - parameter must be nonnull but is marked as nullable
|
OK, that was quick.I used-Dsonar.forceAnalysis=trueand the error went away.
|
Hi I'm running a Jenkins build with sonarRunner (in Gradle) and during this sonarRunner task, it's failing with the following error message. Any ideas! how to fix it?09:57:21.410 ERROR - It looks like an analysis of 'MyProject' is already running (started less than a minute ago).
:****Runner FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':****Runner'.
> org.****.api.utils.SonarException: The project is already being analysed.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
BUILD FAILED
|
SonarRunner failed - Analysis is already running
|
You should useRulesDefinitions. If rules are declared in a XML file with the standard SonarQube format (seeRulesDefinitionXmlLoader), then it can be loaded by using :public class MyJsRulesDefinition implements RulesDefinition {
private final RulesDefinitionXmlLoader xmlLoader;
public MyJsRulesDefinition(RulesDefinitionXmlLoader xmlLoader) {
this.xmlLoader = xmlLoader;
}
@Override
public void define(Context context) {
NewRepository repository = context.createRepository("my_js", "js").setName("My Javascript Analyzer");
// see javadoc of RulesDefinitionXmlLoader for the format
xmlLoader.load(repository, getClass().getResourceAsStream("/path/to/rules.xml"));
repository.done();
}
}
|
I am building a language plugin for sonarqube version 4.3. Currently I am unabl to add new repository for rules.In previous version there was AnnotationRuleParserto parse the rules. what is in version 4.3 ?please tell me how to create a new repository and add rules to it in sonarqube version 4.3 .Thanks !
|
How to create rule repository and load it with some checklist rule in sonarqube 4.3?
|
Indeed, SonarQube currently can't have 2 servers started on the same DB. This limitation (that is referenced inthis JIRA ticket) has beeen here by design since the very beginning - to make sure that you can't start 2 servers having a different set of plugins but pointing to the same DB.To answer your second question, there's no way to have 2 instances pointing to the same DB. But we've starting a big refactoring to eventually make it possible to have a cluster of SonarQube instances, so feel free to watch theSONAR-5391ticket and vote for it.
|
As per this question:Sonar throwing error BadDatabaseVersionit is not possible to run two sonar instances using the same database. Everything I've read so far implies the only solution is to shut down both instances and only restart the one you want to keep. Is my only other option to run two sonar instances, to have another sonar database? This seems pretty costly, and it seems that the only thing holding back sonar from running another instance is sharing server.core.idSo I guess I have two questions:
1) Why is sonar built with this dependency?
2) Are there any other options to run two instances on the same db?
|
Running Two Sonar Instances with One DB
|
Since version 2.2 of Java Plugin and 1.6 of Cobertura plugin, SonarQube does not trigger unit test execution anymore : Only reuse report mode is available.Please note that the recommended version for both of those plugins are the fixed versions Java 2.2.1 and Cobertura 1.6.1 to prevent the collision between JaCoCo and Cobertura plugin (which will happen with 2.2).Because of all this, the property to select the default code coverage tool is not relevant anymore and you only have to provide a coverage report (either cobertura or JaCoCo) to get your coverage information.Please refer to these piece of documentation to get a rough idea on how to do so :http://docs.codehaus.org/display/SONAR/Cobertura+Pluginhttp://docs.codehaus.org/display/SONAR/JaCoCo+Plugin
|
we had SonarQube v3.4 and recently upgraded to SonarQube V4.3. Also we use Jenkins to build and trigger sonar analysis on Maven projects and Cobertura as the code coverage tool.In the version 3.4, Sonar used to trigger (with Jenkins) the cobertura execution and collect the data, but when we upgraded to Sonar 4.3, there was no option in Sonar to select the default code-coverage tool, the Jenkins Sonar execution no longer triggers cobertura and unit test execution. Now it expects a Jacoco dump file in order to provide coverage data to sonar.I cannot find any useful documentation in Sonarqube confluence.How can we configure Sonar to use Cobertura (without modifying ALL the projects pom files) and trigger code coverage unit test execution from Jenkins?.Thanks!.
|
Sonarqube 4.3 dont trigger Cobertura unit test execution on Jenkins
|
Chances are that you don't have the test sources in your .NET solution, so when SonarQube tries to import the test execution results, it can't find to which files they should be attached.In the.NET sample solution, you can see that there is a test project (Example.Core.Tests) which contains the sources of the test classes.
|
I'm re-using reports in my sonar config:sonar.gallio.mode=reuseReport
sonar.gallio.reports.path=gallio-report.xml
sonar.gallio.coverage.reports.path=results.xmlI've previously run Gallio and OpenCover and can confirm that both completed successfully and that Sonar is able to retrieve the files (I've checked the log produced by the-Xflag thoroughly). When I view the project in the sonar dashboard, I see code coverage, but not test results:Kindly ignore the low code coverage percentage, I'm running a small subset of tests while I figure this out.I should see something that reflects the results I saw when I ran Gallio:14 run, 13 passed, 1 failed (1 error), 0 inconclusive, 0 skippedI'm happy to include thegallio-report.xmlif that's helpful, but it's 103kb so clearly it contains plenty of data, and I think this is more likely to be a configuration issue.I'm running OpenCover 4.0.1118 and Gallio 3.2.750 (tests are written with NUnit).Any thoughts why I don't see any test results?
|
Getting code coverage in Sonar but no test results (.Net)
|
Regarding the different groupIDs of the plugins you mentioned, this is explained here:What is the difference between org.codehaus.mojo:sonar-maven-plugin and org.codehaus.sonar:sonar-maven-plugin?
|
I want to analyze a Maven 3 project. I found the following plugins:org.codehaus.mojo:sonar-maven-plugin:2.0org.codehaus.sonar:sonar-maven-plugin:3.6.2org.codehaus.sonar:sonar-maven3-plugin:3.6.2So I can run Sonar analysis with 3 ways:mvn org.codehaus.mojo:sonar-maven-plugin:2.0:sonar (or simply mvn sonar:sonar since the package is org.codehaus.mojo)ormvn org.codehaus.sonar:sonar-maven-plugin:3.6.2:sonarormvn org.codehaus.sonar:sonar-maven3-plugin:3.6.2:sonarWhat is the most appropriate way for me?
|
What is the purpose of sonar-maven3-plugin?
|
Sonar 3.3 has a new feature for combine code coverage metrics generated by both unit tests and integration tests. This is done by using two properties to detail the two different report files generated by thejacocotoo:#Tells Sonar where the unit tests code coverage report is
sonar.jacoco.reportPath=reports/jacoco/jacoco-ut.exec
#Tells Sonar where the integration tests code coverage report is
sonar.jacoco.itReportPath=reports/jacoco/jacoco-it.execThe Sonar examples project has an integration test example for ANT:https://github.com/SonarSource/sonar-examples/tree/master/projects/code-coverage/it/ant/it-jacoco-antUnfortunately it doesn't give an example of running the actual tests, instead it just shows how to configure an ANT build to load data.Finally theSonar documentationhas more details with links to the example projects.
|
I am running Sonar task through Ant, triggered by Jenkins in RHEL environment. I am successfully using Cobertura for Junit code coverage and Surefire for reporting. Sonar imports the Surefire reports fine.However, now I am running Selenium tests using Ant in Jenkins. I would like to report code coverage and test results to Sonar. Apparently I need the JaCoCo plugin which analyses code coverage and reports tests. I presume like for unit tests, Jenkins does the job and Sonar only imports the reports into its own repository.I am puzzled on how to actually do this. The web pagehttp://www.sonarsource.org/measure-coverage-by-integration-tests-with-sonar-updated/references to the JaCoCo pagehttp://www.eclemma.org/jacoco/trunk/doc/ant.html. I am not sure what the steps are to be done. Do I need the coverage target? Should I only start the agent? Where in Ant do I start the agent? Do I need to dump stuff?I really appreciate all the help I can get, thanks :)
|
JaCoCo Selenium test code coverage and import to Sonar using Ant
|
The problem comes from the fact that you haven't specified a correct location for the source directory.This source directory should somehow point to "/root/.jenkins/jobs/Example_4.9/workspace/dev/statsvc/". With the Sonar Jenkins Plugin, this means that you should specify "sonar.sources" to something like "dev/statsvc".
|
Hi i am trying to analyse my code base which is in java using sonar tool, we use ANT as our build tool but when i run sonar-runner from the source directory i get12:36:09.815 ERROR heckstyleSquidBridge - Squid Error occurs when analysing :/root/.jenkins/jobs/Example_4.9/workspace/dev/statsvc/src/java/com/sample/sim/statisticsvc/StatisticsServiceImpl.java
org.sonar.squid.api.AnalysisException: The source directory does not correspond to the package declaration com.sample.sim.statisticsvcWhat should i do in this case? Do i need to run sonar in the light mode if so how do i achieve it?
|
Sonar Analysis throwing squid error
|
From what I see, I guess you're trying to run Sonar analyses with the Sonar Jenkins plugin "on-the-fly" mode, where you specify properties.You have to understand that this mode does not support running tests: it can only reuse test reports (if you specify "sonar.dynamicAnalysis=reuseReports").But as you are using Maven, why don't you just run the Sonar post-build action? (seedocumentation for that)
|
I have some maven projects configured in Jenkins, and I execute them from a parent project (which have them as<modules> in its pom.xml, the children have this project defined as<parent>).The unit tests execute successfully for each project in Jenkins and it shows the results, but then in Sonar all projects appear as having no unit tests.The sonar configuration for each project issonar.projectKey=project:key
sonar.projectName=project_name
sonar.projectVersion=1.0
sources=src/main/java
tests=src/test/java
binaries=target/classesDo I have to do anything else in order for Sonar to pick up the results of the unit tests being executed?Thanks in advance.
|
Unit test results not showing in Sonar when building child projects in Jenkins
|
It all dependes on your need and your team velocity to develop new code, test and integrate new functionalities into the project.If you have a sprint with a time box of a web, probably that on the weekend, the version that started on monday is stable, and therefore bug free, or only a few bugs. If your sprint time box is a week, i would higly recommend at least once a day, so you can get defects running unit tests and so on, giving a good reality on your project quality.I would recommend these practices:Using code coverage like Cobertura, running unit tests at least once a day;Using code analysis like PMD, checkstyle and so on. If possible, create your own rules that applies to your architecture, generating more value for your project in terms of quality.Considering your time box for a Sprint, choose a frequency for your builds in sonar and schedule a cron job that runs it only when you really need it(since its time consuming).These are practices I use in my projects, but you have to look closely to your needs, since the tool (Sonar) is to help you with information about the quality of your project, and therefore, your architecture, your team and your engineering practices.
|
I have been digging quite a bit on Sonar best practices. The consensus seems to be that Sonar would be launched only once a day or week, e.g. during the night. However, what if one uses a CI server such as Jenkins? Jenkins builds on every SVN commit, runs unit tests, deploys to staging environment, runs Selenium tests, etc. The way I understand it, all this additional information is lost if Sonar is launched only once a day/week. Most likely all the team's code problems and failing tests have been resolved on in the afternoon or end of the week. Sonar runs probably on Sunday night or every night. The application is pre-built and tested, and then Sonar analysis is executed based on that information. Most likely all tests pass, no major code problems are left in the repository, and the QA team incorrectly believes that there are no problems since all Sonar reports display green. However, during the day/week it is possible that the project has been a total mess with broken builds etc., but is never displayed in Sonar reports :)Am I missing something here, or should Sonar actually be executed upon every commit, or at least once an hour?
|
Is it enough to launch Sonar only once a day or week?
|
I think the tutorial is old. In the newest sonar (2.1.2), if a plugin doesnt have global configuration it will not appear in the settings.This is what I started with,running the archetype will provide you with an up-to-date example plugin, it's worked fine for me:http://docs.sonarqube.org/display/SONAR/Getting+startedAnd those tips have been really helpful going forward:http://docs.sonarqube.org/display/SONAR/Coding+a+plugin
|
I'm trying to get started with sonar plugin development. Ive started off by following this tutorialhttp://docs.codehaus.org/pages/viewpage.action?pageId=117899451Ive built this hello world plugin and have copied the resulting jar (helloworld-1.0-SNAPSHOT.jar) to the /extensions/plugins directory.I have rebuild the war. .//war/build-war.shThe new war file is built. I then run sonar in standalone mode and browse to "Configuration > Settings" to try and view this plugin.... nothing. All the core plugs are there (Clover, Design....) but not my new hello world plugin.There are no errors or relevant info in the logs. When I explore the new war file I can see that the helloworld-1.0-SNAPSHOT.jar has been added to /WEB-INF/lib/Any ideas?I am using sonar-plugin-api version 1.10, my sonar instance is version 2.1.2. Could this be the issue?I have no feedback from the sonar application at all, so im a little lost.Thanks
|
Sonar, cant see my hello world plugin
|
Posting the answer as it can be helpful to someone in the future:This was happening because the SonarQube was using the old version. I updated the SonarQube and this error vanished.The issue was happening in some 6.3.x version I updated it to 9.x version and everything is solved now.
|
I have a Java project running in Java 17 version. I have pushed my code to the organization repository whereSonarQubeis running. In that repository, I am getting issues/bugs for all theJava Streams Listthat I have used in my project. Even for the simple ones.Can someone please inform me why am I getting the issue for following Java Streams?1. return input.stream().filter(Objects::nonNull).toList();
2. return input.stream().map(String::toLowerCase).toList();
3. return input.stream().filter(Objects::nonNull).map(i -> DOMAIN + "/" + i).toList();For all the above mentioned Java Streams I am getting the following issue:Refactor the code so this stream pipeline is used.I tried to use the.collect(Collectors.toList());instead of.toList();, if I do that then myIntellij/SonarLintshows that I need to use the.toList();. So I am bit confused.Can someone please tell me what's wrong with these Java Streams? I do not have any issue with this?
|
Why does SonarQube is showing the message for all Java Streams: Refactor the code so this stream pipeline is used.?
|
how do we add the "Status to Check" field, what is it pointing to, what reference should be provided?Please follow below steps.Create a build pipeline using this repository and specify its master branch.Please follow this doc:Deploy pull request Artifacts with Azure Pipelinesto configure your release pipeline using this build pipeline.Set up the branch policies and set this build pipeline as theBuild Validation.Create a test pull request to trigger this build pipeline, and then the successful build will trigger a pull request release and then the release is deployed to the specified environments, and the status of the deployment is displayed in the PR page.SelectAdd status policyin the branch policies and select a status policy from the status to check dropdown menu. The dropdown contains a list of recent statuses. Everything is done.Now you should know how to add Sonarqube PR Decoration as the status policy in the branch policies for all the pull request. See video:Azure DevOps Pull Request/Branch Decoration with SonarQubefor more details.
|
I wanted to understand on the Status Check option that is given in the "Build Policies" in AZURE VSTS. I have gone through the below doc from Azure, but I'm unable to know how do we add the "Status to Check" field, what is it pointing to, what reference should be provided?https://learn.microsoft.com/en-us/azure/devops/repos/git/pr-status-policy?view=azure-devopsI want to add Sonarqube PR Decoration for all the pull request created, I have also gone through the below document form sonarqube, but unable to get it how exactly its done.https://sonarqube.kognif.ai/documentation/analysis/azuredevops-integration/#adding-pull-request-decoration-to-azure-devopsCan anyone let me know on this?
|
How add the Status Check Validation in Azure build Policies for PR
|
Have you tried to start SonarQube as root in a previous run?
If so, the ES config file has been created as root and now when you're trying to start the service as another user it can't overwrite the file.To fix it, delete the temp folder in your $SONAR_HOME and it should work.sudo rm -r $SONAR_HOME/temp
|
I install 7.9 version of sonarqube on aws ec2 instance and it is running fine.
due to not compatible with my code i am upgrading to latest version 8.3.
i download zip and unzip it.
after stoping older version, i try to run it.
i am getting error as below.java.lang.IllegalStateException: Cannot write Elasticsearch yml settings fileCaused by: java.nio.file.AccessDeniedException: /opt/sonarqube/sonarqube-8.3/temp/conf/es/elasticsearch.yml
|
Sonarqube will not start due to elasticsearch being unable to write yml settings
|
In Visual Studio:Change the following line:"no-extra-parens": 1,to"no-extra-parens": 0,
|
i'm getting error when i'm running ESLint on my JavaScript code.var crslWt = 100;
var totCrslWt = (crslWt/2)-20;i'm getting errorGratuitous parentheses around expression no-extra-parens
|
Need fix for EsLint error: Gratuitous parentheses around expression-no-extra-parens
|
Looks like the main reason for that to happen is that Scala bug patterns are explicitly excluded for some reasons:Their are plenty of limitation with the SonarQube architecture regarding the multi-language support.
It is closely tie to the sonar-source plugin design.Language can't have the same extension (https://jira.sonarsource.com/browse/MMF-672)Repository can't contains rule that apply to multiple languages. (If you would have Scala only code, the Java core rules would not be enable unless you have one Java file present)Sensor are couple to the language definition (depends on the most popular plugin that declares it).etc, etc..Source:https://github.com/spotbugs/sonar-findbugs/issues/108#issuecomment-305909652All the exclusions can be seen here:https://github.com/spotbugs/sonar-findbugs/commit/526ca6b29fae2684f86b1deba074a4be8a05b67eParticularly, for Scala:static exclusions = ['CUSTOM_INJECTION',
'SCALA_SENSITIVE_DATA_EXPOSURE',
'SCALA_PLAY_SSRF',
'SCALA_XSS_TWIRL',
'SCALA_XSS_MVC_API',
'SCALA_PATH_TRAVERSAL_IN',
'SCALA_COMMAND_INJECTION',
"SCALA_SQL_INJECTION_SLICK",
"SCALA_SQL_INJECTION_ANORM",
"PREDICTABLE_RANDOM_SCALA"]
|
I have been trying to scan my code by using SonarQube + FindBugs + FindSecBugs plugins.The idea is to detect vulnerabilities in the code, and as it says in the github project subject, it works with scalahttps://github.com/find-sec-bugs/find-sec-bugsI have installed the plugin as the documentation says, and tried a few scans but nothing related to vulnerabilities in scala is coming up.So, in order to figure out if the code was really good or there was a misconfiguration on my SonarQube settings, I went tohttp://find-sec-bugs.github.io/bugs.htm, I took one of the examples (Potential Path Traversal), inserted the example code and I ran the scanner again. It was not found.The rule (Security - Potential Path Traversal (file read)) is activated in the Quality Profile, and despite it is a Java profile, it is assigned to the project, since the code in the mentioned example is Scala.I noticed that all the rules coming from find-sec-bugs are java ones, so I'm wondering if they don't work on scala or there is something else I can do to make it work.Thanks in advance, and let me know if you need any extra information, I'd be glad to provide you.
|
Path traversal vulnerabilities not found at Scala code
|
For now (SonarQube 7.4), SonarGo analyzer does not identify automatically*_test.goas test files. This is a missing feature, this is why theSonarGo documentationdescribes how to properly identify test files through settings:sonar.test.inclusions=**/*_test.goWithout proper test identification, the coverage result will be wrong and the analysis result could raise issues that do not make sense (like hard-coded IP addresses in tests).About the coverage accuracy (for files that are not test files), there's two cases:If a file has entries related to it in the coverage report, the covered lines shown in SonarQube should match exactly the ones in the report, otherwise it's a major bug. But thepercentageshown by go tools (ranges coverage) could be slightly different that the percentage shown in SonarQube (lines coverage), e.g: +2%.If a file is not in the coverage report, SonarGo generate a 0% coverage based on its definition ofexecutable line of code. If there's a difference withgo testdefinition ofexecutable line of code, it's a bug that will disappear once the file is partially covered.The best way to have those coverage bugs fixed, is to report them atcommunity.sonarsource.comby creating aReport a Bugtopic with a small code reproducer.
|
SonarQube 7.3 it has inbuilt support for golang where I have found at least 2 issues :-It does not exclude *_test.go automatically from coverage. In unit tests it also picks up IP addresses and asks them to be made configurable (not constant which also does not fix the error).It counts structs and const as not covered lines and hence has a significantly lower % covered than the go coverage tool itself making it a bad use case. For example in a medium size project it reports 40% coverage against go tools 70%Apart from commenting them all to be sonar exclude or putting constants and structs in a common exclude pattern file is there something else that can be done? Is there a plan to address these in a later version of SonarQube?
|
How to exclude golang tests, structs and constants from counting against code coverage in SonarQube?
|
Your question is not very clear to me (especially the relation with tortoisesvn). SonarQube is analyzing source code, and you have to run a SonarQube scanner on the source files you have previously checked out.While analyzing source file content, SonarQube can also use SCM informations (blame) for various features, like issue auto-assignment. The scanner should detect that source files are coming from an SVN repository (thanks to the .svn file located at the root) and will run the blame command on every files.
|
I need to integrate SVN with SonarQube.Is this possible? Somewhere I read that we need to have a local project folder to have this work.Can anyone provide steps to integrate SVN with SonarQube.
|
How to integrate SVN in sonarQube for analysis
|
You can not deactivate rule in a built-in profile. You will need to create your own profile (click on Quality Profile menu). Once you have your own profile you can activate/deactive/customize rules at will.Don't forget to associate the profile with your project or set it as a default afterwards.
|
I want to deactivate the rules in sonarqube. I'm using community edition. I can't find deactivate button on my UI provided. I have googled it but can't find any deactivate button as they specified. I'm attaching my rules page below.
|
Deactivate a rule in Sonarqube community edition
|
You can add this certificate to the java cacerts store.
After that it is trusted for Java. you have to do this for the Java version you are using on Eclipse.Here is an example of the calls for github.com:"C:\Program Files\Java\jdk1.8.0_121\bin\keytool" -keystore cacerts –list
"C:\Program Files\Java\jdk1.8.0_121\bin\keytool" -keystore cacerts -importcert -alias github.com -file C:\temp\github.com.cerNote: you have to open the CMD in the folder where the cacerts file is located. This is normally in C:\Program Files\Java\jre1.8.0_121\lib\security or C:\Program Files\Java\jdk1.8.0_121. The path is here only an example.
|
I followed the steps in the SonarQube docs to allow my SonarQube server to use HTTPS by putting a Proxy behind it:https://docs.sonarqube.org/display/SONAR/Securing+the+Server+Behind+a+ProxyI created an apache server and installed mod_proxy module by following these instructions:http://frvabe.blogspot.com/2016/06/running-sonarqube-behind-proxy.htmlWhen I add the server using http and the default port 9000 the connection is successful. However when I try adding a SonarQube server using https and 8443 I get the fail to request error (Yes I am putting the credentials correctly :)):ErrorI am able to access the URL with https and port 8443 from IE i.e. "https://myserver.com:8443/". I login and view all projects with no problem.I do not see any error logs anywhere (workspace, installation directory, IDE error views, event viewer, etc.)I know that it has to do with the certificate not being "trusted" since in is a self-signed certificate. Is there a way to tell SonarLint to "Trust" this certificate?Any help will be greatly appreciated.Thank you!JP
|
Unable to connect to SonarQube Server using HTTPS in Eclipse Oxygen (SonarLint Plugin)
|
Writing custom rules for SonarPython using java is not supported.
Currently there's no initiative to enable it.
But if the rules are not specific to your context and can be useful to every python code, you can contribute by writing descriptions and non-compliant/compliant code examples in this google group:groups.google.com/sonarqube, or you can create a pull request ongithub.com/SonarSource/sonar-python.
|
According to documentation there're 2 ways to include custom rules:Writing coding rules using Java via a SonarQube pluginAdding XPath rules directly through the SonarQube web interfaceAccording tolinksonar-python doesn't support the first way which I would like to use.I wonder whether something is changing and this feature is going to be supported? If this feature is supported where can I find a tutorial which is like a tutorialfor Java? Or is there only one way to create own Sensor and use implemented python-parser?
|
Sonar: is there a way to add custom rules for python using Java
|
I was seeing the exact same problem as Vignesh. Running SonarQube 6.7.1 and latest version of VSTS SonarQube extension.I found out what the problem was; it's in the SonarQube VSTS Extensions (Prepare, Analyse & Publish).The SonarQube extension uses basic authentication to communicate with the SonarQube API endpoint, and uses the token as username, and password as null.
The npm package 'request' (at least latest version 2.83.0), does not allow null passwords and returns 'auth() received invalid user or password'.To fix it, the password should be set to an empty string instead.Until the VSTS plugin is fixed by SonarSource, you can workaround the issue by manually editing the extension on your VSTS build machine. The file to edit is:<build location>\_tasks\SonarQubePublish_291ed61f-1ee4-45d3-b1b0-bf822d9095ef\4.0.0\common\helpers\request.jsAdd a new row after row 22:options.auth.pass = "";The endresult should be something like:var options = {
auth: endpoint.auth
};
if (query) {
options.qs = query;
options.useQuerystring = true;
}
options.auth.pass = "";
request.get(__assign({ method: 'GET', baseUrl: endpoint.url, uri: path, json: true }, options), function (error, response, body) {I give no guarantees, but this worked for me.
|
I am using Prepare, Run and Publish analysis tasks in VSTS to run the SonarQube analysis and publish the results to build summary. First two steps execute successfully but the 'Publish Analysis' task fails because it is not able to fetch the task for analysis ID. I get the following error message:Could not fetch task for ID 'AWE9-wu8-fbfJflhFQ3-'VSTS Publish Analysis Task Log:2018-01-28T18:15:28.1037139Z ##[debug][SQ] Waiting for task 'AWE9-wu8-fbfJflhFQ3-' to complete.
2018-01-28T18:15:28.1037139Z ##[debug][SQ] API GET: '/api/ce/task' with query "{"id":"AWE9-wu8-fbfJflhFQ3-"}"
2018-01-28T18:15:28.1047138Z ##[debug][SQ] Publish task error: [SQ] Could not fetch task for ID 'AWE9-wu8-fbfJflhFQ3-'
2018-01-28T18:15:28.1047138Z ##[debug]task result: Failed
2018-01-28T18:15:28.1047138Z ##[error][SQ] Could not fetch task for ID 'AWE9-wu8-fbfJflhFQ3-'
2018-01-28T18:15:28.1047138Z ##[debug]Processed: ##vso[task.issue type=error;][SQ] Could not fetch task for ID 'AWE9-wu8-fbfJflhFQ3-'
2018-01-28T18:15:28.1047138Z ##[debug]Processed: ##vso[task.complete result=Failed;][SQ] Could not fetch task for ID 'AWE9-wu8-fbfJflhFQ3-'
2018-01-28T18:15:28.3907147Z ##[section]Finishing: Publish Analysis Result
|
Unable to integrate SonarQube analysis results with VSTS Build Summary
|
Using all files in your maven repository should work but it might make the analysis slower as the plugin will have to look for classes in high number of jars.You should use the SonarQube scanner for maven. It will automatically pick up the classpath from your maven configuration.
|
My Jenkins job uses the Sonarqube plugin to start an analysis. It is reported thatsonar.java.librariesis not set and the result may be inaccurate.What value should I assign to this variable? The project is built with a maven build step. So all the dependecies are somewhere on the jenkins node under/var/lib/jenkins/.m2/repository/.Issonar.java.libraries = /var/lib/jenkins/.m2/repository/**really a correct value or did I misunderstand something?
|
Configuration of parameter sonar.java.libraries when launched from Jenkins
|
Practically speaking, there is little point of using the SonarQube scanner withTreatWarningsAsErrors=true, because when the build breaks, there will be no build results from our analyzers, the end step will not be executed and no issues will be pushed on SonarQube. If there are no issues from your builds, there is no reason to use SonarQube. In addition, withTreatWarningsAsErrors=trueyou will be forced to fix everything beforehand, or live with failing builds for long time, which I would not advise.SonarQube allows you to fix your existing and new issueslittle by littleand avoid having failed builds for long time because of warnings. You can rely on the quality gates for feedback about your code quality and even, if you insist, fail the builds when the quality gate does not pass (note that on large projects this might affect the build time).If your builds are required to fail because of compiler warnings (note that SonarQube does not collect the standard compiler warnings, just the results of the Roslyn analyzers), I would recommend creating a separate build job for analysis. This way you will have the best of both worlds - issue tracking in SonarQube and failing builds because of compiler warnings.
|
I have been trying to make my solution fail to build on Visual Studio Team Services when there are warnings. I have enabled the option in the project in VS2017 to treat warnings as errors, so that it won't build.Also, there is a MsBuild argument for the same purpose set to true on VSTS.This works, as when there is a warning it is treated as error (Eg. an unused int is a warning and becomes an error, failing the build).However, when the SonarQube Analysis is present, the build does not fail. SonarQube overrides "TreatWarningsAsErrors = true" for some reason, and the warning stays as a warning.I haven't found any option to enable TreatWarningsAsError on SonarQube server. I checked rules, quality gates, etc.How is this supposed to be done?
|
Treat Warnings as Errors using SonarQube Analysis
|
You need to download the latest version ofSonarScanner for MsBuild. The zip file contains all needed executables.You should not usesonar-scannerfor analyzing .NET projects.
|
I am checking thedocumentation for sonarqube msbuild scanner. But I can't find theSonarQube.Scanner.MSBuild.exein the distribution given. So when I point the bin directory and run sonar command given in that pageSonarQube.Scanner.MSBuild.exe begin /k:"org.sonarqube:sonarqube-scanner-msbuild" /n:"Project Name" /v:"1.0"
MSBuild.exe /t:Rebuild
SonarQube.Scanner.MSBuild.exe endI got an error saying'SonarQube.Scanner.MSBuild.exe' is not recognized as an internal or external command,Since this exe file is not in the distribution and it runs usingsonar-scannerbat file what is the correct command to run the project?
When I usingsonar-scannerinstead ofSonarQube.Scanner.MSBuild.exe, it complains about/koption.
|
How to configure sonarqube msbuild scanner
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.