Response
stringlengths 8
2k
| Instruction
stringlengths 18
2k
| Prompt
stringlengths 14
160
|
---|---|---|
'FontAwesome' is a custom font, so sonarqube is asking to add generic font to fallback to.
Adding a generic font like "sans-serif" will be sufficinet..calendar-wrapper:after {
font-family: 'FontAwesome', sans-serif;
content: '\f073';
position: absolute;
right: 9px;
top: 9px;
}ShareFollowansweredMay 28, 2021 at 12:10Durga PrasadDurga Prasad41744 silver badges1111 bronze badgesAdd a comment|
|
I'm using FontAwesome 4.7 in one of my project and we have SonarQube integration. At few places in my custom CSS files, I've to provide Font-Family manually like:.calendar-wrapper:after {
font-family: 'FontAwesome';
content: '\f073';
position: absolute;
right: 9px;
top: 9px;
}But at this line, SonarQube shows me bug:
Unexpected missing generic font family (Rule Here)What should be the generic font-family for FontAwesome? I looked everywhere on the internet but didn't found any solution yet.
|
What should be the generic font family for Font-Awesome fonts?
|
I readhttps://docs.sonarqube.org/display/PLUG/Code+Coverage+by+Unit+Tests+for+Java+Projectand used cobertura as my code coverage plugin then I see code coverage displays for small projects. When I check for a big project in sonar I just see code coverage as - that means its empty. In logs I could find that Cobertura report was not found at /.../coverage.xml path.coverage.xml was not generated due to OutOfMemeryError:heapspace. Since my project is such a big project when I set heap memory to 2GB and cobertura plugin memory to 1.5GB sonar gets code coverage displayed.ShareFolloweditedMar 23, 2017 at 9:23WoLfPwNeR1,24844 gold badges1212 silver badges2828 bronze badgesansweredSep 12, 2013 at 6:53VenkatVenkat27322 gold badges33 silver badges1313 bronze badges0Add a comment|
|
I am trying to get code coverage with Sonar and Jenkins. I see Jenkins' Sonar plugin successfully executes JUnit test cases and completes build successfully. But Sonar does not show Code Coverage results (always shows 0.0% as the code coverage) on the project. But Sonar does show "Unit test success".I am using Maven with Jenkins and Sonar.I get the below message in Jenkins logs while executing the Sonar plugin:Project coverage is set to 0% as no JaCoCo execution data has been dumped: .../sonar/target/jacoco.execCan any one help me how to get correct code coverage on any Sonar project.
|
Sonar does not shows up Code Coverage after build successful with Jenkins Sonar plugin
|
projectKey is simply the unique identifier of your project inside SonarQube. You are free to choose whatever you want, as long as it is unique.Analysis Parametersis the official documentation page from Sonar, where you can find additional information about all the properties.ShareFolloweditedNov 4, 2021 at 0:35RenatoIvancic1,95033 gold badges2323 silver badges3737 bronze badgesansweredMar 2, 2015 at 7:45Fabrice - SonarSource TeamFabrice - SonarSource Team26.6k33 gold badges6363 silver badges5858 bronze badges0Add a comment|
|
What is the "projectkey" in sonar-project.properties file?sonar.projectKey=
sonar.projectVersion=1.0
sonar.projectName=How to decide the projectkey? I mean where can we find it for our.Net,plsql projects?Note- I am new to these sonar and trying to setup all these on my own in my organization.
|
What is "projectkey" in sonar-project.properties file
|
Awaiting for an implementation in sonar of the IT execution results (see the@Fabriceanswer). I have found a workaround inthis tutorial. The idea is :... fool Sonar to show test success for both unit and integration tests together by instructing Failsafe to store its test reports to the same directory as Surefire instead of the default failsafe-reports.<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<configuration>
<reportsDirectory>${project.build.directory}/surefire-reports</reportsDirectory>
</configuration>
</plugin>The result is not perfect because all the tests result are shown in the unit test widget. But i really don't want to check the IT tests results in the ci server. I want an all-in-one dashboard for my project.ShareFolloweditedMay 23, 2017 at 12:25CommunityBot111 silver badgeansweredMar 22, 2013 at 10:14gontardgontard29k1111 gold badges9494 silver badges117117 bronze badgesAdd a comment|
|
I have just separated the unit tests and the integration tests. I wanted to separate the coverage results from UT and from IT.I followedthis tutorialand it works (Thanks@JohnDobie).Sonar displays the separate code coverage results and the unit test success (upper right). But how can i get the integration test success in sonar ?
|
Failsafe tests results in sonar
|
+25I think no, a similar question was asked here:Generate Sonar code coverage report from Postman testsThe original poster commented further down:In fact, after a bit of googling, as a work-around we could use remote
Jacoco agent hooked in the java application server. We'll try to run
jacoco maven goals before and after the tests execution in order to
generate jacoco coverage report. See:linkI'll update the post if we
have some progress.Also, newman seems to have aticket about it:https://github.com/postmanlabs/newman/issues/408Though this might helpShareFollowansweredFeb 27, 2018 at 12:58BentayeBentaye9,51855 gold badges3232 silver badges4646 bronze badges1yes, I read that post, I've used jacoco-maven-plugin to get coverage, but the code that is covered by postman tests does not get into the generated statistics–aureliusFeb 27, 2018 at 13:00Add a comment|
|
We have REST services created in RestEasy and running in wildfly server. We are running Postman test cases to test the Rest URLs.Is there a way to get a code coverage of the services when we execute postman test suite?We use SonarQube to analyse the code coverage.
|
How to get code coverage using postman test
|
I was able to make it work by running the cppcheck tool independently before sonnar-runner, and placing the generated xml report in the bin folder of sonnar-runner.In the sonar-project.properties file I've specified the xml directly:
sonar.cxx.cppcheck.reportPath=cppcheck-result-1.xmlShareFollowansweredJun 10, 2013 at 13:25Catalin STAICUCatalin STAICU54611 gold badge44 silver badges1919 bronze badgesAdd a comment|
|
I'm trying to use sonar for static analysis on a c++ code. I've installed sonar and configured my project (it appears on the localhost sonar page, but i do not see any code violation for the respective code). I have the C++ community plugin installed.My sonar-project.properties looks like this:# required metadata
sonar.projectKey=DiceInvaders
sonar.projectName=Dice Invaders
sonar.projectVersion=1.0
# optional description
sonar.projectDescription=DiceInvaders by CS
# path to source directories (required)
sonar.sources=D:\\DiceInvaders\\Code
# path to test source directories (optional)
#sonar.tests=D:\\DiceInvaders\\Code
# path to project binaries (optional), for example directory of Java bytecode
#sonar.binaries=binDir
# optional comma-separated list of paths to libraries. Only path to JAR file is supported.
#sonar.libraries=path/to/library/*.jar,path/to/specific/library/myLibrary.jar,parent/*/*.jar
# The value of the property must be the key of the language.
sonar.language=c++
sonar.exclusions=**/*.ipch, **/**/*.rc
sonar.cxx.cppcheck.path = "C:\Program Files (x86)\Cppcheck\cppcheck.exe"
sonar.cxx.cppcheck.reportPath="D:\DiceInvaders\Code\cppcheck-reports\cppcheck.xml".
# Additional parameters
#sonar.my.property=valueI do not get any error when running sonar-runner from cmd.If i run manually the cppcheck.exe tool on my project I can find violations. Why don't the violations appear on sonar's page?
Is there something else I should configure, am I doing something wrong?
|
How to make sonar analysis for C++ work?
|
Foundthison the sonar source community. Seems like this was missing feature and being released on 10.2ShareFollowansweredSep 15, 2023 at 11:24Aziz ZoaibAziz Zoaib70999 silver badges2323 bronze badges1meta.stackoverflow.com/a/285557/11107541–starballSep 15, 2023 at 19:02Add a comment|
|
I am trying to change my main branch in Sonarqube frommastertomainlineas I have been doing my analysis onmainlinefor the past few months.This post below in the Sonar community says that I have to delete themainlinebranch then rename themasterbranch. The problem with this approach is that I would lose all of my history which I do not want to do.https://community.sonarsource.com/t/how-to-change-the-main-branch-in-sonarqube/13669/37Is there anyway to change the main brach to another branch without losing all of our scan history?Using:
Developer Edition - Version 9.2.1Picture of Branches
|
Change main branch in Sonarqube without deleting branch
|
You could try to make findbugs dev build manually and put it into sonar. Not the easiest way.svn checkout http://findbugs.googlecode.com/svn/trunk/findbugsShareFolloweditedApr 10, 2012 at 13:58Gray116k2424 gold badges299299 silver badges358358 bronze badgesansweredNov 14, 2011 at 21:19Vladislav BauerVladislav Bauer95288 silver badges1919 bronze badgesAdd a comment|
|
I try to use Sonar on a Java 7 project (which relies on new syntactic features) and the PMD part and the Checkstyle part fail to parse those files.The Findbugs part fails to read Java 7 class files.This causes Sonar to consider only 10% of my classes.Can there be a workaround for this?EDIT:There is an issue for Java 7 compatibility.Please vote for this issue, so it will be fixed soon.
|
Any current workarounds to use Sonar for Java 7 code?
|
You should update the database if you use MySQL or another RDBMS: Visithttp://127.0.0.1:9000/setup. After the update finished,visithttp://127.0.0.1:9000. It's ok!ShareFolloweditedMay 22, 2017 at 13:43Matthias Braun33k2626 gold badges147147 silver badges174174 bronze badgesansweredDec 10, 2015 at 5:47fisherfisher42144 silver badges33 bronze badges1Thanks for this! The UI directs you to an upgrade page that does not mention /setup and I was very confused for a moment.–John Kelly IIIJul 13, 2023 at 21:35Add a comment|
|
I added a new extension plugin for typescript, stop and restarted the service and now the web page sonarqube displays "SonarQube is under maintenance".
On the web they said to try \setup but it does not work...Someone have an idea of how to remove this maintenance mode?Thanks in advance.
|
SonarQube is under maintenance
|
After a lot of trial and error, here's the solution that worked for me.I had to install the lastest version ofdotnet-sonarscanneranddotnet-reportgenerator-globaltoolfor this to work. I already had the report generator installed, but needed to update it to use the SonarQube report type.dotnet tool install --global dotnet-sonarscanner --version 5.2.0
dotnet tool update dotnet-reportgenerator-globaltool -g --version 4.8.7With thereportgeneratorthe cobertura files can be converted to the SonarQube format.dotnet sonarscanner begin /k:"MyProject" /d:sonar.host.url="http://localhost:9000" /d:sonar.login="<token>" /d:sonar.coverageReportPaths=".\sonarqubecoverage\SonarQube.xml"
dotnet build
dotnet test --no-build --collect:"XPlat Code Coverage"
reportgenerator "-reports:*\TestResults\*\coverage.cobertura.xml" "-targetdir:sonarqubecoverage" "-reporttypes:SonarQube"
dotnet sonarscanner end /d:sonar.login="<token>"Report generator supported file formats:https://github.com/danielpalme/ReportGenerator#supported-input-and-output-file-formatsSonarQube generic test data format:https://docs.sonarqube.org/latest/analysis/generic-test/ShareFollowansweredApr 14, 2021 at 12:21eddexeddex1,94211 gold badge1717 silver badges4040 bronze badgesAdd a comment|
|
I want to show test coverage for my .NET 5 unit tests in my local SonarQube instance (on Windows).dotnet sonarscanner begin /k:"MyProject" /d:sonar.host.url="http://localhost:9000" /d:sonar.login="<token>" /d:sonar.cs.opencover.reportsPaths="**\TestResults\*\*.xml"
dotnet build
dotnet test --no-build --collect:"XPlat Code Coverage"
dotnet sonarscanner end /d:sonar.login="<token>"Thedotnet testcommand generates the coverage reports ascoverage.cobertura.xmlfiles in the<TestProjectDir>.TestResults\<some-guid>\folder.In the logs I can see the following warning:WARN: Could not import coverage report '<MyTestProject>\TestResults\a4af5812-7f80-469b-8876-3ea0c7c4c98d\coverage.cobertura.xml' because 'Missing root element <CoverageSession> in C:\Users\<Path>\TestResults\a4af5812-7f80-469b-8876-3ea0c7c4c98d\coverage.cobertura.xml at line 2'. Troubleshooting guide: https://community.sonarsource.com/t/37151Following thelinkfrom the warning message, I can see that onlyVisual Studio Code Coverage,dotCoverandOpenCover/Coverletare supported. As far as I can tell from theirGitHub page, isOpenCover/Coverletis "XPlat Code Coverage".In my test projects thecoverlet.collectorNuGet package v 3.0.3 is installed.What am I missing?I found this related question:SonarQube: Unable to import test coveragebut it doesn't help me because I can't usedotCover.
|
SonarQube test coverage .NET 5
|
I have fixed! When I disabled the Shallow Clone on Jenkins, it was still missing the past commits, so I had to run some commands on GIT bash inside the repository folder:git fetch --depth=1000000(unless you have more than 1 million commits)then to confirm that I have removed the shallow:git fetch --unshallowAfter wait the next build and analysis, now has disappeared the warning and I can see the authors!ShareFollowansweredNov 25, 2019 at 15:56Samuel FinattoSamuel Finatto16711 gold badge11 silver badge77 bronze badges2That means ur using no more shallow clones after using this command. right?–TAMIM HAIDERFeb 17, 2022 at 14:382fatal: --unshallow on a complete repository does not make sense–UrasquirrelDec 2, 2022 at 19:30Add a comment|
|
I have a Jenkins server building a solution using MSBuild. Shallow Clone is not enabled (on Advanced Clone Behaviours), so I supposed it's getting all the last commits. And I'm using SonarQube to analyze. I set to run the Begin Analysis before build and the End Analysis after build is complete. The SonarQube Analysis finishes successfully, but I'm receiving a warning:Shallow clone detected during the analysis. Some files will miss SCM
information.
This will affect features like auto-assignment of issues. Please
configure your build to disable shallow clone.Someone knows what I'm missing to SonarQube works fine?
|
SonarQube with shallow clone warning even with shallow disabled on Jenkins build
|
Yes, you can usethis::createSomeValue:private List<SomeValue> createSomeValues(List<Anything> anyList) {
return anyList //
.stream() //
.map(this::createSomeValue) //
.collect(Collectors.toList());
}This kind ofmethod referenceis called"Reference to an instance method of a particular object". In this case, you are referring to the methodcreateSomeValueof the instancethis.Whether it is "better" or not that using a lambda expression is a matter of opinion. However, you can refer tothis answerwritten byBrian Goetzthat explains why method-references were added in the language in the first place.ShareFolloweditedMay 23, 2017 at 10:30CommunityBot111 silver badgeansweredFeb 19, 2016 at 14:48TunakiTunaki135k4646 gold badges355355 silver badges431431 bronze badges0Add a comment|
|
Sonar tells me "Replace this lambda with a method reference"public class MyClass {
private List<SomeValue> createSomeValues(List<Anything> anyList) {
return anyList //
.stream() //
.map(anything -> createSomeValue(anything)) //
.collect(Collectors.toList());
}
private SomeValue createSomeValue(Anything anything) {
StatusId statusId = statusId.fromId(anything.getStatus().getStatusId());
return new SomeValue(anything.getExternId(), statusId);
}
}Is this possible here? I tried several things, like.map(MyClass::createSomeValue) //but I need to change the method to static then. And I am not a big fan of static methods.Explanation of SonarQube is:Method/constructor references are more compact and readable than using lambdas, and are therefore preferred.
|
SONAR: Replace this lambda with a method reference
|
The "False positive" action is only available with the "Administer Issues" permission, so you might want to check the permissions on the newly created project(s). If it is indeed an issue with permissions, then your next step will probably to modify the default permission template associated with projects, so that you get the right permissions upon creation.ShareFollowansweredMar 13, 2014 at 13:06MithfindelMithfindel4,64811 gold badge2323 silver badges3232 bronze badgesAdd a comment|
|
I'm using Sonarqube on Ubuntu 12.01 machine. I use Sonar Runner with Jenkins plugin to analyse my code.The problem came when I execute an analysis for new projects. For example I have saved on Sonar A and B project, if I execute analysis for new C project for this project false positive option don't appear.
This occurs since I update Sonar to the last version 4.1.2. With projects that have been created with the previous version all works fine.
Anyone knows what is the problem?
For my company the possibility of mark errors like false positive is really important.
|
False Positive option don't appear on projects
|
If those two lists are arguments passed to a method,IllegalArgumentExceptionwould be a good candidate to throw. It's a sub-class ofRuntimeException, so you'll still be throwing a kind ofRuntimeException.if (objctArray.length != columnArray.length) {
throw new IllegalArgumentException(String.format("objctArray and columnArray length is not same. objctArray length = %d, columnArray length = %d", objctArray.length, columnArray.length));
}ShareFollowansweredFeb 22, 2016 at 7:41EranEran390k5555 gold badges708708 silver badges776776 bronze badgesAdd a comment|
|
I need tothrow RuntimeExceptionwhen length of two lists is not equal. We are usingSonarQubetool for code review purpose.Here is the code:if (objctArray.length != columnArray.length) {
throw new RuntimeException(String.format("objctArray and columnArray length is not same. objctArray length = %d, columnArray length = %d", objctArray.length, columnArray.length));
}Now,SonarQuberaises issue thatDefine and throw a dedicated exception instead of using a generic one.atthrow new RuntimeExceptionline. I don't know which exception I can replace to resolveSonarQubeissue.
|
How to resolve 'Define and throw a dedicated exception instead of using a generic one.'
|
Workaround: Adding -Dsonar.host.url=http://my.server:9000to mvn command works for meShareFollowansweredOct 23, 2015 at 12:01KaiKai12644 bronze badges2Works fine for me, since we're using Teamcity templates.–FrankOct 26, 2015 at 11:53Just in case if some one stumbles up on this. I had same error with latest SonarQube ( 5.5.1) . I had to use-Dsonar.host.url=http://my.server:9000/sonar- not sure what was wrong.–ring bearerMay 4, 2016 at 18:05Add a comment|
|
After upgrading my POMs to sonar-maven-plugin:2.7 the configuration does not work any more. My configuration in settings.xml is like this:<profile>
<id>sonar</id>
<properties>
<sonar.jdbc.url>jdbc:postgresql://my.server:5432/sonar</sonar.jdbc.url>
<sonar.jdbc.driverClassName>org.postgresql.Driver</sonar.jdbc.driverClassName>
<sonar.jdbc.username>xxxxx</sonar.jdbc.username>
<sonar.jdbc.password>yyyyy</sonar.jdbc.password>
<sonar.host.url>http://my.server</sonar.host.url>
</properties>
</profile>The build is started with-Psonarof course. With version 2.6 everything is fine, with 2.7 I get[INFO] --- sonar-maven-plugin:2.7:sonar (default-cli) @ myproject ---
[INFO] User cache: C:\Users\me\.sonar\cache
[ERROR] SonarQube server 'http://localhost:9000' can not be reached
...
[ERROR] Failed to execute goal org.codehaus.mojo:sonar-maven-plugin:2.7:sonar (default-cli) on project myproject: Fail to download libraries from server: java.net.ConnectException: Connection refused: connect -> [Help 1]Starting the build with-Xgives me the correct mojo configuration in both cases, especially the url is still correct in the log[DEBUG] (f) sonarHostURL = http://my.serverEven deleting the mentioned caching directory does not help.What can I do except of managing the plugin to version 2.6?
|
sonar.host.url not working with sonar-maven-plugin:2.7
|
Add propertysonar.binaries=${workspace}/proy/build/To Sonar Configuration. If you ar using several proyects to build, use coma separed.ShareFollowansweredDec 15, 2014 at 22:15other nameother name10611 silver badge33 bronze badges13After adding below sonar properties in Jenkins it started working for me ....sonar.java.binaries=.Hope it will help someone.–Anurag_BEHSOct 29, 2017 at 14:30Add a comment|
|
I am trying to get SonarQube findbugs working, but when I try to run it I get the error: "Findbugs needs sources to be compiled. Please build project before executing sonar and check the location of compiled classes."sonar.sources is set to a folder with all of my src files and sonar.binaries is set to a folder with all of my class and jar files. This layout works with findbugs for one of my projects, but on the other I get the above error.How can I fix this, and is there a certain folder FindBugs needs classes/jars in to work?Thanks.
|
SonarQube Findbugs "needs sources to be compiled"
|
This is a known issue of SonarQube java analyzer :https://jira.sonarsource.com/browse/SONARJAVA-583This is due to a lack of semantic analysis to resolve properly method reference (thus identify to which method this::isActive refers to).ShareFollowansweredFeb 26, 2016 at 14:19benzonicobenzonico10.7k55 gold badges4444 silver badges5151 bronze badges0Add a comment|
|
I have the following logic;..
if(list.stream()
.filter(MyClass::isEnabled)
.filter(this::isActive)
.count() > 0) {
//do smth
}
..
private boolean isActive(MyClass obj) {
return bool;
}As you see,isActivemethod is being used in the stream structure, but when I build this class on Jenkins, I get the unused private method issue from SonarQube, it says you should delete this redundant private method. Is this a bug? If not, why haven't they still included lambda logic in their analyze structure?Only solution is, obviously, to do this;.filter(obj -> isActive(obj)), but it destroys the uniformity, and even the readability (imo).
|
SonarQube giving unused private method issue for lambda usage
|
This is a feature that is not supported :https://jira.sonarsource.com/browse/SONARJAVA-521There is no plan to implement it for now but this might be addressed in the future.ShareFollowansweredMay 3, 2016 at 10:04benzonicobenzonico10.7k55 gold badges4444 silver badges5151 bronze badges2Do you know if there is a way of suppressing specific issues in another way?–Tomas MelinMay 4, 2016 at 6:304I am using SonarQube Community Edition Version 7.9.1 (build 27448). Is it not possible to ignorecommon-java:DuplicatedBlocksin this version also? I tried putting@SuppressWarnings("common-java:DuplicatedBlocks")at both method as well as class level and it did not work.–Rakesh PrajapatiMar 16, 2020 at 18:09Add a comment|
|
I am using SonarQube 5.4 and investigating the suppressing of several issues. I've found that SonarQube does not detect the suppression of the ruleSource files should not have any duplicated blocksonce I insert@SuppressWarnings("common-java:DuplicatedBlocks")in the beginning of the file (the file does not compile) or at the markup of the one of the duplicated code blocks.I've found the information athttp://docs.sonarqube.org/display/PLUG/Java+FAQwhich states the following:The //NOSONAR tag is useful to deactivate all rules at a given line but is not suitable to deactivate all rules (or only a given rule) for all the lines of a method or a class. This is why support for @SuppressWarnings("all") has been added to SonarQube.I am using the version 3.13.1 of SonarQube Java Plugin.I am aware that I can mark the issue in the SonarQube GUI as a false positive but this will not transfer through branches which is a required feature for me.How should I use the@SuppressWarnings-tag to disable the duplicated code block?
|
How is the warning 'Source files should not have any duplicated blocks' suppressed in SonarQube?
|
Add the following dependency to your pom<dependency>
<groupId>org.joda</groupId>
<artifactId>joda-convert</artifactId>
<version>1.8.1</version>
<scope>provided</scope>
</dependency>ShareFollowansweredOct 9, 2015 at 20:22user5429174user54291746622 bronze badges25That may help in some cases but it is no remedy for the root cause.–Marcel StörOct 17, 2015 at 12:33Did not work for me. I will try this in the future:stackoverflow.com/questions/31593240/…–JonyDMar 21, 2017 at 12:12Add a comment|
|
I have many errors with sonarqube analyse in the Jenkins job with the analyse success[ERROR] [14:36:44.124] Class not found: org.joda.convert.FromString
[ERROR] [14:36:44.126] Class not found: org.joda.convert.ToString
[ERROR] [14:34:42.441] Class not found: org.apache.commons.logging.Log
[ERROR] [14:34:42.724] Class not found: org.apache.oro.text.perl.Perl5Util
[ERROR] [14:34:31.442] Class not found: io.swagger.annotations.ApiModel
[ERROR] [14:34:31.442] Class not found: io.swagger.annotations.ApiModelProperty
[ERROR] [14:28:37.756] Class not found: org.apache.commons.logging.Log
[ERROR] [14:28:40.030] Class not found: org.apache.oro.text.perl.Perl5UtilSonareQube : 5.1.2sonarQube jenkins plugin : 2.6JDK : 1.7Any help pleasethanks
|
“Class Not Found” during SonarQube analyse
|
If you can't decrease the number of switch case or can't refactor the code you can suppress the warning with@SuppressWarnings({"squid:S128", "squid:S1479"}Sample usagehereShareFollowansweredAug 5, 2019 at 16:38MeladMelad1,2141515 silver badges1818 bronze badgesAdd a comment|
|
I can't really figure out why Sonar keeps complaining about the fact that I "don't have a break statement" even if it's not needed..My switch:public static String lookupVoyageId(String referenceNumber, String sender) {
switch (sender) {
case "400_HGENT":
case "200_HAPEN":
case "500_HOOST":
Preconditions.checkArgument(referenceNumber.contains("-"));
return referenceNumber.split("-")[0];
case "600_HZEEB":
Preconditions.checkArgument(referenceNumber.length() >= 6);
return referenceNumber.substring(0, 6);
case "800_BVL":
throw new TransferException("This reference number for IBIS isn't according to the requirements. Can't implement it yet.");
case "MCCD":
throw new TransferException("This reference number for MCCD isn't according to the requirements. Can't implement it yet.");
default:
throw new TransferException("The sender (" + sender + ") couldn't be identified.");
}
}and sonar keeps giving me the critical:
"A switch statement does not contain a break"Why is this? I don't need any breaks in this switch?I know it might be a specific case, but I can't find anything on the web.
|
SonarQube - Java rule "S128" - Why the rule complains about the fact that a break statement is missing when this is obviously not necessary?
|
Others have pointed out that the way to avoid this error is to use:! ("".equals(mapData.get("CON_PTY_PARTY_ID")))But no one has pointed outwhythis matters. The reason the literal should be on the left side of the equals comparison is to avoid the possibility of an exception if the string being compared to it is null.As written in the question, if the value ofmapData.get("CON_PTY_PARTY_ID")wasnull, then the expression would be trying to invoke theequals(..)method ofan object that doesn't exist.That would throw an exception. By putting the literal on the left, then even if the value ofmapData.get("CON_PTY_PARTY_ID")wasnull, the method"".equals(...)would be defined and would not throw an exception. It would simply returnfalse.ShareFolloweditedJun 22, 2015 at 15:39answeredJul 9, 2014 at 16:13Mark MeuerMark Meuer7,33366 gold badges4646 silver badges6767 bronze badges0Add a comment|
|
!mapData.get("PARTY_ID").equals("") // <-- gives SonarQube errorIn the above piece of code, I am getting "String literal expressions should be on the left side of an equals comparison" this error in Sonar. So how we can avoid it.I tried this:("").equals(!mapData.get("CON_PTY_PARTY_ID"))But it does not work.
Give some advice......
|
String literal expressions should be on the left side of an equals comparison
|
From SonarQube'sdocumentation:SonarSource analyzers do not run your tests or generate reports. They only import pre-generated reports.A popular library for generating code coverage for Java isJacoco.SonarQube providesthis guideto create and import Jacoco's reports.ShareFolloweditedNov 23, 2019 at 19:55answeredNov 23, 2019 at 19:45Michele DorigattiMichele Dorigatti80711 gold badge99 silver badges1818 bronze badges21I somehow overlooked the fact that "execution" and "coverage" are two separate things. Your answer made me realize my error. Thank you! I will mark it appropriately. Eventually, I will edit it with a working piece ofsonar-project.propertiesfile.–payneNov 23, 2019 at 19:47SonarQube is a beautiful tool, but they are many bits needed to make everything work.–Michele DorigattiNov 23, 2019 at 19:48Add a comment|
|
I'm using JUnit5 on a SpringBoot backend application server using Maven. Here is thesonar-project.propertiesfile that is at the root of the project:sonar.host.url=https://sonarcloud.io
sonar.login=xxx
sonar.organization=xxx
sonar.projectKey=xxx
sonar.sourceEncoding=UTF-8
sonar.language=java
sonar.java.source=12
sonar.sources=src/main/java
sonar.test=src/test
sonar.java.binaries=target/classes
sonar.junit.reportPaths=target/test-results/TEST-**.xmlI use thesonar-scannercommand line to run update the project after a build/test.TheOverviewboard on sonar-cloud looks like this:I at least got the unit tests to be recognized, but somehow I'm still at 0% in terms of code coverage. Furthermore, here is theMeasuresboard:Apparently, my tests do not cover any lines whatsoever. Now, I'm aware that this means that I most probably didn't hook up the test-results properly, but I'm not sure how to do that.What puzzles me, too, is that despite SonarQube recognizing my tests, it actually says that the lines-of-code of the tests themselves aren't tested. What is this supposed to mean?
|
Setting up properly SonarQube for Code Coverage
|
You're missing the namespace declaration in the topprojectelement of your Ant script.xmlns:sonar="antlib:org.sonar.ant"ought to do it.ShareFollowansweredOct 12, 2012 at 18:45DavidDavid2,62211 gold badge1919 silver badges3232 bronze badges2Is it possible to use the sonar ant task in any way without the specific sonar namespace?–abaloghNov 29, 2012 at 9:04Ant-contrib, at least, can be brought in with no namespace declaration, then you can invoke its tasks like<try> ... </try>with no problems.–DavidNov 29, 2012 at 13:58Add a comment|
|
I have a build.xml-file that looks something like this:<taskdef uri="antlib:org.sonar.ant" resource="org/sonar/ant/antlib.xml" classpath="/path/sonar-ant-task.jar"/>
<target name="sonar">
<sonar:sonar/>
</target>And when I run the file I get:The prefix "sonar" for element "sonar:sonar" is not bound.Any obvious things I'm missing?
|
The prefix "sonar" for element "sonar:sonar" is not bound
|
Looks like thesquid:NoSonarrule is activated in the Quality Profile used by this project, precisely to avoid developers silently marking stuff asNOSONARi.e. sweep problems under the carpet.Moving forward:let the original issue be raised in SonarQube (the onesaying the method is not used anywhere)discuss it with your team to be sure it's a false-positiveclose it asFalse Positivein SonarQube (you can do that right form the UI when managing yourissues)get beerShareFolloweditedAug 18, 2016 at 8:36answeredAug 18, 2016 at 8:30Nicolas B.Nicolas B.7,2631818 silver badges2929 bronze badgesAdd a comment|
|
I have the below method which is showing a sonar issue saying the method is not used anywhere.@Provides
@ObjectMapperAnnotation
public ObjectMapper provideObjectMapper() { //NOSONAR
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JsonOrgModule());
return mapper;
}But this is a method that is called by the guice library and I do not have to call it explicitly. So in order to compress this issue I used the NOSONAR tag as shown above. But it still is showing a major issue as shown below.Is //NOSONAR used to exclude false-positive or to hide real quality flaw ?How can I avoid this issue being shown for using the NOSONAR tag? Any help would be much appreciated.
|
NOSONAR tag to ignore an invalid issue still shows as an issue
|
The JaCoCo measures test coverage based on percentage of bytecode which was actually executed. Declaring static final primitive or String constant creates no bytecode to execute, it's just an entry inside the constant pool. The only bytecode you have here is an implicit default constructor, usually like this:aload_0
invokespecial Object.<init>
returnSo when you don't call it, you have 0%, when you call it, you have 100%.My suggestion is to ignore this problem. You shouldn't try to achieve 100% coverage no matter what. After all it doesn't guarantee anything: even 100% covered code may contain serious bugs.ShareFolloweditedMay 8, 2015 at 10:17answeredMay 8, 2015 at 10:14Tagir ValeevTagir Valeev98.5k1919 gold badges226226 silver badges338338 bronze badges2Thanks @Tagir that makes sense. Do you know any workarounds? What if I use Enum?–Murat AyanMay 8, 2015 at 10:171Added a suggestion what to do.–Tagir ValeevMay 8, 2015 at 10:18Add a comment|
|
I have a class as following:public class XConstants {
public static final int A_TYPE = 1;
public static final int B_TYPE = 2;
}I am using both variables in my tests but when I examine the test coverage with Jacoco it shows %0 test coverage for this class. My guess is, it's because I never instantiate this class, just use its static variables. I tried creating an instance and test coverage went %100. How can I overcome this problem?
|
How to add static member variables Jacoco Test Coverage?
|
Documentation updated:https://docs.sonarqube.org/display/SONAR/Setup+and+Upgrade(credentials: admin/admin). You'll see the "Settings" link once you've logged in as a System administrator.ShareFolloweditedSep 6, 2017 at 18:14gliptak3,60222 gold badges3030 silver badges6262 bronze badgesansweredAug 27, 2013 at 23:32David RACODON - QA ConsultantDavid RACODON - QA Consultant3,99311 gold badge1313 silver badges1414 bronze badges62Doesn't work for SonarQube 6.–IgorGanapolskyOct 11, 2016 at 14:371Worked on SonarQube 5.6.6 User: admin, password: admin.–learnerJul 4, 2017 at 9:01Thanks..It helped a lot–Shalu T DNov 7, 2017 at 23:33This worked on 7.9–Justin RiceAug 28, 2019 at 1:20User: admin, password: admin. Worked for me too.–mujeeb.omrOct 25, 2021 at 6:24|Show1more comment
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question does not appear to be abouta specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic onanother Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.Closed10 years ago.Improve this questionI installed the SonarQube 3.7 in my localbox for Maven Projects (Maven 3), I can able to run the sonar and see the metrics. But i could not able to Log In as administrator in localhost:9000, what are the default login credentials for SonarQube after installation?And also i dont see the 'Settings' link on the top bar!
|
How to login into SonarQube in my local box [closed]
|
My proxy configuration works and looks the following way:http.proxyHost=proxy.domain.de
http.proxyPort=8888Note that there is no "http://" or anything else before the URL.Also, I do not use proxy authentication, so I left "proxyUser" and "proxyPassword" commented out.ShareFollowansweredMay 22, 2014 at 12:13TimStefanHauschildtTimStefanHauschildt59466 silver badges2121 bronze badgesAdd a comment|
|
I cannot get the proxy configuration to work for SonarQube 4.0 so that I can install plugins.When i openhttp://localhost:9000/updatecenter/availableit displays the error: "Not connected to update center. Please check your internet connection and logs."In sonar.log I read: "org.sonar.api.utils.HttpDownloader$HttpException: Fail to download [http://update.sonarsource.org/update-center.properties]. Response code: 403"In sonar.properties I configured it with the same proxy which I use for other programs:sonar.updatecenter.activate=true
http.proxyHost=<host>
http.proxyPort=<port>
http.proxyUser=<username>
http.proxyPassword=<password>I tried the same to configure in wrapper.properties, but it didn't work either by the way.For the proxy host I tried the short and the full name. For the username I tried just the username and with<DOMAINNAME>\<username>and<DOMAINNAME>\\<username>.Nothing of it worked. Any ideas?
|
SonarQube Proxy Configuration, Tricky
|
You can get The above Information Using The below table.1)projects, snapshots , metrics and project_measures. where projects table contain the Projects name . And for each project one snapshot id is created in certain period of time in snapshot table. then from snapshot table take the snapshot id and search it projects_measure table. and search the value of the descibed attribute using metric id.select distinct proj.name NAME_OF_PROJ, metric.description Description,
projdesc.value, snap.created_at CREATED_DATE
from projects proj
inner join snapshots snap on snap.project_id=proj.id
inner join (select max(snap2.created_at) as date_of_creation,id from snapshots snap2
where Date(snap2.created_at) in ('2011-12-20','2012-02-21')
and snap2.project_id in (5507,35252,9807,38954,23018,32390)
GROUP BY DAY(snap2.created_at),snap2.project_id ) as Lookup on Lookup.id=snap.id
inner join project_measures projdesc on projdesc.snapshot_id=snap.id
inner join metrics metric on projdesc.metric_id =metric.id
where metric.id in( 1,2...)ShareFollowansweredFeb 23, 2012 at 7:35user1227727user122772710411 bronze badge0Add a comment|
|
I am trying to generate a monthly report base on below factorLoC(lines of code)Rule Compliance %Comment %Public Documented API %Security ViolationsViolations (excluding Info)Duplicated Line %I tried to check the Entity relation ship in sonar database,all table are independent .
I am not sure from which table I should get the value so as to produce the report .For the hints below query is mentionedHint:select proj.name as ClassName, -- Class Name for which violation has been found out
proj.long_name as LongName, -- Long Class Name i.e. with package for which violation has been found out
rf.failure_level as ErrorLevel, -- Error level of the violation
rf.message as Violation, -- Cause of Violation
rf.line as LineNumber, -- Line number of the class file
ru.name ViolationName, -- Violation Description
ru.plugin_name PluginType -- Plugin tool by which this error has been detected i.e. findbug, PMD, etc.
-- ,ru.description -- (if violation description is required we can add this column) from projects proj inner join snapshots snap on proj.id = snap.project_id inner join rule_failures rf on rf.snapshot_id = snap.id inner join rules ru on ru.id = rf.rule_id
|
What is the sonar database structure?
|
Change yourkey()function to returnString[]rather thanStringthen you can pass various values usingString[]public @interface JIRA {
/**
* The 'Key' (Bug number / JIRA reference) attribute of the JIRA issue.
*/
String[] key();
}Use it like below@JIRA(key = {"JIRA1", "JIRA2"})ShareFollowansweredSep 28, 2012 at 9:55Amit DeshpandeAmit Deshpande19.1k44 gold badges4646 silver badges7272 bronze badgesAdd a comment|
|
I have a Annotation called@Retention( RetentionPolicy.SOURCE )
@Target( ElementType.METHOD )
public @interface JIRA
{
/**
* The 'Key' (Bug number / JIRA reference) attribute of the JIRA issue.
*/
String key();
}which allows to add annotation like this@JIRA( key = "JIRA1" )is there any way to allow this to happen@JIRA( key = "JIRA1", "JIRA2", ..... )the reason is, we currently annotate the test
against a Jira task or bug fix, but sometimes,
then the value will get parsed by sonar.
problem is a single test covers more then 1 bug.
|
how to create a single annotation accept multiple values in Java
|
I believe it is aSonarwarning. I thinkSonarwarnings are not must-do-rules, but just guides. Your code block isREADABLEandMAINTAINABLEas it is. It is already simple, but if you really want to change it you can try those two approaches below, and see if complexity becomes lower:Note: I don't have compiler with me now so there can be errors, sorry about that in advance.First approach:Map<String, String> multipliers = new HashMap<String, Float>();
map.put("country", country);
map.put("exchange", exchange);
map.put("ccp", ccp);
map.put("tenant", tenant);Then we can just use the map to grab the right elementreturn map.get(type) == null ? name : map.get(type).getName() + HOLIDAY_CALENDAR;2nd approach:All your objects have same method, so you can add anInterfacewithgetName()method in it and change your method signature like:getCalendarName(YourInterface yourObject){
return yourObject == null ? name : yourObject.getName() + HOLIDAY_CALENDAR;
}ShareFolloweditedNov 15, 2016 at 13:11answeredNov 15, 2016 at 11:09halilhalil8001616 silver badges3333 bronze badges2tried first approach already, but not able to call getName on map value–Amar MagarNov 15, 2016 at 12:49Use second approach then, introduce a new Interface with a getName() method in it. You should use benefits of polymorphism if you have a common behaviour/method.–halilNov 15, 2016 at 13:18Add a comment|
|
I want to reduce cyclomatic complexity of my switch case
my code is :public String getCalenderName() {
switch (type) {
case COUNTRY:
return country == null ? name : country.getName() + HOLIDAY_CALENDAR;
case CCP:
return ccp == null ? name : ccp.getName() + " CCP" + HOLIDAY_CALENDAR;
case EXCHANGE:
return exchange == null ? name : exchange.getName() + HOLIDAY_CALENDAR;
case TENANT:
return tenant == null ? name : tenant.getName() + HOLIDAY_CALENDAR;
default:
return name;
}
}This code blocks complexity is 16 and want to reduce it to 10.
country, ccp, exchange and tenant are my diffrent objects. Based on type I will call their respective method.
|
Reduce Cyclomatic Complexity of Switch Statement - Sonar
|
Sonar 3.2+This is supported since sonar 3.2 (August 2012) from an option in the adminstration.Ticket:http://jira.codehaus.org/browse/SONAR-1608Older versionsInthis feature-request SONAR-2743you can find a workaround for prior versions, that could work (don't forget to backup you database before even trying).It requires you to manually execute some sql-statements on the database.ShareFolloweditedJun 20, 2020 at 9:12CommunityBot111 silver badgeansweredMar 20, 2012 at 9:54oersoers18.6k1313 gold badges6767 silver badges7676 bronze badges1@Zitrax thx, I will add a screenshot of the new functionality as soon as 3.2 is released–oersJul 18, 2012 at 13:38Add a comment|
|
Due to the integration with Eclipse, the project key of my existing Sonar project needs to be changed. I can change the project key in the ant script and trigger a new analysis.However, Sonar considers it as a new project because the key is different now. This doesn't work for me because my existing project has quite a lot of history information.
How can I change the project key while preserving the analysis history? Or, is there a way to merge 2 sonar projects?
|
How to change the key of a sonar project while preserving the analysis history
|
This is from the Mailing Lists:Indeed, to import historical data you must use the "sonar.projectDate" property (Format is yyyy-MM-dd, for example 2010-12-25) [1] and launch a Sonar analysis on each tag/branch that you'd like to see in your project history.http://sonarqube.15.x6.nabble.com/re-ordering-historical-data-td3191565.htmlThere is an additionalBlogpostthat explains this further.ShareFolloweditedFeb 16, 2015 at 12:58schnatterer7,64977 gold badges6363 silver badges8181 bronze badgesansweredMar 29, 2011 at 7:01oersoers18.6k1313 gold badges6767 silver badges7676 bronze badges0Add a comment|
|
I would like to load the entire project history since its inception into Sonar.I would basically want to execute code like this:0) checkout version 1 from Subversion
1) checkout next version from Subversion
2) if the commit date is from the same day as the previous one - goto 1
3) run mvn sonar:sonar, overriding the build time with the time of the commit
4) if not on last commit - goto 1Is there a tool that does this already? Is there a way of convincing Sonar to use a different date than the current one?
|
How to re-analyze complete history of a project using Sonar?
|
The errors reported at the end of a SonarQube report are sometimes less helpful than the errors when you begin.Eg when I got this error, scrolling to the top of the log showed that I wasn't correctly setting the sonar.projectKey value, but this message the OP shared is still what showed up at the end.ShareFolloweditedMar 20, 2019 at 20:04answeredMar 20, 2019 at 19:18kayleeFrye_onDeckkayleeFrye_onDeck6,82855 gold badges7070 silver badges8484 bronze badges12this helped me. I found this error near the top: "Invalid project key. Allowed characters are alphanumeric, '-', '_', '.' and ':', with at least one non-digit."–sitting-duckSep 11, 2021 at 22:39Add a comment|
|
SonarQube is giving me below error when i integrate the xamarin app with jenkins on windows severSonarQube Scanner for MSBuild 3.0
Default properties file was found at C:\SonarQube\bin\SonarQube.Analysis.xml
Loading analysis properties from C:\SonarQube\bin\SonarQube.Analysis.xml
Post-processing started.
13:49:43.952 SonarQube analysis could not be completed because the analysis configuration file could not be found: C:\Users\Administrator\.jenkins\workspace\Xamarin-ProjectTemplate\.sonarqube\conf\SonarQubeAnalysisConfig.xml.
13:49:43.952 Post-processing failed. Exit code: 1I have followed the below guidehttps://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner+for+MSBuildSonarQube.Scanner.MSBuild.exe begin /k:"org.sonarqube:sonarqube-scanner-msbuild" /n:"Project Name" /v:"1.0"
MSBuild.exe /t:Rebuild
SonarQube.Scanner.MSBuild.exe endPlease help me to resolve this issue
|
SonarQube analysis could not be completed because the analysis configuration file could not be found
|
Well, the easiest way is for sure :Correct what Sonar is saying:)but let's assume that it's false positive.Here are the list of possible method to fix this issue :Since November 2014 :tag support// NOSONAR
the code who display Sonar erroris now fully supported by the JavaScript check (thanks @RPallas)When you don't control the Sonar :quite ugly methodtry {
the code who display Sonar error
} catch(err) { }If you catch any possible problem, Sonar can't detect something (thanks @JavaScript).But the best way is for sure to modify the configuration of Sonar :When you control Sonar :add a pluginTo use the CheckStyle plugin on Sonar : (http://checkstyle.sourceforge.net/)The solution will be to add a Checkstyle structured comment to the offending class to suppress a particular check.The suppression comment (SuppressionCommentFilter) format required is like this://CHECKSTYLE:OFF
the code who display Sonar error
//CHECKSTYLE:ONBut I send you to the documentation of this plugin (http://checkstyle.sourceforge.net/config.html)I hope this answer helps.ShareFolloweditedMay 23, 2017 at 10:29CommunityBot111 silver badgeansweredJul 9, 2015 at 14:30Valentin MontmirailValentin Montmirail2,62411 gold badge2525 silver badges5757 bronze badges1'correct what Sonar is saying' is off topic, and try/catch is a wrong answer. The direct simple answer below is just better.–Oleg MihailikJul 20, 2023 at 10:40Add a comment|
|
I am currently running Sonar for the static analysis of my code. When I was analyzing java files and wanted to suppress a certain warning, I used the @SuppressWarnings(nameOfTheWarningOnSonar) annotation. I wanted to know if there was a simple equivalent in Javascript to suppress specific warnings on Sonar.
|
Javascript equivalent of @SuppressWarnings?
|
The question is, which version of the sonarQube gradle plugin you are using:https://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner+for+GradleThe sonarqube gradle plugin sets some values per default, eg. if you use JaCoCo, which is probably the case, it automatically adds that field, besides the groovy one too.So generally speaking, you need to wait for an update of the sonarqube gradle plugin, which gets rid of this, and is using the other config value.Maybe you can also try to override the setting, by setting it to empty likesonar.jacoco.reportPath=ShareFollowansweredJul 3, 2017 at 19:08Simon SchrottnerSimon Schrottner4,41611 gold badge2525 silver badges3939 bronze badges1FYI.github.com/SonarSource/sonar-scanner-gradle/blob/master/src/…–NamoJan 14, 2020 at 5:47Add a comment|
|
Property 'sonar.jacoco.reportPath' is deprecated. Please use
'sonar.jacoco.reportPaths' instead.I keep getting this message when running SonarQube through Gradle and the phrase "reportPath" does not even appear even once in the entire multi-module project. I even put the sonarqube property under allprojects to override any defaults that may be there. Any tips on how I can get rid of this error?I am using:allprojects {
sonarqube {
properties {
property "sonar.jacoco.reportPaths", "${project.buildDir}/jacoco/test.exec"
}
}
}EDIT 1:Gradle wrapper 3.1Am using this in the root of build.gradleplugins {
id "jacoco"
id "org.sonarqube" version "2.5"
}And tried your suggestion withallprojects {
sonarqube {
properties {
property "sonar.jacoco.reportPath", ""
property "sonar.jacoco.reportPaths", "${project.buildDir}/jacoco/test.exec"
}
}
}No dice, what do you think?
|
Property 'sonar.jacoco.reportPath' is deprecated. Please use 'sonar.jacoco.reportPaths' instead
|
Inhttp://jenkinsInstance/configureI had setup SonarQube only in "SonarQube servers" but not in "Quality Gates" as well.ShareFollowansweredFeb 12, 2017 at 17:47bskybsky19.7k5252 gold badges160160 silver badges275275 bronze badgesAdd a comment|
|
I'm trying to user Sonarqube with Jenkins.I've added the Quality Gates Plugin, to fail the build in Jenkins if the Quality Gates are not respected in Sonarqube.However, as you can see below, there is noProject Keyfield for Quality Gates.Also, if I try to save the configuration, I get:JSONObject["projectKey"] not found.Any idea why this would not appear?
|
Can't fill in Project Key for quality gates plugin
|
You can configure it on the SonarQube server:Global: Settings → General → SCM → SVNPer project: Settings → General Settings → SCM → SVNShareFolloweditedJan 29, 2016 at 13:56Harald Wellmann12.7k44 gold badges4242 silver badges6464 bronze badgesansweredJul 17, 2015 at 7:58agabrysagabrys8,89833 gold badges3535 silver badges7575 bronze badgesAdd a comment|
|
I have a java maven web project, I have alsoJenkins 1.620andSonarQube 5.1.1.I have added in jenkins a maven post action with SonarQube setting the jdk as 7u79, the same used by the project.When I run the jenkins task, I get on the console next error:[ERROR] Failed to execute goal org.codehaus.mojo:sonar-maven-plugin:2.6:sonar (default-cli) on project *****: The svn blame command [svn blame --xml --non-interactive -x -w src/main/java/*****.java] failed: svn: PROPFIND request failed on '/*****/trunk/src/main/java/*****.java'
[ERROR] svn: PROPFIND of '/*****/trunk/src/main/java/*****.java': authorization failed (http://*****.*****.*****)
[ERROR] -> [Help 1]It seems that I have to put login information forSVNinSonarQubetask for a Maven project in Jenkins, but I have not found any documentation on that, and I do not know if it should be asMAVEN_OPTSor Additional Properties, and also the syntaxis.Thanks in advance.
|
SVN authentication failure when running a Sonar analysis in Jenkins 1.620 SonarQube 5.1.1
|
You can't putInteger::toStringbecauseIntegerhas two implementations that fit to functional interfaceFunction<Integer, String>, but you can useString::valueOfinstead:Stream.iterate(0, i -> i + 1)
.limit(100)
.map(String::valueOf)
.collect(Collectors.toList())ShareFolloweditedDec 10, 2018 at 23:56answeredDec 10, 2018 at 23:27UladUlad1,09388 silver badges1717 bronze badges41You can't putInteger::toStringbecause it acceptsintand your case you haveIntegeruse.That's not correct. Lambdas can implicitly box and unbox.–shmoselDec 10, 2018 at 23:29@shmosel then why does itIntStream.range(1, 100).mapToObj(Integer::toString).collect(Collectors.toList())work?–UladDec 10, 2018 at 23:31Because theintoverload is more appropriate for a primitive stream.–shmoselDec 10, 2018 at 23:32@shmosel yes, you are right aboutLambdas can implicitly box and unbox–UladDec 10, 2018 at 23:58Add a comment|
|
This question already has answers here:How to fix ambiguous type on method reference (toString of an Integer)?(3 answers)Invoking toString via method reference in Java 8(1 answer)Closed5 years ago.I have the following code. Sonar is complaining replace this lambda with a method reference.Stream.iterate(0, i -> i + 1).limit(100).map(i -> Integer.toString(i));If I replace it with it code below, it does not compile with compilation error: Type mismatch: cannot convert fromStream<Object>to<unknown>.Stream.iterate(0, i -> i + 1).limit(100).map(Integer::toString);How isInteger::toStringconvertingStream<Object>to<unknown>?
|
Replace this lambda with a method reference [duplicate]
|
There's a public free instance of Sonar athttps://sonarcloud.iowhich is free for open source projectsShareFolloweditedJul 26, 2020 at 3:37draganHR2,68822 gold badges2222 silver badges1515 bronze badgesansweredApr 1, 2013 at 14:51ppapapetrouppapapetrou1,65399 silver badges1313 bronze badgesAdd a comment|
|
Closed.This question is seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. You can edit the question so it can be answered with facts and citations.Closed8 years ago.Improve this questionI know that for Apache foundation projects there ishttps://analysis.apache.org/Is there free Sonar instance for open-sourced projects?UPDATE: ASF Sonar Instance isdeprecated and removedas of 29th November 2019.
|
Free Sonar instanse for open-sourced projects [closed]
|
I have build a plugin for running Scalastyle on SonarQube. It comes with the default Scalastyle Quality profile and you can create or customise quality profiles.github.com/emrehan/sonar-scalastyleShareFollowansweredOct 1, 2014 at 5:59Han TuzunHan Tuzun47111 gold badge55 silver badges99 bronze badges11github.com/NCR-CoDE/sonar-scalastyleis a more updated repo of the same code.–Chris JonesJan 4, 2016 at 19:08Add a comment|
|
Is there basic ruleset/quality profile for SonarQube for the Scala language?I couldn't find any and it's hard to imagine that everyone starts with an empty ruleset.
|
Where is a Scala profile for SonarQube?
|
For me, you can let the CSS / SCSS files empty.
Just because after the build everything around styling will be minified and contained the "styles.js" file.
So, even if it's a bit ugly to see all these empty files in dev mode, the compiler will solve your probelm by itselfthis is a screen of your project after build :ShareFollowansweredApr 2, 2019 at 7:36Hadrien DelphinHadrien Delphin60011 gold badge66 silver badges1919 bronze badges31this falls under major issue for sonar thoughrules.sonarsource.com/css/RSPEC-4667–Abhishek AnandOct 16, 2020 at 11:18@AbhishekAnand yes, but keep in mind, that the empty files are there pre build. During the build webpack will merge the styles in one or two file (js files BTW). So keep empty styles inside your Angular project is actually not an issue.–Hadrien DelphinNov 3, 2020 at 16:59agreed. it's just weird is what I meant. this just shows meaningless major in sonar–Abhishek AnandNov 5, 2020 at 8:45Add a comment|
|
When I create Angular application, I am using CLI for generating components. After certain time of developing app I have style file for every component but major part of them are empty.When I check sonar I have Code smells in empty style files:Remove this empty stylesheet.Add an empty new line at the end of this file.Should I remove sonar rules or I must delete all empty style files in project and recreating them in next versions of project when I need them for component styling? What are best practices?
|
Empty style (.css/.scss) files
|
One ugly solution I used so far is to useSonar Web API.I add onecurlcommand in the end of job (build steps) to fetch the needed metrics likecurl http://sonar.sh.cn.ao.ericsson.se//api/resources?metrics=qi-quality-index,coverage,test_success_density&resource=54936 --output sonar-result.xmlThen I archive thesonar-result.xmlto make it visible inside the job.ShareFolloweditedOct 26, 2015 at 8:58Yogi9,43922 gold badges4646 silver badges6262 bronze badgesansweredOct 13, 2012 at 13:59Larry CaiLarry Cai57.6k3434 gold badges112112 silver badges161161 bronze badges3Hey Larry, just curious if you've found anything new in regard to this, as I'm about to implement something similar. Cheers!–JoeBJan 28, 2013 at 15:26no, not checked further, leave your solution if you can do more–Larry CaiJan 30, 2013 at 1:251You can actually parse the json in the jenkins shell with jq, and get the status. So you don't need to save the result in a file etc.–Somaiah KumberaMar 10, 2017 at 8:49Add a comment|
|
There is asonar plugin for jenkins, it triggers the sonar build inside CI (jenkins), it is useful.While now I want to see the sonar result inside jenkins without jumping to sonar websites, it is useful if I just want to see some key data for this job.It could be sonar-report plugin in jenkins.Do you have similar needs ?
|
how to publish sonar result in jenkins server, or do we have sonar-report jenkins plugin
|
There's no option to "add" a project in Sonar from Sonar UI. Projects are automatically added to Sonar whenever a successful analysis occurs.
I'd suggest you the following :Upgrade to a more recent Sonar version.http://www.sonarqube.org/downloads/Read theanalyzing source code guidewhere you can find instructions for all available methods to trigger a new analysisUpdate: Sonarqube allows (I think after 5.x version) provisioning of projects as described in theirdocumentationShareFolloweditedOct 26, 2017 at 10:15answeredJul 1, 2013 at 7:46ppapapetrouppapapetrou1,65399 silver badges1313 bronze badges2Hi, I have sonar and maven installed on two different host. Would the command mvn sonar:sonar work?? Is there anywhere in maven I need to define the url of sonar or any other update in pom.xml??–user2537893Jul 2, 2013 at 4:571Yes you can, but you still haven't read the instructions :docs.codehaus.org/display/SONAR/Analyzing+with+Maven–ppapapetrouJul 2, 2013 at 7:13Add a comment|
|
I am using sonar to review my code for a java project. the version that I am using is v.2.9, I am using sonar for the first time. I have no idea how to add project in sonar server.
Please help on thisThanks.
|
Adding a new project to Sonar v.2.9
|
The easiest thing would be to useEclipseand clickClean-upon the whole project. InClean-upprofile configuration selectCode styletab. There you can selectUse blocks in if/while/for/do statementsasAlways.ShareFollowansweredNov 11, 2012 at 22:50ShyJShyJ4,61011 gold badge2020 silver badges1919 bronze badges9so this can just run against the entire code-base as a single operation? I could set it off and go get a coffee while it's doing its thing? sounds like the right answer if so!–robertNov 11, 2012 at 23:02It depends on how big the code is and how long it takes you to drink coffee. But yes, it's a single operation for the entire code-base.–ShyJNov 11, 2012 at 23:05it will be a 'vente' at least–robertNov 11, 2012 at 23:08If this works reliably for you, then it seems an easy solution, unless you are unskilled at drinking coffee. If it does not work out, I know of truly language aware tool that can do this easily and reliably.–Ira BaxterNov 12, 2012 at 0:223Update before the reformatting, and check-in before making further changes. This will simplify backing out the change if necessary.–BillThorNov 12, 2012 at 3:19|Show4more comments
|
I want to reduce the number of sonar violations in a large legacy java code-base, and it seems a "quick win" would be to update all these conditional statements to have curly brackets. This seems like an easy thing to do and I can't see why it wouldn't be readily automatable.Does anybody know of a tool that could perform a bulk operation like this? Or why to do such a thing might be a bad idea before I go and spend the time writing something myself? If I were to write one myself what would be the best tools to use? Ideally something that is java language aware, so that I don't have to deal with formatting corner-cases and the like.The rule is non-negotiable by the way, so this really is the best approach.
|
automatically add curly brackets to all if/else/for/while etc. in a java code-base
|
You want to use the connected mode in order to apply the same ruleset on your IDE that the one running on your SonarQube instance.
Have a look at the relevant documentation :http://www.sonarlint.org/eclipse/#ConnectedShareFollowansweredMay 6, 2016 at 9:04benzonicobenzonico10.7k55 gold badges4444 silver badges5151 bronze badges28Can I have diff rule set for my local machine means can I disable some rules which are enable on remote server–Nishant ModiMay 23, 2016 at 5:57Yes you can do an initial sync and then unchecked the rules in the Rules tab under SonarLint general settings–Sudheep VallipoyilNov 1, 2019 at 7:35Add a comment|
|
I have SonarLint installed in Eclipse and there is a remotely set up sonarQube server, but rules are different on both . How can I configure rules same as SonarQube on SonarLint in my Eclipse ?
|
How to enable/disable any rule from SonarLint in Eclipse
|
You only need to configure thesonar.host.url. All communication between scanner and server is done with web services, and the scanner no longer talks to the database at all.ShareFollowansweredFeb 5, 2016 at 18:50G. Ann - SonarSource TeamG. Ann - SonarSource Team22.5k44 gold badges4242 silver badges8484 bronze badges1Currently I am also facing the same issue and is there any way I can connect to MySQL to store the details.This issue is happening only after upgrading to SonarQube 6–Mahesh GApr 17, 2017 at 15:00Add a comment|
|
I am using sonarqube 5.3 latest version and when I configure the sonar jdbc properties in my properties file usingproperty "sonar.jdbc.url", "jdbc:mysql://localhost:3306/sonar")
property "sonar.jdbc.username", "root")
property "sonar.jdbc.password", "root")I get warning messageProperty 'sonar.jdbc.url' is not supported any more. It will be ignored. There is no longer any DB connection to the SQ database.
Property 'sonar.jdbc.username' is not supported any more. It will be ignored. There is no longer any DB connection to the SQ database.
Property 'sonar.jdbc.password' is not supported any more. It will be ignored. There is no longer any DB connection to the SQ database.How to configure external database and not use embedded database provided by sonarqube?
|
sonar jdbc properties are not supported anymore in sonarqube 5.3 version
|
try this:sonar.projectKey=org.mycompany.acc
sonar.projectName=Account
sonar.projectVersion=1.0
sonar.sources=src # try to remove this by the way if you don't have suchdirectory under root folder of project
sonar.modules=invoice,receipt
invoice.sonar.projectName=Invoice
invoice.sonar.sources=invoice/src
receipt.sonar.projectName=Receipt
receipt.sonar.sources=receipt/srcShareFollowansweredMay 25, 2016 at 20:50Мокич АндрейМокич Андрей35444 silver badges77 bronze badges4works with sonarqube version 6, SonarQube Scanner 2.8–JeevananthamFeb 10, 2017 at 6:551Doesn't work for me in Sonar 6.2 perdocs.sonarqube.org/display/SCAN/…–MarkHuFeb 14, 2017 at 6:153As per the docs link above, you can achieve a similar thing by putting a nestedsonar.propertiesfile inside each module directory, and override just the relevant settings.–Cam JacksonSep 10, 2018 at 7:19sonarqube scanner 3.3 works in our ends–mochadwiDec 4, 2021 at 6:15Add a comment|
|
SonarQube Server 5.1.2, Sonar-Runner 2.4As provide inMulti-moduleProjecti have created a project structure asAccounts
|
->invoice
|
->src
->receipt
|
->src
->sonar.propertiesFile:sonar.propertiessonar.projectKey=org.mycompany.acc
sonar.projectName=Account
sonar.projectVersion=1.0
sonar.sources=src
sonar.modules=invoice,receipt
invoice.sonar.projectName=Invoice
receipt.sonar.projectName=ReceiptWhen execute with above configuration in sonar-runner i encountered with error "src" folder is missing in "Account" directory, hope this configuration is same as the conf available in that link. As per the understanding if the configuration is fine then the Invoice and Receipt will be listed assub projectunder Account Project, so what are the changes are required in above configuration to achieve multi module / project under one project.ERRORERROR: Error during Sonar runner execution
ERROR: Unable to execute Sonar
ERROR: Caused by: The folder 'src' does not exist for 'org.mycompany.acc' (base
directory = C:\Users\xyz\Accounts\.)
ERROR:
ERROR: To see the full stack trace of the errors, re-run SonarQube Runner with t
he -e switch.
ERROR: Re-run SonarQube Runner using the -X switch to enable full debug logging.
|
Multi module project analysis with SonarQube
|
These steps apply to sonar 6.7Create a new profilemy wayby copying the default.Activate that profile for your sonar projectYou may also want to set that profile as a defaultOpen the new profilemy wayDeactivate the rule you want to changeActivate the rule again.Get id in description:Search for id in rules:Finally you can set a new severity level
(You'll find the activation button at the button of the description)ShareFolloweditedJul 12, 2019 at 9:58answeredJun 1, 2018 at 20:44Matthias MMatthias M13.6k1717 gold badges9494 silver badges123123 bronze badgesAdd a comment|
|
Can anyone tell me how exactly to change severity of the rule in sonar?
There is a special section in sonar for activities like this - Quality Profiles. But the opportunity of changing severity is disabled.How to make it enabled? Maybе I need some special rights for those activities? If so, what are these rights?Thanks in advance.
|
How to change severity of the rule in sonar?
|
Here are the tools I'm aware of (and just aware):There is CodeNarc that you mentioned.There is alsoGMetrics.And Grails has aTest Code Coverage Plugin.But nothing ready to be used with Sonar AFAIK. I'm watchingSONARPLUGINS-194about this but there isn't much activity although some work has been reported very recently, maybe be you :)ShareFollowansweredFeb 23, 2010 at 18:49Pascal ThiventPascal Thivent566k138138 gold badges1.1k1.1k silver badges1.1k1.1k bronze badges0Add a comment|
|
Sonar is an application for integrating output from several static and test analysis tools into a comprehensive overview of the software's quality.Unfortunately, most of those analysis tools (PDM, FindBugs, etc.) do not support Groovy and, by extension, Grails.We've found tools called CodeNarc and GMetrics which perform some of the analysis, but not test coverage, and we're working on a Sonar plugin to import the CodeNarc output. As I said, though, this is incomplete.Does anyone know of a better set of complexity/rules-based static analysis tools that can handle Groovy, as well as a Grails test coverage metric? Of course, one with a Sonar plugin for reading in the output would be best.
|
Groovy/Grails plugin for Sonar
|
Regardless of what youcompileyour code with, the SonarQube analysis should berunwith a specific Java version.You simply need to usedifferent JDK versionsfor thecompilationandanalysis.ForSonarQube 6.* compatibility], make sure the JAVA_HOME=/path/to/java8ForSonarQube 9.* compatibility], make sure the JAVA_HOME=/path/to/java11ShareFolloweditedFeb 28, 2022 at 16:31Ahmed Nabil18.1k1212 gold badges6464 silver badges9191 bronze badgesansweredOct 28, 2016 at 11:42G. Ann - SonarSource TeamG. Ann - SonarSource Team22.5k44 gold badges4242 silver badges8484 bronze badges3Sure @G. Ann - SonarSource Team I will check this method and update back Thanks!!–Mahesh GOct 28, 2016 at 12:182Thanks It worked like charm by installing Java 8 !! Now I wanted a permanent solution Where My Code should compile with 1.7 and my SonarQube should with Java 8 How can i do that -target 1.7 can you please help me with this.–Mahesh GOct 28, 2016 at 17:48Will this work with Java 17 as well? Getting issue for java 17: An API incompatibility was encountered while executing org.sonarsource.scanner.maven:sonar-maven-plugin:3.9.1.2184:sonar: java.lang.ExceptionInInitializerError: null–RagasAug 16, 2023 at 13:15Add a comment|
|
Can anyone help me in getting solution for the below error.Below are the version of the components to configureSonarQube 5.1.2Soanr-Runner 2.4Java 1.7 [I have to use 1.7 only since my code supports only 1.7]mavn 3.3.9sonar-cobertura-plugin-1.6.3sonar-findbugs-plugin-3.3cobertura 2.6Execution commandmvn -fn -e org.sonarsource.scanner.maven:sonar-maven-plugin:RELEASE:sonar -Dsonar.jdbc.url="jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance" -Dsonar.host.url=http://localhost:9000 -DskipTestsIn Console Window I am getting error[ERROR] Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:
3.2:sonar (default-cli) on project NWT_Core: Execution default-cli of goal org.s
onarsource.scanner.maven:sonar-maven-plugin:3.2:sonar failed: Unable to load the
mojo 'sonar' in the plugin 'org.sonarsource.scanner.maven:sonar-maven-plugin:3.
2' due to an API incompatibility: org.codehaus.plexus.component.repository.excep
tion.ComponentLookupException: org/sonarsource/scanner/maven/SonarQubeMojo : Unsupported major.minor version 52.0
|
Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin: 3.2:sonar
|
I couldn't find a way to do this using the built in NUnit runner. I managed to get it working by using a powershell build step to manually call the required commands.First step is to run the NUnit tests via Gallio within a dotCover cover call:& dotCover cover `
/TargetExecutable="C:\Program Files\Gallio\bin\Gallio.Echo.exe" `
/TargetArguments="/report-type:XML /report-name-format:test-report /runner:IsolatedProcess /report-directory:.\Gallio .\Path\Test.dll" `
/Filters="+:WhatToCover" `
/Output=coverage.snapshotThe Gallio test report is then available to be picked up by Sonar with reuseReport, TeamCity automatically detects the test results.You can make TeamCity directly process the coverage snapshot by writing aservice messageto standard output:Write-Host "##teamcity[importData type='dotNetCoverage' tool='dotcover' path='coverage.snapshot']"To get the coverage info into a format usable by Sonar you need to use the dotCover report command and theundocumented report type TeamCityXML:& dotCover report /Source=coverage.snapshot /Output=coverage-report.xml /ReportType=TeamCityXMLShareFolloweditedJan 9, 2013 at 19:22answeredNov 2, 2012 at 10:07Jeff JohnstonJeff Johnston2,16611 gold badge1414 silver badges2727 bronze badgesAdd a comment|
|
I'm trying to integrate the sonar analysis into by TeamCity build process. I have a NUnit build step which runs my unit tests and then runs dotCover for the coverage.My next step is the sonar-runner. The configuration that currently exists is; gallio.mode=dotCover, sonar.gallio.mode=reuseReport but I also need sonar.gallio.reports.path.Does anybody know the path to the dotCover report generated in the the previous step?
|
TeamCity dotCover report path for Sonar
|
There are 2 ways to inject vault secrets into the k8s pod as ENV vars.1) Use the vault Agent InjectorA template should be created that exports a Vault secret as an environment variable.spec:
template:
metadata:
annotations:
# Environment variable export template
vault.hashicorp.com/agent-inject-template-config: |
{{ with secret "secret/data/web" -}}
export api_key="{{ .Data.data.payments_api_key }}"
{{- end }}And the application container should source those files during startup.args:
['sh', '-c', 'source /vault/secrets/config && <entrypoint script>']Reference:https://www.vaultproject.io/docs/platform/k8s/injector/examples#environment-variable-example2) Use banzaicloud bank-vaultReference:https://banzaicloud.com/blog/inject-secrets-into-pods-vault-revisited/.Comments:Both methods are bypassing k8s security because secrets are not stored in etcd.
In addition, pods are unaware of vault in both methods.
So any one of these can be adopted without a deep comparison.For vault-k8s and vault-helm users, I recommend the first method.ShareFolloweditedFeb 5, 2021 at 3:25answeredFeb 5, 2021 at 3:19James WangJames Wang77311 gold badge55 silver badges1313 bronze badgesAdd a comment|
|
I'm trying to install Sonarqube in Kubernetes environment which needs PostgresSQL.
I'm using an external Postgres instance and I have the crednetials kv secret set in Vault.
SonarQube helm chart creates an Environment variable in the container which takes the username and password for Postgres.How can I inject the secret from my Vault to environment variable of sonarqube pod running on Kubernetes?Creating a Kubernetes secret and using the secret in the helm chart works, but we are managing all secrets on Vault and need Vault secrets to be injected into pods.Thanks
|
Injecting vault secrets into Kubernetes Pod Environment variable
|
I'm facing a similar issue, illustrated by this example:
SonarLint 2.0.2: 99 issues. SonarQube 5.4 UI: 116 issues.
Differences caused by 2 rules which belong to the Checkstyle Plugin.As you are talking about "Variable could be declared final" I'm assuming the rule behind your missing issues ispmd:LocalVariableCouldBeFinal, which belongs to the PMD Plugin.Fabrice has commented on this topic in SonarQube Google Group they"won't add support for any external engine":SonarQube Google Group(this is true for PMD, Checkstyle, Findbugs and others...)So sadly we can only use rules mentioned inSonarLint rules listwhich are provided by SonarQube out of the box (i.e. their Java Plugin).ShareFollowansweredMay 12, 2016 at 10:35Jan S.Jan S.15677 bronze badges2I see! Thanks a lot for the explanation about external engines, now it makes much more sense.–UhlaMay 17, 2016 at 11:32A very good answer indeed! Perhaps, the remedy would be for people to create a new Quality Profile in SonarQube, making use of the mapping of rules and then activate that profile instead of what's available in FindBugs and PMD. I guess this should be a new feature request for the SonarQube product---uplifting FindBugs based profile to SonarSource analyzer.–JaywalkerSep 7, 2017 at 11:56Add a comment|
|
We are using SonarQube server version 5.3 with SonarLint 2.0 in connected mode.
As an IDE we use Eclipse Mars 2.0 and when we compare results found by SonarQube server with results found by SonarLint within IDE, the results differ (example file274 errors in IDE,826 issues in SonarQube!).One of the usual differentiations is that "Variable could be declared final".Also one of my colleagues who is using SonarLint for IntelliJIdea is having similar issues (Idea version 2016.1.1, SonarLint 2.0.2, example file - same as used for comparison in IDE293 errors).I wonder why there are such differentiations against the server and even between IDEs.Could someone help me out on this? Thanks.
|
SonarLint is not showing all records compared to referenced SonarQube server
|
Seems it doesn't detect files in sub-folders using ".". Only way I was able to get it working was to list all of the folders.sonar.sources=helpers,managers,routes,schemas,types
sonar.tests=helpers,managers,routes,schemas,types
sonar.exclusions=**/*.js,test-data,dist,coverage
sonar.test.inclusions=**/*.spec.ts
sonar.testExecutionReportPaths=test-report.xml
sonar.javascript.lcov.reportPaths=coverage/lcov.infoShareFolloweditedMay 16, 2023 at 20:43patyx33411 gold badge33 silver badges1818 bronze badgesansweredAug 12, 2019 at 19:46JarethJareth43111 gold badge33 silver badges1616 bronze badgesAdd a comment|
|
I am using TypeScript and Jest and have my tests next to my source files. e.g:someDirsomeCode.tssomeCode.spec.tsWhen I try and import the text-report.xml (which looks to be fine and matches the format), I get an error saying:'Line X report refers to a file which is not configured as a test file: /someDir/someCode.spec.ts'What configuration do I need in in the Sonarqube properties so that it understand which files are tests and which are source?
|
Sonarqube test report "report refers to a file which is not configured as a test file" when tests and source are together
|
You could do this:Call the APIapi/metrics/searchfirst to get a (json) list of all the metrics and then iterate over that list and create a comma separated string of all the metric keys.For example something like this:ncloc,complexity,violations.. as mentioned in the parameters example value in the API documentationhere.Then you could just add this comma separated list to the url as a parameter something like:http://MY_HOST/api/measures/component?metricKeys=ncloc,complexity,violations&component=project_keyand call it once to get the response for all metrics.Also, I haven't tried this, but as per the latest documentation, the parametercomponentis optional. So if you omit that, ideally you should get a response with metrics of all the projects.ShareFolloweditedApr 7, 2020 at 0:52answeredNov 28, 2018 at 18:43SumitSumit2,33977 gold badges3535 silver badges5555 bronze badges4In my version of SonarQube (6.3), that last parameter (component) should be named componentKey–Per Quested AronssonAug 16, 2019 at 6:51Done, works awesome! Does anyone know how to get a detailed metric info? All i get is this for all metrics { "metric": "code_smells", "bestValue": false, "value": "48" }–Aakanksha ChoudharyMar 4, 2020 at 18:14Here you can get detailed metric info:docs.sonarqube.org/latest/user-guide/metric-definitions–Raphael AmoedoNov 19, 2021 at 12:17is there a way to get measures values user wise?–Milinda KasunMay 25, 2022 at 6:12Add a comment|
|
My question:I am using SonarQube version 7.1 and trying to extract the metrics and quality gate related to individual projects.What we have triedWe were using Python SonarQube API to extract these data before our company upgraded to version 7.1. "api/resources" web service Deprecated since sonarqube5.4, so we cannot use it anymore.I have also tried using getting data using CURL command via Web API using
curl -i -H "Content-Type: application/json" -H "x-api-key:token" -X GET 'http://MY_HOST/api/measures/component?metricKeys=key&component=project_key'We are able to get a json payload for individual metrics, but involves tedious task of creating the URL every single time.But I wanted to know if there is a better/smarter way to access these "measures", be it any language or implementation.
|
SonarQube REST APIs : Read Metrics for individual projects
|
We've created a MMF to allow usage of badges on project that requires authentication :https://jira.sonarsource.com/browse/MMF-1178Unfortunately there's no workaround nor ETA.ShareFollowansweredMay 4, 2018 at 14:28Julien L. - SonarSource TeamJulien L. - SonarSource Team2,5771717 silver badges1515 bronze badges3FYI nowadays this seems to be fixed, but only for the cloud version: Julien Lancelot - 25/Feb/20 3:41 PM: "this MMF was only implemented on SonarCloud"–JulianDec 14, 2020 at 16:54Any update on the above? I'm unable to access the Jira project to check, but having Private projects onSonarQube(notCloud) is causing broken images for the badges...–Rob CJan 3 at 22:15Hi, As this post is very old, I recommend you either to start a new question here or use the Sonar community forum:community.sonarsource.com–Julien L. - SonarSource TeamJan 5 at 8:16Add a comment|
|
We are testing out the new project badge URL's in version 7.1As describedin the release notesThe thought was to, e.g., include this in README's on github.
However, as our Sonarqube instance requires login, these URL's do not work.Is there a workaround for this?
Or a feature planned to allow unauthorized access to badge URL's?
|
Sonarqube 7.1 project badge URL without authentication
|
You can have a look atthis sample projectwhere the path to a LCOV report is specified in thesonar-project.propertiesfile.Note that some property names have changed in the last version of the Javascript plugin.ShareFolloweditedSep 14, 2017 at 10:18answeredApr 2, 2013 at 9:02Fabrice - SonarSource TeamFabrice - SonarSource Team26.6k33 gold badges6363 silver badges5858 bronze badges72Ah, looking at the link you posted, I see that the trick was to add this: sonar.javascript.jstestdriver.coveragefile=target/test-coverage/jscover.lcov sonar.javascript.lcov.reportPath=target/test-coverage/jscover.lcov–grayaiiApr 2, 2013 at 14:193The JsTestDriver no longer exists. They do haveanother Javascriptproject which I found helpful.–cazzerApr 11, 2014 at 15:32@Fabrice-SonarSourceTeam the paths that are generated by istambul. which is used by karma coverage are absolute and in the example they are relative. How are most teams solving this issue?–miguelrNov 29, 2016 at 7:21@miguelr If you run both karma and then SonarQube scanner from the root folder of your project, this should be fine - even if the path are absolute.–Fabrice - SonarSource TeamNov 29, 2016 at 13:19Thanks for the notification, I changed the link to another project that is maintained.–Fabrice - SonarSource TeamSep 14, 2017 at 10:19|Show2more comments
|
We have a Jenkins job that contains a bunch of javascript files.
We build our project via grunt, and at the end of the build we run JSCover to run our unit tests and collect code coverage. It all works. We get a nice LCOV file.We now want to upload the LCOV file to Sonar, and I'm not sure how to do this.
We are building our project from Jenkins as a free style project.I tried playing around with various project properties for sonar, but no love:# project metadata (required)
sonar.projectKey=my.project
sonar.projectName=My Project
sonar.projectVersion=1.0
# path to source directories (required)
sonar.sources=src
# The value of the property must be the key of the language.
sonar.language=java (I tried js and javascript, but no love. Plugin is not installed. Actually, I don't care about the language, since I am already generating the LCOV file during the build. I just need Sonar to use this LCOV file.)
# Advanced parameters
sonar.javascript.jstestdriver.reportsfolder=target/surefire-reports
sonar.javascript.jstestdriver.coveragefile=target/test-coverage/jscover.lcov
sonar.dynamicAnalysis=reuseReportsI suspect the problem is under the "Advanced Parameters", but I don't know how to tell Sonar, "Please use my LCOV file for Code Coverage".
|
How to tell Sonar to use my LCOV file for Code Coverage
|
I checked theSonarHTMLplugin source code and for my understanding you have to add//NOSONARat the line which should be ignored. In your case it should be:<template data-sly-template.step>
<!-- //NOSONAR --><li
data-sly-use.localStep="MyAdapter"
data-sly-test="${(wcmmode.edit && localStep.start) || !wcmmode.edit}"If you compress the source code then the solution is safe to use. If not, you have to be aware that all those<!-- //NOSONAR -->will be send to your client. It means that the resources usage will be bigger (for example network bandwidth - more bytes to send).//NOSONARis handled byorg.sonar.plugins.html.visitor.NoSonarScanner:source codetest classShareFolloweditedFeb 20, 2023 at 12:14answeredNov 5, 2019 at 20:28agabrysagabrys8,89833 gold badges3535 silver badges7575 bronze badges21Thanks @agabrys. It works. As a complement, to avoidNOSONARin output. I made it as a HTL comment, like this:<!--/* */-->–josivanNov 8, 2019 at 14:24//nosonar for HTL issues still needs to be implemented ingithub.com/wttech/AEM-Rules-for-SonarQube/issues/230–BenMay 23, 2022 at 11:40Add a comment|
|
I have a scenario where there is an AEM template file and in this file, I have a single<li>element. In other words, I have a loop inside that generate a list of items.<template data-sly-template.step>
<li
data-sly-use.localStep="MyAdapter"
data-sly-test="${(wcmmode.edit && localStep.start) || !wcmmode.edit}"But, the Sonar's ruleRSPEC-1093is complaining that:"<li>"and"<dt>"item tags should be in"<ul>","<ol>"or"<dl>"container tags.In this case, is not a bug, once that the<ul>is outside of the template. The output file is a well-generated HTML file with no errors.I'm trying to useNOSONARin html file. I have tried<!-- NOSONAR -->and<!-- //NOSONAR -->, but is not working.How can I mark this line in HTML file to be ignored by sonar rules?
|
How can I mark this line in HTML file to be ignored by sonar rules?
|
You are basically hitting this problem :https://jira.sonarsource.com/browse/SONARJAVA-1113Which was that the// NOSONARwas not taken into account in tests.This has been fixed in the latest release of the sonar java plugin release (3.11)(On a side note, using NOSONAR is not great IMO, you should keep track of issue you don't want to fix using SonarQube rather than cluttering your code with comments that are linked to a specific external tool)ShareFollowansweredMar 2, 2016 at 8:38benzonicobenzonico10.7k55 gold badges4444 silver badges5151 bronze badges32Thanks. A side-note about the side-note: it's true for SonarQube, but not an option currently for the SonarLint plugin.–ytgMar 2, 2016 at 9:026Disagree with the note 'on a side'. When you have a good reason to disable a line I personally wouldn't want to be bothered anymore with 'problems'. Adding the comment // NOSONAR still enables you to keep track of these exceptions with a simple search. And you could add an extra comment explaining the reason of the exception.–JosMar 4, 2019 at 11:18How do you ignore a line in an XML file?–CalumAug 16, 2021 at 10:09Add a comment|
|
Sonar complains about a line.Thread.sleep(SLEEP_TIME); // NOSONARIts problem is that"Thread.sleep" should not be used in testsUsing Thread.sleep in a test is just generally a bad idea. It creates brittle tests that can fail unpredictably depending on environment ("Passes on my machine!") or load.And it makes sense, this should be fixed. But my problem is: why doesn't theNOSONARpart has any effect here? It seems to work in other parts of the code where it's used, e.g. withpublic static final String PASSWORD_FILE_NAME = "secret.txt"; // NOSONARit doesn't complain any more that there is a hardcoded password in the code. So why doesn't it work with theThread.sleep()case?I can see the issue both in SonarQube and in the SonarLint plugin for IntelliJ.
|
Ignoring a line with Sonar
|
I think I found the solution. I haven't tested it yet, but reading the doc suggests, that it's the correct approach.First, problem is not in sonar, but in karma. Your coverage report is constructed for processed typescript files, hence the line issues.Check out the doc on karma-coverage-istanbul-reporter npm package description (bold is from me):This is a reporter only and does not perform the actual instrumentation of your code. Babel users should use the istanbul babel plugin to instrument your code andwebpack + typescript users should use the istanbul-instrumenter-loaderand then use this karma reporter to do the actual reporting. See the test config for an e2e example of how to combine them.Angular is more or less webpack + typescript.Same solution, to use istanbul instrumenter loader, is proposed here:https://www.linkedin.com/pulse/typescript-20-how-get-correct-test-coverage-line-numbers-willem-liuI suggest we should reconfigure our karma configs to produce proper lcov.info files and see what it comes out.ShareFollowansweredSep 28, 2018 at 21:46MiqMiq4,11922 gold badges1818 silver badges3232 bronze badgesAdd a comment|
|
I have an Angular project with some tests. My build is written in Gulp. I run the tests using Karma and produce an lcov report.I then use the gulp-sonar plugin to run Sonar. My sonar config looks like this:"sonar": {
"host": {
"url": "http://mysonar.example.com.au"
},
"projectKey": "sonar:advertising-test",
"projectName": "advertising-test",
"projectVersion": "1.0.0",
"sources": "app/js",
"javascript": {
"lcov": {
"reportPath": "reports/coverage/lcov.info"
}
},
"exec": {
"maxBuffer": "1048576"
}
}Sonar runs and analyses the code but it fails when trying to read the lcov report with the following:[09:38:58] 09:38:58.322 WARN - Problem during processing LCOV report: can't save DA data for line 0.
java.lang.IllegalArgumentException: Line with number 0 doesn't belong to file app/js/main.js
...
[09:38:58] 09:38:58.324 WARN - Problem during processing LCOV report: can't save DA data for line 65.
java.lang.IllegalArgumentException: Line with number 65 doesn't belong to file app/js/constants.jsand so on for pretty much every js file i have.If i produce an html coverage report then the report looks fine so it seems the report is being correctly generated.I wonder if this is caused by the karma-browserify step that I use.Can someone help with my lcov report errors?Has any one managed to get lcov coverage reports working with karma and browserify?
|
Karma produces lcov report for angular project with invalid line numbers
|
Assuming you are using jenkins sonar plugin, refer tothis documentationon how to configure the plugin to specifyadditional parameterswhich allow files to be excluded from analysis.ShareFolloweditedJul 8, 2016 at 8:41Fabian Braun3,77211 gold badge2828 silver badges4545 bronze badgesansweredJan 13, 2012 at 9:51RaghuramRaghuram52.1k1111 gold badges112112 silver badges123123 bronze badges12Both links are 404.–Earl RubyNov 30, 2021 at 0:51Add a comment|
|
Closed.This question is seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. You can edit the question so it can be answered with facts and citations.Closed4 years ago.Improve this questionI am running sonar from Jenkins. I want to exclude some java files in the sonar report. Is that possible through Jenkins? If yes, how can I do that?
|
Excluding java files in sonar report through Jenkins [closed]
|
I upgraded from 6.3.1 to 6.4 and are using Azure AD to authenticate. I saw the exact same behavior as Tom Busby. After deleting everything below /data/es as Bernard Dubreuil suggested it is working as expected again!ShareFollowansweredJun 7, 2017 at 10:23MariWingMariWing39633 silver badges77 bronze badges0Add a comment|
|
Hi the problem i am having is after upgrading from 5.1.2 -> 5.6 -> 6.4. I believe i followed the upgrade path as documented.
The system worked fine on 5.1.2 & 5.6 but now on 6.4 the initial projects page that loads first thing is empty. It reads "Once you analyze some projects, they will show up here." Does this mean i need to analyse new projects? It does not pull the old analysis from the previous versions?If i go into administration -> projects -> management i see all the projects in there.Also if i go into administration -> security -> users all i see in the admin user. (i am not logged in as admin i am logged in as tbusby)
If i go to administration -> security -> groups i see groups and all the members e.g. sonar-users - 23users.We use Crowd as our user repository and it seems to be authenticating fine just not displaying the users.Just wondering if this behaviour is expected with the new UI and i am just reading things wrong or there is an actual issue.Kind Regards
Tom Busby
|
Newly upgraded Sonar not showing projects or users
|
Fortify essentially classifies the code quality issues in terms of its security impact on the solution. While Sonarqube is more of a Static code analysis tool which also gives you like "code smells," though Sonarqube also lists out the vulnerabilities as part of its analysis.However, the biggest difference is in-terms ofCost. Sonarqube is Free to use (with community support) while Fortify needs a license, which is expensive.ShareFolloweditedJun 8, 2021 at 11:42Amol M Kulkarni21.4k3434 gold badges122122 silver badges165165 bronze badgesansweredOct 15, 2019 at 17:38Soumen MukherjeeSoumen Mukherjee3,12133 gold badges2424 silver badges3636 bronze badges44Not only this for Fortify. Fortify when doing his Security Analysis, try to identify all the points with no sanitizing systems, try to apply some security rules on the dataflow etc.... As I remember, Sonarqube did not a so indeep analysis.–SPointOct 17, 2019 at 8:442Actually, paid versions of SonarQubedo provide data tracing/tainting analysis. And if you're thinking about Fortify, you're probably thinking about paying for something anyway.–WillDFeb 21, 2020 at 18:16SonarQube cloud version (SonarCloud) is only free in case you don't mind that your code becomes accessible to the public.–Luis GouveiaJul 22, 2020 at 10:40Just a random question around Fortify Pricing, how much does the license cost?–jadavparesh06Jun 29, 2023 at 4:34Add a comment|
|
Closed.This question is seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. You can edit the question so it can be answered with facts and citations.Closed2 years ago.Improve this questionCan someone tell me what is the difference between SonarQube and Fortify? Both are static code analysis tool. I found out Fortify is more inclined towards security as it gives information about vulnerabilities included in OWASP, SANS etc. SonarQube also shows this information.
|
Difference between SonarQube and Fortify? [closed]
|
One of the reasons might be that Sonar cannot find that directory if you do analysis before building your project.
Thetarget/classesdirectory does not exist before you started building the project using maven.Try this value to workaround:sonar.java.binaries=targetorsonar.java.binaries=.ShareFolloweditedApr 3, 2020 at 12:09answeredApr 3, 2020 at 12:02Sergey NemchinovSergey Nemchinov1,4481717 silver badges2222 bronze badgesAdd a comment|
|
I'm performing an analysis with Sonar but I get the following error:Error during SonarQube Scanner execution
java.lang.IllegalStateException: No files nor directories matching 'target/classes'In my project I've the target directory but no classes directory or files, what should be in there for the analysis to work?
|
Sonar analysis abort because 'No files nor directories matching 'target/classes'
|
There is not (for now) any plugin which will break build when Quality Gate did't pass onSonarQube5.2.But for SonarQube 5.3+ you can again useBuild Breakerplugin.From mailing list:Breaking the build in SonarQube 5.2(21/Oct/2015)Fabrice Bellingrad: TheBuild Breaker
Pluginwon't be available for SQ 5.2+. The idea is to develop a core feature
to answer the use cases previously covered by this plugin. This is
what we call the "what if" feature =>https://jira.sonarsource.com/browse/SONAR-6763This issueSONAR-6763is planned forSonarQube 6.X.ShareFolloweditedJan 18, 2021 at 12:30CommunityBot111 silver badgeansweredNov 3, 2015 at 20:48agabrysagabrys8,89833 gold badges3535 silver badges7575 bronze badges5Note that that release date may move. :)–G. Ann - SonarSource TeamNov 4, 2015 at 20:184This is pretty disappointing. We rely on this as part of our continuous integration. Is there some justification for removing a useful feature?–jbarrusNov 6, 2015 at 20:25I'm with you. We will not upgrade to 5.2 because of that. This is a must have feature when building your continuous integration platform!–João SimasNov 10, 2015 at 20:57There is a big discussion on SonarQube mailing list. The conclusion:this will be a core feature in SonarQuibe 5.4.–agabrysNov 10, 2015 at 21:03SonarQube Teamchanged fix versionfor issueSONAR-6763from 5.4 to 6.X.–agabrysFeb 8, 2016 at 7:10Add a comment|
|
It seems like theBuild Breaker Pluginis no longer compatible with SonarQube 5.2. Is there any alternative to have a (VSO) build fail if a Sonar gate is not fulfilled or are there plans to update the Build Breaker Plugin to 5.2?
|
Build Breaker Plugin with SonarQube 5.2
|
Go tohttp://localhost:9000Then go to administrationThen go to projects managementThen press create project, enter project name exactly like in your IDE.Then go toIntelliJ IDEA -> Settings -> Other settings -> SonarLint Project
Settings Bind to server:Press refresh binding.That's it.ShareFollowansweredJul 9, 2016 at 22:29avalonavalon2,25133 gold badges2424 silver badges5151 bronze badges4So simple. is it needed to run analysis? or I may run without connection to remote server?–Katoteshi FukuJul 9, 2016 at 22:361You can't, remote server is what doing analysis, not ide plugin doing it–avalonJul 9, 2016 at 22:44i gave same name and key as master still says project isnt intialized on sonar server :(–amITFeb 27, 2017 at 12:20In SonarLint 4.2.0, there is no "Refresh binding" action any more. It has been replaced with: IntelliJ IDEA > Settings > Other Settings > SonarLint General Settings, button Update binding.–Ivan dal BoscoNov 8, 2019 at 12:34Add a comment|
|
IntelliJ IDEA -> Settings -> Other settings -> SonarLint General SettingsSonarQube servers: Localhost (http://localhost:9000;
login: admin; password: admin;
test connection - "Authentification successful") Update binding: few seconds agoIntelliJ IDEA -> Settings -> Other settings -> SonarLint Project SettingsBind to server: Localhost SonarQube project:Update server binding
firstBut it's already bound! What may be wrong? Web interface also can't see the project.When I pressAnalize code with SonarLintin workspace, I get an error popup: "Project bound to invalid SonarQube server. Please, check configuration"
|
SonarLint doesn't see server binding
|
The problem could be that Sonar is exporting your ruleset for v4.x format and your Eclipse plugin expects them in v5.x format.Try changing your rules from:<rule ref="rulesets/basic.xml/UnusedNullCheckInEquals">
<priority>3</priority>
</rule>to<rule ref="rulesets/java/basic.xml/UnusedNullCheckInEquals">
<priority>3</priority>
</rule>Please note therefattribute. A simple find and replace all will work out fine for you.ShareFollowansweredJun 5, 2013 at 15:12Ivan NikolovIvan Nikolov79344 silver badges1515 bronze badges2Just tried this with SonarQube 3.7 and Eclipse Kepler and it didn't work. Any updates on this answer?–André StannekFeb 11, 2014 at 13:04Also, you may also have to use Dove and KrishPrabakar answers below. Additionally, the following also changed - The rules UnusedPrivateField, UnusedLocalVariable, UnusedPrivateMethod, UnusedFormalParameter, UnusedModifier moved from controversial.xml to unusedcode.xml. The rule design.xml/UseSingleton changed to design.xml/UseUtilityClass–Rakesh NMar 13, 2015 at 13:38Add a comment|
|
I would like to use the same Ruleset in my IDE (Eclipse) that my Sonar profile.I got the PMD XML ruleset from the Sonar Permalinks and would like to import it into my PMD Eclipse Plugin but when i try to do it, the "OK" button is desactivated ...Can someone help me ?
|
Can't import PMD Ruleset in Eclipse
|
As any automatic tool, Sonar - and the rule engines it relies on (Findbugs/PMD/Checkstyle/...), can make "mistakes" while raising a violation: only a human can detect this, and you have the ability to flag this "mistake" as a false-positive to be sure that you won't spend time on it again.Obviously, this feature must not be used to mute real violations. What's more, each time you flag a violation as false-positive, a good habit is to write a meaningful comment (and also report the issue on the user mailing list of the corresponding tool).ShareFollowansweredSep 4, 2012 at 7:56Fabrice - SonarSource TeamFabrice - SonarSource Team26.6k33 gold badges6363 silver badges5858 bronze badgesAdd a comment|
|
When I encounter a violation in Sonar (in violation drilldown tab), in the source code view Sonar has some action like comment, assign, etc, one of those is False-positive, I want to know what exactly is the meaning of this operation, and when should I use it?
|
What exactly is the meaning of False-positive operation in sonar?
|
SonarQube Community Edition is free of charge without any LOC (Lines Of Code) limitations. You can use if freely in your commercial project.ShareFolloweditedAug 17, 2020 at 14:20Mohammed Noureldin15.7k1818 gold badges7373 silver badges102102 bronze badgesansweredJul 20, 2018 at 6:43PeskaPeska4,02033 gold badges2525 silver badges4242 bronze badges5I will give it a spin, will update this thread if I find any surprises.–DevOpsyJul 25, 2018 at 1:241@DevOpsy Did you find any limits or issues? I'm looking at using it for the same use case currently.–Erdss4Oct 25, 2018 at 7:061@Erdss4: community edition is pretty good, didn't hit any limits on the LOC. We bought developer edition and it has additional features mainly OWASP top 10 security scanning and branch analysis. Still analyzing and learning.–DevOpsyOct 26, 2018 at 4:18Could you provide the source or a reference to this answer please?–Mohammed NoureldinAug 17, 2020 at 13:49You can check Plans & Pricing:sonarsource.com/plans-and-pricingor read this explanation about LOC usage:community.sonarsource.com/t/loc-limit-explanations/5082–PeskaAug 18, 2020 at 14:44Add a comment|
|
I am analyzing SonarQube to use it for our closed source product which is mostly .Net and web technologies.
Are there any caveats to using community edition for commercial projects?
What is the limit on the lines of code that community edition can scan?
|
SonarQube community edition for commercial project
|
You need to edit the value of the rule parameter in the appropriate profile. If you're using the Sonar way profile, you'll find that it's not editable there. In that case, you'll need to make a copy of the Sonar way profile and edit the parameter there. Then either set your new profile as the default, or explicitly assign the relevant projects to be analyzed with it.ShareFollowansweredMay 21, 2018 at 12:30G. Ann - SonarSource TeamG. Ann - SonarSource Team22.5k44 gold badges4242 silver badges8484 bronze badges6Thanks for response, I think it can be done by setting up a new quality gate–Shubh Rocks GoelMay 23, 2018 at 14:05This doesn't seem like a reasonable answer. It requires cloning and changing the entire profile to customize settings? You are unable to customize settings in the default profile?–elyJan 17, 2020 at 13:55This is an incomplete answer. It could be completed by listing all the steps. For example, it is not obvious to me how to "copy" a profile.–ArunApr 7, 2022 at 22:29agree that this answer is incomplete. How about identifying the rule parameter name, and even how to add rules to files. Where is this profile thing? Whats the param in the ocnfig file?–RubesMNSep 30, 2022 at 14:32There's no file. It's all in the UI.–G. Ann - SonarSource TeamOct 3, 2022 at 11:08|Show1more comment
|
Do anyone knows how to increase the cognitive complexity threshold inSonar Portal? I searched in the portal but I could not find any clue on it.Default is15, I want to increase it to25
|
SonarQube: How to increase the Cognitive Complexity Threshold in Sonar Portal?
|
Since Sonar 3.1, it includes a plugin that has specific PMD rules to be executed against the unit tests (a JIRA was created for that). You can see them in theConfiguration > Quality Profiles > Coding Rules.However, it seems that you want to run a full analysis on thetestsource code, like you do on theproductionsource code, and get additional metrics (for ex. a% rules complianceand also a% rules compliance for unit tests). I don't think that Sonar provides such feature natively. What you can do is to run 2 Sonar analysis:Your first analysis is the current one;The second analysis will consider thesrc/test/javaas the "production" source code. Thus, this second analysis will give you the quality of your code. For this analysis, you can specify a specific Maven profile (or an alternativepom.xml) that will change the project information (for ex. it will indicate thatsrc/test/javais the defaultsourceDirectory).ShareFollowansweredJan 17, 2013 at 10:30Romain LinsolasRomain Linsolas80.5k5050 gold badges203203 silver badges275275 bronze badges2thx, that's what i need, not a full analysis but some rules :)–pan40Jan 17, 2013 at 11:22In Sonar >3.4 you can copy your own rules and improve the "PMD Unit Tests" plugin–pan40Jan 17, 2013 at 12:07Add a comment|
|
Is it possible to check in Sonar the quality of the *Test.java source code, e.g. Methods maximum size 100 lines?The problem is, that the Java Junit tests are growing with the productive code, also the complexity.We have unit test classes with more than 1000 lines and 2 methods.We want to check in Sonar some rules for these *Test.java classes.
|
Sonar Java: check the quality of the test classes source code?
|
This is a false positive that is already fixed and soon to be released with SonarQube Java 3.14.For further reference, please checkSONARJAVA-1478.ShareFollowansweredApr 30, 2016 at 6:52Fabrice - SonarSource TeamFabrice - SonarSource Team26.6k33 gold badges6363 silver badges5858 bronze badges2Uh? Link is not dead.–Fabrice - SonarSource TeamAug 5, 2016 at 11:51Ahh.. My company's network was stopping me from accessing that link. I do apologies for wasting your time.–akashAug 8, 2016 at 5:31Add a comment|
|
This question already has an answer here:When is an IntStream actually closed? Is SonarQube S2095 a false positive for IntStream?(1 answer)Closed6 years ago.I have a next code:private Stream<Field> getStreamWithAccessibleFields(final Object object) {
return Arrays.stream(object.getClass()
.getDeclaredFields()).peek(field -> field.setAccessible(true));
}Sonar throws me an issue:[MINOR] Close this "Stream". squid:S2095.
Can anybody give an advice, how I can handle this problem?
|
Sonar wants to close the Stream [duplicate]
|
If you use Spring, you can useReflectionUtils.makeAccessible(field)to make that field accessible. Fortify does not complain about this tweak.You can read more about this inthis article.ShareFolloweditedDec 13, 2017 at 7:40Dimitri Mestdagh43.2k1414 gold badges101101 silver badges136136 bronze badgesansweredDec 13, 2017 at 5:24Vidyasagar GayakwadVidyasagar Gayakwad7111 silver badge22 bronze badges1It served perfectly to solve the problem proposed by the question. And that's what matters.–LoveraJun 29, 2019 at 0:30Add a comment|
|
I used reflection to invoke a private constructor of a class in order to solve insufficient branch coverage issue shown by sonar scan report. This is the snippet of my code I was working:// reflection to access a private constructor of a class
Constructor<CMISBridgeMaps> c = CMISBridgeMaps.class.getDeclaredConstructor(new Class[0]);
c.setAccessible(true);
cmisBridgeMaps = c.newInstance(new Object[0]);The above code solved my sonar scan critical issue. But unfortunately fortify is now showing theAccess specifier manipulationissue on the following line:c.setAccessible(true);How can I solve both fortify and sonarcube issues? Any help would be greatly appreciated.
|
Fortify high: Access specifier manipulation on reflection that is used to invoke a private constructor
|
I have managed to fix our issues by adding this property inside thesonarqubeblock:property 'sonar.sources', 'src/main'ShareFollowansweredSep 7, 2016 at 14:59Andrea BergiaAndrea Bergia5,51222 gold badges2424 silver badges3939 bronze badges11if you need to specify multiple source folders, how to specify it?–NagaAug 30, 2017 at 8:52Add a comment|
|
We have a pretty standard web project using Java, which contains also some javascript code in the standardsrc/main/webappfolder. We are using Gradle 2.14 as our build tool.We have just installed a brand new Sonarqube 6.0.1 on a fresh server, checked that both the Java and Javascript plugins are installed, and modified the build.gradle file as recommended on theSonarqube documentation:plugins {
id 'org.sonarqube' version '2.0.1'
}
sonarqube {
properties {
property 'sonar.projectName', 'Our-Project'
property 'sonar.projectKey', 'com.ourcompany:our-project'
}
}This doesn't work as expected: the java code is analyzed correctly and we can browse the results on sonar, but the javascript code isn't analyzed.What are we doing wrong? Thanks.
|
Project with both java and javascript in sonarqube using gradle
|
You can use the /api/rules web service:http://docs.sonarqube.org/pages/viewpage.action?pageId=2392166ShareFolloweditedAug 21, 2016 at 8:56Mark Rotteveel105k207207 gold badges148148 silver badges204204 bronze badgesansweredNov 13, 2014 at 9:48David RACODON - QA ConsultantDavid RACODON - QA Consultant3,99311 gold badge1313 silver badges1414 bronze badges2I did not use this in the end, because it was easier to search for the description manually (I did not have a huge list), but I'll keep this in mind, it looks really useful! Thanks ;)–makeMondayNov 13, 2014 at 14:03Web API is now available via{yourSonarServer}/web_api.docs.sonarqube.org/display/DEV/Web+API–ThoomasAug 22, 2017 at 9:50Add a comment|
|
I am trying to find a way to get a list of all Sonarqube Java (or whatever) rules (with keys, description, etc.) and export it as an Excel, csv or xml. I get to list them "dynamically" likethis, but I would like to have them all in a file. Does anyone know how to do this?
|
Export list of coding rules from Sonarqube
|
I don't think I would want Sonar to change source. It's a codeanalyzer.You could configure your IDE to format on save and do an initial format of all afflicted source files, so that it puts the satements on separate lines.Also, you might want to review the importance of the problem and change/edit the Quality Profile.ShareFollowansweredDec 11, 2013 at 13:26DormouseDormouse1,62711 gold badge2323 silver badges3333 bronze badges2I don't want sonar to make changes , I am looking for a separate tool or plugin to do that after I have done code analysis from sonar. And the statement on separate lines is just an example , that could be solved by using code formatting. For a better example I have 280 cases of "if/else/for/while/do statements should always use curly braces" , its painful to add 287*2 curly braces manually !! Or around 1000 cases of "Avoid commented-out lines of code" ....is there a way to do this automatically by giving instructions to a plugin ?–Prakhar DixitDec 12, 2013 at 10:24Curlies can also be added by Save Actions or formatting in Eclipse. Comments are a different story, but can be achieved by regex replacement. But again, these are minor issues and could be removed from the profile or be edited.–DormouseDec 12, 2013 at 10:40Add a comment|
|
I am working on fixing issues caught by sonar on a very old Java project(8 years old approximately ).
It is a huge project with a lot of faulty code that is caught by sonar.
Although they are very trivial fixes but there are a number of them.
Is there a way to automatically fix a series of similar issues ?
Like i have around 1200 cases of "statements should be on separate lines" , to do it manually would take ages.
Can i automate these fixes somehow ?
|
Automate fixes for issues found by Sonar
|
I was facing the same issue:zsh: command not found: sonar-scannerI have installed sonar globallynpm install sonarqube-scanner -gAnd it worked for me.ShareFolloweditedDec 28, 2022 at 0:36Jeremy Caney7,3728383 gold badges5252 silver badges8080 bronze badgesansweredDec 27, 2022 at 7:20AnanyaAnanya6111 silver badge22 bronze badgesAdd a comment|
|
i followed the directions as per the SonarQube documentation. I installed the sonarqube and sonar-scanner from the instructions into my applications folder. But having trouble getting my terminal to recognize sonar-scanner. I checked my path variable by trying the following:echo $PATHand got.../Users/Neptune/Applications/SonarQube/bin:/Users/Neptune/Applications/SonarScanner/bin:/Users/Neptune/anaconda/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Applications/domino:/Library/TeX/texbin:/Library/Apple/usr/binThis is what i have for my pathexport PATH="/Users/Neptune/Applications/SonarScanner/bin:$PATH"
export PATH="/Users/Neptune/Applications/SonarQube/bin:$PATH"I then changed it to:export PATH="/Users/Neptune/Applications/SonarScanner/bin/sonar-scanner:$PATH"AFter each method, i restarted my shell and still no luck. I then went to my project root directory where i have my python code installed and added a project.properties file but i don't see how that helps with the terminal recognizing sonar-scanner -h as a command. Can someone please help. ThanksSonarQube fires for me and im able to start a localhost:9000 server. Its getting mac to recognize sonar-scanner is whats causing me problems.edit: i managed to get sonar-scanner working. But it's such a painful process. I have to always type:sh /Applications/SonarScanner/bin/sonar-scanner
|
sonar-scanner command not found in mac
|
currently, this does not seem to be possible. however,this npm rfc 0004specifies anpm audit --owaspflag with solving this problem. this rfc was accepted, but is not yet implemented.maybe it is worth a try to parse the output ofnpm audit --jsonwith some sonarQube plugin, but I have no more knowledge about how to do this.Edit 2021-08-09the npm rfc waswithdrawn:The npm cli team would be happy to land this change in case it comes from a community contribution, this withdrawn was based on the fact that this is not remotely closed to being in the roadmap of the current team.ShareFolloweditedAug 9, 2021 at 9:10answeredSep 8, 2020 at 8:17hajahaja31122 silver badges88 bronze badges2Thanks @haja for the rfc link ;) Wait and see–Geoffrey LallouéSep 8, 2020 at 9:58sadly, the rfc was withdrawn–hajaOct 2, 2021 at 9:37Add a comment|
|
I'm working on web application.
I need to check security of dependencies.I'm actually scanning my source code with OWASP dependency check but i think it's not the best tool to use on web app.
I think npm audit or yarn audit is better tool to check dependencies security of this king of application.With OWASP, i use OWASP SonarQube Project to integrate result into sonarQube
Example of settings used :sonar.dependencyCheck.reportPath=$(System.DefaultWorkingDirectory)/DependencyCheckResults/dependency-check-report.xml
sonar.dependencyCheck.htmlReportPath=$(System.DefaultWorkingDirectory)/DependencyCheckResults/dependency-check-report.htmlIn the same way, is there a way to use the npm audit (or yarn audit) report into SonarQube?At the moment i generate report in json format, using this command:npm audit --jsonI also know that it's possible to generate HTML report from npm audit withhttps://github.com/eventOneHQ/npm-audit-htmlSo, it's just missing a SonarQube plugin to import it or something like that, but i can't find it.
|
use npm audit report in SonarQube
|
This is indeed a bug, so thanks a lot for reporting it.The problem is here in the code :https://github.com/SonarSource/sonar-java/blob/3.9/java-checks/src/main/java/org/sonar/java/checks/ConstantMathCheck.java#L117where there is absolutely no check on the type of the left operand of the % operator.I just filed the following bug to handle this :https://jira.sonarsource.com/browse/SONARJAVA-1457ShareFollowansweredJan 7, 2016 at 7:57benzonicobenzonico10.7k55 gold badges4444 silver badges5151 bronze badgesAdd a comment|
|
SonarQube raises the major violationSilly math should not be performedin my code. The description saysCertain math operations are just silly and should not be performed
because their results are predictable.In particular,anyValue% 1 is silly because it will always return 0.In my case though,anyValueis a double. And this worksas intendedfor me. Here's the actual code:double v = Double.parseDouble(Utils.formatDouble(Double.valueOf(value.getValue()), accuracy.intValue()));
boolean negative = v < 0;
v = Math.abs(v);
long deg = (long) Math.floor(v);
v = (v % 1) * 60;Is the analyser assuming my variable is anint(which is their bug)? Or am I missing something else?
|
Why is anyValue % 1 "silly math" in Sonar when anyValue is a double?
|
According toSonarQube rules, This rule flags for review code that initiates loggers configuration.The goal is to guide security code reviews. Also, there is no way to fix it by code instead you should ask yourself whether:unauthorized users might have access to the logs, either because they are stored in an insecure location or because the application gives access to them.the logs contain sensitive information on a production server. This can happen when the logger is in debug mode.the log can grow without limit. This can happen when additional information is written into logs every time a user performs an action and the user can perform the action as many times as he/she wants.the logs do not contain enough information to understand the damage an attacker might have inflicted. The loggers mode (info, warn, error) might filter out important information. They might not print contextual information like the precise time of events or the server hostname.the logs are only stored locally instead of being backuped or replicated.You are at risk if you answered yes to any of those questions.For more info about security logging project, check theowasp pageShareFollowansweredDec 18, 2019 at 18:54FontsFonts17511 silver badge66 bronze badges0Add a comment|
|
I am getting the following issue for my code on Sonar:Make sure that this logger's configuration is safe.The code that I have written is:public static final Logger logger = Logger.getLogger("logger");
if (logLevel.equalsIgnoreCase("info"))
logger.setLevel(Level.INFO);
else
logger.setLevel(Level.ALL);It is showing me this error onlogger.setLevelcalls.How can I solve these?
|
Sonar issue: Make sure that this logger's configuration is safe
|
If this is for a private project on SonarQube, this is most likely a permissions issue.There is currently an open issue for SonarQube to allow this to work:https://jira.sonarsource.com/browse/MMF-1942As an FYI, this feature has already been implemented for SonarCloud:https://jira.sonarsource.com/browse/MMF-1178.ShareFollowansweredJul 3, 2020 at 9:53RekovniRekovni6,85444 gold badges4747 silver badges6767 bronze badges4thx for your reply. The project on sonarqube is listed as public.jira.sonarsource.com/browse/MMF-1942i dont really see how this is helping. there is no real instructions on how to do it. the moment i click on the provided link i get an "access denied"–JonathanAgeJul 7, 2020 at 12:55The project on sonarqube is public, but is the sonarqube instance itself public or private? (From the sounds of it in your question it is private as you need to login to access it)–RekovniJul 7, 2020 at 13:471The link to the JIRA issue is to let you know that SonarQube are looking to implement this feature you require.–RekovniJul 7, 2020 at 13:471I cannot access / see these issues - have they moved? is this still an issue with sonarqube?–IARINov 28, 2021 at 12:48Add a comment|
|
I have a project on gitlab for which I'm trying to display quality badges from sonarqube on. For that I used the "Get project badges" button on the bottom right corner of your sonarqube project overview. They give you for each badge a Markdown which you can easily copy & paste to your README.md file on gitlab/github.Markdown looks like this:[](https://yourprojectonsonarqube/dashboard?id=your_project_key)For me it looks like this on the README.md file(logged in as maintainer):For other users on the project which also have maintainer or developer permissions it looks like this:If you click on the missing images, it will redirect you to sonarqube and ask for you to log in. Afterwards the images are visible. How can I change that? I want them to always be visible to every user of my project.
|
Sonarqube quality badges on gitlab
|
It depends what you mean withmapping. JSHint has a list of built-in rules, some of which your developers will have enabled.For each of the rules they have enabled, they'll need tofind the equivalent in theSonarQube list of rules. (I'd suggest making a shared spreadsheet, so this lookup only needs to happen once.)Should there be any rules that don't have a SonarQube equivalent yet, they will need towrite such a rule themselves.Here is an example rule.The code will probably be similar towhat JSHint uses internally; however, JSHint does not have separate files per rule.ShareFollowansweredApr 4, 2016 at 7:50Ruben VerborghRuben Verborgh3,62522 gold badges3232 silver badges4444 bronze badgesAdd a comment|
|
Some of our dev groups are using JSHint for code quality and we are looking to adopt SonarQube for greater transparency. Sonar explained they want to maintain their own rules list here:The SonarwayIs there a way to easily map existing JSHint rules into the "Sonarway" equivalents? We'd like to maintain 1 set of rules for JS.
|
Convert JSHint rules to Sonar
|
-1Make your class final so that Instance creation can be avoided.@SuppressWarnings("static-access")
public final class SuperClass {
private SuperClass() {
}
}ShareFollowansweredJan 27, 2020 at 15:04Deepak MathuriaDeepak Mathuria133 bronze badgesAdd a comment|
|
I am performing static code analysis on old code using a SonarLint analysis. I cannot paste the code here but it is similar to:@SuppressWarnings("static-access")
public class SuperClass {
private SuperClass() {
}
public static SuperClass getInstance() {
return InstanceHolder.instance;
}
private static class InstanceHolder {
public final static SuperClass instance = new SuperClass();
}
public void doSomething() {
//do something
}
}SonarQube (sonar-java: 4.2.1.6971), reports an issue onS1118.Adding a private constructor toInstanceHolderhas no solving effect here, sinceSuperClassis the only class that can create an instance of it due to its private modifier.SuperClasscan still create an instance, even withÌnstanceHolderhaving a private constructor.BTW: adding the constructor removes the sonar-issue, so I think the analyzer marked this as a rule violation because of the internal 'UtilityClass' without further investigation.Is this a bug? Instead of a design flaw, this is an example of a thread-safe singleton.
|
Java - SonarQube, issue on 'Utility classes should not have public constructors' (squid:S1118) in singleton
|
Locate the config filemy.cnf(If your MySQL is running in Windows, locatemy.ini)Add this to the config file[mysqld]
max_allowed_packet=256MThen, restart mysqlFor Linux,service mysql restartFor Windowsnet stop mysqlnet start mysqlGive it a Try !!!ShareFollowansweredJan 29, 2013 at 21:14RolandoMySQLDBARolandoMySQLDBA44.1k1616 gold badges9393 silver badges134134 bronze badges3Thanks for this. Mine was located in /etc/my.cnf. Information is hereserverfault.com/questions/346647/mysql-wheres-the-my-cnf-pathand the magic command to find where it might be ismysql --help | grep "Default options" -A 1–Ashley FriezeOct 20, 2016 at 12:285I needed to restart my sonar server for this to eventually worksudo service sonar restart–Ashley FriezeOct 20, 2016 at 14:06Restarting the sonar server along with the solution worked for me. Thanks for the tip @AshleyFrieze–Udara JayawardanaAug 17, 2018 at 10:23Add a comment|
|
When I try and run a sonar analysis I get this exceptioncom.mysql.jdbc.PacketTooBigException: Packet for query is too large
(1807198 > 1048576). You can change this value on the server by
setting the max_allowed_packet' variable.Where on the sonar server should I set this value?I'm using Sonar 3.4.1 and MySQL 5.x
|
PacketTooBigException when running a sonar analysis
|
i figure it out. if you MUST get the rules from another group then do this:click configuration and choose the quality profileclick the permalink tabcopy the xml of all the rules you wanted, save them accordlyingcreate a new profile and use those files you saved as the new rulesShareFollowansweredFeb 16, 2012 at 14:54iCodeLikeImDrunkiCodeLikeImDrunk17.3k3535 gold badges110110 silver badges170170 bronze badges1what if i want to import rules for PHP language?? do you have any idea reagarding this–Abhijeet KambleFeb 19, 2015 at 15:22Add a comment|
|
I have a rules.csv file which I downloaded from another site, how do I import this to my sonar?I do not have the credentials to get the XML file.
|
How to import rules.csv to sonar?
|
SonarQube (formerly just "Sonar")is a server-based system. Of course you can install it on your local machine (the hardware requirements are minimal). But it is acentral server with a database.Analyses are performed by someSonar"client" software, which could be the sonar runner, the sonar ant task, the sonar Eclipse plugin etc. The analysis results can be automatically uploaded to the server, where they can be accessed via the sonar Web application.In an environment with many developers, you should run a build server (e.g. Hudson or Jenkins), which performs automatic sonar analyses as part of the nightly build. Other schedules are possible, but the developers should know when they can expect updates of the server-side analysis results. The results of the automated analysis can be displayed in the individual developer'sEclipseeditor by way of the sonar Eclipse plugin.ShareFollowansweredJan 27, 2015 at 5:36CodeWalkerCodeWalker2,32944 gold badges2424 silver badges5151 bronze badgesAdd a comment|
|
Can anybody explain me what is the difference between sonar and sonarQube as i have said to integrate the sonar with eclipse i am using eclipse Luna but when i tried to search sonar usingHelp----> Eclipse Marketplace ---->search (sonar)i am getting sonarQube not sonar
Therefore my question is that are they same or different if same i can go ahead to install in the eclipse if not then from where to install sonar as it is my requirement.please anybody suggest
|
difference between sonar and sonarqube
|
It means your constants are supposed to match this regular expression:^[A-Z][A-Z0-9](_[A-Z0-9]+)$Which basically means, only use upper case characters, numbers and underscores (in the order which is valid Java syntax). So instead ofStreetOwner, useSTREET_OWNER.RegisteredByshould beREGISTERED_BYand so forth.ShareFollowansweredOct 17, 2019 at 8:16EliasElias1,57288 silver badges1919 bronze badgesAdd a comment|
|
I have created this enum classpublic enum StreetNameEnum {
StreetOwner("0"), StreetedBy("1"), StreetedFor("2"), RegisteredBy("3"), StreetContact("4"), AssignedTo("5");
private String code;
StreetRoleEnum(String code) {}
public String getCode() {
return code;
}
}SonarQube issue:Rename this constant name to match the regular expression
'^[A-Z]A-Z0-9$'.
|
SonarQube issue: Rename this constant name to match the regular expression '^[A-Z][A-Z0-9](_[A-Z0-9]+)$'
|
Use it like that in windows Terminal:
.\gradlew sonarqube -Dsonar.host.url=http://my.url-Dsonar.login=login --stacktraceAfter that ,you will find the project already in the SonarQube server.ShareFollowansweredJan 10, 2019 at 8:13ka whosyourka whosyour2622 bronze badges1Thanks that helped. I have mentioned my mistake in more layman language below!–sud007Mar 18, 2021 at 15:27Add a comment|
|
Analysing project with this command.\gradlew sonarqube \ -Dsonar.host.url=http://my.url \ -Dsonar.login=login --stacktraceGetting this errororg.gradle.execution.TaskSelectionException: Task '\' not found in root project 'JavaLint'And here is my gradle fileplugins {
id "org.sonarqube" version "2.6.2"
}
apply plugin: 'application'
apply plugin: 'java'
apply plugin: 'eclipse'
archivesBaseName = 'JavaLint'
version = '0.1-SNAPSHOT'
mainClassName = 'Main'
repositories {
mavenCentral()
}
jar {
manifest {
attributes 'Main-Class': 'com.test.Run'
}
}
sourceSets {
main {
java {
srcDirs 'src'
}
}
}
dependencies {
compile group: 'commons-io', name: 'commons-io', version: '2.6'
compile group: 'commons-lang', name: 'commons-lang', version: '2.6'
compile group: 'org.jsoup', name: 'jsoup', version: '1.11.2'
compile group: 'junit', name: 'junit', version: '4.12'
compile group: 'log4j', name: 'log4j', version: '1.2.16'
}Stack traceI don't understand what am i supposed to do with it.
|
Sonarqube gradle analyzing project, task not found in root project
|
Copy/Paste Detection?Wikipedia: Copy/Paste Detector (CPD)FromSonarqube docs: Analysis Parameters, Duplication:A piece of code is considered duplicated as soon as there are at least 100 duplicated tokens in a row (override withsonar.cpd.${language}.minimumTokens) spread across at least 10 lines of codeShareFolloweditedAug 30, 2023 at 10:01hc_dev8,74611 gold badge2828 silver badges4040 bronze badgesansweredAug 29, 2019 at 20:33mattbornskimattbornski12.2k44 gold badges3131 silver badges2525 bronze badgesAdd a comment|
|
I works with Sonarqube every day in my job. But, I realized that I don't know what means CPD. Phrases like "INFO: CPD calculation finished", etc. I would like some help to know this.
|
What's CPD of the Sonarqube?
|
We were just faced with this issue, and found out that it's related to dotnet's and msbuild's reuse of nodes that were left running by a previous multi-threaded build.To avoid the problem, use either/nodereuse:falseor/nr:falseon your command line as the following:msbuild /m /nr:false myproject.proj
msbuild /m /nodereuse:false myproject.proj
dotnet restore myproject.sln /nodereuse:falseShareFollowansweredOct 5, 2018 at 13:15fstefffsteff54355 silver badges1919 bronze badgesAdd a comment|
|
Good evening,I am using the .Net Core 2.0 version from herehttps://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner+for+MSBuildon a 2.1 project in Jenkins with:withSonarQubeEnv('SonarQubeMain') {
bat "dotnet ${globals.SONAR_QUBE_MSBUILD_PATH}\\SonarScanner.MSBuild.dll begin /k:\"${globals.SONAR_QUBE_PROJECT}\" /d:sonar.host.url=${globals.SONAR_HOST_URL} /d:sonar.cs.xunit.reportsPaths=\"XUnit.xml\" /d:sonar.cs.opencover.reportsPaths=\"coverage.xml\"
}
bat "dotnet build --version-suffix ${env.BUILD_NUMBER}"
dir('test/mytestprojecthere') {
bat 'D:\\OpenCover\\OpenCover.Console.exe -target:"c:\\Program Files\\dotnet\\dotnet.exe" -targetargs:"xunit --no-build -xml XUnit.xml" -output:coverage.xml -oldStyle -filter:"-[*Tests*]*" -register:user'
}
withSonarQubeEnv('SonarQubeMain') {
bat "dotnet ${globals.SONAR_QUBE_MSBUILD_PATH}\\SonarScanner.MSBuild.dll end"
}It works the first build but on the next build it fails with:Failed to create an empty directory 'D:\Jenkins\workspace\xxxxxxxx\.sonarqube'.
Please check that there are no open or read-only files in the directory and that you have the necessary read/write permissions.
Detailed error message: Access to the path 'SonarScanner.MSBuild.Common.dll' is denied.and checking my windows server I can see multiple .Net Core Host Background process. If I kill these I can build again..I readed about msbuild/nodereuse:falsefor MSBuild but seems is not working for the dotnet core version?
|
dotnet.exe locking SonarScanner.MSBuild.Common.dll
|
I would have expected this format (without the "value ="):@SuppressWarnings({"PMD.UnusedPrivateField", "PMD.SingularField"})Similar format is working for me in PMD 5.1.3 (although Eclipse complains about them not being supported).ShareFolloweditedFeb 28, 2017 at 13:18stkent20k1414 gold badges8888 silver badges112112 bronze badgesansweredSep 16, 2014 at 19:18colbadhombrecolbadhombre81388 silver badges1111 bronze badges2This is exactly the case, thanks :-) I worked this out myself, but forgot to update my question.–Morten FrankSep 19, 2014 at 7:13In my case I was using a constant to save the description then it will not works because PMD analyse the source file I can't interpret the a constant reference for example–deFreitasFeb 20, 2019 at 22:20Add a comment|
|
PMD and SonarQube a nice tools but I have problems trying to suppress PMD warnings.We use Lombok a lot in our project, so many of the model classes have a:
@SuppressWarnings("PMD.UnusedPrivateField")
as an class-level annotations.This works fine.The problem is, that if I wan't to ignore one more rule, I would expect the following syntax:
@SuppressWarnings(value = { "PMD.UnusedPrivateField", "PMD.SingularField" })
This looks like the correct syntax, also reading the implementation of the PMD annotation.However, this seems not to works:
None of the rules are now suppressed.
|
@SuppressWarnings more than one rule not working
|
Add lombok.config file at the root of your project and add:config.stopBubbling = true
lombok.addLombokGeneratedAnnotation = trueconfig.stopBubbling = true is telling Lombok that this is the root
directory and that it shouldn’t search parent directories for more
configuration files (you can have more than one Lombok config files
in different directories/packages).lombok.addLombokGeneratedAnnotation = true is telling Lombok to add @lombok.Generated annotation to all generated methods.Jacoco (at least 0.8.0) filters out all methods annotated with @lombok.Generated.Source:https://medium.com/@mladen.bolic/lombok-data-improve-your-code-coverage-a74fb624a72bShareFolloweditedSep 20, 2019 at 19:48answeredSep 20, 2019 at 19:42WillemWillem1,03277 silver badges1313 bronze badges2Thanks for your quick response. I will try this and let you know–Dinesh MSep 20, 2019 at 20:02Thanks! As we have a lot of POJOs using lombok@Databut not much business code this bumped our sonar code coverage from 40 to 80 percent (Apparently branch coverage is very important to the default sonar quality measure config).–GuillermoApr 11, 2020 at 16:55Add a comment|
|
For below class Sonar is complaining about Uncovered Conditions for @EqualsAndHashCode (lombok annotations). I have tried adding '// NOSONAR' to ignore but it did not help. Please see code below for reference.import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@EqualsAndHashCode(callSuper = false) // NOSONAR
public class UserPersonalInfo extends PersonalInfo {
private String userId;
private String empployeeId;
}It shows 22 uncovered conditions for EqualsAndHashCode in Sonar report. Please help me to resolve this issue.
|
How to ignore Sonar 'Uncovered Conditions' for lombok @EqualsAndHashCode
|
Static variable are mostly used for Constants.Here you have declared static and assigning it instance ofSimpleDateFormat.Either makeDATE_TIME_FORMATnon-static or assign a constant to this variable.Better change it to instance variable and use a Sting to do that.e.gpublic final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss:SSS";ShareFolloweditedMar 4, 2019 at 8:12answeredMar 4, 2019 at 8:07TheSprinterTheSprinter1,5991717 silver badges3131 bronze badgesAdd a comment|
|
I have a rest web service, and below is how i have declared DateFormat as this is the date format i am going to use application wide.When i did code analysis using SonarLint eclipse plug-in, i got major warning saying "MakeDATE_FORMATas instance variable."public class Constants {
private Constants() {
}
public static final DateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss:SSS");
}Can anyone tell me what issue i might face if i use it this way in my rest API ?If i use it as instance variable i will end up declaring it in multiple classes ?
|
Sonar - Make DATE_FORMAT as instance variable
|
Install the Groovy plugin in Sonar. Login as admin/admin and go to
the administration/system/update-center tabAdd the following property in the
pom file<sonar.tests>src/test/groovy,src/test/java</sonar.tests>If you do this both Spock and JUnit tests are shown correctly!
See attached screenshotShareFollowansweredJan 27, 2017 at 8:39kazanakikazanaki8,03688 gold badges5353 silver badges7979 bronze badges0Add a comment|
|
I use spock to write test case and jenkins to run and publish my test cases.
I was able to get the code coverage reported but sonar shows meonly JavaUnit test cases; thegroovy test cases are totally missingThe following pom.xml is used as referencehttps://github.com/kkapelon/java-testing-with-spock/blob/master/chapter7/spring-standalone-swing/pom.xmlwould anyone please know what I am missing ?
|
Integrate Spock's test with Sonar
|
On this blog postIdentify Code Structure Patterns with No Effortit is explained how to use a Dependency Structure Matrix to identify Code Structure Patterns. The screenshots are done with theDependency Structure Matrixof the tool NDepend. Here are a few patterns:Layered code (code with no cycle, certainly the coolest thing that a DSM can show you at a glance)Code with dependency cyclesHigh Cohesion / Low-CouplingHungry CallerPopular CalleeMutual CouplingData ObjectShareFolloweditedJul 16, 2019 at 12:06answeredSep 1, 2010 at 13:38Patrick from NDepend teamPatrick from NDepend team13.5k66 gold badges6464 silver badges9696 bronze badges4This is really helpful. Unfortunately, the images in thelinked articleare now missing, and were already missing in the first Wayback capture:web.archive.org/web/20110324091932/http://codebetter.com/…–seanfDec 28, 2018 at 5:01I don't see any image missing, they are all here well displayed?–Patrick from NDepend teamJul 12, 2019 at 9:211Hi Patrick, I was referring to the missing images on the blog post:Identify Code Structure Patterns at a Glance. The images here don't provide the full context, so I was hoping to find out more from the article.–seanfJul 14, 2019 at 23:061See also Patrick's newer articleblog.ndepend.com/…which shares a lot of the same text and images, including some of the images above. (Archived asweb.archive.org/web/20191003234718/https://blog.ndepend.com/…)–seanfOct 3, 2019 at 23:57Add a comment|
|
I would like to start using DSM, but not sure how to get started.What does a good dependency matrix look like and why? How does it work?
|
Can someone show me what a good dependency matrix looks like and specify why?
|
The SonarQube Maven Plugin is an aggregator plugin. It's executed only on the root module. That's the reason why Maven flags sub-modules as SKIPPED, even if they are correctly analysed.ShareFollowansweredSep 2, 2016 at 11:47Simon BrandhofSimon Brandhof5,13611 gold badge2222 silver badges2828 bronze badgesAdd a comment|
|
I'm trying to run sonar on entire project using maven, but for some reason it skips submodules and analyse only root module. Is there any explanation of such a strange behaviour?Any help is greatly appreciated!Here is maven final output:ADDITIONmvn clean install doesn't skip anything, but mvn sonar:sonar do.
|
sonar skipping all modules except root one
|
You can use a plugin developed by the SonarQube community to support TypeScript.You will find it on the "Other Plugins" page on the officialSonarQube Plugin Library.ShareFollowansweredMar 24, 2017 at 10:08Fabrice - SonarSource TeamFabrice - SonarSource Team26.6k33 gold badges6363 silver badges5858 bronze badgesAdd a comment|
|
I'm usingnode_modules/codelyzerto analyze my source codeTypescript. I define manually rules intslint.jsonfile.But it is possible to analyzeTypescriptwithSonarQube?
|
Analyse Typescript with SonarQube
|
No, this is not possible. This is not the responsibility of SonarQube to handle this part. Instead, you should configure a CI server (like Jenkins) that will do this job: check if your repo has been updated, and if so, trigger a SonarQube analysis.You can read the following answer that is not exactly related to your question but that describes what you should do:Do I need sonar and sonar runner for Jenkins?ShareFolloweditedMay 23, 2017 at 12:18CommunityBot111 silver badgeansweredMar 5, 2015 at 11:26Fabrice - SonarSource TeamFabrice - SonarSource Team26.6k33 gold badges6363 silver badges5858 bronze badges1while I agree with this in principle, for my code base with lots of modules and lots of class files, the build time increases from 12 minutes to 96 minutes and ideally I want to run the analysis on every branch (to see the diff between two branches to help with code review)–Ali HAug 23, 2017 at 5:40Add a comment|
|
I have a SonarQube Instance running on my Debian 7 machine, and now I want that every time I push something in my git repository (BitBucket), the SonarQube Server automatically starts the scan from my repo.Is this possible? And how?Thanks
|
Can SonarQube fetch Data from a Git Repository?
|
I encountered the same issue, the tricks here are:The key of the sonar project must follow the naming convention, [groupid]:[artifactid]. They are separated by a ":". For example, if the keycom.example:sample, then the groupid iscom.example, artifactid issample.The eclipse project name must be same as the artifactid (case-sensitive).So, you need to 1) change the sonar project key to the naming convention above, 2) change the eclipse project name to the artifactid. Then eclipse will be able to automatically link your eclipse project to sonar project when your click the button "Find on server".ShareFolloweditedMar 20, 2012 at 9:51answeredMar 19, 2012 at 7:53Mingjiang ShiMingjiang Shi7,66522 gold badges2727 silver badges3232 bronze badgesAdd a comment|
|
I'm using Maven And Sonar with eclipse. I already have my maven projects on LocalHost 9000.
But when i go to eclipse configure>associate with sonar says that my groupId is empty. I think thats not supposed to happen. Anybody know how to fix this? Thanks
|
Empty GroupID sonar eclipse
|
I found your question while searching for a similar topic, and I noticed you had not received an answer. If you pass the -Dsonar.branch, each branch will be treated as a different project. As documented here:http://sonarqube.15.x6.nabble.com/Sonar-Analysis-for-Feature-Branches-td5004642.html#a5004647Hope this helps.ShareFollowansweredJun 3, 2014 at 17:50user3704176user370417611111 silver badge33 bronze badgesAdd a comment|
|
We currently have multiple feature releases in perforce. Each of these branches has POM files that contain a version tag and name tag that is tied to that branch.When we run sonar:sonar each branch scan overwrites another branch scan and you only see one at a time in the sonar gui.Can a sonar project be tied to maven GroupId>ArtifactId>Version or even instead of just being Tied to the GroupId.FYI, GroupId and ArtifactId do not change when we branch the POM.
|
running maven sonar:sonar on multiple branches of the same source project
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.