Response
stringlengths
8
2k
Instruction
stringlengths
18
2k
Prompt
stringlengths
14
160
You could usenpm run audit. It is a security audit command, which will alert you of any found vulnerabilities - in yournode_modules,package.lock&package.json(You can choose from many flags in that command)Read more about ithereIf you are injecting with<script>tag itself, I would recommend trying to find thenpmmodule for it and installing it that way, so you can keep track of everything at once withnpm run audit. If that is not the case, I suppose you could find a vulnerability scanner on google, but I am not so familiar with them to write on their accuracy.
I have a create-react-app and I add some scripts to use a third-party library how can I check if those libraries have vulnerabilities?
How to check vulnerabilities of a third-party library use in a React JS app?
When you're connected to Sonar. Go toquality profilestabThen select the profile "sonar way" and create new copy of it . Because Sonarqube does not allow us to change the root profile, if you want to modify the rules set, you need your own rules.Then select the new profile and deactivate rules you don't want.Finally set this new profile as the default one.
I would like to analyse my code only against aFinbug quality profile.In order to simplify the issues reading, I would like to deactivate the default 'Sonar way' profile or at least to filter its rules out. How can I achieve that ?
Is it possible to deactivate 'Sonar way' quality profile from an analysis?
TheStream<Path>is closable:List<String> foundFiles; try (Stream<Path> pathStream = Files.walk(Paths.get(PACKAGE_BASE), 1)) { foundFiles = pathStream .filter(subdirectory -> subdirectory.resolve(requestedFile).toFile().exists()) .map(String::valueOf) .collect(Collectors.toList()); }
I have this code:String requestedFile = Paths.get(prefix, name).toString(); // Find all matching files List<String> foundFiles; try { foundFiles = Files.walk(Paths.get(PACKAGE_BASE), 1).filter(subdirectory -> Paths.get(subdirectory.toString(), requestedFile).toFile().exists()).map(String::valueOf).collect(Collectors.toList()); // Maybe we didn't find anything? if (foundFiles.isEmpty()) return null; String matchingFile = Paths.get(foundFiles.get(0), requestedFile).toString(); return matchingFile; } catch (IOException e) { return null; }My sonar scan is saying:Use try-with-resources or close this "Stream" in a "finally" clauseIt happens in the Files.walk call, but I did not write this code, and I don't know how to break this up properly to make it a try with resources, or get the stream to close in the finally.Any Ideas?
Sonar scan says close stream, but there is no stream to close
Use UriComponentsBuilder to encode the URL instead of using raw URL.
I have a RESTful service controller that requests another RESTful service@ResponseBody @RequestMapping(value = "/headerparameters/{instanceId}", method = RequestMethod.DELETE) public RestContainerFormBean passivizeHeaderParameter(@PathVariable String instanceId) throws GenericException, IOException { String url = proactiveURL + "/customerheaders/" + instanceId; if(isSecurityCheckOK(url)){ ResponseEntity<CustomerHeaderParameterBean> response = restTemplate.exchange(url, HttpMethod.DELETE, new HttpEntity<>(new HttpHeaders()), CustomerHeaderParameterBean.class); CustomerHeaderParameterBean result = response.getBody(); setButtonActivity(result); l10nOfValue(result); return new RestContainerFormBean(result); } else{ throw new IOException(); } }This code can not pass SonarQube policy.Refactor this code to not construct the URL from tainted,User provided data, such as URL parameters, POST data payloads, or cookies, should always be considered untrusted and tainted. A remote server making requests to URLs based on tainted data could enable attackers to make arbitrary requests to the internal network or to the local file system.The problem could be mitigated in any of the following ways:Validate the user provided data based on a whitelist and reject input not matching. Redesign the application to not send requests based on user provided data.How can I pass the policy by sticking on REST conventions ?
Server Side Request Forgery vulnerability
I see one possible case not covered. The inputvalmight benull. In that case, yourswitchstatement would throw aNullPointerException. To remedy this, you could add null check to the start of the method.private static String mapMyVal(String val) { switch (val) { case "foo": return "FOO_FOO"; case "bar": return "BARR"; default: throw new InvalidArgumentException(); } }
When I run coverage on my code below:private static String mapMyVal(String val) { switch (val) { case "foo": return "FOO_FOO"; case "bar": return "BARR"; default: throw new InvalidArgumentException(); } }I see "8 out of 10 conditions covered" when I run my unit tests on this with coverage. However I see all three lines being covered inside the statement.Since there are no other conditions than "foo", "bar" and everything else, what are those missing two conditions?
Condition coverage on switch statement
You can't useSystem.arraycopyto store data in something that's not an array. As it statesin the documentation:... if any of the following is true, anArrayStoreExceptionis thrown and the destination is not modified:Thesrcargument refers to an object that is not an array.Thedestargument refers to an object that is not an array....Ifcolsis a reference-typed array, just useArrays.asListandsubList:columns.addAll(Arrays.asList(cols).subList(1, cols.length - 1));
My java code:public class TestArray { public static void main(String[] args) { final String[] cols = { "a", "b", "c", "d" }; List<String> columns = new ArrayList<>(4); // for (int i = 1; i < cols.length - 1; i++) { // columns.add(cols[i]); // } System.arraycopy(cols, 0, columns, 0, cols.length - 1); for (String c : columns) { System.out.println(c); } } }Sonar say:Arrays should not be copied using loopsUsing a loop to copy an array or a subset of an array is simply wasted code when there are built-in functions to do it for you. Instead, use Arrays.copyOf to copy an entire array into another array, use System.arraycopy to copy only a subset of an array into another array, and use Arrays.asList to feed the constructor of a new list with an array.Note that Arrays.asList simply puts a Collections wrapper around the original array, so further steps are required if a non-fixed-size List is desired.so, I try this:System.arraycopy(cols, 1, columns, 0, cols.length -1);I have this error:Exception in thread "main" java.lang.ArrayStoreException at java.lang.System.arraycopy(Native Method) at com.company.TestArray.main(TestArray.java:16)I think my problem come from array is not list
Java - Sonar - Arrays should not be copied using loops
Sensor is a scanner side extension point. It will run during the analysis on your build agent. PostProjectAnalysisTask is a server side extension point, that will be instantiated/called at the end of the analysis report processing. You can’t share state like you did using a class attribute, since at runtime two classes will be instantiated on different JVM.I think it is better to implement the two extension points in separate classes, and use the scanner context to pass values between scanner side and server side:public class MyPlugin implements Plugin { @Override public void define(Context context) { context.addExtensions( MySensor.class, MyPostAnalysisTask.class); } } public class MySensor implements Sensor { @Override public void describe(SensorDescriptor descriptor) { descriptor.name(getClass().getName()); } @Override public void execute(SensorContext context) { // Get command line param. Optional<String> param = context.config().get("my.param.name"); if (param.isPresent()) { context.addContextProperty("my.context.key", param.get()); } } } public class MyPostAnalysisTask implements PostProjectAnalysisTask { @Override public void finished(final ProjectAnalysis analysis) { if (analysis.getScannerContext().getProperties().containsKey("my.context.key")) { // Perform custom post analysis task. } } }
I'm developing a plugin for SonarQube that will run a custom post analysis task,but onlyif a named scanner parameter is supplied to the sonar-scanner command. Can I do something like this?public class MyPlugin implements Plugin { @Override public void define(Context context) { context.addExtension(MyPostAnalysisTask.class); } } public class MyPostAnalysisTask implements PostProjectAnalysisTask, Sensor { private String param = ""; @Override public void describe(SensorDescriptor descriptor) { descriptor.name(getClass().getName()); } @Override public void execute(SensorContext context) { // Get command line param. Optional<String> param = context.config().get('my.param.name'); if (param.isPresent()) { this.param = param.get(); } } @Override public void finished(final ProjectAnalysis analysis) { if (!this.param.isEmpty()) { // Perform custom post analysis task. } } }I'm unfamiliar with the scope/lifecycle of my plugin objects. Are they unique per scan or per SonarQube server instance?
SonarQube Plugin Post Analysis Task only when Scanner Parameter set
You can always customize Sonar so that it won't show such unuseful errors. Many of the checks may be valid only in specific cases. You can either disable this config for your whole project or put// NOSONARat the end of the line so that Sonar ignores that. Also you can ask Sonar to ignore a file by putting the following annotation on top of your class:@java.lang.SuppressWarnings("squid:S00112")in which the value aftersquid:is the rule code corresponding to the rule that you're talking about.
I have a controller class and sonar is saying i should add a private constructor that throws an error but the class is used in a test class so doing this would cause the tests to fail. So should I add a public constructor to the class just so sonar doesn't pick it up?
Sonar is saying to use an private constructor instead of an implicit public constructor but the constructor is used in tests
First of all, you need to understand the purporse of these tools. Sonarqube are focused in code quality, Fortify do scans for code vulnerabilities. For CI/CD environments, it's quite common two tools running on each pipiline deployment, because those analysis are different.
Want to get a clear thought about why SonarQube should be chosen for code analysis, code review than the tools like ReSharper, Fortify etc. and why it is better than the code analysis features that Microsoft provides?
Why i should choose SonarQube over tools like ReSharper, Fortify etc. and over code analyzing features that Microsoft provides?
You can't do a partial analysis of a SonarQube project.Either you analyze the entire project every times. Or you analyze each Gradle module as a separate SonarQube project in the first place.
Given gradle project structure like belowparent - moduleA - moduleBIt's possible to perform sonar analysis using gradle plugin 'org.sonarqube' for entire project structure with commandgradle sonarqubeWhen I try to perform analysis only for moduleA or moduleB then an exception appears in SonarQube build task:org.sonar.api.utils.MessageException: Validation of project failed: o Component (uuid=XXX, key=parent:moduleA) is not a project o The project "parent:moduleA" is already defined in SonarQube but as a module of project "parent". If you really want to stop directly analysing project "parent", please first delete it from SonarQube and then relaunch the analysis of project "parent:moduleA".parent/build.gradle Sonar configuration:sonarqube { properties { ... property "sonar.projectKey", "parent" } }parent/moduleA/build.gradle Sonar configurationsonarqube { properties { ... property "sonar.projectKey", "parent:moduleA" } }Did I miss something or maybe it is impossible to analyze specified module of the project?
How to perform sonar analysis only for one module at once using gradle or maven?
Sonarqube does not only analyze the source code. It also produces some reports on code coverage of tests. Therefore tests must be run and all your code needs to be compiled.If your project is in Java, thispostalso explains that Sonarqube performs semantic analysis based on.classfile
I am wondering why Gradle builds my project, when I call Sonarqube for static code analysis:./gradlew sonarqubeHow can I prevent Gradle from building the whole project?
Why is Gradle building my Java project, when I just call für a SonarQube analysis?
I am not using any of these tools...i am running analysis with sonar scanner.SonarQube doesn't generate code coverage data. It displays data provided by reports generated by other tools. You have to configure and execute any code coverage tool and then scanner will upload results to the server.See how to do it for C#:Code Coverage Results Import (C#, VB.NET)More about code coverage:Seeing Coverage
I am running analysis on my solution which contains a Unit Test project just like any other projects . But there is 'No Data' in Unit Test Coverage Widgets .But I can see the analysis if I open respective folder/file of UT . How can I see Unit Test Coverage details by adding widget.
Unit Test Coverage not visible in Sonarqube
Quotinghttps://docs.sonarqube.org/display/PLUG/Building+on+Mac+OS+X:Add execution of Build Wrapper as a prefix to the usualbuild command that you use to build your project(the example below uses xcodebuild, but any build tool that performs afull buildcan be used)In other words:all files that should be analyzed must be compiled during execution ofbuild-wrapper. This is needed becausebuild-wrapperwatches compiler invocations to gather information about which files are compiled in your project and with which options, then this information is used for analysis during execution ofsonar-scanner.I seriously doubt that your execution ofcmake .performs compilation ofmain.c- it just generates make-files, and thus that's whymain.cis actually not analyzed properly.Execution ofcmake . build-wrapper-macosx-x86 --out-dir bw-output make clean allfollowed by execution ofsonar-scannerwith-Dsonar.cfamily.build-wrapper-output=bw-outputproduces desired result:
I made a very simple C file just to test the output of sonarcloud when using C code. My entire code is this:#include <stdio.h> #include <stdlib.h> int main() { int i; for(int j = 0; j < 100; j++) { void* unreleasedMemory = malloc(1024); printf("Address: %p\n", unreleasedMemory); } printf("Uninitialized i is: %d", i); return 0; }When I start a new project on sonarcloud and issue both build-wrapper and sonar-scanner commands like this:build-wrapper-macosx-x86 --out-dir bw-output cmake .After that:sonar-scanner \ -Dsonar.projectKey=ctest \ -Dsonar.organization=<orgname> \ -Dsonar.sources=. \ -Dsonar.cfamily.build-wrapper-output=bw-output \ -Dsonar.host.url=https://sonarcloud.io \ -Dsonar.login=<tokenvalue>Output of both parameters looks fine. Unfortunately, it doesn't detect these fairly obvious errors:What am I doing wrong so sonarcloud will pick them up?
Sonarcloud not finding obvious C problems
There is no functionality within SonarQube to duplicate. You must perform analysis with the new branch name to create your long-lived branch.
Is it possible to copy/duplicate a SonarQube branch (using theBranch Plugin) to a new branch? Or would analysis have to be re-run with new branch's name?Here's an example:Themasterbranch is the main branch of a project. Now let's say version 2.0 of the product is being released. Before version 3.0 code is created and analyzed, we want to spin-off arelease-2.0long-lived branch from master. What is the most efficient way to do this?Is there an option to duplicate the main branch in SonarQube to a new branch with a new name?Or Would you have to re-perform analysis on the code but specify thesonar.branch.nameproperty asrelease-2.0?
Copy/Duplicate SonarQube Branch?
You've hitSONAR-10569. It's fixed in 6.7.4 and 7.2.
We have configured Sonarqube 6.7.3 fresh setup (no history, no old data). I am trying to update the default project visibility to private using admin credentials as well as my account which is added to sonar-admin group but getting below errorUnknown url : /api/organizations/update_project_visibilityAny idea about this?
cannot update default project visibility to private
The latest SonarQube versions have an api-documentation link. For SonarCloud you can find the documentationhere. The documentation to create a new project ishere. If you look at the details ofapi/projects/createyou can see the parameters needed, the changelog and a response example. This API is available since version 4.0.
Im trying to create a project with SonarQube web api, I can't find any good tutorial to create them.I need to analyze a code and then get the information that SonarQube provides, I need to automatize all of this in a web application.Is this possible to do with SonarQube web api?
Creating projects with SonarQube web api
sonar-scanner(formerlysonar-runner) is useful when you don't have a build automation tool like gradle, maven, ant or jenkins.If you build withgradle, then you only need theorg.sonarqubeplugin.Here is the documentationAnalyzing with SonarQube Scanner for Gradle
I'm in process of setupSonarfor my Android-Kotlin gradle based project. There I setup local system that run./gradlew Sonarqubeand generate report.I come across another tool sonar-runner which need to generate report. I checked sonarqube downloaded folder & that already has some sonar-scanner file & generating report without explicit setup. So do we really need sonar-scanner explicitly ?What I understood isSonarScanneris the scanner that work for scanning & help sonarqube to generate report.Please make me correct
Relationship between Sonarqube & SonarScanner
SonarLint is an IDE extension for IntelliJ IDEA, Eclipse, Visual Studio, VS Code, Atom.SonarLint includes a list of language analyzer plugins, and SonarTS is the one for Typescript.To check if SonarLint support TypeScript in your IDE visithttps://www.sonarlint.org/and click on your IDE name.At the time I'm wiring this answer, TypeScript is included in SonarLint for VS Code, but not in SonarLint for Visual Studio.
I am really confused aboutSonarLintandSonarTS.I have usedSonarLintin my Visual Studio, but my client ask me to useSonarTs pluginSonarLintdoes analysis for overall project andSonarTSdoes analysis for only Typescript Projects.Am I correct?DoesSonarTsPluginesupport C# code? I am totally confused. I have an idea aboutSonarQube And SonarLint difference, but no idea aboutSonarLintandSonarTS.
SonarLint vs SonarTS
I guess SonarQube wants you to define two actions:ActionResult Strings(CultureInfo id); ActionResult Strings();withpublic ActionResult Strings() { CultureInfo cultureInfo = CultureInfo.CurrentUICulture; return Strings(cultureInfo); }andActionResult Strings(CultureInfo id)as before, but without the null check forCultureInfo.
Right now sonar qube analysis shows an error in the build as follows,and current code ispublic ActionResult Strings(CultureInfo id = null) { CultureInfo cultureInfo = id ?? CultureInfo.CurrentUICulture; }so how should i modify?
Use the overloading mechanism instead of the optional parameters
Because you don't want a rolling 14-day period, you'll have to manually re-configure to the start date of the new sprint every 2 weeks.Alternately, you could jigger your versions to something like3.14-sprintAlpha3.14-sprintBeta...And use theprevious_versionleak period setting.
I would like to configure SonarQube Leak Period to match our sprints (14 days). We don't release after each sprint, and our branch is always "develop" so I can't key off of a release.I know that I can configure X number of days, but I don't want a rolling account over a 14 day period... I would like it to do the delta by comparing each of the 14 days to Day 1. So, Day 2 <> Day 1, Day 3 <> Day 1, etc. Then on the 15th day it would reset for the start of the new sprint.How can I configure SonarQube to always start the leak period with the start of a new sprint?
Configure Leak Period to match sprints
) How can I syn the analyzed result to my server?To analyze your project and see the result on SonarQube, you need to use one of the scanners. For example, if you build your project with Maven, then you can use thescanner for Maven. Or if you build your project withAntorGradle, there is a dedicated scanner for those too (as I linked). If you don't use any build tool, then you can use thescanner for CLI.2) Are there any tool to category the analyzed result such as by severity? as I only interest on the "BUG"?I'm not aware of such tool. And, at the time of this writing, theSonarLint On-The-Flyview is not configurable to do this (unlike the "native"Problemsview of Eclipse). (This might be a good idea for future improvement, if there's enough interest for it.)3) How can I configure the rule of SonarLint in Eclipse Environment?It seems your project is bound to a project on SonarQube. You can configure this on SonarQube. In SonarQube, each project is associated with aquality profile. After you can configure what rules to include, you can update the bindings in Eclipse to apply the same configuration for SonarLint in Eclipse.
I installed the SonarLint 6.6 for Eclipse (neno) using Eclipse marketplace.It successful scanned my java project and returned 4725 items found.I bind the project to SonarQube server which installed at the same PCAfter anaylized the project again, I click "update all project bindings" at the SonarQube at Eclipse server to syn the result to SonarQubeMy Questions1) How can I syn the analyzed result to my server?2) Are there any tool to category the analyzed result such as by severity? as I only interest on the "BUG"?3) How can I configure the rule of SonarLint in Eclipse Environment?May I have your help? Many thanks!
Sonarlint issues shown in eclipse not in bind Sonarqube project
There is not a way to configure the webhook payload. However, youcoulduse a webhook to notify some intermediate system, which would then useweb servicesto retrieve the other values you're interested in and pass them on to the target system.
i want to send sonarqube code coverage / smells numeric analysis values in addition to the quality gates status. webhooks seem ideal for my task but they only send quality gates status, is there a way to customize/configure webhooks?
is there a way to configure payload sent by sonarqube webhooks?
It is not possible to import/export the logic of those custom rules, only their presence in a profile.In the case of rules coded in Java, you must make them give you at least the jar containing the rule implementations. Once you install that jar (and restart your server) the rules will be available to you.In the case of rules written in XPath, you must make them give you their XPath configurations, and you will need to re-create those XPath rules on your side (a tedious process of filling in a form once for each rule).
We're transferring our CI stack from a consulting company to in-house. We need to export the SonarQube profiles from the consultant's SQ instance to our corporate instance. We can export the profiles but the consultants created hundreds of custom rules and when we try to import the profile it fails to import the custom rules. We found in the API where you can export the rules to a JSON file, but can't find documentation on how to import them.Is it possible to import SonarQube rules? What is the best way to go about that?Referenced documentation:SQ Docs - Copying Quality Profiles:https://docs.sonarqube.org/display/SONAR/Quality+Profiles#QualityProfiles-CopyaprofilefromoneSonarQubeinstancetoanotherStackOverflow - How to export Rules:How to extract or export rules from SonarQubeSQ API - Rules:https://docs.sonarqube.org/pages/viewpage.action?pageId=2392166
Is it possible to Import SonarQube rules?
Try using theapi/measures/componentservice instead. You'll be able to specifycomponentKeyto narrow the result to only the projects you want.
We are using SonarQube ver 5.6.6. My requirement is to fetch metrics for all the projects currently in use, through the SonarQube API. I am able to get the same, using the below API URL.http://sqserver/api/resources?metrics=ncloc,coverageThe list returned by the API is huge. It includes all the projects created in SonarQube, from the beginning. Many of those projects are not active any more. So, I want to exclude those projects from the API response. How can I achieve this? Is there any way to specify multiple project names in the URL in the same way as we mention multiple metrics.
SonarQube API - How to fetch metrics for multiple projects
Usual suspectInconsistent measures and/or issue counts just after a SonarQube migration/upgradecanindicate that the local ElasticSearch index has been corrupted. (reminder:ElasticSearchis a search engine used by SonarQube to index issues, rules etc. so that it can access this data rapidly without having to query the database all the time, see SonarQubeArchitecture).Solutionstop SonarQubeerasesonar_install_dir/data/esstart SonarQube (note: restart might take longer due to reindexing)Root-cause analysisTo the question of why did that happen in the first place: a common case is an ElasticSearch index not being properly rebuilt after upgrading and/or changing database. Here's a typical scenario: you first start SonarQube on embedded H2 database, experiment a bit with it, then plug it to a full-fledged database. If the ElasticSearch index does not get scratched/rebuilt in between, then the index gets corrupted as the database/dataset it used to be in synch with just changed all of the sudden.Good newsAn improvement is coming in SonarQube v6.6 to better detect/handle this scenario at the application level (i.e. detect that ElasticSearch index should be rebuilt because the DB changed). SeeSONAR-5681-When a change occurs on the DB, the Elasticsearch index must be dropped.
Sonar scanner version:3.0.1.733 Sonarqube version: 5.6.5We have a sonar scanner on a Windows box which scans our project and submit a result to our Sonar server which is now on a Linux box. Prior to this, both the scanner and the sonar server and sonar db were on the same Windows box and we did not have any issues. We took a sonar db backup and restored it on another database on our new Linux box (now Sonar DB and Sonarqube server are on our Linux box). The server was installed from the native packagesMy Issue now is when our scanner submits to the server no issue get reported. We used to have some issues before and now everything is reset back to zero.I investigated a little bit, I can see the background tasks were received and processed successfully. Even the server UI shows the date of the latest scan.The scanner reports success as well. I ran the scanner in the debug mode and I can see connections to the server with 200 status responses.I cannot see anything out of ordinary in the logs.If I re-point the scanner back to my old Windows sonar box it still shows correct number of issues.Could anyone help me on this?
Sonarqube fails to show the submitted sonar scanner result
The suggested replacement rules should be linked. Click through. Now you're on the detail page of the suggested replacement. At the bottom next to "Quality Profiles", assuming you're logged in with the correct permissions, you'll see an "Activate" button. Use it to turn the replacement on in your profile. Now you can go back to the deprecated rule and remove it from your quality profile.
I'm looking for a way to change deprecated rules in SonarQube. I've got my own Quantity configuration, but Sonar shows that there are 2 deprecated rules, it suggest mi other ones, but I have no idea how to change/fix them. I've looked through internet and google, but there's no asnwer, can anyone help?
SonarQube 6.4, deprecated rules and how to fix them
SonarQube will do any intermediate stepsfor you. If you start a 6.5 server on a 5.6.6 database, it will automatically detect this discrepancy and internallydo one upgrade after another.Side note: SonarQube in some cases even undoes some migration steps after having done them. Just to be sure that you are able to migrate from any version to any higher version!
Can we upgrade SonarQube from 5.6.6 to 6.5 directly, or is there any intermediate step required?
How to upgrade from 5.6.6 LTS to 6.5?
The old dotnet plugin was a kind of enabling plugin for .NET analysis. It is no longer needed. Just install the latest version of SonarC#, which calculates the basic metrics and provides a number of rules, and it will replace the "sonar C# plugin v2.1" as well as the "sonar dotnet plugin v2.1".The NDeps, Gendarme, and StyleCop plugins are abandoned.I've never heard of the "sonar dotnet powertool plugin" and Google doesn't seem to know about it either.
Hi all am trying to upgrade sonarqube from 4.5.6 to 5.6.6Current plugins:Sonarqube v4.5.6sonar C# plugin v2.1sonar C# stylecop plugin v2.1sonar dotnet fxcop plugin v2.1sonar dotnet gendarme plugin v2.1sonar dotnet ndeps plugin v2.1sonar dotnet plugin v2.1sonar dotnet powertool plugin v2.1sonar resharper plugin v2.0Latest plugins:Sonarqube v5.6.6sonar resharper plugin v2.0 (same from v4.5.6)sonar fxcop plugin v1.0 (replacement for the sonar dotnet fxcop plugin v2.1)I need the replacement plugins for the above current list plugins other than the lastest plugins.
Is there any plugin to replace the Gendarme rules plugin
Install in your local repo by running below maven commandmvn install:install-file -Dfile=api-1.0.jar. This allows maven to have that jar without being fetched from remote repos.Then, you don't need to specify the scope assystem.
Need help in resolving a sonar issue. We are using some third party jars which are not there on maven public repository. I defined its dependency as:<dependency> <groupId>api</groupId> <artifactId>api</artifactId> <scope>system</scope> <version>1.0</version> <systemPath>${project.basedir}\lib\api-1.0.jar</systemPath> </dependency>But Sonar is giving a critical violation for it with messageUpdate this scope and remove the "systemPath".What is the right way of adding third party jar with maven which are not there on maven public repository.
Sonar violation for dependency scope system
http://localhost:9000/web_apilists the web service endpoints available on your server and provides documentation for each one. In my copy of 6.3, the documentation for "api/resources" saysRemoved since 6.3, please use api/components and api/measures insteadYou say you've triedhttp://localhost:9000/api/componentsand gotten an error. That's because there's not actually a web service there. You'll have to add the qualifier for the service you want, such as/api/components/search, as described in the docs for that set of services:http://localhost:9000/web_api/api/components
I would like to poll the quality gate execution status of my SonarQube 6.3 instance using a REST api call. I went through a few api calls, which did not give me the expected results.I tried to use these urls:http://localhost:9000/api/resourceshttp://localhost:9000/api/componentsBut I always got this response:{"errors":[{"msg":"Unknown url : /api/resources"}]}How can I poll the quality gate execution status via REST?
How to poll the quality gate execution status?
Source version is not a property of the scanner, but of the projects. Configure these values in your pom, or yoursonar-project.propertiesfiles, or in the command line arguments (-Dsonar.java.source=1.x), but not in the SonarQube Scanner properties.
I have 3 different projects. One of them is based on java 1.6 and the others are using java 8 features. I havesonar-scannerlocally and running the analysis by using scripts (no Maven or Gradle is being used). I have configured thesonar.java.sourceto be 1.6.My problem is thatsame runneris being used to analyze the other 2 projects (java 8 ones). How can I change the version of the java source for the other ones? I don't want to manually change it each time I want to run the runner. Can I somehow pass it as parameter?
Change java source version for multiple project using same sonar scanner
This is currently not supported to use the scanner on non Windows platforms.There is an open issue for that:https://jira.sonarsource.com/browse/SONARMSBRU-319
I am working on a Xamarin project. I would like to check code quality with sonarqube. I see there is a support for .net/c# project. I have followed the instructionherefor Xamarin.I was able to do the first two steps Begin and Rebuild. When i execute the third step "end"SonarQube.Scanner.MSBuild.exe endI am getting below errormono /Users/apple/Downloads/sonar-scanner-msbuild-2.3.2.573/SonarQube.Scanner.MSBuild.exe end SonarQube Scanner for MSBuild 2.3.2 Default properties file was found at /Users/apple/Downloads/sonar-scanner-msbuild-2.3.2.573/SonarQube.Analysis.xml Loading analysis properties from /Users/apple/Downloads/sonar-scanner-msbuild-2.3.2.573/SonarQube.Analysis.xml Post-processing started. SONAR_SCANNER_OPTS is not configured. Setting it to the default value of -Xmx1024m Calling the SonarQube Scanner... Execution failed. The specified executable does not exist: /Users/apple/Downloads/sonar-scanner-msbuild-2.3.2.573/sonar-scanner-3.0.3.778\bin\sonar-scanner.bat The SonarQube Scanner did not complete successfully 13:17:17.361 Creating a summary markdown file... 13:17:17.366 Post-processing failed. Exit code: 1
Does Sonarqube supports Xamarin for code quality?
Not yet (May 2017)This is requested and followed bySONAR-8632: "Support Microsoft SQL Server 2016".You can watch and vote this issue up.Update January 2018:This is closed and available inSonarQube 6.6(Oct. 2017).
Does SonarQube support SQL 2016?Based on documentation (Link), I did not find any useful information.
Does Sonarqube support SQL 2016?
You've found a false positive in a rule. Specifically, your test framework is not taken into account by the rule.The best course for rule false positives in general is to open a thread on theSonarQube Google Groupsaying, essentially, "For language L, could you add case X to rule Y, please?". Don't forget to include a minimum code sample to reproduce the false positive.UpdateIt's a Discourse instance now:https://community.sonarsource.com/
I have implemented controller test (using spring web testing framework).mvc.perform(MockMvcRequestBuilders.post("/calendar").contentType(V1_0) .content(toJSON(createCalendarDto(expectedCalendar)))) .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(V1_0)) .andExpect(jsonPath("$.id", is(notNullValue()))) //... .andExpect(jsonPath("$.email", is(expectedCalendar.getEmail())));this test covers some important cases, checking json structure and field values.Test works correctly, sonar prints a message:Tests should include assertions. Code smell Critical squid:S2699I could use workaround like@SuppressWarnings("squid:S2699")but I hope it can be managed in better way.java 1.8 Sonarcube Version 6.3.1 Spring-boot 1.4.3
Sonarqube squid:S2699 if jsonPath validation
You could create build which uses the branch/commit hash from which to build as a build parameter. Than create another build jobs that runsgit log --pretty=oneline head...whaterver_commit | awk '{print $1}'and takes the commit hashes to trigger the first parameterised job.Edited:Here is an pipeline script example that should work:node('your-jenkins-slave') { checkout scm def result = sh (script: "git log --pretty=oneline | awk '{print \$1}'", returnStdout: true) def hashes = result.split('\n') for (int i = 0; i < hashes.size(); i++) { def commitHash = hashes[i] build job: 'your_job_id', parameters: [[$class: 'StringParameterValue', name: 'BRANCH', value:commitHash]] } }
I want a Jenkins job to traverse through all commits on a branch in chronological order given a starting commit. I want to run Sonar on all commits on the branch. And Sonar is triggered through Jenkins. Is there an option in Jenkins to achieve this?It is not an option to invoke sonar from my local machine after checking out commits individually in my workspace.
How to have Jenkins build all commits in a single branch?
Like described in theofficial documentation of the SonarQube Scanner for Jenkins, you must usewaitForQualityGate()outside ofwithSonarQubeEnv:node { stage('SCM') { git 'https://github.com/foo/bar.git' } stage('SonarQube analysis') { withSonarQubeEnv('My SonarQube Server') { sh 'mvn clean package sonar:sonar' } // SonarQube taskId is automatically attached to the pipeline context } } // No need to occupy a node stage("Quality Gate"){ timeout(time: 1, unit: 'HOURS') { // Just in case something goes wrong, pipeline will be killed after a timeout def qg = waitForQualityGate() // Reuse taskId previously collected by withSonarQubeEnv if (qg.status != 'OK') { error "Pipeline aborted due to quality gate failure: ${qg.status}" } } }
Using pipeline code,stage ('SonarQube') { withSonarQubeEnv { dir ('mydir/') { sh "'${mvnHome}/bin/mvn' sonar:sonar -Dsonar.login=something -Dsonar.projectKey=someproj -Dsonar.projectName=somename" } } timeout(time: 15, unit: 'MINUTES') { def qg = waitForQualityGate() if (qg.status != 'OK') { error "Pipeline aborted due to quality gate failure: ${qg.status}" } }Which progresses crrectly over the first mvn section and breaks on waitforqualitygate() operation:org.sonarqube.ws.client.HttpException: Error 401 on http://mysonarserver/sonar/api/ce/task?id=somecodethe link is clickable and leads to a filled json structure.Why the build fails? Webhook seems to be set properly in sonar, and other sonar projects are working correctly, webhook in jenkis also seems to be active.
Why SONAR fails at waitForQualityGate() with error 401?
You get this message when you are trying to run a Java application that requires Java 8, but you only have 7 or lower.SonarQube requires Java 8 (bytecode version 52.0). You can try to install Java 8, or try SonarQube 5.5 instead (5.6 was the first version to mandate Java 8).
WrapperSimpleApp: Unable to locate the class org.sonar.application.App: java.lang.UnsupportedClassVersionError: org/sonar/application/App : Unsupported major.minor version 52.0I'm trying to run the simplest sonarqube (2 minute intro) project and have gotten this error. From looking around I thought this error was supposed to occur when you don't have the latest version of java installed on mac. I have java version 8, installed via brew, am I missing something?
How to run sonarqube on mac?
I decided to stop contributing to the SonarQube ecosystem.Tamas Kende is (re)taking the lead on the CSS / SCSS / Less plugin that is now hosted athttps://github.com/kalidasya/sonar-css-plugin
Where is the sonar-css-plugin gone ?I was trying to install a sonarqube test instance but couldn't install this plugin, as the github repository seems gone.
https://github.com/racodond/sonar-css-plugin gives a 404
The Sonar-ESQL-Plugin is only a plugin for sonarQube. For a eclipse integration the plugin needs to support SonarLint, which it does not.To analyse ESQL code you need to install SonarQube, add the ESQL-plugin to it and run the analysis using maven or SonarQube Scanner:https://docs.sonarqube.org/display/SCAN/Analyzing+Source+CodeBTW: The website you used to download the plugin, doesn't provide the latest version. Try to download it for github:https://github.com/EXXETA/sonar-esql-plugin
I am trying to use the Sonar-ESQL plugin in IIB V10 for ESQL code scanning. I downloaded the plugin jar file from the websitehttp://www.sonarplugins.com/esql, then added the jar file in the plugin folder for Eclipse and restarted Eclipse. But I dont see any difference in Eclipse. How do I use that plugin? There are no instructions on that site.Please suggest something. Thank you very much!
Using ESQL-Sonar plugin in IIB V10
This rule requires configuration. List names of variables and functions shared across files in "sonar.javascript.globals" project property.
I have a JavaScript project that consists of several source files. These files are referenced in<script>tags inindex.htmlpage. There are functions and variables defined in those source files and used in other source files. The problem is that Sonar treats those files as independent and I gotNon-existent variables should not be referenced (javascript:S3827)issue. Can anybody help how to avoid this?ThanksPavel
SonarJS - how to avoid "Non-existent variables should not be referenced" issue
SonarQube 6.2 offers the ability to register up to 10 URLs at the global level and an additional 10 at the project level to be POSTed to once the analysis report has been processed server-side.
I am integrating TFS 2015 with SonarQube 6.1, and I need to know when the analysis are finished to run another process.I have had a look at some triggers called hooks, but it required develop a plugin for SonarQube.Is there another way of doing this?
It is possible to send HTTP response when the analysis is finished on SonarQube?
By applying templates (predefined values), you've removed your own account. Please contact us with this form :https://about.sonarqube.com/contact/
I am usingsonarqube.comwithTravisfor on of my project:Cognifide/aet. While granting permissions for my colleague I have probably:Selected all available permissionsClickedApply TemplatebuttonNow me and my colleague have an issue with permissions: neither of us can see theAdministrationtab for theCognifide/aetproject. The Travis builds are failing formy colleague's tokenas well as formine.There is already similar question:permissions for Administrator accidentally removed, but I don't have access to database in this case.What can I do in order to reset the permissions? If it would be easier to delete this project and add it again forsonarqube.comthen it is also acceptable solution.
permissions for Administrator accidentally removed - sonarqube.com
SonarQube cannot recognize the fact that successive calls ofsettings.getStringwill return the same value.Might be it is right because it possible if other thread modify settings between calls.So assigning value to variable as @Andreas mentioned in comment should resolve this issue.UPD:public boolean isLocalHost(@Nonnull final ServletRequest request) { if(settings == null) { return false; } String localhost = settings.getString(LOCALHOST); return localhost != null && localhost.equals(request.getServerName()); }Or check variable from another side:public boolean isLocalHost(@Nonnull final ServletRequest request) { String requestServerName = request.getServerName(); return settings != null && requestServerName != null && requestServerName.equals(settings.getString(LOCALHOST)); }UPD2: Removed one of snippets becauseHttpServletRequest.getServerName() occasionally returning null in concurrent use?
I have the following code block/** * Checks if the server name is equal to localhost in the servlet request. * * @param request * servlet request * @return true if the server name is equal to localhost. */ public boolean isLocalHost(@Nonnull final ServletRequest request) { return settings != null && settings.getString(LOCALHOST) != null && settings.getString(LOCALHOST).equals(request.getServerName()); }But Sonarqube keeps on complaing thatgetStringmay be nullable, even though from what I can tell it can't happen due to boolean short circuiting
How do I fix squid:S2259 `NullPointerException might be thrown as 'getString' is nullable here`?
Quality gate compliance is calculated as part of the analysis. No way around that.
Is there any way to tell Sonarqube to check again if a project passes a quality gate without starting a new analysis?Currently, whenever I change the metrics of a quality gate, I would run a new analysis (obviously with the same result, as there are no code changes) for every project using that gate to get updated information whether it passes with the new requirements.I hope there is an easier way?
Re-evaluate quality gate in Sonarqube without a new analysis
Thanks. I wrote the linked google group note. Sadly it looks like SSO as it worked isn't going to be supported even if the plugin is updated. Users will still have to click a link.https://github.com/SonarQubeCommunity/sonar-activedirectory/issues/9Use the BaseIdentityProvider API (https://github.com/SonarSource/sonarqube/blob/master/sonar-plugin-api/src/main/java/org/sonar/api/server/authentication/BaseIdentityProvider.java) ->It will allow SSO by creating a link in the login page
After upgrading to SonarQube 6.0 we cannot use the SSO login plugin anymore. This is our SonarQube.log in TRACE mode:DEBUG web[o.s.s.u.NewUserNotifier] User created: xxxx@xxxx. Notifying NewUserHandler handlers... TRACE web[sql] time=0ms | sql=select u.login,u.name,u.email,u.active,u.scm_accounts,u.created_at,u.updated_at from users u where u.updated_at>? | params=1470426045520 TRACE web[es] ES refresh request on indices 'users' | time=94ms **ERROR web[rails] cannot load Java class org.sonar.server.user.RubyUserSession** DEBUG web[http] GET /active_directory/validate | time=2703msThe plugin configuration is very simple (just one line):sonar.security.realm=ACTIVE_DIRECTORYIs there a way to solve this problem by adding other configuration settings and how can I tell if this error is in the SonarQube or SSO code?
Error using sonar-activedirectory 1.0 in SonarQube 6.0
You cannot subscribe someone else to SonarQubespamnotifications.(This should be one of the things you see Bart Simpson writing on the blackboard.)You must convince them to subscribe themselves.SonarQube is a tool first and foremost for developers. Shove something down a developer's throat/inbox and you it will quickly be filtered to the trash.This is your opportunity to train new developers on how SonarQubehelps them be better at their jobsand show them why they should be interested enough to subscribe on their own.
I installed a Sonarqube webapp to control code quality in my company. I use LDAP plugin to authenticate users and everything works fine.Moreover, we use another plugin (Issue assign plugin) which assign issues to their SCM authors and send emails to them so that they can correct the code.However, when a new user logs in, notifications are off. We'd like to create a batch which would turn notifications on for all users (using mass update whatsoever) but we can not locate where user account's notifications are stored ... I didn't find it in the database.Have you an idea of where this setting is stored ? (We use Sonarqube 4.5.6 for compatibility issues).
How could I mass update Sonarqube account notifications?
You're looking forSONAR-5366 Make it possible to back up and restore customizations of rules, which is not yet implemented, unfortunately.
I am using SonarQube 5.1.2. I have created many custom rules using Rule Templates for quality profiles of both Java (plugin version 3.13.1) and C# (4.3) languages. I wanted to replicate this SonarQube instance onto a new server and hence did a Backup of the quality profiles and performed 'Restore Profile' on the new SonarQube server.Strangely, all the custom rules are not imported on to the new SonarQube instance. Why is it so? What should I do to import the custom rules onto new SonarQube instance?
Custom Rules do not get imported when Quality Profile is restored on another SonarQube instance
It is possible to set a version on SonarQube snapshot. You can then use this version inthe differential periodincluding the leak period.Note also that adding an event to a snapshot prevent the snapshot to get deleted from the history. Find more information about this inHistory and Events documentation.You can set a version to a snapshot from SonarQube UI in the history of project's analyses (project administration permission is required).
Is it possible to freeze a version in SonarQube's time machine and make this snapshot always visible in the history chart? For example I have tagged a version in Git as v1.0 and I want this to be always in the chart so I can compare it with the latest versions and track the progress. Is the only way to launch Sonar Maven each time on this version?
Is it possible to freeze a version in SonarQube's time machine?
Okay I figured it outI forgot to add a/t:rebuildin between building with MSBuild and running the End Analysis command.
I got a Jenkins Server set up on Windows 2012 R2. These are my build settings:Underneath you see the error. It should be said that the pre-build step runs successfully:[Test CSharp Build Job] $ ...\Jenkins\.jenkins\tools\hudson.plugins.sonar.MsBuildSQRunnerInstallation\MSBuild_2.0\MSBuild.SonarQube.Runner.exe end SonarQube Scanner for MSBuild 2.0 Default properties file was found at ...\Documents\Jenkins\.jenkins\tools\hudson.plugins.sonar.MsBuildSQRunnerInstallation\MSBuild_2.0\SonarQube.Analysis.xml Loading analysis properties from ...\Documents\Jenkins\.jenkins\tools\hudson.plugins.sonar.MsBuildSQRunnerInstallation\MSBuild_2.0\SonarQube.Analysis.xml Post-processing started. SonarQube Scanner for MSBuild End Step 1.1 No ProjectInfo.xml files were found. Possible causes: 1. The project has not been built - the end step was called right after the begin step, without a build step in between 2. An unsupported version of MSBuild has been used to build the project. Currently MSBuild 12.0 upwards are supported 3. The build step has been launched from a different working folder Generation of the sonar-properties file failed. Unable to complete SonarQube analysis. 11:18:18.015 Creating a summary markdown file... Post-processing failed. Exit code: 1 ERROR: Execution of SonarQube Scanner for MSBuild failed (exit code 1)So in my Jenkins Configuration I have this:Am I missing something to make this work?
SonarQube can't complete the post-build step
if (params.isEmpty() && params == null)If you've successfully executedparams.isEmptywithout throwing aNullPointerException, thenparamsis necessarily non-null.I think perhaps you meant:if (params == null || params.isEmpty())
I have the below lines of code and sonarqube is saying,"Change this condition so that it doesn't always evaluate to false".Below is the line.if (params.isEmpty() && params == null) { throw new ServiceSDKException("Parameters cannot be empty or null!"); }Below is the whole method in case you need.public void init(String params) throws ServiceSDKException { if (params.isEmpty() && params == null) { throw new ServiceSDKException("Parameters cannot be empty or null!"); } String[] configParams = params.split(","); options.setMqttURL(configParams[0]); options.setMqttClientID(configParams[1]); try { options.setWillMessage("v1/items/mqtt/0/event/will" , "Last will" , 2, true); new File("./db").mkdir(); edgeNode = EdgeNodeFactory.createMQTTChannel("./db", options, subscriptionTask, 500, 500); isClientConnected = true; } catch (EdgeNodeException e) { isClientConnected = false; throw new ServiceSDKException("EdgeNodeException occurred", e); } }
How can the below line generate sonar qube issue of always evaluating to false?
The best solution is to specify which sources to analyze using a GLOB pattern. For example:sonarlint --src '**/src/main/**'.
I am using Sonarlint command line tool Version 1.0 for static code analysis in my Android project.It is analyzingsrcas well asgenfolder. I do not want gen folder to be analyzed.As sonarlint has very less documentation, can anyone help me on "How to add exceptions/Exclusions in sonarlint command line tool".
SonarLint Command Line Tool - Add File/Folder Exceptions
As perSVN Plugin documentationyou should most likely usesonar.svn.usernameandsonar.svn.password.securedproperties.The setting of such properties can be done in various places. Either in your project definition (seeScanner for Maven) or just follow the documentation of theScanner for Jenkins(for example using-Dsonar.svn.username).
I am trying to run sonarqube as part of a hudson job. I installed sonarqube 5.4 and sonar plugin 2.0.1 in hudson.But when the job runs I get the following error, where do I provide SVN authentication details for Sonar?I already provided SVN details as part of my job but sonar is unable to read that properties.Can't I make sonar to read source downloaded by hudson instead of again trying to connect to SVN?Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.0.1:sonar (default-cli) on project MyProject: Error when executing blame for file Myfile.java: svn: E170001: Authentication required for ' Subversion repository'
Sonarqube integration in hudson and SVN
sub-modules should be properly deleted but for the sake of it you could check forghost dataunder Settings - System - Bulk Deletion.You could also query theapi/projects/index?subprojects=trueWebService to check ifsomesubmoduleappears somewhere.
I analyzed a project and then deleted it throught SonarQube web interface. This is on a fresh installation of SonarQube 5.1.2.In the web interface I can no longer see any projects.When I runmvn sonar:sonaranalysis fails with message similar to[ERROR] Failed to execute goal org.codehaus.mojo:sonar-maven-plugin:2.7.1:sonar (default-cli) on project myproject: Module "somesubmodule" is already part of project "myotherprojectkey"So I think what happens is that in a multi-module Maven project, project deletion through web interface will only delete the top-level module as a project. All other lower level modules will remain in the database preventing code analysis.These "projects" cannot be deleted through the web interface because they are invisible.I check the database and it is true that theprojectstable is not empty at all.Is there a way to purge the database from project data in a consistent way?I don't want to reinstall SonarQube just for the sake of removing a project.
SonarQube fail to execute goal on empty instance "module already part of project"
It is not possible and there's no plan to add such a feature. The only thing that you might want to do is to exclude this rule for this very specific file by setting exclusions:http://docs.sonarqube.org/display/SONAR/Narrowing+the+Focus#NarrowingtheFocus-IgnoreIssues(Ignore Issues on Multiple Criteria criterion)
Is it possible to Suppress Warnings in properties file? Warnings are generated bySonarQube Java Properties Plugin.Warning key *jproperties:** is (for examplejproperties:key-naming-convention)I tried to add comment with#@SuppressWarnings("jproperties:key-naming-convention")Before offending line but it does not work.I know I could do one ofdisable those rules in my quality profilesuppress warning in Sonar Web UII do not want solution 1) because it will ignore rule for all files, not just for single place.I do not like solution 2) because I have separate sonar project for each branch (master, develop, feature branches) and separate project for each developer (for ad-hoc analysis). I do not want to suppress warnings in webUI for each project separately, I prefer to suppress warnings once-in source code.
How to Suppress Warnings in Sonar for properties file?
You need to run an analysis. Assuming yours is a Maven project, open a command prompt, and:cd my/project/dir mvn clean install mvn sonar:sonarNote that the two Maven commands could be combined:mvn clean install sonar:sonar
I got an embarassing question. We just started programming a new project with Java in NetBeans. In School we once loaded it to sonarqube, but if I tryhttp://localhost:9000/(after starting sonarqube) in explorer there is only the old version of the project on my dashboard. I forgot the way to upload the current version of my project to sonarqube.Thank you for your help
How do I load my NetBeans project into sonarqube?
The problem seems to come from the Scm Stats Plugin. I suggest you to remove it (it is not compatible with SonarQube 5.2).
I'm trying to run Sonar from within Maven v3.3.3, using the v2.7.1 of the org.codehaus.mojo:sonar-maven-plugin, but I get this error:[ERROR] Failed to execute goal org.codehaus.mojo:sonar-maven-plugin:2.7.1:sonar (default-cli) on project mio-tbc: org.sonar.plugins.scmstats.MavenScmConfiguration has unsatisfied dependency 'class org.apache.maven.project.MavenProject' for constructor 'public org.sonar.plugins.scmstats.MavenScmConfiguration(org.apache.maven.project.MavenProject)' from org.picocontainer.DefaultPicoContainer@e97f51c:205<[Immutable]:org.picocontainer.DefaultPicoContainer@377e90b0:211<[Immutable]:org.picocontainer.DefaultPicoContainer@64921450:36<| -> [Help 1] [ERROR] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. [ERROR] Re-run Maven using the -X switch to enable full debug logging.Any ideas what's wrong?ThanksNick
Maven sonar:sonar failing using the latest plugin version
This feature is now a dedicated widget called "Project File Word Cloud" that you can add on one of your dashboards in SonarQube.
We have a Java project, which gets built by a Jenkins job and is then analyzed by Sonar.We used to have a view within the Sonar part of the Jenkins build results called "Clouds", which showed the complexity of a class versus its test coverage, which was a very useful metric. (Seeherefor an example)But now - I assume after some updates which were made to Sonar/Jenkins - it is not longer available. Can someone tell me how to get it back?[We use SonarQube 4.5.4]
How do I get the "clouds" view back in Sonar?
This behavior is normal.When you resolve (mark False Positive, Won't Fix, or Fixed) an issue the numbers in your dashboard won't reflect that resolution until after the next analysis. That's because those dashboard numbers areMetrics, and metrics aren't updated on the fly - only during analysis.However, you should see the counts on the Issues page update immediately. Those numbersarecalculated on the fly based on the issue set that matches the current query.
When I mark as false positive or resolved some issues, the total number of issues is not decremented. Is that behavior normal? If so, is there a way to decrease this number according to the number of marked issues?I'm using SonarQube 4.5.4 (LTS).
How to decrease the number of issues?
I know its a 4 year old post but I was working on it now and this works for lines of code -import requests from requests.auth import HTTPBasicAuth token = 'xxx' PARAM = {'component': 'your_project', 'metricKeys': 'ncloc'} test_url = 'http://sonarqube.com:9000/api/measures/component' test_response = requests.get(test_url, auth=HTTPBasicAuth(username=token, password=""), verify=False,params=PARAM) test_json = test_response.json() print(test_json)
I am trying to pull out useful metrics from SonarQube (like lines of code, technical debt, sqale rating, etc).The issue is I am stuck on the best way to do this. I am looking at their Web Service API documentation,http://docs.sonarqube.org/pages/viewpage.action?pageId=2392172. Is this same thing as a RESTful service?So as a simple example...Nemo is a public demo of SonarQube. And the following demonstrates how to get lines of code.Get the metric 'Lines of Code' (key = ncloc)GEThttp://nemo.sonarsource.org/api/metrics/nclocSo my question is, can I write a Python program or something to grab the metrics I want from SonarQube? Is this a RESTful API? What is the best way to get this data?Thanks!
How can I pull out useful metrics from SonarQube
Your project structure looks like the old Eclipse/WSAD structure where you have sources on the root and a "bin/" folder for your compiled classes. Your application code looks like it has a package definition that starts withcom.So I am presuming this is your structure:project root +-- * = source files +-- bin/* = compiled files +-- Tests/JUnit/* = test source files +-- dependencies/*.jar = extra JAR files +-- rapports/junit/* = JUnit test results +-- rapports/jacoco/coverage.exec = Jacoco resultsYour configuration should be:sonar.sources=. sonar.tests=Tests/JUnit sonar.jacoco.reportPath=rapports/jacoco/coverage.exec sonar.junit.reportsPath=rapports/junit sonar.java.binaries=bin sonar.java.libraries=dependencies/*.jar sonar.inclusions=com/**Thesonar.inclusionsshould have a more full path e.g.sonar.inclusions=com/trajano/project/**
To begin with, I'm aware ofthis question. Since I'm neither using maven or jenkins, I can't use the provided solution.When analysing my project with sonar-runner, I get the following warning :Class 'XXX/XXX/XXX' is not accessible through the ClassLoaderon every class of my project. I also get the following warning from the jacoco coverage plugin :No JaCoCo analysis of project coverage can be done since there is no class files.My sonar-runner properties are defined as follows :sonar.sources=com // sources are analysed sonar.tests=Tests/JUnit/com // works, since wrong location results in an error sonar.binaries=bin/com // no presence in logs sonar.java.libraries=dependencies/*.jar // no presence in logs. sonar.junit.reportsPath=rapports/junit // results are displayed sonar.java.coveragePlugin=jacoco sonar.jacoco.reportPath=rapports/jacoco/coverage.exec // not loggedNeedless to say, I checked the various path (event replaced them by their absolute counterparts or by listing every jar in binaries) but I'm unable to make the analysis.Any ideas on what may go wrong ?
WARN - Class 'XXX/XXX/XXX ' is not accessible through the ClassLoader
MongoDB is not supported. Check this -http://docs.sonarqube.org/display/SONAR/Requirements
Can't see anywhere whether MongoDB is supported by SonarQube. If anyone could help that would be great. Thanks.
Is MongoDB supported by SonarQube?
See in yoursonar.properties:# Paths to persistent data files (embedded database and search index) and temporary files. # Can be absolute or relative to installation directory. # Defaults are respectively <installation home>/data and <installation home>/temp #sonar.path.data=data #sonar.path.temp=tempYou can uncomment the linesonar.path.dataand set the value as needed.
How to change data folder in sonarqube? I need to change the installation data folder to other location, is it possible? Who is the responsible of write & change this folder? Is the wrapper? I can change de location of h2 database but not the data folder location. I use Sonarqube 5.0
How to change data folder in sonarqube?
I found 2 solutions for this problem:Rename the key of the submodule in projekt I (Project configuration > Update key)Delete project I.
I'm really stuck on this:1) existing project I has module A2) create new project and move module A into new project IISonar tells me module A is already part of project I.I've tried all manner of exclusion patterns etc and got nowhere.the (maven) module is at 'feature-A' level.${project.baseDir}/my-features/feature-A/benefit-1Hints or suggestions please!
sonar module already part of project
I was able to fix this issue by going into Manage Jenkins -> Configure System -> Scroll to the SonarQube section -> Click advanced -> fill in "Version of sonar-maven-plugin" with the verison you would like to use.....I used 2.5.
I'm building a project in Jenkins with Sonar Integration.Everything goes smoothly until the sonar analysis part. I get the following error:[ERROR] Failed to execute goal org.codehaus.mojo:sonar-maven-plugin:2.2:sonar (default-cli) on project project-whatever: Can not execute SonarQube analysis: Please update sonar-maven-plugin to at least version 2.3 -> [Help 1]and then the build fails.I must explain that I have no references to sonar in my project pom.xml. This has been done exclusively with Jenkins configuration.I'm using the latest available versions both on Jenkins (1.599) and Sonar (5.0). All Jenkins plugins are updated. Already looked for a way to update the sonar-maven-plugin version, but I can´t find it: either it doesn't exist or I'm not looking at the right places...Does anyone have any ideia how to work around this?
Please update sonar-maven-plugin to at least version 2.3
If you want to import the same list of rules than what is configured in your SonarQube instance, you can go to "Quality Profiles > Your_Quality_Profile > Permalinks": you will find a link that you can use to download the list of Findbugs rules configured in your quality profile.For instance, take a look at this page on Nemo:http://nemo.sonarqube.org/profiles/permalinks/169Then, you just need to import this downloaded file in IntelliJ.
I'm using the FindBugs-IDEA plugin for IntelliJ. It finds much less bugs than our SonarQube (SonarQube uses FindBugs under the hood). The plugin says I can Import/Export a bug collection from xml or html. Where can I find these collections?
Where can I find a bug collection to import into FindBugs?
I would suggest to have two separate coverage tools for Java and Scala. More specifically, useScoveragefor Scala (withplugin for Sonar).The reason is that for Java you would probably like to measureline coveragewhere for Scala it's much better to measurestatement coverage. Simply said because there are many statements on a single line in Scala and you would like to measure which of them were invoked. I've writtenan article about this.
The project is a multi module maven project with 90% of the source code written in Java (there's a small bit in Scala). The unit tests are 80/20 java/scala, and the integration tests are 20/80 java/scala.I tried Clover, but(at this time)it doesn't support scala.I tried Jacoco. First I ran into problems getting any results due to the mutli-module configuration, but now using Sonar I've got the java coverage shown (thankshttp://www.aheritier.net/maven-failsafe-sonar-and-jacoco-are-in-a-boat/). I used timezra (http://timezra.blogspot.com/2013/10/jacoco-and-scala.html) with jacoco, but that only analyzed the small bit of source code that is scala.I started to try Scoverage, but that seems to have the same problem as timezra (it analyzes scala-to-scala, not the mix that I have). I therefor haven't even tried scct or undercover.Is there any tool that handles mixed java/scala?
getting code coverage for java code with scala tests
Unless you're using the Maven plugin, Sonar will not understand how to compile your code, so it's up to you to ensure that sonar is run against fresh binaries.It's Findbugs that requires access to the compiled class files and dependency jars, in order to complete it's analysis.
Since sonar is a static coda analyzer, when we need to specify binaries. It is not going to compile and build .class by itself.What if I ran a latest source with an old binary??
What is the importance of class files in Sonar analyzer?
Sonar is not smart enough to know if an object is mutable or not. Especially if you're returning aList, it can't tell if what you're actually returning is anArrayList, anImmutableListor an unmodifiable list. So it doesn't emit any warning to avoid flooding you with false positives.Arrays and Date, on the other hand, are well-known standard classes that are mutable, and for which it can safely emist this warning.
I'm getting the following violation reported by Sonar: May expose internal representation by returning reference to mutable object.It's because I'm returning a String[] from a getter.I know what the problem is and how to solve it but going through several thread on stackoverflow I noticed that seems to be happen for String[] and Dates for example:Malicious code vulnerability - May expose internal representation by returning reference to mutable objectMalicious code vulnerability - May expose internal representation by incorporating reference to mutable objectBut given the reason why that happens which is returning a reference to an object whose internal state could be changed by the caller. Shouldn't that violation be raised for every getter returning a mutable object?For example:public List<String> getList() { return list; } public Foo getFoo() { return foo; } //where foo is just a random object with getters and setters...The caller could change the state of the returned objects. Shouldn't sonar report the same for those?Many thanks, Francisco.
Malicious code vulnerability - May expose internal representation by returning reference to mutable object - With what objects?
It is because your static code analysis tool detectsnullas a hardcoded literal, which, rigorously, is true.The recommended behavior is to declare a constant object likefinal static Object NULL = null;and use it likeif(singleWrapper != NULL)But I haven't still met a developer doing this. In this case, I think you're OK and you can ignore the code check warnings. That's my 2 cents.
I am getting error likeAvoid Literals In If Conditionin sonarqube , and unable to find the proper solution to it.SingleWrapper singleWrapper=null; : : singleWrapper=createWrapper(); : private void wrap(){ if(singleWrapper != null){ //Here i am getting error. //do Something } }I know this question seems to be repeated one but its not,because previously asked forString. Thanks for any help.
Avoid Literals In If Condition SonarQube error
Go to the Settings > General page and the add the "buildstability" plugin part of the default list of plugins to be excluded for Preview and Incremental modes. Ticket created to make this behavior the default one :https://jira.codehaus.org/browse/SONAR-4980.
I'm new to sonar and installed this Build-stability plugin. But when i run it locally i get this error.Caused by: org.sonar.api.utils.SonarException: Access to the secured property 'sonar.build-stability.username.secured' is not possible in preview mode. The SonarQube plugin which requires this property must be deactivated in preview mode.How to disable a plugin in different modes? Any other help would be appreciated.
Disable Sonar Build Stability plugin in Preview Mode
Turns out i misunderstood the complaint of Sonar. It was not expecting a specific name for the logger, but for the code to send both the message AND the exception itself to the logger, like so:catch (IOException e) { Log.e(AnkiDroidApp.TAG, "<actual message here", e); }
I get this issue:"Exception handlers should provide some context and preserve the original exception"On code like this:catch (IOException e) { Log.e(AnkiDroidApp.TAG, "<actual message here"); }How can I tell to Sonar that our logger isn't Logger, but Log?
How to configure logger used for "Exception handlers should provide some context and preserve the original exception" issue?
See alerts / Quality Gates section in SonarQube.(http://docs.codehaus.org/display/SONAR/Quality+Profiles#QualityProfiles-alertsEditingAlerts) and Build Breaker plugin (http://docs.codehaus.org/display/SONAR/Build+Breaker+Plugin).
So we have Checkstyle, PMD, Findbugs as tools which performs static code analysis or work on bytecode to find various issues in code and using them in Jenkins/Hudson (under Post build actions), can turn a build to a unstable, failed, successful build depending upon what threshold values we set there.As SonarQube is the upcoming/future single dash for showing all such analysis in one page for a project/module, I was wondering where in SonarQube settings (I can set such threasholds) to make a build as a failed, unstable, successful i.e. Jenkins will launch the build (ANT/Maven/Gradle etc), calls, sonarRunner (task in Gradle) / sonar-runner (executable in Linux/Unix), then if threasholds are not good, then Jenkins will mark the build as unstable/failed/successful depending upon the set threashold values.Any ideas?
Setting thresholds values - Java - Static Code analysis - SonarQube Sonar
To start Sonar :sonar.sh startTo stop Sonar :sonar.sh stopTo uninstall Sonar : remove the Sonar installation directory.That's it !
To install sonar there is asonar.shfor it. How to uninstall sonar then on linux shell? Is there any script to remove all and don't leave any trash in the system?
Sonar Qube uninstall linux
If the SonarQube server tries to recreate the tables when using the new host that might mean that the content of the schema_migrations table has been incorrectly migrated.
I export my Sonar database (Oracle) and import it into another Oracle database. And I change my Sonar's sonar.properties to the new host. But when I start Sonar, it try to create the table and because these tables are already on the database server, I cannot start Sonar.Is there any configuration I should set for this change? The change reason is the old database is too small and we want to change to larger database.
How to move Sonar database to another host?
You should definitely give a try to JaCoCo. Its integration with Sonar allows to benefit from new features, for example :merge coverage by unit and integration tests. Seehttp://www.sonarsource.org/sonar-3-3-in-screenshots/track the relations between tests and tested code (since sonar 3.5). You can find a screenshot on the documentation page:http://docs.codehaus.org/display/SONAR/Resource+Viewer#ResourceViewer-CoverageTab
Reasking my older question:Java test coverage: who covers what?Background: I look at sonar's coverage report for a class and want to know, which test contributes to the coverage of a specific line / branch, so that it easy to got to that test and add the test for the newly introduced if-branch.Are there other (preferably free) alternatives to clover in the IDE? Perhaps even such that they can be included into sonar ?Or maybe tricks to enhance, accumulate information with some scripting in emma-reports ?Or even further, patch emma or cobertura to log the required info (instead of logging a "1" for counting, one could well log the names of class under test and the test, I assume)Thanks!
Free alternatives to Atlassian Clover?
Okay, despite the fact that this seems to be a little longer and that I need support forpdependin sonar, I have hacked a "solution"Rename yourpdependcommand topdepend_origand create newpdependcommand:echo "Renaming files that use traits to *.phphide" grep --files-with-matches -re "use .*Trait" . | rename -v s/.php/.phphide/ find -name "*Trait.php" | rename -v s/.php/.phphide/ echo "Running original pdepend" pdependorig $@ echo "Renaming files that were hidden back to *.php" find -name "*.phphide" | rename -v s/.phphide/.php/It hides files where you are using Traits so that Traits are excluded frompdepend. As a hack, it works.
I am usingSonarfor QA with PHP. Currently I have started to usingtraitsin source codes but since that, Sonar fails to analyse the source code with phpdepend - it is not able to parse informations in phpdepend output file. I have found that this is aBug in Sonar's PHP plugin. This bug effectively disables using Sonar's PHP Plugin for PHP 5.4 - which is really bad, as php5.3 is reaching end of life soon!I do not want to believe that nobody uses sonar and QA for PHP 5.4, so there must some solution exists...
Checking PHP 5.4 code with Sonar - unable to parse informations in phpdepend output file
A Sonar install consists of 2 parts: the Sonar server, and the Sonar batch (usually run through a CI software like Jenkins).Our advise is to have both parts as close to the DB as possible. This is all the more important forthe batch partwhich heavily queries and updates the DB when doing analyses. Having the DB far from the CI server that runs Sonar analyses can have a huge impact on performances.
We are trying to set up a dedicated/single Sonar instance at an organization level with close to 60 projects (different languages) with MySQL DB. The goal is to make sure that the system performs optimally, i.e both Sonar and MySQL DB.Below are the hardware specification for the VM that we are planning to procure.RAM: 8GB , Hard Disk: 100GB, OS: Windows 2008 serverThe only question with this set up that we want to have is, whether to have Sonar and MySQL running in the same machine or have a dedicated machine to run MySQL server in the same network.Any inputs is highly appreciated.
Sonar: local or external MySQL database?
The fact that Sonar server is running on a different machine is definitely not a problem for launching an analysis, and you shouldn't have any problem running a Sonar analysis from your Jenkins master, may the Sonar DB and/or the Sonar Server be on different machines.You just have to make sure that the configuration on your Jenkins (= Sonar properties) + the configuration of your machine (= potential firewall) allows the Sonar batch to:Query the Sonar Web server URLsQuery the configured database
I have a Jenkins job running Maven on master machineI've added a post build step to run Sonar and pointed it to the project'spom.xml.The problem is that Jenkins build runs on master, and Sonar server is running on different machine. So when the build finishes, Sonar looks for the build artifacts in the repository where it's installed instead of the master machine where Jenkins ran Maven.Is there a workaround other then installing both Sonar and Jenkins on the same machine ?More Details:[ERROR] Failed to execute goal on project server-api: Could not resolve dependencies for project frm:frm-server-api:jar:1.0-SNAPSHOT: Failure to find frm:frm-model:jar:1.0-SNAPSHOT in http://DIFFERENT_SERVER:7080/nexus/content/repositories/releases/ was cached in the local repository, resolution will not be reattempted until the update interval of releases has elapsed or updates are forced -> [Help 1]TheDIFFERENT_SERVERis a server not related tosonarserver orJenkinsserver, We are using it but not in the context of this project so i don't really know how it got there. I am guessing this is configuration error. more details:The Jenkins job type is a general project and not a pure maven job.I am using thesonarjenkins plugin as post build trigger and specifying thepom.xmli'm using.I have configuredsettings.xmlinMAVEN_HOME/confwith the required details.
Sonar looks for artifacts in wrong maven repository
The problem was that all projects were not being built to the same output directory, which was corrected. All projects must be built in order for FxCop to be able to scan since FxCop scans binary files.
I am currently trying to use FxCop to analyze the assemblies generated by my solution within Sonar and am getting the following message when Sonar calls FxCop to scan each project:INFO No assembly to check with FxCopAny help with correcting this issue is much appreciated.
How to get FxCop working with Sonar for a C# solution?
The only way to configure the PMD file generated by Sonar is to modify the quality profile that you are using. To do so, you have to log in the Web admin console and go to the "Quality profiles" section (you may have to create a profile of your own if you're using the default one - this is easy, you just copy it)Seehttp://docs.codehaus.org/display/SONAR/Quality+profilesfor more information.
I would like to activateprotectedAllowedoption from checkStyle in my pom.xml.How can I do this ?
How to customize PMD configuration file generated by Sonar from pom.xml?
You're not obliged to use Maven if you want to run Sonar analyses. You can also use Ant (see doc) or simply the Java Runner (see doc).The Java Runner is really the simplest way, and this is actually the preferred way when analysing applications built with other languages than Java (for instance C#, PHP, Groovy, Python, Cobol, C/C++, ...)The main advantage of using Maven for Java projects is that it compiles the project and runs the unit tests for you.Using Ant can certainly be a bit more complex, however we providesample applicationsthat you can use to get started.
I'm messing around with Sonar, there are a limited amount of tutorials and guides on how to get sonar up and running without a pom.xml.When I use Maven it's über simple, 2 commands and you're up and running!But let's play with the thought that you want to use Sonar on a project that doesn't use maven, or pom.xml-files for that reason.Is this possible?
Sonar without pom?
Sonar stores it's analysis on a daily basis, which explains why it's kind of pointless to run analysis several times in a day. Each analysis run will overwrite that day's existing results, which in turn spoils ongoing statistical analysis.I would suggest running Sonar, from a dedicated build server likeJenkins(which has a Sonar plug-in). This daily analysis will populate the Sonar database and keep the project dashboard current. This architecture also enables you to keep the database credentials confidential.Obviously developers would like to see the results of their bug fixing. For that I'd recommend running the Sonar Eclipse plug-in. The latest version will run the same Sonar analysis locally. Recent versions of Sonar also enable you to assign violations to developers for resolution.
I have configured one project in sonar and integrated sonar with maven for build time analysis of the project.After analysis, report is generated and uploaded to Sonar for browsing. But once another user compiles the same project their report overwrites mine.Basically I want that one user's report on one project is not overwritten by report from other user. A user must be able to see their current violations independently. Is it possible in Sonar?
User specific sonar reports for same project
You have 2 choices:Either those projects are really linked together, and you can configure an Ant build script to have a multi-module project that wraps all your projects =>http://docs.codehaus.org/display/SONAR/Analyse+with+Ant+Task#AnalysewithAntTask-AnalysemultimodulesprojectOr those projects are different (=> they have different lifecycles, they are functionnaly different, ...), and the best option is to use the Views Plugin =>http://www.sonarsource.com/plugins/plugin-views/Overview/
I have some projects and i wrote an ant script to run sonar with this projects.Its okay so far. But i need to show these projects under a top level project like sub projects.I am using just Ant to run sonar and i just working on pure code not on binaries.(I just need to analysis)I could not find how i can solve this.
SONAR - Ant Script for sub Project
Documentation says nothing about content type for sending parameters. I assume they do not support JSON as an input. You may try 'x-www-form-urlencoded' form instead.curl -u user:password --data 'name=dummy_token_name&type=GLOBAL_ANALYSIS_TOKEN' -H 'Content-Type: application/x-www-form-urlencoded' http://localhost:9000/api/user_tokens/generate
I'm encountering an issue while attempting to generate aGLOBAL_ANALYSIS_TOKENusing the SonarQube API. I'd appreciate any assistance or insights you can offer.Setup and ConfigurationSonarQube Version:Enterprise Edition Version 9.9.1 (build 69595)Endpoint:https://quality-analysis.my-company.io/sonar/api/user_tokens/generateHTTP Method:POSTRequest PayloadHere is the JSON payload I am sending:{ "name": "TestingfromAPI", "login": "[email protected]", "projectKey": "demo", "type": "GLOBAL_ANALYSIS_TOKEN", "expirationDate": "2023-10-30" }Error MessageUpon sending the request, I receive the following error message:{ "errors": [ { "msg": "The 'name' parameter is missing" } ] }QuestionsDespite specifying the name parameter in the JSON payload, why am I still getting an error stating it's missing?Is there any specific formatting or encoding required for the name parameter?Could there be any version-specific limitations causing this?Any guidance would be highly appreciated. Thank you!
Issue Generating GLOBAL_ANALYSIS_TOKEN via SonarQube API - 'name' Parameter Missing
Do you have an example repository to share? The key point is to determine if you have a single-module or multi-module Maven project and then you can design the report or report-aggregate goal of thejacoco-maven-plugin.Here are some links to help:Sample Maven repos with Jacoco coverage:https://github.com/SonarSource/sonar-scanning-examplesImporting Jacoco coverage using XML format:https://community.sonarsource.com/t/coverage-test-data-importing-jacoco-coverage-report-in-xml-format/12151For more help, you should ask your question inSonar Communitywhere the official Sonar employees reside to help.
i'm working on a project and the pom.xml file is a child of apache commons-parent (commons-parent provides common settings for all Apache Commons components). I have to calculate code coverage using JaCoCo and Sonarcloud, but to do so I need the jacoco report to be an xml file, while unfortunately the plugin used in commons-parent outputs a .exec file. How can I do this?I tried overriding the jacoco plugin but it still used the parent configuration.EDIT: Thanks tothis answer, I realized I was actually trying to add coverage for a single-module maven project when it actually was a multi-module.
How can I generate a JaCoCo XML report for Sonarcloud in a project using apache commons-parent?
It is not a false positive.IffileInputStream.close()throws an exception,objIn.close()will not be called and theObjectInputStreamwill not be closed.You should separate the twoclosecalls to make sure both streams are closed:finally { try { if (fileInputStream != null) { fileInputStream.close(); } } catch (IOException ignored) {} try { if (objIn != null) { objIn.close(); } } catch (IOException ignored) {} }
For the below java code though resource is closed in a finally block sonar is reporting:Use try-with-resources or close this “ObjectInputStream” in a “finally” clause.FileInputStream fileInputStream = null; ObjectInputStream objIn = null; try { fileInputStream = new FileInputStream(value); objIn = new ObjectInputStream(fileInputStream) } finally { try { if (fileInputStream != null) { fileInputStream.close(); } if (objIn != null) { objIn.close(); } } catch (IOException e) {} }Sonar doesn't report above issue when try-with-resources is used , since the version of java i use doesn't support try-with-resource i had to go with closing resource in a finally block.
sonarqube: Is try-with-resources or close this "ObjectInputStream" in a "finally" clause for this code false positive?
Do what the linter says. Create alias for union type.type InformationType = 'someValue' | 'anotherValue'; // .... informationType: InformationType;
SonarLint gives the following and I have not found how to solve it since it is a global variable.variable sample img
how can I fix the warning "Replace this union type with a type alias"
According to this resourcehttps://sonarsource.atlassian.net/browse/RSPEC-2819, you need to check the domain the message was posted fromself.addEventListener("message", function(event) { if (event.origin !== "http://example.org") // Compliant return; console.log(event.data) });And also add a specific domain to your postMessage function if you used a wildcard '*'self.postMessage("secret", "*");
My project runs the sonarqube scan for each build.In the lineself.addEventListener, I have the"Verify the message's origin in this cross-origin communication."vulnerability in scan results.My application is getting loaded in an iframe.The code snippet is as follows:-self.addEventListener("message", function(e) { switch (e.data.cmd) { case "init": _initializeTimer(e.data.timeIntervalInSec); break; case "resetTimer": clearTimeout(self.sessionTimer); _initializeTimer(e.data.timeIntervalInSec); break; default: self.postMessage({ status: "error", info: "please send a valid command" }); break; }What is the potential cause of this vulnerability ?How can I resolve this ?
How to resolve the "Verify the message's origin in this cross-origin communication" vulnerability in sonarqube.?
Yes,third party issuesare supported with SonarQube. For PyLint, you can setsonar.python.pylint.reportPathin your sonar.properties file with the path of the report(s) for pylint. You must use--output-format=parseableargument topylint.When you run sonar scanner, it will collect the report(s) and send it to SonarQube.
I apologize in advance.I have a task to create CI pipeline in Gitlab for projects on python language with results in SonarQube. I found somegitlab-ci.ymlfile:image: image-registry/gitlab/python before_script: - cd .. - git clone https://gitlab-ci-token:${CI_JOB_TOKEN}@gitlab/python-education/junior.git stages: - PyLint pylint: stage: PyLint only: - merge_requests script: - cp -R ${CI_PROJECT_NAME}/* junior/project - cd junior && python3 run.py --monorepoIs it possible to some code in script to output in SonarQube?
Use pylint with sonarqube
I contacted the sonar team and they said this problem occurs with older versions.The version I am using is 4.30 and they asked me to upgrade it to 6.1.So,problem solved.
Sonar does not accept the control when we check for null via method. What can be the solution?It only accepts when you do as follows:if (callID == null) { throw new ArgumentNullException(nameof(callID)); }It doesn't see it when I do it like below.private static void a(string callID) { if (callID == null) { throw new ArgumentNullException(nameof(callID)); } }Is this a general problem for sonar?Thanks in advance.
Sonar does not accept null check via method
The issue here is thethrows Exceptionin your method signature:public void configureGlobal(AuthenticationManagerBuilder auth) throws ExceptionSonarQube informs you that instead of the genericExceptionthat is the basis of all exceptions, both checked and unchecked you shoud reference the actual (checked) exception that may be thrown by the methods that you are calling.Usually, your IDE should already suggest a suitable Exception class.
I need to throw RuntimeException for the KeycloakAuthenticationProvider . We are usingSonarQubetool for code review purpose.Here is the codepublic void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider(); auth.authenticationProvider(keycloakAuthenticationProvider); }Now, SonarQube raises an issue for the same , Now what should be replaced to fix the sonar violation.
SonarQube major isuue raised 'Define and throw a dedicated exception instead of using a generic one.'?
Creating a separate identity that would belong to SonarQube is the only option. The identity posts the comments using theDevOps APIwhere the PAT is the only identification of the identity.Using a developer's account for PR decoration not only feels strange when reading the comments, but it is also fragile. When the developer leaves the company, their account will be terminated and suddenly, PR decoration will break and it may not be immediately clear why. Also, the developer could revoke the PAT at any time by mistake. In a larger organization, no single developer will have the right to comment on pull requests everywhere, so multiple developer accounts will be in use, which makes the configuration even more complex and fragile.
We have successfully integrated SonarQube into our build pipelines on Azure DevOps and have used a developer's account to generate a PAT for pull request decoration. The problem is now that the developer's account is posting comments across all our repos on different Pull Requests. It seems the alternative is to create a whole new user titled 'SonarQube' (or similar) in our Active Directory and generate a new PAT to do this, which seems overkill. Any alternative options would be appreciated.
Azure Devops SonarQube Pull Request Decoration
just for code brief, change the first line fromconst columnsEventModal= Column[] = [...] return columnsEventModal;to the linereturn [...]because you dont do anything in between insertion and return statement, Sonar doesnt understand why you would allocate a variable
After analyzing my code with SonarLint, I get the following smell code: "Local variables should not be declared and then immediately returned or thrown".Even if this is not blocking and the component works perfectly.I think there is a better way to post thereturnin the function but I don't see how, if anyone knows the trick.here is my component :const ColumnModalEvent = (currency: any) => { const columnsEventModal: Column[] = [ { Header: () => <I18nWrapper translateKey="movement.type.fieldName" />, accessor: 'type', disableSortBy: true, Cell: ({ value }) => ( <I18nWrapper translateKey={value} prefix="movement.type" /> ), }, { Header: () => ( <I18nWrapper translateKey="movement.uniqueReference.fieldNameShort" /> ), accessor: 'uniqueRef', }, { Header: () => <I18nWrapper translateKey="movement.documentDate" />, accessor: 'createdDate', className: 'text-end', headerClassName: 'text-end', Cell: ({ value }) => <DateFormater dateToFomat={value} />, }, ]; return columnsEventModal; }; export default ColumnModalEvent;
SonarLint : Code Smell : Local variables should not be declared and then immediately returned or thrown
It may be better to implement a utility/helper method to handle null checks (either directly, usingObjects::isNullorOptional) and return expected result:public class Util { public static List<?> copyOrNull(List<?> src) { return null == src ? src : new ArrayList<>(src); } public static List<?> copyOrEmpty(List<?> src) { return null == src ? Collections.emptyList() : new ArrayList<>(src); } }Then update the DTO code as needed:public MenuItemDTO( PropertiesDTO propertiesDto, List<ModifierDTO> modifierDtoList, List<AllergenInfo> allergenInfoList ) { this.uuid = propertiesDto.getUuid(); this.modifierDtoList = Util.copyOrNull(modifierDtoList); this.allergenInfoList = Util.copyOrEmpty(allergenInfoList); }
I have the following DTO and I pass the objects to theArrayLists to prevent objects to be changed and fix the SonarQube error as"Message: Store a copy of allergenInfoList", etc.public MenuItemDTO( PropertiesDTO propertiesDto, List<ModifierDTO> modifierDtoList, List<AllergenInfo> allergenInfoList ) { this.uuid = propertiesDto.getUuid(); this.modifierDtoList = new ArrayList<>(modifierDtoList); this.allergenInfoList = new ArrayList<>(allergenInfoList); } }However, this approach requires null check and it makes my code ugly as shown below:public MenuItemDTO( PropertiesDTO propertiesDto, List<ModifierDTO> modifierDtoList, List<AllergenInfo> allergenInfoList ) { this.uuid = propertiesDto.getUuid(); if (modifierDtoList != null) { this.modifierDtoList = new ArrayList<>(modifierDtoList); } if (allergenInfoList != null) { this.allergenInfoList = new ArrayList<>(allergenInfoList); } }So, is there any better approach to fix the problem without null check?
Java mutable object to causing nullpointer exception
Well,This rule raises an issue when a method contains several return statements that all return the same value.Sonar reports that it complains aboutall return statements having the same return value. Your code indeed contains (at least) two such statements:if (obj == null) { return true } ... return true;I think that you missed a semicolon there, but that's another story.You could at least rewrite this to:if (obj != null) { ... } return true;Now see if the complaint disappears. If it does not disappear, there's not much you can do. As Federico already pointed outin a comment, Sonar is a very nice tool, but it is not the holy grail. There are cases where you have to tell Sonar that this is the only way.Regarding some comments saying that you should change the return type tovoid— I would advise you the same, but you cannot do that, or course, if you are overriding from a supertype. (I'm assuming here that you are overridingandroid.os.Handler.Callback.handleMessage(Message)).
SonarQube says doing following is wrong:@Override public boolean android.os.Handler.Callback.handleMessage(Message msg) { super.handleMessage(msg); Object obj = getXY(); if (obj == null) { return true; } ... ... ... ... ... ... return true; }When a method is designed to return an invariant value, it may be poor design, but it shouldn't adversely affect the outcome of your program. However, when it happens on all paths through the logic, it is surely a bug.This rule raises an issue when a method contains several return statements that all return the same value.I don't think this warning is true in this case, what do you think? Would you have a different approach?
SonarQube warning "Methods returns should not be invariant"
The token may be valid, but the way it is used is not.Authorizationheader is supposed to contain authentication method and a value, which in case of methodBasicshould be a base64-encoded string ofusername:password. With SonarQube token you should replace a username with a token and use empty password.Given the base64-encoded value:$ echo -n '479ec8bdb82b316abad411fc21d3bed129e19c05:' | base64 NDc5ZWM4YmRiODJiMzE2YWJhZDQxMWZjMjFkM2JlZDEyOWUxOWMwNTo=the header should be:Authorization: Basic NDc5ZWM4YmRiODJiMzE2YWJhZDQxMWZjMjFkM2JlZDEyOWUxOWMwNTo=The easiest way, however, withrequestslibrary would be to useauthinstead of calculating the header on your own, i.e.:response = requests.get('https://urlsonar/api/components/search_projects', auth=('479ec8bdb82b316abad411fc21d3bed129e19c05', ''))
When using the Api address directly in the Browser, it brings the data and Json correctly.But when trying the same in Postman or Python, the data is not loaded.The token is valid, I'm on the VPN from the normal company, but without success.Has anyone been through this and knows a way to analyze it?Code:response = requests.get('https://urlsonar/api/components/search_projects', verify=False) print(response.status_code) print(response.json())Code 2:response = requests.get('https://urlsonar/api/components/search_projects', headers={'Authorization': '479ec8bdb82b316abad411fc21d3bed129e19c05'}, verify=False) print(response.status_code) print(response.json())Error:401 Traceback (most recent call last): File "C:\Users\Paulo\Documents\projetos\python\CONEXAO_SONAR_EMISSAO.py", line 39, in print(response.json()) File "C:\Users\Paulo\AppData\Roaming\Python\Python39\site-packages\requests\models.py", line 900, in json return complexjson.loads(self.text, **kwargs) File "C:\Program Files\Python39\lib\json_init_.py", line 346, in loads return _default_decoder.decode(s) File "C:\Program Files\Python39\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Program Files\Python39\lib\json\decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) PS C:\Users\Paulo\Documents\projetos\python>
Error 401 when extracting data from Api from Sonarqube
In this case probably the easiest thing would be to instruct sonar-scanner to wait for quality gate result. From thedocumentation:you can use thesonar.qualitygate.wait=trueanalysis parameter in your configuration file. Settingsonar.qualitygate.waitto true forces the analysis step to poll your SonarQube instance until the Quality Gate status is available. This increases the pipeline duration and causes the analysis step to fail any time the Quality Gate fails, even if the actual analysis is successful.
I'm working on a jenkins job without the possibility of using a pipeline.What i need to do is to launch some sonarQube Analysis and to check if the quality gates has passed. If the analysis with the quality gate fails, i would like to block my job.I know that i can do this by scripting a pipeline and i know how to do it, but in this particular case i cannot write a pipeline but i can use only the "Prebuild steps" and "After Build Steps" of the job. So my questions are:Is possibile to implment the pipeline into the job that doesn't have the pipeline section?how can i check if the analysis have passed the quality gate? I've also read about a Jenkins plugin called "Quality Gate", but it has a problem about security (credentials in plain text) so i think they will not allow me to use it.Thanks everybody!
How to check the quality gate of a SonarQube analysis into a job
Try using the matches() function for a regex like this:Details[@type="banking"]/@name[not(matches(., "^GLO_(.){3}_UPLOAD_STATEMENT"))]
we received banking statements from the SAP System. We sometimes observe the naming convention of the file name will be not as per the standards and the files will be rejected. We wanted to validate the file name, as per the below example, we get the file name in thenameattribute.Can the country ISO code escape in the validation? We wanted an Xpath that captures GLO_***_UPLOAD_STATEMENT like this so that ISO code is not validated.Example XML:<?xml version="1.0" encoding="UTF-8"?> <Details name="GLO_ZFA_UPLOAD_STATEMENT" type="banking" version="3.0"> <description/> <object> <encrypted data="b528f05b96102f5d99743ff6122bb0984aa16a02893984a9e427a44fcedae1612104a7df1173d9c61a99ebe0c34ea67a46aecc86f41f5924f74dd525"/> </object> </Details>Xpath tried:Details[@type="banking"]/@name[not(starts-with(., "GLO_***_UPLOAD_STATEMENT"))]which is not working :(Can anyone help here, please :) Thanks in advance!
how to use '*' in XPATH starts-with()?
For some reason, the port9000isblockedby Zscaler (My machine has Zscaler turned on, I've not made any changes to Zscaler settings). However the solution I found is to change the Sonarqube's port to something else, eg9090StepsGo tosonarqube-8.7.0.41497/conf(Im using 8.7, so you need to go the version you're using)Open upsonar.propertiesChangesonar.web.port=9000tosonar.web.port=9090Launch your sonarqube again by runningsonar.sh startTry scanning your project, by runningsonar-scannerwhere yoursonar-project.propertiesis.
Versions : Sonar : 8.8.0.42792 Sonar-scanner : 4.5.0.2216 MacOS : Catalina 10.15.6sonar-project.properties :sonar.projectName=camel sonar.projectKey=camel-key sonar.projectVersion=1.0 sonar.sources=src sonar.language=java sonar.sourceEncoding=UTF-8 sonar.java.binaries=build/classessonar-scanner :#----- Default SonarQube server sonar.host.url=http://localhost:9000 # tried with local IP 127.0.0.1 & network IP too #----- Default source code encoding sonar.sourceEncoding=UTF-8Sonar Qube is UP, status is running , can access console too.I have ZScaler security firewall, protected with password so can't modify or stop it.Now, while executing below command from Project root directory where sonar-project.properties file exists , I am getting following error.Caused by: java.net.SocketTimeoutException: Read timed outAny particular reason and how to solve this , please ?
Unable to execute SonarScanner analysis due to Time out Exception
You need to install theSonarQube extension:After that you will see it:
Tried looking all over couldn't find the option or the solution to get the option, any inputs would be deeply helpful.My Azure DevOps Version:I'm pretty sure the Azure DevOps is the latest.
Not able to find SonarQube Service Connection in Azure Devops in new service connection list