Response
stringlengths 8
2k
| Instruction
stringlengths 18
2k
| Prompt
stringlengths 14
160
|
---|---|---|
Sonarlint/SonarQube allows you to use comments for disabling analysis in specific lines. In order to do this, you can just add a comment with the textNOSONARin the same line:Random rand=new Random();//NOSONAR not used in secure contextsAside from this, you can mark Security Hotspots as resolved in the web Dashboard of SonarQube. In order to do this, you need to navigate to the Security Hotspot and mark it as not an issue. You might even want to disable that specific type of Security Hotspot entirely if it is generally not applicable for your project.
|
I'm getting a Sonar CSRF Security Hotspot complaint on a Spring Boot code with Spring Security enabled that needs to be reviewed every then and now, and I would like to suppress the hotspot from the code as in@SuppressWarnings("squid:x")sonar.cpd.exclusionssonar.coverage.exclusionsbut as it it not a rule it has no id, at least on the screenHow can I silence this warning on the server from the code?
|
How to SupressWarnings for Sonar Security Hotspots?
|
SonarQube lets you get exhaustive data using its Web API. Taking your example of project's measures:Since SonarQube 5.4Useapi/measuresWeb API (see parameters indocumentation). Example for projectpostgresql:Get the component ID:https://nemo.sonarqube.org/api/components/show?key=postgresqlGet the desired metrics:https://nemo.sonarqube.org/api/measures/component?componentId=6d75286c-42bb-4377-a0a1-bfe88169cffb&metricKeys=sqale_debt_ratio&additionalFields=metrics,periodsBefore SonarQube 5.4Useapi/resourcesWeb API:http://sonarqube_url/api/resources?resource=your_resource&metrics=metric_keyListing metric keysUseapi/metrics/search(documentedhere), see alsoMetric Definitions.
|
I want to be able to extract, for example, just the Technical Debt numbers out of my sonar instance for all the projects I have, and display them on a page.Does Sonar provide an api that I can utilize and achieve this?
|
SonarQube - Is there an API to grab a part of analysis for all projects you have?
|
It seems no repository is declared for the project you want to use with the sonar-runner plugin.
You might have configured repositories for buildscript or for other projects only (in your multiproject build?)To resolve the sonar-runner you need to configure a repository where it could be resolved from. You might have a coorporate repository in your company or you could use public ones like mavencentral or bintray. to declare for example the jcenter repository to resolve the sonar-runner. just add the following to your build script:repositories {
jcenter()
}
|
I am trying to set up the Sonar-Runner with my existing gradle project. I am using Sonar-Runner 2.4 Gradle 2.2.1 and our Sonar server is 4.3.1. When I run gradle sonarRunner I get the following error:Could not resolve all dependencies for configuration ':sonarRunner'.
Cannot resolve external dependency org.codehaus.sonar.runner:sonar-runner-dist:2.4 because no repositories are defined.I do have the artifact "org.codehaus.sonar.runner:sonar-runner-dist:2.4" in my nexus server that is set up in my build.gradle file. Does anyone have any intuition about this error? I have googled it extensively and been stuck on this for a couple of hours now.My build.gradle for the sonar runner is very simple:apply plugin: 'sonar-runner"
sonarRunner{
toolVersion = '2.4'
sonarProperties{
property "sonar.host.url", "$sonarHost"
}
}
|
Gradle cannot resolve dependencies for Sonar-Runner
|
Removed SonarQube plugin .This solved the issue.
Now it works all fine.
But is there any other solution to this problem since I have to use sonar.
|
I had made an maven project and it worked fine.
Then I installed plugins
EclEmma Java Code Coverage,
PHP Development Tools (PDT),
Eclipse.orgSonarQubeThen I worked on some other project. When I again wanted to create an maven project,it threw the following error window which saidThe selected wizard could not be started
reason
plug-in org.eclipse.m2e.core.ui was unable to load class
org.eclipse.m2e.core.ui.internal wizards.MavenProjectWizard
|
plug-in org.eclipse.m2e.core.ui was unable to load class
|
Common pitfall to use the wrong pattern to exclude. Notice the .Bad :<sonar.jacoco.excludes>*.model.*</sonar.jacoco.excludes>Good:<sonar.jacoco.excludes>*model*</sonar.jacoco.excludes>Documentation for weary travellers.
|
When I write<sonar.jacoco.excludes>*.model.*</sonar.jacoco.excludes>The package is not excluded from instrumentation / reporting and coverage shows as 0%Why is this ?Sonar version 3.6
|
Sonar Jacoco Excludes sonar.jacoco.excludes causes 0% coverage instead of ignored.
|
Search in Google by keywordssonarqubekotlinjacocoandis out of range in the filereveals following pagehttps://community.sonarsource.com/t/sonar-kotlin-coverage-fails-due-to-line-is-out-of-range-errors/3201/18, which states that problem was fixed in JaCoCo version0.8.3And which contains link to pagehttps://github.com/jacoco/jacoco/issues/763, which in its turn contains quite expressive explanation of problem, including explanations of why it affects SonarQube.So make sure that you use JaCoCo version0.8.3or even better latest, which is0.8.7as of 8 September 2021.
|
I'm having some issues when trying to import Jacoco code coverage to SonarQube.I am using SonarQube with Jacoco for importing test coverage results (https://docs.sonarqube.org/display/PLUG/Java+Unit+Tests+and+Coverage+Results+Import). Everything has worked well until i haveforEachblock in some method.ERROR: Cannot import coverage information for file, coverage data is invalid.
java.lang.IllegalStateException: Line 29 is out of range in the file (lines: 28)If I removeforEachfile then test coverage is correctly generated, but withforEachI get 0% coverage.This happens only when i integrate it with sonarqube, if i run jacoco locally it works perfectly.We use SonarQube Scanner 3.3.0.1492, SonarQube server 7.5.0.
|
Issue when trying to import Jacoco code coverage to SonarQube: Cannot import coverage information for file, coverage data is invalid
|
SonarQube provides plenty of options for ignoring issues in specific files and/or code blocks, seeNarrowing the Focus documentation(and to your specific case: look forIgnore Issues in Blocks).
|
I would like to disable a block of code(say a function) in a file for analysis by SonarQube... Any suggestions on how to do that..I found something for java here -->Turning Sonar off for certain code
|
SonarQube JavaScript disable a part of code
|
There is a big difference between sonar.junit.reportPath and sonar.jacoco.reportPath. You are mixing up the values.Similarly, there's sonar.jacoco.itReportPath (for non-Unit tests based jaocco.exec files for ex: jacocoIT.exec (if you are creating for Integration tests).Now, Depending upon the version of sonarQube instance (4.x or latest 5.x.x), you may need to set either sonar.junit.reportPath or sonar.java.junit.reportPath to the value (which is the folder containing the .xml data).For ex: If my Unit tests or Integration tests folder's result files (.xmls) are in folder build/test-results/UT folder, then:sonar.java.junit.reportPath=build/test-results/UTorsonar.junit.reportPath=build/test-results/UTFor the code coverage file (.exec), you have to use:sonar.jacoco.reportPath=build/jacoco/UT/jacocoUT.execorsonar.jacoco.itReportPath=build/jacoco/IT/jacocoIT.execImportant- Sonar Properties:sonar.jacoco.xxxpoints to the filename.sonar.junit.xxxorsonar.java.junit.xxxpoints to a folder name.sonar.surefire.xxxorsonar.java.surefire.xxxpoints to a folder name.Similar tosonar.junit.reportPath, there's also another property called: sonar.surefire.reportPath or sonar.java.surefire.reportPath. Look for Sonar docs for more help under Analyzing Source code with Maven/Gradle.http://docs.sonarqube.org/display/SCAN/Analyzing+Source+Code(expand it).For ex: UnderAnalyze with Gradle build system, look forConfigure Analysis Propertiessection/more.
|
This question already has answers here:SonarQube not picking up Unit Test Coverage(10 answers)Closed8 years ago.I generated a coverage report usingEclEmmawith the following path :C:/tmp/coverageReport/report.execThis file exists, is not empty and is readable.
My sonnar-runner configuration regarding code coverage is defined as follows :sonar.java.coveragePlugin=jacoco
sonar.junit.reportsPath=C:/tmp/coverageReport/report.execThe analysis completes successfully but no data is visible in theUnit test coveragewidget.Moreover, I get the following lines during the analysis :18:23:45.036 INFO - parsing C:/tmp/coverageReport/report.exec
18:23:45.037 WARN - Reports path not found: C:/tmp/coverageReport/report.execAny ideas on what I'm missing ?
|
Jacoco reports path not found by sonar-runner [duplicate]
|
I found this unanswered question when searching on the same issue. Do not use Create, use Restore Profile link above it for profile backups.
|
I have an issue when creating a new profile in sonarqube-4.1.2. Here is at I did:I have sonar 3.1 rt now, that has 461 rules. Did a back up and saved the rule files containing rules for checkstyle. pmd and findbug.I did try to create a new profile by clicking on "Create" in 4.1.2. It give me errorThe Findbugs configuration file is not valid : profile : profile [hide]I also tried to Restore Profile which also is not importing the right number of rules. restoring only 345 rules.In the log I see this error:ERROR [o.s.p.f.FindbugsProfileImporter] The Findbugs configuration file is not valid
com.thoughtworks.xstream.mapper.CannotResolveClassException: profile : profile
at com.thoughtworks.xstream.mapper.DefaultMapper.realClass(DefaultMapper.java:68) ~[xstream-1.3.1.jar:na]Please suggest what can be done to fix this.
|
The Findbugs configuration file is not valid Error While uploading rule file to sonarQube
|
The classification of these curly braces as “useless” is wrong.You can omit curly braces around a singleexpression statement, that is, for example, a method invocation, anewexpression, orx++,x+=y, etc.Or you can transform a sole… -> { return x; }statement into an expression… -> x.But you can’t omit curly braces around every single statement.You can’t fix that. The only thing you can do is file a bug report.By the way, even then, removing them is not necessarily a readability improvement. It depends…
|
These code examples:import java.util.Observer;
public class Main {
public static void main(String[] args) {
Observer observer = (o, arg) -> {
if (arg != null) {
System.out.println(arg);
}
};
}
}import java.util.Observer;
public class Main {
public static void main(String[] args) {
Observer observer = (o, arg) -> {
try {
String test = (String) arg;
...
}
catch (ClassCastException e) {
}
};
}
}are noncompliant with thissonarqube rule:Lamdbas containing only one statement should not nest this statement
in a block : Remove useless curly braces around statementhow can i fix it ?
|
Sonar : lambda - Remove useless curly braces around statement
|
The Magic Number violation doesn't understand if this number appears in an annotation or not. IMHO this is a false-positive and you can deal with it in two ways.
Either disable this rule in your quality profile or create a MAGICNUMBER class and list all the numbers you're using as static properties. For example look the following classpublic final class MAGICNUMBER {
public static final int L8000 = 8000;
public static final int L300 = 300;}Then you can use it in your class like this@NotNull
@Size(min = 1, max = MAGICNUMBER.L300)
@Column(name = "NAME")
|
We are using sonar for managing our code quality. I have a problem with "Magic Number" violation for JPA annotation like that:@NotNull
@Size(min = 1, max = 300)
@Column(name = "NAME")Is this a true violation for annotation?If not, how can we deal this kind of Sonar violation?
|
Magic number sonar violation on JPA annotations
|
I did not configure thesonar.exclusionsvia the UI like what you mentioned. You can try with below method in azure devops.Just specify it in task definition(Sample):- task: SonarCloudPrepare@1
displayName: 'Prepare analysis on SonarCloud'
inputs:
SonarCloud: 'SonarCloud'
organization: 'xxxx'
scannerMode: 'MSBuild'
projectKey: 'xxxx'
extraProperties: sonar.exclusions=**/Properties/**Here is what my project structure:See thisPropertiesfolder was ignored successfully:
|
I have an ASP.NET MVC5 web app running on an Azure Devops CI/CD pipeline which includes SonarCloud for static code analyses. I am trying to ignore all 3rd party files such as Javascript/JQuery libraries which are throwing up a lot of "Bugs" and "Code Smells".I would like to hide these files specifically:INFO: 4/9 files analyzed, current file: BookingSystem/Scripts/jquery-3.3.1.jsI have tried various sonar.exclusions in Administration > General Settings > Analysis Scope > Files > Source File Exclusions and none have hidden the specific folders:sonar.exclusions=**\Scripts\**
sonar.exclusions=Scripts\**
sonar.exclusions=**\Scripts**
sonar.exclusions=**\BookingSystem\Scripts\**picture of logsCan anyone tell me which format to use please?
|
ignoring specific files/folders with sonar.exclusions
|
Have a look athttps://sonarcloud.io/explore/projects.It is not a demo site - it is a globally available SonarQube server, managed by SonarSource (the company behind SonarQube). Many huge open source projects are managed there for free, but you can also host your own, private projects for closed source.It gets updated every couple of weeks and for public releases.Besides that, there ishttp://next.sonarqube.com, the publicly visible SonarQube server for SonarQube itself and related projects (yes: SonarQube for SonarQube).This instance gets updated every couple of days. If you want to have a look at what features SonarQube's next version will look like: have a look there.
|
I've haven't looked at SonarQube for some time. The latest version looks quite interesting.The last time I checked out this product, they had a site where they had pushed various popular open source libraries (like Tomcat, ActiveMQ etc) through the SonarQube process. It was a great way of seeing how the product works.Is this facility still available for the latest versions?
|
Does SonarQube still have demo site that shows analysis on major open source projects?
|
On Linux the port below 1024 can only be bind by root user. Your SonarQube must be runned with a normal user account.The usual solution for this is to use nginx or apache to proxy from port 80 to 9000.
|
I've been trying to change the port of SonarQube from 9000 to 80.
What I did was uncommentsonar.web.portand set it to 80 in the/opt/sonar/conf/sonar.propertiesfile, and then:sudo update-rc.d sonar defaults
sudo /etc/init.d/sonar restartBut when I try to hit the URL, nothing shows up (no answer from the server).
If I revert my changes and execute the two previous commands again, SonarQube doesn't come back. I have to reboot the machine.I'm running the latest version of Ubuntu and of SonarQube. The database is on SQL Azure. Everything works on port 9000.My knowledge of SonarQube is limited so it's most likely I'm doing something wrong but can't figure out what.
|
Change port of SonarQube to 80
|
Since SonarQube 5.4, you can restart it directly from the UI (Administrators should be able to request a server restart from web console) or using the WS /api/system/restart (WS /api/system/restart should trigger a true restart of SQ).
|
I implementedSonarQubeon the server, and I do most of the configurationsremotly. Hence whenever a plugin is installed, a restart ofSonarQubeis required and every time I have toexplicitly (manually) restart theSonarQubeserver.Is there a way to restartSonarQuberemotely?For example, likejenkinsthroughhttp://sonar_url/restart.
|
Restart SonarQube Server remotely
|
Thanks to the following sitehttp://www.codewrecks.com/blog/index.php/2009/07/19/integrate-nunit-test-into-a-tfs-build/I was able to convert the output of OpenCover test results to a .trx format using an XSLT transformation. After the transformation I just used the default import functionalitysonar.cs.vstest.reportsPaths=MyTestRestultFile.trx
|
I'm currently changing things to our Sonar setup since Gallio isn't supported anymore by C# Ecosystem 3. I already successfully imported the unit test coverage by using OpenCover with following command."C:\Program Files (x86)\OpenCover\OpenCover.Console.exe" -register -target:"c:\Program Files (x86)\NUnit 2.6.3\bin\nunit-console-x86.exe" -targetargs:"d:\Sonar\MyTest.dll /noshadow /framework=net-4.0" -output:"d:\Deploy\Sonar\Coverage.xml" "-filter:+[*]* -[*]Test"With this command I'm only getting the Unit Test Coverage but I would also like to see the number of failed and successful tests. I think I can achieve this with the /result option like"C:\Program Files (x86)\OpenCover\OpenCover.Console.exe" -register -target:"c:\Program Files (x86)\NUnit 2.6.3\bin\nunit-console-x86.exe" -targetargs:"d:\Deploy\Sonar\MyTest.dll /noshadow /framework=net-4.0 /result=tests.xml"This command returns an xml with information about the tests that ran but is there any way to import this xml into SonarQube? Or isn't this supported?Currently I'm importing the Coverage.xml file with the following command:sonar.cs.opencover.reportsPaths=D:/Deploy/Sonar/Coverage.xmlIs there a similar property to import the tests.xml file with the test results?
|
Is it possible to import OpenCover /result in SonarQube?
|
It's not something that can be configured on the build side. Instead, the "build breaker plugin" has to be configured on the Sonar side. I'm not completely sure if it works with Gradle, but I think it does.
|
How do I configure my Gradle build to fail when there are Sonar violations?I want my Gradle build to fail if there are any are any critical or blocker violations in Sonar, is this functionality supported? If so, is it documented anywhere?
|
Fail Gradle Build for Sonar Violations
|
What does Sonar try to say is that you should avoid hardcoded literals (likenull) in theifcondition.Suppose the following example:Let's say we have thisifstatement, for which Sonar warns withAvoid Literals In If Condition:if (i == 5) {
//do something
}By declaring the hardcoded literal as (final) variable with descriptive names maintainability is enhanced:final int FIVE = 5;
if (i == FIVE) {
//do something
}and Sonar doesn't warn anymore.
|
This part of code is rejected by pmd in sonar:public String getFoo() {
String foo = System.getProperty("foo");
if (foo == null) {
foo = System.getenv("foo");
} else if (foo == null) {
foo = "defaultFoo";
}
return foo;
}It says "Avoid Literals In If Condition". Can someone tell me what's wrong with this or what this rule try to effect?
|
Avoid Literals In If Condition
|
What can you do:Send the component as the prop:IconComponent={AngleIcon}If you need to pass anything to the component on the fly, you can wrap it withuseCallback:const SectionTab = () => {
const IconComponent = useCallback(props => <AngleIcon props={props} />, []);
return (
<Select
id="course_type"
readOnly={true}
IconComponent={IconComponent}
variant="standard"
defaultValue="cr"
disableUnderline
/>
);
};This would generate a stable component, but it's pretty redundant unless you need to pass anything else, and not via theprops. In that case, a new component would be generated every time that external value changes, which would make it unstable again. You can use refs to pass values without generating a new component, but the component's tree won't be re-rendered to reflect the change in the ref.const SectionTab = () => {
const [value, setValue] = useState(0);
const IconComponent = useCallback(
props => <AngleIcon props={props} value={value} />
, []);
return (
<Select
id="course_type"
readOnly={true}
IconComponent={IconComponent}
variant="standard"
defaultValue="cr"
disableUnderline
/>
);
};
|
I am getting the following error during sonarqube scan:Do not define components during render. React will see a new component type on every render and destroy the entire subtree’s DOM nodes and state. Instead, move this component definition out of the parent component “SectionTab” and pass data as props. If you want to allow component creation in props, set allowAsProps option to true.I understand that it says that I should send the component as a prop from the parent, but I don't want to send the icon everytime that I want to use this component, is there another way to get this fixed?import Select from "@mui/material/Select";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faAngleDown } from "@fortawesome/pro-solid-svg-icons/faAngleDown";
const AngleIcon = ({ props }: { props: any }) => {
return (
<FontAwesomeIcon
{...props}
sx={{ marginRight: "10px" }}
icon={faAngleDown}
size="xs"
/>
);
};
const SectionTab = () => {
return (
<Select
id="course_type"
readOnly={true}
IconComponent={(props) => <AngleIcon props={props} />}
variant="standard"
defaultValue="cr"
disableUnderline
/>
);
};
export default SectionTab;
|
SonarQube "Do not define components during render" with MUI/TS but can't send component as prop
|
I also encountered the similar issue while running SonarQube with JaCoCo Code Coverage Reports for Java code:ERROR: Error during SonarQube Scanner execution
java.lang.IllegalStateException: Line [..] is out of range in the file [..]The problem was due to the old code coverage report that was generated before updating the code. It was fixed after generating coverage reports again. So, please also make sure that the any coverage reports that are left behind from the previous run are cleared and new coverage reports are in place.
|
We have a quite large code base, and one of the projects breaks the SonarQube analysis with the following error.016-12-15T11:20:30.8989361Z ##[error]ERROR: Error during SonarQube Scanner execution
2016-12-15T11:20:30.8999277Z ##[error]java.lang.IllegalStateException: Line 1203 is out of range in the file Converters/IMSServiceToESBConverter.cs (lines: 1202)We are using SonarQube 6.1 and the latest C# plugin (5.5.1.522).Disabling all rules in the C# profile still causes this problem.
|
Line 1203 is out of range when scanning C# file
|
The key requirement to obtainnew_code-related information/metrics is to leverageSonarQube SCM integration. And to benefit from that you have to install a compatible SCM Plugin applicable to your project (e.g.Git Plugin,SVN Pluginetc.).
|
I have set up SonarQube, Maven and Cobertura to upload unit test coverage at every build run. I want to use the differential views to get coverage for the delta (new code only).The coverage itself is successfully uploaded, and I can see the delta in lines of code. However, I can't get the "Coverage on new Code" to work.I tried different values for the leak period, includingprevious_analysisandprevious_version(changing the version from 1.0 to 1.1 in the new analysis). I also used-Dsonar.projectDateto simulate a past date of analysis but still no luck.Any thoughts?
|
SonarQube: Coverage on New Code never calculated
|
You cannot use Eclipse SonarQube Plugin with SonarQube 5.2 or newer.FromSonarQube Wiki:The SonarQube Eclipse plugin is deprecatedThe SonarQube Eclipse plugin does not work with SonarQube 5.2+. It is replaced bySonarLint for Eclipse.Note that SonarLint for Eclipse 1.x series do not cover yet all the features of SonarQube Eclipse plugin, but versions 2.x will definitely cover this gap.
|
I updated from SonarQube 5.1.2 to 5.2.In Eclipse I start analysis with SonarQube with the latest plugin version. But a dialog pops up saying there is a NPE. The Eclipse error log displays:java.lang.NullPointerException
at org.sonar.ide.eclipse.wsclient.internal.SonarWSClientFacade.getUnresolvedRemoteIssuesRecursively(SonarWSClientFacade.java:170)
at org.sonar.ide.eclipse.core.internal.remote.RemoteSourceCode.getRemoteIssuesRecursively(RemoteSourceCode.java:107)
at org.sonar.ide.eclipse.core.internal.jobs.SynchronizeAllIssuesJob.doRefreshIssues(SynchronizeAllIssuesJob.java:131)
at org.sonar.ide.eclipse.core.internal.jobs.SynchronizeAllIssuesJob.fetchRemoteIssues(SynchronizeAllIssuesJob.java:120)
at org.sonar.ide.eclipse.core.internal.jobs.SynchronizeAllIssuesJob.run(SynchronizeAllIssuesJob.java:76)
at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55)What is the problem? How can I make analysis in Eclipse work with SonarQube 5.2?
|
NPE when analysing project in Eclipse (SonarQube 5.2)
|
There's no plugin for this, so if you want it, you'll have to develop it.In any case, we've deprecated and removed this metric because we found it was difficult to compute it correctly and therefore to use it correctly. Maybe this could give you a hint on whether you should keep on considering it or not...
|
IsLCOMmetric available withSonarQube 4.2version ?I need this metric to be added in my report, but i don't see its available.Please let me know is there any specific jar to be added to get this metric. This metric was available in Sonar 3.7Any help is appreciated.Thanks,
Sreekanth
|
How to get LCOM(Lack of Cohesion of Methods) metric in SonarQube 4.2?
|
Make the classfinalso it can not be extended. The warning is there to prevent the extended class (potentially) trying to use inexistent resources.
|
Sonar is indicating this error in our Java project. Any suggestion for safe programming is welcome!URL url = getClass().getResource("/myWonderfulResource.txt");
if (url == null) {
throw new IllegalStateException("File not found: /myWonderfulResource.txt");
}
|
Sonar flag "Bad practice": Usage of GetResource in XYZ may be unsafe if class is extended
|
I am fairly sure there are no other mutation testing plugins for sonar.I've not actually tried the pit sonar plugin myself, but I understand the issue with maven 3 can be worked aroundseehttps://groups.google.com/forum/?fromgroups=#!topic/pitusers/bkDD13iBtHUThe PIT maven plugin itself is quite mature and is being used successfully in production. If you encounter issues with the sonar plugin you could just publish the maven reports from your CI server.Please do feedback any issues you hit - I'm sure Alexandre will be kean to fix them.
|
I want to integrate somemutation testingto ensure the quality of my junit tests. I want to have the results in thesonardashboard of my project.Thesonar pitest pluginseems to do what I want, but there are some issues with maven 3 and it is still under development.Has anyone ever tried this plugin ?
Are there others alternatives ?
|
Sonar Pitest Plugin
|
you have to define alert thresholds on the number of blocker/critical violations (>0 is your case) in quality profile and install the build breaker plugin (category "Integration" in Update Center of sonar 2.4).
|
Is there a way to configureSonaror the Sonar Maven plugin to make a build fail when a violation of a certain priority (Blocker, Critical) is detected?
|
Sonar Maven plugin - fail the build on violation
|
List<UUID> insrVrfyIds =
insrVrfyObjsNew.stream().map(CustomerInsrVrfy::getCustomerInsrVrfyId).collect(Collectors.toList());This worked for the above.. That's my bad, it's working by replacing the variable (insrVrfy) with it's class name(CustomerInsrVrfy).
|
List<UUID> insrVrfyIds = insrVrfyObjsNew.stream().map(insrVrfy -> insrVrfy.getCustomerInsrVrfyId()).collect(Collectors.toList());For the following code i am getting a warning as i mentioned in title. Can anyone please explain me how to convert this.here in the above code, i have a list of objects from that i want to extract all the primary keys using lambda expression.But i am getting the violation like "Replace this lambda with a method reference. (sonar.java.source not set. Assuming 8 or greater.)"
|
Replace this lambda with a method reference. (sonar.java.source not set. Assuming 8 or greater.)
|
You've got it mostly right:Maven will use some plugins and communicate with SonarQube serverLoad all the rules that it have in SonarQube server in location we runmvn sonar:sonarAnalyze source code using set of rules we loaded from SonarQube serverCalculate file-level metricsRead coverage reports if anyCompile data into an analysis report and push it back to the SonarQube serverThe server pops the uploaded report from the queue, and integrates it, storing issues and calculating high-level metricsUser sees updated project status on Project homepage
|
I have a question that, how analysis happen in sonarqube. when I do mvn sonar:sonar -Dsonar.host.url=http://sonar.comwhat will happen in background. what I felt is likeMaven will use some plugins and communicate with sonarqube serverLoad all the rules that it have in sonarqube server in location we runmvn sonar:sonarAnalyze source code using set of rules we loaded from sonarqube serverpush it back to SonarQube database and results will be displayed on SonarQube serverIs this is the proper way that it works? or source code will go into sonarqube server and analysis will happen in sonarqube server itself?Thanks for the help
|
How sonarqube works
|
After you install SonarLint for Visual Studio, analysis results (warnings) will automatically show up in the Error Window. You might need to enableTools/Options/Text Editor/C#/Advanced/Enable full solution analysisotherwise only open files will be analyzed.Most of the rules are enabled by default, some of them are not. You can control this through the ruleset file, but when no ruleset file is present, the default rule activation is used. Rule enablement can be changed for each of your projects by right clicking onReferences/Analyzers/Open Active Rule Set. This part is documented on the SonarLint website here:FAQ. (Note that this is not specific to SonarLint though, it's the normal Visual Studio experience.)
|
I have installed SonarLint extension (V 2.8) for Visual Studio 2015.
Can the code be analysed locally WITHOUT connecting to a SonarQube server?Do I need to install something else in order to analyze my code (if i dont have SonarQube)?I dont see the rulesets added to my project. How do I add rulesets? and from where?I checked the SonarLint GitHub page but couldn't find the relevant documentation
|
Running SonarLint VisualStudio plugin without SonarQube
|
Sonar should use the Maven project version by default for this number. So this may actually be the best version number to use. You will need to make sure your maven versions are updated correctly with new releases.If you want to use the Jenkins job number, you can do so by passing it through the mvn sonar command, something like:mvn sonar:sonar -Dsonar.projectVersion=$BUILD_NUMBERWhen using ANT. You can define a property in thebuild.xmlfile like so:<property name="sonar.projectVersion" value="${projectVersion}" />then when running the ant command from Jenkins pass it through:ant -DprojectVersion=$BUILD_NUMBERThis pagehas details
|
I have a jenkins based ant build project which uses the "Invoke Standalone Sonar Analysis" build step to call sonar. The build and the analysis both work fine. However what we really want to do from a reporting perspective is to compare builds in terms or code quality over a range of version numbers.We were thinking of using the Jenkins generated build number as the sonar.projectVersion. Is there a way I can extract that information from Jenkins and use this as my sonar.projectVersion?If that is not possible is there any other sequence number that we can use?
|
How do I populate the sonar.projectVersion in sonar.properties?
|
roslynissues are not found by a Sonar-compatible analyzer (plugin), but by an external tool which imported them. Such rules are not managed by SonarQube which means you cannot change their status. You have to fix the issues or suppress them in the external analyzer tool configuration.From theSonarQube documentation:There are a couple of limitations with importing external issues:you can't manage them within SonarQube; for instance, there is no ability to mark them > False Positive.you can't manage the activation of the rules that raise these issues within SonarQube. > External rules aren't visible on the Rules page or reflected in Quality Profiles.External issues and the rules that raise them must be managed in the configuration of your linter.
|
I cannot change the status of theroslynissues, but I'm able to manage other:My user is allowed to administer issues and security hotspots:project:global:Do you have an idea why I cannot change their status?
|
Why I cannot change status of the SonarQube roslyn issues?
|
I have found solution to the problem. That's why I am adding for other to be helped. We have usedpytestandcoverageto compute the coverage report. SonarQube just read that coverage report.
To exclude some line we have add the following inline comment after that line:# pragma: no coverFor example the lineprint("Hello World")will be excluded from the test coverage report,if __name__=="__main__":
print("Hello World") # pragma: no cover
|
I have some requirement that at least 80% of the line coverage need to be achieved. I have some file where a large portion of the code is underif __name__ == '__main__':which need not to be tested.How can I instruct SonarQube to exclude that portion of code from test coverage. I have seen there are options to exclude files and module usingsonar.exclusionsandsonar.coverage.exclusions. It would be a great help for me to exclude some parts of a file. For example, I want to exclude everything in theif __name__ == '__main__':block below from sonarQube:#Test Everything inside this method
def do_something():
# Some code
# Do not test and include the following codes in the SonarQube coverage
if __name__ == '__main__':
# A lot of codes for running different functions of this module
|
How to exclude codes under `if __name__ == '__main__':` from SonarQube test coverage
|
If you must make SonarQube happy & useInitialContextconsider usingPropertiesSee:https://docs.oracle.com/javase/8/docs/api/java/util/Properties.htmlSo instead of:final Hashtable<String, Object> jndiProperties = new Hashtable<>();Use:final Properties jndiProperties = new Properties();Note from the JavaDocs:Because Properties inherits from Hashtable, the put and putAll methods
can be applied to a Properties object. Their use is strongly
discouraged as they allow the caller to insert entries whose keys or
values are not Strings. The setProperty method should be used instead.
If the store or save method is called on a "compromised" Properties
object that contains a non-String key or value, the call will fail.
Similarly, the call to the propertyNames or list method will fail if
it is called on a "compromised" Properties object that contains a
non-String key.This means that your orginal code example should look like:private Context getInitialContext() throws NamingException {
final Properties jndiProperties = new Properties();
jndiProperties.setProperty(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
// This "new InitialContext()" receives a Hastable, and I can't modify that
// because that is part of a jar
// "javax.naming.InitialContext.InitialContext(Hashtable<?, ?> environment)
// throws NamingException"
context = new InitialContext(jndiProperties);
return context;
}
|
Im having trouble replacing hashtable for hashmap because the method im using receives a hashtable:private Context getInitialContext() throws NamingException {
final Hashtable<String, Object> jndiProperties = new Hashtable<>();
jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
// This "new InitialContext()" receives a Hastable, and I can't modify that
// because that is part of a jar
// "javax.naming.InitialContext.InitialContext(Hashtable<?, ?> environment)
// throws NamingException"
context = new InitialContext(jndiProperties);
return context;
}InitialContext method:public InitialContext(Hashtable<?,?> environment)
throws NamingException
{
if (environment != null) {
environment = (Hashtable)environment.clone();
}
init(environment);
}What can I do to solve this codesmell??
|
Sonar: Replace the synchronized class "Hashtable" by an unsynchronized one such as "HashMap"
|
Thesonar-custom-rules-examplesyou pointed at are all written in Java and use parsers written in Java for the various target languages.
Thesonar-dotnetanalyzers for C# and VB.NET are written in C# using theRoslyn frameworkprovided by Microsoft.If you want to write your own custom rules for C# then writing a Roslyn analyzer is definitely the easiest way to do it (Roslyn replaced FxCop, which is now obsolete). However, there are dozens of free third-party Roslyn analyzers available, so it's possible that someone has already written at least some of the rules you want. Have a look onNuGetto see what's available.Next, you want issues raised by a Roslyn analyzer to appear in SonarQube. If you are using new-ish versions of SonarQube (v7.4+), the SonarScanner for MSBuild (v4.4+) and the SonarC# plugin (v7.6+), then issues raised by third-party Roslyn analyzers will automatically be imported asgeneric issues. See thedocsfor more info.Generic issues have a couple of significant limitations, just as not being able to select which rules to run in the SonarQube UI. If you want a more full-featured experience (or if you are using an older version of SonarQube), you can use theSonarQube Roslyn SDKto generate a custom SonarQube plugin that wraps the Roslyn analyzer. Using the SDK is straightforward: it's an exe that you run against the Roslyn analyzer, and it generates a SonarQube plugin jar for you.
|
I've been doing some research on it.
What I found is a list of quite nice samples but forotherlanguageshere.I also looked atsonar-dotnet. But it doesn't look similar to the other implementations.Finally, and to be honest probably my last chance, I took a quick look atFxCop Custom Rulesand I'm not sure what would be the right way.What I'm trying to do is just a basic c# rule that can be reviewed likethis predefined by sonar.I mean, withNoncompliant CodeandCompliant Solution.
|
How can I create my own C# custom rules for SonarQube?
|
You have to use the/d:property=foosyntax. For example,/d:sonar.host.url=http://urlToYourServer.comor/d:"sonar.host.url=http://urlToYourServer.com"I have updated thedocumentation of the Scanner for MSBuildso it will be easier for the next person.Thanks for raising this!
|
From searching online and looking at sonarqube docs the only thing that I can find is:SonarQube.Scanner.MSBuild.exe /k:KeyOfProject /n:NameOfProject
msbuild.exe C:\projectpath\soultion.sln
SonarQube.Scanner.MSBuild.exe endThe problem is there's no switches that i've found to set things like:analysis mode (preview, publish, increment/issues to set if sqube reports the project to server)how to make sonarqube comment on issues and code in GitlabThe ONLY thing i can think of is by passing properties in the SonarQube.Analysis.xml but the syntax isn't clear for the sonar. properties.<Property Name="sonar.host.url">http://urlToYourServer.com</Property>is a given, but everything is highly speculative. Does anyone actually know what they're doing? The documentation online just plain sucks.Sources I've checked out :https://github.com/SonarSource/sonar-scanning-examples/tree/master/sonarqube-scanner-msbuild/CSharpProjecthttps://docs.sonarqube.org/display/SONAR/Analysis+Parametershttps://docs.gitlab.com/ee/ci/variables/
|
How do i give parameters to SonarQube.Scanner.MSBuild.exe?
|
If you're building your project withGradle, you can use the propertysonar.scm.disabled.For example, set it in yourbuild.gradle:// Let SonarQube analyze the project
sonarqube {
properties {
property "sonar.projectKey", "YourProjectId"
property "sonar.projectName", "Your Project"
property "sonar.sourceEncoding", "UTF-8"
// For SVN projects, SonarQube would run "svn blame" to know
// who changed which parts of the code. Without authorization
// this fails, so we disable it
property "sonar.scm.disabled", "True"
// Address of the SonarQube server
property "sonar.host.url", "localhost:9000"
}
}You can also pass the property via the command line to Gradle:./gradlew sonarqube -Dsonar.scm.disabled=True
|
It seems that addingsonar.scm.disabled=trueto the conf doesn't not work. The sonar-scanner will report the following error:ERROR: Error during SonarQube Scanner execution
java.lang.IllegalStateException: Error when executing blame for file
betamao/betamao/admin.py at
org.sonar.plugins.scm.svn.SvnBlameCommand.blame(SvnBlameCommand.java:86)
at
org.sonar.plugins.scm.svn.SvnBlameCommand.blame(SvnBlameCommand.java:59)
at org.sonar.batch.scm.ScmSensor.execute(ScmSensor.java:86) at
org.sonar.batch.sensor.SensorWrapper.analyse(SensorWrapper.java:57)
at
org.sonar.batch.phases.SensorsExecutor.executeSensor(SensorsExecutor.java:58)
...I still have to disable SCM in "General Settings > SCM" administration page to make it work.Is this a bug?My environment is:sonar-scanner 3.0.3.778 with openjdk8-u131sonarqube-5.6.6lts with openjdk8-u131
|
Disabling SCM in sonar.properties doesn't work
|
The latest version of SonarLint only supports SonarQube 5.6+ (5.6 is the current LTS version).Apart of that, you might also be facing a problem with server SSL certificates. SonarLint will try to validate the server's SSL certificate using the JVM's truststore. So if your SonarQube server uses an SSL certificate, you might need to install the CA certificate in the trustore of the JVM used by IntelliJ.Due to a limitation in SonarLint, certificates configured within IntelliJ aren't supported by SonarLint:https://jira.sonarsource.com/browse/SLI-75
|
I am trying to integrate sonarqube(version 5.1.2) with intellij(2016.2). I have added sonarLint plugin.
when I am trying to add a sonar server to the sonarLint settings it asks for username and password for sonar server and other details like url.
But it somehow is unable to connect to the sonar server and gives error :
Fail to request :https://example.com/api/system/status
|
unable to connect to Sonarqube via intellij (SonarLint)
|
Unless you want to surround the methods withmarker comments and use exclusions, the answer is no.
|
Is there a way to exclude specific methods in classes when analyzing with sonarqube? All I find is how to exclude files and modules.
|
Exclude methods in Sonarqube
|
You must define project permissions for the scanned project with only that user and admin having the permission to "Browse" the project.
If you need to do that repeatedly you may use permission templates.
Seehttp://docs.sonarqube.org/display/SONAR/Authorization#Authorization-ProjectPermissions.
|
I want that when a project is scanned and it's scan result is created only Admin and a specific user can see that project in dashboard and all other places and only he can access that project. Also I want to send email to that user when project was scanned.I know I can assign role to user and set permissions for it by going to that project, but should I have follow all these steps for this? Can't I just select a user from UI so that only that selected user can view that project?
|
How to Assign a project to specific user only in SonarQube?
|
I managed to achieve this by doing the following.To get javascript junit reports into sonarfind and downloadsonar-karma-test-report-plugin-1.0.0.4.jarwhich is not available via the update centerput jar file in/usr/local/Cellar/sonar/5.3/libexec/extensions/pluginsand restart sonarTell karma to omit the name of the browserjunitReporter: {
useBrowserName: false
}Get Karma to create a junit xml file via the normal karma-junit-reporter and have it call the fileTESTS-xunit.xml(I had the file calledtest-results.xmland sonar would not detect it WTF)In thesonar-project.propertiesfile setsonar.javascript.karmajstestdriver.reportsPath=reports/js/unit-components/results/callsonar-runnerSonar requires the path to the test file in order to process the report. Jasmine does not make this available to the reporter. My understanding is the sonar plugin iterates over xml file and finds the classname for each test which has the test name (iemy cool tests) and does a string replace to change that to the location of the file
|
Is there a karma reporter which can be used to generate aresults.xmlfile which is compatible with the sonar Generic Test Coverage plugin? Or alternatively a parser for the junit file which is output bykarma-junit-reporterand which will work with the generic plugin?I am using SonarQube 5.3 and Karma / JasmineI want to import the junit reports that come from karma into SonarQube but cannot see a way to do this easily. Something likehttps://www.npmjs.com/package/mocha-sonar-generic-test-coveragefor karmaFYI I have seenkarma-junit-sonarqube-reporter(https://www.npmjs.com/package/karma-junit-sonarqube-reporter) but that seems to expect the name of the test to match the path to the file which is too restrictive for me.karma-sonarqube-unit-reporterseems to be unfinishedgrunt-karma-sonarseems to rely onjstestdriverwhich is deprecated
|
How to get karma javascript junit xml reports into sonar
|
Remove the TODO,stop using themfor anything that's not short term (for the length of a ticket or fork) and move them into tickets on your ticket tracking system.TODO comments have multiple problems:-they can be hard to find if you are using an IDE which doesn't auto locate them. (I know Devs who use sublime or even Emacs so a specific search would be needed)whose job is it to find and fix these?how is time spend on them tracked?they can get out of date, like most comments. If someone fixes the problem without reading the TODO and leaves it there, it causes confusion. If another fix inadvertently fixes it, the comment is unknowingly left there.You now have two issue tracking systems, one of internal documentation and one in whatever issue tracking system you use.If you are writing TODOs then you are the very person with the knowledge to fix it. Someone coming along later will have to fix it based on a very short comment without description.There's nothing more irritating than a piece of code by a developer who was too lazy to do a good job, so left it for the next guyor one who wasn't lazy but was too scared to break something and just ended up making the problem more complex with minimal comments suggesting there's a problem
|
We have an application which is big and we have added the TODO rule to the quality gates which gives error if TODO comments are found.
If we just removing the TODO comment (which is scary) it works but the whol purpose of adding TODO comment is lost. Is there still a way to keep the TODO comment by adding anything extra which way we can defer the TODO task ?(which is giant task for example) .
|
How to handle TODO comments when sonar error is encountered
|
You have configured SonarQube to use an external system to manage security, in this particular case Active Directory. So the default (and expected) behaviour is to delegateboththe authentication and the authorizations to this system.In your example, if you want the user to belong to some specific group, you have to configure this in your Active Directory. Next time the user logs in, he will be associated to this(those) group(s).Note that the groups must exist in SonarQube otherwise this won't work (i.e. you have to manually add them in the "Security > Groups" ).
|
I have installed SonarQube 5.2 and the LDAP plugin 1.5 a few hours ago. I am really happy about the easy configuration of the LDAP plugin in an Active Directory domain.But I experience something which looks like a huge problem.1) An AD user loads the web page of the SonarQube instance[behind the scenes] a user is being created (starting up from the headers of the HTTP request and the information present in the Active Directory)2) An administrator of the platform (e.g. admin, default administrator of the platform) gives her some rights (e.g. add her to the sonar-administrators group)the web interface shows an updated set of rights for this user3) The user starts a new session!!!The user has lost all of its rights. She doesn't belong anymore to the sonar-administrators group(expected behavior)the user gets an updated interface, with the menus reserved to the sonar-administrators groupAm I missing some important part of the documentation?
|
Sonarqube 5.2, LDAP plugin 1.5: users losing privileges at their next login?
|
This is the propertysonar.projectVersionthat control the version number of your project.But indeed if your are using the SonarQube Maven plugin to do your analysis (mvn sonar:sonar) then this property is automatically set using version declared in your pom.xml.
|
SonarQube has a "since previous version" filter. How does Sonar determine version number? I have a Maven project with version numbers in a pom file - is Sonar smart enough to interrogate this?
|
SonarQube - how is version determined?
|
squid:S1451 "Copyright and license headers should be defined"has two parameters:headerFormatisRegularExpressionInheaderFormatyou define expected text. If you setisRegularExpressionto true, then the text will be treated as regular expression.If you use normal text, then you need to put full license, e.g.:/*
* Maven Plugin Utils
* http://www.gabrys.biz/projects/maven-plugin-utils/
*
* Copyright (c) 2015 Adam Gabryś
*
* This file is licensed under the BSD 3-Clause (the "License").
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* https://raw.githubusercontent.com/gabrysbiz/maven-plugin-utils/master/src/main/resources/license.txt
*/If you use regular expression, then you can omit some parts, e.g.:^\/\*.+www\.gabrys\.biz\/projects\/.+Copyright \(c\) [0-9]{4}.+This file is licensed under the.+\(the "License"\)\..+You may not use this file except in compliance with the License\..+You may obtain a copy of the License at:.+$
|
All of my SonarQube code analysis Java projects are failing on this rule.Each source file should start with a header stating file ownership and the license which must be used to distribute the application.
This rule must be fed with the header text that is expected at the beginning of every file.There is one parameter:headerFormat Expected copyright and license header (plain text)But there are no examples of how this should be configured. By default headerFormat is empty and I cannot find documentation on configuring this rule.I'm guessing there should be some kind of regular expression or template language that can be used?
|
SonarQube Rules squid:S1451 Copyright and license headers should be defined
|
I found the problem and the solution.From Sonar website I see this:By default, when no coverage report is found, the JaCoCo plugin will
not set any value for coverage metric. This behaviour can be
overriden to force coverage to 0% in case of a lack of report by
setting the following property :sonar.jacoco.reportMissing.force.zero=trueThis means that UT analysis was skipped for modules without any tests.
Since I've set thesonar.jacoco.itReportPathfrom parent pom thenallmodules got analyzed for integration tests coverage, andoverallcoverage.Bottom line: setting the propertysonar.jacoco.reportMissing.force.zero=truefrom parent pom fixed the numbers.
|
I'm running Jacoco and Sonar on multimodule Java8 project.
I have unit tests in each of the modules and to save resources I collect all 'integration tests' into one "integration-tests-runner" and run them all there (wrapping them with before and after tests).When measuring coverage UT generates exec file per module target/jacoco-ut.exec, while the IT generates one exec file: /target/jacoco-it.exec.When I run sonar I reuse those exec files, giving path to the jacoco-it.exec.I get a very weird image:How can it be thatoverallcoverage is lower?
|
Sonar false overall coverage (jacoco)
|
You can find examples in the Community plugins for SonarQube project.For instance, the Sonar Artifact Size Plugin defines some additional metrics. You can see the code inhttps://github.com/SonarQubeCommunity/sonar-artifact-size/tree/master/src/main/java/org/sonar/plugins/artifactsize
|
I am creating a plugin for Sonar and I need to create a custom metric since there are no core metrics within Sonar API that fulfill my needs.I need to be able to display this metric on the dashboard.Any help is greatly appreciated!
|
How to create a custom metric using Sonar API
|
We have made comparisons and benchmarks at Snyk.
The short answer is simple:Sonarqube is focused on Code Quality and is fairly good at that. But the security scan is an add on and very limited (in language supported, in rule coverage, amount of false positive) and rarely considered as a SAST toolSnyk does not support quality (just some rules in IDE) but heavily focused on security. With fast scans, accuracy, depth in the number of CVEs covered for SAST and wide language coverage. Plus, Snyk has a strong SCA support.
Hope that helps.I personally ran a comparison on this repo:https://github.com/OWASP-Benchmark/BenchmarkJavaand the results are clear.
Hope that helps.
|
I need to do a comparison between the features and functionality of Snyk and Sonarcloud/Sonarqube and the only thing I can find is a speed comparison:https://snyk.io/blog/sast-tools-speed-comparison-snyk-code-sonarqube-lgtm/....does anyone know if there are any comparison of features and functionality between two? If so, please can you let me know where to look?thanks very much in advance for any help with this.
|
Comparison between Snyk and Sonarcloud/SonarQube?
|
+100You can use the officialSonarJS pluginfrom SonarSource. In the latest 4.2 version it supports import of ESLint issues, seedocumentation here.It will allow to track your technical debt, you can also import your test coverage, etc. There is also SaaS offering onhttps://sonarcloud.io
|
We're using ESLint in our company in order to detect errors, that break the build and block the deploy, but we also have some other rules which trigger some warnings in our console.We want to see those warnings in a timeline, so we'll be able to check if we are improving our tech debts or not.I triedSonarEsLintPluginin SonarQube but it does not work properly in version 7+Anyone knows other way to have ESLint timeline snapshots?
|
Static analysis using ESLint with snapshot
|
It seems that the tagsecureis not working, use a repo variable instead:language: java
sudo: false
install: true
addons:
sonarcloud:
organization: "ron190-github"
jdk:
- oraclejdk8
script:
# JaCoCo is used to have code coverage, the agent has to be activated
- mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent package sonar:sonar -Dsonar.login=${SONAR_TOKEN}
cache:
directories:
- '$HOME/.m2/repository'
- '$HOME/.sonar/cache'
|
I'm followingGet startedinstructions on sonarcloud.io to execute the SonarQube Scanner for Maven from my computer:mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent package sonar:sonar \
-Dsonar.host.url=https://sonarcloud.io \
-Dsonar.organization=ron190-github \
-Dsonar.login=9...eManual execution is working:[INFO] ANALYSIS SUCCESSFUL, you can browse https://sonarcloud.io/dashboard/index
/jsql-injection:jsql-injectionBut when I'm ready to automate with Travis CI it's failing withNot authorized. Please check the properties sonar.login and sonar.password.:[ERROR] Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.4.0.905:sonar (default-cli) on project jsql-injection: Not authorized. Please check the properties sonar.login and sonar.password. -> [Help 1]And if I addsonar.loginto themvncommand then it's working:language: java
sudo: false
install: true
addons:
sonarcloud:
organization: "ron190-github"
token:
secure: "v...s="
jdk:
- oraclejdk8
script:
# JaCoCo is used to have code coverage, the agent has to be activated
# Not working
# - mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent package sonar:sonar
- mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent package sonar:sonar -Dsonar.login=9...e
cache:
directories:
- '$HOME/.m2/repository'
- '$HOME/.sonar/cache'I have also used theexample script.Do you know whysecuretoken is ignored and why it's failing with default config?
|
Error using Travis CI with Sonarcloud: Not authorized. Please check the properties sonar.login and sonar.password
|
Yeah, looks like a Bug . Seems this got recently addressed in SonarJava 5.0 (compatible with SonarQube 6.7+) which got released last Decemberhttps://jira.sonarsource.com/browse/SONARJAVA-2115
|
I got some trouble with asonarissue:Remove this unused method parameter "messageId".well my method looks like:private static Optional<Status> getStatus(Member member, String messageId) {
return Optional.ofNullable(member)
.map(Member::getTraffic)
.map(Traffic::getSymlinks)
.map(messages -> messages
.stream()
.filter(message -> message.getMessageId().equals(messageId))
.findFirst()).flatMap(message -> message.map(Message::getStatus));
}themessageIdis used inside theequalsof the filter.
It is no field. It is the method parameter.Is that asonarbug or have I overlooked something?
We are using Sonar 5.6
|
Remove this unused method parameter in Sonar
|
I believe that this is kludgy and that your original code is better, but this will eliminate the SonarQube complaint. Initialize your map in a @Bean, then reference that as @Autowired. Load the map with data in the @PostConstruct.@Bean
public Map<Object, Object> getMapLoadedByDatabaseCalls() {
return new HashMap<>(Object.class);
}
@Autowired
private Map<Object, Object> mapLoadedByDatabaseCalls;
@PostConstruct
private void setMap() {
...
// load data into the map
mapLoadedByDatabaseCalls.put(key, value);
....
}
|
I am running into an issue with my Spring Applications and SonarQube. SQ is flagging both examples with "Annotate this member with "@Autowired", "@Resource", "@Inject", or "@Value", or remove it." on the instance variable mapLoadedByDatabaseCallsExample 1:@Service
public class Service implements InitializingBean {
@Autowired
private Dao dao;
private Map<Object, Object> mapLoadedByDatabaseCalls;
@Override
public void afterPropertiesSet() throws Exception {
mapLoadedByDatabaseCalls= new HashMap<>(Object.class);
....
}
}Example 2:@Service
public class Service {
@Autowired
private Dao dao;
private Map<Object, Object> mapLoadedByDatabaseCalls;
@PostConstruct
private void setMap() {
mapLoadedByDatabaseCalls= new HashMap<>(Object.class);
....
}
}What is the correct way to instantiate variables after DI has completed?
|
Spring App SonarQube Issue S3749
|
You can edit:C:\Users\HOME_FOLDER\.jenkins\tools\hudson.plugins.sonar.SonarRunnerInstallation\SonarQubeScanner\bin>notepad sonar-scanner.batand put following:SET JAVA_HOME=< JDK Path>
|
I am trying to set up the Sonarqube for my project, but when I start to generate a build, I get the following error:ERROR: JAVA_HOME exists but does not point to a valid Java home
folder. No "\bin\java.exe" file can be found there.
The SonarQube Scanner did not complete successfullyI check some docs but none of them helps. For the JAVA_HOME environment variable, I point it to beC:\Program Files (x86)\Java\jdk1.8.0_111I also double check it by using powershelljava -versioncommand. It also gives me the same answer:java version "1.8.0_111". Anyone knows how to solve the problem?Thanks.
|
Jenkins Sonarqube Plugin: JAVA_HOME exists but does not point to a valid Java home
|
As previously responded, you should fill thesonar.java.binariesproperty in order to allow bytecode analysis and symbol resolution. Having this property filled, the analysis would not raise any issue on that case.Now, it is indeed annoying that we raise an issue when we can not resolve the symbol type of a field. I created the following ticket to handle the issue:SONARJAVA-1266
|
It might look like duplicate question, but i have posted the code sample suggested by sonar rule Compliant one. When evaluating the below highlighted code with SonarQube it results in squid:S1948 rule violation.Result,Still its a mystery that why its showing violation for compliant code, plz clarify.UPDATEtransient or serializable issue not resolved even withsonar.java.binariesSonar Scan is success but throws class loader warn:08:26:44.984 INFO - Java bytecode scan...
08:26:44.992 WARN - Class 'dummyserial/Address' is not accessible through the C
lassLoader.
08:26:44.993 WARN - Class 'dummyserial/Person' is not accessible through the Cl
assLoader.
08:26:44.993 WARN - Class 'dummyserial/Address' is not accessible through the C
lassLoader.
08:26:44.994 WARN - Class 'dummyserial/Person' is not accessible through the Cl
assLoader.
08:26:44.994 WARN - Class 'dummyserial/Address' is not accessible through the C
lassLoader.
08:26:44.997 WARN - Class 'dummyserial/Person' is not accessible through the Cl
assLoader.
08:26:44.998 INFO - Java bytecode scan done: 14 ms
|
SonarQube - Rule Fields in a "Serializable" class should either be transient or serializable
|
SonarQube needs to talk to the database in order to save the results (metrics) of the analysis.I will not talk about all the different possibilities that you can implement in order to avoid SonarQube's users to know the admin login, but here is the one I use:SonarQube + RunnerJenkins with Sonar pluginThis post (on my blog) is 1 year oldhttp://qualilogy.com/en/install-sonarqube-the-sonarqub-jenkins-plugin/) but it will give you an idea.You already have SonarQube + Runner installed.Install JenkinsInstall SonarQube plugin for JenkinsConfigure the plugin:Location of RunnerSonarQube dashboard URLConnection to the DB : password is encrypted.Then, when configuring and running an analysis from Jenkins, no need to use any DB login as a parameter.Hope it helps.
|
In the similar questionSonar-Runner talks to the local database"David RACODON - SonarSource" wrote:The SonarQube Runner needs to talk to both the database and the web server.I'm will try to understand why Sonar Runner talks do sonar database, because somebody who use sonar runner will known database user and password and do anything on it, for example change admin password and take control on Sonar instance.On the other hand, at sonar runner docs (http://docs.sonarqube.org/display/SONAR/Installing+and+Configuring+SonarQube+Runner) I see info:The SonarQube Runner is recommended as the default launcher to analyze a project with SonarQube.So, it means that I should give database password to each developer of my team? This is inconsistent. Could somebody explain it?
|
Why Sonar-Runner talks to the local database?
|
Explanation from aSonarSource team member:In a multi-module build an aggregator plugin can't resolve dependencies from target folder. So you have two options:mvn clean install&&mvn sonar:sonaras two separate processesmvn clean package sonar:sonaras a single reactorI was surprised too, so I made atweetan received the followinganswer from the official Maven account:If the plugin is not designed to use the target/classes folder as a substitute, then yes you would need to have installed to get the jar when running *in a different session*.Complain to the plugin author if they force you to use install without foo reason[ed -@connolly_s]
|
official documentationhttp://docs.sonarqube.org/display/SONAR/Analyzing+with+Mavensays that the proper way of invoking sonar is:mvn clean install -DskipTests=true
mvn sonar:sonarbut doesn't say why. how does sonar work? does it need compiled classes? so why not justmvn clean compile? or does it need a jar file? so why not justmvn clean package? what exactly does sonar plugin?
|
why sonar:sonar needs mvn install before?
|
Sonar has no built-on cron, nor any connector to SCM tools to retrieve source code. So retrieving sources and triggering an analysis is out of its scope: this is the responsibility of other tools like CI servers (Jenkins / Hudson / Team City / Bamboo / ...).
|
I have my source repository hosted in GitHub. I now want my Sonar instance (deployed on Amazon EC2) to pull from the git repository periodically to analyze the codebase. The project is a simple JavaScript project, I do not want ANT, Maven or Jenkins to be involved, but just Sonar to pull code periodically.Is this possible?
|
Can Sonar pull code from my git repository and analyze periodically?
|
You can pass parameters to the SonarScanner for MSBuild either on the command line or in theSonarQube.Analysis.xmlXML settings file as described in thedocs.
|
I have a simple C# Hello World project which I am trying to do Code Quality analysis with SonarQube.dotnet C:\git\itergo\sonar\sonar-scanner-msbuild-4.7.1.2311-netcoreapp2.0\SonarScanner.MSBuild.dll endthrows an error.sonar-project.properties files are not understood by the SonarScanner for MSBuild. Remove those files from the following folders: C:\git\sonar_test\samples\core\console-apps\HelloMsBuild
09:24:17.089 Post-processing failed. Exit code: 1
|
Sonarqube.project.properties file not allowed
|
This is a SonarQube bug, it doesn't handle SpringBootApplication properly. You should report it here :https://community.sonarsource.com/c/bug
|
'ABCService' is not reachable by @ComponentsScan or @SpringBootApplication. Either move it to a package configured in @ComponentsScan or update your @ComponentsScan configuration.This the error message I get in 9 critical bugs in Sonarqube analysis, one for each Service and Controller.Though @Autowire and dependency injection is working fine but still Sonar seems to be complaining.The rule in question causing the issue is:Spring beans should be considered by "@ComponentScan"Spring beans belonging to packages that are not included in a
@ComponentScan configuration will not be accessible in the Spring
Application Context. Therefore, it's likely to be a configuration
mistake that will be detected by this rule. Note: the @ComponentScan
is implicit in the @SpringBootApplication annotation, case in which
Spring Boot will auto scan for components in the package containing
the Spring Boot main class and its sub-packages.Since @SpringBootApplication is has component scan which scans main class package and all it's sub packages as well this issue shouldn't come.
|
Spring boot configuration issues with sonar
|
in case it helps, I was having the same issue. Thisissue reporthelped me.To summarize, this problem can be due to one or more of the following factors:Sonarqube's analysis mode needs to be set to preview (-Dsonar.analysis.mode=preview) otherwise it seems it won't attempt to connect to GitHub; it will store the results in the SonarQube database.If the issues found in your code as a result of the scan have already been saved to the SonarQube's database, it won't send them to GitHub, in other words, there need to be new issues when you run it in preview mode for them to be sent to GitHub.An obvious one, but always good to double check, make sure your oauth credentails are correct and the parameters named correctly.Double check the properties "Plugins accepted for Preview mode" and "Plugins excluded for Preview mode" in SonarQube Admin settings (General section) to ensure the Github plugin hasn't been excluded.There might be more, but hopefully this will help. The ones that were getting me were number 1 and 2.
|
I'm trying to set upSonarQubeto comment on my GitHub pull requests after a successful Travis build.I've already have normal analysis working. For the pull request analysis I also have all tokens in place, plugins installed, etc. Issues in the pull request are successfully identified: the debug log shows successful HTTP requests where the server responds with the relevant issues. Some lines of the log:15:06:10.194 INFO: ANALYSIS SUCCESSFUL
15:06:10.197 DEBUG: Post-jobs : GitHub Pull Request Issue Publisher (wrapped)
15:06:10.197 INFO: Executing post-job GitHub Pull Request Issue Publisher (wrapped)On GitHub I can see that the oauth token used by sonar is actually being used.When adding commits to a pull request, there even is a status for sonarqube: when a new commit is added, for a short while it is waiting for a response, then it changes to"SonarQube reported no issues". Note that this status appears before the sonar scanner has ran on Travis.Does anyone know what could be the problem or what I could do to debug this any further? Thanks in advance!
|
SonarQube doesn't comment on GitHub pull requests
|
Duplications are marked by a yellow-orange bar in the left margin. Click it to see details:
|
In sonarqube 5.6.4, how do I view the duplicate code blocks? In 4.5, there was a mostly hidden UI element under the duplication metric. Now it does nothing.Since the issue is attached to a top of the file, how can I tell what I need to fix?
|
viewing sonarqube duplicate code
|
Try to put the exclusions in the project file (.csproj) itself, something like:<ItemGroup>
<SonarQubeSetting Include="sonar.exclusions">
<Value>**/Migrations/*</Value>
</SonarQubeSetting>
</ItemGroup>SeeAppendix 2: Configuring the SonarQube Scanner for MSBuild.
|
We are using the SonarQube Scanner for MSBuild (1.1.0.0) and have a solution containing multiple projects.There is aSonarQube.Analysis.xmlin the solution root folder which we supply to the scanners cli.<SonarQubeAnalysisProperties xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.sonarsource.com/msbuild/integration/2015/1">
<Property Name="sonar.cs.opencover.reportsPaths">output/nunit-coverage.xml</Property>
<Property Name="sonar.cs.nunit.reportsPaths">output/nunit-result.xml</Property>
<Property Name="sonar.exclusions">Project1/Migrations/*</Property>
<Property Name="sonar.coverage.exclusions">Project1/Migrations/*</Property>
</SonarQubeAnalysisProperties>Now the problem is:Project1/Migrations/*seems not to get excluded because theBase diris set to.../Project1during the scan. The same happens for all other projects in the solution. The result is that.../Project1/Project1/Migrations/*is an unknown path.So what is the recommended way to exclude a whole directory from coverage and sourcecode analytics when using MSBuild Scanner?
|
How to exclude single files when using MSBuild Scanner
|
I guess 255 is your alpha channel, in that case I guess you wanted255 << 24.SonarQube doesn't know your intentions, but it has a valid point, as Toby stated.As for readability, you can also try hexa code (e.g.0xFF5B9BD5), many devs are used to that already. Of course, a decimal number would be totally unreadable and ugly.
|
I have written:public static final int MY_GREAT_COLOR = (91 << 16) + (155 << 8) + 213 + (255 << 32);And sonar says:New: Squid:S2183 Severity: CRITICAL, Message: Remove this useless shiftCould anybody tell me why? Is that only the fact that there should be no calculations on literals, even if it adds to readability?
|
SonarQube Java Analyser, rule S2183, why should I remove this useless shift?
|
The rules are defined in the sonar server as a set of configurations for pmd, findbugs, checkstyle etc.You have to reference a configuration in your pom file (see the sonardocumentation/wiki).the property issonar.profileBut basically you will assign the profile for the project in the sonar server configuration.
(see Profiles Section in theWiki). Profiles will also allow you to move rule configurations between environments, e.g. between development and production.
|
With maven-pmd-plugin, I am able to configure it to scan my unit tests for PMD violations:<configuration><rulesets><ruleset>/rulesets/junit.xml</ruleset></rulesets>Sonar 2.0.1 doesn't seem to provide any way to add in new rulesets that I can see. Has anyone figured out how to do this?
|
How can Sonar be configured to import new rulesets?
|
I did a lot of things to finally managed to get the coverage working but I think that the problem was the "ProjectGUID" missing in each .csproj of my solution making the projects ignored by SonarQube scanner.I also upgraded from SonarQube 6.2 to 8.1 at the same time which may have solved the problem.My steps remained unchanged to make this work.
|
Good morning,Sorry to bother you, I have a problem and I have no leads.I have a pipeline on Azure DevOps where I use coverlet to generate a code coverage report when I use the command "dotnet test".Indeed, the report is well generated.At first, in the "Prepare analysis on SonarQube" step, I set the variable "sonar.cs.opencover.reportsPaths="$(Agent.TempDirectory)/coverage.opencover.xml".And yet the end in my SonarQube there is 0% code coverage... I don't know what to do or any leads...Thanks
|
Azure Devops + Coverlet + SonarQube shows 0%
|
Send data asapplication/x-www-form-urlencodedor form-data.
SonarQube Web API doesn't handle POST body in raw JSON format. See thisquestionabout Java ServletRequest to know more (Tomcat is used under the hood).
|
I'm migrating SonarQube from 5.6 version to 6.7. I'm using SonarQube API with my Jenkins jobs and the problem is the API for groups permissions isn't working with 6.7 version...I've tried manually with Postman (POST raw JSON) this :{
"groupName": "project-name-admin",
"permission": "admin",
"projectKey": "project-name"
}The result returned is :{
"errors": [
{
"msg": "Group name or group id must be provided"
}
]
}And it's the same if I use :{
"groupId": 53,
"permission": "admin",
"projectKey": "project-name"
}or{
"groupId": 53,
"groupName": "project-name-admin",
"permission": "admin",
"projectKey": "project-name"
}It's working with 6.5 verison and I've no idea where this problem may come from :(@SonarQube developers team : can you fix thaaaat please ?
|
SonarQube 6.7 LTS group permissions API doesn't working
|
I connected to sonarqube DB and I executed this query to retrieve the "in progress" jobselect * from ce_queue where status<>'PENDING';Then I deleted the recorddelete from ce_queue where id=2325;
|
I am trying to kill a background task that is in progress in m sonarqube.This task is doing a scan on a project.
|
How to cancel a Task in SonarQube that is In Progress?
|
This is how we solved this issue (90% solution):Replaced all deprecated Checkstyle/PMD/FindBugs rules with recommended squid rules. -> This left over 80 Checkstyle, 16 PMD and 0 FindBugs rules (and 60 squid rule), eliminating FindBugs.Use SonarLint + Checkstyle plugins in Eclipse. For Checkstyle, we export the rules XML from SonarQube, put them in our version control and configure Checkstyle plugin to use that.Ignore PMD in Eclipse and use direct browser access to SonarQube to see PMD rule violations in code reviews. This saves us from installing/confguring PMD for "only 16 rules".The solution makes about 90% of our rules visible in Eclipse. The price we pay:Install & configure 2 plugins for rules checking instead of 1.Manually keep Checkstyle rules XML up to date whenever SonarQube updates lead to changes.squid rule violations only visible for opened classes, and in a separate "SonarLint On-the-fly" view.Only 90% of rules visible directly in Eclipse.We would be very happy if one day SonarLint would displayallSonarQube rules violations in Eclipse's standard "Problems" view, covering workspace and selection scopes. Then we would only need a single Eclipse plugin and SonarQube would be the only rules repository.
|
If I work with Eclipse and want to use SonarQube as single source of code rules, I understand I need to use the SonarLint plugin. However, SonarLint will only check squid rules, no Checkstyle/PMD/Findbugs rules (although they can be used in SonarQube).My question: If a project has been using a Checkstyle/PMD/Findbugs rule set, how should these rules be handled so that they can also be seen by the Eclipse developers?Please consider these points:I don't want to manually export rules from SonarQube and install Eclipse plugins for Checkstyle/PMD/Findbugs and configure them with the exported rules. That's too cumbersome.I see that some Checkstyle/PMD/Findbugs are marked as deprecated and there are squid-replacements. Thats ok. But what do I do with all the rules that are not deprecated?
|
Eclipse / SonarQube Integration: How to handle Checkstyle / PMD / FindBugs
|
Hidden folders are explicitly filtered out from the analysis. This is hardcoded in the SonarQube scanner. This is precisely to not spend time trying to analyze technical locations that are not part of source code (.git, .svn, ...). I think most IDEs are not showing hidden files, so this seem consistent.
|
I'm trying to run SonarQube 4.5.4 on a project. Files and metrics are found for each folder except for the hidden ones (the ones like .m2, .something). Sadly those folders are the one that I am more interested in.Is someone else experiencing the same problem? Are those folders filtered out by some default property?
|
How to scan hidden folder such as ".nameFolder" in SonarQube?
|
Short answer is NORefer:Reduce log level in Sonar 2.1.xBut other than this if you see logging of other sonar plugins you might, may have log level set to WARN.
|
Is it possible to change the default logging level of a sonar runner from INFO to WARN or similar? Our nightly SonarQube analysis is blowing the Team City logs out with huge amounts of entries. According to the source, the logging is standard slf4j but when i've tried to reconfigure it, it doesn't work.According to the docs, least verbose level supported is info; can this be overridden?http://docs.sonarqube.org/display/SONAR/Server+Log+ManagementThanks
M
|
Sonar Runner default logging level
|
To complement Alexandre's answer; The parameters are describedhere.Since SonarQube 4.0 you can do the following:sonar-runner -Dsonar.analysis.mode=preview -Dsonar.issuesReport.html.enable=true
|
We have recently upgraded SonarQube to 5.1 version. In earlier versions there was Issues report plugin to generate html report for the issues. Now that plugin becomes native in 5.1, I wonder where the settings for issues report is? Is there anyway to generate html issues report as earlier?
|
How to Generate html issues report in SonarQube 5.1
|
I had the same issue just now.What helped me in the end was to test the server connection from Eclipse'sWindow -> Settings -> SonarQube -> Servers -> http://localhost:9000 -> Edit -> Test connectionI am running a fresh SonarQube installation and did not specify a username nor a password. The test returnedSuccessfully Connected!and thereafter SonarQube markers showed up in the source code as well as in the SonarQube issues tab.
|
I am new to Sonar and I am trying to install and configure Sonar in my local system. I have followed the steps mentionedherefor installing sonar and integrating it with eclipse, but I can not associate my project with sonar and getting exception One of your SonarQube server cannot be reached. Please check your connection settings. please see the below screen shots, and let me know if i am missing something.Thanks
|
One of your SonarQube server cannot be reached. Please check your connection settings
|
You can place your file, i.e.findbugs-sonar.xmlin the src/main/resource folder and specify the path in your maven reporting settings like this:<reporting>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
<version>2.5.3-SNAPSHOT</version>
<configuration>
<includeFilterFile>findbugs-sonar.xml</includeFilterFile>
</configuration>
</plugin>
</plugins>
</reporting>
|
How can I use a FindBugs configuration file from Sonar as the rule set in theMaven FindBugs plugin?
|
Import FindBugs configuration from Sonar to Maven
|
After some trial and error and looking at the error messages, I came up with this which compiles:import org.sonar.api.batch._
import org.sonar.api.resources._
object D {
type R = Resource[T] forSome {type T <: Resource[_ <: AnyRef]}
type S[T] = Resource[T] forSome {type T <: Resource[_ <: AnyRef]}
}
class D extends Decorator {
def decorate(r: D.R, context: DecoratorContext) {}
//def decorate(r: D.S[_], context: DecoratorContext) {} // compiles too
def shouldExecuteOnProject(project: Project) = true
}I'm not sure whether it will allow you to implement what you need. I looked atResource, and it could representFilewhich extendsResource<Directory>or sometimes be an erased (raw?) type that just extendsResourcelike forDirectory.Edit: thinking about it some more, theforSomecan be eliminated - this compiles too:def decorate(resource: Resource[_ <: Resource[_ <: AnyRef]],
context: DecoratorContext) {
}
|
I'm trying to build an extension for Sonar, using Scala.
I need to extend the following Java interface:public interface Decorator extends BatchExtension, CheckProject {
void decorate(Resource resource, DecoratorContext context);
}butResourcetype is actually defined like:public abstract class Resource<PARENT extends Resource>I know I can workaround creating a Java raw super-class.
I'd like to stick to Scala-only, also know if there's a solution I'm missing, and whether there's an improvement I could suggest to SonarSource people to make on their side (on using raw types).I've read there were issues with this, and some workarounds for some cases, but none seemed to apply here (a workaround,an apparently fixed ticket, also there's ticket 2091...)
|
Implement Java Interface with Raw type from Scala
|
I think it is clear thatnullis perfectly fine here, so I's suggest to suppress it. This worked for me:@SuppressWarnings("squid:S2637")
|
How isOptional.orElse(null)marked withorg.jetbrains.annotations.NotNullThe javadoc oforElseexplicitly states that null is allowed* @param other the value to be returned, if no value is present.
* May be {@code null}.But my code flags a "bug" in SonarQube.return users.findById(userID)
.flatMap(user -> students.findByUser(user))
.map(GetAllStudentsSvc::mapToStudent)
.orElse(null);Looking at the code it doesn't appear to be marked. Looking at the IDE it also does not appear to be markedEven annotating the code as@Nullabledoes not help.
|
Optional.orElse(null) is marked with org.jetbrains.annotations.NotNull
|
I have some problem and solved change version of surefire-plugin:<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
|
I am trying to get coverage per test feature working with Sonarqube 7.I am using jacoco-maven-plugin and my tests are running with JUnit 5.I successfully managed to get global Coverage on Sonarqube dashboard, but I would like to go deeper by being able to see which tests covered which lines of my classes.I've tried with the given configurationherebut without success : I get the following message in the logs 'No information about coverage per test'. I see that this can be obtained by adding a listenerorg.sonar.java.jacoco.JUnitListener, but it is a JUnit 4 listener, so I guess it is not working because of that.How can I manage to make the Coverage per test feature work with JUnit 5 ?
|
Sonar + Jacoco + Junit 5 : No information about coverage per test
|
There is no option to ignore getters and setters. However, if you have classes you'd like omitted entirely from coverage calculations, you can easily do so withexclusions.
|
Is there a setting in SonarQube dashboard that allows for ignoring getter and setters? This sounds like a better option then coding //nopmd on every method in your codebase.My codebase has a lot of them and they are dramatically lowering my unit test coverage % being reported in the Sonarqube dashboard
|
SonarQube ignore getter/setters in code analysis
|
I abandoned attempting to get Kotlin code coverage with Sonar shortly after posting the question.However, I have gotten many projects to work with Java and JaCoCo.Retrospectively looking back at mysonar.propertiesfile I may have been able to fix this by referencing the output of the JaCoCo task by adding the following line to the sonar.properties file:sonar.jacoco.reportPath=build/jacoco/test.execI am not sure that this will work with Kotlin, but it helped with Java coverage and solved my use case.
|
I have configured a Jenkins item that, after gradle building and testing, calls the "Execute SonarQube Scanner" with the following specifications:sonar.projectKey=my_project_key
sonar.projectName=my_Android
sonar.projectVersion=1.0
sonar.sources=app/src
sonar.java.binaries=app/build/intermediates/classes/debug
sonar.coverage.exclusions=app/src/test/**,app/src/androidTest/**,app/src/main/res/**This successfully runs SonarQube and generates a report to IPaddress:9000 that measures: Bugs, Vulnerabilities, Debt, Code Smells, and Duplications just like it is supposed to. However there is no place in this report that defines the code covered by tests. SonarQube is running the Kotlin plugin successfully and sees the codebase itself, but is not determining coverage. Is this possible to gather this information with SonarQube when using Kotlin Android?I did try installing Jacoco, but did not see any new data on the SonarQube results.
|
Is it possible to analyze Android Kotlin code-coverage with SonarQube?
|
This configuration is not support yet in SonarQube.But the good news is that this will change with SonarQube 6.4 (expect in early May 2017). See the following tickets:SONAR-6724SONARGRADL-5
|
I need to make analyzing only root project, and ignore nested sub module, but it dSo I have this hierarchy:ProjectMain
-src
-subProjectAngular
settings.gradleMy configurationsettings.gradlerootProject.name="ProjectMain"
include 'subProjectAngular'I need to make analyzing only root project, and ignore nested sub module, but I got:A multi-module project can't have source folders, so 'C:\Users\vagrant\develop-2\site\Source\Site\Vessels\src\main\java' won't be used for the analysis. If you want to analyse files of this folder, y
ou should create another sub-module and move them inside it.Then I tried to add multi module configuration:systemProp.sonar.projectKey=site
systemProp.sonar.projectName=vessels-test
systemProp.sonar.projectBaseDir=.
systemProp.sonar.sources=src
systemProp.sonar.modules=javamodule, angularmodule
systemProp.javamodule.sonar.projectName=vessels
systemProp.javamodule.sonar.sources=src
systemProp.javamodule.sonar.projectBaseDir=.
systemProp.javamodule.sonar.language=java
systemProp.angularmodule.sonar.projectName=angular
systemProp.angularmodule.sonar.projectBaseDir=.
systemProp.angularmodulebut got message at UI:no analysis has been performedIt's only works when I remove definishion of subproject fromsettings.gradle, and remove all submodule confguration
|
SonarQube not apply analyzing to the root project
|
We experienced a similar false positive producing the error 'Change this condition so that it does not always evaluate to "false"'.
The code in question follows:public Properties getProperties() {
Properties properties = new Properties();
InputStream in = getClass().getResourceAsStream("/my.properties");
IllegalStateException streamCloseError = null;
try {
if (in != null) {
try {
properties.load(in);
} catch (Exception e) {
//fall through...
}
}
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
streamCloseError = new IllegalStateException(e);
}
}
if (streamCloseError != null) {
throw streamCloseError;
}
return properties;
}The error was thrown on the lineif (streamCloseError != null) {.
We cleaned up this code after reading about using the above try-with-resources.Would it be possible with this rule to detect if it was found in conjunction with "closing" and if so provide the hint to use try-with-resources?Thanks for considering this.
|
Why is SonarQube complaining about this part of the code??SonarQube says:
Change this condition so that it does not always evaluate to "false"However I can't seem to understand why the condition would always be false? Indeed, actually it's not, I just reran this part again in debug mode and it works perfectly, it does go inside, and the condition is not false most of the time.Here's the code part:} finally {
if ((inboxFolder != null) && (inboxFolder.isOpen())) {
try {
inboxFolder.close(true);
} catch (MessagingException e) {
log.error(e.getMessage(), e);
}
}
if ((store != null) && (store.isConnected())) {
try {
store.close();
} catch (MessagingException e) {
log.error(e.getMessage(), e);
}
}
}It's the finally part of try-catch when trying to receive email with javax.email, it's complaining about both if conditions.This is the declaration of those variables, they get instantiated int the try part:Folder inboxFolder = null;
Store store = null;So why is SonarQube complaining about this?
|
SonarQube: Change this condition so that it does not always evaluate to "false" (for finally in javax.mail receiving)
|
You can mark the issue as a false positive through the SonarQube UI, as shown in this related question:Sonarqube 5 - how do I mark false-positive?I've created the following ticket to the SonarQube Python Plugin's backlog to consider adding theNOSONARcomment marker support in an upcoming version:http://jira.sonarsource.com/browse/SONARPY-129
|
I want to suppress the "Method names should comply with a naming convention" rule in my python code, but only in the case when I'm overriding a method from a Qt class.For example: inheriting fromQWidgetand overriding theresizeEvent()method (which is not compliant with the rule).According to theFAQthere are//NOSONARand@SuppressWarnings(which will fit my needs) but these are only available for java.Is there some special keyword for this or should I do something like creating new custom rule?
|
How to suppress sonarqube rule in a particular case?
|
It will be fixed in version 3.4See this issue on SonarSource :http://jira.sonarsource.com/browse/SONARJAVA-1117
|
Concerning rule squid: S109 Magic numbers should not be usedShouldn't it be allowed to have numbers in the constructor of an enum in java? The code below shouldn't violate the rule in my opinion.public enum Color{
RED(42),
GREEN(123456),
BLUE(666);
public final int code;
Color(int colorCode){
this.code=colorCode;
}
}I'm using Sonar java plugin version 3.3
|
SonarQube: Should magic numbers be allowed in java constructor enums
|
They are using the views plugin to do it, without (paying for) it you won't be able to do it.Once you get the plugin, create a view with all your projects, use the view's dashboard as your main dashboard (in manage dashboards) and add the following widgets : "SQALE overview", "issues and technical debt", "timeline", "measure filter as donut chart" and "measure filter as treemap".That's it, cheers.
|
I have installed a sonar web site, a jenkins web site( CI machine).While CI server build projects and send info to sonar server as sonar client.There are lots of projects in my sonar server.I need a way to setup dashboard with all projects view or widget.Just liketimelineinsonar demo siteBut when I configure my own sonar dashboard, I think there areonly treemap and list which hava filter. ( with filter I can get analysis of all projects )How did sonar demo web site do this?(Sonar 3.6.2 , CentOS 6.4)Thanks a lot ~
|
How to setup dashboard with all projects view/widget?
|
Thesimplecovis only used for coverage metrics. Unfortunately the is no native Ruby plugin that you can use to create a unit test count report, but you can use asonar.testExecutionReportPathsparameter with generic report. I've usedthis formaterfor it.sonar.testExecutionReportPaths=./path-to-your/report.xml
|
I'm using Sonarqube with RoR and RSpec as testing tools, successfully get coverage but not the count of Unit Tests as shown on the image below:Please help 🙏🏼Configuration:spec_helper.rbif Rails.env.development? || Rails.env.test?
require 'simplecov'
require 'simplecov-json'
SimpleCov.formatter = SimpleCov::Formatter::JSONFormatter
SimpleCov.start
endsonar-project.propertiessonar.projectKey=myapp
sonar.sources=.
sonar.exclusions=**/vendor/**,**/coverage/**,**/assets/**
sonar.tests=app-code/spec
sonar.test.inclusions=**/*_spec.rb
sonar.test.exclusions=**/vendor/**
sonar.ruby.coverage.reportPaths=app-code/coverage/.resultset.json
sonar.ruby.coverage.framework=RSpecGemfilegem 'simplecov', '>= 0.17', '< 0.18'
gem 'simplecov-json', '<= 0.2'
|
Sonarcube using rspec not showing count of Unit Tests
|
Real world cases of hidden backdoors learn that the code is typically far more obscured to use a variable name that indicates the purpose.So to get to something foolproof, you'd need to do a full static analysis and have "intelligence" in the code checker to understand the code and find where the authentication happens and then work backwards to verify there are no hidden ways to achieve this.IMHO it's cheaper to hire somebody to do (security) code reviews than to try to automate this.
|
I have been trying to detect hard coded passwords in source code files.Currently I am checking for variable assignments and comparison for identifiers with a sub-string matching with password,pswd.But it is leading to lots of false positives like in this case(Reading passwords from a config file)String PASSWORD_KEY = "server.password";
String password = prop.getProperty(PASSWORD_KEY);I can flag out some sub-strings like Key,location,path for which i can skip the error generation but apart from this I cannot think of a better approach.All suggestions are appreciated.
|
Detecting Hard Coded Passwords
|
JaCoCo is now supported in Android Studio when using build tools version 0.10.0New Build SystemRelease Notes:0.10.0....Test code coverage support with JacocoEnable in the tested Build Type with testCoverageEnabled = trueHTML and XML Report generated in build/reports/coverageConfigure version of Jacoco withandroid {
jacoco {
version = '0.6.2.201302030002'
}
}Known issue: This is not compatible with using Dagger......
|
I am trying to get code coverage working for a new empty Android project using Gradle in Android Studio.I managed to get Sonar working but I can't seem to figure it out for the code coverage. (never done anything like it before)I have looked at JaCoCo but it is not compatible with Android. The same goes for Cobertura. And it seems Emma doesn't work with Gradle yet.I am using Gradle 1.11, Android Studio 0.5.1 and Sonar Runner 2.3
|
Code Coverage in Android Studio with Sonar & Gradle
|
From what I understand, you should probably have a first instance of Sonar which is only used during the build to break it if your quality requirements are not met, and a second one that is used by your CI system and that is the reference for your products. And if you really want to enforce your process and be sure that code which breaks those requirements is not pushed into your SCM system, then you could bind a Sonar analysis on a pre-commit hook. But this seems a bit extreme to me...At SonarSource, we haven't chosen the "block a commit because of violations" approach. Indeed, we consider that having some technical debt (= violations) is OK as long as you manage it. Managing technical debt means reviewing each incoming violation in Sonar and fixing them in the code or affecting those violations to action plans, the main idea being that the technical debt should not have increased at the end of a development sprint. This is what the review feature of Sonar is meant for. And Sonar provides widgets to monitor the evolution of reviews and new violations without a review.
|
I'm configuring a multi-module maven project that force the execution ofsonar:sonarin theverifyphase.I also use the build-breaker-plugin of sonar to avoid deploying the module if some alerts are thrown by sonar.The problem with this approach is that the developer should go to the sonar server to check the alerts. This is not that bad but if several users try to analyses the same module at the same time is impossible to know if the last/current analysis have your alerts.CONTEXT: we have a CI system that builds all the modules each hour. So sometimes this collides with some developer deploy (that force the analysis)IMHO, only the CI system should commit the analysis to the sonar server, because the CI have the lasted committed and deployed code. But the developer should only check locally his changes.So, why we are forcing the analysis in the developer build? To avoid deploying modules that does not respect the code quality thresholds (The build-breaker plugin of sonar helps on this).There is a way to configure the maven-sonar-plugin to do this?local analysis in the developer build.server analysis in the CI build
|
Can maven-sonar-plugin make a local analysis?
|
Jenkins seems to set that property:Hudson build successful with unit test failuresWith the property (-Dmaven.test.failure.ignore=false), when there is a test failure, the build stops.There is ajenkins pluginfor sonar:
That seems to analyze even if Tests fails:http://jira.codehaus.org/browse/SONARPLUGINS-461In my sonar installation, I run the tests seperate from sonar and reuse the junit/surefire reports. That way I can control the tests independently from sonar.
|
I have a job in Jenkins that is run every night. The tasks executed during this build are: compilation, unit tests, integration tests (which are only JUnit tests which are longer than "real unit tests" to execute), and Sonar quality analysis.When a test fails, the job is however considered as successfull and thus, no email is sent to notify this failure.The Maven command used ismvn clean install sonar:sonar. Removing theinstallgoal does not change anything.What is wrong with that?Is there a way to get the expected behavior (i.e. having an unstable build when a test failed) with only one Jenkins job, or should I create two jobs, one for the whole "Java part" (compile, unit test and integration tests), and one for the Sonar analysis?We are using Maven 2.0.9, Java 1.6, Sonar 2.8, Jenkins 1.413.
|
Why my Sonar Jenkins job never becomes unstable, even with test failures?
|
do you have configured jacoco prepare-agent? I faced the same issue and have found out, that I missed this configuration.Helpful link for that could behttps://docs.sonarqube.org/display/SONARQUBE45/JaCoCo+Plugin.Or via pom.xml:<build>
<plugins>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.0</version>
<configuration>
<append>true</append>
</configuration>
<executions>
<execution>
<id>prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>Regarding to your report paths:Which version of SonarQube do you use?sonar.junit.reportsPathis deprecated since version 4.11 andsonar.junit.reportPathsshould be used instead.And how do you create your xml report file?
|
I have configured a project in SonarQube and the anlaysis is run using JaCoCo plugin for visualisation of unit test coverage .The tests are run successfully in Jenkins and the reports can be seen in the Jenkins workspace .However ,sonar dashboard shows the coverage as 0% but the number of unit tests are still seen on sonar dashboard as well .
I have tried using the following properties in command line .These properties are configured in the SonarQube configuration as well.-Dsonar.junit.reportsPath=target/surefire-reports -Dsonar.coverage.jacoco.xmlReportPaths=target/site/jacoco/jacoco.xml
|
SonarQube coverage percentage with jacoco plugin shows zero percentage but hte number of unit tests are seen
|
I have a similar problem with the potential deprecation of this feature. We have too many projects to be managing this administratively in sonarqube.The best approach for our site is to allow the teams to select an approved profile using setting in the maven pom.xml.
|
Having a look to our build logs, I can see this warning:build 31-Dec-2015 10:37:39 [WARN] [10:37:39.896] Ability to set quality profile from command line using 'sonar.profile' is deprecated and will be dropped in a future SonarQube version. Please configure quality profile used by your project on SonarQube server.Even if I can easily understand why it could be deprecated, I have an issue with that. We have a single SonarQube installation for all our teams. Each team must be compliant with a given Quality Gate but can define its own profile, depending on the needs. We are working with git branches. We have "static" branches such as master and develop, but also feature and bugfix branches which are also scanned (to insure code quality before merge). Entries in sonar are created also from command lineDsonar.project.branch=${bamboo.planRepository.branch}Which helps us to get one sonar entry per development branch.Issue: Each time we create a feature, not having the command line will force us to go to Sonar and manually change the profile.Do you have any suggestions, ideas, which may help us ?Thanks
|
Sonar quality profile in command line cannot be replaced by a project profile
|
According tohttp://docs.oracle.com/javase/7/docs/api/index.html?javax/annotation/package-summary.htmlthe classes you expect are not part of JDK 7.The classes you're looking for are part of google JSR-305 implementation that was initiated herehttps://code.google.com/p/jsr-305/source/browse/trunk/ri/src/main/java/javax/annotation/Nullable.java?r=24and which moved to Findbugs:<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>3.0.0</version>
</dependency>According tohttps://jcp.org/en/jsr/detail?id=305the JSR-305 is finished, but is indormantstatus and has not been added to a JDK release yet.Hope it helps.ShareFolloweditedOct 5, 2015 at 12:05answeredOct 5, 2015 at 11:58KraalKraal2,81911 gold badge1919 silver badges3636 bronze badges29Reading this answer, I'm not sure what is the solution. Should I add this dependency withing the sonar maven plugin configuration ?–baraberOct 9, 2015 at 12:451I see similar problems and adding the google findbugs dependency to the project dependencies helps. Similar problems occured with joda convert like[ERROR] [20:44:25.247] Class not found: org.joda.convert.ToString. Hence I added–Gerd AschemannDec 29, 2015 at 1:14Add a comment|
|
My setup:Sonarqube 5.1.1Sonar-Maven Plugin 2.6 (also tried 2.7 and 3.6)JDK 1.7.0_51Example of the error:16:00:54 [INFO] [23:00:54.219] Sensor JavaSquidSensor
16:00:55 [INFO] [23:00:55.030] Java Main Files AST scan...
16:00:55 [INFO] [23:00:55.030] 1532 source files to be analyzed
16:00:58 [ERROR] [23:00:57.927] Class not found: javax.annotation.Nullable
16:00:58 [ERROR] [23:00:57.928] Class not found: javax.annotation.CheckReturnValue
16:00:58 [ERROR] [23:00:58.114] Class not found: javax.annotation.NullableAccording to thisstackoverflow question, javax.annotation should be part of java 1.7 and up. Furthermore, I've tried putting it in the local maven repository but that didnt help.So where is Sonar trying to find this package? Any help?!?Update:I've tried modifying the sonar-maven-plugin to include a dependency on javax.annotationI've tried putting the dependency in my maven's settings.xmlUpgrading my JDK to 1.8 has not helped.
|
SonarQube "Class Not Found" during Main AST Scan
|
SonarQube uses an older version of thei18n gem(see theweb/WEB-INF/gems/gemsdirectory).If you disable thervm, Sonar should work fine.Disable rvm$ rvm use systemShareFolloweditedJun 20, 2020 at 9:12CommunityBot111 silver badgeansweredApr 21, 2015 at 14:29Dawid StępieńDawid Stępień1,37711 gold badge99 silver badges66 bronze badgesAdd a comment|
|
After having downloaded sonarqube, I start the server and try to access it athttp://localhost:9000. Logs show that server is started.
I have however an error:2015.03.11 14:39:02 INFO web[o.s.s.app.Logging] Web server is started
2015.03.11 14:39:03 ERROR web[o.s.s.ui.JRubyFacade] Fail to render: http://localhost:9000/
"fr" is not a valid locale
/home/osallou/.rvm/gems/ruby-1.9.3-p429/gems/i18n-0.7.0/lib/i18n.rb:284:in `enforce_available_locales!'
/home/osallou/.rvm/gems/ruby-1.9.3-p429/gems/i18n-0.7.0/lib/i18n/config.rb:13:in `locale='
/home/osallou/.rvm/gems/ruby-1.9.3-p429/gems/i18n-0.7.0/lib/i18n.rb:43:in `locale='
....fr_FR is in my locale (ubuntu), and my default locale is en_USI do not understand why it takes french (but why not), but I need to fix the conf/startup issue. I do not see any locale config in sonar.conf.Thanks
|
Can't acess SonarQube: not a valid locale
|
Less you have helpless and duplicate code and more the code is readable and maintainable.List<String> nameList = new ArrayList<String>();orList<String> nameList = new ArrayList<>();Ok, not a lot of differences.But suppose now that you have to change the generic:StringbyInteger, with the first way you have to do two modifications:List<Integer> nameList = new ArrayList<Integer>();
^------ -------------^Really not nice.With the diamond a single one is required :List<Integer> nameList = new ArrayList<>();
^---But take another example :Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();orMap<String, List<Integer>> map = new HashMap<>();It makes things clearer.In an application, you generally declare and instantiate tons of collections and generic classes. Refactoring it is really cheap. So just do it.ShareFolloweditedJan 9, 2020 at 13:38lealceldeiro14.7k66 gold badges5252 silver badges8484 bronze badgesansweredAug 31, 2018 at 15:18davidxxxdavidxxx128k2323 gold badges218218 silver badges221221 bronze badges1Is there some code refactoring tool/utility to do that in an old codebase that can replace all such occurrences? Any help with an IDE?–Prashant C ChaturvediSep 2, 2021 at 10:49Add a comment|
|
So I have below line of code in my fileList<String> nameList = new ArrayList<String>();Now each time I run sonar scans it shows an error in above line saying I should use diamond operator instead. Now I understand that from Java7 compiler will automatically detect and supply the type of objects for ArrayList but my question is there a harm if I do it myself while declaring the class ?Here is therule link from Sonar website. I really don't understand the example they are supplying with this rule.Is there any performance, efficiency or any other type of gain in
changing the code to what Sonar is suggesting ?
|
Sonar complaining "The diamond operator ("<>") should be used"
|
Probably because another piece of code could execute:Constants.FORMATS[0] = "SOME GARBAGE";And break the rest of your code.In other words your array is constant but not its content.Examples of alternatives:you can store each format as a separate String constantyou can use an immutable list instead:public static final List<String> FORMATS = Collections.unmodifiableList(Arrays.asList("yyyy-MM-dd HH:mm:ss.S z", "yyyy-MM-dd HH:mm:ss.S"));make it a method:public static String[] formats() {
return new String[] { "yyyy-MM-dd HH:mm:ss.S z", "yyyy-MM-dd HH:mm:ss.S" };
}ignore the warning if you are confident that (i) only your own code will access that class and (ii) there is no way you/your colleagues would even think of reassigning one of the values.ShareFolloweditedMay 20, 2013 at 9:30answeredMay 20, 2013 at 9:24assyliasassylias325k8383 gold badges664664 silver badges787787 bronze badges2so final would just prevent re-assign like FORMATS = new String[] {"a","b"}. But that's bad so I have to use a immutable list then?–dumperMay 20, 2013 at 9:28Yes that's the problem and that's one possibility.–assyliasMay 20, 2013 at 9:29Add a comment|
|
Sonar is giving me the message:Malicious code vulnerability - Field should be package protected for
static arrayFORMATS.Why is this code considered malicious? I have a public class to store all the constants.public class Constants
{
/*
all the public static final constants of primitive datatypes for which
there is no sonar warning.
*/
public static final String[] FORMATS = new String[] {
"yyyy-MM-dd HH:mm:ss.S z",
"yyyy-MM-dd HH:mm:ss.S"
}
|
Malicious code vulnerability - Field should be package protected
|
Bitnami developer here,The following commands worked for me on a GCE instance:Download solr-scanner 4.2.0:Unzip it in/opt:sudo unzip -d /opt sonar-scanner-cli-*.zipDownload sonar-scanning-examples:Unzip them in$HOME/sonar-scanning-examples:unzip -d $HOME master.zip
cd /home/bitnami/sonar-scanning-examples-master/sonarqube-scannerAnalyze a project as shown below. Replace the PASSWORD placeholder with the correct password./opt/sonar-scanner-*/bin/sonar-scanner -Dsonar.login=admin -Dsonar.password=PASSWORDIn case you face some issue, try to load the environment before analyzing the project:sudo /opt/bitnami/use_sonarqubeI hope it helpsShareFollowansweredDec 4, 2019 at 11:05David GomezDavid Gomez64455 silver badges99 bronze badgesAdd a comment|
|
I've been trying to configure sonarqube to work with cloud build trigger and want to use bitnami's sonarqube compute instance installation but when I installed sonar-scanner using this guide:https://docs.sonarqube.org/latest/analysis/scan/sonarscanner/and when runsonar-scanner -hI receive this Error"Could not find 'java' executable in JAVA_HOME or PATH"my JAVA_HOME isopt/bitnami/javaand PATH isopt/bitnami/java/binhelp me what I'm doing wrong or if missing something.
|
Error "Could not find 'java' executable in JAVA_HOME or PATH" while installing sonar-scanner with sonarqube google compute instance
|
You can use this open source app:https://github.com/cnescatlab/sonar-cnes-reportIt is officially available on SonarQube Marketplace.It generates a docx report and an xlsx file with all issues. You can also generate markdown and csv files based on your own templates.ShareFolloweditedSep 11, 2020 at 9:36answeredFeb 19, 2018 at 14:51begarcobegarco75677 silver badges2121 bronze badges3This plugin isn't working for latest version, i.e community edition - version 9.6. Check this matrixgithub.com/cnescatlab/sonar-cnes-report#compatibility-matrix–Abhishek PandeyAug 17, 2022 at 12:53Together with the compat matrix mentioned by @AbhishekPandey you should also check this issue report with comments about compatibility down to version 9.4 (as I write this):github.com/cnescatlab/sonar-cnes-report/issues/270–JpsySep 6, 2022 at 8:38this is getting installed in version 8.9.9–avishekdrSep 15, 2022 at 5:31Add a comment|
|
Closed.This question is seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. You can edit the question so it can be answered with facts and citations.Closed6 years ago.Improve this questionI have SonarQube 7.0 -Community version.I was looking for some reporting plugin that would bring the code smells, bugs and other issues in a PDF report.I found Governance report plugin, but that was only for commercial editions.Is there any reporting plugin in the community edition that would fit my need?
|
SonarQube - Community edition - Reporting Plugin [closed]
|
You apply both profiles by creating a third profile that contains all the rules in each of your source profiles.The easiest way to accomplish that is toGo to Quality Profiles and create a new profileNow in the list of profiles, click on therule countfor one of your source profiles. This takes you to the list of rules active in that profileUse theBulk Change > Activate In...option to turn those rules on in your new profileReturn to step 2 with the next source profile in your list.ShareFolloweditedAug 24, 2017 at 9:14JJD50.6k6060 gold badges207207 silver badges345345 bronze badgesansweredJun 13, 2017 at 13:40G. Ann - SonarSource TeamG. Ann - SonarSource Team22.5k44 gold badges4242 silver badges8484 bronze badges12Nice, thank you a lot. - I would love to see this feature a bit more intuitive or better discoverable in the documentation.–JJDJun 13, 2017 at 13:49Add a comment|
|
I would like to useSonarQube6.3.1 to analyze the Java and Kotlin code of anAndroidproject. Therefore, I installed theAndroid Lintplugin besides the preinstalledSonarJavaaka.Sonar wayplugin. Both show up in theJavalanguage dropdown in theAdministrationsection of the project as shown in the screenshot.How can I applymultipleprofiles at the same time?Where can I find other profiles suitable for Java/Kotlin/Android projects?Related postsSonarqube: use multiple custom quality profiles for a single multilanguage project...?
|
SonarQube: How to apply multiple quality profiles to one project?
|
I think SonarQube is spot on here: there's no parameter namedUserCode, so you shouldn't be specifying it as an argument to theArgumentNullExceptionconstructor. I would avoid usingArgumentNullExceptionat all here, as theargumentisn't null - otherwise it would be throwing aNullReferenceExceptionatcommand.UserCode.Instead, just useArgumentExceptionwith a descriptive message, e.g.throw new ArgumentException(
$"{nameof(command.UserCode)} property cannot be null or empty",
nameof(command));Now we can tell which parameter is incorrect (command) and how (itsUserCodeproeprty is null or empty). SonarQube should be fine with this, and it meets the meaning of the exception type more accurately IMO.ShareFolloweditedDec 10, 2018 at 17:51answeredDec 10, 2018 at 17:46Jon SkeetJon Skeet1.5m876876 gold badges9.2k9.2k silver badges9.2k9.2k bronze badges2Great catch! (Y)–Nikhil VartakDec 10, 2018 at 17:50Thanks! this makes very much sense :)–Wampie DriessenDec 12, 2018 at 10:46Add a comment|
|
Our SonarQube often raises the following issue (Code Smell) on our code: "Parameter names used into ArgumentException should match an existing one".Hereis the rule that triggers this issue.An example of this issue being triggered can be the following:private void Validate(SaveCommand command)
{
if(string.IsNullOrEmpty(command.UserCode))
throw new ArgumentNullException(nameof(command.UserCode));
....
}My question is: How do i properly refactor the code to abide by SonarQube (andMSDN) guidelines?Or should i just keep it like this. If so, why?
|
Using a parameter's property in an ArgumentException
|
Just found out in theproject's documentation.Ignore Code CoverageYou can prevent some files from being taken into account for code
coverage by unit tests.To do so, go to Administration > General Settings > Analysis Scope >
Code Coverage and set the Coverage Exclusions propertyThere is also the following directive that can be used in thesonar-project.propertiesfile:sonar.coverage.exclusionsShareFolloweditedDec 20, 2021 at 12:53T'n'E59855 silver badges1717 bronze badgesansweredJan 22, 2018 at 9:48pkaramolpkaramol17.6k4646 gold badges171171 silver badges373373 bronze badgesAdd a comment|
|
I want to provide a coverage report for auiproject.The project mainly consists of.tsfiles which under version control.Thegulpcommand used to check coverage, generates.jsfiles which are then checked for coverage. (and a coverage report that ... reportsonlyon those files)The.jsfiles are not under version control and, when produced are intermingled with the.tsfiles (i.e., wherever there is a.tsfile, a.jsfile will be generated next to it).This creates the following issue:Whensonarqubegenerates coverage report, to my report above (pointed to bysonar.javascript.lcov.reportPaths), the.tsfiles are added (which of course have0.0%coverage) and this breaks the actual cov value.Is there a way / pattern to instruct sonarqube to:a) perform code analysis on.tsfilesb) ignoreall.tsfiles when generating coverage report?
|
SonarQube: Ignore files during coverage report
|
You have to set skipProject to true in a project you want to skip:sonarqube {
skipProject = true
}https://docs.sonarqube.org/display/SCAN/Analyzing+with+SonarQube+Scanner+for+Gradle#AnalyzingwithSonarQubeScannerforGradle-SkippinganalysisofaprojectShareFollowansweredJun 25, 2017 at 13:33kzakza1,6001313 silver badges3232 bronze badges4When i do that I have the issue that it lost my server configuration and returns to defaultlocalhost:9000–AbbadonSep 26, 2018 at 15:30Looks like a bug in the 2.6.x plugin. When I bumped the version to 2.7 it honoured skipProject and didn't fail over to localhost.–user437212Apr 24, 2019 at 21:20Cannot access 'skipProject': it is private in 'SonarQubeExtension'–Michel JungApr 18, 2023 at 12:44isSkipProject = true–bsautnerJul 25, 2023 at 14:32Add a comment|
|
I have a multi module gradle java project analyzed with sonarqube.I need to skip sonarqube analysis of one module entirely.I was not able to find a solution in sonarqube documentation. Closest page is Narrowing The Focus, but it is about skipping files and directories while I'd like to skip entire module.
Seehttps://docs.sonarqube.org/display/SONAR/Narrowing+the+Focus
|
How to skip sonarqube analysis of gradle module
|
If I were to boil it down to a short phrase, SonarQube is used for ensuring code quality, and CheckMarx is used for ensuring the security of a system running that code.SonarQube looks at several areas, including the code coverage percentage of unit tests of the code, duplication percentages, and also code quality issues found through static analysis of the code.CheckMarx, on the other hand, just analyzes the flow of the code and the inputs and outputs. It looks for situations where inputs that could have been provided by an end user are used directly to control behavior, and other "attack vectors".ShareFollowansweredMay 21, 2022 at 17:40David M. KarrDavid M. Karr14.7k2121 gold badges9898 silver badges207207 bronze badgesAdd a comment|
|
I have integrated SonarQube and Checkmarx SAST and SCA into the Azure DevOps build pipeline. I am able to see both the SonarQube and Checkmarx reports without any issues.I have the following questions. Could someone please clarify:What is the difference between SonarQube and Checkmarx CxSAST?What is the common thing between these two?In which situations are SonarQube and Checkmarx preferred?
|
What is the difference between SonarQube and Checkmarx CxSAST & CxSCA?
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.