Response
stringlengths
8
2k
Instruction
stringlengths
18
2k
Prompt
stringlengths
14
160
Unfortunately it is still impossible out of the box. To fix the issue you can either:use istanbul merged withthisrequest,process the output file using tools likesed(example),generate the report from the same machine that Sonar scanning is performed (original advice).ShareFollowansweredAug 11, 2017 at 9:09Artur MalinowskiArtur Malinowski1,1241010 silver badges3030 bronze badgesAdd a comment|
I need to have relative path as value of SF: parameter in the lcov.info file generated by karma coverage. This is to enable SonarQube to gather the info to display the coverage. Currently, the SF parameter is having complete absolute path , e.g. c:\abc\xyz....\src\bar\foo.jsI need to have SF: src\bar\foo.jsIs there a way to achieve this?
LCOV.INFO has absolute path for SF
SonarLint is right. The problem is that there is no guarantee thatelementsfield is serializable. You need to add type bound onTtype like thispublic class Page<T extends Serializable> implements Serializable {}This way the list will be serializable if implementation chosen for it is serializable (which is true for standard collection types in Java).ShareFollowansweredJul 24, 2017 at 13:12Tibor BlenessyTibor Blenessy4,3123030 silver badges3737 bronze badgesAdd a comment|
My question is very similar tothisexcept that this issue I have encountered in SonarLint V3 (squid:S1948).My code is :public class Page<T> implements Serializable { Summary summary; List<T> elements; public Page() { summary = new Summary(); } public List<T> getItemsReceived() { return elements; } public void setItemsReceived(List<T> list) { this.elements = list; } public Summary getSummary() { return summary; } public void setSummary(Summary summary) { this.summary = summary; } }The Summary Object implements serializable.public class Summary implements Serializable { int offset; int limit; long totalElements; public int getOffset() { return offset; } public void setOffset(int offset) { this.offset = offset; } public int getLimit() { return limit; } public void setLimit(int limit) { this.limit = limit; } public long getTotalNumberOfElements() { return totalElements; } public void setTotalNumberOfElements(long totalNumberOfElements) { this.totalElements = totalNumberOfElements; } }Now, If I replace List by ArrayList , then another warning in SonarLint arises that we should be using interface instead of implementation classes.I think this might be resolved in SonarQube but for SonarLint I don't know. Is this a bug or am I doing something wrong ?
SonarLint V3: Fields in a "Serializable" class should either be transient or serializable for List interface
JdbcTemplatehas 3 methods namedquery, where first argument is aString, and second argument is anObject[]:query(String sql, Object[] args, ResultSetExtractor<T> rse)query(String sql, Object[] args, RowCallbackHandler rch)query(String sql, Object[] args, RowMapper<T> rowMapper)The functional interface for the third argument of the first two take a single parameter of typeResultSet:ResultSetExtractor.extractData(ResultSet rs)RowCallbackHandler.processRow(ResultSet rs)That is why the compiler needed a little help to figure out which one you meant.That IDE/Sonar is flawed and cannot see that cast is necessary, is just a bug.ShareFollowansweredFeb 28, 2017 at 6:52AndreasAndreas157k1313 gold badges155155 silver badges250250 bronze badges0Add a comment|
When I compile this code it's showing[ERROR] The method query(String, Object[], ResultSetExtractor) is ambiguous for the type JdbcTemplateCollection<MyType> col = getJdbcTemplate().query(someQuery, new Object[]{param}, rs -> { Map<Long, MyType> map = new HashMap(); while (rs.next()) { // mapping logic } return map.values(); });But if I castrsto(ResultSetExtractor<Collection<MyType>>)it somehow compiles properly.Collection<MyType> col = getJdbcTemplate().query(someQuery, new Object[]{param}, (ResultSetExtractor<Collection<MyType>>) rs -> { Map<Long, MyType> map = new HashMap(); while (rs.next()) { // mapping logic } return map.values(); });But my IDE(with sonar) reports it as redundant cast, reports everything inside the lambda body as unused. I'm using jdk 1.8.0_121Can somebody throw some light on this please, thanks
Using lambda with JdbcTemplate query method showing ambigious error
sonar.projectKeyis an ID of the project. Example: if you will analyze project A and next project B with the same ID, then data of B will overwrite result stored for A project.sonar.projectNameis a display name - visible in SonarQube dashboard. Example: My Projectsonar.branchallows you to analyze more branches of one project. Example: if you analyze development branch of project A with ID equal to A, then SonarQube will create project A. Next if you analyze any branch of project A, then new data will overwrite previous results. But if you want to create a new project for other branch (instead of overwrite result for development branch), then you can usesonar.branchproperty which will generate a new ID (combined value ofsonar.projectKeyandsonar.branch)ShareFollowansweredDec 23, 2016 at 20:54agabrysagabrys8,89833 gold badges3535 silver badges7575 bronze badgesAdd a comment|
I'm not sure if I understand correctly the use of parameters ProjectKey, ProjectName and branch in a sonarscanner analysis.Suppose that I have a project with diferents branches. When I run the analysis independently of the branch, the value for ProjectName and ProjectKey parameters has to be always the same?Or every branch analysis must have a different project key? What is the best practices in that case?
Right use of ProjecKey, ProjectName and Branch
+50This is just impossible to merge analysis reports for one project.Technically, this would probably be achievable to execute only 1 single SonarQube analysis that does both the .NET part and the Java/JavaScript part. This would answer your use case. But this would be a kind of hack.IMO, the good way to do it is to split your source code in 2: the .NET part and the Java part. There are chances that these are 2 different technical components anyway, that might have different life cycles even though they relate to the same "business" application.ShareFollowansweredNov 28, 2016 at 10:53Fabrice - SonarSource TeamFabrice - SonarSource Team26.6k33 gold badges6363 silver badges5858 bronze badgesAdd a comment|
We are using the SonarQube Scanner for MSBuild and the default SonarQube Scanner through Jenkins in our project. The two scanners are executed from different jenkins jobs. One job for .net code and the default scanner for java & typescript.As project version, the git commit hash is used. The results from both scanners seem to overwrite each other even with the same commit hash. Either we have only C# results or only java / ts results.How can we get merged results in one SQ project?SonarQube Version 5.6
How to get merged project results in SonarQube from 2 scanners?
I found this question because I got the same "parameter missing" error message.So what we both did not understand: The SQ API expects the parameters as plain URL parameters and not as json formatted parameters as most REST APIs do today.PS: Would be nice if this could be added to the SQ documentation.ShareFolloweditedJun 6, 2017 at 5:10answeredJun 1, 2017 at 15:41Horst KrauseHorst Krause67677 silver badges2222 bronze badgesAdd a comment|
we try to automate the creation of projects (including user/group Management) in sonarqube and I already found the Web-API-documentation in our sonarqube 5.6-Installation. But if I try to create a project with the following settingsJSON-File create-project.json:{"key": "test1", "name": "Testprojekt1"}curl-requestcurl --noproxy '*' -D -X POST -k -u admin:admin -H 'content-type: application/json' -d create_project.json http://localhost:9000/api/projects/createI get the Error:{"err_code":400,"err_msg":"Missing parameter: key"}It's a bit strange because if I try e.g. the URL:http://localhost:9000/api/projects/indexI get the list of the projects I created manuelly and if I try a request likecurl -u admin:admin -X POST 'http://localhost:9000/api/projects/create?key=myKey&name=myProject'it works too, but I would like to use the new api because it looks like it support much more function that the 4.X API of sonarqube. Maybe someone here can help me with this problem, if would very thanksful for every useful hint. best regards Dan
create project for sonarqube with the rest-api / web-api
If you are using version3.14of the SonarQube Java Plugin, it is a known issue. The fix will be released with next incoming version (4.0). Associated JIRA ticket:SONARJAVA-1719For older versions of the plugin (3.13.1and before), the@SuppressWarningsannotation should work as expected and hide issue when the key of a rule is used.ShareFollowansweredJun 20, 2016 at 8:10WohopsWohops3,1011919 silver badges2929 bronze badges1Yes, I can confirm that we have version 3.14 of the Java plugin installed. This explains everything.–AlixJun 20, 2016 at 9:10Add a comment|
In SonarQube 4.5.x LTS the annotation@SuppressWarningscould be used to suppress false positives in code but after upgrading to 5.4 and re-arranging some packages these, previously suppressed, issues have resurfaced. Why?I have been told that the recommendation from SonarSource (company developing SonarQube) is to suppress false positives from the administrative UI but we prefer to do it directly in code for reasons*. The violation below is clearly suppressed using the annotation:Is@SuppressWarningsno longer handled in SonarQube?* Reasons include:No dependency on SonarQube database stateNot having to rely on SonarQube being able to identify an old suppressed line of code when changed)Update (2017-02-03): SonarQube 6.x handles moving code around and keeping false positives
@SuppressWarnings broken in SonarQube?
First off, this rule does not indicate a general problem in the code -volatileis a perfectly fine keyword, and there is nothing wrong with it. That's why it's acontroversial rule.On the other hand, using it is indeed a bit of an advanced technique that requires you to know what you are doing. Situations exist where you would know that, let's say, the people who will maintain your code will not have sufficient Java knowledge. In such cases, the rulemaymake sense.To satisfy the rule in your case, useAtomicBoolean.ShareFollowansweredDec 23, 2015 at 10:16barfuinbarfuin17.1k1111 gold badges8787 silver badges133133 bronze badgesAdd a comment|
One of the rule defined in the PMD rule set is:"Avoid using Volatile"which explains that"Use of modifier volatile is not recommended". This rule is mentioned under theControversial Rule Setof PMD.In my team, we have Sonar configured on various modules which indirectly has the rule set from PMD and hence any use ofvolatilepops as a critical warning.Question is why are we using volatile?The volatile keyword is used for boolean variables to control the state of the external session. This state is accessed across various threads and hence to know if the state is UP or DOWN, it is maintained as a boolean volatile variable, so that visibility is shared across multiple threads.My question is how to fix this sonar warning?One solution is to remove the rule from the rule set, which is not allowed because: firstly it is not recommended as these rules form the basic guidelines defined from PMD rule set and secondly the SONAR server in my organisation is a central server being used by all the teams. Hence is not allowed.Another solution is to ignore the sonar warning by use of some annotation, which is again not recommended on basic rule set.Can anyone suggest how can we fix this sonar warning in code?Thanks in advance.
Avoid Using Volatile Fix
It sounds like you're using the built-in profile as your default profile. If you're happy with the built-in profile as-is, then that's a great way to go. But it sounds like you're not. So instead, I'd suggest you make a copy of Sonar Way, I'll call it 'Copy', and set it as your default profile. Then after each upgrade, you can reset Sonar Way, use the comparison service to see the differences between Copy and Sonar Way and then choose which new changes to apply in Copy.ShareFollowansweredNov 11, 2015 at 12:12G. Ann - SonarSource TeamG. Ann - SonarSource Team22.5k44 gold badges4242 silver badges8484 bronze badges17As this is the current solution, it is not the most proper way to go. What if I want to decorate a class in Java - do I have to create a new class that is a copy of the original and synchronize it on each change of the original class or I could just extend it and let the compiler do the rest :)–Adrian MitevNov 11, 2015 at 14:36Add a comment|
I've read the docs about profile inhertiance[1]. They say that "A rule inherited from a parent cannot be deactivated". Is this on purpose and will it be supported in the future?When I upgrade some plugin (i.e. the JavaScript analysis plugin) there are new rules and I have to restore the built-in profile "Sonar Way" in order to get the new rules. However when I do this I lose all the previous configurations (deactivated rules) and I have to remember what I've done in the past and repeat that again.
SonarQube: Profile inheritance and rule deactivation
Yes, you can. Just make sure the following variables are unique:conf/wrapper.confwrapper.ntservice.name=SonarQube[version]conf/sonar.propertiessonar.web.port=[unique port]sonar.jdbc.url=jdbc:postgresql://localhost/sonar[version] #(in case you have a postgresql db)ShareFollowansweredSep 14, 2015 at 8:37TallandtreeTallandtree87166 silver badges77 bronze badges3Thanks for the info. Let me check this if this can be implemented and can I choose the specific Sonar version for specific job.–drsdarpanSep 14, 2015 at 8:54Do I need to use different db for new version?–drsdarpanSep 14, 2015 at 9:04Yes, you need to create a new database instance for the other version. BTW: you need to set sonar.search.port also to another portnumber.–TallandtreeSep 14, 2015 at 10:53Add a comment|
Can we run 2 instances(2 different versions) of Sonar on same machine?At present Sonar 3.7.3 is installed and is been used with Hudson for Sonar Reports. Now, there are some projects that run on Java 8 and Java 8 is not supported by 3.7.3 Sonar version.So to run the Java 8 projects, I need to use the latest version of Sonar but upgradation of Sonar would impact the existing projects that run on Java 6.So can we configure 2 Sonar instances and can configure Hudson accordingly so that both the java 6 and java 8 projects can be run for Sonar reports?
2 instances of Sonar on same machine
Replacing default Maven logging implementation is currently not supported. Ticket created:http://jira.sonarsource.com/browse/MSONAR-122ShareFolloweditedJun 10, 2015 at 8:14answeredJun 8, 2015 at 14:29Julien H. - SonarSource TeamJulien H. - SonarSource Team5,25711 gold badge2020 silver badges2525 bronze badges9Ok, fixed the command. I still get an error related to logging, though not the same. No issue with Maven 3.1.1, Maven 3.2.2 and 3.3.3 fail.–fbivilleJun 8, 2015 at 15:57FYI I'm using Maven 3.2.2 without any issue. Do you have changed default logging implementation of Maven (for example I read that it is possible to replace logback by log4j2 to get console colorization)?–Julien H. - SonarSource TeamJun 8, 2015 at 16:171Right, I'm usinggithub.com/jcgay/maven-colorwith Maven 3.2.2 (not active with 3.3.3 tho).–fbivilleJun 8, 2015 at 16:42I have reproduced, thanks. Ticket created. Should be fixed in next version of the SQ Maven plugin.–Julien H. - SonarSource TeamJun 10, 2015 at 8:14Hi guys, I'm also encountering this error. Im using spring boot with aspectj-maven-plugin plugin. Could this be the reason? Here's my pom:textuploader.com/a5y78–OrvylJul 24, 2015 at 3:55|Show4more comments
I've been facing an issue with Maven SonarQube plugin (v2.6) when Maven version is recent (strictly larger than 3.1).Here is what I run:mvn clean verify -Psonar mvn org.codehaus.mojo:sonar-maven-plugin:2.6:sonar -PsonarThe first invocation makes sure sources are compiled and JaCoCo agent is prepared.The interesting part comes, when the second command is run:[ERROR] Failed to execute goal org.codehaus.mojo:sonar-maven-plugin:2.6:sonar (default-cli) on project merlin-schema: Error setting Log implementation. Cause: java.lang.reflect.InvocationTargetException: org/slf4j/Marker -> [Help 1]Any fix to be published?
Logging error when executing Maven SonarQube plugin
I had to use a different setting.Instead of Configuration->Settings->Exclusions->Files->Source Files ExclusionsI had to use Configuration->Settings->Exclusions->Issues->Ignore Issues on Multiple Criteria.In this setting, I had to set the RULE KEY PATTERN to*, and I had to set the path wildcard in the FILE PATH PATTERN,**/Migrations/.works perfectly.ShareFollowansweredJun 8, 2015 at 12:24Mark VinczeMark Vincze7,83588 gold badges4343 silver badges8282 bronze badges2Which version of SonarQube was this for?–user944849Aug 24, 2015 at 20:31This was with version 4.1. I updated to the latest 5.1.1 since then, but I haven't checked if it's still working.–Mark VinczeAug 25, 2015 at 9:38Add a comment|
There have been some questions about this, but none of them solves my problem.I use SonarQube to do code analysis on one of my projects, which contain a Migrations directory. I would like toexcludeall the source files in that directory from the code analysis.In the projects Configuration->Settings->Exclusions->Files->Source Files Exclusions I added"**/Migrations/.", but in the analysis results I still get issues in code files in that directory.The directory structure of my project looks like this:\MyProject\Migrations\SourceFile.csWhat am I doing wrong? Am I entering the wildcard in the wrong place, or my wildcard is wrong?In the logs I can see13:06:23.460 INFO - Copy-paste detection exclusions: 13:06:23.476 **/Migrations/*.*but then I can also see13:06:12.076 INFO - Inspecting <MyProject>\Migrations\SourceFile.cs
How to exclude a directory from the code analysis?
Like what you can read on thedocumentation of the differential view featureof SonarQube, you can achieve this using the "period 4" or "period 5" properties at project level, and specify a version to compare to.Note that you can update the analysis history of your project to add versions on specific analyses, as described on theHistory and Events documentation page.ShareFolloweditedDec 18, 2015 at 9:46Rolf Staflin2,12222 gold badges2222 silver badges1919 bronze badgesansweredSep 30, 2014 at 8:31Fabrice - SonarSource TeamFabrice - SonarSource Team26.6k33 gold badges6363 silver badges5858 bronze badges12Ah. And it only workedafterI made Sonar run over the code again.–TheodosiusOct 10, 2014 at 15:56Add a comment|
At the top of the SonarCube page for my project there is a drop down box to access deltas - but I can only choose "since previous analysis", and "over 30 days". As I have a very slow developing project, like a version every two months, the 30-days choice is of no use for me at all, and this drop down boils down to two versions.What I need is to compare any two arbitrary versions of the project (that Sonar analysed before). Is this possible? How?Note: Currently I run SonarQube 4.3.
SonarQube: How do I compare arbitrary versions?
I don't know if it applies to your concrete example, but keep in mind that code coverage tools typically don't work well for alternative JVM languages unless they support them explicitly. This is because virtually all of those languages generate extra byte code that may only get executed in certain cases. For example, Groovy might generate byte code for a slow path and a fast path, and might decide between them automatically, without the user having a say.The situation might improve with Groovy 3.0, which will be designed around Java invokedynamic, meaning that less "magic" byte code will have to be generated. Meanwhile, I've heard that Clover has explicit Groovy support, although I don't know how up-to-date it is.ShareFollowansweredJun 20, 2012 at 18:13Peter NiederwieserPeter Niederwieser123k2222 gold badges324324 silver badges259259 bronze badgesAdd a comment|
I have a Groovy class with a single static method:class ResponseUtil { static String FormatBigDecimalForUI (BigDecimal value){ (value == null || value <= 0) ? '' : roundHalfEven(value) } }It has a test case or few:@Test void shouldFormatValidValue () { assert '1.8' == ResponseUtil.FormatBigDecimalForUI(new BigDecimal(1.7992311)) assert '0.9' == ResponseUtil.FormatBigDecimalForUI(new BigDecimal(0.872342)) } @Test void shouldFormatMissingValue () { assert '' == ResponseUtil.FormatBigDecimalForUI(null) } @Test void shouldFormatInvalidValue () { assert '' == ResponseUtil.FormatBigDecimalForUI(new BigDecimal(0)) assert '' == ResponseUtil.FormatBigDecimalForUI(new BigDecimal(0.0)) assert '' == ResponseUtil.FormatBigDecimalForUI(new BigDecimal(-1.0)) }This results in6/12branches covered according to Sonar/JaCoCo:So I've changed the code to be more...verbose. I don't think the original code is "too clever" or anything like that, but I made it more explicit and clearer. So, here it is:static String FormatBigDecimalForUI (BigDecimal value) { if (value == null) { '' } else if (value <= 0) { '' } else { roundHalfEven(value) } }And now, without having changed anything else, Sonar/JaCoCo report it to be fully covered:Why is this the case?
Sonar + JaCoco not counting Groovy code as covered
As Mark said, you just have to use theWS APIto query the database. What you're missing is probably the name of the metrics related to integration tests (they are not documented yet on ourmetric definitions page). So here they are:it_coverageit_lines_to_coverit_uncovered_linesit_line_coverageit_coverage_line_hits_datait_conditions_to_coverit_uncovered_conditionsit_branch_coverageit_conditions_by_lineShareFollowansweredApr 1, 2012 at 13:45Fabrice - SonarSource TeamFabrice - SonarSource Team26.6k33 gold badges6363 silver badges5858 bronze badgesAdd a comment|
I am developing an application using sonarJava web service client API. I would like to get Integration Test code coverage per class from theJaCoCo plugin. Can this be done with this API?
Get JaCoCo Integration Coverage from Sonar
I had the same issue. I fixed by importing only the function.For tsimport { saveAs } from 'file-saver'; saveAs(blob, doc.docName);For jsconst { saveAs } = require('file-saver');I think that this sonar issue is because the browsers do not natively support interface.ShareFolloweditedAug 24, 2022 at 16:31answeredAug 18, 2022 at 7:58jhonnyfcjhonnyfc18111 silver badge44 bronze badges1It works! The warning disappears!–EvanAug 18, 2023 at 1:30Add a comment|
Working on filesaver, while running SONAR QUBE it shows " 'fileSaver' is deprecated. use{ autoBom: false }as the third argument "this.http.get(`getTemplate/${doc.id}`, { responseType: 'blob' }).subscribe( (data: any) => { fileSaver.saveAs(new Blob([data], { type: this.fileType }), doc.docName)error :- 'fileSaver' is deprecated. use{ autoBom: false }as the third argumentEven if I use autobom:false it still shows the sameHere is the code for autobomthis.http.get(`getDocument/${doc.docId}`, { responseType: 'blob' }).subscribe( (data: any) => { var blob = new Blob([data], { type: this.fileType }); fileSaver.saveAs(blob, doc.docName,false);'saveAs' is deprecated. use{ autoBom: false }as the third argumentWhy is this an issue?'fileSaver' is deprecated. use{ autoBom: false }as the third argument Why is this an issue?
File saver is deprecated. How to resolve this issue from SonarQube
You have to setXMLConstants.ACCESS_EXTERNAL_DTDandXMLConstants.ACCESS_EXTERNAL_SCHEMAto "".Below code will not give any violation with SonarLint and SonarQube.private Validator validator; ... SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); Schema schema = factory.newSchema(new File(getResource(path))); validator = schema.newValidator(); validator.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, ""); validator.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");Then, Block external entities where you are validating it. For example, If you are using STAX parser. Then setXMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIESandXMLInputFactory.SUPPORT_DTDtoFalse.XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE); factory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE); validator.validate(new StAXSource(factory.createXMLStreamReader(inputStream)));If you are using sonarLint then clean your caches by deleting target folder of the project.For more info:https://rules.sonarsource.com/java/RSPEC-2755ShareFolloweditedJan 28, 2021 at 6:57answeredJan 27, 2021 at 15:49Krishna Kumar SinghKrishna Kumar Singh16611 silver badge1616 bronze badgesAdd a comment|
I am using javax.xml.validation.Validator to validate my xml as belowprivate final Validator validator; ... SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); factory.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, ""); factory.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); Schema schema = factory.newSchema(new File(getResource(path))); validator = schema.newValidator(); validator.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, ""); validator.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");Any idea why sonar says this code is noncompliant?
Sonar: Disable XML external entity (XXE) processing
Using of sonar-scanner is suggested when You are using a build tool that does not have a specific sonar-scanner plugin. If You are using maven You should use the maven sonar scanner. Also some CI servers has sonar plugins which can be used to centralize SonarQube server connection configurations. (but a Sonar scanner has to be used this way and You should use Your build tools plugin in this case also.)Sonarscanner is responsible for analyzing the code and sending the result of the analysis to SonarQube server. And SonarQube will do a final processing on these results. (keeping history of the analysis and metrics are server's responsibility.)You can find the details in the following links.https://docs.sonarqube.org/display/SCANhttps://docs.sonarqube.org/latest/analysis/background-tasks/https://docs.sonarqube.org/latest/analysis/overview/ShareFollowansweredMar 26, 2019 at 16:42miskendermiskender7,67022 gold badges1919 silver badges2323 bronze badgesAdd a comment|
I would like to understand, if it's better to use thesonar-scanner, or your build tool's plugin for this? For example, both Maven and Gradle have plugins for Sonar. From what I understand, thesonar-scanneris an alternative to using it through your build tool. How does this help? Which approach is better? Doessonar-scanneronly publish to Sonarqube, or is it also responsible for other things like collecting/merging metrics and reports? Are there any articles that clarify these differences?
When to use sonar-scanner over your build tool's plugin for Sonarqube?
SonarCloud does not support Groovy analysis.The project you found is an old one, not analyzed for more than a year. It's a left-over from the former version of the service (called SonarQube.com at that time) that had some sort of support for Groovy.ShareFollowansweredJan 17, 2018 at 15:36Fabrice - SonarSource TeamFabrice - SonarSource Team26.6k33 gold badges6363 silver badges5858 bronze badges2Is Groovy on the roadmap?–pdoubleJan 18, 2018 at 17:571It's not for the moment.–Fabrice - SonarSource TeamJan 19, 2018 at 20:50Add a comment|
I cannot get SonarQube to scan my .groovy files on sonarcloud.io. I added the following to my build.gradle:sonarqube { properties { property 'sonar.host.url', 'https://sonarcloud.io' property 'sonar.organization', System.getenv('SONARQUBE_ORG') property 'sonar.login', System.getenv('SONARQUBE_LOGIN') property 'sonar.inclusions', '**/*.groovy,**/*.java' } }It reports indexing 5 files, but there are 0 lines of code in sonarcloud.io.My source is in the 'sonarqube' branch athereMy sonar cloud project is athereHere is a project that is scanning groovy, but I can't find the source code to determine how it is configured:Link
Does sonarcloud.io support groovy?
Though the implementation is correct, you might want to use a method reference instead :List<String> emps = empList.stream().map(Employee::getEmpName).collect(Collectors.toList());which is what the rulesquid:S1612expects.Method/constructor references are more compact and readable than using lambdas, and are therefore preferred.ShareFolloweditedNov 4, 2017 at 12:41answeredNov 4, 2017 at 12:07NamanNaman29.4k2727 gold badges225225 silver badges361361 bronze badges23but this is only applicable to static methods–dragonalvaroMar 5, 2018 at 10:35@dragonalvaro No, it works for any method.–Dávid HorváthSep 16, 2021 at 14:42Add a comment|
public class FetchVarableList { public static void main(String[] args) { Employee e1 = new Employee(1, "Abi", "Fin", 2000); Employee e2 = new Employee(2, "Chandu", "OPs", 5000); Employee e3 = new Employee(3, "mahesh", "HR", 8000); Employee e4 = new Employee(4, "Suresh", "Main", 1000); List<Employee> empList = new ArrayList<>(); empList.add(e1); empList.add(e2); empList.add(e3); empList.add(e4); List<String> emps = empList.stream().map(p -> p.getEmpName()) .collect(Collectors.toList()); emps.forEach(System.out::println); } }This about programming is working fine, but in that I have a sonar violation, how to change to lambda expression? I need some help
Sonar violation squid:S1612
Thesquid:UnusedPrivateMethodraises this issue, but itsdocumentationmentions:This rule doesn't raise any issue on annotated methods.So a simple workaround is to annotate the constructor with@SuppressWarnings("unused")public enum MyEnum { GOOD("good"), BAD("bad"), BETTER("better"); @SuppressWarnings("unused") private MyEnum(String value){ // ... } }ShareFollowansweredJan 21, 2019 at 11:03neXusneXus2,06544 gold badges2929 silver badges5757 bronze badges21This is the right solution, reg. the Java docs,another possibility is to mark issue as wont fix or something similar, I know its possible somewhere in SonarQ ui–xxxvodnikxxxJan 21, 2019 at 11:51It is indeed possible in the SonarQube UI. However but due to some company policy our developers (including me) don't have the required privileges to do that. This annotation is the next best thing.–neXusJan 21, 2019 at 12:10Add a comment|
SonarQube is throwing an error for my below code.I have an enum that accepts String. I want users to use thevalueOfmethod of my enum. Example:MyEnum.valueOf("good"). Hence I had to create a constructor which takes String as a parameter. But SonarQube is not letting me get away with it.It is currently throwing me an error asking me to remove the unused private constructor. Removing the constructor is not possible as it will raise a compilation error for not having a constructor with String as parameter.How can I make SonarQube ignore this or is there any alternative solution for my coding?Below is my code.public enum MyEnum { GOOD("good"), BAD("bad"), BETTER("better"); private MyEnum(String value){//asks me to remove this. But I can't do that } }
SonarQube UnusedPrivate constructor
I think the title of your question is confusing. This is not about SonarLint startup, but about SonarLint "update all bindings" feature.I have created a ticket that we will try to fix in the next version:https://jira.sonarsource.com/browse/SLE-200Note that not binding Eclipse project to the correct SonarQube project/module will prevent correct match between local and remote issues. It means issues flagged as "won't fix" or "false positive" on SonarQube side will not be muted in Eclipse.You said mapping many projects is tedious. What about the auto-bind feature? If it is failing to correctly guess binding between local and remote projects, I encourage you to open a thread on theSonarLint Google groupto so that we can investigate the reason.
In our case we had a parent project (trunk) where all plug-ins where sub-projects and we want all the sub projects to have the same rules. In order to make maintenance easier we thought we could bind all plug-in projects in eclipse to trunk (so we can just batch update them etc.). The problem here is that for some reason it always loads all sub projects for each project. 1) they are always the same 2) there is not more information in the call of the sub-project that the former call did not get.If we bind each project to the real correct project in SonarLint that is a lot of effort. (we have hundreds of plug-ins.) Still, for our 100+ plug-in projects that we have in Eclipse SonarLint takes some minutes to get all the info from the server.How can we make SonarLint faster? Is there a recommended way? Can we help to improve the logic for this scenario?
How can we make SonarLint startup faster in Eclipse with lots of projects?
You setup the options sonar.sources=src but your code is in SonarTest/src.Change to sonar.sources=SonarTest\srcAccess hereto see the list of sonar paramaters.
I get the following error when I try to execute SonarQube Scanner as a part of Jenkins build:Other configurations as follow:The project in SVN:The directory as follow:
Error during SonarQube Scanner execution.The folder 'src' does not exist for 'SonarTest'
localhost:9000is the default sonar qube url, regardingthe official documentation. You'll have to set the correct url in yourpom.xml(assuming you're ussing Maven, which seems to be the case).if you set thesonar.host.urlproperty in yourpom.xmlorsettings.xmlwith your correct sonar qube url (ie: 192.168.0.9 for example), it should work as expected<properties> <!-- Optional URL to server. Default value is http://localhost:9000 --> <sonar.host.url> http://myserver:9000 </sonar.host.url> </properties>
I am currently trying to get my Jenkins/Sonar integration to work.Here is what I have: Jenkins is working Sonarqube is working (reachable from webinterface) Ports are openHowever! I tried all possible settings, Jenkins insists that Sonarqube is Localhost:9000, no matter what I tell it (and even if, this should work too). This leads to following:and ultimately lets the build fail. What could I try to rectify this?
Jenkins can't reach Sonarqube
You can use the rest api provided by Sonar.Step 1. Create gatedef result = ["curl", "--user", auth, "-X", "POST", "-H", "Content-Type: application/json", "-d", "{'name':'" + qualityGateName + "'}", "https://yoursonarserver/api/qualitygates/create"].execute().textStep 2 Bind project into the gate["curl", "--user", auth, "-X", "POST", "-H", "Content-Type: application/json", "-d", "{'gateId':'"+qualityGateId+"','projectId':'"+projectId+"'}", "https://yoursonarserver/qualitygates/select"].execute().textAbout how to get the projectId and qualityGateId, you can use the following two apisGet project IDString result = ["curl", "--user", auth , "-X", "GET", "-H", "Accept: application/json", "https://yoursonarserver/api/projects/index", "-d", "search=" + projectName ].execute().textGet Quality gate iddef result = ["curl", "--user", auth, "-X", "GET", "-H", "Accept: application/json", "https://yoursonarserver/api/qualitygates/list"].execute().textThe above two apis will get a list of ids, so you need parse them based the project name.Br,Tim
We use jenkins, sonarqube 5.5, maven and git. When developers create a new git branch and push it, jenkins analyses the branch too, so the developers can fix everything before merging. To avoid this development branch analysis mixing up with the master branch analysis, jenkins passes the branch name into the analysis. The causes sonarqube to create a new project for each branch. So far that's ok.But recently we switched from one default quality gate for all projects to different quality gates for projects under active development and projects which are just in maintenance.So how can we tell sonar when creating an new project for a new branch which quality gate to use? Until some versions ago, there was a sonar.qualitygate property which could be set. But now this is deprecated. So what's the new way to define the proper quality gate for a newly created project?
How to set non-default quality gate for new sonar projects
There are minimum versions for the SonarQube server and for each analyzer plugin.Your SonarQube server should be ok, but you need to install a more recent Java analyzer plugin (version >= 3.8) in the SonarQube server.More information about the Java analyzer:https://docs.sonarqube.org/display/PLUG/SonarJava
When I try to connect to SonarQube server, an error is occured saying:The following plugins do not meet the required minimum versions, please upgrade them: java (installed: 3.4, minimum: 3.8).But as of the SonarLinthttp://www.sonarlint.org/eclipse/: and "June 3, 2016 - We released version 2.1.0 of SonarLint for Eclipse with extended support of SonarQube 4.5.4+ ",the latest version is 2.1 which I have already installed. My SonarQube server is 4.5.4. Have I missed something here or any solution please.
SonarLint Eclipse plugin version error
We have configuredJenkinsto launch the unit tests and the results are “forwarded” to Sonar to be interpreted as a post build action
I'm just starting to mess about with continous integration. Therefore I wanted to set up Jenkins as also Sonarqube. While reading manuals/docs and tutorials I got a little bit confused.For both systems, there are descriptions about how to set up unit test runners. So where should unit tests ideally be run? In Jenkins or in Sonarqube or in both systems? Where does it belong in theory/best practice?
Jenkins and Sonarqube - where to run unit tests
you need to use the start cmd command,for example:start YourBatch.batThis will open a new CMD window and Jenkins won't wait for result.Bare in mindthat if you get an exit code different than 0, it won't fail the build.
I have a Jenkins job which is building /packaging/ deploying .NET project. I use "Clean Before checkout" git property for each build.Finally, I'm executing a batch file. This batch file scanning sonar Qube MSBuild, c# analysis and update the code quality results. But It is taking a long time and I don't want to increment Jenkins job's total execution time from 1 minute to 5 minutes. Developers are thinking so the deployment is taking a long time and not finished yet.I want to run this batch file independent from the Jenkins job and don't want to see the console output in Jenkins. How could I do this without creating a new Jenkins job for each Jenkins project (upstream/downstream projects)
How to trigger a batch file in Jenkins without waiting for batch execution results and status
SonarQube 5.5 will be officially released at the end of April / early beginning of May.
As per SQ 5.5 release notes, it seems “Views” plugin would be deprecated and replaced by “Governance” plugin. Please refer to following ticket for more details :https://jira.sonarsource.com/browse/SONAR-7428What would be the support option for anyone using "views" plugin with community edition?SQ 5.5 release date was 22 April 2016 but it has not been released as of 25 April 2016. What is the new release date for SQ 5.5 release?
SonarQube 5.5 and Views plugin
Javascript plugin provides "NOSONAR" mechanism since 2.2 version (seehttps://jira.sonarsource.com/browse/SONARJS-294).And since v2.6 there is improvement of this rule "Functions should not have too many lines" to ignore AMD pattern (seehttps://jira.sonarsource.com/browse/SONARJS-404)So update of Javascript plugin should work.
module.exports = function (grunt) { // NOSONAR grunt.initConfig({Unfortunately Sonar detects a false positive when it comes to certain functions like this one (or AMD module definitions).The rule in question is: "Functions should not have too many lines"The // NOSONAR or //NOSONAR approach does not work for some reason.Can somebody provide me with a valid work-around? This rule cannot be deactivated on a file-to-file bases since it is triggered for all AMD modules as well.SonarQube version: 3.7.4 - Sonar-Runner: 2.4Thank you!
How to surpress SonarQube JavaScript issues
The incremental mode will analyze only changed files since latest "regular" analysis on server. So in your case you should first run a normal (now called "publish") analysis:mvn sonar:sonar -Dsonar.java.coveragePlugin=jacocoThen your can use the incremental mode:mvn sonar:sonar -Dsonar.analysis.mode=incremental -Dsonar.java.coveragePlugin=jacoco
I've trying to fiddle with SonarQube and now I'm learning about theincrementalmode. In my understanding it should analyze only the changed files.So my first test is just to run SonarQube twice on our project without any change. I run SonarQube (5.1.2) installed locally on windows 7 64-bit machine with SSD drive and I7 CPU. We use java 1.7 and Maven 3.3.3. Our project is fairly big (~570 modules) of maven, most of them are java code. After I run aprepare-agentofjacocoalong with my unit tests I understand that its time to runsonar:sonarand create a report.So what I try is:mvn sonar:sonar -Dsonar.analysis.mode=incremental -Dsonar.host.url=http://localhost:9000 -Dsonar.java.coveragePlugin=jacocoThis runs for 20 minutes. Ok, now I run the same command again without doing any change and it still runs the same 20 minutesSo my question is - whether someone can explain me how to use the incremental mode correctly? I have a hard time understanding what I'm doing wrong, in my understanding the second run has to be much faster, otherwise I don't see any advantage over the preview mode here.Thanks Mark
How to use incremental mode in SonarQube?
Turns out that the MsBuild runner looks at the full path of your project to see if it's a Test project. so if your Build agent name or Build definition name or any folder leading up to your project file has the word "test" in it, all projects will be considered a test.As discussed offline, in your case it was the Build Definition name. Renaming it to not be named "SonarQubeTestBuild" solved the issue.
I have installed SonarQube on my local development machine by following installation guide:SonarQube Installation Guide for Existing TFS Environment.pdf.The build is succesfull. The project is added to the dashboard. But there was only testcoverage data.I have 4 projects in my solution, 2 of them are unittest projects. The build for SonarQube logs that there are found 4 test projects and no product projects:SonarQube Analysis Summary Analysis succeeded for SonarQube project "ConsoleApplication", version 1.0 (Analysis results) Product projects: 0, test projects: 4 Invalid projects: 0, skipped projects: 0, excluded projects: 0As far as I can see and have checked I have followed the manual on every point. Is there any setting that I have missed and results in zero product projects?
TFS with SonarQube, no product projects, only test projects
For the X-Frame option, this has been fixed in SQ 5.1 and you can actually verify this on ourNemo instance.For the CSRF protection, we have an open ticket about this:SONAR-5040. Note that when an XSS vulnerability is discovered, we always fix it in the upcoming version as well as in the latest LTS version (currently 4.5.x).
I am running aSonarqube 4.2instance on a linux box. Since in our system we have a central portal page from where we navigate to all the child pages, I need to have sonarqube inside a frame. When I have an href, Sonarqube is denying which I guess is due toX-Frame optionsset asSAMEORIGIN. Any clue how we can modify this?Also I need to provideCSRFprotection in sonarqube. For jenkins, it comes with a built in option to enableCSRFprotection. Does sonarqube have anything similar?Thanks in advance for all the inputs.
Sonarqube 4.2 X-Frame options and Cross site scripting vulnerabilities
Looks like that's not possible...From Sonatype blog postConfiguring Plugin Goals in Maven 3:The latest Maven release finally allows plugin users to configure collections or arrays from the command line via comma-separated strings.Plugin authors that wish to enable CLI-based configuration of arrays/collections just need to add the expression tag to their parameter annotation.But in thecode of the plugin:/** * The format of the report. (supports 'html' or 'xml'. defaults to 'html') * * @parameter expression="${cobertura.report.format}" * @deprecated */ private String format; /** * The format of the report. (can be 'html' and/or 'xml'. defaults to 'html') * * @parameter */ private String[] formats = new String[] { "html" };As you can seeformatsdoesn't haveexpressiontag (unlikeformat) so it cannot be configured from the command line.UpdateI just realised that I answered wrong question :) Question I answered is "How can I generate multiple different report types from the Maven command lineusing 'formats' option?". But original question was "How can I generate multiple different report types from the Maven command line?"Actually there is a simple workaround - run maven twice (second time withoutclean), like this:mvn clean cobertura:cobertura -Dcobertura.report.format=xml mvn cobertura:cobertura -Dcobertura.report.format=html
With Maven I can generate multiple different types of code coverage reports with Cobertura by changing the reporting section of my POM, ala ...<plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>cobertura-maven-plugin</artifactId> <configuration> <formats> <format>html</format> <format>xml</format> </formats> </configuration> </plugin>Alternately, I can generate a single type of report from the Maven command line, ala ...mvn clean cobertura:cobertura -Dcobertura.report.format=xmlHow can I generate multiple different report types from the Maven command line?Apparently, I can only do one. ... I've tried this below, and it does not work!mvn clean cobertura:cobertura -Dcobertura.report.formats=xml,html(NOTE: The above property uses "formats" versus "format". The abovealwayscreates the default HTML report without seeing the two specified formats. I'm using Maven 3.2.3 and Cobertura plugin version 2.0.3.)Please help, my Googol Fu is failing. ... Anyone know if this is possible or not?
Generating multiple Cobertura report formats via Maven command line
Since SonarQube 4.0 (or if you have an older version, using the Switch Off Violations plugin), you candefine a patternto ignore this rule on classes ending inTest:Connect to SonarQube with a global administrator accountGo to: Administration > Configuration > General Settings > Analysis ScopeFind section: Issues > Ignore Issues on Multiple CriteriaAdd an entry with:Rule Key Pattern:squid:S00112File Path Pattern:**/*Test.javaPlease also note that recent versions of SonarJava (at least since 3.1) only apply a specific set of rules to test classes.
I agree that it's generally a bad idea to declare "throws Exception" in normal Java code.However, I think it is a good idea to do this in unit tests. It simplifies the test method, but still results in any unexpected exceptions causing the test to fail.I'd like to see if it's practical or possible to make Sonar only report this issue for classes not ending in "Test". I'd rather not add overrides in the code, I'd prefer to make this happen entirely in the Sonar configuration, or in the properties sent through sonar-runner.Can anyone see a way to do this?
Make Sonar override "don't declare 'throws Exception'" only in unit test classes
I believe the rule is being fired because you are logging the simple toString() message from Exception e, rather than the full stack trace. Something likeLOG.error(SampleClass.class.getSimpleName() + ": " + e, e);would satisfy the rule.SonarQube has very good examples of compliant/non-compliant code with each rule definition. Expand the name of the rule, either in the issues or in Quality Profiles to see the examples.You can alter (some aspects) of the default quality profile by creating a profile of your own that inherits from "Sonar Way..." and then change rules. You'll need admin access to your SonarQube to do that, then navigate to Quality Profiles to get started.For example, our team decided that the particular issue you are looking at should not be Critical, given the number of times it occurs in our legacy code. We create our own profile inheriting from Sonar Way, and it is easy to lower the severity of this rule to Major. We have altered a number of rules, changing thresholds and/or regular expressions to better suit our needs. We haven't seen a need to write new rules, so I can't tell you how to do that, other than suggest checking the docs.
I'm new to SonarQube and Squid (and CheckStyle and FindBugs and PMD). I'm using SonarQube 4.1.1. and the default 'Sonar way with Findbugs' quality profile to evaluate some of my Java projects.In the result of my analysis I get a ton of the same critical issue from Squid:Exception handlers should provide some context and preserve the original exception When handling a caught exception, two mandatory informations should be either logged, or present in a rethrown exception:Some context to ease the reproduction of the issue.The original's exception, for its message and stack trace.In my code I use a logger, e.g.catch(Exception e) { LOG.error(SampleClass.class.getSimpleName() + ": " + e); }Why is this rule fired? The exception is logged. Is it, because I don't use a 'Logger' but a 'Log'?A second question I have is: Where can I see and change the Squid rules and maybe add a couple of my own? As far as I understand FindBug, CheckStyle and PMD I can write my own rules. Is this possible with Squid too?
How can I change a Squid rule in Sonar?
Well, you get all the required information in the blog post: the SQALE methodology is perfectly explained on theofficial SQALE website.The blog post even mentions that there's a Sonar plugin that implements the methodology: theSonar SQALE plugin.
We try to use Sonar to manage the software quality, like this page, we can get the technical debt.http://www.sonarqube.org/sqale-the-ultimate-quality-model-to-assess-technical-debt/My question is, how to define the debt to fix a violation, remove some duplicated code or a new test case. Is there any calculate algorithm?
How to calculate the technical debt?
From Freddy Mallet on the list:"... the problem doesn't come from the DB but come from the algorithm to identify all the package dependencies to cut. ... If you manage to cut this project in several modules, then your problem will vanish."I tested this theory by excluding a relatively large package, and sure enough it dropped dramatically. In theory the number of connections could grow quadratically with the number of packages, so this approach is probably as good as is possible with such a large codebase.
I maintain the build process for a large (> 500,000 LOC) Java project. I've just added a Sonar analysis step to the end of the nightly builds. But it takes over three hours to execute ... This isn't a severe problem (it happens overnight), but I'd like to know if I can speed it up (so that I could run it manually during work hours if desired).Any Sonar, Hudson, Maven or JDK options I can tweak that might improve the situation?[INFO] ------------- Analyzing Monolith [INFO] Selected quality profile : Sonar way, language=java [INFO] Configure maven plugins... [INFO] Sensor SquidSensor... [INFO] Java AST scan... [INFO] Java AST scan done: 103189 ms [INFO] Java bytecode scan... ... (snip) [INFO] Java bytecode scan done: 19159 ms [INFO] Squid extraction... [INFO] Package design analysis... ... (over three hour wait here) [INFO] Package design analysis done: 12000771 ms [INFO] Squid extraction done: 12277075 ms [INFO] Sensor SquidSensor done: 12404793 ms12 million milliseconds = 200 minutes. That's a long time! By comparison, the compile and test steps before the sonar step take less than 10 minutes. From what I can tell, the process is CPU-bound; a larger heap has no effect. Maybe it has to be this way because of the tangle / duplication analysis, I don't know. Of course, I know that splitting up the project is the best option! But that will take a fair amount of work; if I can tweak some configuration in the meantime, that would be nice.Any ideas?
How can I speed up Sonar's package design analysis?
For me, adding this to the Dockerfile was enough:ENV LANG=C.UTF-8 LC_ALL=C.UTF-8
I am running the sonar scanner for my project with (-Dsonar.sourceEncoding=UTF-8) but I am getting the following error.INFO: SonarQube Scanner 3.2.0.1227INFO: SonarQube server 8.9.7INFO: Default locale: "en_US", source code encoding: "UTF-8"WARN: SonarScanner will require Java 11 to run, starting in SonarQube 9.x...ERROR: Error during SonarQube Scanner executionERROR: Malformed input or input contains unmappable characters:src/main/html/images/T??cnica.jpgThe word has a tilde.I have tried to exclude the .jpg files and the folder where this file is located but I still get the same error. Any solution?Solution:Inside the Jenkins container run the following commands to change the localeapt-get update && apt-get install -y locales sed -i '/es_ES.UTF-8/s/^# //g' /etc/locale.gen locale-gen update-locale LC_ALL="es_ES.UTF-8"
ERROR: Malformed input or input contains unmappable characters
This is a workaround if you are using Jenkins, that isn't perfect. It can be used to suppress a specific warning for an entire file (instead of just one function).In the Jenkins property file add something like:sonar.issue.ignore.multicriteria=e1 sonar.issue.ignore.multicriteria.e1.ruleKey=python:S107 sonar.issue.ignore.multicriteria.e1.resourceKey=path/to/file.pyWherepython:S107is the rulekey for a function having more than 7 parameters, andpath/to/file.pyis the file you want to suppress this specific rule for. Unfortunately it will supress it for the entire file, as opposed to the specific function.
In Python we can suppress all Sonarqube warnings at a particular line in the code by applying the# NOSONARcomment. This is not ideal. Is there a way to suppress a specific error, instead of supressing all errors?For example, you may have a function with two warnings:Function "foo" has 8 parameters, which is greater than the 7 authorized. Refactor this function to reduce its Cognitive Complexity from 17 to the 15 allowedHow can you suppress the first, but not the second?
Sonarqube How to supress a specific warning in Python using # NOSONAR
work arounds here for this as for as my research:There is an update to xccov-to-sonarqube-generic.sh script for Xcode 11+. Try using thishttps://github.com/SonarSource/sonar-scanning-examples/blob/master/swift-coverage/swift-coverage-example/xccov-to-sonarqube-generic.shUse Code Coverage Converter (cococo) utility to generate sonar's xml file format. Refer for more info:https://medium.com/monsterculture/cococo-code-coverage-converter-from-xcode-11-to-sonarqube-7f48cff97b9bAny shell script that is capable to convert Xocde 11+ *.xcresult file to sonar's xml file format
I am using following code to export test code coverage using Xcode11.4../xccov-to-sonarqube-generic.sh /DerivedData/MyApp-*/Logs/Test/*.xcresult/ > sonarqube-generic-coverage.xmlI am getting following errorThis version of Xcode does not support opening result bundles created with versions of Xcode and xcodebuild using the v1 APIKindly help me with the proper way.
Unable to export test result in Xcode 11.4
for changing watermark setting, you can use dynamic cluster update setting:https://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-update-settings.htmlfor watermark, something like this:curl -s -XPUT 'localhost:9200/_cluster/settings?pretty' -d ' { "persistent" : { "cluster.routing.allocation.disk.watermark.flood_stage" : "99%" } }'
I'm trying to run SonarQube on a server with ~2TB disk space, and only ~50G free space. When trying to use docker as in the official manual (nothing special), elasticsearch fails with a message about the read-only index. As far as I can get, this happens because it hits theflood_stagewatermark, which is set to 95% by default. I'm pretty sure that we can set this watermark (and all others) to non-percentage smaller values, but I can't seem to find the configuration file, which the embedded elasticsearch is using. I've tried/opt/sonarqube/conf/elasticsearch.yml(which did not exist, needed to create it) and/opt/sonarqube/elasticsearch/config/elasticsearch.yml, which contained the default elasticsearch configuration.Even when writing complete non-yml gibberish into these files, elasticsearch fails with the same error, so I'm pretty sure that these are not the files that are in use. I have also tried to search through the documentation, but it seems that the only hint it contains about this behaviour is "increase the disk space, and delete all indexes". So, what files should I use to configure embedded elasticsearch?UPD: We have ended up monkey-patching the/opt/sonarqube/elasticsearch/bin/elasticsearchstartup script to insert additional lines into the dynamically generated config (which is located in/opt/sonarqube/temp/conf/es/elasticsearch.ymlbtw). Not a clean solution, but this seems to be the simplest, considering how sonarqube generates the config dynamically
SonarQube: embedded elasticsearch configuration location
I was able to achieve my goal by using the web api after each scan, like example below :http://0.0.0.0:9099/api/issues/search?componentKeys=com.test&facets=owaspTop10&owaspTop10=a1,a2,a3,a4,a5,a6,a7,a8,a9,a10
Is it possible to keep a security report OWASP Top 10 after every scan, so i can identify the delta of OWASP vulnerabilities between two version ?Sonarqube GUI offer the security reports just for the last scanThanks for any advice
Sonarqube security reports : OWASP Top 10
Copied from theofficial documentation:Java bytecode is requiredAnalyzing a Java project without providing the Java bytecode produced byjavac(Android users: Jack doesn't provide the required.classfiles) and all project dependencies (jar files) is possible, but will result in an increased number of false negatives, i.e. legitimate issues will be missed by the analyzer.From SonarJava version 4.12 binary files are required for java projects with more than one java file. If not provided properly, analysis will fail with the messagePlease provide compiled classes of your project with sonar.java.binaries propertySeeJava Plugin and Bytecodefor how to provide the Java bytecode if you are not using Maven to run your analysis.As you see, the bytecode is required. If you don't feed the analyzer with the bytecode then built syntax/dependecy tree will miss some data, and you get more false negatives (issues which should be reported, but weren't).
I'm running SonarQube scanner on a java project. In the properties file there's a propertysonar.java.binaries=**/classesto specify classes location for the projects.The scan failed showing this error:ERROR: Error during SonarQube Scanner execution ERROR: Please provide compiled classes of your project with sonar.java.binaries propertywhen:I removed thesonar.java.binariespropertyI setsonar.java.binariesproperty tonullI set the property tosonar.java.binaries=**/classesbut in the project directories there was no classes dir or there were empty onesThe scan was completed successfully when:I set the propertysonar.java.binaries=**/classesand I created a classes folder putting into it a bogus fileblabla.classSo my question is: why are the classes required if the scanner is working also without them?
SonarQube Scanner: are binaries really needed?
ThePublish Quality Gatestep polls the SonarQube server until the background processing on the server has completed, and then posts the success/failure result to the Azure DevOps build summary page.If you can live without the SQ summary on the build summary page then you can just disable thePublish Quality Gatestep.To investigate why the step is taking so long you need to look at your SonarQube server. The docs onBackground Tasksdescribe how to look at the background processing to see how long each task is taking. There are also perf suggestions on theHardware RecommendationsandBenchmarkpages. If you are using the Enterprise edition you can increase the number ofcompute engine workers.
Publishing Quality Gate results take way too long. Right now, when I publish using the respective Azure DevOps task, I have to wait for at least 18min until the process finished. The project doesn't have a huge codebase (only 45k lines of code) and as far as I can see, the process itself doesn't load our Azure-based database as well. What could be the issue? Are there any ways of improving QG publishing performance?
SonarQube publish quality gate result takes far too long
you can return a new HashSet:@Override public Set<Class<?>> getClasses() { return new HashSet<>(resourceSet); }
This is my code so far:public class RestApplication extends Application { private final Set<Class<?>> resourceSet; public RestApplication() { this.resourceSet = new HashSet<Class<?>>(); resourceSet.add(PCardController.class); resourceSet.add(PricingController.class); resourceSet.add(TransactionFeedController.class); initializeMaps(); } @Override public Set<Class<?>> getClasses() { return resourceSet; // ... } // Added by edit! // ... } // Added by edit!SonarQube says that the return of a copy is a resource set.How can I do that?
SonarQube: Mutable members should not be stored or returned directly
It is recommended to use squid rules because they are supported bySonarLint.Unfortunately, there is no available a rules mapping which allows you to easily migrate from Checkstyle, FindBugs or PMD to SonarJava plugin (it was, but has been dropped:Where is dist.sonarsource.com content?).
I am using sonarqube community version 6.7.2, and, as I remember, SonarJava plugin was aiming to replace (mostly at least) Findbugs and PMD rules by squid ones. There was an information on rules from those providers when there was a proper squid rule replacement, but now I am unable to find it and some rules from findbugs, for example, are very similar to others I know from squid.Sonarqube recommends using only squid rules? Does those rules replaces well rules from PMD and Findbugs?
Sonarqube, PMD, findbugs and checkstyle
The current version of php analyser (SonarPhp 2.14 in SonarQube 7.3) doesnothave a feature (annotation based or not) for ignoring a specific rule.The php analyser only support one issue filtering, the NoSonarFilter that disable all rules at a specific line by using a comment containingNOSONAR.If a rule generate some false positives, or if you are facing a real life example where such filter is require, you can provide some feedback atcommunity.sonarsource.com
I know that in Java, we can ignore the a Sonarqube rule for specific method with annotations. For example...@SuppressWarnings("squid:S2078")With php, I have not narrowed down how to do this yet. Is there an equivalent example that ignoresonerule for a specific piece of code (not necessarily for a class/function, but it would be a start :) )
Sonarqube: Php equivalent annotation for ignoring sonarqube rule
you can use thewithSonarQubeEnv()plugin function to pull the values. You have to configure Jenkins with the Sonar variables you want it to use. You can find more info about that at the link below. Unfortunately, I can't seem to find documentation from Sonarqube what variables are being provided. You might want to run something likesh "env"within thewithSonarQubeEnvstanza to get an idea.https://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner+for+Jenkins#AnalyzingwithSonarQubeScannerforJenkins-AnalyzinginaJenkinspipeline
How to get sonar environment variables like sonar host, sonar project key or sonar workspace in order to use them in email with Jenkins plugin: Editable Email Notification.any help or idea ?
Jenkins : How to get sonar environment variables
Take a look atExclusions, which allow you to exclude files fromconsideration altogetherissuescoverageduplications
If I specify<SonarQubeTestProject>true</SonarQubeTestProject>it will exclude the project from not just code coverage but also code smell and duplicate detection.Is there a way to just exclude from code coverage but scan for every other aspects?
Sonarqube exclude code coverage for tests but include in code smell and duplicate detection
There are no rules in the SonarJava plugin that validate JavaDoc parameter names. Searching forall available Java rules, there are only three that are directly related to JavaDoc:Deprecated elements should have both the annotation and the Javadoc tagPublic types, methods and fields (API) should be documented with JavadocPackages should have a javadoc file 'package-info.java'However, if you install theCheckstyle plugin, you get some more Javadoc rules that may be close enough to what you are looking for. Here are some of theirJavaDoc checks:JavadocMethod: Checks the Javadoc of a method or constructor.JavadocPackage: Checks that all packages have a package documentation.JavadocParagraph: Checks Javadoc paragraphs.JavadocStyle: Custom Checkstyle Check to validate Javadoc.JavadocTagContinuationIndentation: Checks the indentation of the continuation lines in at-clauses.JavadocType: Checks the Javadoc of a type.JavadocVariable: Checks that a variable has Javadoc comment.
I found a rule that makes sure JavaDoc's exist for public methods -> "Public types, methods and fields (API) should be documented with Javadoc", however, it doesn't appear to validate the param names are correct. For example, the JavaDoc below should fail because 'badName' does not match 'aParam'. Is there another rule I can use to validate JavaDoc's are documented correctly?/** * @param badName String */ public void myMethod(String aParam) {}
Is there a SonarQube rule to validate JavaDoc's?
If you are using TeamCity JaCoCo integration for Gradle runner the coverage should be automatically. Make sure you've provided "Binaries location:" in the SonarQube Runner. In this case the build log will contain such lines:# before SonarQube start: -Dsonar.java.coveragePlugin=jacoco -Dsonar.jacoco.reportPath=/.../buildAgent/temp/buildTmp/JACOCO8457480821230827929coverage/jacoco.exec # while SonarQube is executed: Sensor JaCoCoSensor Analysing /.../buildAgent/temp/buildTmp/JACOCO8457480821230827929coverage/jacoco.execIn case you want to use JaCoCo plugin in your Gradle script you should manually set coverage type and data location in the SonarQube Runner step-Dsonar.java.coveragePlugin=jacoco -Dsonar.jacoco.reportPaths=%system.teamcity.build.checkoutDir%/build/jacoco/jacocoTest.execSo try to add "sonar.java.coveragePlugin" property
I have a gradle project with some codes insrc/main/javaand some unit tests insrc/test/javaBelow is snippet frombuild.gradleapply plugin: "jacoco" sourceSets { main { java { srcDir 'src/main/java' } } } test { jacoco { append = false destinationFile = file("$buildDir/jacoco/jacocoTest.exec") classDumpDir = file("$buildDir/jacoco/classpathdumps") } } jacoco { toolVersion = "0.7.8" } jacocoTestReport { reports { xml.enabled false csv.enabled false html.destination "${buildDir}/reports/jacoco/jacocoHtml" } }On TeamCity, I have 2 steps, first is Gradle step with commandgradle clean jacocoTestReport buildand second step isSonarQube runnerwith the following parameters:-Dsonar.sources=%system.teamcity.build.checkoutDir%/src -Dsonar.java.binaries=%system.teamcity.build.checkoutDir%/build/classes -Dsonar.branch.name=%teamcity.build.branch% -Dsonar.jacoco.reportPaths=%system.teamcity.build.checkoutDir%/build/jacoco/jacocoTest.execHowever, on SonarQube dashboard, my project still shows to have0% Coverage. Please advise me if I feedjacococoverage report correctly to SonarQube (Version 6.7)
Feed jacoco coverage report to SonarQube using TeamCity but it shows 0% coverage
No, currently there is possibility to do that from the user interface. Not even the REST api, provides such functionality.From theAPI-docs:Comma-separated list of coding rule keys. Format is <repository>:<rule>This does not allow any special syntax for to specifically exclude a rule.However these two suggestions might help:Query for all rules, except the one you want to exclude. This will be a quite long query (lots of clicks to do...), but should work.Remove that rule from the quality profile. The rule will not be active in the next analysis and the issues won't be visible anymore (but this means not visible to youand all other users).
In the web UI of SonarQube, you can filter issues based on several criteria. But it seems none of them can be negated.I like to find out allcriticalissues, that arenotrulexyz. I currently see from the web UI only the possibility to select what I like to see, not what I not want to see.Is there any way to create such a query?
Filter issues in sonarqube by ignoring a rule
I found the answer.You need only use the LDAP Reverse Code between the search pattern member={dn}# Nested Group Search ldap.group.request=(&(objectClass=group)(member:1.2.840.113556.1.4.1941:={dn}))
we use Sonarqube 6.2 with the LDAP Plugin 2.1.0.507. We have a connection to our Active Diretory. Normal user authentication and group mapping is working. But we have problems with nested groups.I try to use the specificy LDAP memberOf Filter (memberof:1.2.840.113556.1.4.1941:) but unfortunally it is not working.QuestionsIs the LDAP Plugin able to handle nested group ?If yes, what kind of changes are necessary in the filter settings ?Attached you find my LDAP filter sonar.propertiesldap.user.request=(&(objectClass=user)(sAMAccountName={login})) ldap.group.request=(&(objectClass=group)(member=memberof:1.2.840.113556.1.4.1941:={dn}))I hope this are enough informations.Best RegardsAdam
SonarQube LDAP Plugin Active Directory nested groups
You are right that this is a false positive. However such complex logic doesn't belong to the finally block, and if possible should be extracted to aptly named cleanup method. This will not only shutdown the warning, but also improve readability of your code.
I know, jump statements in finally block should not be used. In this simple example 'break' is used to break the 'switch'. SonarQube (5.6.3) with sonar-java 4.5.0.8398 reports an issue on:"Jump statements should not occur in "finally" blocks (squid:S1143)"public static void breakInFinallyIssue(){ int a = 0; try{ a = 1 / 0; }catch(Exception x){ System.out.println("div by zero"); } finally{ switch (a) { case 0: //do something break; default: break; } //do something more } }Is this a known FP/bug?
SonarQube, jump statements in finally block (squid:S1143)
Having a closer look to the console, you'll see the following message :You must install a plugin that supports the language 'php'.So all you need to do is to install the SonarPHP plugin:https://docs.sonarqube.org/display/PLUG/SonarPHP
Trying to setupSonarqubefor PHP code base for codecoverage analysis. I have modified the sonar-scanner.properties file with the following configuration.Path = sonar-scanner-2.8\conf\sonar-scanner.properties sonar.projectKey=PhpProject sonar.projectName=PhpProject sonar.language=php sonar.sources=C:/Users/Hameetha/Downloads/SonarSource-sonar-examples-4.5-21-gbb6c0f9/SonarSource-sonar-examples-bb6c0f9/projects/languages/php/php-sonar-runner-unit-tests sonar.scm.provide=sonarphphowever when running the sonar-scanner the following error msg is shown.
How to configure Sonarqube for PHP projects?
Quality gates build step can only come underPOST build actions.So try to add post build action of Quality Gates. And make sure you are giving a project key.Project Key can be taken note of from sonar server console.This should solve the error.
I have a Jenkins jobs for sonar analysis. When I try to add build step for Quality Gates (in order to mark a failure if new bugs), I get this error:JSONObject["projectKey"] not found.Can someone help?
Jenkins sonar quality gates issue
The message is clear enough and you understood it well: when you want to connect SonarLint to a SonarQube server, there are some constraints on the language plugins that are installed on this server.In your case, the version of the SonarQube Java plugin is 3.7 whereas only versions above 3.8 are supported in the connected mode.If you don't have administration permissions, there's nothing you can do about it. You have to stay in the default mode - i.e. no connection to the server, until the SonarQube instance gets updated.
I am trying to run Solar Lint with Intellij, when I configure the SonarQube server in the plug-in and "Test Connection"I keep getting the following error message:The following plugins do not meet the required minimum versions, please upgrade them: java (installed: 3.7, minimum: 3.8)I do not fully understand what this means and I would really appreciate any help on this.P.S. I cannot upgrade the Java Plugin on the sonar server if that is the only solution to this problem because I have no access to the server administration capabilities.
How to integrate SonarLint with Intellij
SonarLint and SonarQube are 2 different products:You want very fast feedback on the code you are working on to make sure you don't inject issues => SonarLint analyses the files as you open them to write or review codeYou want a 360° vision of the quality of your code => SonarQube analyses all the files of your projectThe "connected mode" is the bridge between the 2 worlds, and its development is still underway. For instance, we plan to make it possible to see inside SonarLint all the issues found on the project by SonarQube (see and vote forSLE-54).
I'm evaluating SonarQube 5.4 with SonarLint eclipse plugin.SonarQube as well as the plugin are set up and are running. But now I'm pretty confused how SonarLint is supposed to run in 'connected mode':SonarLint is connected with SonarQube and is bound to the corresponding project. But some issues are only shown in SonarQube. It was my understanding SonarLint should be able to identify issues likeMalicious code vulnerability - May expose internal representation by incorporating reference to mutable object. But it does not. SonarQube does.When analysing a single file with SonarLint, there are a lot of debug messages in the SonarLint Console likeClass not found in resource cache : org/company/project/CommonSuperClass. But even worse:Class not found in resource cache : java/lang/Class. Is it supposed to do that?We are specifically interested in highlighting the issues introduced by developer. SonarQube is connected our repo and does a nice job inblamingthe committer. But it seems there is no way of showingmy own issuesin sonarlint.I'd like to run the SonarLint analysis at a time of my choice, so I decided to deactivated "Run SonarLint automatically". But it seems I can only analyze files manually, not packages or projects. Am I missing something again? I do not want to click on every one of my ~2000 files and analyze it by hand.
Analyse complete project at once with SonarLint - Analysis file by file yields incomplete results
SonarQube 4.x does support parallel analysis of different projects, but not parallel analysis of the same project. This is a technical constraint to avoid conflicts when persisting analysis into the shared database.SonarQube 5.2 introduces a major architecture change. Analyzers (launched by your Hudson job) are no more connected to database. They generate and send to server a report that contains only raw data, basically sources and issues. Computation of measures, validation of Quality gate and persistence are done asynchronously on server. In your case that allows analyzers to be executed in parallel, even on the same project, but they can't directly verify Quality gate. For that you should implement a kind of listener on web services to get the gate status when report is processed. Seehttp://docs.sonarqube.org/display/SONAR/Breaking+the+CI+Buildfor more details. Note also that version 2 of the build breaker plugin implements this solution directly in the analyzer (seehttps://github.com/SonarQubeCommunity/sonar-build-breaker)
SonarQube does not support parallel execution as parallel execution is failing with:Caused by: org.sonar.api.utils.SonarException: The project is already been analysingI am usingSonarQube v4.3.3for code inspection.Now my hudson jobs are running in parallel and due to this restriction I am not able to add sonar analysis to my Hudson job.Please suggest how can I use SonarQube with hudson in a continuous pipeline using SonarQube.
SonarQube does not support parallel execution - How to use in continuous pipeline
You're observing this behaviour becauseCoverage on new codecurrently identifies new code based on the date of the previous analysis (and not the commit date of the code previously analyzed), seeSONAR-7085.For your scenario to work you have to force a past date for the analysis of the old code, using-Dsonar.projectDate. Good article on this right here:Sonar Time Machine : replaying the past.
I am trying to do Sonar analysis with the unit tests code coverage on new code. When I do code coverage analysis with cobertura and do Sonar analysis the overall code coverage of the code is displayed correctly, however the code coverage of new code is not displayed.Settings:scm = Gitsonar.scm.disabled = falseI did followingchecked out earlier version of source codeset Sonar project version to 1.0created Cobertura report (xml file)executed analysis and checked that the analysis was uploaded, the overal code coverage by unit tests was displayed correctlychecked out latest version of source codeset Sonar project version to 2.0executed analysis and checked that the analysis was uploaded, the overal code coverage by unit tests was displayed correctlyThe overall code coverage of the code by unit tests got increased as I have implemented some unit tests on a code that was changed. TheOn New Codeitem in the widget however stays hidden and the code coverage of new code is not displayed.Does any of you have any tips that could bring more light to this?Thank you all.
SonarQube - unity tests code coverage on new code not working
This issue is due to some flow analysis errors and have been solved in sonar java plugin version 3.9
Note: the code here is just minimal code to recreate, the code that caused this issue actually involved theInitialContextobject.SonarQube rule squid:S2583,Change this condition so that it does not always evaluate to "true"appears to produce false positives when an object is instantiated, even if the constructor throws a checked exception. As a minimal example,public void falsePositive() { TestObject myValue = null; try { myValue = new TestObject(); } catch (Exception e) { e.printStackTrace(); } finally { if (myValue != null) { System.out.println("Not null"); } } }WithTestObjectdeclared aspublic class TestObject { public TestObject() throws Exception { throw new Exception(); } }This produces an issue on theif (myValue != null)line, implying thatmyValueis always non-null which is obviously not the case.Is this a bug in the rule, or am I just missing something here?
False positive in SonarQube squid:S2583
This is SonarQube warning coming from FindBugs.You can rewrite your code like this:if (docPropertiesMap != null) { IDocProperty[] docProperties = new IDocProperty[docPropertiesMap.size()]; int iArrIndex = 0; for (Map.Entry<String, String[]> entry : docPropertiesMap.entrySet()) { String strPropName = entry.getKey(); String[] propValue = entry.getValue(); IDocProperty docProperty = (IDocProperty) FDMAFactory.getDataObject("DocProperty"); docProperty.setPropertyName(strPropName); docProperty.setArrPropertyValues(propValue); docProperties[iArrIndex++] = docProperty; } metadata.setArrDocProperties(docProperties); return metadata; }
This question already has answers here:Performance considerations for keySet() and entrySet() of Map(3 answers)Closed8 years ago.This piece of code throws the error This method accesses the value of a Map entry, using a key that was retrieved from a keySet iterator. It is more efficient to use an iterator on the entrySet of the map, to avoid the Map.get(key) lookup. Kindly guide me how to rephrase itif (docPropertiesMap != null) { Iterator<String> properties = docPropertiesMap.keySet().iterator(); IDocProperty[] docProperties = new IDocProperty[docPropertiesMap .size()]; int iArrIndex = 0; while (properties.hasNext()) { String strPropName = properties.next(); String[] propValue = docPropertiesMap.get(strPropName); IDocProperty docProperty = (IDocProperty) FDMAFactory .getDataObject("DocProperty"); docProperty.setPropertyName(strPropName); docProperty.setArrPropertyValues(propValue); docProperties[iArrIndex++] = docProperty; } metadata.setArrDocProperties(docProperties); return metadata; }
Performance - Inefficient use of keySet iterator instead of entrySet iterator [duplicate]
You cannot to do this automatically.Maybe instead of suppress rule you can useIMap. You can create simple class which can translate enums:public class Enum1ToEnum2Translator { private static IMap<Enum1, Enum2> MAP = new Map<Enum1, Enum2>(); static { MAP.add(Enum1.VAL1, Enum2.VAL1); MAP.add(Enum1.VAL2, Enum2.VAL2); MAP.add(Enum1.VAL3, Enum3.VAL3); } public Enum2 translate(Enum1 enum) { return MAP.get(enum1); } }
The C# plugin within Sonar flags methods where the cyclomatic complexity is greater than 10 (CSharpsquid:S1541 - Methods should not be too complex). This is great for 'real' code, but my team finds it annoying when a method containing just a simple 'switch' statement with 5 cases (used to translate one enum type into another enum type) is flagged as being too complex.Is it possible to suppress the flag/rule on individual methods within the code-base? If so, how?
Can individual rule violations be suppressed during code-analysis in Sonar?
This is because the class SemanticModel is not designed to be used in custom rules and is not part of the API. As such, you are encountering an error at runtime as this class is not made available whereas we can't "forbid" you to use it during compilation. Please seehttp://sonarqube-archive.15.x6.nabble.com/How-to-use-JavaFileScannerContext-getSemanticModel-td5029996.htmlfor more details. This limitation is done by SonarQube plugin packaging. I guess the error message should be mroe explicit (yes, this is an understatement).If you want to access semantic information please use the semantic API from the tree nodes to access symbols and types.
Hi I wrote own plugin for sonar 5.1.2 based on some checks from java-web-plugin 3.5 (dependency in pom for java-checks 3.5) and when I try to run analysis on project i get error:Caused by: java.lang.ClassCastException: org.sonar.java.resolve.SemanticModel cannot be cast to org.sonar.java.resolve.SemanticModel at org.sonar.java.checks.SubscriptionBaseVisitor.scanFile(SubscriptionBaseVisitor.java:32) at org.sonar.java.model.VisitorsBridge.visitFile(VisitorsBridge.java:123) at org.sonar.java.ast.JavaAstScanner.simpleScan(JavaAstScanner.java:94) ... 38 morefor example i copied to my plugin code from BadMethodName_S00100_Check.java and changed only class name, description and issue info. Why am I getting error? Other checks which don't use semanticModel works just fine.
Sonarqube error java.lang.ClassCastException: org.sonar.java.resolve.SemanticModel cannot be cast to org.sonar.java.resolve.SemanticModel
This is not currently possible. You can follow and vote forhttps://jira.sonarsource.com/browse/SONAR-4972.EDIT: Issue was closed with "Won't fix" as"the effort is to be done on each language plugin".For now, you can only ignore issues on generated files:http://docs.sonarqube.org/display/SONAR/Narrowing+the+Focus#NarrowingtheFocus-IgnoreIssues
I want to ignore generated Java source code files. Not by file or module name, but by some "signal text" in the file itself. E.g. when the source code file contains a comment/line saying/** * This file was auto-generated from WSDL * by the IBM Web services WSDL2Java emitter. * cf10631.06 v81706232132 */Even better would be to count all lines of code of such files as generated lines of code.I only foundthis articleby now.Any ideas how to approach this? Any pointers are appreciated.
How can I ignore generated code in Sonar?
Check this out:https://github.com/groupe-sii/sonar-web-frontend-pluginPlugin for Sonarqube for the Web world with various technologies and languages (JavaScript, CSS, SASS, HTML, AngularJS...). This plugin consumes reports generated by tools that are heavily used by the Web community:Linters:JSHintCSS LintSCSS LintHTMLHintAngular HintESLint plugin for AngularJSUnit testingJasmineCode coverage:IstanbulCode duplicationSimianCPDCode complexityPlatoSeems promising... :)
Is there any option to add JSHint or ESLint or TSLint toSonarQube? If it is there, could you please provide the step by step procedure.Thanks, Siva Ramanjaneyulu
How to add JSHint or ESLint or TSLint to Sonar qube?
This was fixed in Java Plugin 3.9 (SONARJAVA-818, seerelease notes).
I develop a Java library which is intended for applications based onJDK5. Tools used to build applications require JDK7 or bigger. I use version 8 update 45:java version "1.8.0_45" Java(TM) SE Runtime Environment (build 1.8.0_45-b14) Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)After the analysis I received a lot of False Positives on methods that are implementing interface specification, e.g:public interface FileScanner { Collection<File> getFiles(File directory, String[] includes, String[] excludes); }(see full sources:https://github.com/gabrysbiz/maven-plugin-utils)I found that rule makes decisions based on bytecode (seeJira ticket). My class major version is equal to 49 which is related to JDK5 (seemajor version numbers)$ javap -verbose AntFileScanner.class Classfile /D:/Projects/maven-plugin-utils/sources/plugin-utils/target/classes/biz/gabrys/maven/plugin/util/io/AntFileScanner.class Last modified 2015-07-16; size 1881 bytes MD5 checksum 7ea340377469b44df88d5936c2ff4134 Compiled from "AntFileScanner.java" class biz.gabrys.maven.plugin.util.io.AntFileScanner implements biz.gabrys.maven.plugin.util.io.FileScanner minor version: 0 major version: 49 flags: ACC_SUPERI run the analysis usingJenkins1.619 withSonarQube Plugin2.2.1. I useSonarQube5.1.1 withJava Plugin3.4.How can I correct it?
How to enforce the correct behavior for the squid:S1161 rule: "@Override" annotation should be used on any method
If reflection is an option, you can always do something likepublic class Test { @PathParam("path") public Response doSomething() { return null; } public static void main(String[] args) throws Exception { Method method = Test.class.getMethod("doSomething"); Annotation annotation = method.getAnnotations()[0]; System.out.println(getValue(annotation)); } private static String getValue(Annotation annotation) throws Exception { Class<?> type = annotation.annotationType(); if (!ANNOTATIONS.contains(type)) { throw new IllegalArgumentException("..."); } String value = (String) type.getMethod("value").invoke(annotation); return value; } private static final Set<Class<?>> ANNOTATIONS; static { Set<Class<?>> annotations = new HashSet<>(); annotations.add(HeaderParam.class); annotations.add(QueryParam.class); annotations.add(PathParam.class); annotations.add(MatrixParam.class); annotations.add(CookieParam.class); annotations.add(FormParam.class); ANNOTATIONS = Collections.unmodifiableSet(annotations); } }
Need to optimize this code :import java.lang.annotation.Annotation; import java.lang.reflect.Method; import javax.ws.rs.CookieParam; import javax.ws.rs.FormParam; import javax.ws.rs.HeaderParam; import javax.ws.rs.MatrixParam; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; ... private String valueParam(Annotation a) { String value = ""; if (a.annotationType() == QueryParam.class) { value = ((QueryParam) a).value(); } else if (a.annotationType() == PathParam.class) { value = ((PathParam) a).value(); } else if (a.annotationType() == CookieParam.class) { value = ((CookieParam) a).value(); } else if (a.annotationType() == HeaderParam.class) { value = ((HeaderParam) a).value(); } else if (a.annotationType() == MatrixParam.class) { value = ((MatrixParam) a).value(); } else if (a.annotationType() == FormParam.class) { value = ((FormParam) a).value(); } return value; }SonarQube complains about the complexity of this method.It's not so easy to change because we need to check the annotation type before getting its value!Note : The trap is on the Annotation interface that doesn't have a value() method.P.S. : This code based on thisexample(Code Example 4)
(Java) if statement optimization
Well, it's pretty straightforward:Manually download the HPI file with thelink you providedTheninstall the HPI manually in your Jenkins
How can I download and install the jenkins sonar (version 2.1) plugin to jenkins (version 1.532)?We cannot use the jenkins Update Center, as it failes to connect to the update site:hudson.util.IOException2: Failed to download fromhttp://jenkins-updates.cloudbees.com/download/plugins/sonar/2.1/sonar.hpiPlease note that opening the firewall to the update site is not an option we wish to consider - for security reasons, we want to do this process manually.How can this plugin be installed manually?tx
How to install the jenkins sonar plugin manually?
Sonar was renamed to SonarQube. I believe you should use Sonar. Outdated doc is probably just that. Outdated doc :) (feel free to edit it, or propose new screenshots)THe plugin is in the manual downloads section:http://updates.jenkins-ci.org/download/plugins/sonar/
I'm trying to set up SonarQube to run as part of a Jenkins job but I am unable to find the correct plugin.Looking in the Update Centre [host]/pluginManager/available I can't see a plugin called SonarQube as thedocumentationsuggests. There is a plugin listed called Sonar but I think that this related to an older version as the configuration options do not match the screen shots in the documentation.The plugin is listed on theJenkins Wikibut not in themanual downloadssection.Other than downloading and building from source is there a way to install this plugin?
Where/How do I install the SonarQube plugin for Jenkins?
I had the same problem and found a very different solution, perhaps because I don't believe any of the previous answers / comments. With 10 million lines of code (that's more code than is in an F16 fighter jet), if you have a 100 characters per line (a crazy size), you could load the whole code base into 1GB of memory. Simple math. Why would 8GB of memory fail?Answer: Because the community Sonar C++ scanner seems to have a bug where it picks up ANY file with the letter 'c' in it's extension. That includes .doc, .docx, .ipch, etc. Hence, the reason it's running out of memory is because it's trying to read some file that it thinks is 300mb of pure code but really it should be ignored.Solution: Find the extensions used by all of the files in your project (see here).Then add these other extensions as exclusions in your sonar.properties file:sonar.exclusions=**/*.doc,**/*.docx,**/*.ipchThen set your memory limits back to regular amounts:%JAVA_EXEC% -Xmx1024m -XX:MaxPermSize=512m -XX:ReservedCodeCacheSize=128m %SONAR_RUNNER_OPTS% ...
I am using Sonar Runner 2.2 and setSONAR_RUNNER_OPTS=-Xmx8000m, but I am getting the following error:Final Memory: 17M/5389M INFO: ------------------------------------------------------------------------ ERROR: Error during Sonar runner execution ERROR: Unable to execute Sonar ERROR: Caused by: Java heap spaceHow can this be?
Unable to execute Sonar: Caused by: Java heap space
A good starting point is to have a look at the code of existing plugins:http://github.com/sonarqubecommunity
I have gone through thehttp://docs.codehaus.org/display/SONAR/Developing+Pluginsbut unfortunately it does not give detailed steps. Can some one help me understand how I need to call a code review tool that uses ANTLR for parsing the code files and then capture the output into Sonar As well how do I start maintaining the rules based on XPATH for my code analysis tool on Sonar as it is done for Java/Javascript?
Step by Step guide for Sonar Plugin Development
cdinto the submodule and runmvn sonar:sonarthere.The drawback of this approach is that it will create a new top-level entry on the Sonar server; Sonar can't merge the results of a submodule run with an existing full analysis.
I am using Sonar integration with Jenkins. I want to run Sonar only on a sub-module of a project and not the entire project. But, when I specify-pl sub-modulein the options for Sonar, it says that it is not supported.Is there a way to achieve this?Thanks
How to run Sonar on a sub-module?
Had the same issue. The problem is that there is something wrong with the CURL command and you need to specify the full url as string using quotes.Your case would be:curl -u foo:bar "https://sonar.example.com/api/measures/search?pageSize=100&componentKeys=my-app&metricKeys=ncloc,violations,complexity"This is an example with measures. Be sure to check the required parameters.
Is there a way to get an issues report by querying the SonarQube web API?With previous versions of SonarQube, I was able to generate an HTML report after each build but this feature looks like it's been deprecated in newer installments.At the moment, I'm trying this bit of codecurl -u foo:bar https://sonar.example.com/api/issues/search?pageSize=100&componentKeys=my-app&metricKeys=violations,ncloc,lineBut it errors with{"errors":[{"msg":"The 'component' parameter is missing"}]Ideally, what I'm after is to just get the lines of code, the number of bugs, vulnerabilities, and Code smells in each run/scan.Something like thisBut through querying the API after each analysis.Is this possible, please?
How to get SonarQube Issues Report via API
Try adding the following to your .csproj<PropertyGroup> <DebugType>Full</DebugType> </PropertyGroup> <PackageReference Include="Microsoft.CodeCoverage" Version="16.9.4" />
I created a test unit for a class and it passed well on my local, on sonarqube it is shown as 0% for Coverage, I found post advice to addcoverlet.msbuildI added but still no news:<PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" /> <DotNetCliToolReference Include="dotnet-xunit" Version="2.3.1" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.0" /> <PackageReference Include="coverlet.msbuild" Version="3.0.3"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> </ItemGroup>Any idea?
Coverage always at 0% on sonarqube even i added test unit
As perthis Sonarsource documenation,This rule flags any execution of a hardcoded regular expression which has at least 3 characters and at least two instances of any of the following characters:*+{..So, you must make sure your pattern complies with the rule.Alternatively, you may disable the warnings byTurning Sonar off for certain code.
I'm getting a critical sonar issue "Using regular expressions is security-sensitive" when using the codePattern.compile(regex, Pattern.CASE_INSENSITIVE)Can anyone help to fix this? Is there any alternatives available for this?
How to fix the Sonar critical issue on Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
I have created a test project which fill all my needs in mygithub repoThe key facts are that you have to put you sonar task in your root gradle file and the jacoco one at any module in your project.The importantsonar propertiesare:sonar.host.urlandsonar.coverage.jacoco.xmlReportPathsFor thejacocotask you have to define your java-Classes"../app/build/intermediates/javac/debug/compileDebugJavaWithJavac/classes/de/logerbyte/jacocotest/javaClasses", your kotlin-Classes"../app/build/tmp/kotlin-classes/debug/de/logerbyte/jacocotest"and your normal src"../app/src/main/java"for every module.With these information you have to set the propertiesclassDirectories,executionDataandsourceDirectoriersin your own created jacoco task.At the end you run the gradle tasks forbuild,testDebugUnitTest,jacocoTestReportandsonarqube.
I have seen different approaches with different specification: only java, only single module, with jacoco exec file or xml report for sonarqube, sonarqube.gradle included in all modules or only in root.... and tried a lot. At the end I struggled always and some of my requirements don't work.Does anyone have an approach that fit all my needs?
How to configure SonarQube (with jacoco) on multi module android project (kotlin + java)?
Maybe it requires a full path withhttp://according to this article:Exercise 2: Modify the Build to Integrate with SonarQube. Or azure devops service can not find your SQ server. You can find the SQ url in the Project Setting under Service Connections:
I have added sonarkube in my CI by Azure Devops, there is a job called prepare analysis on SonarQube in my CI and in this job I have created a service connection, in this popup window, SonarQube server URL muss be added, In my Azure Portal I can only finde "abcsonarqube.westeurope.azurecontainer.io" in container instance. In a website I have seen, that the SonarQube server URL is based on "cloudapp.azure.con:9000", so I have added this url "abcsonarqube.westeurope.cloudapp.azure.con:9000".but by deployment I got this error:##[error][SQ] API GET '/api/server/version' failed, error was: {"code":"ENOTFOUND","errno":"ENOTFOUND","syscall":"getaddrinfo","hostname":"abcsonarqube.westeurope.cloudapp.azure.com","host":"abcsonarqube.westeurope.cloudapp.azure.com","port":"9000"}Does somebody have any solutions?
How finde the SonarQube server URL in Azure Portal
In short: Sonar was wrong, you never skip that await inreturn await asyncFn();.There used to be a performance benefit argument, there also used to be people saying it is the same anyway so why don't we spare those 6 keystrokes?But towards the end of 2022 the industry is slowly arriving at an understanding that this rule was a bad idea.The performance claims were shown to be false:Are there performance concerns with `return await`?And also it turns out it is not the same. By skippingawaitan enclosing try-catch will not catch the errors and an enclosingtry-finallywill not wait for the promise, so thefinallyblock will run sooner than expected. Thenewusingkeyword for "Explicit Resource Management"will also be broken if you don't await in return.It is planned to remove the rule from the default ruleset:https://community.sonarsource.com/t/await-should-not-be-used-redundantly/29074/8
I have an error in SonarQueb that saysRefactor this redundant 'await' on a non-promise.Below is my JS code. Is the await really redundant? What would be the 'correct' non-redundant code (that keeps the same functionality)? Just removeawait?async getNavLink(name: string) { console.log(`getNavLink ${name}`); return await element(by.cssContainingText('.navigation li span', name)); }
Why is Sonarqube telling me await is redundant in async function
Eventually it was decided to mark the Sonar issue as a false positive and move on about our lives.
When running a SonarQube scan allcase classandobjectscala files are flagged with a weird issue:Method com.org.package.ExampleCaseClass$.<static initializer for >() uses a Side Effect ConstructorIf I convert it to a normal class the issue goes away oddly enough. What is it that is different for the case classes/objects?Decompiling the Scala into Java shows that there does exist a static block:public static final ExampleCaseClass$ MODULE$; static { new ExampleCaseClass$(); }Example case class with the issue:case class ExampleCaseClass(var1: String, var2: String, var3: String, var4: String, var5: String, var6: String, var7: String, var8: String)Sonar expands on the issue saying:This method creates an object but does not assign this object to any variable or field. This implies that the class operates through side effects in the constructor, which is a bad pattern to use, as it adds unnecessary coupling. Consider pulling the side effect out of the constructor, into a separate method, or into the calling method.However, considering this class just takes strings in the constructor I'm not sure what the side effect could be. Is this a false positive?
Why does SonarQube find this issue (<static initializer for >() uses a Side Effect Constructor) with case and object class files?
) First ensure you are using fresh versions of SOnarQUbe/SonarJava plugin2) SonarQube is software written by people, so it could have errors. For example, similar casehttps://groups.google.com/forum/#!topic/sonarqube/qyOOOZORBNsI suggest you file issue in their Jira.3) Meanwhile, just suppress it. Suppressing is not evil if you have reason to do so
I have a list of allowed custom annotations and I'm trying to check whether a specific annotation is allowed by calling thecontainsmethod on the list. This works but Sonar complains about rulesquid:S2175. It says:A "List<Class>" cannot contain a "Class"A couple Collection methods can be called with arguments of an incorrect type, but doing so is pointless and likely the result of using the wrong argument. This rule will raise an issue when the type of the argument to List.contains or List.remove is unrelated to the type used for the list declaration.How can I fix this?Here's a minimal example:private boolean testClassContains(){ final List<Class<? extends Annotation>> annotations = Arrays.asList(MyAnnotation.class,YourAnnotation.class); return annotations.contains(YourAnnotation.class); }
How to check if a List<Class> contains a Class while avoiding Sonar rule squid:S2175
Do you have pluginGroups in your settings.xml?You can find the document fromSonarQubeAnd double check if you define all your plugins in section
I'm getting this error:No plugin found for prefix 'sonar' in the current project and in the plugin groups [org.codehaus.mojo, org.apache.maven.plugins] available from the repositoriesI have added all plugins in my local, but it's still showing the same issue.
No plugin found for prefix 'sonar' in the current project and in the plugin groups
sonar.sources - comma-separated paths to dirs containing sourcessonar.tests - the same but for test sourcesIn the documentationhttps://docs.sonarqube.org/latest/analysis/analysis-parameters/you can find information that its not compatible with Maven so probably it will look into default maven tests location
What is the difference between sonar.sources and sonar.tests in while configuring sonarqube in Maven project configuration in jenkins?
Difference between sonar.sources and sonar.tests in sonarqube
Technically and factually, it's not a bug: the rule finds that the code uses arbitrary numbers.However, I find reasonable to think that this very particular use case, with fixed indices for column numbers, should be considered a false positive. And indeed, I see no point in trying to "fix" the code. So my suggestion is to either mark these individual issues asFalse positiveorWon't fixin SonarQube, or to exclude this rule from analyzing your DAO classes.
By definition,"Magic number" is a value that should be given a symbolic name, but was instead slipped into the code as a literal, usually in more than one place.This is a perfect example of a magic numberfor(int i = 0; i < 4; i++){ // Noncompliant, 4 is a magic number ...and should be changed to something meaningful likefor(int i = 0; i < NUMBER_OF_CYCLES ; i++){ ...But Sonar throws errors for indexNumbers too. For instance, I have a DAO class where insert statement has almost 50+ columns and sonar throws error forps.setString(1 ,...)I am sure this is more readable thanps.setString(INDEX_ONE ,...)Is there anything wrong in my understanding? or Is it a bug in Sonar?
SonarQube: Magic numbers should not be used (squid:S109)
Upgrade your SonarQube to thelatest version. We recently reimplementedS1200and it is available again. Please, not that SonarQube does not have class coupling metric built-in, just this rule will raise warnings if the coupling is above the specified threshold.This rule wasdropped a few years agobecause its implementation generated too many false positives.
I have the 7.0.0.36138 SonarQube version.I’m trying to find a way to measure the Class Coupling metric of a project with SonarQube. In other versions of SonarQube it was possible to do it.In this version, I tried to look over all the possible measures of my project, but I couldn’t find the Class Coupling.Thank you.
How to measure Class Coupling metric with SonarQube
Some implementations of Map are serializable, others are not. So if you initialize it as a null, it will raise the rule as Sonar doesn't have a way to know what implementation you're going to use.This post has it all explained:Java why a Map of Map (ex: Map<String,Map<String,String>>) not serializeable
I am using SonarQube 6.7.3 with Sonar java plugin 5.3I have a Serializable java class with a map as an instance variable. 1. Map is showing S1948 rule violation when initialized with null explicitly. 2. Map is not showing any violation when that explicit null initialization is removed.Same can be seen below screenshot. Can you help me understand the difference between the two.Screen shot:
Map in a serializable class is shown as Sonar violation when explicitly initialized with null
This is indeed a case which is not handled correctly by implementation of rulesquid:S1612.I would advise you to mark this as a False Positive (FP) and not fix it. Like you correctly mentioned, both cases are not at all equivalent and the rule should therefore not raise an issue here. For more details about why these cases are not equivalent, refer toJLS §15.13 - Method Reference Expressions.The following ticket will fix implementation:SONARJAVA-2763
currently im testing some new sonar rules. With the new sonar rules a new code smell has appeared. "Lambda should be replaced with method references". I think the rule is quite cool, but with 1 case i have some issues I'll give an example and maybe someone can explain this case:Currently a call looks like this:rxTransaction( () -> new SubscriptionJavaLite( subscription ).toSubscription());My first naive thought (and also the suggestion of Intellij) was to use the following methods reference:rxTransaction( new SubscriptionJavaLite( subscription )::toSubscription);So Sonar was satisfied and everything looks the same . But it is no longer equivalent because thenew SubscriptionJavaLiteis executed at different times:Case 1 runs rxTransaction -> new SubscriptionJavaLiteCase 2 executes new SubscriptionJavaLite -> rxTransaction. Almost earlier.Is it possible to solve the case differently? Is this finding just a mistake from the sonar rule? Now I do not want to write SupressWarning over the cases everywhere.Thanks for help.
Sonar rule: Lambdas should be replaced with method references
Ok I have managed to get this to work. You need to add the following to the start/d:sonar.analysis.mode=issuessetting. Yes, I know this was depreciated in version 6.6 of SonarQube however, it gets it to work. I have tested this against versions 6.5, 6.7 & 7.0 of SonarQube.
Has anyone managed to get SonarQube working with Upsource? I have downloaded the upsource-sonar-plugin-0.1-SNAPSHOT.jar plugin for SonarQube and set the following in my SonarQube setting file that I add via the /s switch<Property Name="sonar.upsource.url">url to my upsource</Property> <Property Name="sonar.upsource.project">my upsouce project id</Property> <Property Name="sonar.upsource.revision">svn revision number</Property> <Property Name="sonar.upsource.token">See below</Property>For the sonar.upsource.token I have tried both the Upsource Build Authentication token and User Permanent Token.I'm getting no errors when I run theSonarQube.Scanner.MSBuild.exe end /d:sonar.login="*******"And get the following in the outputINFO: More about the report processing at http://********** INFO: Executing post-job Push issues to UpsourceHowever, I'm not seeing any information in Upsource in regards to what SonarQube has found.
Upsource and SonarQube
If you're building with Gradle, you shouldAnalyze with Gradle. Specifically, there's no need for asonar-project.propertiesfile. Instead, you configure the SonarQube plugin in yourbuild.gradle, and most of this shouldjust work.
Sonar scanner - 3.1Java 1.7I'm trying to configure sonar properties to get coverage from a multi-module project. Coverage is generated under the path: Module/build/jacoco/test.exec, so I wanted to add it to sonar.properties file according to documentation:https://docs.sonarqube.org/display/PLUG/Code+Coverage+by+Unit+Tests+for+Java+Projectsonar.java.coveragePlugin=jacoco sonar.jacoco.reportPaths=**/build/jacoco/*.execI was trying different combinations even with the absolute path but it seems that sonar-scanner doesn't see this property at all and always looks at default path. I'm always getting information in the logs that:INFO: JaCoCoSensor: JaCoCo report not found : path\target\jacoco.exec INFO: JaCoCoSensor: JaCoCo IT report not found: path\target\jacoco-it.execIt does read other properties from the file like login, password, language, sources etc.Also, the project is based on Gradle.
Sonarqube + Jacoco - sonar does not read report path from properties
To activate verbose mode, you simply need to pass the following argument:/d:sonar.verbose=trueReference:https://docs.sonarqube.org/display/SCAN/Additional+Analysis+Parameters
I have some problems while scanning a mixed C#, C++ solution withSonarQube.Scanner.MSBuild.exe. (during theSonarQube.Scanner.MSBuild.exeend) So I want to ask if there is a verbose option to activate enhanced/debug output.The output is that a file is not found, but there is a additional subfolder in the path that is not correct, and I want to understand where it comes from.Example:a.cppis located onC:\src\ProjektA\Modul1, but the output says:"Warn: Cannot find the file "C:\src\ProjektA\**Modul2**\Module1\a.cpp" skipping violations"By the way: inFilesToAnalyse.txtthe path is correct
Is there a verbose mode of SonarQube.Scanner.MSBuild.exe?
This issue will be fixed in SonarQube 6.6:https://jira.sonarsource.com/browse/SONAR-9561
We're using SonarQube 6.3 with a PHP project. We have the sonar.language property set to php since that's what we're interested in. We have exclusions configured so some vendor libraries are not included in the scan. These exclusions work for the actual analysis but our scan log is full of warnings about files being ignored because they aren't php.Sample warning:WARN: File 'vendor/somejavascriptlib/cooljavascript.js' is ignored because it doens't belong to the forced langauge 'php'We have sonar.exclusions set to "vendor/**/*" but that doesn't seem to impact the file indexing that is creating these warnings. Is there a way to supress the warning? Or a different config property we should be using?
How can I configure sonar-scanner to not warn on files not matching forced language?
To have your .yml files analyzed, you need to install an analyzer that handles that language. I'm not currently aware of any such plugin.
i have a problem with my .yml rules. I can include them into my project, he does get the custom rules, but I cannot show them in sonarqube, because he says he does not know the rules. can anyone help me? my .swiftlint.yml file is in the homedirectory and I only run the run-sonar-swift.sh with swiftlint, tailor and lizard.Thanks a lot.
run-sonar-swift.sh with custom swiftlint .yml file
Currently there is no way to do that. I've createdthis issueto address the problem.
I can't seem to use wildcards to specify a path to mylcov.infofile in the SonarQube MSBuild Scanner. e.g.:/d:sonar.javascript.lcov.reportPath="..\..\build\coverage\lcov\*\lcov.info"but if I specify the full path, it works:/d:sonar.javascript.lcov.reportPath="..\..\build\coverage\lcov\Chrome 57.0.2987 (Windows 10 0.0.0)\lcov.info"This is going to vary depending on what browser is on the build agent!Any idea how I can get around this?
Wildcards for lcov.info path in the SonarQube scanners?
With recent versions of SonarQube, you don't have built-in tables that show you a list of metrics over different versions of your project.Still, you can see the evolution of each metric over the past versions when you go to "Measures > [select the metric] > History". You will see something like:
i'd like to compare code coverage and other metrics between two different versions of my project, but using the leaking period mechanism i was not able to get the view i want.I would like to compare version metricslike this:On my researches i've read something similar was possible on older versions of sonar.Can someone give a tip on how to do it?
SonarQube compare versions of the same project
You can use SonarLint standalone - in which case you will get the default, non-editable rule set - or connected to your SonarQube server - in which case you will get the rules in the profile that's applied to your project.There is no middle ground where you could feed a list of rules in standalone mode.
Is it possible to use a rule set defined in .Xml (based on SonarQube- und FindBugs rules) and run it without setting up a SonarQube server. I want to use SonarLint in Eclipse for some Java projects with only the input of the rule set i get forwarded from other projects of the company.
Use an xml file as a rule set for SonarLint (no SonarQube server) in a Eclipse Java environment
As far as I know Once the job is complete, the plugin will detect that a SonarQube analysis was made during the build and display a badge and a widget on the job page with a link to the SonarQube dashboard as well as quality gate status.Please referthisand verify your configurations.If this is happening to you, verify that the test is actually running if not, verify your configuration.
I've set up a multi-branch pipeline in Jenkins which performs a SonarQube analysis using thewithSonarQubeEnv()step and thesonar:sonarMaven goal.This works fine, and the analysis results do show up in SonarQube.What I'm missing (compared to the traditional non-pipeline Jenkins integration) is a clickable link on the Jenkins build page which will open the analysis results in SonarQube.There is a small SonarQube icon next to every build in the left panel, but this icon is not clickable.Is there any configuration switch that will produce a clickable link, or is this simply a missing feature?
Link from Jenkins Pipeline page to SonarQube
Don't know if this is ideal, but I'm getting the status from the SonarQube api with a request (which you can do with the HttpRequest plugin).def response = httpRequest 'https://SONAR_USER:SONAR_PASSWORD@SONAR_URL/api/qualitygates/project_status?projectKey=PROJECT_KEY' def slurper = new groovy.json.JsonSlurper() def result = slurper.parseText(response.content) if (result.projectStatus.status == "ERROR") { currentBuild.result = 'FAILURE' }
i'd like to start a Sonar project analysis with Jenkins 2.x Groovy Script Build Pipeline.I have sonar configured in Maven so thats no big deal:withEnv(["JAVA_HOME=${javaHome}", "PATH + MAVEN=${mavenHome}/bin:${env.JAVA_HOME}/bin", "MAVEN_OPTS=${mavenOpts}"]) { sh 'mvn -B sonar:sonar' }But how can i get results from sonar ? Or even better how can i determine if a quality gate was achived so that i can stop the build-pipeline.The build breaker concept is obsolet since some versione of sonar, as far as i know. Or how would you handle this.I still think it would be a good idea to stop/pause a build pipeline if the underlying code of a project is too bad.
Jenkins Script Pipeline sonar Integration
You need to first delete the user then log in with its login.It's true when you delete a user some data remains in database, but in any case you can safely use its login with another identity provider, LDAP in your case.
We have a local user account in SonarQube 5.6 that was created before we added the LDAP plugin.How can we change that account to use LDAP rather than the local account password for authentication?It doesn't seem like a simple matter of deleting the account and logging in again, since AFAIK user accounts can't be deleted.
How to change a local user to LDAP
As far as we(SonarSource)know, there's no alternative to the Governance product - may it be open-source or even commercial.
Are there alternatives to Views plugin for Community Edition 5.6? Not commercial plugins (Governance license). Cannot comment inSonarQube 5.5 and Views plugin.
Non-commercial alternatives to Views plugin for SonarQube Community Edition 5.6