Response
stringlengths 8
2k
| Instruction
stringlengths 18
2k
| Prompt
stringlengths 14
160
|
---|---|---|
You can declare the constant outside of the enum:private static final String TYPE_A_NAME = "Type A";
public enum Type {
TYPEA(TYPE_A_NAME), TYPEB("B");
private String value;
Type(String value) {
}
}ShareFollowansweredJul 6, 2016 at 17:48Tea CurranTea Curran2,94322 gold badges1818 silver badges2222 bronze badges1Thanks for your answer :)–SofianeMar 14, 2017 at 15:42Add a comment|
|
I'm using SonarQube to verify and inspect my Java code, and i've encountered an issue with Avoid Duplicate Literals in an Enum class type, here is an exemple :public enum Products {
A ("Product A"),
C ("Product A"),
D ("Product B"),
P ("Product B");
private String name = "";
Products (String name){
this.name = name;
}
public String toString(){
return name;
}
}Sonar is telling me to declare the Strings 'Product A' and 'Product B' as a constant field, but you can't declare variables in Enum type class.
|
Avoid Duplicate Literals Sonar Error
|
Sorry, no. Your best bet here is pen and paper. :-/ShareFollowansweredNov 4, 2015 at 19:50G. Ann - SonarSource TeamG. Ann - SonarSource Team22.5k44 gold badges4242 silver badges8484 bronze badges5Is this still true? No way to copy off the filesystem either?–barbiepylonOct 25, 2016 at 12:50Yes, its still true–G. Ann - SonarSource TeamOct 26, 2016 at 13:241Surely this still cannot be true? @G.Ann-SonarSourceTeam–NanotronJul 8, 2019 at 8:59Yep. Still true @Nanotron.–G. Ann - SonarSource TeamJul 8, 2019 at 11:151@Nanotron, Yes it is true. And don't call me Shirley–Raja AnbazhaganMay 10, 2022 at 7:16Add a comment|
|
We are in the process of moving our SonarQube server and DB on to AWS and I want to be able to copy the setting and configuration from the existing server to the new one in AWS. The quality profiles have a back up operation, so these are easy to move. Is there something similar for the quality gates?
|
Backup SonarQube Quality Gates
|
I'm getting this kind of warnings for every Pylint rule that is disabled in the current quality profile, so it seems that this is a feature, not a bug (SonarQube 5.1.1 + Python plugin 1.6-SNAPSHOT)ShareFollowansweredJun 11, 2015 at 7:37alexandrulalexandrul13k1313 gold badges7373 silver badges9999 bronze badges1Based onjira.sonarsource.com/browse/SONARPY-291this behavior was improved starting with version 1.12–alexandrulNov 11, 2019 at 11:11Add a comment|
|
I am trying to use sonarQube with eclipse and python.
The quality profile was sonar way, and it had only 11 rules to start with. So i added the pylint rules and they are marked as activated. But when i run analyze on the project I don't get any more issues compared to before (when i used 11 rules). Then console looks something like this:16:38:49.091 INFO - Sensor org.sonar.plugins.python.pylint.PylintSensor@1603ae07...
16:38:50.079 WARN - Pylint rule 'C' is unknown in Sonar
16:38:50.079 WARN - Pylint rule 'C' is unknown in Sonar
16:38:50.079 WARN - Pylint rule 'C' is unknown in Sonar
16:38:50.079 WARN - Pylint rule 'C' is unknown in Sonar
16:38:50.079 WARN - Pylint rule 'C' is unknown in Sonar
16:38:50.079 WARN - Pylint rule 'C' is unknown in Sonar
16:38:50.079 WARN - Pylint rule 'C' is unknown in Sonar
16:38:50.079 WARN - Pylint rule 'C' is unknown in Sonar
|
Pylint rule is unknown to sonar
|
There is a commercial Developer Cockpit plugin that does just this, plus other nifty features.ShareFollowansweredApr 17, 2014 at 18:27MithfindelMithfindel4,64811 gold badge2323 silver badges3232 bronze badges1Thanks Mithfindel: the Developer Cockpit seems to do exactly what I need. Nevertheless, it is rather pricey at 7k Euro per instance per year, so I will give it time before I accept an answer: I hope and expect there are other practical ways to go about it, even if they aren't so elegant.–Tomislav Nakic-AlfirevicApr 21, 2014 at 17:44Add a comment|
|
Scenario: a team works on a Java/Maven/JUnit project using some kind of SCM. We would like to increase test coverage, meaning all developers should test code more intensively. Measuring overall test coverage improvements using something like SonarQube is easy enough, but you need to do it per developer in order to be able to recognise the outliers: engineers which have the best test coverage and engineers whose coverage is worst.How would you answer the question "what is the test coverage of code modified by developer X during the last month?" Is there a surrogate, approximate measure that could be followed more easily?
|
How to measure Java code unit test coverage per developer?
|
I found a workaround:
- I launch mvn clean install on parent project
- then I launch sonar:sonar at 'level 2' module, I can do it because all the code source to be analyzed is under the same module.At least it is working onmy sample projectbut currently I didn't handle yet to make it working on my real project.ShareFollowansweredJan 24, 2014 at 16:02Aurélien PupierAurélien Pupier15411 silver badge33 bronze badgesAdd a comment|
|
I encounter issue to configure a multilevel maven modules for Sonar Analysis.It is working fine with the following structure:parent module
|- level 1
|- module with code to analyzeBut if I add a depth to the module with code to analyze, I'm not able to configure it.parent module
|- level 1
|- level 2
|- module with code to analyzeI tried several configurations:with no special configuration:
I get anCan not execute SonarQube analysis: The project 'level 2' is already defined in SonarQube but not as a module of project 'level 1'. If you really want to stop directly analysing project 'level 2', please first delete it from SonarQube and then relaunch the analysis of project 'level 1'.error. I don't want to launch on level 1 because I have my integration tests at the same level, directly in parent module.using skippedModules property on level 1 and level 2: Only the parent module is analyzed.using includedModules by specifying "module with code to analyze": Only the parent module is analyzed.Does someone has an idea on how to handle it? (I mean without to modifying the hierarchy folder which is really helpful for some other requirements)Thanks by advance
|
How to configure Sonar and Maven multilevel modules?
|
Did you have an earlier version of the sonar eclipse plugin installed? It might be neccessary to remove some files manually and the start eclipse with the -clean flag.Find out more details in this discussion:http://sonarqube.15.x6.nabble.com/Eclipse-No-Sonar-Menus-although-installed-td5017264.htmlShareFollowansweredMay 22, 2014 at 18:48TimStefanHauschildtTimStefanHauschildt59466 silver badges2121 bronze badgesAdd a comment|
|
I have installed SonarQube in eclipse and restarted eclipse, but it doesn't show up in the preferences. I'm at a loss of what to try next.
|
SonarQube plugin in Eclipse doesn't show up in preferences
|
I'm assuming You are using In Your params:-Dsonar.coverage.exclusions=**/pom.xml,**/domain/dtos/**/*,**/domain/models/**/*,**/services/someClass.javaYou are mixing path and file exclusions which can cause problems, as mentioned here by Sonar Dev -https://community.sonarsource.com/t/sonar-coverage-exclusions-not-excluding-too-much/31276/4This should work:-Dsonar.coverage.exclusions=**/pom.xml,**/domain/dtos/**/*.*,**/domain/models/**/*.*,**/services/someClass.javaShareFollowansweredJun 3, 2022 at 12:02XupiXupi10411 silver badge99 bronze badgesAdd a comment|
|
I am writing generic code for an application which should support multiple country-specific changes, e.g, Brazil and France.There are some java classes in Brazil which are not required for France. Hence for running the sonarqube, I need to exclude those files for sonar coverage. Also, I would need to exclude dtos, util classes.We usually exclude the coverage for the classes in the pom file using tag. But I would be requiring to exclude the files with mvn clean install command.Traditional approach:But I want to exclude the java classes in the terminal like below:C:\Projects\web-application>mvn clean install -Dspring.profiles.active=dev -Dspring.profiles.country=brazil -Dsonar.coverage.exclusions=**/pom.xml,**/domain/dtos/**/*,**/domain/models/**/*,**/services/someClass.javaSonarqube runs but unable to exclude the files.
|
How to exclude files for sonar coverage using terminal command for running sonarqube?
|
You can avoid the "unknown type selector". You have to change the quality profile of the rule (like CSS in this case), in order to do that you must have admin access to sonarqube.Browse to quality profiles --> CSS, and then on the gear icon right of Sonar Way select ExtendThen browse to the rules, search the rule you want to customize, and you’ll have a change button that will allow you to customize selectors, ignoring types with a regex.See there:https://community.sonarsource.com/t/how-to-change-css-rule-selectors-should-be-known/31912ShareFolloweditedJul 12, 2021 at 15:12answeredJul 12, 2021 at 15:05julisjulis2644 bronze badgesAdd a comment|
|
I want Sonarqube to analyse my Angular application based on Angular Material.There is this kind of styling :.some-class {
mat-icon {
color: red;
}
}Since Angular Material is globally included through configuration in angular.json, Sonarqube seems to be unable to see mat-icon and shout out a bug :Unexpected unknown type selector "mat-icon"Is there a workaround ? a configuration ?
|
How to include Angular Material styles in Sonarque?
|
I think this is now possible out-of-the box with SonarSource pipes. It boils down to something likepipelines:
default:
- step:
clone:
depth: full
script:
- pipe: sonarsource/sonarqube-scan:1.2.0
variables:
SONAR_HOST_URL: ${SONAR_HOST_URL}
SONAR_TOKEN: ${SONAR_TOKEN}
- pipe: sonarsource/sonarqube-quality-gate:1.0.0
variables:
SONAR_TOKEN: ${SONAR_TOKEN}But better look into the pipes documentationhttps://bitbucket.org/product/features/pipelines/integrations?&search=sonarShareFollowansweredMar 29, 2023 at 11:58N1nguN1ngu3,45222 gold badges1818 silver badges4545 bronze badgesAdd a comment|
|
We are trying to integrate Bitbucket Pipelines (Cloud) with SonarQube (6.4).In particular, we want that the Pipelines build fails if the SonarQube analysis detects some quality gate violations in ourJavacode.Currently, we are using Jenkins (Multi-branch project), and we managed to achieve this behaviour thanks the commandwaitForQualityGate()included in the Jenkinsfile file (where I defined the pipeline to be executed).Now, we want to give a try to the Bitbucket Pipelines feature, since our Git Repository is hosted inBitbucket Cloud, and keep using our current server instance of SonarQube.For completeness, our projects are written in Java and managed by maven; we also use sonar-scanner plugin in the build process.Can anyone give me an hint? Or Does anyone have a clue how to achieve this behaviour?I am aware of the sonar plugin that creates reports as comments of a Pull Requests in BitBucket, but that is not what we need.Thanks in advance for your help.
|
Bitbucket Pipelines Read Quality Gate Results
|
InstallSonarQubeweb server as a first step. Default port will be localhost:9000.After installing SonarQube you need to create anAnt target. Sample Script is available onGitHub. If Hudson is working correctly earlier. It will pick up the changes in Ant Script and perform the Analysis. After the completion of Analysis report will be generated and accessible at SonarQube Web Dashboard.ShareFollowansweredMar 27, 2017 at 13:04Nauman RafiqueNauman Rafique38544 silver badges88 bronze badgesAdd a comment|
|
I want to use SonarQube for Code Quality analysis. I have Hudson as the CI tool and have integrated clearcase. How do I use SonarQube when the Ant build happens? Do I need to install SonarQube in a server and use a plugin to access it?
Can someone help me?
|
How do I use Sonar Plugin with Hudson?
|
That's a well known limitation of SonarQube. You can follow/vote for:https://jira.sonarsource.com/browse/SONARGRADL-5ShareFollowansweredSep 4, 2016 at 16:20Julien H. - SonarSource TeamJulien H. - SonarSource Team5,25711 gold badge2020 silver badges2525 bronze badges8Thanks! Good to know it has potential to be modified. Is there a way around it in the mean time? Can the source of parent be added to sonar.modules? I have not been successful at getting this to work. Is it possible to just skip all the sub modules and just scan the parent?–E PaizSep 5, 2016 at 1:36To skip all submodules you can probably override property sonar.modules to blank. But then you are on your own to pass all correct properties (sonar.sources, sonar.tests, sonar.java.binaries, ...)–Julien H. - SonarSource TeamSep 6, 2016 at 10:01I have been attempting to override the sonar.modules to blank, but nothing seems to change. I looked here and didn't find a "sonar.modules". Is there a different param I should be updating? I updated my question with the sonarqube properties block I am usingdocs.sonarqube.org/display/SONAR/Analysis+Parameters–E PaizSep 8, 2016 at 21:27Do you mean passing blank sonar.modules continue to analyze sub-modules?–Julien H. - SonarSource TeamSep 9, 2016 at 7:19Yes. Setting this property in my gradle script -- property "sonar.modules" , "" -- seems to have no effect.–E PaizSep 9, 2016 at 13:17|Show3more comments
|
I have a multi-project gradle build that I am attempting to use sonarqube to analyze. It successfully analyzes all the nested modules in the project but doesn't analyze the base or parent project.I see this warning in the logs:12:07:23.332 WARN - /!\ A multi-module project can't have source folders, so 'C:\workspaces\platform\myProject\src\main\java' won't be used for the analysis. If you want to analyse files of this folder, you should create another sub-module and move them inside it.Is there a way to move the parent src, test, and binary as folders to be scanned with out creating submodule out of the parent?My SonarQube properties look like this:sonarqube{
properties {
property "sonar.host.url", "http://ww:80"
property "sonar.jdbc.url", "jdbc:jtds:sqlserver://db:5555;databaseName=sonarqube"
property "sonar.jdbc.driverClassName", "net.sourceforge.jtds.jdbc.Driver"
property "sonar.jdbc.username", "u"
property "sonar.jdbc.password", "p"
property "sonar.scm.disabled", "true"
property "sonar.junit.reportsPath", "${buildDir}/test-results"
property "sonar.jacoco.reportPath", "${buildDir}/jacoco/test.exec"
property "sonar.modules" , "" }
}
|
MultiProject Gradle Build that will analyze the Parent Project?
|
There is no possibility to send a report at the moment.Regarding thedocumentationyou have following options to enable a notification:Changes in issues assigned to me or reported by meIssues resolved as false positive or won't fixMy New IssuesNew issuesNew quality gate statusPerhaps you can define aQuality Gateand if it fails or succeed you will receive a mail.ShareFolloweditedJul 25, 2017 at 12:55JavierSA79311 gold badge1111 silver badges2727 bronze badgesansweredJun 2, 2016 at 7:12CSchulzCSchulz10.9k1111 gold badges6060 silver badges116116 bronze badgesAdd a comment|
|
I am using SonarQube Server 5.5 which doesn't suppport PDF report plugin
|
How to send Sonar Analysis report in email from Jenkins?
|
Yes, SonarQube is probably getting confused about the use of+=inside the loop.String tag = "prefix";is created inside the loop so there is no String concatenation inside aforloop and, technically, the warning is a false positive.Note that you could still useStringBuilderto append both part of the tag, but you'd have to measure if it's necessary or not.ShareFollowansweredDec 15, 2015 at 11:55TunakiTunaki135k4646 gold badges355355 silver badges431431 bronze badges3I am really surprised SonarQube doesn't filter variables created INSIDE the loop and then consumed by something else for this rule. I got away by creating a StringBuilder outside the loop, instantiating and appending in the loop, and pushing the builder.toString(). The code is a bit more verbose, but SonarQube stopped crying...–Sir4ur0nDec 15, 2015 at 16:461@jdebon A note of warning though: don't become a slave of the tool. False positives are a reality and you can declare a violation as false positive in SonarQube. This might be better than reworking your code.–TunakiDec 15, 2015 at 16:502Yup, I'm aware of that =) But in my case it was still a slight performance improvement, so I didn't mind. If the concatenation had happened all on the same line, I would have flagged as FP. Thanks =)–Sir4ur0nDec 15, 2015 at 17:04Add a comment|
|
I have some code looking like this (I replaced my business variables with generic ones):Map<String, String> map = new HashMap<String, String>();
for (int i = 1; i < 10; i++) {
String suffix1 = retrieveValue1(i);
String suffix2 = retrieveValue2(i);
String tag = "prefix";
if (suffix1 != null) {
tag += suffix1;
}
else {
tag += suffix2;
}
map.put(tag.toUpperCase(), "on");
}What bugs me is that I receive the following SonarQube violation:Performance - Method concatenates strings using + in a loopIn my opinion this is a false-positive (because there is no real loop on a String here) but I'd like to double check first.I could not find any similar case with my friend Google.Is it a false-positive, or is there a real performance loss in my loop please?
|
False positive SonarQube violation on String concatenation in loop
|
LDAP plugin 1.5.1 with fix for this issue (LDAP-49is released and available for download from SonarQube's update center.Refer toSonarQube LDAP plugin documentationpage:LDAP 1.5.1 – Dec 02, 2015 – Compatible with SonarQube 5.2+
Bug fixes for Active Directory environmentsShareFollowansweredDec 3, 2015 at 4:36Sulabh UpadhyaySulabh Upadhyay10255 bronze badges0Add a comment|
|
AD login is not possible after upgrading from LDAP 1.4. In the TRACE log the following error message is logged:DEBUG web[o.s.p.l.w.WindowsUsersProvider] Requesting details for user: xxxxxx
ERROR web[rails] Error from external users provider: exception Java::Com4j::ExecutionException: com4j.ComException: 8007203a Failed to MkParseDisplayName : The server is not operational. : .\com4j.cpp:217Removing the LDAP settings from sonar.properties did not help. After downgrading to LDAP 1.4 everything works again. Did we miss some configuration setup?
|
SonarQube 5.2, LDAP plugin 1.5: com4j.ComException
|
Automated emails can be configured only for following points.Changes in issues assigned to any user or reported by userNew false positivesNew issuesNew quality gate status (fail to pass and pass to fail)Once there are any changes identified by Sonar Analysis in the above mentioned points , SonarQube will send emails to every member of the team.for more details you can check the user profile.ShareFollowansweredAug 7, 2015 at 5:50Abhijeet KambleAbhijeet Kamble3,19122 gold badges3030 silver badges3737 bronze badges2There's no concept of a "team" in Sonarqube that I can find. There are Groups. So let's say I have 10 users and 8 projects in SonarQube. I have configured my email server in Sonarqube but haven't found anywhere to configure rules around when emails are sent and why. If an Analysis triggers a quality gate for one of the 8 projects, will it automatically email all 10 users?–Kevin MMar 17, 2017 at 15:211Right, @KevinM but also think if you have 100+ user and same 100+ project( consider you are working on a centralized Sonar) then do you still want to unnecessary bug all 100 users even if they are not interested...–Abhijeet KambleMar 18, 2017 at 12:04Add a comment|
|
SonarQube Quality Gate is a great feature but the only problem I am having is that we dont get email alert everytime there is low code coverage on new code less than quality gate thresold value.For example:Quality Gate Thresold value for code coverage on new code < 80% send email alert1st analysis : code coverage is 85%2nd analysis : code coverage is 70% - email alert received.-- Quality gate status: Orange-- New quality gate threshold:Coverage on new code < 80 since...3rd analysis : code coverage is 67% - no email alert is received.4th analysis : code coverage is 50% - no email alert is received.The email alert is received only when the color/state changes from one to another. We would like to setup email alert for every analysis it runs and if the code coverage on new code is less than thresold value, trigger email.
|
How to configure Sonarqube Quality Gate inorder to sent email alert everytime there is low code coverage than thresold value
|
Give a try toSonarLint for Eclipse. Much more faster than the SonarQube Eclipse plugin, it will make you able to run SonarQube analysis without the need to get connected to SonarQube server.If you want to connect to a SonarQube server anyway in order to synchronize analysis configuration, it is also possible but not required. ;)ShareFollowansweredMay 12, 2016 at 8:37Jean-Denis CoffreJean-Denis Coffre15866 bronze badgesAdd a comment|
|
Steps followed,-> Installed sonar plugin in Eclipse 4.2.2 by following the steps from -http://eclipse.dzone.com/articles/static-code-analysis-and-> Build project with mvn sonar:sonar command.-> Right clicked project in Eclipse to associate to sonar and get the below error in "Problem Occurred popup"'Synchronize issues' has encountered a problem.
Error during issue query
org.sonar.wsclient.issue.IssueQuery@d6cd19How to fix this? Any help?
|
Synchronize issues has encountered - Sonar integration error in eclipse
|
Look like the reason why code is not covered is in theFAQCode with exceptions shows no coverage. Why?JaCoCo determines code execution with so called probes. Probes are
inserted into the control flow at certain positions. Code is
considered as executed when a subsequent probe has been executed. In
case of exceptions such a sequence of instructions is aborted
somewhere in the middle and not marked as executed.Still i don't understand why the coverage of the direct throw still appears on sonarShareFollowansweredJan 25, 2015 at 3:38Thai TranThai Tran9,84577 gold badges4545 silver badges6666 bronze badges2Which version of SonarQube are you using?–CSchulzJan 27, 2015 at 8:45@CSchulz: I used both 4.2 and 4.5–Thai TranJan 28, 2015 at 2:13Add a comment|
|
I am writing code coverage for my project and experiencing a weird behavior. I have a function like thispublic void testException(int i) throws Exception {
if (i == 0) {
throw new Exception("exception");
}
}and the test case@Test
public void testException() {
try {
mapper.testException(0);
fail("Wrong");
} catch (Exception ex) {
assertEquals("exception", ex.getMessage());
}
}After running test case through maven (mvn sonar:sonar), then the branch is covered in Sonar. However, if the tested function is like thispublic void testException(int i) throws Exception {
if (i == 0) {
throwException();
}
}
public void throwException() throws Exception {
throw new Exception("exception");
}then theifbranch is not covered, though the inner ofthrowExceptionfunction is actually executed. Is there anyway to overcome this problem? I need to cover 100% of the class
|
Sonar cannot cover branches calling to Exception throwing function
|
As far as I know you can't exclude only this type of duplication from your analyse. You can only exclude the whole file from your analyse, but this is not a good idea. Maybe you can try out theSourceMeter plugin for SonarQube. It has a bit more sophisticated duplication finder. You can find an online demohere.ShareFollowansweredSep 10, 2014 at 7:59L. LangóL. Langó1,09977 silver badges1111 bronze badgesAdd a comment|
|
SonarQube shows me this kind of duplication:1 package pl.com.bernas.ioz.user.domain;
2
3 import java.io.Serializable;This is not desired behaviour.Can I disable this kind of duplication?
But I don't want to disable duplication rule at all, or add class to ignore. Can I ignore just this particular case?
|
SonarQube - duplicated block, how to change configuration
|
Jacoco is based on bytecode analysis. The exec file is combined with the class files to get the final code coverage values. The problem in my case was that the bytecode generated by Eclipse compiler for Java (for Jacoco eclipse plug-in) and that produced by Javac (during analysis on sonar runner) were different. Hence, the code coverage values generated by both tools were different.ShareFollowansweredAug 20, 2014 at 15:21umairaslamumairaslam36744 silver badges2323 bronze badges2how did you fix it?–Nelson RamirezOct 24, 2016 at 20:05@NelsonRamirez use exact same compiler (vendor, version) in both cases–GodinOct 31, 2016 at 20:32Add a comment|
|
I have a Java project. The code coverage of that project according to Jacoco eclipse plug-in (EclEmma Java Code Coverage 2.3.1.201405111647) is 22.3%. I generate the .exec report and feed it to SonarQube and run an analysis with sonar runner. The code coverage shown on SonarQube's web interface as a result is 20.2%. The coverage values at package level are also different to what shown by Jacoco's eclipse plug-in. How is that possible? Isn't SonarQube taking values from the .exec report generated by Jacoco?
|
Code coverage percentage values in Jacoco eclipse plug-in and SonarQube are different
|
I figured question number 2 out:List<Metric> smq = sonar.findAll(MetricQuery.all());
System.out.println(smq);
for(int i = 0; i< smq.size(); i++){
System.out.println(smq.get(i));
}ShareFollowansweredMar 18, 2013 at 9:55LStrikeLStrike1,62044 gold badges2727 silver badges5959 bronze badgesAdd a comment|
|
I have two questions regarding sonar:I have taken a look at the database of sonar. I was wondering where sonar stores the results of each measurement?I found only the tablemeasure_data, but the field data looks to me like a has value.
Can anyone tell me where sonar stores the data of all measurements?Yes I know, that it is better to use the REST API, and I will do it, but I also want to know, how the database is used by sonar itself.Is there a way by using the API to get a full list of all used metrics?
|
Sonar database structure & sonar api metrics
|
Plugins can provide static files like images, CSS or JS files. They have to be copied in src/main/resources/static and then can by accessible from the public URL :
http:///static//You can read more here :http://docs.codehaus.org/display/SONAR/Extend+Web+Application#ExtendWebApplication-StaticfilesShareFollowansweredNov 15, 2012 at 9:32ppapapetrouppapapetrou1,65399 silver badges1313 bronze badges3Thanks for the answer. I used this idea in my local mechine and its working perfectly. but it's not working on jenkins.–ѕтƒNov 15, 2012 at 10:08Jenkins? Am I miss something. Don't you implement a Sonar plugin?–ppapapetrouNov 15, 2012 at 10:14junkins is an other server i am working with.. this query is not working there–ѕтƒNov 15, 2012 at 11:06Add a comment|
|
in sonar 2.5, there is jit-yc.js file in javascript folder.this js file is used to develop the radiator plugin. But this file is removed from sonar 3.1.is there any other js file same as jit.jy.js in sonar3.1. I need this file to build a plugin.Is there any other way to use this file.
|
sonar 3.1 javascript issue
|
This is currently not possible. The best way to achieve this is to replay the project history by running Sonar analyses with the "-Dsonar.projectDate=xxxx-xx-xx" property.For more information, take a look a the "sonar.projectDate" description on the"Analysis Parameters" documentation page.ShareFolloweditedMar 20, 2014 at 12:50answeredJan 25, 2013 at 13:18Fabrice - SonarSource TeamFabrice - SonarSource Team26.6k33 gold badges6363 silver badges5858 bronze badges2Is it possible with SonarQube 4.x? I have set up a new instance with the latest Sonar, and have some projects that need moving across, with their history intact. Failing that, could you elaborate on the answer you gave above, as it's unclear exactly what to do?–RCrossMar 20, 2014 at 12:25I added a link to the doc page that explains this.–Fabrice - SonarSource TeamMar 20, 2014 at 12:51Add a comment|
|
Is there anyway to migrate individual projects and merge them into an existing instance of Sonar?Background:I've setup a new instance of Sonar by performing a normal backup and restore. Another team, also using Sonar, want to migrate their projects over to this new server as well. I'm now faced with a data merging problem.
|
Import project into Sonar
|
Please try to add the following dependency into your pom.xml file
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
and Download lombok.jar from the given link
https://projectlombok.org/download
Now if it is zipped unzip it first and then copy it to the directory
where you have your SpringToolSuits(STS installed).
Let say your STS version is 4.11.0.RELEASE then copy lombok.jar to STS
directory/sts-4.11.0.RELEASE i.e. inside STS/sts-4.11.0.RELEASE/
Now try to rebuild and update your project.ShareFolloweditedFeb 2, 2022 at 6:15answeredFeb 1, 2022 at 14:33KM PRIYA AGRAWALKM PRIYA AGRAWAL6644 bronze badges0Add a comment|
|
I am using sonar version 8.9.6.
I know this issue has been asked around a lot of times and i have tried a lot of those and none of the solutions has worked for me.following are some of the things that i have tried.1)<sonar.exclusions>
// my domain package here
</sonar.exclusions>added the following plugin<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<includeArtifactIds>lombok</includeArtifactIds>
</configuration>
</execution>
</executions>
</plugin>and then added the following property<sonar.java.libraries>target/dependency/*.jar</sonar.java.libraries>Added lombok.config and added the following propertiesconfig.stopBubbling = true
lombok.addLombokGeneratedAnnotation = trueNone of these have worked for me and especially sonar exclusions doesn't work at all.
Any help would be appreciated and Thanks in advance.
|
Sonar Doesn't pick lombok Annotations ( Remove unused private field)
|
To extend what @JulioMalves said, this is how I set up the ignore rule on SonarQube's admin interface.ShareFollowansweredNov 5, 2021 at 23:29shicholasshicholas6,14344 gold badges2828 silver badges3838 bronze badgesAdd a comment|
|
I created an example Next.js application usingnpx create-next-app. After sonarqube scan, there is 1 code smell appeared that says "Default export names and file names should match"(related link). But since_app.jsfile is a special file for the Next.js framework I can't rename it and can't solve that code smell. How can I fix this code smell?
|
How to fix Sonarqube "Rename this file" code smell that contained in _app.js in Next.js?
|
Best I could figure out was ViewEncapsulation.none and then usingapp-component-name {}to prevent all the css from bleeding outShareFollowansweredMay 26, 2021 at 15:01RobertRobert1Add a comment|
|
In ourproject , we have used angular material for development. We have overridden theangular material styles using ::ng-deepto customize the CSS properties.While using ::ng-deep getting an error as "Unexpected unknown pseudo-element selector ::ng-deep" in sonar report.Prior to ::ng-deep team tried to override the properties using parent classes ( mat-input-underline.mat-form-field-underline ) and by using customstyle.scss file but It didn't work as expected.Just curious to know whether there is any alternate solution for this issue or shall we skip this rule in our sonar metrics. Any one please advise on this ?ReferenceWhat to use in place of ::ng-deep
|
SonarQube - ::ng-deep getting an error as "Unexpected unknown pseudo-element selector ::ng-deep"
|
You canresolvethe issueas false positive. This will make this issue disappear from your dashboard:Select the issueClick on Bulk change > Selected issue(s)Choose Transition, Resolve as false positiveApplyThat's it.ShareFollowansweredSep 14, 2018 at 9:06BenoitBenoit5,27422 gold badges2727 silver badges4747 bronze badges2Thanks. Two questions: 1) Will this still be marked as false positives if I rerun the sonarqube analysis? 2) If there is duplicated code from other source files in the future, won't this duplication be ignored?–Fischer LudrianSep 14, 2018 at 9:10@FischerLudrian 1) No the same issue will be ignored in subsequent rerun, you won't have to resolve as false positive again and again. 2) No only the specific duplication you resolved is ignored, not the whole rule.–BenoitSep 14, 2018 at 9:15Add a comment|
|
I use Sonarqube with Jenkins to check various violations. There are two classes,AandB, that have a lot of duplicated code. I know that and accept that. Therefore, I'd like to ignore these violations. However, I still want to be informed about the duplicated code from other classes, like C. I just want to ignore the duplicated code betweenAandB. How can I do that?
|
Exclude Sonarqube's duplicate code check between two specific classes
|
Although this question is 2 years old, however there are two ways to do static analysis of the Dockerfile.usingFromLatestusingHadolintOption#2 is mostly preferable since this can be used as an automated process inside CICD pipelines.Hadolint also provide ways to exclude messages/errors using ".hadolint.yml"ShareFollowansweredJan 9, 2020 at 7:43ankidaemonankidaemon1,3731414 silver badges2020 bronze badgesAdd a comment|
|
I was wondering if there is any tool support for analyzing the content of Dockerfiles. Syntax checks of course, but also highlighting references to older packages that need to be updated.I'm usingSonarQubefor static code analysis for other code but if it does not support it (I could not find any information that it does), is there is any other tool that does this?
|
Static code analysis of Dockerfiles?
|
Looks like a wrong rule.The method should also check @Componentprivate static boolean isSpringComponent(SymbolMetadata clazzMeta) {
return clazzMeta.isAnnotatedWith("org.springframework.stereotype.Controller")
|| clazzMeta.isAnnotatedWith("org.springframework.stereotype.Service")
|| clazzMeta.isAnnotatedWith("org.springframework.stereotype.Repository");
}Also there might be cases with fields annotated with@Value("${some.property}"etc.ShareFollowansweredApr 21, 2017 at 7:59StanislavLStanislavL57.2k99 gold badges6969 silver badges9999 bronze badges1Version 4.9 will address this to some degree. Discussion and community PR are still open. Join in?groups.google.com/d/topic/sonarqube/T-f83S9mvQU/discussion–G. Ann - SonarSource TeamApr 21, 2017 at 13:26Add a comment|
|
The SonarJava analyzer introduced in latest release (4.8.0.9441) among others rules3749(Members of Spring components should be "@Autowired"). It turns out, that SONAR rules out completely other autowiring modes than field injection, i. e. constructor/setter @Autowired doesn't prevent this rule from failing. Is there any rationale behind this?
|
SONAR: Members of Spring components should be "@Autowired"
|
Out-of-the box Sonar supports Jacoco (embedded into lastest versions of eclEmma) and Cobertura engine to report code coverage by unit tests just like eclEmma. So normally they should output the same results. My guess is that you dont have a correct configuration in your Sonar configuration and some tests dont run so it would be nice if you paste it so that we can have a look.ShareFollowansweredMay 19, 2016 at 12:24Alexius DIAKOGIANNISAlexius DIAKOGIANNIS2,53522 gold badges2222 silver badges3232 bronze badgesAdd a comment|
|
I am running eclemma as well as for measuring the test coverage in my project.
I noticed a weird thing,that I am able to get correct results with the help of Eclemma but the results from sonar are different and it is not covering some of the code which expect to be covered by the test cases I have written.Why do results from both the tools differ?
|
Test coverage Eclemma vs Sonar
|
+50I think you need to rename you modules like if your project is abc.
Please change your modules like abc_xxx etc...it may work for youShareFollowansweredSep 22, 2015 at 5:16anilanil51Add a comment|
|
We have a case where there are multiple projects configured in sonar. All the project have different modules with same names.With this, as and when we execute sonar for one of the project, the execution is getting terminated with below error.[ERROR] Failed to execute goal org.codehaus.mojo:sonar-maven-plugin:2.6:sonar (default-cli) on project XXX: Module "XXXX" is already part of project "YYYY" -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.codehaus.mojo:sonar-maven-plugin:2.6:sonar (default-cli) on project XXXX: Module "YYYY" is already part of project "YYYY"It seems that because the module name is same , Sonar is terminating the execution. Note that we are using sonar version 4.5.5 and facing this issue. While earlier we were using sonar version 4.1.1 and with that version the execution was successful (probably sonar was overriding earlier report with the newer one in case of conflicting module name).Please suggest possible solution for this? Thanks,Complete error log is available herehttps://groups.google.com/forum/?utm_medium=email&utm_source=footer#!msg/sonarqube/-L7cby77-28/6L6zPlb6AAAJ
|
We have a case where there are multiple projects configured in sonar. All the project have different modules with same names?
|
ExtendScript is based on ECMAScript (JavaScript). So you should be able to use Sonarqube for this. I wasn't sure about this (didn't know a thing about sonarqube -- now I do), but I plugged some jsx code into this demo, which uses sonarqube ...http://google.github.io/traceur-compiler/demo/repl.html#and it seemed to work fine.ShareFollowansweredFeb 26, 2015 at 21:43CRGreenCRGreen3,43611 gold badge1515 silver badges2424 bronze badges1Nope it does not work. SonarQube Javascript parser fails on JSX syntax. E.g. ERROR - Parse error at line 63. It fails where in the render method you use HTML.–GEMISep 10, 2015 at 8:08Add a comment|
|
I have a list of files with .jsx extension which needs to be analyzed with Sonar. No plugin is available in Sonarqube for the same. Can anything be done to the existing JavaScript Sonar plugin to analyze .jsx files.Anyone?
|
Sonar analysis for ExtendScript(JSX) files
|
Just ran into this issue this morning. Resolved it by configuring the server to access the MySQL database:http://docs.codehaus.org/display/SONAR/InstallingYou want to edit the {sonar_home}/conf/sonar.properties and uncomment the url, username, and password.You might have to add a new database user if you would like.ShareFollowansweredNov 18, 2014 at 17:22caseycasey2811 silver badge66 bronze badges1I will try out this solution, but the thing is i have also setup Sonar on a windows machine and there it works fine without editing the default properties.–Ash AshNov 19, 2014 at 14:57Add a comment|
|
I have recently setup Sonarqube-4.5.1 on my linux machine ( x86_64 x86_64 x86_64 GNU/Linux ).I am able to start sonar with./sonar.sh startcommand. On checking the sonar status with./sonar.sh statuscommand, it saysSonarQube is running (18493)but when i try to open the dashboard urlhttp://ip-address:9000it shows "Connection refused" message on the browser.On running themvn sonar:sonar -Dsonar.host.url=http://localhost:9000command i get the following error:[ERROR] Failed to execute goal org.codehaus.mojo:sonar-maven-plugin:2.4:sonar (default-cli) on project app-dao: Execution default-cli of goal org.codehaus.mojo:sonar-maven-plugin:2.4:sonar failed: SonarQube server can not be reached at http://localhost:9000. Please check the parameter 'sonar.host.url'. Connection refused -> [Help 1]I also tried the solution mentioned atmaven connecting to Sonarand added the following entries in my maven's conf/settings.xml file, but still unable to fix the issue.<profile>
<id>sonar</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<!-- EXAMPLE FOR MYSQL -->
<sonar.jdbc.username>admin</sonar.jdbc.username>
<sonar.jdbc.password>admin</sonar.jdbc.password>
<sonar.host.url>http://localhost:9000</sonar.host.url>
</properties>
</profile>
|
SonarQube server can not be reached at http://localhost:9000 with Sonarqube-4.5.1
|
You need to be sure the format generated by Jasmine is compliant with the JUnit XML format expected by the JavaScript Plugin :http://docs.sonarqube.org/display/PLUG/JavaScript+Unit+Tests+Execution+Reports+ImportYou can also have a look at the format supported by the Generic Test Coverage Plugin :http://docs.sonarqube.org/display/SONAR/Generic+Test+CoverageYou don't need to merge the XML reports, there are different sonar.* properties to feed depending on the way you want to load your data: thru the JavaScript Plugin or the Generic Test Coverage. As a consequence, you don't need to run SonarQube analysis twice.ShareFollowansweredNov 19, 2015 at 15:01Alexandre - SonarSourceAlexandre - SonarSource51922 silver badges55 bronze badgesAdd a comment|
|
Our project uses Maven as the build tool and we are using Sonar to track quality. JUnit tests are executed by SureFire and the results are displayed in Sonar. We've added some JavaScript tests which are run by thejasmine-maven-pluginand want to include these results in the Sonar project.The plugin generates a JUnit style XML report. How should we go about including the XML report in Sonar? Do we want to merge the XML reports as part of the build maybe?
|
How to get Sonar to report both Java and JavaScript tests run by Maven
|
I assume you are not facing a sonar or findbugs problem, but you probably
have a maven specific problem, e.g. a problem with your multi module pom - you actually even stated it "target/classes is empty". Focus on that before focusing on sonar or findbugs.
As a workaround, try setting up a jenkins build for a specific module first. When this is properly built with class files in your target folder, add a sonar goal to your jenkins project and I'd expect it to work.p.s.: Compare:Maven sonar findbugs fails with no source to compileShareFolloweditedMay 23, 2017 at 11:45CommunityBot111 silver badgeansweredApr 26, 2015 at 14:06Marcus BielMarcus Biel44044 silver badges1515 bronze badges0Add a comment|
|
In a Java project, I'm using Sonar with Maven and it's work fine with "sonar way" profile. But when switching to the "Sonar way with Findbugs" profile, it fails :"Can not execute Sonar: Can not execute Findbugs: Findbugs needs sources to be compiled. Please build project before executing sonar and check the location of compiled classes."The project is correctly build before the execution of Sonar. But the root module / project doesn't contains any classes. So target/classes is emptyMy project is composed of several modules and a root pom.xmlProject|_Module 1|_Module 2|_Module 3pom.xmlSonar is running fine for every modules and try to analyze the root project but this one doesn't contains any classes so it fails.Is there a way to exclude the root project / module (exclude root module is not possible) or tell sonar to only generate a warning in this case or another solution?Thanks in advance.
|
Sonar / findbugs fails when root project doesn't contains any classes
|
-1Someone looking for the same solution can try following:reportPath to reportPathssonar.javascript.lcov.reportPaths=coverage/lcov.infoOR (in case of tyescript)sonar.typescript.lcov.reportPath=coverage/lcov.infoShareFollowansweredSep 7, 2018 at 11:18Arun SainiArun Saini7,27411 gold badge2020 silver badges2424 bronze badgesAdd a comment|
|
I am getting the below error whenever I try to import lcov report in to SONAR15:00:17.230 WARN: Could not resolve 1 file paths in [/opt/app/workload/jenkins_25172/data/jobs/DEV02/workspace/coverage/lcov.info], first unresolved path: /opt/app/workload/jenkins_25172/data/jobs/DEV02/workspace/common/actions/actionCreators.jsSONAR properties:sonar.login=**
sonar.password=**
sonar.verbose=true
sonar.language=js
sonar.sources=.
sonar.projectBaseDir=/opt/app/workload/jenkins_25172/data/jobs/DEV02/workspace/
sonar.inclusions=coverage/**/*
sonar.javascript.lcov.reportPath=coverage/lcov.info
sonar.projectKey=test2
sonar.projectName=test2
sonar.projectVersion=version1
sonar.branch=test
sonar.att.view.type=dev
sonar.tattletale.enabled=falseAny input to fix this issue is appreciated.
|
SONARQUBE lcov import error - Could not resolve 1 file paths
|
If there is no FindBugs rule activated in the Quality Profile used by this project then it looks like you're impacted by a bug in the FindBugs Plugin:Issue #37-FindBugs plugin should not start an analysis if no rules are enabledShareFollowansweredOct 25, 2016 at 9:24Nicolas B.Nicolas B.7,2631818 silver badges2929 bronze badgesAdd a comment|
|
I have an android project and was asked to setup sonar analysis.There is findbugs plugin installed on the Sonarqube server and I cannot remove it as other java projects are using it.The problem is I don't want the findbugs analysis, but it looks like it is mandatory when I config the sonar-project.properties like this:# Language
sonar.language=java
sonar.profile=Android LintI triedsonar.findbugs.skip=true
sonar.findbugs.disabled=truebut no luckso how can I disable the findbugs sensor for this specific project?
|
Is it possible to disable Findbugs Sensor for specific java project with sonar-scanner
|
URLapi/rules/search?languages=javais the correct way to get all Java rules. Response is paginated, so only 10 rules are returned by default :{
"total": 781,
"p": 1,
"ps": 10,
"rules": [ <here are 10 rules ]
}Use pagination parameterp(page index) for traversing all results. Note that the page size can be changed with parameterps(defaults 10).ShareFollowansweredNov 30, 2016 at 12:48Simon BrandhofSimon Brandhof5,13611 gold badge2222 silver badges2828 bronze badges1thank you it worked. I used REST client on add-on on firefox and extracted the details as :localhost:9000/api/rules/…–shavanthaDec 5, 2016 at 11:22Add a comment|
|
Appriciate if I can get help for the below scenario. My issues to identify how to extract/export all java rules on SonarQube 4.5.7. I tried the below two API calls but I get a "The page you were looking for doesn't exist".The sonarqube version I have shows 781 java rules my objective is to extract them to an excel or a csv file[1]curl -X GET -v -u admin:adminhttp://localhost:9000/api/rules?language=java[2]curl -X GET -v -u admin:adminhttp://localhost:9000/api/rules/search?languages=java>> java.jsonThe second option seems to generate an output but not all 781 rules are extracted
thanks,shavantha
|
How to extract or export rules from SonarQube
|
The code given in the question has no synchronization. I assume that you synchronize on thethis.listValidRessomewhere else in your code. And exactly that is what Sonar tells you: if you synchronize on a resource do so onallusages or don't do it at all and have someone else deal with it.Basically it is a design decision:You canchose tonotsynchronizeand have the client bother with it. The advantage is that without synchronization it will be significantly faster. So if your class is used in a single-threaded setup, it will be better to ditch synchronization.Butdocument it clearly to benotthreadsafe or a clientwilluse it multithreaded and complain about weird errors...If youchose to(or have to)synchronize, then do it on every usage of the critical resource. There are different ways to achieve this. Maybe you want to show a usage of the resource that you in fact did synchronize. Maybe I or someone else can give you some good advice on that.ShareFolloweditedSep 8, 2017 at 11:34answeredMay 28, 2013 at 15:56FildorFildor15.5k44 gold badges3939 silver badges7070 bronze badges0Add a comment|
|
Whats wrong with this...?public final void setListValid(final List<ValidRes> listValidRes) {
this.listValidRes = listValidRes;
}Sonar yells me at:Inconsistent synchronization of xxx.listValidRes; locked 50% of timeDoes anyone know what things i need to do ?
|
Multithreaded correctness - Inconsistent synchronization
|
I do not know much aboutSonarQube. I just figured outSonarQubeis tool to check the code quality and get that it requiredawaitonly prefix with thepromisesand theremongoosefails even having.then.Mongoose queries do not return "fully-fledged" promise even they have.then(). So in order to get "fully-fledged" promise you need to use.exec()function.const user = await User.findOne({ _id: req.params.id }).exec()ShareFollowansweredJun 5, 2019 at 9:37AshhAshh45.6k1515 gold badges107107 silver badges135135 bronze badges0Add a comment|
|
I like the async await syntax, and I use it a lot with mongoose.So in my project there is plenty of :const user = await User.findOne({
_id: req.params.id
})Which works just as expected. However, in sonarqube, I have these errors :Refactor this redundant 'await' on a non-promise.And the sonarqube rule i :It is possible to use await on values which are not Promises, but it's
useless and misleading. The point of await is to pause execution until
the Promise's asynchronous code has run to completion. With anything
other than a Promise, there's nothing to wait for.This rule raises an issue when an awaited value is guaranteed not to be a Promise.Noncompliant Code Examplelet x = 42;
await x; // NoncompliantCompliant Solutionlet x = new Promise(resolve => resolve(42));
await x;
let y = p ? 42 : new Promise(resolve => resolve(42));
await y;I am using mongo 4.0 and mongoose 5.3.1Since I can use the.then,.catchsyntax I thought that I was dealing with promise so how could I fix that ?
|
Mongoose promise and sonarqube
|
If your source code is written in TypeScript, the coverage report (lcov.info) must contain information about TypeScript files, and not compiled JavaScript. The property you must be using in this case issonar.typescript.lcov.reportPaths.You can check out this example (https://github.com/SonarSource/SonarTS-example) to get more details.ShareFollowansweredJan 22, 2018 at 14:12Stas VilchikStas Vilchik43922 silver badges44 bronze badges4I understand but this does not justifySonarQubefrom trying to provide coverage for filesnotin mylcov.info–pkaramolJan 22, 2018 at 14:31If I correctly understand what you're saying, SonarQube automatically sets coverage to 0 for all files that are not included in the report. You can opt-out this behavior by ignoring code coverage on some files (the ones that are not included in the report). See more:docs.sonarqube.org/display/SONAR/…–Stas VilchikJan 22, 2018 at 20:41I actually tried this and it worked. However the problem now became: hownotto include generated.jsin the static code analysis (not the coverage report), As I am saying in the question body, usingsonar.coverage.exclusions=**/*.tspartially solves the problem given that code analysis is done for both*.tsand*.js, while I wantonly*.ts.–pkaramolJan 22, 2018 at 22:264sonar.typescript.lcov.reportPaths has now been depreciated, use sonar.javascript.lcov.reportPaths. Reference:docs.sonarqube.org/latest/analysis/coverage–Ramandeep SinghApr 26, 2020 at 15:00Add a comment|
|
I am scanning auiproject.The source code is intypescript.gulp test-coveragegenerates.jsfiles (which are then scanned for coverage). (each.tsfile gets a.jsfile right next to it, in the same location)I am pointing the scanner to thelcov.infofile as follows:sonar.javascript.lcov.reportPaths=test-coverage/lcov.infoThe problem:Thelcov.info, provides coverage information for.jsfilesFor some reason, SonarQube also provides coverage information for the*.tsfiles (althoughnotincorporated
in the test coverage report).Why is that?If I explicitly usesonar.inclusions=**/*.tsorsonar.language=tsthe.jsfiles will be ignored from the coverage reportIf I usesonar.coverage.exclusions=**/*.tsand no specific inclusions, this will lead toboththe.tsand.jsfiles being scanned for errors, which will end up in duplicate errors (after all,.jsfiles are generated by their.tscounterparts.Any suggestions?The whole issue of course would just go away, if sonarqube took litteraly thelcov.infoand did not take initiatives about scanning other files.)
|
SonarQube: Scanning process ignores lcov.info
|
One solution could be to changeDictionarytoImmutableDictionary, then run.ToImmutableDictionary()after initializing the dictionary.public static readonly ImmutableDictionary<string, Func<UpdateContactServiceRequest, object>> UpdateContactMapping =
new Dictionary<string, Func<UpdateContactServiceRequest, object>>
{
{ "firstname", req => req.FirstName },
{ "lastname", req => req.LastName },
{ "full_name", req => req.FullName },
{ "email", req => req.Email },
{ "phone", req => req.Phone },
{ "date_of_birth", req => req.BirthDate },
{ "job_title", req => req.JobTitle },
{ "occupation", req => req.Occupation },
{ "renda", req => req.MonthlyIncome },
{ "lifecyclestage", req => req.LifeCycleStage },
{ "hs_lead_status", req => req.LeadStatus },
{ "ali_email_validated", req => req.EmailValidated },
{ "ali_sms_token_validated", req => req.CellphoneValidated },
{ "id_da_proposta_atual", req => req.CurrentProposalId },
{ "contact_type", req => req.ContactType }
}.ToImmutableDictionary();ShareFolloweditedFeb 6 at 14:13Audwin Oyong2,41633 gold badges1717 silver badges3535 bronze badgesansweredJan 7, 2021 at 21:38kjellrekjellre15611 silver badge44 bronze badges1That solved my problem, thank you very much!–Anderson GonçalvesJan 7, 2021 at 21:46Add a comment|
|
I'm having a problem with a class in an old project and I don't know how to refactor this part, I get the following error message from sonarcube:Use an immutable collection or reduce the accessibility of the field(s) 'CreateContactMapping'.Why is this an issue?This is the piece of codepublic static readonly Dictionary<string, Func<UpdateContactServiceRequest, object>> UpdateContactMapping =
new Dictionary<string, Func<UpdateContactServiceRequest, object>>
{
{ "firstname", req => req.FirstName },
{ "lastname", req => req.LastName },
{ "full_name", req => req.FullName },
{ "email", req => req.Email },
{ "phone", req => req.Phone },
{ "date_of_birth", req => req.BirthDate },
{ "job_title", req => req.JobTitle },
{ "occupation", req => req.Occupation },
{ "renda", req => req.MonthlyIncome },
{ "lifecyclestage", req => req.LifeCycleStage },
{ "hs_lead_status", req => req.LeadStatus },
{ "ali_email_validated", req => req.EmailValidated },
{ "ali_sms_token_validated", req => req.CellphoneValidated },
{ "id_da_proposta_atual", req => req.CurrentProposalId },
{ "contact_type", req => req.ContactType }
};How best to solve this?
|
C# Use an immutable collection or reduce the accessibility of the field(s) 'CreateContactMapping'
|
To fix the links, open the web UI's Settings area, and under the "General" section, set the "Server base URL" value so that links in generate emails, etc, point to the right location. This can also be set in your sonar.properties file as sonar.core.serverBaseURLDon't forget to restart the Sonar service for the changes to take effect.ShareFollowansweredJan 28, 2014 at 1:54John M. WrightJohn M. Wright4,54711 gold badge4444 silver badges6262 bronze badgesAdd a comment|
|
Sonar send notifications by email which contains a link. This link isn't always correct when I changed default configurations, example: when I changed the port from 9000 to 8088, email give always the default port like this localhost:9000...
How can I change this link? Can I make my personal email format?
|
How to config Sonar notification email?
|
Create new profile in maven and add call sonar with new branch for each profile:mvn clean install -Pprofile1 sonar:sonar -Dsonar.branch=BRANCH1<properties>
<sonar.branch>
DEFAULT_BRANCH
</sonar.branch>
</properties>
<profiles>
<profile>
<id>sonar</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<sonar.host.url>
http://localhost:9000
</sonar.host.url>
</properties>
</profile>
<profile>
<id>profile1</id>
<properties>
<!-- Optional URL to server. Default value is http://localhost:9000 -->
<sonar.host.url>
http://myserver:9000
</sonar.host.url>
</properties>
</profile>
</profiles>ShareFolloweditedJan 8, 2021 at 9:14answeredFeb 27, 2012 at 14:07Andrzej JozwikAndrzej Jozwik14.5k33 gold badges6060 silver badges6969 bronze badgesAdd a comment|
|
I would like to create two sets of Sonar reports from the same project. One would have everything covered and the other one would have some packages excluded.Is this possible and if so, how to do such?Edit: Setting exclusions is not a problem but having two reports is.
|
How to generate two sonar reports from the same project?
|
As perdocumentation on Background Tasks:You can control the number of Analysis Reports that can be processed at a time in $SQ_HOME/conf/sonar.properties (see sonar.ce.workerCount - Default is 1).Careful though: blindly increasingsonar.ce.workerCountwithout proper monitoring is just like shooting in the dark. The underlying resources available (CPU/RAM) are fixed (all workers run in theCompute EngineJVM), and you don't want to end-up with very limited memory for each task and/or high CPU-switching. That would kill performance for each of the tasks, rather than having only a few in parallel which will be much more efficient.In short: better to have maximum 2 tasks in parallel that can complete under a minute (i.e. max 10 minutes to run 20 tasks), rather than 20 sluggish tasks in parallel that will overall take 15 minutes to complete because they struggle to share common CPU/RAM.Update: with SonarQube 6.7+ and the newlicence plans, "parallel processing of reports" has become a commercial feature and is only available in theEnterprise Edition.ShareFolloweditedMar 9, 2018 at 8:21dokaspar8,3761414 gold badges7272 silver badges102102 bronze badgesansweredJan 11, 2017 at 11:28Nicolas B.Nicolas B.7,2631818 silver badges2929 bronze badgesAdd a comment|
|
In SonarQube (5.6.4 LTS) there is a view where background (project analysis) tasks are visualized: (Administration / Projects / Background Tasks). It seems like the tasks are run in sequence (one at a time). Some tasks could take 40 minutes which means other projects are queued up waiting for this task to finish before they could be started.Is it possible to configure the SonarQube Compute Engine so that these tasks are run in parallel instead?
|
Possible to parallellize SonarQube background tasks?
|
Go tohttps://www.sonarqube.org/downloads/link and under Website FindHistorical DownloadsView in ScreenshotAll versions listed, Download any version directly..ShareFollowansweredNov 18, 2019 at 13:46ArshitArshit13622 silver badges77 bronze badgesAdd a comment|
|
How can I download an older (specific) version of Sonar?http://www.sonarqube.org/downloads/only gives certain download options.
|
SonarQube download specific version
|
I'm not sure what is the problem. The announcements informs that you have to use Java 11+ to execute scans, but you can still compile your code with Java <11. You didn't provide any information about your project, so let's take a Maven project as an example.It generally means that you have to do something like this:// set Java to 8
export JAVA_HOME=/path/to/jdk8/
// compile, test and build
mvn package
// set Java to 11
export JAVA_HOME=/path/to/jdk11/
// execute scanner
mvn sonar:sonarShareFolloweditedJan 12, 2022 at 17:13answeredFeb 21, 2021 at 19:57agabrysagabrys8,89833 gold badges3535 silver badges7575 bronze badgesAdd a comment|
|
As the following announcement points out, SonarSource ended support to run code Analyzers with pre-11 Java versions:January 2021 - Move analysis to Java 11The version of Java installed in the scanner environment must be upgraded to at least Java 11 before 1 February 2021. Pre-11 versions of Java are already deprecated and scanners using them will stop functioning on that date.Additionally, there will be a brownout from 11 January 2021 to 15 January 2021 during which the first analysis run with a scanner using Java versions less than 11 will fail. To avoid this inconvenience you should upgrade by 11 January 2021.The installation of Java discussed here refers specifically to the JDK or JRE installed and used in the context where your SonarCloud scanner analysis tool is running. This may be your local build environment or your Cl service.This does not have any impact on the Java version targeted by your project code. You can still analyze Java projects that target versions less than 11.I have tried to search for afull exampleabout how to run a bitbucket pipeline to execute SonarScanner analysis using a java 11 Analyzer but having target code using pre-java 11 versions (e.g. java 8), but I wasn't able to found one. According to that image, it should be possible.
|
Run SonarScanner analysis with Java 11, run target code with Java 8
|
You can use theonMethodattributeof the annotation to add any annotation you want to the generated method.@Getter
public class MyClass implements MyInterface{
@Getter(onMethod = @__(@Override))
private Object a;
private Object b
}As a matter of style in this case, I would probably move the class-level@Getterto the other field. If there werec,d,ewhich should all use normal (no annotation) @Getter logic, I would leave it as above.public class MyClass implements MyInterface{
@Getter(onMethod = @__(@Override))
private Object a;
@Getter
private Object b
}You may also want toenable Lombok's generated annotations. It will prevent some tools (coverage, static analysis, etc) from bothering to check Lombok's methods. Not sure if it will help in this case, but I pretty much have it enabled in all of my projects.lombok.addLombokGeneratedAnnotation = trueShareFolloweditedSep 10, 2020 at 15:38answeredSep 10, 2020 at 15:01MichaelMichael43k1111 gold badges8989 silver badges136136 bronze badgesAdd a comment|
|
I'm using lombok in my project and I have an interface :public interface MyInterface{
Object getA()
}And a class@Getter
public class MyClass implements MyInterface{
private Object a;
private Object b
}And i've checked the generated class and the method generated in the class is not@OverrideI'm wondering how to add this annotation ? And what are the consequences of a missing@Override?It's maybe an another question but this code is analyzed by sonarqube and sonar say that private field a is never used.I've already seen the subject aboutsonarqube + lombok = false positivesBut In my case b doesn't create a false positive. So I don't think this is directly relatedDo you see a solution to avoid this problems without reimplement getA() ?
|
How to tell to lombok the generated getter is an @Override
|
You are perfoming an operation in two steps when you could do that by using theFirstlambda expressionstring custName = order.First(s => s.Key == "o123").Value;Linq methodFirstdefinition:First<TSource>(this IEnumerable<TSource>, Func<TSource, Boolean>)First parameter is the IEnumerable you are using (Linq are extension methods)Second parameter allows you to set the filter declaring aFunc<TSource, Boolean>as parameter, that you could define ass => s.Key == "o123"ShareFolloweditedJul 20, 2018 at 10:19answeredJul 20, 2018 at 10:14X.OtanoX.Otano2,09911 gold badge2323 silver badges4141 bronze badgesAdd a comment|
|
I have a windows application which has some similar code as below.As class namedOrder.class Order{
public string Orderid { get; set; }
public string CustName { get; set; }
}Now, in another class in this application, object for Order class is created and value is assigned to it.Order order = new Order();
order = JObject.Parse(some JSON data).ToObject<Order>();Now I want to extract theCustNamebased on Orderid fromorder. For this I have used LINQ.string custName = order.Where(s => s.Key == "o123").First().Value;I'm using Sonarqube to check the code quality. When I run the SonarQube tool , it is showing that I need to refactor my code where I have used LINQ. This is the exact line it shows.Drop 'Where' and move the condition into the 'First'.I have searched for it a lot but couldn't understand what it is trying to say. Can anyone explain me how to refactor this line , so that it passes the SonarQube expectations.Any input is highly helpful.Thanks.
|
Drop 'Where' and move the condition into the 'First' in LINQ
|
Download and install JavaGo toc:/program files/java/jre/binand create a folder called "server"Now go into thec:/program files/java/jre/bin/clientand copy all data of this folder toc:/program files/java/jre/bin/ServerShareFolloweditedApr 4, 2018 at 14:25Antikhippe6,48922 gold badges2929 silver badges4444 bronze badgesansweredApr 4, 2018 at 12:50Lucas FonsecaLucas Fonseca37633 silver badges55 bronze badges1Thanks, great it works for me i can successfully installed and started sonarqube-7.6.–Gautam SharmaJul 31, 2019 at 11:59Add a comment|
|
I resolved this issue, I did it by following the instructions found here:Elasticsearch installation : Error missing 'server' JVM at ...jvm.dllI was using SonarQube fine the day before, but today when I tried to start the program I'm getting a error.I have not changed anything on SonarQube as far as I know, I did made a successful connection with SonarQube to Jenkins. But if I remember correctly, I didn't had to install/change files for SonarQube for this(I just made a project, and generated a user login token for Jenkins). Also, I'm sure I'm using the "vanilla" version of SonarQube.
|
SonarQube startup Error: log4j2 could not find a logging implementation. Please add log4j2 to the filepath
|
Base problem was wrong LDAP port:ldap.url=ldap://ad1.prod:1389should beldap.url=ldap://ad1.prod:389I never bothered to question the 1389 port even though that's not the default LDAP port since I'd copy/pasted from another, working app. I guess I fat-fingered something in the process.Also, this:ldap.user.request=(&(objectClass=inetOrgPerson)(uid={login}))had to be this:ldap.user.request=(sAMAccountName={0})to actually enable searching AD. This is an implementation-specific thing.ShareFollowansweredOct 21, 2016 at 12:11Richard SchaeferRichard Schaefer56533 gold badges1414 silver badges4545 bronze badgesAdd a comment|
|
I'm struggling with configuring theLDAP 2.0 plugin for Sonarqube5.6.3 LTS for Active Directory. I read all the plugin docs and got this for our environment:# LDAP configuration
# General Configuration
sonar.security.realm=LDAP
sonar.security.savePassword=false
sonar.forceAuthentication=true
ldap.url=ldap://ad1.prod:1389
ldap.bindDn=CN=myUser,OU=Service-Accounts,DC=ad1,DC=prod
ldap.bindPassword=myPassword
# User Configuration
ldap.user.baseDn=DC=ad1,DC=prod
ldap.user.request=(&(objectClass=inetOrgPerson)(uid={login}))
ldap.user.realNameAttribute=displayName
ldap.user.emailAttribute=mailand when I start Sonarqube I get:INFO web[org.sonar.INFO] Security realm: LDAP
INFO web[o.s.p.l.LdapSettingsManager] User mapping: LdapUserMapping{baseDn=DC=ad1,DC=prod, request=(&(objectClass=inetOrgPerson)(uid={0})), realNameAttribute=displayName, emailAttribute=mail}
INFO web[o.s.p.l.LdapSettingsManager] Groups will not be synchronized, because property 'ldap.group.baseDn' is empty.
INFO web[o.s.p.l.LdapContextFactory] Test LDAP connection: FAIL
ERROR web[o.a.c.c.C.[.[.[/]] Exception sending context initialized event to listener instance of class org.sonar.server.platform.PlatformServletContextListener
java.lang.IllegalStateException: Unable to open LDAP connection
at org.sonar.plugins.ldap.LdapContextFactory.testConnectionI've tried tweaking the configuration a bit but no luck. Anything stand out to anyone who's more familiar with this?
|
How to configure Active Directory for SonarQube 5.6.3 with LDAP 2.0 plugin?
|
Yes, you are correct. You can use the sonar.exclusions property to exclude source files from analysis and the sonar.test.exclusions property to exclude unit tests. You should pass a comma-delimited list of file path patterns to these properties.I suggest you referto this topicto learn how to specify path patterns. Say, if you need to exclude all the .spec.js files from all the src/app directories, use this pattern:**/src/app/*.spec.jsShareFolloweditedNov 13, 2017 at 23:08jlb19.6k88 gold badges3737 silver badges6565 bronze badgesansweredMar 22, 2017 at 10:50PasickPasick38422 silver badges77 bronze badges1Thanks, it is working ok, but I have put: sonar.test.exclusions=**/*.spec.js, I wil check the documentation to understand it–EladerezadorMar 22, 2017 at 11:13Add a comment|
|
I am using Sonar in a Angular Application for the front part.I have many js files in my application, but i need that the Sonar ignore or exclusion my js files that ending in .spec.js, are tests unit of Angular.I have many folders under "src/app" and inside i have many folders with the .spec.js files .In the properties file to Sonar (sonar-project.properties), I think I can use:sonar.test.exclusions=src/app/*.spec.jsorsonar.exclusions=src/app/*.spec.jsBut I'm not sure, in what format is the value of property.Thanks,
|
Sonarqube - Exclude a set of specific files
|
The ResultSet is not "linked" to a connection or any other resource that needs closing. It's backed by an array. See:https://github.com/datastax/java-driver/blob/2.1/driver-core/src/main/java/com/datastax/driver/core/ArrayBackedResultSet.javacredits:https://groups.google.com/a/lists.datastax.com/forum/#!topic/java-driver-user/yjDP1xeYyYMStatement contains only statement ID, so you don't need to close it too.ShareFolloweditedSep 28, 2015 at 10:19answeredSep 28, 2015 at 10:09VovkaVovka59933 silver badges1010 bronze badges3Thank you vovka, I must have missed this answer, don't know why. Anyway, now I have my result. (I may add for those having doubt that the original answer is from a datastax product manager, see link)–FundhorSep 28, 2015 at 11:31Does this mean the entire resultset is pulled into memory?–Dylan WilderMay 12, 2016 at 14:153Edit: scratch that. it appears to do paging. My question is: If I execute a query and then never do anything with the resultset, when is the resultset "expired" (either by the cassandra server or the client).–Dylan WilderMay 12, 2016 at 15:05Add a comment|
|
Hello World !I'm in trouble trying to close some datastax resources (Statement, ResultSet).
Sonar is yelling at me to close those resources after i use them.(for information after i use this myMethod() i call aSystem.exit(0)) Bu anyway, I would like to do it according to Sonarsession.close()is not enough since it appears to let Statement and ResultSet./!\ ResultSet and Statement are from com.datastax.com.driver and these close() method doesn't exist on them. (different from java.sql)I think a session.getCluster.close() would do, but I don't want to close the Cluster.What would be the right way to close those resources properly ?import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.Statement;
public void myMethod() {
Statement statement = session.prepare("select * from .....").bind();
ResultSet rs = session.execute(statement);
// doSomethingWithThisResultSet() ...
session.close();
}Thanks in advance for your help !
|
Close ResultSet and Statement resources (datastax, no close() method)
|
You can createStringBuilderoutside theforloop and reuse it.StringBuilder sb=new StringBuilder();
for (final FieldError fieldError : result.getFieldErrors()) {
sb.append(fieldError.getField())
.append(" - ")
.append(getErrorMessageFromProperties(fieldError.getCode()))
.append("*");
}After appending all tosbyou can callString error=sb.toString()just after theforloopShareFollowansweredSep 26, 2014 at 8:07Ruchira Gayan RanaweeraRuchira Gayan Ranaweera35.3k1717 gold badges7676 silver badges117117 bronze badgesAdd a comment|
|
I'm encountering this issue on this line of code even I use .append() inside the loop.for (final FieldError fieldError : result.getFieldErrors()) {
errors = new StringBuilder(errors).append(fieldError.getField()).append(" - ")
.append(getErrorMessageFromProperties(fieldError.getCode())).append("*").toString();
}how can I fix this?
|
Performance - Method concatenates strings using + in a loop
|
Sonar is giving you suggestion that your "member" which is:public final Map<String, String> myMap = new HashMap<>();shouldnotbe public.Why?Leaving this aspublicmakes it availablefrom any other package- so you are exposing the member to everybody. Below code is accessing thememberdirectly:AllMap allMap = new AllMap();
allMap.myMap.put("X", "Y");In most casesmembersshould beprivateand accessed bygettersandsetters, which could prevent with returning the same reference - so you can implement some logic before yougetthe reference orsetit.If you need to make itstatic, makestaticgetters and setters.ShareFollowansweredSep 26, 2017 at 8:46DevDioDevDio1,53511 gold badge1919 silver badges2727 bronze badgesAdd a comment|
|
In the below class I am declaring myMappublic class AllMap {
public static final Map<String, String> myMap= new HashMap<>();
static {
Map.put("yy", "AA");
Map.put("xx", "BB");
}
}I need to access map in other class.public class Test {
FieldMap.Map;
}Everything is working fine,but sonar is giving warning on 1st class:Make this member "protected".on the linepublic static final Map<String, String> myMap = new HashMap<>();Should I ignore this warning or should I change it to protected?
|
Sonar Error - Make this member "protected"
|
Here I followed the following blog to enable SSL with reverse proxy using IIS rewrite.https://jessehouwing.net/sonarqube-configure-ssl-on-windows/Thanks all for the answersShareFolloweditedJul 8, 2018 at 16:27jessehouwing110k2222 gold badges264264 silver badges358358 bronze badgesansweredJun 16, 2016 at 11:27chandrachandra11111 gold badge11 silver badge88 bronze badges3the most important part is Make sure to turn off the checkbox “Reverse rewrite host in response headers” within the ARR (Application Request Routing) configuration of IIS. (Application Request Routing Cache --> Server Proxy Settings), if you are using rewrite sonarqube server in localhost:9000–Gautam SharmaSep 4, 2019 at 13:57does this mean the sonar will be accessible over https rather than http over internet after applying all the steps ?–Aatif AkhterNov 17, 2021 at 9:33if you want to make your sonarqube accessible over internet, you need a public ip which will point to your machine and to have ssl for the sonarqube website, you need to follow the above process.–chandraNov 18, 2021 at 4:14Add a comment|
|
I installed Sonarqube on a server and given a domain name likehttp://sonarqube.xyz.com:9000and now I would like to have the URL to be https.I have changed the properties of sonar.properties in the conf file and tried redirecting the URL using IIS with URL rewrite.
|
How to enable SSL in sonarqube
|
The SQALE Rating is a direct correlation with the Technical Debt Ratio of your project. The Technical Debt Ratio is the following:The technical debt of your project (= sum of the debt of all issues)Divided by the estimation of the cost to rewrite your application from scratchThe idea is to tell you that if this ratio "Debt vs. cost to rewrite" grows too high, maybe it's a good time to rewrite the application instead of spending time reimbursing your debt.By default, SonarQube is configured to give a A rating when the ratio is below 5%. But this is just a default configuration that you can override in the global administration page under "Configuration > General Settings > Technical Debt".ShareFolloweditedJul 5, 2016 at 12:33answeredFeb 3, 2016 at 11:53Fabrice - SonarSource TeamFabrice - SonarSource Team26.6k33 gold badges6363 silver badges5858 bronze badges2Are there any example Open Source projects that have their SQALE score displayed (in AppVeyor or the like...)–Steve DunnJul 2, 2018 at 16:33A bunch of projects publishes analyses onsonarcloud.io. Some random examples:MySQL,ReactOS,KeepassXC. Note that not all of the projects on SonarCloud are analysed automatically by CI systems, and it's not always the maintainer(s) who set up the analysis. Still, it may be useful to get an idea about how SonarQube and its SQUALE ratings work.–Jens BannmannJul 9, 2018 at 20:40Add a comment|
|
I'm using sonar to analyze a set of related projects.
And I'm using SQALE Rating to justify the need for a refactoringMy question is what is the logic behind SQALE to Technical Debt ratio mapping?Why SQALE A rating is Tech Debt in range from 0% to 5%. But not 0% to 3% for instance?
How should I define a SQALE rating limits?
Why 5% Tech debt is good?
Is there any methodology I can use?
Or i have to come up with this standards by my own?
And is there a way in SonarQube to change them?
|
SQALE SonarQube Rating
|
You have to provide the 3rd party libraries you use (ie your classpath) viasonar.java.librariesproperty for the analyzer to be able to detect that you are using Lombok and make the correct exclusions.ShareFollowansweredMay 6, 2015 at 12:20benzonicobenzonico10.7k55 gold badges4444 silver badges5151 bronze badges31@benzonico I am using gradle to build the project, so what should I put for the sonar.java.librares property?–DavidMay 29, 2015 at 8:44you would have to provide your classpath, ie path to the libraries you are using.–benzonicoMay 29, 2015 at 8:45sonar.java.libraries=/jenkins/jenkins-user-home/.m2/repository/org/projectlombok/lombok/1.16.20/lombok-1.16.20.jar–Barış ÖzdemirMay 29, 2018 at 11:03Add a comment|
|
I am using SonarQube 4.5.4 with Java plugin 3.1. As I know this sonar-java version supportsLombok partially (Getter and Setter annotations) starting from 2.8.But in my case it still reports field withlombok.Getteras:squid:S1068 Unused private fields should be removed:
@Getter
private String userName;Do you have any ideas why this could happen and where can I fix it?updateFor bytecode I tried bothsonar.java.binariesandsonar.binariesI use sbt and run analysis with sonar-runner for belowsonar-project.propertiessonar.projectVersion=0.1
sonar.java.binaries=\
target/scala-2.11/classes,\
target/scala-2.11/test-classes
sonar.sourceEncoding=UTF-8
sonar.projectName=projectName
sonar.host.url=http://hostname:9000
sonar.login=login
sonar.password=password
sonar.projectKey=projectKey:webJava
sonar.modules=app
app.sonar.projectBaseDir=web
app.sonar.sources=app
app.sonar.tests=test
sonar.analysis.mode=preview
sonar.issuesReport.lightModeOnly=false
|
SonarQube Lombok Getter recognition
|
Steps to make a backup/reimportGo toConfiguration --> Quality ProfilesClick theBackup-Button of the desired profile and save the fileGo to the target sonar instanceGo toConfiguration --> Quality ProfilesClickRestore Profile(it is in the upper right corner and a bit hard to miss.)Select the previously saved fileDoneRelated Sonar documentation can be foundhere.ShareFolloweditedJun 26, 2016 at 13:08jotik17.4k1515 gold badges6161 silver badges126126 bronze badgesansweredFeb 1, 2012 at 8:10oersoers18.6k1313 gold badges6767 silver badges7676 bronze badges0Add a comment|
|
i am having a file rules.csv in ms-excel format. The rules.csv is downloaded from quality profiles of other sonar server.Now i want to implement my sonar with same quality profiles.now my questions arehow to import csv file to sonarrules.csv file is enough to create the same quality profiles of other
|
importing rules.csv file to sonar
|
They just released what you need :https://wiki.jenkins-ci.org/display/JENKINS/JaCoCo+PluginShareFollowansweredAug 23, 2012 at 7:32Pulak AgrawalPulak Agrawal2,48144 gold badges2626 silver badges4949 bronze badges2Could you describe a bit more the problem that you solved? As I understood you told aboutissues.jenkins-ci.org/browse/JENKINS-14927but there was not descriptions there. How can we use code coverage with jenkins & sonar & ant ?–SoidAug 27, 2012 at 22:14@GregoryLo sorry did not understand ? Did you mean to post this here as I have not contributing anything for this issue–Pulak AgrawalSep 4, 2012 at 5:01Add a comment|
|
I followed the instructionshereI am NOT using Maven.My Jenkins job output says:
12:32:33.951 INFO Sensor JaCoCoSensor...
12:32:33.961 INFO Project coverage is set to 0% as no JaCoCo execution data has been dumped: /var/lib/jenkins/workspace/SeqGen/SeqGen/jacoco.exec
12:32:35.152 INFO Sensor JaCoCoSensor done: 1201 msHere are my properties:project.home=SeqGen
sonar.projectKey=com.skyboximaging:seqgen
sonar.projectName="SeqGen"
sonar.projectVersion=1.0
sonar.dynamicAnalysis=true
sources=src/java
tests=test/java
binaries=classes
sonar.jacoco.reportPath=jacoco.exec
sonar.jacoco.antTargets=test-with-coverageOn the Sonar server, I set General Settings > Code Coverage > Code coverage plugin to jacocoI am very confused by the documentation athttp://docs.codehaus.org/display/SONAR/Code+coverage+pluginsI am particularly puzzled by this sentence:
"During Sonar analysis, the Sonar Jacoco plugin will take care to attach the Jacoco agent to the JVM and to launch the unit tests."As far as I can tell, my Ant target is not getting invoked. How does the Sonar Jacoco plugin know where to find my build.xml?What am I doing wrong?
|
How to get JaCoCo coverage with Sonar in Jenkins?
|
You can get it in checkstyle xml format by navigating toConfigurationQuality Profiles -> select your Profileactivate "Permalinks" tabThis should give you access to the checkstyle config as xml.In Eclipse you can even configure the checkstyle plugin to use the URL and fetch always the latest rules over the web.ShareFolloweditedMay 13, 2011 at 12:02sth225k5555 gold badges285285 silver badges367367 bronze badgesansweredMay 12, 2011 at 21:01p1brunnep1brunne44433 silver badges33 bronze badges0Add a comment|
|
I want to export checkstyle rules from sonar and import them into the checkstyle eclipse plugin. Unfortunately sonar exports the checkstyle rules to a csv file.But the checkstyle plugin only accepts import of xml files.Is there any way to do that?
|
Import checkstyle-configuration from sonar into eclipse-checkstyle-plugin
|
MethodStream.toList()has been already mentioned in therules of Java analyzer. And the latest SonarQube'sVersion 9.5according to its description should support Java 16.So firstly, try to update the SonarQube.If it would not resolve the issue, you can substitutetoList()withcollect(Collectors.toList()).ShareFollowansweredJun 15, 2022 at 19:14Alexander IvanchenkoAlexander Ivanchenko27.3k66 gold badges2525 silver badges4949 bronze badgesAdd a comment|
|
im working in java 17 project and i have the following method :public List<String> getUserroles(List<UserRoleDTO> userRoles) {
return userRoles.stream().filter(UserRoleDTO::getRight).map(UserRoleDTO::getActionId)
.toList();
}and my build is failled because sonarqube prompt Major issue "Refactor code so that stream pipeline is used".any suggestion please on how i can adapt my code to be sonar compliant.Best regards
|
Sonarqube Major issue "Refactor code so that stream pipeline is used"
|
Try one of these:sonar.exclusions=**/static/**Or
Full path beforestatice.g. :sonar.exclusions=/put/your/full/path/static/**ShareFollowansweredDec 27, 2019 at 14:43ameramer1,59511 gold badge1414 silver badges2323 bronze badges2Does it matter where sonar-project.properties file is placed? I mean I have tried to place it almost everywhere.–PavelDec 27, 2019 at 14:541Where is it placed ? Place it in the root folder wheresettings.gradleorREADMEfor example are.–amerDec 27, 2019 at 14:58Add a comment|
|
I am running Spring Boot project which I want to analyze with SonarQube.in a~/static/~folder I have libs (boostrap and JS) that I want to exclude from analyze.I have tried both ways:Setting upproject-sonar.propertiesfile withsonar.exclusions=**/static/**/*Going from Sonar project local web to Coverage Exlusions also settingsonar.exclusions=**/static/**/*But none of the ways seem to be working for me.I would appreciate any help! :)
|
How to exclude directory from SonarQube analysis?
|
Insonar-project.properties, Try adding something like:sonar.exclusions= **/*.spec.ts, **/*.ts, src/test/*ShareFollowansweredJun 4, 2019 at 12:00Shashank VivekShashank Vivek17.2k88 gold badges6565 silver badges107107 bronze badges3can't we do this in project level.–aryaaJun 4, 2019 at 12:02@Rajesh Yes, you can. create thispropertiesfile at project level. It takes relative path.–Shashank VivekJun 5, 2019 at 5:15try with sonar.coverage.exclusions=**/myfolder/** because the propertie sonar.exclusions not allow to sonar find bugs and other issues in your code in these files that are excluded, however sonar.coverage.exclusions= only exclude files for test-coverage–duvanjamidApr 26, 2022 at 18:02Add a comment|
|
How do I exclude ts.files in SonarQube Analysis for better Code Coverage.I tried with with below code"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.spec.json",
"karmaConfig": "src/karma.conf.js",
"codeCoverageExclude": [
"src/app/user/about-report/about-report.component.ts"
],
}
}But no luck its is getting analized in sonar. Can you help me out. I am using Angular 7.
|
Exclude files in Sonar Code Coverage Analysis Test - Angular 7
|
Looks like the documentation still refers to old versions of Jenkins. In latest versions theSonarQube Scannersection hides underManage Jenkins-Global Tool Configuration.ShareFollowansweredAug 5, 2016 at 7:00Nicolas B.Nicolas B.7,2631818 silver badges2929 bronze badges1You sir, are a life saver !–Saif AsifJan 3, 2017 at 10:08Add a comment|
|
I can't find the SonarQube Scanner configuration inside Jenkins Administration.
After installing the SonarQube Plugin, I've got the "SonarQube servers" section but not the "SonarQube Scanner" section as described in the documentation :http://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner+for+JenkinsDid I miss something ?Versions :Jenkins 2.7.1SonarQube Plugin 2.4.4SonarQube Server 5.6I tried on latest Jenkins 2 Version (2.7.2), same result.
It works on latest Jenkins 1 Version (1.651.3)
|
No Sonarqube scanner configuration in Jenkins 2.7.1
|
That's because the artifact with Maven coordinatesorg.codehaus.mojo:sonar-maven-plugin:3.0.1is apomfile in Maven Central and not ajar, so it cannot be resolved properly.The latest official version of the plugin using these coordinates is2.7.1Thesonar-maven-pluginhas changed then coordinates, moving to a newgroupId:org.sonarsource.scanner.maven, which indeed provides the3.0.1version.You should hence change the existing coordinates used by yourpom.xmlfile to:<groupId>org.sonarsource.scanner.maven</groupId>
<artifactId>sonar-maven-plugin</artifactId>
<version>3.0.1</version>That's also documented on the officialSonarqube Maven documentation.ShareFolloweditedJun 15, 2016 at 21:45answeredJun 15, 2016 at 21:15A_Di-MatteoA_Di-Matteo27.3k77 gold badges100100 silver badges131131 bronze badges2@fsantos did this answer help you out?–A_Di-MatteoJun 20, 2016 at 12:47Absolutelly @A_Di-Matteo. Thanks a lot!–fsantosJun 30, 2016 at 4:39Add a comment|
|
I'm using Intellij IDEA 2016.1 working in an imported Maven project.
Intellij complains only about sonar-maven-plugin.I have already tried to reimport in maven option but Intellij stills mad with this plugin.The error message in Intellij is:
Unresolved plugin org.codehaus.mojo:sonar-maven-plugin:3.0.1Apache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-10T09:41:47-07:00)
Maven home: /usr/local/apache-maven-3.3.9
Java version: 1.8.0_92, vendor: Oracle Corporation
Java home: /Library/Java/JavaVirtualMachines/jdk1.8.0_92.jdk/Contents/Home/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "mac os x", version: "10.11.5", arch: "x86_64", family: "mac"
|
Unresolved org.codehaus.mojo:sonar-maven-plugin:3.0.1 Intellij - Maven Project
|
The SonarQubeRunner 5.3 does not exist.You incorrectly configuredSONAR_RUNNER_PATH. You set path to the SonarQube server instead of the runner. The latest version is 2.5.1 (seereleases).Better choose optionInstall automatically(at work I use SonarQube Runner 2.4 with SonarQube Server 5.3 without any problems).ShareFolloweditedJan 24, 2016 at 18:13answeredJan 24, 2016 at 18:07agabrysagabrys8,89833 gold badges3535 silver badges7575 bronze badges0Add a comment|
|
I am trying to integrate jenkins and sonarqube.Sonarqube version is 5.3.I have a java gradle project to monitor. I have installed both jenkins and sonar on my local linux system. Both run individually fine.I have setupBelow is my entire configuration.
|
Why I am getting SonarQube runner executable was not found for SonarQubeRunner 5.3?
|
You can do that easily on issue page of your project : just click on the rule facet and you should have the list of most violated rules.Seehttp://nemo.sonarqube.org/issues/search#resolved=false|projectUuids=b38e4f29-df5f-491e-9118-a0a4f5cda406for instance and click on "Rule" facet.ShareFollowansweredAug 21, 2015 at 7:47benzonicobenzonico10.7k55 gold badges4444 silver badges5151 bronze badges5Thanks, exactly what I needed.–Paul HenryAug 23, 2015 at 20:522Is there a way to seeallthe issues grouped by rule?–Rodrigo SasakiOct 29, 2015 at 19:12Go to the issue page and use the rule facet–benzonicoOct 29, 2015 at 21:265I'm finding that the UI only displays the first 15 rules that were violated. Is there a way to get it to display all of them?–aatuc210Mar 1, 2016 at 16:16Broken link on 4th link of answer–DaleJul 1, 2021 at 18:05Add a comment|
|
How can we identify the most common types of issues in a project in our current code base.We have recently upgraded from Sonar 4.5 to 5.1In 4.5 we used to view the issues list in a specific project, and the issues were grouped by issue type. For instance in one project the rule "Use a logger to log this exception" might be the most common critical rule with 45 violations. We could then use that information to drive improvement efforts.In 5.1 we are now presented with a long list of issues with no apparent way of group them.The ability to see what type of violation was most common was also useful in allowing us to see where best to direct our efforts in terms of remedial action.
|
Sonar 5.1 Issues list - How to group by Issue Type
|
@Techtwaddle is correct: the MSBuild.Runner invokes the sonar-runner.The MSBuild.Runner v0.9 does the following:fetches configuration settings from the SonarQube server;gathers information during the MSBuild phase;generates a sonar-project.properties file;invokes the sonar-runner to carry out further analysis.Some of the analysis is now performed before calling the sonar-runner. For example, FxCop analysis is now happens as part of the MSBuild phase rather than being invoked from the sonar-runner.Currently, you have to manually install both the sonar-runner and the MSBuild.Runner. Work is planned to change this so you will only need to install the MSBuild.Runner. Seehttp://jira.sonarsource.com/browse/SONARMSBRU-42.ShareFollowansweredJun 18, 2015 at 10:05duncanpduncanp1,57211 gold badge1010 silver badges88 bronze badges2And indeed, with that change, the fact that the MSBuild Runner internally relies on the sonar-runner will become an implementation detail. I even can imagine that at some point in the future, the MSBuild Runner won't rely on the sonar-runner anymore.–Dinesh BolkensteynJun 18, 2015 at 12:57Thanks for the confirmation. I blog about TFS and wanted to make sure I had the facts straight. Blog post in case it helps anyone:pleasereleaseme.net/…–Graham SmithJun 18, 2015 at 22:53Add a comment|
|
Regarding theannouncementof SonarQube integration with MSBuild and Team Build, can anyone advise on the relationship between SonarQube Runner and SonarQube.MSBuild.Runner? I'm unclear whether SonarQube.MSBuild.RunnerreplacesSonarQube Runner or whether it sits on top of it.
|
Relationship between SonarQube Runner and SonarQube.MSBuild.Runner
|
This is possible but the trick is that you have to use system properties (usingsystemPropprefix):systemProp.sonar.host.url=http://localhost:9000
systemProp.sonar.jdbc.url=jdbc:postgresql://localhost/sonar
systemProp.sonar.jdbc.username=sonar
systemProp.sonar.jdbc.password=sonar
systemProp.sonar.login=admin
systemProp.sonar.password=adminSee:https://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner+for+Gradle#AnalyzingwithSonarQubeScannerforGradle-GlobalconfigurationsettingsThis should work with the old 'sonar-runner' plugin but feel free to give a try to new 'org.sonarqube' plugin:https://plugins.gradle.org/plugin/org.sonarqubeShareFolloweditedMar 22, 2017 at 10:37G. Ann - SonarSource Team22.5k44 gold badges4242 silver badges8484 bronze badgesansweredJun 15, 2015 at 7:45Julien H. - SonarSource TeamJulien H. - SonarSource Team5,25711 gold badge2020 silver badges2525 bronze badges0Add a comment|
|
I want to Externalize the sonar configuration properties from build.gradle file to gradle.properties file.for example,
apply plugin: 'sonar-runner'sonarRunnersonarPropertiesproperty "sonar.java.coveragePlugin", "jacoco"
property "sonar.host.url", "http://10.42.58.229:9000/"
property "sonar.jdbc.url", "jdbc:mysql://10.42.58.229:3306/sonar"
property "sonar.jdbc.driverClassName", "com.mysql.jdbc.Driver"I want to pass the property values from gradle.properties file, which is present in user home.
|
Externalize the sonar configuration properties to gradle.properties file in user home
|
SonarQube does not support Java try-with-resources constructs.It also reports a bogus null-check issue on use.Since SonarQube is using other tools (PMD/FindBugs, etc) and they use byte-code analysis, they (admittedly) say that sometimes these are false-positives.
The answer the "SonarQube Way" is to NOT use try-with-resources until they have proper handling of the resulting byte-code.However, no sane developer would recommend having the tail wag the dog.
My suggestion is to mark as false-positve via SonarQube plug-ins but it will not help about test-coverage because its analysis of the byte-code in this case is just wrong.SonarQube itself has thousands of issues (they eat their own dog food).ShareFolloweditedJun 12, 2015 at 14:15dcsohl7,29611 gold badge2727 silver badges4545 bronze badgesansweredJul 31, 2014 at 12:02Darrell TeagueDarrell Teague4,16211 gold badge2727 silver badges3838 bronze badges1There is apparently a fix for this in SonarCube updates, at least to stop reporting the "null check" false-positive. It does not speak to whether it fixes the resulting test-coverage due to the way the byte-code gets put together to handle exceptions but these links may be useful:stackoverflow.com/questions/17354150/…andsonarqube.org/sonar-2-12-in-screenshots–Darrell TeagueJul 31, 2014 at 14:43Add a comment|
|
Using the latest version (4.3.2) of SonarQube, a try-with-resources block gives a false positive to branch coverage of thecatchline. For example:public List<String> getLines(String filename) {
try (InputStream inputStream = getInputStream(filename)){
return IOUtils.readLines(inputStream);
} catch (IOException e) { // <<<<<<< REPORTS AS BRANCH COVERAGE 2/8
throw new IllegalArgumentException(e);
}
}But my unit tests cover exceptions thrown at every point, and all other lines have 100% coverage - the actual coverage is 100%. And where's the "8" coming from? There's aren't 8 places that an exception can the thrown.I tried adding// NOSONARto the problem line, and even tried adding it to every line, but the report is the same.Other types of problemwereignored when using// NOSONAR, so it's not a sonar configuration problem.I suspect it's because sonar doesn't allow for the extra try-catch blocks in the bytecode that a try-with-resources block produces.Is there a way to decorate the code that successfully causes sonar to ignore this particular false positive?
|
Sonar reports false positive for insufficient branch coverage in try-with-resources block
|
+50Try to usesonarqube.server.com:9000/api/metrics/domains, I am able to get json response from this.APIs that you can use are listed at:sonarqube.server.com:9000/web_api/api/metrics/domains/searchbut just remove "web_api" while calling, to get json response.ShareFolloweditedMay 1, 2018 at 8:43Jesse3,56266 gold badges2525 silver badges4040 bronze badgesansweredMay 1, 2018 at 8:18Amit BooraAmit Boora14422 bronze badges0Add a comment|
|
I am using SonarQube version 6.7.1I am trying to get JSON Response for our projects sonarQube statistics
Just want simple details likeBug count, vulnerability count , % code duplication , code coverageTried URLhttp://sonar-server:9000/api/metrics&json=truebut got error Unknown url, can someone point out correct URLEnd Aim is to store Above counts for each run in time series DB .. any suggestions how to do it ?May be i am not reading / understanding documentation clearly , possibly a pointer to tutorial or example or some other pointers will help me,
|
SonarQube REST APIs : Read Metrics
|
In Maven projects,pom.xmlis the main configuration file. If we add below lines in that, the ruleS1191will not be applied. And this is in tight coupling with the project, which is what was required. So, no need to configure any SonarQube instance, rather specify below lines inpom.xmlunderpropertiestag. That will work.<sonar.issue.ignore.multicriteria>e1</sonar.issue.ignore.multicriteria>
<sonar.issue.ignore.multicriteria.e1.ruleKey>squid:S1191</sonar.issue.ignore.multicriteria.e1.ruleKey>
<sonar.issue.ignore.multicriteria.e1.resourceKey>**/*.java</sonar.issue.ignore.multicriteria.e1.resourceKey>ShareFolloweditedJan 10, 2018 at 20:03Matias Kinnunen8,14833 gold badges3636 silver badges4848 bronze badgesansweredSep 19, 2017 at 6:41Aakash GoyalAakash Goyal1,06044 gold badges1212 silver badges4444 bronze badges12How would that go for a build.gradle?–user1414745Sep 27, 2018 at 8:13Add a comment|
|
I have a Java project and it will be submitted in Gitlab. In the code present in Gitlab, SonarQube will be used for its analysis. Currently the project is showing Code Smells with detailClasses from "sun.*" packages should not be used.How do I include the exclusion of this rule when my Maven Project is analysed by SonarQube?What I go to know is that we have to put this insonar-project.properties. But I am not able to find what tag should be used for that.
|
sonar project properties Exclude rule squid:S1191
|
Ability to configure Quality profiles and Quality gates is not implemented yet on sonarqube.com.SonarSource teams are heavily working on that feature. However no release date can be estimated at the time of writing.ShareFollowansweredNov 12, 2016 at 17:42Simon BrandhofSimon Brandhof5,13611 gold badge2222 silver badges2828 bronze badges12Quality profiles and Quality gates can now be configured on sonarcloud.io (ex-"sonarqube.com").–Simon BrandhofMar 30, 2018 at 19:29Add a comment|
|
I am using the onlineSonarQube.comfree OS services for my Java Android project.I encountered several bugs where I checked the equality of strings with == instead of .equals().I found out that sonarqube has what seems to be a good rule to find these bugs:Objects should be compared with "equals()". Unfortunately this rule is disabled in the defaultJava Sonarway quality profile.My question is, since I do not have admin privileges on the publicSonarQube.comserver, is there a way to activate this rule for my project?
|
Change quality profile on SonarQube.com
|
Sonar is suggesting to check the result ofcompareToagainst0, not if it returns directly1,-1.if (recBalanceAmt.compareTo(recRolloverEligibility) > 0) {You can find the reason for this suggestion in thecompareTo() JavadocReturns: a negative integer, zero, or a positive integer as this
object is less than, equal to, or greater than the specified object.ShareFollowansweredMay 20, 2016 at 7:09guidoguido19k66 gold badges7171 silver badges9696 bronze badges3Why? compare with 1 is not OK? or is there any issue with comparing with 1?–Shiladittya ChakrabortyMay 20, 2016 at 7:166by contract, a compareTo method can return any positive value, not necessarily 1, so if the method returns 2 and you compare the result to 1 your condition won't be satisified.–benzonicoMay 20, 2016 at 7:27I can see everytime it is returning +1 for greater and -1 for smaller. Can there be any scenraio I can create where it will return -2 instead of -1?–Sourabh RoyApr 14, 2022 at 12:38Add a comment|
|
I am compare two values and getting sonar lint throwing"Only the sign of the result should be examined" this issue.Code :if (recBalanceAmt.compareTo(recRolloverEligibility) == 1) {
recExpAmt = recBalanceAmt.subtract(recRolloverEligibility);
}How to resolve this issue?
|
Sonar lint : "compareTo" results should not be checked for specific values
|
I had same issue before, but for me the lack of virtual memory of my linux instance was the issue.Increasing the memory Maven options didn't help muchShareFollowansweredJan 11, 2016 at 6:37JeelJeel2,39755 gold badges2323 silver badges3939 bronze badges11Correct. We have increased the physical memory from 16GB to 24GB. The problem has disappeared.–Laurent TOURREAUJan 13, 2016 at 13:39Add a comment|
|
I have a project with hundreds java modules.
I run SonarQube 5.1 with following plugins:Java 3.3Findbugs 3.2Checkstyle 2.3PMD 2.4.1Issue Assign 1.6SQALE 2.6SVN 1.1LDAP 1.4JIRA 1.2Cobertura 1.6.3I use jenkins 1.639 with SonarQube plugin 2.3.I set a job with the following settings:Goals :$SONAR_MAVEN_GOAL -Dsonar.host.url=$SONAR_HOST_URL -Dsonar.jdbc.url=$SONAR_JDBC_URL -Dsonar.jdbc.username=$SONAR_JDBC_USERNAME -Dsonar.jdbc.password=$SONAR_JDBC_PASSWORD -Dsonar.log.level=DEBUGMAVEN_OPTS:-XX:MaxPermSize=512m -Xmx8192m`When I perform an analysis with Jenkins I get the following error:<code>[INFO] [08:57:22.023] Store results in database
[DEBUG] [08:57:22.029] Execute org.******.batch.phases.GraphPersister
[DEBUG] [08:57:22.126] Execute org.******.batch.index.SourcePersister
[DEBUG] [08:57:28.263] Updating semaphore batch-com.mycompany.myapp:myapp
[DEBUG] [08:57:38.265] Updating semaphore batch-com.mycompany.myapp:myapp
[DEBUG] [08:57:48.267] Updating semaphore batch-com.mycompany.myapp:myapp
[DEBUG] [08:57:51.788] Execute org.******.batch.index.ResourcePersister
[DEBUG] [08:57:51.788] Execute org.******.batch.index.MeasurePersister
[DEBUG] [08:57:58.269] Updating semaphore batch-com.mycompany.myapp:myapp
[DEBUG] [08:58:08.271] Updating semaphore batch-com.mycompany.myapp:myapp
ERROR: Maven JVM terminated unexpectedly with exit code 137</code>Can you help?
|
Exit code 137 when running SonarQube analysis on Jenkins
|
You're right: There are build step/tasks for the MSBuild SonarQube Runner available out-of-the-box for Team Foundation Server 2015 (and soon Jenkins) - but not for TeamCity. You indeed need to use the command line step/task to manually invoke the MSBuild SonarQube Runner begin and end phase, and MSBuild in between.From there, the actual configuration and usage is identical to the command line scenario, which is why the TeamCity doesn't have its own documentation.ShareFollowansweredOct 20, 2015 at 8:07Dinesh BolkensteynDinesh Bolkensteyn3,01111 gold badge1919 silver badges2020 bronze badges0Add a comment|
|
We use TeamCity as our build server - how does one setup TeamCity to run SonarQube analysis for C# / .NET solutions?I'm thinking we'll need to execute the MSBuild runner as a command line task since the TeamCity SonarQube runner doesn't call the MSBuild SonarQube runner.(It would be great ifhttp://docs.sonarqube.org/display/PLUG/C%23+Plugindescribed this scenario.)EDITThe URL in the original post has changed. Correct link ishere.
|
Using SonarQube with TeamCity and C# / .NET
|
At some point in your program, you will have to implement the logic:If the new facility has a property defined, update the old facility accordinglyIf not, do not override the previous value from the old facility.Without having a global look at your project, what you can do is to move that logic inside the setters of each property:public class Facility {
public void setSomething(String something) {
if (something != null) {
this.something = something;
}
}
}This way, yourupdatemethod would simply be:private Facility updateFacility(Facility newFacility, Facility oldFacility) {
oldFacility.setSomething(newFacility.getSomething());
// etc for the rest
}ShareFollowansweredOct 1, 2015 at 10:14TunakiTunaki135k4646 gold badges355355 silver badges431431 bronze badges21Object would still be having null if we didnt use the setter method right .–NayeemNov 10, 2015 at 12:20@Nayeem What do you mean? Instead of doingsomething != nullyou could write a more complex expression likesomething != null && !something.isEmpty(). But the idea is the same.–TunakiNov 10, 2015 at 12:30Add a comment|
|
I have the following code:private Facility updateFacility(Facility newFacility, Facility oldFacility) {
if (newFacility.getCity() != null)
oldFacility.setCity(newFacility.getCity());
if (newFacility.getContactEmail() != null)
oldFacility.setContactEmail(newFacility.getContactEmail());
if (newFacility.getContactFax() != null)
oldFacility.setContactFax(newFacility.getContactFax());
if (newFacility.getContactName() != null)
oldFacility.setContactName(newFacility.getContactName());
// ......
}There are around 14 such checks and assignments. That is, except for a few, I need to modify all the fields of the oldFacility object. I'm getting a cyclomatic complexity of this code 14, which is "greater than 10 authorized" as per SonarQube. Any ideas upon how to reduce the cyclomatic complexity?
|
Reducing the cyclomatic complexity, multiple if statements
|
Not all applications use JAVA_HOME variable, so you can have JAVA_HOME pointing on your 64 bits version while you are using a 32 bits.
Note: the 'Java_Home' key in the registry is not the JAVA_HOME variable.Well, one way to be sure is to uninstall the current service, with ..\windows-x86-64\UninstallNTService.bat and install the 32 bits version with ..\windows-x86-32\InstallNTService.bat.If it works, you definitively have a 32 bits JVM.ShareFollowansweredMar 16, 2015 at 7:48QualilogyQualilogy78955 silver badges66 bronze badges3I found JavaHome in the registry in several places. In one particular section of the registry, HKEY_LOCAL_MACHINE -> SOFTWARE -> Wow6432Node -> JavaSoft, I found some JavaHome keys pointing to the path of a 32-bit Java 1.8. I didn't explicitly install that JVM, but I suspect that installing Java for Firefox did, since that browser is 32-bit.–Chris HarrisMar 16, 2015 at 20:50I tried your advice and was able to install the 32-bit service. However, I ran into another issue that I've posted on SO (can't write to a Temp) folder). So, I uninstalled the 32-bit wrapper, uninstalled the 32-bit JRE, and installed the SonarQube 64-bit wrapper. That solved both the .dll error message and the Temp folder error message. Thanks!–Chris HarrisMar 16, 2015 at 20:53Dont forget to add %JAVA_HOME%/bin as very first path element in Windows PATH variable. That will turn off any offending 32 bit paths on sonar startup.–magguApr 7, 2015 at 9:14Add a comment|
|
I'm installing SonarQube v5.0.I'm running Windows Server 2012 64-bit (a virtual OS), Java 1.8 64-bit, and the SonarQube windows-x86-64 wrapper.SonarQube, whether run via StartSonar.bat using Command Prompt as Administrator or as a Windows Service, keeps throwing the following warning:WARNING - Unable to load the Wrapper's native library 'wrapper.dll'.
The file is located on the path at the following location but
could not be loaded:
C:\sonarqube-5.0.1\bin\windows-x86-64\.\lib\wrapper.dll
Please verify that the file is readable by the current user
and that the file has not been corrupted in any way.
One common cause of this problem is running a 32-bit version
of the Wrapper with a 64-bit version of Java, or vica versa.
This is a 32-bit JVM.
Reported cause:
C:\sonarqube-5.0.1\bin\windows-x86-64\lib\wrapper.dll: Can't load AMD 64-bit .dll on a IA 32-bit platform
System signals will not be handled correctly.The only info that I've found on the web is some JIRA's from 2010 that don't really help me. I can't create a sonar user on this Windows installation. All my other tools in my CI environment are running on Java 1.8 64-bit, which means that JAVA_HOME is set to JDK 1.8 64-bit. I really don't want to have to run Java 32-bit and the 32-bit Wrapper. That means that the JRE bin/java path at the top of wrapper.conf will have to specify the 32-bit JRE.What can I do to get rid of this warning?
|
SonarQube - Unable to load the Wrapper's native library 'wrapper.dll'
|
If you have asonar-project.propertiesfile for your project, the name is specified thanks to thesonar.projectName=...property in that file.If you are on a Maven project, this value comes from the the project name provided inside the root POM file.Otherwise, you can set the name on the command line when running the analysis, usually with the-Dsonar.projectName=...argument.ShareFollowansweredMar 27, 2018 at 13:12Fabrice - SonarSource TeamFabrice - SonarSource Team26.6k33 gold badges6363 silver badges5858 bronze badges1Yes, adding-Dsonar.projectName=...changes project name whenever you add it (tested on CE)–vladkrasMar 25, 2019 at 16:19Add a comment|
|
I already changed the key, but the displayed Name stayed the same. How can I change that one?
|
How to change the display name of a project on SonarQube?
|
SonarJava is having the rule S2970 "Assertions should be complete" that can detectassertThatwithout assertions for AssertJ, Fest and Truth.See:https://rules.sonarsource.com/java/RSPEC-2970ShareFolloweditedJul 5, 2018 at 16:39Nat3,6572121 silver badges2222 bronze badgesansweredMar 21, 2018 at 20:11Alexandre - SonarSourceAlexandre - SonarSource51922 silver badges55 bronze badgesAdd a comment|
|
I'm reading through test classes that use Assertj to verify results.
Occasionally, I've spotted an assertThat without assertions.assertThat(object.getField());Is it possible to identify these classes somewhere in the development cycle? My first guess would be to use a custom Sonar rule. Although I don't see how I should define that this method should be followed by an assertion (a method returning void?).
|
Verify that assertions have been called in Assertj
|
SonarQube doesn't calculate a code coverage. It only displays results provided by other tools.You have to execute a tool which calculates code coverage (e.g.Coverage.py) and next add analysis parameters:sonar.python.coverage.reportPath- a report path of the unit test resultssonar.python.coverage.itReportPath- a report path of the integration test resultsYou can read everything on SonarQube wiki:https://docs.sonarqube.org/display/PLUG/Python+Coverage+Results+ImportShareFollowansweredJan 21, 2018 at 19:02agabrysagabrys8,89833 gold badges3535 silver badges7575 bronze badgesAdd a comment|
|
I installed sonarqube in my MAC machine using the docker compose given below.version: "2"
services:
sonarqube:
image: sonarqube
ports:
- "9000:9000"
networks:
- sonarnet
environment:
- SONARQUBE_JDBC_URL=jdbc:postgresql://db:5432/sonar
volumes:
- sonarqube_conf:/opt/sonarqube/conf
- sonarqube_data:/opt/sonarqube/data
- sonarqube_extensions:/opt/sonarqube/extensions
- sonarqube_bundled-plugins:/opt/sonarqube/lib/bundled-plugins
db:
image: postgres
networks:
- sonarnet
environment:
- POSTGRES_USER=sonar
- POSTGRES_PASSWORD=sonar
volumes:
- postgresql:/var/lib/postgresql
# This needs explicit mapping due to https://github.com/docker-library/postgres/blob/4e48e3228a30763913ece952c611e5e9b95c8759/Dockerfile.template#L52
- postgresql_data:/var/lib/postgresql/data
networks:
sonarnet:
driver: bridge
volumes:
sonarqube_conf:
sonarqube_data:
sonarqube_extensions:
sonarqube_bundled-plugins:
postgresql:
postgresql_data:After which I used the commandsonar-scannerto analyse the project using sonarqube.The analysis report is shown above. If you notice, the code coverage part is left blank, even though I have written some python unittest scripts. Please suggest a way so that I can get the code coverage report for my python project in sonarqube. Thanks in advance.
|
sonarqube for python project not showing any test coverage
|
The reasoning behind this issue is that you are invoking a method for no good reason. How can we verify this :
Let's take this (complicated ;)) codeBoolean foo(String s) {
return true;
}What can be done is decompile this. This gives us the following bytecode instruction (simplified a bit for brevity)ICONST_1
INVOKESTATIC java/lang/Boolean.valueOf (Z)Ljava/lang/Boolean;
ARETURNAs you can see there is a method invocation to create aBooleanfrom constant 1.If we now change the code to something like:Boolean foo(String s) {
return Boolean.TRUE;
}bytecode generated is :GETSTATIC java/lang/Boolean.TRUE : Ljava/lang/Boolean;
ARETURNWhich is getting a static constant and returning it which should be more efficient.ShareFollowansweredAug 25, 2017 at 14:16benzonicobenzonico10.7k55 gold badges4444 silver badges5151 bronze badges32"which should be more efficient" the JIT will do a fine job of making them identical.–Andy TurnerAug 25, 2017 at 14:24I fully agree. That's why I used conditional here, this is the reasoning of the check and it is most probably optimized by the VM.–benzonicoAug 25, 2017 at 14:40It won't be more efficient. The JVM inlines this tiny static method and further, can trivially convert the compiled assembly to be the same.–Scott CareyFeb 26, 2018 at 18:40Add a comment|
|
We have a bunch of these messages being reported in our Java code by SonarQube's analyzers.Methodfoo(String, String)needlessly boxes a boolean constantIn many cases it is returningtrueforBooleanreturn type method.I am wonder to what extent is this a (performance?) problem with Oracle Java 8 in 2017? Does it really end up creating newBooleaninstance or does it optimize intoBoolean.TRUEauto-magically?UPDATEThe Sonar rule key isfb-contrib:NAB_NEEDLESS_BOOLEAN_CONSTANT_CONVERSION.
|
"Method foo() needlessly boxes a boolean constant" Sonar warning
|
There is aregression bugin either the Scanner for MSBuild or the VSTS extension that cause code coverage file to not being automatically imported if the user doesn't specify the report path.As mentioned in the linked thread, you can fix this issue by adding/d:sonar.cs.vscoveragexml.reportsPaths="**\*.coveragexml"into theAdvanced>Additional Settingsof theSonarQube Scanner for MSBuild - Begin Analysis (new) task.Note : make sure you have enabled theCode Coverage EnabledinTest Assembliesstep.ShareFollowansweredAug 17, 2017 at 4:19Andy Li-MSFTAndy Li-MSFT29.7k22 gold badges3535 silver badges5757 bronze badgesAdd a comment|
|
I've set up SonarQube and integrated it with our on-prem TFS build server, which is working fine except for one feature - code coverage. For some reason, it's not detecting any code coverage results even though the second SonarQube step is picking up .trx files.The "code coverage enabled" tickbox is ticked and within TFS, I am getting code coverage metrics:However, SonarQube isn't displaying coverage:When I check the build logs, it does appear that SonarQube is picking up the necessary file:However it's just not processing coverage. What could I have missed?TFS is Version 15.112.26307.0SonarQube is version 6.5
|
Sonarqube not measuring code coverage from TFS 2017 Build
|
Assuming your users and groups already exist: search for them. By default, this interface shows entities that already have permissions. To add more, just search for the missing entities by name. They'll show up in the interface and you can toggle the boxes to grant them permissions.ShareFolloweditedJun 21, 2017 at 13:18answeredJun 20, 2017 at 19:57G. Ann - SonarSource TeamG. Ann - SonarSource Team22.5k44 gold badges4242 silver badges8484 bronze badgesAdd a comment|
|
I have SonarQube 6.4 installed and I created few projects. How to grant a user/group for a private project? When I go to Project Administration Permissions (where I can switch a project between public and private), it only shows sonar-administrators group. Where can I add a group for this project?
|
How to grant project permissions to new users/groups?
|
You can try to do it directly from you pipeline script:def scannerHome = tool 'SonarQube Scanner';
withSonarQubeEnv('SonarQube') {
sh "${scannerHome}/bin/sonar-scanner -Dsonar.projectKey=advant-web -Dsonar.sources=. -Dsonar.exclusions=node_modules/**,build/** -Dsonar.projectVersion=1.0.${BUILD_NUMBER}"
}
sleep 10
sh "curl -u user:password -X GET -H 'Accept: application/json' http://localhost:9000/api/qualitygates/project_status\\?projectKey\\=my-project > status.json"
def json = readJSON file:'status.json'
echo "${json.projectStatus.status}"
if ("${json.projectStatus.status}" == "ERROR") {
currentBuild.result = 'FAILURE'
error('SonarQube quality gate status of a project is invalid.')
}or in case of upgrade SonarQube Scanner for Jenkins up to 2.61 you can write something like following:...
timeout(time: 5, unit: 'MINUTES') {
def qualitygate = waitForQualityGate()
if (qualitygate.status != "OK") {
error "Pipeline aborted due to quality gate coverage failure."
}
}You can read more here:https://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner+for+JenkinsShareFolloweditedNov 12, 2017 at 22:38CommunityBot111 silver badgeansweredNov 12, 2017 at 21:31Andrew MolyukAndrew Molyuk5111 silver badge33 bronze badgesAdd a comment|
|
I have created a Jenkins build pipeline and configured SOnar as I described in one of my earlierquestions.The Console Output for the build provides in it a URL that I am using for checking the results of Sonar Analysis. However, my requirement is that based on the number of defects that Sonar finds, it should fail the Jenkins build if a specific 'x' no. of defects are found. Pls suggest how this can be configured in the pipeline
|
Failing a Jenkins build pipeline based on Sonar Results
|
if(savedList == null && supplierList == null){
return false;
}
if(savedList == null && supplierList != null){The conditionsupplierList != nullis always true when reached.
Due to the short-circuiting behavior of the&&operator in Java,
beforesupplierList != nullis reached,savedList == nullmust be true first.But ifsavedList == nullis true,
then we know from the previous condition thatsupplierListis notnull, so it's a pointless condition.On the other hand, ifsavedList == nullis false,
then the due to the short-circuiting behavior,
thesupplierList != nullwill not be evaluated.Thus, regardless of the outcome ofsavedList == null,supplierList != nullwill never be evaluated,
so you can simply remove that condition.if (savedList == null) {
return true;
}Next:if(savedList != null && supplierList == null){Thanks to the simplification earlier, now it's clear thatsavedListcannot benull. So we can remove that condition too:if (supplierList == null) {
return true;
}In short, this is equivalent to your posted code:if (savedList == null && supplierList == null) {
return false;
}
if (savedList == null || supplierList == null) {
return true;
}ShareFolloweditedDec 20, 2016 at 9:04answeredDec 19, 2016 at 18:37janosjanos123k3030 gold badges234234 silver badges241241 bronze badges1You could even merge the last two if clauses toif (savedList == null || supplierList == null) return true–ChristianDec 20, 2016 at 8:43Add a comment|
|
I am getting sonar violation:"Conditions should not unconditionally evaluate to "TRUE" or to "FALSE""for the code below.List<MediaContent> savedList = source.getChildMediaContents();
List<MediaContent> supplierList = target.getChildMediaContents();
// if existing and incoming both empty
if(savedList == null && supplierList == null){
return false;
}
// if one is null and other is not then update is required
if(savedList == null && supplierList != null){
return true;
}
if(savedList != null && supplierList == null){
return true;
}Below the two if blocks it is giving an error// if one is null and other is not then update is required
if(savedList == null && supplierList != null){
return true;
}
if(savedList != null && supplierList == null){
return true;
}
|
Sonar error Conditions should not unconditionally evaluate to "TRUE" or to "FALSE"
|
This is expected behaviour. When analysing Maven projects with theSonarQube Scanner for Maven,sonar.projectKeyis automatically set to<groupId>:<artifactId>.To analyse different branches of the same project: do not overridesonar.projectKey, simply use thesonar.branchparameter.Full details in theSonarQube Analysis Parameters documentation.ShareFollowansweredAug 10, 2016 at 8:31Nicolas B.Nicolas B.7,2631818 silver badges2929 bronze badges0Add a comment|
|
I'm having some trouble and I'm trying to fix my Jenkins builds.I use it to build the same project but different branches. So, to separate the result for the Sonar analysis.In the Build tab from my project, the options I set are :clean install -DtestFailureIgnore sonar:sonar -Dsonar.projectKey=MY_PROJECT_KEYFor some builds, it just works perfectly fine, and for some others, my project key in Sonar becomegroupId:artifactIdusing thepom.xmldata, and it makes Sonar mixing some of the branches.Does anyone know how to help about that problem?Sonar version:5.4Jenkins version:1.651.1
|
Wrong projectKey with Jenkins Build on Sonar Analysis
|
SonarQube 5.6 (LTS *) – Jun. 3, 2016Long Term Supported version, requires Java 8 to runVersion fromSonarQube 5.1.2toSonarQube 5.5Should work fine with Java 7ShareFollowansweredJun 22, 2016 at 4:26Beniton FernandoBeniton Fernando1,53311 gold badge1414 silver badges2121 bronze badgesAdd a comment|
|
My jdk version is 1.7.0. I searched answer but I don't find correct answer yet.This is error I have got. Plaese help me to solve the problem.C:\sonarqube-5.6\bin\windows-x86-64>StartSonar.bat
wrapper | --> Wrapper Started as Console
wrapper | Launching a JVM...
jvm 1 | Wrapper (Version 3.2.3) http://wrapper.tanukisoftware.org
jvm 1 | Copyright 1999-2006 Tanuki Software, Inc. All Rights Reserved.
jvm 1 |
jvm 1 | WrapperSimpleApp: Unable to locate the class org.sonar.application.App: java.lang.UnsupportedClassVersionError: org/sonar/application/App : Unsupport
ed major.minor version 52.0
jvm 1 |
jvm 1 | WrapperSimpleApp Usage:
jvm 1 | java org.tanukisoftware.wrapper.WrapperSimpleApp {app_class} [app_a
rguments]
jvm 1 |
jvm 1 | Where:
jvm 1 | app_class: The fully qualified class name of the application t
o run.
jvm 1 | app_arguments: The arguments that would normally be passed to the
jvm 1 | application.
wrapper | <-- Wrapper Stopped
Press any key to continue . . .
|
SonarQube does not start on windows even though path variables were set
|
Current support for bugs and vulnerabilities is a "creative implementation" (read "hack") based on tags. So, add the "bug" tag to your rule and its issues will be raised as bugs. Add the "security" tag to a rule and its issues will be raised as vulnerabilities.Rules with both "bug" and "security" tags will be treated as bug rules.For future reference, this mechanism is expected to change in the "near" future, but there's currently no schedule for it.EditThe current (6.1) version of the API provides the ability to simply declare rule type.ShareFolloweditedNov 14, 2016 at 15:05answeredJun 20, 2016 at 11:51G. Ann - SonarSource TeamG. Ann - SonarSource Team22.5k44 gold badges4242 silver badges8484 bronze badges3Thank you for the explanation. I suppose there isn't a way to add tags on-the-fly at the time of the creation of the issue (object), am I right?–jonyperaJun 20, 2016 at 12:50Uhm... that would be a very dark corner of the API indeed.–G. Ann - SonarSource TeamJun 20, 2016 at 14:371No problem. Glad to know how that categorization works at least. In the future (like you said), it would be nice to categorize the issue with ease, like one more parameter ofnewIssueBuilder(). Just a developer's suggestion :) Thanks again.–jonyperaJun 20, 2016 at 14:43Add a comment|
|
After upgrading to 5.5 version and now the latest (5.6) SonarQube always shows the issues I create through my plugin as "Code Smell". I would like to know more about the categorization and how can I add them as other types ("Vulnerability" and "Bug"). The code where I create the issues is as follows:Issuable issuable = this.resourcePerspectives.as(Issuable.class, inputFile);
if (issuable != null) {
Issue issue = issuable.newIssueBuilder()
.ruleKey(activeRule.ruleKey())
.line(vulnerability.getLine())
.message(someMessage)
.severity(severity)
.build();
issuable.addIssue(issue))
} //...
|
SonarQube adds all issues as Code Smell
|
The Build Breaker stopped working in SonarQube 5.2. You now have 2 ways to implement the Build Breaker functionality:thecommunity supported plugintheapi/qualitygates/project_statusweb service (developed in 5.3). You can then easily create your own script to check the quality gate status of a given projectFor a bit of context, here'swhy SonarSource thinks the Build Breaker shouldn't be usedShareFolloweditedNov 21, 2016 at 15:48bmg15322 silver badges88 bronze badgesansweredApr 29, 2016 at 14:08Teryk - SonarSourceTeryk - SonarSource99455 silver badges1212 bronze badgesAdd a comment|
|
I am usingJenkins Continuous Integrationserver andSonarqubefor code coverage. I want to make sure that if the issues in the project reach athresholdvalue ofQuality Gate, the project build should fail. I have installedBuild Breakerplugin inSonarqube. I read somewhere that it applies on each and every project by default and sends build failed report to CI server(Jenkins in my case).But this is not happening. My project builds are successful on CI server even if the issues have reached threshold value.I am not able to use Build Breaker as it doesn't provides any parameters or something to configure it. The problem looks like this:Please help me to configure this, so that I can send a failed build status to my CI server.
If it is not possible in any way, then please let me know if there is any notification mechanism to at least notify developers about issues that have reached threshold.
|
How to use the Build Breaker on sonarqube 5.1+ if a project quality gate fails
|
As of G. Ann response was actually discontinued puglin for Sonar, but searching the internet, and recently (3 days) the developerFabricio Columbusmade it happen!We tested and is running the current version of Sonar:Compatible with SonarQube 4.5.x and SonarQube 5.1.2https://github.com/fabriciocolombo/sonar-delphiRelease:https://github.com/fabriciocolombo/sonar-delphi/releasesJAR:https://github.com/fabriciocolombo/sonar-delphi/releases/download/0.3.3-SNAPSHOT/sonar-delphi-plugin-0.3.3-SNAPSHOT.jarPS: Translated from Portuguese to English by Google Translate.ShareFolloweditedDec 17, 2015 at 11:54answeredDec 15, 2015 at 16:24DavidDavid29011 gold badge66 silver badges1515 bronze badges5Sorry but I don't know what to do with that. It's source code only. Not the plugin itself. Do you have a link for the .jar file of the plugin itself?–RemiDec 17, 2015 at 8:30Later I upload and place the Link–DavidDec 17, 2015 at 10:05And what parameters do you need to use? Is sonar.language=delphi? Or sonar.language=.pas?–RemiDec 17, 2015 at 15:351I believe that "delph", download the repository that has a set every instance, will help you better.github.com/fabriciocolombo/sonar-delphi/tree/master/samples–DavidDec 17, 2015 at 15:461JAM Software created a fork of the SonarDelphi plugin. We fixed various grammar issues and a few others:github.com/JAM-Software/SonarDelphi–Joachim MarderFeb 12, 2021 at 13:43Add a comment|
|
I want to configure SonarQube so it can analyze Delphi project too, and when I search online I saw there used to be a delphi plugin for SonarQube. But when I look at the plugins with the latest build it doesn't show the delphi plugin.Is the plugin still available in an other way?Or is it possible to configure SonarQube for delphi without the plugin?
|
How to Configure SonarQube for delphi?
|
Finally found a solution myself.In SBT you can define a new task A which captures the result of another task B. This dependency ensures that task B is run when the new task A is started. By capturing the result, the result of task B is not the result of task A so if B fails, A does not (have to) fail.So in this case, I added created a new 'ciTests' tasks to the 'build.sbt'// Define a special test task which does not fail when any test fails,
// so sequential tasks (like SonarQube analysis) will be performed no matter the test result.
lazy val ciTests = taskKey[Unit]("Run tests for CI")
ciTests := {
// Capture the test result
val testResult = (test in Test).result.value
}Now in the Jenkins job it build the project using SBT with commands (usingSCoverage SBT plugin):update coverage ciTests coverageReportThis build will succeed ignoring any failing tests. Therefore a next build step to start SonarRunner will start the analysis of the Scala project and put the results in SonarQube.Thanks to @hugo-zwaal for pointing me tothis answerwhich helped me solving my issue.ShareFollowansweredMar 9, 2015 at 10:40Joost den BoerJoost den Boer4,71744 gold badges2626 silver badges4040 bronze badgesAdd a comment|
|
For SonarQube jobs in Jenkins we'd like to proceed even though some tests might fail. Currently the Sonar Runner is not kicked off, because a test fails.
In Maven you'd just add-DtestFailureIgnore = true, but I cannot find anything similar for SBT.I did find aonFailurething for sbt, but have not found any examples anywhere how to use this. Could this be used to ignore test failures so the build job continues so the Sonar Runner gets started afterwards?Or is there a setting in Jenkins to ignore the result of the build?
We use 'sbt clean coverage test coverageReport' as build command and have Sonar Runner in a post-build step.
|
sbt ignore test failures
|
Make sure you are logged into Sonar.Click on Quality Profiles in the top navigation bar, then click on "Restore Profile" on the right hand side under the search bar. Make sure you have all the applicable quality plugins that the export is using or the restore will choke.ShareFollowansweredNov 5, 2014 at 18:11William HelgesonWilliam Helgeson13688 bronze badges3What are the required plugins for restoring profile? I replicating some profile from one Sonar to another, but its not importing rules.–Kuldeep SinghNov 24, 2016 at 7:41what are the plugin you are mentioning–BravoJan 19, 2017 at 8:29Things like CheckStyle, PDM, FindBugs etc. See thePlugin Library.–William HelgesonJan 19, 2017 at 21:39Add a comment|
|
i have a local sonar server running. i would like to create a new profile with a set of rules that were predefined by someone else. i have the XML file containing all the rules.is there a way to upload the XML file to the profile and not define the rules manually?thanks
|
How can I load a predefined rule set to a sonar profile
|
I think if you would manage to attach the JaCoCo-agent to the jvm that runs the jetty, it should be able to measure which code has been called over the time you run the integration tests against your webapp. So you should get a statistic that shows you the code coverage.There is a JaCoCo Maven Plugin - though I'm not sure if this will help with you scenario. Just used it during unit tests.Edit: found a blog-post that seems to point in the right direction hereMeasure Code Coverage by Integration Tests with SonarShareFollowansweredNov 21, 2013 at 18:37PepperBobPepperBob70933 silver badges88 bronze badgesAdd a comment|
|
I am writing a multi-module application. Some of the modules are just basic Java libraries which are then included in the WAR of a webapp.I would like to run code coverage in the following scenario:I am running the webapp through an embedded Jetty that is started via Maven.I have tests which are executing HTTP requests against the webapp.I would like to get code covered in the webapp and also by the tests.Is this possible and how can it be achieved with Cobertura, JaCoCo or Emma? From what I understand, the code coverage will only cover the client-side code in this scenario. Am I correct?
|
Code coverage of client/server web application
|
Not sure what Sonar is thinking but defensive shallow copying withclone()should work fine for arrays, as wouldArrays.copyOfandSystem.arrayCopy().On the other hand, since you are already calling the array a list:selectedObjectsList, you could also make it an actual list and refactor a bit:public final void setSelectedSchedules(List<ScheduleDTO> selectedSchedules) {
this.selectedSchedules = selectedSchedules != null ? new ArrayList<ScheduleDTO>(selectedSchedules) : null;
}ShareFollowansweredJun 3, 2013 at 19:29JukkaJukka4,6131919 silver badges1414 bronze badges16+1. And while you're at it, using null arrays or lists is a bad practices. These should never be null. Empty, yes. Null, no.–JB NizetJun 3, 2013 at 19:37Add a comment|
|
I even refered :Sonar Violation: Security - Array is stored directlyMy code is as --->public final void setSelectedObjectsList(final ScheduleDTO[] selectedObjectsList)
// Security - Array is stored directly
//The user-supplied array 'selectedObjectsList' is stored directly.
{
if (selectedObjectsList != null) {
this.selectedObjectsList = selectedObjectsList.clone();
} else {
this.selectedObjectsList = null;
}
}This is already taking care of defensive copy wonder why sonar is yelling at me right at function parameter.This not not duplicate asSonar Violation: Security - Array is stored directlyAgain, Thank-you for your hyelp and time.
|
Security - Array is stored directly
|
Sonar cannot run tests, it can only analyze testing reports.You can run yourself JUnit ( using Maven or Ant for exemple ) and push reports to Sonar (try Sonar's Mavenpluginfor that)or you can give yourself a build factory (tryhudsonfor exemple) and plug it tosonar.ShareFolloweditedOct 21, 2014 at 14:10Giovanni P.1,0271616 silver badges2424 bronze badgesansweredAug 10, 2012 at 12:49mabroukbmabroukb69144 silver badges1111 bronze badges4Well then I want to reuse TestNG results. Isn't a way to show sonar the path to these results (xml file)?–spaunyAug 10, 2012 at 13:30This is not true, Sonar can run tests. If you look at the documentationdocs.codehaus.org/display/SONAR/Analyzing+with+Mavenyou will see they recommend turning off tests in the Maven build to avoid them being run twice, once when you build, once when you use Sonar.–Mark ButlerAug 18, 2013 at 12:59both analyses you're talking about are run with maven : first one during maven install goal, second one during maven sonar goal–mabroukbAug 25, 2013 at 9:001@MarkButler your link is dead. Also, according to thissonarsource.com/blog/unit-test-execution-in-sonarqubesonar dropped the unit test execution.–JRichardszApr 13, 2023 at 14:54Add a comment|
|
I have a project built with maven and I recently integrated Sonar... It is really easy to configure Sonar to analyze you're project but I couldn't configure it to run my project unit test also. I tried something with Jacoco but I get some Seam error and all the other tests are skipped. By the way I'm using TestNG to run tests manually.
|
Sonar how to run unit test successfully
|
result.getToken()might return null. So when you callresult.getToken().getToken()you are callinggetToken()on a null reference. Thus a NullPointerException will be thrown.So you could do something likeYourClass token = result.getToken();
if(token != null) {
String vaultToken = token.getToken(); // whatever you want to do with it
}
else {
// error handling
}ShareFolloweditedAug 6, 2021 at 1:16andrewwong978,81911 gold badge1212 silver badges66 bronze badgesansweredFeb 20, 2021 at 9:56geanakuchgeanakuch85699 gold badges1515 silver badges2727 bronze badgesAdd a comment|
|
Small question regarding a SonarQube flagged issue I do not understand please.My snippet is very simple.VaultTokenResponse result = getWebClient().mutate().baseUrl(vaultUrl).build().post().retrieve().bodyToMono(VaultTokenResponse.class).block();
String vaultToken = result.getToken().getToken();However, on the second line here, Sonarqube is telling me:findbugs:NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE Style - Possible null pointer dereference due to return value of called method
The return value from a method is dereferenced without a null check, and the return value of that method is one that should generally be checked for null. This may lead to a NullPointerException when the code is executedI am a bit unsure what this means.Most of all, I do not know how to fix this.Little help please?Thank you
|
Possible null pointer dereference in [...] due to return value of called method
|
There seem to be a way of doing it but it may not be supported i.e.<properties>
<sonar.issue.ignore.multicriteria>e1</sonar.issue.ignore.multicriteria>
<sonar.issue.ignore.multicriteria.e1.ruleKey>squid:S00107</sonar.issue.ignore.multicriteria.e1.ruleKey>
<sonar.issue.ignore.multicriteria.e1.resourceKey>**/*.java</sonar.issue.ignore.multicriteria.e1.resourceKey>
</properties>Refer to :https://community.sonarsource.com/t/documentation-about-ignore-issues-seems-to-be-wrong-or-outdated/3353but they do state :We recommend users to use the UI to configure this, for best
experience. Consider the configuration via sonar-project.properties as
an undocumented hack, not official supported that may or may not work
reliably, use at your own risk.ShareFolloweditedJan 18, 2021 at 20:54leo3,58733 gold badges2121 silver badges1919 bronze badgesansweredSep 9, 2019 at 15:22mkanemkane90099 silver badges1616 bronze badges2nice, thank you, how about if i want to add multiple squid id?–aswzenJun 18, 2020 at 9:33Not tried this but one would assume that you just add another comma separated entry i.e. 'e2' to sonar.issue.ignore.multicriteria and then just add the two new entries i.e. sonar.issue.ignore.multicriteria.e2.ruleKey and sonar.issue.ignore.multicriteria.e2.resourceKey with their independent values.–mkaneJun 19, 2020 at 14:07Add a comment|
|
I am usingSpring Boot and Spring Jpaexample and looking to disabled below Sonar rule through Maven mainly usingpom.xmlfile. I don't have access or can't go and disable that rule inSonarQubeas it's configured for the Org level.Methods should not have too many parameters (squid:S00107)I already went through web many times and did not find any promising solutions yet. This is what I look at :Configure Sonar to exclude files from Maven pom.xmltoo.
|
Disable Sonar rule using pom.xml?
|
According toJaCoCo changelogsuch private empty no-argument constructors are automatically filtered out starting from JaCoCo version 0.8.0. Changelog also notes:Tools that directly read exec files and embed JaCoCo for this (such as SonarQube or Jenkins) will provide filtering functionality only after they updated to this version of JaCoCo.Announcement of release of JaCoCo version 0.8.0states:Tools that directly read exec files (which is not a final report) and embed JaCoCo for generation of report will provide filtering functionality only after they updated to this version of JaCoCo.
So please follow/wait/etc respective vendors such asSonarQube -https://jira.sonarsource.com/browse/SONARJAVA-2608Eclipse EclEmma -https://bugs.eclipse.org/bugs/show_bug.cgi?id=529391Jenkins -https://github.com/jenkinsci/jacoco-pluginReports generated by corresponding version (0.8.0) of integrations developed as part of JaCoCo project by us (Ant Tasks, Maven Plugin and Command Line Interface) provide filtering functionality.As of today (30 Jan 2018):update for SonarQube (https://jira.sonarsource.com/browse/SONARJAVA-2608) is supposed to be in not yet released SonarJava plugin version 5.1update for Jenkins Plugin (https://github.com/jenkinsci/jacoco-plugin/commit/d04b50962a022b615d5085271f1696d9f6080198) is committed but also not yet releasedShareFollowansweredJan 30, 2018 at 8:05GodinGodin10.1k33 gold badges4141 silver badges7878 bronze badgesAdd a comment|
|
I have a util class which is final and I have added one private constructor for hide the default public one. How I can get the coverage for this class in sonarqube with jacoco coverage report and build in Jenkins?public final class Util {
// My contructor
private Util() {
super();
}
}
|
How to give test coverage for private constructor of a final class in sonarqube?
|
You can also usesonar.propertiesto define the smtp settings. But this approach is not recommended and therefore barely documented.However, there is a little of documentation inthe sources.An example:email.smtp_host.secured=my.smtp.server
email.smtp_port.secured=9918
email.smtp_secure_connection.secured=true
email.smtp_username.secured=slartidan
email.smtp_password.secured=password123[email protected]email.prefix=[SONARQUBE] Important:ShareFolloweditedAug 18, 2017 at 9:44answeredAug 17, 2017 at 15:29slartidanslartidan20.9k1616 gold badges8888 silver badges135135 bronze badges5Thanks for your response. can you please show some configuration for reference.@slartidan–SamAug 17, 2017 at 15:45@Sam I added an example (untested)–slartidanAug 18, 2017 at 9:44Thanks, I tried with the values you provided, after giving all config for these attributes I can able to see only smtp port and prefix is the only value passed from sonar.properties to sonarqube UI. Values for hostname and username doesn't get passed from sonar.properties to UI. My sonarqube version is 5.6.6 is there any modifications I need to proide?–SamAug 21, 2017 at 21:16Have you had any success? It seems to be a bug, I found this discussion as well:groups.google.com/d/topic/sonarqube/aAFPS2KpuY8/discussion–StephanFeb 15, 2018 at 11:05Why is it not recommended? Seems best practice for me for modern approaches like infrastructure as code, that explicitly avoids manual changes.–DanielSep 26, 2019 at 12:03Add a comment|
|
SonarQube's SMTP settings can be changed in the web UI.How can I set those SMTP settings in thesonar.propertiesconfiguration file?
|
How to configue SMTP in sonar.properties?
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.