Response
stringlengths 8
2k
| Instruction
stringlengths 18
2k
| Prompt
stringlengths 14
160
|
---|---|---|
Your logs show that no file is indexed for "MyProject Admin Client":[INFO] ------------- Scan MyProject Admin Client
[INFO] Base dir: /Users/wdb/Projects/myproject/myproject-admin-client
[INFO] Working dir: /Users/wdb/Projects/myproject/myproject-admin-client/target/sonar
[INFO] Source paths: pom.xml
[INFO] Binary dirs: target/classes
[INFO] Source encoding: UTF-8, default locale: en_US
[INFO] Index files
[INFO] 0 files indexedYou have to configure thesonar.sourcesproperty so that your JavaScript files are indexed. Please see the documentation of theSonarQube Scanner for Maven.
|
I have a multi-module Maven project with 2 modules: one is a Java project the other one is a JavaScript project using the front-end Maven plugin that runs gulp.I get my Java code checked by Sonar and code coverage for that as well. However, the Javascript module (shown as a 'component' in Sonar) does seem to have been recognized as such. Do I need to do something for Sonar to 'see' this is a JavaScript module?I am using SonarQube 5.2 and the JavaScript plugin is installed. (I can see 'Sonar Way' quality profile for JavaScript under 'Quality Profiles')UPDATE:Java plugin has version 3.8JavaScript plugin has version 2.9Seehttp://pastebin.com/Rv0qffjsfor log
|
SonarQube not showing anything on my JavaScript Maven sub-module
|
Indeed, sonar.exclusions does not work in this case. I logged a bug to track this:https://jira.sonarsource.com/projects/SONARMSBRU/issues/SONARMSBRU-191
|
Using SonarQube 5.2 (MSBuild.SonarQube.Runner.exe)... Given a Visual Studio solution containing 10 C# projects, is it possible to exclude half of those projects from SonarQube analysis without having to edit the *.csproj files directly? (I'm working with a shared code-base and don't want to pollute the project files with SonarQube specific configuration).I've tried and failed to leverage the Analysis Scope 'Source File Inclusions' and 'Source File Exclusions' settings because the source file paths appear to be relative to the project directory and do not include the base path.e.g. if my 'Base dir' is 'C:\Source\Projects\Project1' the source paths are detected as Source1.cs, Source2.cs, SubFolder/Source3.cs, etc. and this prevents an inclusion or exclusion rule of **\Project1***.cs from working.Does anyone know of a way to accomplish what I need without the klunky rigmarole describedhereandhere? Is there a way to change what 'MSBuild.SonarQube.Runner.exe' considers the base path for instance?
|
Excluding projects from the MSBuild Runner without changing csproj files
|
i created a plugin for this behavior (and by extend to link sonar to my maven projects):https://github.com/VandeperreMaarten/sonar-maven-plugin.The only thing you need to do isadd following plugin to your pom.xml<plugin>
<groupId>com.viae-it.maven</groupId>
<artifactId>sonar-maven-plugin</artifactId>
<version>LATEST</version>
</plugin>call the plugin to validate themvn com.viae-it.maven:sonar-maven-plugin:validate-qualitygate
|
I want to be able to completely stop a Maven build process in case SonarQube detects new rule violations during incremental analyses in the developer's machines. I want to do this in order to force the developers to verify their code quality prior to checking their changes in to the SCM (Apache Subversion, in our case).The Build Breaker plugin is not a possibility since it doesn't break the build. It lets the build finish successfully, and only reports a status of BUILD FAILURE. Furthermore, Build Breaker is not supported anymore for SonarQube 5.1+ for preview/incremental modes.
|
It is possible to break Maven builds when SonarQube detects new violations, without using the Build Breaker plugin?
|
The code producing this was generated by AspectJ so it was not visible for me, but visible for sonar...
|
In Sonar I see a Redundant nullcheck of this, which is known to be non-null Error, but I can not find the Reason for this.Hope somone can help me to find the reason.Thx & RegardsEdit1:public class Filter extends AbstractBaseEntity implements Serializable {
public Filter() {
super();
}
}AbstractBaseEntity has no implemented constructor
|
Cannot find reason for Redundant nullcheck of this, which is known to be non-null
|
If you have lots of Junit/Integration tests that run each time sonar is analyzing your code it can take a long time before it is finished.If this is the case , maybe you should move (part) of your tests (for example the once that use the db) to a separate sonar project, which you'll only run once in a while. And run only your small and real unit tests.
|
My sonar analysis takes a long time to complete. Initially it took around 20-30 mins. Later it increased to 1hr+. Now after 5 months it takes whole 5 hours.
Can someone suggest the reason and how to rectify the same.I use sonarqube 4.4 with postgresql 9.3 db. The sonar db takes up almost 40G of space.If you check my log below you will notice that most of the time is spent on IndexProjectPostJob.08:53:47.437 INFO - Executing post-job class org.sonar.plugins.core.issue.notification.SendIssueNotificationsPostJob
08:53:48.687 INFO - Executing post-job class org.sonar.plugins.core.batch.IndexProjectPostJob
12:56:24.924 INFO - Executing post-job class org.sonar.plugins.dbcleaner.ProjectPurgePostJob
12:56:26.601 INFO - -> Keep one snapshot per day between 2015-06-10 and 2015-07-07
|
Sonar analysis takes long time
|
Eclipse SonarQube plugin 3.4 is definitely compatible with Eclipse Mars.Unfortunately, you cannot install it from the Eclipse Marketplace - probably because we need to update the compatibility information there. As mentionned by Freddy in his comment,SONARCLIPS-446was created for this purpose.Meanwhile, please follow the instructions described on"Install SonarQube in Eclipse"to manually install the plugin.UPDATE July 21rst, 2015: the Marketplace has been updated so anybody using Mars can install the plugin through the Marketplace.
|
I cannot install SonarQube plugins in Eclipse Mars (tested with Java, RCP and Modeling versions).When I search for SonarQube in 'Help' / 'Eclipse Marketplace' then the result list isempty. I can click at the link 'Browse for more solutions' which opens the marketplace site on the internet. There, I see SonarQube with the link 'Install' but when I click on it I get the error "The following solutions (SonarQube) are not compatible with this version of Eclipse"!Any ideas how the problem can be solved?
|
Is the Eclipse SonarQube plugin compatible with Eclipse Mars?
|
First, the set of available rules is defined by the installed plugins, it does not depend on the version of SonarQube.Some language plugins support custom rules. As mentioned by benzonico, adocumentation on writing custom rulesis available. Custom rules can be written in Java or XPath depending on the language plugin.If you don't want to write custom rules, you have to find a plugin which implements the rule you need. The PHP plugin used to provide some integration with external tools like PHPCodeSniffer and supported the import of a quality profile through XML. However, as mentioned in thedocumentation of this plugin, that feature was removed in version 2.0.
|
I have a requirement to add few more rules to the existing rules. But I am unable to find any way for the latest version of sonarqube i.e 5.1+
Can someone tell me how to do that?As we know in the latest version, we already have sonarway of rules, which get caught as issues when we run sonar runner for any language specific plugin. I want to add few more rules to the existing rules, which would be caught while running sonar runner.Manual rules are like we need to do it manually.I Have done a lot of research before posting the question.
|
How to add custom rules in sonarqube 5.1+
|
As documentedhere, this API requires the user to have 'Browse' permission on the project. You will need to pass the credentials using Basic Auth to the server, it should work.You need to passAuthorization: Basic <base64encoded-username-password>in the HTTP header of your request. You can find many tools to generate the code, I use fiddler. In fiddler, go to Tools -> Text Wizard. In the dialog box enterusername:password(e.g.admin:admin) and select 'ToBase64'. Copy this code in the HTTP header and try sending the request again.
|
I want to access the web service API to checkout some information of a project regarding especially the code coverage. My request URL I try to use is:https://<host>/api/coverage/show?key=<project-key>The Problem is that I will only get the following response:{
errors: [
{
msg: "Insufficient privileges"
}
]
}I'm logged in via valid session in cookie and I have all necessary permissions (i.e. browse permission). So why can't I get data?
|
Insufficient privileges - Web service API
|
Assuming you have access to svn repository server, an automated build system(maven/ant or similar) and sonar server has a build breaker plugin with quality gates configured, you can write a simple shell script to :svn update repository workspacecompile task(maven/ant)execute sonar-runner in incremental modecustom error messages in case build breaksCopy the script to the repository hook directory. If the repository already has a pre-commit hook, append the command /bin/shyour_shell_script_full_path.If the pre-commit hook file does not exist, create the file pre-commit.sh and include the same.
|
I've installed SonarQube on my Ubuntu machine and ran a sonar runner for one of my PHP projects. It works perfectly and I can see all the errors in the sonar web panel.http://localhost:9000/sonarBut what I really want is to analyze all the files for errors which are going to be committed in my svn repository. I read a lot about Hudson and Jenkins but really not getting the exact idea to do it. In my previous company there was both sonar and svn. When we committed the files in svn, sonar used to analyze the codes of all outgoing files and my svn client returned all the error.I also read about pre and post commit svn hooks but experts are saying that it would take a lot of time to commit the file and will let the other users wait for their svn usage.
|
Run Sonar Runner on each SVN commit to analyse outgoing SVN files
|
I just had the same issue; there's no blame info because the file is probably not tracked.If you run a "git status", is sub/someinclude.h not committed? Either commit it or try to add it to .gitignore. In my case I just committed the file and Sonarqube worked.
|
I have C++ projects with source code libraries in sub-modules and am using the Sonar commercial C++ plugin. I wish to analyze all the sources.The parent project needs access to some of the headers (and compiled libs) in the sub-modules and therefore by using sub-modules I can readily pin (and hence compile against) the right library version.eg
./main.c contains #include sub/someinclude.hwhere sub is the directory containing the git sub-moduleWhen analysing with sonar with SCM enabled I am getting:INFO: -----------------------------------------------------------------------
INFO: EXECUTION FAILURE
INFO: -----------------------------------------------------------------------
Total time: 2:17.478s
Final Memory: 27M/617M
INFO: -----------------------------------------------------------------------
ERROR: Error during Sonar runner execution
ERROR: Unable to execute Sonar
ERROR: Caused by: Unable to blame file sub/someinclude.h. No blame info at line 1. Is file commited?Sonar appears to be failing to do a git blame probably because it tries to reference the projectBaseDir rather than the current file directory and someinclude.h is not in the parent git repo.I have tried several multi-project sonar property file configurations placed in the parent and the sub-module or even externally but cannot find one that works.This looks like a normal use case so can anybody advise a solution or is this a bug/limitation that needs fixing?
|
Sonar 5.0 SCM plugin unable to blame source in git sub-modules causing analysis failure
|
Lots of answers here, but I haven't seen this mentioned yet:Most of the "dangers" associated with usingbreakorcontinuein a for loop are negated if you write tidy, easily-readable loops. If the body of your loop spans several screen lengths and has multiple nested sub-blocks, yes, you could easily forget that some code won't be executed after the break. If, however, the loop is short and to the point, the purpose of the break statement should be obvious.If a loop is getting too big, use one or more well-named function calls within the loop instead. The only real reason to avoid doing so is for processing bottlenecks.
|
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the help centerfor guidance.Closed10 years ago.Is it a bad practice to usebreakstatementinside aforloop?Say, I am searching for an value in an array. Compare inside a for loop and when value is found,break;to exit the for loop.Is this a bad practice? I have seen the alternative used: define a variablevFoundand set it to true when the value is found and checkvFoundin theforstatement condition. But is it necessary to create a new variable just for this purpose?I am asking in the context of a normal C or C++ for loop.P.S: TheMISRA coding guidelinesadvise against using break.
|
Reasons to not use 'break' statement in loops [duplicate]
|
Upgrade to the latest Findbugs SonarQube plugin, 3.1. That solved the issue for me. Please let us know.Log in as adminUnder "settings" on the top menuClick "Update center" in the left navigationNow under "Plugin updates" in the content pane tabs...But mostly I can't take my eyes off the righthand side of your screenshot. Some really excellent recursion going on. Thanks for that.
|
This question already has answers here:ArrayIndexOutOfBound Error - Java [closed](2 answers)Closed9 years ago.I'm having this error while trying to analyze a project with Sonar Server:INFO: EXECUTION FAILUREINFO: Total time: 50.063s Final Memory: 13M/164MERROR: Error during Sonar runner executionERROR: Unable to execute SonarERROR: Caused by: Can not execute FindbugsERROR: Caused by: java.lang.ArrayIndexOutOfBoundsException: 30344ERROR: Caused by: 30344We were using the default rules before and everything was working. We changed to other rules, and this error happened. It's weird 'cause they worked in other PC with the same set-up described below:Sonar-runner version: 2.4Sonarqube version:4.5.1Finbugs version: 2.4
|
Sonar - ArrayIndexOutOfBoundsException: 30344 [duplicate]
|
First thanks for your feedback,
There are in fact many questions in your question (sic) :The way to write custom checks for Java as of today is to use theBaseTreeVisitor. All the other ways are now deprecated and we are working to be able to remove them (but it is not always straightforward as some of them requires a complete semantic analysis to be removed). What is currently lacking from this api is the access to the semantic analysis to be able to request type information read from bytecode.
You can have a look at this project :https://github.com/SonarSource/sonar-examples/tree/master/plugins/java-custom-rulesFor all the other questions, please ask them on the mailing list.(Small notes though : BaseTreeVisitor does not use SSLR directly, the java plugin is not moving away from SSLR rather from one class, specificallyASTNode, in order to work on a SyntaxTree with a class specific for each type of node, The drop of Xpath checks occurs in that logic of moving away from a non-typed SyntaxTree).
|
What is currently the best way to write SonarQube 4.5 checks for :Bytecode AnalysisSource AnalysisUnfortunately, I could not find an up-to-date web page providing a clear explanation, and I see that existing checks use many deprecated classes and methods, use "bridges" about to be abandonned, checks are regularly removed from the codebase (such as the XPath rule).I would like to be sure that the checks I'm about to write will be well written and durable.So...should I useBytecodeVisitorto analyse bytecode ?should I useBaseTreeVisitorto analyse sourcecode ?What is the replacement fororg.sonar.api.rules.RuleRepository?What is the replacement fororg.sonar.api.resources.Java?What is the replacement fororg.sonar.api.rules.AnnotationRuleParser?How can I write XPath like rules (BaseTreeVisitoris using SSLR and if I'm not wrong SonarQube is moving away from SSLR /AbstractXPathCheckis part of sslr squid bridge.)What else should I know ?In other words I'm a bit lost.Thank you in advance for your help.
|
What's the right way to write custom checks for SonarQube 4.5
|
You can try this here<project>
...
<build>
<!-- To define the plugin version in your parent POM -->
<pluginManagement>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>sonar-maven-plugin</artifactId>
<version>2.5</version>
</plugin>
...
</plugins>
</pluginManagement>
<!-- To use the plugin goals in your POM or parent POM -->
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>sonar-maven-plugin</artifactId>
<version>2.5</version>
</plugin>
...
</plugins>
</build>
...
</project>the website that has information to help you is thisone here.
|
I have a maven project(POM.xml) having java and Js files.I want to call sonar analysis from Jenkins.Please let me know how can I do to analyse both Java and Javascript files.I have done it for Java using sonar runner but the problem is Javascripts files are in different locations in Project directory.Hence,
sonar.src=src/main/java will not work here.I think I need to go with Maven POM.xml to do the analysis as using POM.xml the project is getting build so analysis may be possible also?1)I know using mvn sonar:sonar is possible but what I need to add in POM.xml for Sonar?
2)What I need to change in MAVEN settings.xml?
3)Please let me know the exact step by step if possible.Thanks in advance!
|
calling Sonar analysis of Java and Javascript from Jenkins using Maven not SonarRunner
|
The computation of the trend is different from the differential periods. It uses the last analyses to guess the evolution of the measure for the given metric. This is why you can have some differences between what you see in the differential periods (depending on what you configured) and the trend icon.If you really want to know how this trend is computed, you can take a loot at theTendencyAnalyser.javaclass in SonarQube source code.
|
The 'Technical Debt and Issues' widget in aSonarqubedashboard includes an issue list broken down by severitye.g. Blocker, Critical, Major etc .The widget display displays a trend arrow(Up, down, no-change)against each issue category.A great feature, but I'd wanted to know how this is calculated for the default view.If you select a time-change category of 'Since Previous Analysis' or 'over 30 days', the answer is self-evident, its the delta in the selected periods. However not sure about the default where no period is selected.Reason for the question is that I have a current project where a couple of categories have downward trends over 'previous' and 'over 30 days', but this isn't reflecting as a downward trend in the default view.
|
'Technical Debt and Issues' widget. How is issue trend calculated
|
I think you should specifysonar.librariesproperty too."Comma-separated paths to files with third-party libraries. This property is used by rule engines during issues detection (mainly the SonarQube and FindBugs engines, which both rely on bytecode)."Details:http://docs.sonarqube.org/display/SONAR/Analysis+Parameters.Or use maven based analyzes that collects the dependencies automatically. But I'm not sure that findbugs can handle this correctly.
|
I am having serious major difficulties configuringSonarQubeto use theFindBugsplugin. I know that this 1) requires the location of the binaries (.class files) to be explicitly defined in the sonar-project.properties file. My problem is that I have a huge amount of source code to scan with binaries located throughout the project. There are also .jars and .war files. Also, the entire project is in a .ear file.I have had success using theFindBugsplugin withSonarQubewhen there is a single source file (.java) and a single binary (.class file). My problems arise when there is more than one binary and more than one class file that are all hidden through the various directories of a large project.My Main Questions:Can anyone tell me how to configure the properties file correctly to specify where to find the binaries? Doesfindbugsneed the location of every single binary or just a few binaries? Can I group all the binaries into one location or do they need a specific directory structure? Should I specify the entire relative path to the binaries or is something different needed?Thank-you for reading this. Also, is it easier to useFindBugswithMaveninstead ofSonar-Runnerto analyse source code for problems?
|
SonarQube with FindBugs Plugin
|
This is a bug on the SonarQube C# plugin side. I have created the following ticket to fix it:https://jira.codehaus.org/browse/SONARFXCOP-29Note that this is not related to the presence of *.pdb files, but only on the presence of the referenced assemblies.
|
I'm trying out the new C# plugin v3.0 with SonarQube 4.2.
According to plugin documentation, I need .pdb files to run analysis which includes FxCop rules, and indeed I get a failure message when executing sonar-runner if said .pdb files are not present in the output folder; FxCop exits with code 1536.The thing is, the analysis seems to require .pdb files for ALL the binnaries, and the output folder contains several dependencies in addition to my own compiled code. These are NuGet packages and I cannot find symbol files for all of them.So, is there any way I can have the analysis to skip the files without debugging symbols?
The regular SonarQube file exclusion lists seem to apply to source code files only (e.g. *.designer.cs) and not for binnaries.
|
C# analysis fails without .pdb files
|
It is not configurable, basically the plug-in does not support this SQALE feature. In fact, the most recent version of SonarQube does not use SQALE anymore.
|
I am trying to run sonar analysis for Erlang. I have downloaded the plug-ins and with 60+ rules, it is able to tell me which part of the source code is not compliant.However, I cannot get the SQALE rating to work correctly, in particular, the technical debt always shows 0.0 days. How do I configure this?
|
SonarQube Analysis for Erlang
|
It is possible to get coverage report with Sonar Emma plugin.
Please follow below link.http://docs.codehaus.org/display/SONAR/Emma+Plugin
|
We measure the code coverage in a gwt project with emma, as described here:http://www.gwtproject.org/doc/latest/DevGuideTestingCoverage.htmlThis works and I get the html report, theemma.emand theemma.ecfile.On sonar I have only jacoco as coverage recording, which doesn't work for gwt unit tests.
But there is the possibility to import jacoco.exec files:sonar.jacoco.reportPathHow can I convert now theemma.emand/or theemma.ecfile to the jacoco.exec format?
Or is it possible to generatejacoco.execfiles directly from emma?
|
code coverage with emma / sonar / jacoco
|
As of SonarQube 4.2, the only way to have some test code analyzed is to activate rules from "PMD Unit Tests" repository inside your quality profile.Note that these are rules specific to test code (like the existence of at least one assertion). You can't activate "standard" rules on test code yet. You can vote for the following ticket to extend the scope of source analysis:SONAR-3748
|
According to the documentation I've found Sonar will not analyse test code by default. I found some Jira's that indicate it should be possible but nothing with enough information on how to do it.It's java code setting under src/test/java. I use both the eclipse plugin for local analysis and sonar-runner plugin for gradle via a jenkins job on the CI server so ideally the solution would support both those.Ta,
Andrew
|
How can I get SonarQube to analyse test code?
|
AFAIK, it is not possible to have Sonar use the Checkstyle definitions from the repository. Isis, however, possible to have Sonar use the current Checkstyle suppression filter from the repository.As for the rules definitions, I think you will have to maintain them in Sonar, and when anything is changed, also change the copy in the repository which is used by eclipse-cs. This is redundant, but at least it affects only one person - the rest of the team can reap the benefits. This approach also enables intentional differences, e.g. when some Eclipse-specific issue is checked (say, something concerning source folders, which don't exist in Sonar).The path to the suppressions filter file can beconfigured in Sonarto refer to the location where your stuff is checked out for Sonar analysis. So that part can be maintained in the repository without any redundancy.
|
My co-workers and I would like to incorporate SonarQube into our existing projects. Our normal development process for Java projects involves running Checkstyle on code changes to ensure they follow our style rules, committing the project to our code repository and having Jenkins build and package the latest version. We’d like to add SonarQube to this final step (through the Jenkins plugin) but we don’t want to duplicate all of our Checkstyle rules in SonarQube, since this would require us to maintain two separate sets of rules and make things more complicated if we need to make changes to the rules. We don’t want to completely switch to SonarQube since we’d like to still run Checkstyle before we commit code to our repository. We’d also prefer to maintain our own Checkstyle files as the main set of style rules as opposed to maintaining the style rules on SonarQube and downloading the generated XML files for our local development.So is there any way to “upload” (so to speak) our existing set of Checkstyle XML files to SonarQube for it to use in its evaluation?Thanks for the help.
|
How to use existing Checkstyle files in SonarQube
|
-1Sonar is complaining about not logging the exact exception.This should make the warning go:LOGGER.debug("All sub merchants have been evicted from cache.", e);
|
my company started using SonarQube.
I am seeing that it complains that code which contains logger is not covered by unit test, for example:LOGGER.debug("All sub merchants have been evicted from cache.");How do we cover by unit test logger?One more code sample:@Override
@TriggersRemove(removeAll = true, cacheName = TRUNCATE_PARAMS_CACHE_NAME,
keyGenerator = @KeyGenerator(name = CACHE_KEY_GENERATOR,
properties = @Property(name = "includeMethod", value = "false")))
public void evictAll() {
LOGGER.info("Evicting all truncation candidates");
}
}Sonar marked the line where LOGGER appears as not covered by unit tests.
|
SonarQube complaining that Logger is not covered by unit test
|
SonarLint, as of now, won't work with third party analyzers like PMD or FindBug, if you are using those, they will simple be ignored.You can update your rules in SonarQube Server to only use rules defined in the SonarQube repository, most of them have an equivalent version.
|
SonarLint v2.0 for IntelliJ is out now, and has this "connect to sonar server" feature, but even so, it seems it isn't in sync with my server rules.http://www.sonarlint.org/intellij/#ConnectedIs it working for someone?
I'm I missing a step?
Or could it be a bug?Thanks!IntelliJ Idea Version: 2016.1
SonarLint Version: 2.0.1
SonarQube Version: 5.4
|
Connected Mode on SonarLint v2.0 on IntelliJ not working?
|
-1According to a previous revision of the question, the OP solved their problem like this:We were using SonarQube 4.0 version. Updating the version to 4.4, made the properties be taken into account.That was in 2014; the current version now is5.5.The steps to upgrade can be foundhere:Stop the old SonarQube serverDownload and unzip the new SonarQube distribution in a fresh directory, let's say NEW_SONARQUBE_HOME.Start it using the default H2 database and use the update center to install the plugins you need.Manually install any custom plugins.Stop the new server.Update the content of the sonar.properties and wrapper.conf files located in the NEW_SONARQUBE_HOME/conf directory with the content of the related files in the OLD_SONARQUBE_HOME/conf directory (web server URL, database settings, etc.). Do not copy-paste the old files.If a custom JDBC driver is used, copy it into NEW_SONARQUBE_HOME/extensions/jdbc-driver/.Back up your database.Remove the data/es directory.Start the new web serverBrowse tohttp://localhost:9000/setup(replace "localhost:9000" with your own URL) and follow the setup instructions.
|
I'm trying to do code analysis of Java unit test using maven sonar plugin. But the plugin doesn't seem to take into account my sonar properties "sonar.*". I've tried to modify simple examples and it did work either. According toMSONAR-70, the issue has been fixed and I'm using the version 2.4.For the test, I've tried it on a simple case:Clonesonar-examples.gituse the projectsonar-examples/projects/languages/java/maven/java-maven-simpleas exampleRenamedsrc/maintosrc/testIn the pom.xml, add to the properties section :<sonar.sources>src/test/java</sonar.sources>
<sonar.binaries>target/test-classes</sonar.binaries>Run mvn sonar:sonar.--> the code analysis didn't took into account my settings. The project is created on SonarQube but code as not been analyzed.If I use the sonar-runner command line, it's analyzing the code:sonar-runner [...] -Dsonar.sources=src/test/java
-Dsonar.binaries=target/test-classes
-Dsonar.language=java
-Dsonar.sourceEncoding=UTF-8
-Dsonar.projectKey=org.codehaus.sonar:example-java-maven
-Dsonar.projectName="Simple Java Maven Project"
-Dsonar.projectVersion=1.0-SNAPSHOT
|
Unit test code analysis using "sonar.*" property and maven-sonar-plugin
|
Starting with Jacoco 0.7.10, it is now possible that Lombok-generated code gets excluded by setting the flaglombok.addLombokGeneratedAnnotationtotruein lombok.config.More onhttp://www.rainerhahnekamp.com/ignoring-lombok-code-in-jacoco
|
SonarQube supports partially Lombok annotations (getters - setters etc). However, it does not still support@[email protected] have tried all answers on StackOverflow and others sites. However, it does not work in my case.Is there any way to say SonarQube or Jacoco, that do not analyze this annotation(s) or do not include them in test coverage results or what would be your solution to this problem?
|
SonarQube does not recognize some Lombok annotations - misleading test coverage results by Jacoco
|
Under the assumption that the question is "why":What do you actuallydowithsession? Nothing.HttpSession session =request.getSession(true); // session assigned
request.getSession().invalidate(); // session NOT used
myApplication.logout();
SecurityContextHolder.clearContext();
session=null; // session re-assignedPerhaps you meant this?HttpSession session =request.getSession(true);
session.invalidate();
myApplication.logout();
SecurityContextHolder.clearContext();BTW, I've droppedsession = nullsince there's no reason in Java (C would be another matter) to do that.Of course, the code could be even cleaner:request.getSession().invalidate();
myApplication.logout();
SecurityContextHolder.clearContext();
|
I have the following piece of code in my program and I am running SonarQube 5 for code quality check on it after integrating it with Maven.However, Sonar is asking toRemove this useless assignment to local variable "session".@RequestMapping(value = "/logoff", method = RequestMethod.GET)
public String getLogoffPage(HttpServletRequest request, HttpServletResponse response) {
logger.info(" Before Log Offf........ " + request.getSession().getId() );
HttpSession session =request.getSession(true);
request.getSession().invalidate();
myApplication.logout();
SecurityContextHolder.clearContext();
session=null;
return "login";
}
|
Sonar complaining about useless assignment of local variable
|
If my understanding is correct, the /api/rules/search web service should cover your need. Seehttps://sonarcloud.io/api/rules/search?languages=javafor the list of Java rules.The API supports many parameters that are documented here:https://sonarcloud.io/web_api/api/rules/search(click the Parameters header above the horizontal line to open the descriptions).For example, the rule_key parameter makes it possible to search for a specific rule. To find information about the S2065 rule (fields in non-serializable classes should not be "transient"), you can use:https://sonarcloud.io/api/rules/search?rule_key=squid:S2065
|
I am trying to find a way to get a list of all Sonarqube rules from a particualar Profile complete with Descriptions and export it as an Excel, csv or xml.
I am able to export a list to xml and convert to excel using the Permalinks option under Quality Profiles but this only provides details on the priorty,key, language and profile name associated with each rule and not anything further like the descriptrion of the rule.I found the following question on the forum which outlines the steps to download the xml file with the details listed but not the description as requiredExport list of coding rules from SonarqubeI also discovered this question which also asks the same question on how to obtain Descriptions on each rule but was unable to get the details requiredsonar quality profile rule export with descrptionI was able to run the command provided in the previous link to obtain some required results by referencing the repositorykey and key_name from the xml obtained under permalinks in the Quality Profiles sectioncurl -X GET -v -u admin:admin "http://[Sonarservername]:[port]/api/rules/show?key=[repositorykey]:[key_name]" --output file.xmlThis command provides the result required (Description of the rule) but there is a requirement to change the repositorykey adn key_name for each rule.
This is not feasible as I need the description for over 550 rulesWhat is requried to get description/rule description text?Please help.
|
Export Sonar Rules with Description to excel
|
If I do not set the field to null, that object may be sent to the second generation and will wait more.If you don't have a finalizerat allthen your object will be eligible for garbage collection earlier, and its fields won't be counted as GC roots, so the other objects may be eligible for garbage collection at the same time.Even if youdoneed a finalizer, unless that finalizer resurrects the object, the finalized object will still be eligible for garbage collection, so its fields won't keep the other objects alive.It's veryveryrarely a good idea to write a finalizer in Java... and if it's just going to set fields to null, that's definitely a bad idea. (It will almost certainlyhurtperformance rather than help it.)
|
When you do something like below,@Override
protected void finalize() throws Throwable {
////////////////////////
this.aVeryBigComponent = null;
////////////////////////
super.finalize();
}Sonar complains aboutBad practice - Finalizer only nulls fieldsfindbugs : FI_FINALIZER_ONLY_NULLS_FIELDSThis finalizer does nothing except null out fields. This is completely pointless, and requires that the object be garbage collected, finalized, and then garbage collected again. You should just remove the finalize method.As long as I know setting a field to null helps garbage collector destroy an object in the first run/generation. If I do not set the field to null, that object may be sent to the second generation and will wait more.What do you think?
|
What do you think about Sonar's Bad practice - Finalizer only nulls fields?
|
Well, Sonar gives an explicit message for the violation: the variable "Pending" does not match the given regexp pattern "^[a-z][a-zA-Z0-9]*$". This pattern means: any string that begins with a lowercase letter, followed by any letters or digits. So your variable should be called "pending", not "Pending".What's more, as Juvanis said, this is the standard naming convention for variables in Java.
|
following line of code in my code segment detected as an Issue by sonar.code segment:final int Pending=1;sonar Issue:Name 'Pending' must match pattern '^[a-z][a-zA-Z0-9]*$'.why sonar detect this as an issue?
|
Solution for following sonar Issue?
|
Make sure you added the jdk binaries to the system PATH, on enviroment variables.C:\Program Files\Java\jdk-x.x.x\bin\java
|
When starting SonarQube (v8.3) it get this error:Unable to execute Java command. Access is denied. (0x5) ... ...
wrapper | wrapper |
------------------------------------------------------------------------ wrapper | Advice: wrapper | Access denied errors when attempting to
launch the Java process are wrapper | usually caused by strict access
permissions assigned to the directory wrapper | in which Java is
installed. wrapper |
------------------------------------------------------------------------ wrapper | wrapper | Critical error: wait for JVM process failedI have set all the permissions that are obvious on the java folderC:\Program Files\Java\jdk-11.0.4This is running on a newly installed Windows 2016 Server.Does anyone have a suggestion?
|
SonarQube - Unable to execute Java command. Access is denied. (0x5)
|
I also tried many options with the Ansibleuricommand with no luck despite being able to use the API viaurifor things like setting Authentication etc.I did succeed however using a parameterisedshell: curlcommand:Set Vars:vars:
sonar_api_url: "https://yoursonarqubeserver.com/api"
sonar_token: "YourSonarQubeApiTokenThatRequiresAdminRights"
sonar_profile: "YourSonarQubeProfileToLoad.xml"Task:- name: POST a SonarQube Profile xml via curl
shell: 'curl -X "POST" "{{ sonar_api_url }}/qualityprofiles/restore" \
-H "Content-Type: multipart/form-data; charset=utf-8; boundary=__X_PAW_BOUNDARY__" \
-u {{ sonar_token }}: \
-k \
--form backup=@{{ sonar_profile }}'Note the API token is passed in as the username with a plank password via the curl -u.I also have asample GitHub repowith a working example you can refer to.
|
SonarQube allows the upload of aprofile.xmlfile via form-dataPOSTrequest as follows:curl -u admin:admin -X POST http://sonar:9000/qualityprofiles/restore -F[email protected]I'm trying to translate thiscurlcommand into Ansible, using theurimodule. Unfortunately, I don't see any chance to map the-Fform-data option and the parameterbackupto Ansible. Here's my attempt:- name: create quality profile
uri:
url: "{{ sonar_api_url }}/qualityprofiles/restore"
method: POST
body: "{{ lookup('file', 'profile.xml') }}"
user: "{{ sonar_admin_user }}"
password: "{{ sonar_admin_pass }}"
force_basic_auth: "yes"
status_code: 200I've also tried something like this:body: "backup={{ lookup('file', 'profile.xml') }}"Or just like this:body: "backup=profile.xml"But all without success. I keep getting the error "A backup file must be provided". Any ideas how this can be achieved?
|
How to use the Ansible uri module to POST a file as form-data?
|
I would do earlycontinueto avoid the repetition ofcommand.execute().
I don't think it's worth to combine the conditions in one or creating another function for its sake.for(Command command : commands) {
if (command instanceof AddCommand || command instanceof UpdateCommand) {
if (isMaturityDateInPast() || paymentDueDate().isAfter(LocalDate.now())) {
continue;
}
}
command.execute();
}
|
My code analysis plugin is complaining about code complexity in the method that contains following code. I noticed following code looks like it could be combined, but I am not sure how to do it:for(Command command : commands) {
if (command instanceof AddCommand || command instanceof UpdateCommand) {
if (!isMaturityDateInPast() && !paymentDueDate().isAfter(LocalDate.now())) {
command.execute(request);
}
} else {
command.execute(request);
}
}I tried introducing boolean variable and setting it in both if and else statements, but that just adds more lines of code.
I am not very good when it comes to logically placing parts of code that have something in common. I can tell thisif-elsecould be combined, but I don't know how to do it. Can someone shed some light?
|
Reducing complexity of code for if-else statements
|
This was finally fixed by the Sonarqube team, starting with the6.7release.
|
Sonarqube keeps marking code with this issue which is, in my opinion, a false positive.
Code looks like this:try(PreparedStatement st=con.prepareStatement(myQuery)){
st.setInt(1, myValue);
...
ResultSet rs = st.executeQuery();
...
}If I'm not mistaken, the PreparedStatement implements Closeable and, when closing itself, it also closes the underlying ResultSet.This behaviour would prevent the ResultSet from being kept open, yet Sonarqube analysis marks it as a critical error.Am I mistaken?
Any way of making Sonarqube ignore this ruleunder this circumstances?Tested under Sonarqube 6.7.3 and JDK 8.From theResultSetjavadoc:A ResultSet object is automatically closed when the Statement object that generated it is closed, re-executed, or used to retrieve the next result from a sequence of multiple results.
|
Sonarqube false positive for "Use try-with-resources or close this "ResultSet" in a "finally" clause"
|
Although you can return null, you shouldn't, at least according tosquid: S2447Whilenullis technically a validBooleanvalue, that fact, and the distinction betweenBooleanandbooleanis easy to forget. So returningnullfrom aBooleanmethod is likely to cause problems with callers' code.If you disagree you can disable it locally:return null;//NOSONAROr deactivate this rule entirely in settingsAlso discussed insonar group:Many rules also criticize things that I personally do not find bad i.e. "Null should not be returned from a "Boolean" method (squid: S2447)". So I can probably give no good tips.andSonar communityQuestion:I suggest that there should be an extra rule for it.So a Boolean should not be checked like this:Boolean flag = service.getFlag();
// that's the unsafe call which could cause a null pointer exception
if(flag) {
// do something
}Answered:Instead of introducing a new rule, what about using S2447:Nullshould not be returned from aBooleanmethod 1 that prevents a method returning aBooleanobject to return anullvalue?
|
How I can edit this code block as a readable or logical way so that I don't get a warning from sonar?
I need three resultfalse,trueornullpublic Boolean x() {
if (...) {
return true;
} else if (...) {
return false;
} else {
return null;
}
}
|
Java Sonar Null Caution "null returned but Boolean expected"
|
You can usesquid:S2253, which is a template rule, to set up a rule that raises an issue when your method is called.
|
I use SonarQube for a Java project.I want to have a violation when a given static method from a library is used.Is there a way to do that in the UI, or shall I resort to custom java code as described inhttps://github.com/SonarSource/sonar-custom-rules-examples/?
|
SonarQube - Custom rule to prevent call to some static methods
|
I think this could also be due to problems in the indexing service.. can you try deleting /data/es folder and restart sonar server and see if it fixes the issue?
|
I installed SonarQube 5.1 on a Linux server and ran some java project analysis. In the project dashboard, the issues (blocking, critical, major) are visible. If I click on one of the issue counts, the component_issues page is open but on the left side, all the indicators are zero.In the log there is nothing relevant.
|
SonarQube 5.1 shows no issues when going to detail
|
The method declaration syntax for interfaces is covered in theJLS, section 9.4.Briefly, method modifiers must precede the method header, which includes the method's return type. Your declaration has one method modifierdefaultand its return type isbooleanso there is no other possible arrangement in this declaration other thandefault boolean isValid(/*parameters*/) { /*body*/ }Therefore I think this must be a bug in Sonar.
|
I just started using Sonar and I have a project with JDK 8. The only problem I've got so far is:Reorder the modifiers to comply with the Java Language Specification.This is happening for my default methods in interfaces, likedefault boolean isValid([params here]) {
/*method body here*/
}I know that this is really a minor issue, but I don't want to disable any rule, so how do you fix it?Thank you very much!p.s. I haven't found anything on Google, I know what this rule means(I have read its description), but I cannot figure out how to deal with default keyword.Update: It looks like a bug, I have reported it here,https://jira.codehaus.org/browse/SONARJAVA-590Update 2: It seems it's already fixed and it will be available in 2.4 version.
|
Sonar rule - Reorder the modifiers for interface default methods
|
I fail to understand your reasoning: in the first snippet, you usesortedPolygons.remove(key2);to remove a key. Nothing prevents you to do the same in the second snippet:sortedPolygons.remove(entry.getKey());Whatever the way you iterate, this will lead to aConcurrentModificationExceptionanyway, because for most collections, you can't modify it while iterating on it, except by using its iterator.Quote fromthe javadoc:The iterators returned by the iterator method of the collections returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException.So the code should be:for (Iterator<Map.Entry<Double, Polygon>> it = sortedPolygons.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<Double, Polygon> entry = it.next();
if (entry.getValue().getExteriorRing().equals(hole)) {
it.remove();
// if you want to exit the loop as soon as you found a match:
break;
}
}
|
This a a similar question to [FindBugs warning: Inefficient use of keySet iterator instead of entrySet iteratorHowever, there I am trying to do something a little different. My current code is here:for (Double key2 : sortedPolygons.keySet()) {
if (sortedPolygons.get(key2).getExteriorRing().equals(hole)) {
sortedPolygons.remove(key2);
break;
}
}Doing something like the solution in the link does not work. Here is an implementation of said solution:for(Map.Entry<Double, Polygon> entry : sortedPolygons.entrySet()) {
if (entry.getValue().getExteriorRing().equals(hole)) {
.....The problem here is that I am trying todeletethe entry. There is noentry.remove(). How can I replace my first block of code, without the FindBugs error:Inefficient use of keySet iterator instead of entrySet iterator->This method accesses the value of a Map entry, using a key that was
retrieved from a keySet iterator. It is more efficient to use an
iterator on the entrySet of the map, to avoid the Map.get(key) lookup.To note, the underlying structure isTreeMap, and it cannot be changed.
|
FindBugs warning: Inefficient use of keySet iterator
|
The issue here is that you haven't specified an encoding for the file, which means that the file will be read with your system's default encoding. This means that the behaviour of the code could vary from system to system.You should explicitly state the file's encoding, for example,new InputStreamReader(
new FileInputStream(
properties.get(FILE_BASED_CONFIGURATION).toString()), "UTF-8")This reads the file with aFileInputStream(which reads bytes from a file), then wraps this in anInputStreamReaderwhich converts those bytes to characters using the stated encoding.
|
Below mentioned Code snippet gives Sonar comment with following squid rule:squid:S1943try(BufferedReader reader = new BufferedReader(**new
FileReader**(properties.get(FILE_BASED_CONFIGURATION).toString())))
{
//some code
}
catch (IOException | ArrayIndexOutOfBoundsException e)
{
LOG.error("Exception while reading from File", e);
//customerInfo.clear();
}[SONAR] MAJOR: Remove this use of constructor "FileReader(String)"
|
SonarQube issue with New FileReader
|
You check, thatdir.list()is not null. Afterwards you do other calls todir.list(), and assume, that is cannot be null in this case.SonarJava tries to tell you, that even thoughdir.list()has not been null in the first place, it could have turned null for the second/third call.To solve this issue:save the result ofdir.list()in a variablecheck that the variable is not nulluse the variableThis is also know as theextract variablerefactoring, and it has additional good effects. If you don't expect the result ofdir.list()to change between calls, then you will improve the performance as well, since the program doesn't need to access the filesystem again to produce the content of the directory.
|
Possible null pointer dereference error in this code:if(!Util.isNull(dir)){
if (dir.isDirectory()){
if(!Util.isNull(dir.list()))
if((!Util.isNull(dir.list().length))) // issue reported here
if(dir.list().length == 0) // another issue reported here
if (dir.delete())
LOGGER.info("deleted:");
}
}How can I fix these issues?
|
SonarQube shows Possible null pointer dereference
|
Analysis happens in two steps:A SonarQube Scanner runs on your code, compiles an analysis report, and submits it to the serverThe analysis report is processed on the server side and the project updated in the databaseStep #1 happens synchronously. Step #2 happens asynchronously.When an analysis/report is inPENDINGstate on the server side, it means that it is queued and waiting to be processed.When an analysis/report moves toIN_PROGRESS, it means it has reached the head of the queue, been popped off, and is being integrated, server side. This integration doesn't happen instantly; there are aggregated metrics to compute and the database to update. Depending on the size of the project and the resources available to the server this could happen very quickly or take a few minutes.To see what's going on in the processing queue, take a look atAdministration > Projects > Background Tasks
|
I ran sonarqube by using Jenkins with maven build.
When it build success, but I can not see report on sonarqube web page.
Like this,,, build succeeded[INFO] ----------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 18:21 min
[INFO] Finished at: 2017-02-15T10:44:14+09:00
[INFO] Final Memory: 17M/114M
[INFO] ------------------------------------------------------------------------
Waiting for Jenkins to finish collecting data
[JENKINS] ArchivingWhen I went to url in log
- INFO: More about the report processing athttp://127.0.0.1:9000/sonarqube/api/ce/task?id=AVo_WHJYU5rNTJ7ZmiZq{"task":{"id":"AVo_WHJYU5rNTJ7ZmiZq","type":"REPORT","componentId":"AVk906UDu6xeCo3BQ_gU","componentKey":"online","componentName":"AMIS3-Online","componentQualifier":"TRK","status":"PENDING","submittedAt":"2017-02-15T10:17:46+0900","submitterLogin":"admin","logs":false}}What is the status Pending?..
Build succeeded, but Why status is pending??
And I can not see Report in sonarqube webpage..Thank you in advance...
|
What is sonarqube status PENDING, IN_PROGRESS?
|
Access control in SonarQube is managed through Global Permissions and Project Permissions. Each permission can be granted to user(s) and/or to group(s). The documentation you pointed at is quite outdated, read theAuthorization pagefor the most up to date details.AD/LDAP integration is a different topic, documentedhere. Withgroup mapping, group membership stays managed in AD but will be replicated in SonarQube when users log in (the AD groups must first be created in SonarQube with the same name).To your example: if AD users belonging to groupfoodeserve to administer your SonarQube, just create groupfooin SonarQube, and (in the Global Permissions settings) giveAdminister Systempermission to groupfoo.
|
I am new to SonarQube and trying to setup up a proper access control, with requirements as follows:We have a few project areas, each area should have someone able to
manage their area, such as creating new projects and manage the
boards, not sure exactly what. This is something like project area
administrators.A few administrators can do anything.Integrate to ADA few questions:In a few places like this link:http://www.sonarsource.com/products/features/security/, I see this role based method, but I can't find these default roles, "SonarSource products come with three project-specific roles – project administrators, project users and project code viewers" anywhere in the system. Right now, I am using the community edition I guess without a license. Is there any more detailed document on that?I kind of understand the default Global Permissions and Project Permissions. In my case, shall I create e.g. three groups in AD, sonar-administrators,sonar-project-administrators, sonar-users to map to the default groups?I notice the following: right now I don't have the above AD groups, when I integrate to AD, I can login with my domain id/password, but once logout/in, the group information I added to the local user gone. I guess it sych with AD. So to use AD, I have to create these groups in AD?Jirong
|
How to do role based access control with SonarQube?
|
I believe what it's trying to tell you is to log theExceptionas it is, not thetoString()version, likehere, also adding some 'context' or information to thelogfor (String QT : Q_T) {
try {
// some logic
} catch (JsonParseException e) {
LOG.log(Level.SEVERE, "context", e);
} catch (JsonMappingException e) {
LOG.log(Level.SEVERE, "context", e);
} catch (IOException e) {
LOG.log(Level.SEVERE, "context", e);
} catch (Exception e) {
LOG.log(Level.SEVERE, "context", e);
}
}
|
This is my method, when I try to analyze my code by sonarQube am getting this error:Exception handlers should preserve the original exception : Either log or rethrow this exception.Why am getting this error, should I not catch the exception like my method?my method :for (String QT : Q_T) {
try {
// some logic
}
} catch (JsonParseException e) {
LOG.log(Level.SEVERE, e.toString());
} catch (JsonMappingException e) {
LOG.log(Level.SEVERE, e.toString());
} catch (IOException e) {
LOG.log(Level.SEVERE, e.toString());
}
catch (Exception e) {
LOG.log(Level.SEVERE, e.toString());
}
}
}
|
Exception handlers should preserve the original exception : Either log or rethrow this exception
|
Indeed since SonarQube JavaScript PLugin version 1.5 it is not possible to import unit test results. See sectionRelease Notein SonarQube documentation.This feature might be reintroduce in future version.
|
I am following this tutorial -http://blog.dasberg.nl/getting-your-frontend-code-quality-in-order/- to push the front end quality metrics to SonarQube. I was able to reuse the coverage report generated by Karma in Sonar but I don't see the section for "unit test success" at all.
This is how it looks in the sonar4.2 on my workstationand this is my sonar properties file# Required metadata
sonar.projectKey=org.rj.js:javascript-build-process
sonar.projectName=javascript-build-process
sonar.projectVersion=1.0
# Comma-separated paths to directories with sources (required)
sonar.sources=src/js
# Language
sonar.language=js
# Encoding of sources files
sonar.sourceEncoding=UTF-8
sonar.dynamicAnalysis=reuseReports
sonar.junit.reportsPath=coverage/junit
sonar.javascript.lcov.reportPath=coverage/PhantomJS 1.9.7 (Mac OS X)/lcov.info
sonar.verbose=trueAlso the log doesn't show any warnings or errors. Am i missing anything else here?
|
why am I not seeing "unit test success" section of "unit tests coverage" widget in SonarQube
|
I gather that you want to avoid using integer literals in the code. Your solution is not particularly effective because it simply moves the literals to the top of the method. It gains a little bit because it gives meaningful names to the constants, but these names are private to the method.A better approach would be to define the numbers as fields in an interface. You can then statically import the fields and use them as symbolic names for the constants.If the enum is declared in the same order as the constants:enum UserStatus {PENDING, ACTIVE, SUSPENDED, DELETED, LOGIN_DISABLED}you can do another trick:public static UserStatus getEnum(int code) {
UserStatus[] values = UserStatus.values();
return (code >= 0 && code < values.length) ? values[code] : null;
}However, this creates a linkage between the constant values and the declaration of the enum. This may be okay, depending on where the actual parameter values are generated in calls togetEnum.
|
Consider the following code segment...public static UserStatus getEnum(int code) {
switch (code) {
case 0:
return PENDING;
case 1:
return ACTIVE;
case 2:
return SUSPENDED;
case 3:
return DELETED;
case 4:
return LOGIN_DISABLED;
default:
return null;
}
}Now number 3 and 4 in cases(case 3 and case 4) are detected as magic numbers by SONAR.To avoid that issue I changed my code segment as follows...public static UserStatus getEnum(int code) {
final int Pending=0;
final int Active=1;
final int Suspended=2;
final int Deleted= 3;
final int Login_details=4;
switch (code) {
case Pending:
return PENDING;
case Active:
return ACTIVE;
case Suspended:
return SUSPENDED;
case Deleted:
return DELETED;
case Login_details:
return LOGIN_DISABLED;
default:
return null;
}
}Is this a good way to solve the magic number issue in this kind of scenario ?.
|
Solution for Magic Number issue......?
|
Our tool,SourceMeterhas aplug-in for SonarQubethat can list the most complex methods. It provides widgets for method level metrics. You can check it outhere.
|
I have installed sonar 2.12. Going to Violations > Major > Cyclomatic Complexity I can see the number of methods with CC over 10, but I need to go method by mehod to see its actual CC. I wonder if there a way to see a list of the methods with most CC?
|
how to list methods with most cyclomatic complexity
|
Try with/d:sonar.exclusions=<value>. The text box in Jenkins expects command line arguments for Scanner for MSBuild, which are in the form/d:<sonar.property>=<value>.Thesonar.exclusionsproperty is not very intuitive, because the filter is applied separately for each project and is relative to the project root, not the solution root (and you cannot use..to go back to the solution)...Perhaps a better option to exclude a single project from analysis is to put the following within the.csprojfile itself:<PropertyGroup>
<!-- Exclude the project from analysis -->
<SonarQubeExclude>true</SonarQubeExclude>
</PropertyGroup>
|
We have a Visual Studio solution containing 10+ projects including ASP.NET Web project. Created a Jenkins Jobs and configured with SonarQube to show code coverage metrics, and the job runs successfully.When tried to narrow down the focus while calculating code coverage metrics (excluding ASP.NET Web Projects) using the below argument then getting an error-sonar.exclusions="\ASP.NET PROJECT NAME*"Error- Unrecognized command line argument: sonar.exclusions=\*Already referredNarrowing the FocusandExcluding projects from the MSBuild Runner without changing csproj filesCould anyone please suggest with actual syntax- how to exclude projects from 'SonarQube Scanner for MSBuild- Begin Analysis’ plugin in JenkinsThanks!! Any lead is much appreciated
|
How to exclude few .NET projects from ‘SonarQube Scanner for MSBuild- Begin Analysis’ plugin in Jenkins
|
You can pass any valid directory as the value ofsonar.java.binaries, for example:mkdir /tmp/empty
mvn sonar:sonar -Dsonar.java.binaries=/tmp/emptyThis will bypass the problem raised by the Java analyzer,
but keep in mind that the analysis results won't be perfectly accurate.
It's very common to have some false positives when the analyzer doesn't have access to the bytecode binaries.
|
I have a java codebase I need to scan in sonarqube, but when I run the scanner I get:Please provide compiled classes of your project with sonar.java.binaries propertyI don't have the classes; the code I was given wasn't compiled. It's also a pretty complex application and I don't really have time to figure out how to build it myself. Is there a way I can force the analysis to run without any binaries available?Thanks for any help/ideas!-Jason(Also, I ran sonarqube 5.x last year on java code, and definitely did not have to use classfiles for that analysis. I figured this was a new "feature" for version 6, but the documentation says this has been since version 4.12 (?!)
|
How do I disable the byetcode requirement for scanning Java projects in sonarqube 6.5.0.27846?
|
In the above class,SonarQubeis trying to say thatDATE_FORMATTERdoes not need to be static if it is not used by anystaticmethod.In fact,SimpleDateFormatshould not be an instance variable as well, as it's not thread safe (explainedhere). If multiple threads are accessing methods ofTimeAclass simultaneously then it will lead to incorrect result.If the format is same then you can declare it as afinal Stringand createSimpleDateFormatinstances locally, e.g.:public final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";
public void someMethod(){
SimpleDateFormat df=new SimpleDateFormat(DATE_FORMAT);
df.setTimeZone(TimeZone.getTimeZone("GMT"));
//Further processing
}
|
SonarQube 5.5 (with thesonar-java-plugin-3.13.1.jarplugin) reports an issue on this code:public class TimeA {
public static final SimpleDateFormat DATE_FORMATTER;
static {
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
DATE_FORMATTER=df;
}
}The error message isMake "DATE_FORMATTER" an instance variable.How can I avoid this SonarQube issue?
|
How to resolve the "Make field an instance variable" issue?
|
You can use theconnected modeto bind your project in the IDE to a project in SonarQube.SonarLint will use the same code analyzers and rules as the ones in SonarQube.In SonarQube, it's possible to change the quality profile assigned to projects and in this way, toenable or disable rules.More information:https://www.sonarlint.org/intellij/howto.html
|
I am developing a Java application and Using SonarLint to test the code quality.
Sonar shows the error :Take the required action to fix the issue indicated by this comment.For below line of code:// FIXME: temp here until we drop tomee or remove all exceptions from ejb <-> non-ejb path.Is there any way I can suppress the warning in SonarLint ?
|
How to suppress warnings for FIXME comment in Java
|
You should have a look at the sonar-gitlab-plugin project :https://gitlab.talanlabs.com/gabriel-allaigre/sonar-gitlab-pluginEdit: As for the GitHub plugin mentioned in a previous answer, the GitLab plugin will analyze new code that is pushed to the Git repository. So the analysis happen after having commited and pushed your work to the repository.
|
I have already set up SonarQube, Sonar Runner and Jenkins latest versions on my local machine (Ubuntu 14.04 LTS desktop version).I want to know how we can integrate these with git (GitHub or GitLab).
When we push the code to git we want to previously analyse it and after this automatically commit it into Git.What should I do?
|
How to configure SonarQube, Sonar Runner, GitLab and Jenkins to obtain Continuous Integration
|
Try this:Login into Sonar as administratorClick on 'Rules'and select C#Under Repository section search for FxCop and add it (it should show a certain number of rules)With C# and FxCop selected, click on 'Bulk Change' or 'Settings icon' (depends on which version of sonar you're running), and select 'Activate in.."In the search box that appears, add the sonar profile you want to activate these rules in (e.g. Sonar Way), and select Apply
|
Executing Sonar (version 4.5.4) analysis on a C# sln using the C# built in plugin (version 4.0).
I've set in the settings the location of the FxCopCmd.exe, but I get the following in the execution:
"All FxCop rules are disabled, skipping its execution"
How do I enable the rules?Thanks,Ariel
|
Unable to execute FXCop analysis in SonarQube
|
The new update URL is:http://downloads.sonarsource.com/eclipse/eclipse/This will be updated on the Eclipse Marketplace.
|
Codehausis shutting down its services, including the Eclipse Plugin of SonarQube. Does anyone know whether there is already a replacement for the P2 repositoryhttp://dist.sonar-ide.codehaus.org/eclipse/?Thanks
|
SonarQube P2 repository has gone forever
|
I would say, the most likely explanation is that your OwnBeanException extends RuntimeException, which would explain why it's redundant. RuntimeExceptions (including all classes extending it) are per definition unchecked, declaring them via throws doesn't make sense.All possibilities, according to thedocumentation:An exception in a throws declaration in Java is redundant if:It is listed multiple timesIt is a subclass of another listed exceptionIt is a RuntimeException, or one of its descendants
|
I've defined a function in an interface that throwsmy own exception. When I run Sonar it says it a redundant throw. How can I solve this little problem?This is the definition of the function:OwnBean getOwnBean(Integer code1, String code2) throws OwnBeanException;Thanks for your help!More info:I've managed to get more information about this.The exception is a descendant of other exception that at the end is descendant ofException.The messagge I get is"Unable to obtain the information of class OwnBeanException".
|
Sonar says i have a redundant throw in an interface
|
Steps to set environment variables for SONAR_RUNNER_HOMEOpen your environment variables window.
Click new button in System variables section.Set a variable name SONAR_RUNNER_HOME and its value should be the unzipped path of sonar-runner zip file.Example:-
variable name:- SONAR_RUNNER_HOME
variable value:- C:\Program Files (x86)\sonar-runnerAnd then append sonar-runner's bin path %SONAR_RUNNER_HOME%\bin to the environment variables path.Example:-
variable name:- PATH
variable value:- %SONAR_RUNNER_HOME%\bin;
|
I am working on eclipse helios and windows 7.I dont know
1.What needs to be added as a seperator, like ";" , "%" and where?
2. Which directory path of Sonar is to be assigned to the path?In short I need whole procedure for setting the SONAR_RUNNER_HOME in windows.
|
How to create environment variable SONAR_RUNNER_HOME for sonar (eclipse ) in windows 7
|
The correct way is adding a local analysis property in the sonar plugin configuration:sonar.buildbreaker.skip=trueThis way the sonar analysis during build willl break by the build breaker plugin, in the meantime developer can analyze and fix issues locally in Eclipse before check-in.
|
When enable build breaker plugin in sonarqube, I found there is no way to run local analysis anymore, because the analysis finishes with failures. And no detail issue list is available. It blcoks usage of the plugin, as developer cannot examine locally whether their check-in may break the build before submitting their changes, but if the change is submitted the build will break...
Currently what I can imagine is installing another server for local analysis by disabling build breaker plugin, but it brings other issues like synchronizing configurations between two different sonar instances. Any better idea?Best Regards,
|
SonarQube BuildBreaker plugin blocks local analysis
|
Found the solution, added-DskipTests=truewith maven command.The full command which works for me is :mvn clean install -DskipTests=true -Dmaven.test.failure.ignore=true sonar:sonar
-Dsonar.database=mysql
-Dsonar.jdbc.driver=com.mysql.jdbc.Driver -Dsonar.jdbc.url=jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8
|
I have installed sonar and trying to analyze maven based application using following command :clean install -Dmaven.test.skip=true -Psonar sonar:sonarstill its executing test-cases.What if I doesn't want the analysis of unit test cases?
|
Ignore test cases while running maven project with sonar
|
You can use Java'sObjects.equalsto check equality of fields easily. It will returntrueif both given objects are equal or both arenull, elsefalse.if (this == obj) return true;
if (obj == null || this.getClass() != obj.getClass()) return false;
Bean other = (Bean) obj;
return Objects.equals(this.property1, other.property1)
&& Objects.equals(this.property2, other.property2)
&& ...;As an alternative there's Apache CommonsEqualsBuilderwhich also provides areflectionEqualsmethod that automatically gets all fields from your class and compares them. Though this approach might be slower because of reflection and you have less control over what's happening.
|
I want to reduce cognitive complexity of the following method. How to do it ? To my point of view, I can't, but I am unexperienced in the matter@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (!(obj instanceof Bean)) return false;
Bean other = (Bean) obj;
if (property1== null) {
if (other.property1!= null) return false;
} else if (!property1.equals(other.property1)) return false;
if (property2== null) {
if (other.property2!= null) return false;
} else if (!property2.equals(other.property2)) return false;
if (property3== null) {
if (other.property3!= null) return false;
} else if (!property3.equals(other.property3)) return false;
if (property4== null) {
if (other.property4!= null) return false;
} else if (!property4.equals(other.property4)) return false;
return true;
}
|
How to reduce cognitive complexity of a method
|
You could define an interface, sayProductTypeCreatorpublic interface ProductTypeCreator {
boolean isApplicable(String val1, String val2, String val3);
ProductType create(String val1, String val2, String val3);
}Then, create an implementation for each specific if case.
You could then have a List creators, and refactor your method to something like.public ProductType createProductType(String val1, String val2, String val3) {
// this should already be instantiated
List<ProductTypeCreator> creators;
return creators
.stream()
.filter(creator -> creator.isApplicable(val1, val2, val3))
.map(creator -> creator.create(val1, val2, val3))
.findFirst()
.get();
}In this way, you could avoid the ifs.Hope this helps!
|
I have to fix sonar issue related to big cyclomatic complexity, but still haven't got any good idea how to do that.The code consist of big amount of 'if' operators that are check parameters that came in method and decide which enum value to createHere is a code snippet for example:public ProductType createProductType(String val1, String val2, String val3) {
if (PRODUCT_MODEL.equals(val1) && PRODUCT_TYPE.equals(val2) {
return ProductType.SOAP;
}
if (PRODUCT_MODEL.equals(val1) || val3.equals(SWAP)) {
return ProductType.STRING;
}
}And so on..
As you can see I am not able to write this using switch case because there are more than 1 variable is checked.
Also I can't create static map with keys of Predicate type because comparing criteria came to method dynamically.
So I can't understand how to eliminate this 'if' operators.Any suggestions?EDITif divide it into methods for each product type how then I will check when the product type is created?
I mean I haveProductType productType = null;
productType = tryParseSoap;
if (Objects.nonNull(productType)) {
return productType;
}
productType = tryParseString;
if (Objects.nonNull(productType)) {
return productType
}if do this I still have a lot of if cases for null-checking
because without them suggest product created on the first check and then I will anyway check it a lot of times and this is a big productivity reducing
|
Reduce cyclomatic complexity issue
|
Currently it is not possible to "amend" coverage to an existing analysis. You have to orchestrate your build pipeline so that all kind of coverage reports are produced before you actually starts the SonarQube analysis.
|
For Java I know the possibility to merge test coverage results on build level by specifying the same path of JaCoCo reports (seeSonarQube: Multiple unit test and code coverage result files). This might be transported to SonarQube.But is it possible to make this on SonarQube level?I mean from different build servers or different jobs build and test software and combine coverage results at SonarQube side (perhaps by marking the SW version or any kind of given label)?For me it would be usefull to combine integration and unit tests.
|
Is it possible to merge test coverage on sonarqube level?
|
You should move the@NotNullannotations to the constructor and setter parameters:public Dummy(@NotNull Integer dummyField) {
this.dummyField = dummyField;
}
public void setDummyField(@NotNull Integer dummyField) {
this.dummyField = dummyField;
}If you verify that all possible mutators of that value only set it to non-null values, it's the same effect as stating that the value itself must be non-null - butshouldavoid the spurious warning
|
Consider the below code. When I analyze the code for sonar rule, it complains about"javax.validation.constraints.NotNull" but is not initialized in this constructor.I can resolve it by initializing the field with default value (see example here) but it will make @NotNull annotation redundant. So my question is how to resolve this problem in best possible way.public class Dummy {
@NotNull(message = "Dummy field cannot be null")
private Integer dummyField;
public Dummy(Integer dummyField) {
this.dummyField = dummyField;
}
public Integer getDummyField() {
return dummyField;
}
public void setDummyField(Integer dummyField) {
this.dummyField = dummyField;
}
}
|
What is the best way to handle SonarQube error "javax.validation.constraints.NotNull"
|
SonarJava, the Java plugin for SonarQube, has a rule explicitly targeting magic numbers. See its description here:S109 - Magic numbers should not be used.There is also a rule which is going to ask you to define constants instead of using multiple time the same string, but only when used in the same file (like already mentioned in the other answer) (S1192 - String literals should not be duplicated). Consequently, it is not going to flag any string constant used only once in the body of any methods, nor identify duplicated constants spread across multiple files.If you desperately need to track usage ofallthe string constants in your project(s), the best way would be to write your own rule targeting them, as part of a custom plugin (SeeWriting Custom Java Rules).Now, if you want to benefit from these rules, the only thing you have to do is to setup the analysis of your project in order to perform a SonarQube analysis of your code, and be sure that all the rules you need are enabled, as they are not all part of default quality profile (SeeSonarQube, orSonarCloudwebsites for details about setup).
|
Is there a way to find all hard coded numbers and strings in Java?
I mean values which have not been placed into dedicated variables.For example :while (i < 6) {
System.out.println("6 is a number"); // Hard Coded, "Magic" String
}I got suggestions on SonarQube but I have no idea how to use it.
|
Finding Hard Coded (Magic) numbers and Strings
|
Eugene's answer is pretty good, but you can go step further and use the same logic inside enumenum HeaderField {
AUS(HeaderDTO::setAudval),
AXL(HeaderDTO::setAxlfieldl);
private BiConsumer<HeaderDTO, String> fieldSetter;
HeaderField(BiConsumer<HeaderDTO, String> setter) {
fieldSetter= setter;
}
public void setField(HeaderDTO headerDTO, String value) {
fieldSetter.accept(headerDTO, value);
}
}Then you can use it:HeaderField.AUS.setField(headerDTO, "value");
HeaderField.AXL.setField(headerDTO, "axl");
|
I have 139 switch cases in setHeaderprivate static void setHeader(String headertableField, String headerValue) {
switch (headertableField) {
case AUS:
headerDTO.setAudval(StringUtils.getTrimValueAfterNullCheck(headerValue));
break;
case AXL:
headerDTO.setAxlfieldl(StringUtils.getTrimValueAfterNullCheck(headerValue));
break;
................
..................
default:
break;
}
}It shows sonar issues. Can you please suggest any solution to reduce complexity.
|
The Cyclomatic Complexity of this method "setHeader" is 139 which is greater than 10 authorized
|
Theapi/resourcesdoesn't support thekeyparameter. You have to specify project id by usingqualifiersandresourceparameters.This should work for you:https://mysonar/api/resources/index?metrics=coverage&qualifiers=TRK&resource=test-projectAvailable values of thequalifiersparameter:VW: viewSVW: sub-viewTRK: projectBRC: moduleUTS: unit testDIR: directoryFIL: fileDEV: developer
|
Sonar version : 5.3I am making this callhttps://mysonar/api/resources/index?metrics=coverage&key=test-projectHowever , I am not getting the coverage of test-project from this call.
But I am getting rest of the projects and their coverages.
When I just do thishttps://sonaraws.kdc.capitalone.com/api/resources/indexI am able to see my test-project on the api response.How do I drill down to a specific project and not check the other projects from the rest call to Sonar.
|
Check the code coverage for a project on sonar with rest api
|
Use single quotes in your "SONARQUBE_JDBC_URL" environment variable. I just tried to delimit that particular variable so that docker understands it as a complete string with it's starting & ending point. Due to some reason, it was unable to fetch the IMAGE_NAME argument which was required to run the container.docker run -d --restart=always --name sonarqube -p 9000:9000 -p 9092:9092 -e SONARQUBE_JDBC_USERNAME=my_user_name -e SONARQUBE_JDBC_PASSWORD=my_password -e SONARQUBE_JDBC_URL='jdbc:postgres://host:[email protected]:5432/database?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory' sonarqubeThis worked for me.
|
I'm running a docker container; it's sonarqube: When I use this command:docker run -d --restart=always --name sonarqube -p 9000:9000 -p 9092:9092 sonarqubeThe container runs well, but when I use the command to run and to configure the database, this command:docker run -d --restart=always --name sonarqube -p 9000:9000 -p 9092:9092 -e SONARQUBE_JDBC_USERNAME=my_user_name -e SONARQUBE_JDBC_PASSWORD=my_password -e SONARQUBE_JDBC_URL=jdbc:postgres://host:[email protected]:5432/database?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory sonarqubeI'm getting this error:"docker run" requires at least 1 argument.
See 'docker run --help'.
Usage: docker run [OPTIONS] IMAGE [COMMAND] [ARG...] [flags]
Run a command in a new containerWhat is wrong? or How to fix this little problem?
|
Sonarqube doesn't work on Docker
|
Sonar Scanner is a program that connects to a SonarQube server, downloads analyzers and active rules, runs the analyzers locally on your source code, and finally pushes the analysis results to SonarQube, so that you can manage the quality of your source code on SonarQube.SonarLint is designed to analyze files as you work on them in your IDE (VS2015 in your case). It does not produce analysis reports and does not push them to SonarQube server. Not even in connected mode. The purpose of connected mode is to use the same analyzers and same rules as configured on SonarQube. Pushing analysis reports to the server is out of the scope of SonarLint.In short, if you want to see analysis results on SonarQube and manage the quality of your software, you cannot skip the Sonar Scanner.
|
I have installed Sonar Scanner and Sonar Qube and i am running code analysis with Sonar Scanner and i can see the results on Sonar Qube server in bowser. Also,I have SonarLint added in my VS2015 and i am using connected mode with my sonar qube server. And i run analysis with sonar lint also locally.
|
Can i run analysis with sonarlint and see the same on sonarqube server without involving sonar scanner at all
|
You do not. Starting with SonarQube 6.5 default profiles are not editable. Instead, make a new profile andcopy the Sonar way rules into it. Then you'll be able to edit your copy.If after each upgrade you want to make sure you haven't missed any exiting new rules, justcompare your copy with Sonar wayand edit your profile to handle the differences.
|
I have the default profile for Java in SonarQube called Sonar way.When I try to deactivate any rules in it, there is no way I can do it.How do I specifically disable rules for this profile?
|
SonarQube: How to deactivate rules in a default Quality Profile?
|
There used to be a rule for this:Rule S1607: Tests should not be ignored(old)However this rule was updated and now actually allows ignored Tests, if appropriatly commented:Rule S1607: JUnit4 @Ignored and JUnit5 @Disabled annotations should be used to disable tests and should provide a rationale(new)
|
I'm concerned about some developers who usually ignore failing tests with @Ignore to bypass SonarQube static verification.For that I'm looking a rule that creates issues.Does anybody know how I could achieve this?I'm using SonarQube 5.4 and JUnit.
|
Sonarqube rule for JUnit @Ignore
|
Go toGeneral Settings > Generaland set "Cross project duplication detection
" to true.You can also set it directly in your config file.sonar.cpd.cross_project = true
|
In SonarQube how to detect copy pasting between projects?There is CPD analysis running for every module
|
SonarQube - How to detect copy pasting of code between projects?
|
You're likely missing thesonar.organizationanalysis property. You should be able to get the value from the Organization Key field on your project home page. If your project doesn't exist on the server yet, you can get it by logging in then:My Account > Organizations
|
I have a Sonarcloud account and I'm trying to analyze a Visual Studio solution using SonarQube.Scanner.MSBuild.exe. I've created a token and am passing that on as the sonar.login property in the SonarQube.Analysis.xml file.
I'm usinghttps://sonarcloud.ioas sonar.host.url, but I've also triedhttps://sonarqube.com.Here is the relevant snippet of the configuration:<Property Name="sonar.host.url">https://sonarcloud.io</Property>
<Property Name="sonar.login">***my*token****</Property>
<Property Name="sonar.password"></Property>
<Property Name="sonar.organization">MyOrganization</Property>The analysis seems to run fine, but in the end when it tries to upload the analysis to Sonarcloud, I'm getting this error:ERROR: Error during SonarQube Scanner execution
ERROR: You're only authorized to execute a local (preview) SonarQube analysis without pushing the results to the SonarQube server. Please contact your SonarQube administrator.I've tried connecting to a local Sonarqube server and that works fine. Does anybody have any idea what's going wrong here?
|
Error uploading analysis to SonarQube
|
Those are:S1612 "Lambdas should be replaced with method references"S1602 "Lamdbas containing only one statement should not nest this statement in a block"Both pages include example on how to fix your code.x -> System.out.println(x+1)
(a, b) -> a+b //For return statement, the return keyword should also be dropped
|
public Integer getMaxCount(String id,String type) {
String maxCount ="SELECT MAX(ID) AS COUNT FROM STUDENT";
try {
return queryForObject(
maxCount,
new Object[]{id,type},
(rs, i) -> {return rs.getInt(COUNT);},
"maxCount"
);
} catch (EmptyResultDataAccessException ex) {
LOG.error(ex);
return 9999;
}
}Getting below sonar violations for above block of code how to fix.Lambdas should be replaced with method referencesLambdas containing only one statement should not nest this statement in a block
|
Sonar violation
|
Your best bet is to monitor to access log of the SonarQube server.
It's inlogs/access.logof a SonarQube installation.
It includes the IP address and timestamp of requests,
as well as the project key when a scanner pushes analysis results to the server.
It should be easy to identify the origin of any scan.
|
We have a SonarQube server that is actively used by several other teams in the company, but which my team hasn't been using for several years.
When I tried to encourage my team to start monitoring code quality with Sonar again, I discovered that the Project in Sonar is being updated on a regular basis.However, no-one in the team has any idea where these updates are coming from!Sonar is not included in our main project POM file (we use Maven), and as far as I can tell, it's not being triggered by Jenkins (the Sonar plugin for Jenkins does not appear to be installed or configured).That leaves a scheduled execution of a SonarScanner as the most likely source for these updates. However, in a company with several hundred servers and thousands of users, I have no idea where to start looking for this scheduled job!Is there anything in the Sonar logs that would point to the source of the update, or anything I can configure so that this kind of information is logged?
|
Tracking the origin of a SonarQube Scan
|
First:do nottry to get the data from the database directly. It's not an API, data structures may change anytime in there, at the discretion of technical implementations.You're safe though: SonarQube exposes all its data/workflows viaits Web API. Go through its documentation and you'll findapi/measures/component(documentation):Return component with specified measures.Real-life example:this project on sonarqube.com (51k LOC as of writing). Key (shown on right pane) isorg.apache.abdera:abdera.queryingapi/measures/component:https://sonarqube.com/api/measures/component?componentKey=org.apache.abdera:abdera&metricKeys=nclocGives you the value for thatnclocmetric. Job is done. :)Note: same approach works for any metric (seeMetric Definitionsfor info on metric keys).
|
I am developing an application in which i display some details of each project in Sonar. So i want to show the line of codes for each project in my page. I have access to Sonar DB. Can anyone tell me the tables / queries that i should use to get the line of code.
|
How to get Line of code for a project in Sonar
|
The easiest way is excluding external code from the report withnarrowing the focus feature.Just add to yoursonar-project.propertiesfile path pattern to exclusion, for example# Exclude all classes ending by "Bean"
# Matches org/sonar.api/MyBean.java, org/sonar/util/MyOtherBean.java, org/sonar/util/MyDTO.java, etc.
sonar.exclusions=**/*Bean.java,**/*DTO.java
# Exclude all classes in the "src/main/java/org/sonar" directory
# Matches src/main/java/org/sonar/MyClass.java, src/main/java/org/sonar/MyOtherClass.java
# But does not match src/main/java/org/sonar/util/MyClassUtil.java
sonar.exclusions=src/main/java/org/sonar/*
|
I have a web app project where the quality is measured under sonarqube.As i'm dealing with an external code within my project filesRecently i have had some issues appearing due to that exetrnal code and which i'm not focusing on its quality :So i wanna just delete the issue to appear from my sonar dashboard (which looks like the following):The solutions that i have had where not really usefull , as :i was suggested to change the level of the rule itself from"issue"to"info":And of course that seems to be not usefful because , i won't affect the rule itselfthe second suggestion was to use the :@SuppressWarningsdecorator in my blocks of code where the issues appeared ; : for example use it underclasses or methods or even fields->this method results in adding some code to my extarnal code and that won't be also good as i'm not even having the permission to do it.I wanna just thesimpliest solution to delete the issue from the sonar dashboard, just suppress it from the SonarQube interface , strangely it seems that there is no a direct way to do it :Any better ideas ??
|
How to delete an issue from SonarQube interface
|
There is no plugins to add. All the rules of your langage you have in SonarQube are tagged "cwe, owasp, bug" or something like this.You could setup a profile with all the rules you want to check and name it "OWASP profile".BTW, actually the OWASP SonarQube project was closed. And nothing more will be done on it.
|
I am trying to find a documentation on how to setup OWASP projecthttps://www.owasp.org/index.php/OWASP_SonarQube_Projectto setup it for SonarQube. I tried to find in available plugins but i couldn't find anything related to it. I read few documentation and little bit confused how to use OWASP to SonarQube.
I have SonarQube 5.6 version. Can anyone help me to understand how to setup OWASP in SonarQube.Thanks,
|
How to setup OWASP plugin to sonarqube
|
What you should focus here is not the version of SonarQube but version of SonarQube Java Analyzer. Last release of the analyzer (3.12 at time of writing) contains rules that cover more than 80% of findbugs rules and this coverage is likely to keep increasing.So yes, by updating to the latest version of SonarQube and the java analyzer, you don't need to use the FindBugs plugin anymore.
(Disclaimer, I am maintainer of the SonarQube java plugin, and author of the mentioned blog post in the question so I am a bit biaised here ;) )
|
There was saying that 'SonarQube Java Analyzer' will be containing FindBug rules .so we need not to add any external findbug rule to sonar .http://www.sonarqube.org/sonarqube-java-analyzer-the-only-rule-engine-you-need/Is this already added in SonarQube 5.4 ?ThanksGanesh
|
Does SonarQube 5.4's 'Sonar way' quality profile contain Findbugs?
|
My name is Tim Rosenblatt and I'm one of the senior engineers here at Ship.io. I'm not sure why you didn't get a reply from our support email, and I'm glad you posted about this here.As Viktor mentioned, we definitely support custom scripts. You absolutely can run whatever you like during your build process with this type of step.I've got a few links that should be helpful for you in getting SonarCube added to your Ship job, but you can definitely get in touch with us if anything isn't clear enough for you. You can use the in-app support icon at the bottom right of your dashboard, or just email me personally -- tim at ship dot iohttp://support.ship.io/environment/install-softwarehttp://support.ship.io/environment/custom-shell-scriptsThanks!
|
We have a setup where we want to usehttps://ship.io/as our cloud-based continuous-integration server.However we also want to have some kind of static code analysis (preferably SonarCube but that is debatable), which isn't supported officially by ship.io.
The Projects are classic mobile Projects (Android and iOS).I have seen some posts of people mentioning that they managed to setup this kind of configuration. SonarCube just has released a gradle pluginhttp://www.sonarsource.com/2015/06/15/sonarqube-gradle-1-0-released/so the Android part should be doable.However at the moment i have no idea what would be the best way do do this for the iOS part of the project.We already contacted the ship.io team on this issue but did not recieve a response yet.Any suggestions/insights on this?
|
Howto integrate static code analysis (SonarCube) into ship.io for mobile projects?
|
Do any other examples exist for SonarQube plugins using the latest API?No, I faced exactly the same issue today and couldn't find any. But here is the solution :Create a class implementingRulesDefinition-> it is aServerExtensionwhose sole purpose is to make your custom rules appear in SonarQube's UI if you've explicitly provided a definition (programatically, or in a XML file, or through annotations). This extension is loaded at server startup.Create a class implementingBatchExtensionandJavaFileScannersFactory-> its purpose is to make all your custom java rules available during batch analysis by returning instances of your rules. This extension is loaded during analysis.Create a class extending SonarPlugin which returns Extensions created in points 1 and 2 above.Your custom rules will then be both available in UI and during analysis. If you don't do 1. you won't be able to activate / configure them. If you forget 2, they will be activable / configurable, but will never be executed (and no error will be raised neither)It's a slight difference withRulesRepository: yourCustomRulesRepositoryextendingRulesRepositorycould directly implement BatchExtension andJavaFilesScanner.
|
SonarQube version: 4.5I created a Java project based on thesonar-xoo-plugin.
Then I added a simple rule which inheritsBaseTreeVisitorandalways raises an issueinvisitMethod(MethodTree). I annotated the class with@Rule(key = "x1")and used the same key in the classMyRulesDefinitionwhen creating a new rule in the repository.I built the project, put the jar file into the plugins folder and started the sonar server. The plugin was loaded and the rule existed. I activated it for the selected quality profile and ran an analysis butno issues were found by the rule.What am I doing wrong? How is the rule template inMyRulesDefinitionmapped to the logic of the rule?Do any other examples exist for SonarQube plugins using the latest API?
|
How to register custom rules in a plugin for SonarQube 4.5?
|
FYI @goodspeed, we're going to reintroduce this RCI metric by publishing a dedicated plugin. I expect this plugin to be released by the end of July.
|
I am doing code anaylysis using SonarQube version 4.3 with Sonar Runner 2.4. But I don't see RCI (Rules compliance index) which was there in version 3.7.Question:is RCI replaced by Technical Debts ? (as inSONAR-4820)is it possible to view RCI in SonarQube version 4.3, if so how ?
|
How to enable RCI in SonarQube 4.3?
|
The return type of a ternary (or more correctly,conditional) expression where the second and third operands consist of one primitive and one corresponding boxed version, is that of the primitive.(For a complete analysis of the type of the conditional operator, look atthe Java Specifications 15.25.)Since the second operand here,UNSPECIFIED_PARAMETER_KEY, is along, and the third,valueis aLong, Java has to unboxvalueto alongto evaluate the expression.After this, aLongis to be returned, sovalueis immediately reboxed.You can fix this by changing your constantUNSPECIFIED_PARAMETER_KEYinto aLong.
|
In sonar i see a major violation warning for codepublic Long getValue(FieldType fieldType) {
Long value = paramLevelMap.get(fieldType); // ok returns Long not long
return value == null ? UNSPECIFIED_PARAMETER_KEY : value; // complaints here
}Where 'UNSPECIFIED_PARAMETER_KEY' is pvt static long , and 'value' is also long.Boxed value is unboxed and then immediately reboxedIts complaining on the 2nd line. I didn't quite understand it , when & how is primitive long being converted to corresponding class object ? and back ?
|
Java Auto Boxing and conditional operator
|
My problem is resolved now since it was mainly a problem of maven metadata file.Theorg/codehaus/mojo/sonar-maven-plugindid not contains the correctmaven-metadata.xmlfile. Thus, Maven 2 was unable to know which version of the plugin was needed. Adding it resolved my issue.
|
I try to execute themvn sonar:sonarcommand on a machine where Maven is configured to have no access to external repositories (in reality, this is not exactly the case, but it helps me to explain my problem).So currently, if I run this command, I get the following error:[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] The plugin 'org.codehaus.mojo:sonar-maven-plugin' does not exist or no valid version could be foundI think it means that I have some incorrect metadata in my local repository, as I have a[local repo]\org\codehaus\mojo\sonar-maven-plugin\1.0-beta-1directory (with the JAR inside, of course).Have you any idea why my command is failing?tech infos: Maven 2.2.1, Java 1.6, Sonar 2.1.2
|
Execution of "mvn sonar:sonar" with no external access
|
Updated answer (august 2022)Problem is fixed in the official v9.6 image.Updated answer (june 2022)I was able to build a working image by using this Dockerfile:FROM sonarqube:community
USER root
RUN apk add --no-cache --upgrade 'zlib>=1.2.12-r1';
USER sonarqube(credits tothis Github comment)Original answer (april 2022)As stated inthis issuefrom the Docker-Sonarqube repository:This bug appeared when the alpine base image has been updated to 3.14.5+. So you have two choices for now:Either rollback Sonarqube 9.2.4 (prior versions have the Log4J vulnerability)Re-build the latest Sonarqube image yourself with alpine version set to 3.14.3 (as explained inthis comment)
|
I'm trying to create docker container with SonarQube inside it, but I get this error while composing for the first time:Caused by: java.util.concurrent.ExecutionException: org.apache.lucene.index.CorruptIndexException: checksum failed (hardware problem?) : expected=f736ed01 actual=298dcde2 (resource=BufferedChecksumIndexInput(NIOFSIndexInput(path="/opt/sonarqube/data/es7/nodes/0/_state/_7w.fdt")))I tried installing it on a fresh instance with fresh docker installation, I even tried to install it on a different server to rule out hardware failure, and I still get the same error. What could be the cause of it?docker-compose.ymlversion: "3"
services:
sonarqube:
image: sonarqube:community
depends_on:
- db
environment:
SONAR_JDBC_URL: jdbc:postgresql://db:5432/sonar
SONAR_JDBC_USERNAME: sonar
SONAR_JDBC_PASSWORD: sonar
volumes:
- sonarqube_data:/opt/sonarqube/data
- sonarqube_extensions:/opt/sonarqube/extensions
- sonarqube_logs:/opt/sonarqube/logs
ports:
- "9000:9000"
db:
image: postgres:12
environment:
POSTGRES_USER: sonar
POSTGRES_PASSWORD: sonar
volumes:
- postgresql:/var/lib/postgresql
- postgresql_data:/var/lib/postgresql/data
volumes:
sonarqube_data:
sonarqube_extensions:
sonarqube_logs:
postgresql:
postgresql_data:
|
SonarQube Docker Installation CorruptIndexException: checksum failed
|
After some research I found an option that is aligned with what I was looking for.MochaThis is inspired by MaterialUI repo which usesmochawithchai:import { expect } from 'chai';
import * as MyLib from './index';
describe('MyLib', () => {
it('should have exports', () => {
expect(typeof MyLib).to.equal('object');
});
it('should not have undefined exports', () => {
Object.keys(MyLib).forEach((exportKey) =>
expect(Boolean(MyLib[exportKey])).to.equal(true),
);
});
});source:https://github.com/mui-org/material-ui/blob/next/packages/material-ui/src/index.test.jsJESTAs we use JEST in my project we had to convert it:import * as MyLib from './index';
describe('MyLib', () => {
it('should have exports', () => {
expect(MyLib).toEqual(expect.any(Object));
});
it('should not have undefined exports', () => {
for (const k of Object.keys(MyLib))
expect(MyLib).not.toHaveProperty(k, undefined);
});
});
|
I have anindex.tstop file in an NPM library which has only export statements.i.e.:export * from "./foo"
export * from "./bar"SonarCloud is showing those lines as not covered, as it is expected that those should have no tests. I know we can live with the missing coverage but it is somehow annoying.I know I could also ignore the file, but then I would need to do the same for every file with a similar purpose that group and export components down inside the library.Is there any best practice or configuration I can use to overcome that?
|
How to get Jest to have coverage for export only lines?
|
You can use sonarqube Web API in your script to set the quality gate for your project.Note: You need the "Administer Quality Gate" permission to set the qualitygate.First, you need to get the id of the quality gate that you want to set. You can use the web API to get the list of quality gate available and their corresponding id.curl -u "<Username>:<Password>" -X GET "http://localhost:9000/api/qualitygates/list"Now, use the below web api to set the quality gate to the specific project.curl -u "<Username>:<Password>" -X POST "http://localhost:9000/api/qualitygates/select?projectKey=webapp&gateId=10180"Here, you can change the projectKey and gateId according to your project and quality gate Id (you get from above api) respectively.Please find more information here in the screenshot:
|
How to assign Quality Gate dynamically to project from the script. [SonarQube 6.5]I tried with 'sonar.qualitygate' but got below warning.Thanks in advance.[WARNING] Property 'sonar.qualitygate' is not supported any more. It will be ignored.
|
How to assign Quality Gate dynamically to project from the script [SonarQube 6.5]?
|
The documentation seems not up-to-date.You should add-Dsonar.host.urland-Dsonar.host.urlarguments to the maven command to ovveride the default settings :image: maven:latest
variables:
SONAR_TOKEN: "your-sonarqube-token"
SONAR_HOST_URL: "http://your-sonarqube-url"
GIT_DEPTH: 0
sonarqube-check:
script:
- mvn verify sonar:sonar -Dsonar.qualitygate.wait=true -Dsonar.host.url=$SONAR_HOST_URL -Dsonar.login=$SONAR_TOKEN
allow_failure: true
only:
- merge_requests
- master
|
I was trying to integrate the GitLab CI/CD with SonarQube 8.1 based on the following documentationhttps://docs.sonarqube.org/latest/analysis/gitlab-cicd/.I tried to use the SonarScanner for Maven sample configurationsimage: maven:latest
variables:
SONAR_TOKEN: "your-sonarqube-token"
SONAR_HOST_URL: "http://your-sonarqube-url"
GIT_DEPTH: 0
sonarqube-check:
script:
- mvn verify sonar:sonar -Dsonar.qualitygate.wait=true
allow_failure: true
only:
- merge_requests
- masterThe problem is that it looks like the SONAR_HOST_URL, and probably, the SONAR_TOKEN is ignored for unclear reason. When looking at the pipeline log I get[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.6.0.1398:sonar (default-cli) on project sonar-java-test: Unable to execute SonarQube: Fail to get bootstrap index from server: Failed to connect to localhost/0:0:0:0:0:0:0:1:9000: Connection refused (Connection refused) -> [Help 1]I tried to workaround this by setting the variables using the gitlab (12.3.2) CI/CD variables, but it doesn’t workAny ideas?
|
GitLab SonarQube CI/CD variables are not passed to the Pipeline
|
The return statements have no effect because you do not have any code after the if-elseif-else block. If you remove the return statements, your code will leave the matching if-block and return at the end of the method.Only the first one of the if-elseif-else blocks that evaluates to true gets executed.A void-method has an implicit "return" statement in the end.
|
I have a method in which there is a if else conditions . The if-else looks something similar as below.public void agreementCoduct(String agreement) {
if(agreement.equals("Pass")) {
{ //do someting
return; // getting Remove this Redundant Jump
} else if(aggrement.equals("NotPass")) {
// do something
return; // getting Remove this Redundant Jump
} else {
// do something
return; // getting Remove this Redundant Jump
}
}I'm running Sonarqube to check the code quality. It is showing the message "Remove this redundant jump." . I want to know how can I remove this Code smell and still achieve what I want. as this is void method so return; should work fine?
|
Getting : Remove this Redundant Jump in SonarQube
|
You can not delete a default or built-in quality profile. Otherwise, you would see that option in the dropdown menu.
|
Does anybody know how to delete a quality profile in SonarQube?I am trying to suppress the unused javascript quality profile "Sonar way" :I am administrator and clicking the down arrow, I only have the following options :CompareCopySet as default
|
How to delete a quality profile in SonarQube
|
Sonar has very opinionated ideas about what you should do to avoid defects. Here, their opinion is that you should be explicit about initializing instance fields. I assume their thinking is that adding " = null" shows that you meant to set the field to null and that it is not an oversight.Adding many //NOSONAR in code shared by many developers is a poor practice, as doing so soon becomes a convention and defeats the purpose of using Sonar. I suggest simply submitting to Sonar and adding the initialization. Either that, or turn off the rule.
|
We're using Sonar for code analysis. For classes something like thispublic class Car {
private Engine engine;
// getter setter for engine
}we get errors such asNon-abstract classes and enums with non-static, private members should explicitly initialize those members, either in a constructor or with a default value.We usually serialize our objects with Jackson, so constructor is not used anywhere in our code. So why do I still need to write a constructor? Would it make sense to disable this rule?Rule LinkAnother thing, if I change code as belowprivate Engine engine = null;The error is not thrown. By default, all Java references are assigned with a null value. Is this line fooling Sonar? Should this be a bug in Sonar?
|
Java: Sonar compulsory constructor
|
Add the mentionNOSONARanywhere on the line for which you wish to disable Sonar inspection. Like that:/** Model which defines data from the oracle view V_THINGS_TODO which contains blabla NOSONAR */
public class ThingsTodo ... {
|
I am trying to add a javadoc to explain what a class is doing but I am encountering a sonar alert.Track uses of "TODO" tags (squid:S1135)The thing is the word TODO is not used as a todo message or with @todo.
Here is my javadoc :/** Model which defines data from the oracle view V_THINGS_TODO which contains blabla */
public class ThingsTodo ... {the word TODO is present in the javadoc but as a View name...
So far I am using this workaround V_THINGS_T0D0 (as 0 1 2..) but It is kinda bad if someone try to search for this in the database.Is there any magic trick I am not aware of to not trigger this alert with the todo word ?Next time I will be more cautious about reserved word :-<
|
how to write the word "todo" in javadoc without triggering the sonar alert?
|
it is solved one just need to check the tool location in general tool configs and give the path adn call it in jenkins file.stage('PDNS-UI-Sonar') {
environment {
SONAR_SCANNER_OPTS = "-Xmx2g"
}
steps {
sh "pwd"
sh "/opt/sonar-scanner/bin/sonar-scanner -Dproject.settings=sonar-project.properties"
}
}enter image description here
|
Does SonarQube scanner support BlueOcean pipeline plugin without maven and docker, if it does how does the script works in Jenkinsfile?I'm new to Jenkins and BlueOcean and have tried all the basic possible aspects available.If the SonarQube plugin did support Declarative:pipeline {
agent any
stages {
stage('SonarQube analysis') {
tools {
sonarQube 'SonarQube Scanner 2.8'
}
steps {
withSonarQubeEnv('SonarQube Scanner') {
sh 'sonar-scanner'
}
}
}
}
}
|
How to execute SonarQube scanner in Jenkins Declarative Pipeline without Maven and Docker
|
As stated inannouncement of release of JaCoCo version 0.8.0:Please NoteTools that directly read exec files (which is not a final report) and embed JaCoCo for generation of report will provide filtering functionality only after they updated to this version of JaCoCo.So please follow/wait/etc respective vendors such asSonarQube-https://jira.sonarsource.com/browse/SONARJAVA-2608Reports generated by corresponding version (0.8.0) of integrations developed as part of JaCoCo project by us (Ant Tasks, Maven Plugin and Command Line Interface) provide filtering functionality.With Gradle JaCoCo Plugin you can select both runtime and version for "JaCoCoReport" task using "toolVersion" -https://docs.gradle.org/current/userguide/jacoco_plugin.htmlThis is also stated inJaCoCo changelog:Note: Tools that directly read exec files and embed JaCoCo for this (such asSonarQubeor Jenkins) will provide filtering functionality only after they updated to this version of JaCoCo.As of today (29 Jan 2018) fix forhttps://jira.sonarsource.com/browse/SONARJAVA-2608is supposed to be in not yet released SonarJava plugin version 5.1.From all the above: report generated by Gradle should already be filtered, report generated by SonarQube will be filtered after upgrade of SonarJava.
|
I'm using Gradle 4.4 on my Java project with JaCoCo 0.8.0, and Sonar with SonarJava 5.0.1.I have a class annotated with lombok's@[email protected] JaCoCo config in build.gradle looks like this:jacoco {
toolVersion = "0.8.0"
reportsDir = file("$buildDir/reports/jacoco")
}
jacocoTestReport.doFirst{
classDirectories = files("buildDir/classes")
}
task jacocoReport(type: JacocoReport){
sourceSets sourceSets.main
executionData test, integrationTest
}Also, I have lombok.confi file, with propertylombok.addLombokGeneratedAnnotation = true, and generated stuff does actually [email protected] in build/classes.However, the coverage on Sonar is still low. It reports a ton of conditions and lines to cover.
|
Filtering coverage with Lombok, Gradle, Jacoco and Sonar
|
You need theShare Dashboards and Filterspermission. Then you'll be able to make your dashboards public and @Jeroen Heier pointed out in his comment, your team mates will be able tosubscribeto them.Note that dashboards were dropped in SonarQube 6.2.
|
I have created a SonarQube dashboard, which gives overview of my team's SonarQube projects. However, I'm unable to share the dashboard with my team. How can I share the dashboard? What permission does the administrator need to enable so that I can share it? We're using SonarQube Version 5.6.7.
|
How to share Sonarqube Dashboard?
|
Why doesn't 'Sonar way' contain all SonarJava rules.Because some of the rules are:too restrictive - not suited for many types of applications and should be enabled after some discussions in teamsmutually exclusive (example:RSPEC-1105says that opening{character should be at the same line andRSPEC-1106that should be at a new line)they only apply if certain technologies are used (JAVA 8, Spring framework, jUnit framework etc.)Those a few reasons whySonar waycontains part of the rules, not all. It causes that more people can use the default set of rules without being frustrated.Is there some drawback in creating a profile that contains all rules from SonarJava repository, and using this profile?You can create a new Quality Profile and enable all rules using bulk operation. Read more:https://docs.sonarqube.org/latest/instance-administration/quality-profiles/
|
My company is using SonarQube for quite some time, and now that we installed latest SonarQube verzion 6.4, we would like to upgrade quality profiles that we are using.As far as I can understand there is no need to use FindBugs, PMD and Checkstyle plugins any more because rules from SonarJava plugin contain all rules from other plugins.I wanted to use 'Sonar way' built-in profile but I noticed that it only contains subset of all the rules in SonarJava repository. There are 292 rules in Sonar way and 427 in SonarJava rule repository. I noticed a bunch of important rules missing from 'Sonar way'.Questions are:Why doesn't 'Sonar way' contain all SonarJava rules.Is there some drawback in creating a profile that contains all rules from SonarJava repository, and using this profile?
|
in SonarQube, why 'Sonar way' quality profile doesn't contain all the rules from SonarJava repository
|
take a look at the documentation of sonarqube for analyzing source code ( current linkhttps://docs.sonarqube.org/latest/analysis/overview/) - there you find a lot of useful scanners for different environments and languages.You just need to configure them properly, but this is also something you can find within the docs of sonarqube.
|
On my SonarQube server I have 2 quality profiles (1 for C# and 1 for JS).How to run a code analysis from the command line locally using them (retain them on server, without using tools like SonaLint) or using a gulp task?
|
How to run a code analysis locally from the command line using a quality profile on the SonarQube server?
|
sonar.profilewas deprecatedseveral years agowith the introduction of multi-language analysis.If you nonetheless usesonar.profile- rather than having a project administrator associate the project to the desired profiles via the UI - then youmust havea profile of that namefor each languagefound during analysis. From the error, you don't.
|
While building the code, the following message is logged in the SonarQube Scanner step:sonar.profile was set to 'xxxxxxxx profile' but didn't match any profile for any language. Please check your configuration.This message is logged even though the 'xxxxxxxx profile' is available and mapped to the corresponding language. This was working in the past and encountering this error only recently. There have been no recent changes in the configuration or related settings via UI and also no module of any other language (i.e. other language without association with quality profile) is committed.What could be the cause of this issue and how to resolve this?
|
"Sonar Profile didn't match" error however the profile is mapped correctly in SonarQube
|
In Sonar 7.6 this is under Administration > Configuration > General settings. Look for field "Server base URL".
|
I have enabled Email notification to few of my projects in SonarQube Dashboard, so that any issues assigned will be notified to the specific developer. The Link in Email body needs to be changed from "http://localhost:9000/issues/search#issues=AVtbuWsccyuRBiLrOmUr" to "http://IP:PORT/issues/search#issues=AVtbuWsccyuRBiLrOmUr". How do it achieve this.please help me on this.Thanks.
|
How to change the Sonar Dashboard URL from localhost:9000 to a specific IP in Email Notification Body Link
|
The SonarQube analysis is split into two separate tasks:The 'Sonar Scanner' runs the analysis on the code (which is what happens in your Jenkins build) and packs the results and sends them of to the SonarQube instance.The 'Compute Engine' (CE) uses the packed results and calculates several quality metrics (for ex. the CE is responsible to update the Quality Gate status)As your Jenkins build is successful this means that the Scanner did do it's work just fine, but on the CE side it failed to process the results of the scanner.SeeBackground Tasksdocumentation on how to obtain the log of the CE task and see why the analysis results processing failed.
|
I am using sonarqube 6.1 which is integrated with Jenkins 2.48. In Jenkins, it is showing my build ran successfully. But in Sonarqube, it is showing Failed.Jenkins :POST BUILD TASK : SUCCESS
END OF POST BUILD TASK : 0
Finished: SUCCESSSonarqube (Failed in red color) :[![enter image description here][1]][1]What "failed" mean in Sonarqube project?
Does it means wrong configuration or wrong iteration with Jenkins?How can I solve this?I have checked in background task. Project failed recently but in project summery, it is showing past failed details.
[![enter image description here][2]][2]
|
sonarqube project failed
|
When your issue counts are scrambled like this, it means the ElasticSearch index is corrupted.shut the server downdelete$SONARQUBE_HOME/data/esstart the server back upStartup will take a little longer because there's an added delay while the index is rebuilt. The duration of this delay is dependent on the size of your instance.Once your server comes back up, your numbers should be right.
|
Sonarqube is showing incorrect total for projects and issues.Total projects says 4 however there are only 2. Claims there are 78 bugs but there are none, and none get displayed in the results section. (see below)I've checked the database a grouping the[projects]table by[project_uuid]only returns 2 rows.Sonarqube v6.2 is being used, with an SQL Server database if that makes any difference. Could this be a setup issue, I only setup this instance a few days ago but I am not sure where to check other than the database where the projects table at least.
|
Sonarqube totals wrong
|
Eventually I realised that I should have addedQuality Gatesas aPost Build Actionfor every job I was using it on.
|
I want my Jenkins build to fail if the code doesn't have 90% test coverage. For that, I have installed theQuality Gatesplugin, which should check the SonarQube analysis.I have the following configuration inJenkins, underQuality Gates:Name: SonarQubeServer
SonarQube Server URL: http://my-server.com:9000
SonarQube account login: admin
SonarQube account password: ****SonarQube displays:Quality Gate FailedJenkins displays:SonarQube analysis completed: SUCCESSand the build passes.Any idea why Jenkins doesn't get that the quality gate failed?
|
Jenkins doesn't pick up Quality Gate failure
|
It looks like you're trying to run a class compiled with Java 8 on an older version of the JVM. Is that Tanuki wrapper honouring the JAVA_HOME variable that you set? What happens if you run it without going through the wrapper?See here:How to fix java.lang.UnsupportedClassVersionError: Unsupported major.minor versionEdit: Also, I see that your path refers to both JDK 1.7 and JDK 1.8. I would try to remove the reference to JDK 1.7 to see if that makes a difference.
|
Installed the sonarqube 6.1,
Set the JAVA_HOME as C:\JDK\jdk1.8.0_92 in StartSonar.bat file and added C:\JDK\jdk1.8.0_92\bin in path variable alsoWhen trying to start getting the below errorSetting JAVA_HOME
PATH: C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System3
2\WindowsPowerShell\v1.0\;C:\Program Files\TortoiseSVN\bin;C:\svnrepository\bin;
C:\SVN\bin;C:\apache-maven-3.0.4\bin;C:\Sonar\sonar-runner-2.0\bin;C:\JDK\jdk1.7
.0_60\bin;C:\ANT\ant-1.8.2\bin;C:\Maven\apache-maven-3.0.4\bin;C:\JDK\jdk1.8.0_9
2/bin;
JAVA_HOME: C:\JDK\jdk1.8.0_92
wrapper | --> Wrapper Started as Console
wrapper | Launching a JVM...
jvm 1 | Wrapper (Version 3.2.3) http://wrapper.tanukisoftware.org
jvm 1 | Copyright 1999-2006 Tanuki Software, Inc. All Rights Reserved.
jvm 1 |
jvm 1 | WrapperSimpleApp: Unable to locate the class org.sonar.application.Ap
p: java.lang.UnsupportedClassVersionError: org/sonar/application/App : Unsupport
ed major.minor version 52.0
jvm 1 |
jvm 1 | WrapperSimpleApp Usage:
jvm 1 | java org.tanukisoftware.wrapper.WrapperSimpleApp {app_class} [app_arguments]
jvm 1 |
jvm 1 | Where:
jvm 1 | app_class: The fully qualified class name of the application to run.
jvm 1 | app_arguments: The arguments that would normally be passed to the
jvm 1 | application.
jvm 1 | Picked up _JAVA_OPTIONS: -Xms1024m -Xmx2048m
wrapper | <-- Wrapper Stopped
|
Unable to start sonarqube 6.1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.